Merge pull request #2632 from kasthack/sysweb-import
[mono.git] / mcs / tools / mkbundle / mkbundle.cs
1 //
2 // mkbundle: tool to create bundles.
3 //
4 // Based on the `make-bundle' Perl script written by Paolo Molaro (lupus@debian.org)
5 //
6 // Author:
7 //   Miguel de Icaza
8 //
9 // (C) Novell, Inc 2004
10 //
11 using System;
12 using System.Diagnostics;
13 using System.Xml;
14 using System.Collections.Generic;
15 using System.IO;
16 using System.IO.Compression;
17 using System.Runtime.InteropServices;
18 using System.Text;
19 using IKVM.Reflection;
20
21
22 using System.Threading.Tasks;
23
24 class MakeBundle {
25         static string output = "a.out";
26         static string object_out = null;
27         static List<string> link_paths = new List<string> ();
28         static bool autodeps = false;
29         static bool keeptemp = false;
30         static bool compile_only = false;
31         static bool static_link = false;
32         static string config_file = null;
33         static string machine_config_file = null;
34         static string config_dir = null;
35         static string style = "linux";
36         static string os_message = "";
37         static bool compress;
38         static bool nomain;
39         static string custom_main = null;
40         static bool? use_dos2unix = null;
41         static bool skip_scan;
42         static string ctor_func;
43         static bool quiet;
44         
45         static int Main (string [] args)
46         {
47                 List<string> sources = new List<string> ();
48                 int top = args.Length;
49                 link_paths.Add (".");
50
51                 DetectOS ();
52                 
53                 for (int i = 0; i < top; i++){
54                         switch (args [i]){
55                         case "--help": case "-h": case "-?":
56                                 Help ();
57                                 return 1;
58
59                         case "-c":
60                                 compile_only = true;
61                                 break;
62                                 
63                         case "-o": 
64                                 if (i+1 == top){
65                                         Help (); 
66                                         return 1;
67                                 }
68                                 output = args [++i];
69                                 break;
70
71                         case "-oo":
72                                 if (i+1 == top){
73                                         Help (); 
74                                         return 1;
75                                 }
76                                 object_out = args [++i];
77                                 break;
78
79                         case "-L":
80                                 if (i+1 == top){
81                                         Help (); 
82                                         return 1;
83                                 }
84                                 link_paths.Add (args [++i]);
85                                 break;
86
87                         case "--nodeps":
88                                 autodeps = false;
89                                 break;
90
91                         case "--deps":
92                                 autodeps = true;
93                                 break;
94
95                         case "--keeptemp":
96                                 keeptemp = true;
97                                 break;
98                         case "--static":
99                                 static_link = true;
100                                 if (!quiet) {
101                                         Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
102                                         Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
103                                 }
104                                 break;
105                         case "--config":
106                                 if (i+1 == top) {
107                                         Help ();
108                                         return 1;
109                                 }
110
111                                 config_file = args [++i];
112                                 break;
113                         case "--machine-config":
114                                 if (i+1 == top) {
115                                         Help ();
116                                         return 1;
117                                 }
118
119                                 machine_config_file = args [++i];
120
121                                 if (!quiet)
122                                         Console.WriteLine ("WARNING:\n  Check that the machine.config file you are bundling\n  doesn't contain sensitive information specific to this machine.");
123                                 break;
124                         case "--config-dir":
125                                 if (i+1 == top) {
126                                         Help ();
127                                         return 1;
128                                 }
129
130                                 config_dir = args [++i];
131                                 break;
132                         case "-z":
133                                 compress = true;
134                                 break;
135                         case "--nomain":
136                                 nomain = true;
137                                 break;
138                         case "--custom-main":
139                                 if (i+1 == top) {
140                                         Help ();
141                                         return 1;
142                                 }
143                                 custom_main = args [++i];
144                                 break;
145                         case "--style":
146                                 if (i+1 == top) {
147                                         Help ();
148                                         return 1;
149                                 }
150                                 style = args [++i];
151                                 switch (style) {
152                                 case "windows":
153                                 case "mac":
154                                 case "linux":
155                                         break;
156                                 default:
157                                         Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
158                                         return 1;
159                                 }
160                                         
161                                 break;
162                         case "--skip-scan":
163                                 skip_scan = true;
164                                 break;
165                         case "--static-ctor":
166                                 if (i+1 == top) {
167                                         Help ();
168                                         return 1;
169                                 }
170                                 ctor_func = args [++i];
171                                 break;
172                         case "--dos2unix":
173                         case "--dos2unix=true":
174                                 use_dos2unix = true;
175                                 break;
176                         case "--dos2unix=false":
177                                 use_dos2unix = false;
178                                 break;
179                         case "-q":
180                         case "--quiet":
181                                 quiet = true;
182                                 break;
183                         default:
184                                 sources.Add (args [i]);
185                                 break;
186                         }
187
188                 }
189
190                 if (!quiet) {
191                         Console.WriteLine (os_message);
192                         Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
193                 }
194                 if (sources.Count == 0 || output == null) {
195                         Help ();
196                         Environment.Exit (1);
197                 }
198
199                 List<string> assemblies = LoadAssemblies (sources);
200                 List<string> files = new List<string> ();
201                 foreach (string file in assemblies)
202                         if (!QueueAssembly (files, file))
203                                 return 1;
204                         
205                 GenerateBundles (files);
206                 //GenerateJitWrapper ();
207                 
208                 return 0;
209         }
210
211         static void WriteSymbol (StreamWriter sw, string name, long size)
212         {
213                 switch (style){
214                 case "linux":
215                         sw.WriteLine (
216                                 ".globl {0}\n" +
217                                 "\t.section .rodata\n" +
218                                 "\t.p2align 5\n" +
219                                 "\t.type {0}, \"object\"\n" +
220                                 "\t.size {0}, {1}\n" +
221                                 "{0}:\n",
222                                 name, size);
223                         break;
224                 case "osx":
225                         sw.WriteLine (
226                                 "\t.section __TEXT,__text,regular,pure_instructions\n" + 
227                                 "\t.globl _{0}\n" +
228                                 "\t.data\n" +
229                                 "\t.align 4\n" +
230                                 "_{0}:\n",
231                                 name, size);
232                         break;
233                 case "windows":
234                         sw.WriteLine (
235                                 ".globl _{0}\n" +
236                                 "\t.section .rdata,\"dr\"\n" +
237                                 "\t.align 32\n" +
238                                 "_{0}:\n",
239                                 name, size);
240                         break;
241                 }
242         }
243         
244         static string [] chars = new string [256];
245         
246         static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
247         {
248                 int n;
249                 
250                 // Preallocate the strings we need.
251                 if (chars [0] == null) {
252                         for (int i = 0; i < chars.Length; i++)
253                                 chars [i] = string.Format ("{0}", i.ToString ());
254                 }
255
256                 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
257                         int count = 0;
258                         for (int i = 0; i < n; i++) {
259                                 if (count % 32 == 0) {
260                                         ts.Write ("\n\t.byte ");
261                                 } else {
262                                         ts.Write (",");
263                                 }
264                                 ts.Write (chars [buffer [i]]);
265                                 count ++;
266                         }
267                 }
268
269                 ts.WriteLine ();
270         }
271         
272         static void GenerateBundles (List<string> files)
273         {
274                 string temp_s = "temp.s"; // Path.GetTempFileName ();
275                 string temp_c = "temp.c";
276                 string temp_o = "temp.o";
277
278                 if (compile_only)
279                         temp_c = output;
280                 if (object_out != null)
281                         temp_o = object_out;
282                 
283                 try {
284                         List<string> c_bundle_names = new List<string> ();
285                         List<string[]> config_names = new List<string[]> ();
286
287                         using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
288                         using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
289                         string prog = null;
290
291 #if XAMARIN_ANDROID
292                         tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
293                         tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
294                         tc.WriteLine (@"
295 typedef struct {
296         const char *name;
297         const unsigned char *data;
298         const unsigned int size;
299 } MonoBundledAssembly;
300 void          mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
301 void          mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
302 ");
303 #else
304                         tc.WriteLine ("#include <mono/metadata/mono-config.h>");
305                         tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
306 #endif
307
308                         if (compress) {
309                                 tc.WriteLine ("typedef struct _compressed_data {");
310                                 tc.WriteLine ("\tMonoBundledAssembly assembly;");
311                                 tc.WriteLine ("\tint compressed_size;");
312                                 tc.WriteLine ("} CompressedAssembly;\n");
313                         }
314
315                         object monitor = new object ();
316
317                         var streams = new Dictionary<string, Stream> ();
318                         var sizes = new Dictionary<string, long> ();
319
320                         // Do the file reading and compression in parallel
321                         Action<string> body = delegate (string url) {
322                                 string fname = LocateFile (new Uri (url).LocalPath);
323                                 Stream stream = File.OpenRead (fname);
324
325                                 long real_size = stream.Length;
326                                 int n;
327                                 if (compress) {
328                                         byte[] cbuffer = new byte [8192];
329                                         MemoryStream ms = new MemoryStream ();
330                                         GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
331                                         while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
332                                                 deflate.Write (cbuffer, 0, n);
333                                         }
334                                         stream.Close ();
335                                         deflate.Close ();
336                                         byte [] bytes = ms.GetBuffer ();
337                                         stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
338                                 }
339
340                                 lock (monitor) {
341                                         streams [url] = stream;
342                                         sizes [url] = real_size;
343                                 }
344                         };
345
346                         //#if NET_4_5
347 #if FALSE
348                         Parallel.ForEach (files, body);
349 #else
350                         foreach (var url in files)
351                                 body (url);
352 #endif
353
354                         // The non-parallel part
355                         byte [] buffer = new byte [8192];
356                         foreach (var url in files) {
357                                 string fname = LocateFile (new Uri (url).LocalPath);
358                                 string aname = Path.GetFileName (fname);
359                                 string encoded = aname.Replace ("-", "_").Replace (".", "_");
360
361                                 if (prog == null)
362                                         prog = aname;
363
364                                 var stream = streams [url];
365                                 var real_size = sizes [url];
366
367                                 if (!quiet)
368                                         Console.WriteLine ("   embedding: " + fname);
369
370                                 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
371                         
372                                 WriteBuffer (ts, stream, buffer);
373
374                                 if (compress) {
375                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
376                                         tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
377                                                                   " assembly_data_{0}, {2}}}, {3}}};",
378                                                                   encoded, aname, real_size, stream.Length);
379                                         if (!quiet) {
380                                                 double ratio = ((double) stream.Length * 100) / real_size;
381                                                 Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
382                                         }
383                                 } else {
384                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
385                                         tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
386                                                                   encoded, aname, real_size);
387                                 }
388                                 stream.Close ();
389
390                                 c_bundle_names.Add ("assembly_bundle_" + encoded);
391
392                                 try {
393                                         FileStream cf = File.OpenRead (fname + ".config");
394                                         if (!quiet)
395                                                 Console.WriteLine (" config from: " + fname + ".config");
396                                         tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
397                                         WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
398                                         WriteBuffer (ts, cf, buffer);
399                                         ts.WriteLine ();
400                                         config_names.Add (new string[] {aname, encoded});
401                                 } catch (FileNotFoundException) {
402                                         /* we ignore if the config file doesn't exist */
403                                 }
404                         }
405
406                         if (config_file != null){
407                                 FileStream conf;
408                                 try {
409                                         conf = File.OpenRead (config_file);
410                                 } catch {
411                                         Error (String.Format ("Failure to open {0}", config_file));
412                                         return;
413                                 }
414                                 if (!quiet)
415                                         Console.WriteLine ("System config from: " + config_file);
416                                 tc.WriteLine ("extern const char system_config;");
417                                 WriteSymbol (ts, "system_config", config_file.Length);
418
419                                 WriteBuffer (ts, conf, buffer);
420                                 // null terminator
421                                 ts.Write ("\t.byte 0\n");
422                                 ts.WriteLine ();
423                         }
424
425                         if (machine_config_file != null){
426                                 FileStream conf;
427                                 try {
428                                         conf = File.OpenRead (machine_config_file);
429                                 } catch {
430                                         Error (String.Format ("Failure to open {0}", machine_config_file));
431                                         return;
432                                 }
433                                 if (!quiet)
434                                         Console.WriteLine ("Machine config from: " + machine_config_file);
435                                 tc.WriteLine ("extern const char machine_config;");
436                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
437
438                                 WriteBuffer (ts, conf, buffer);
439                                 ts.Write ("\t.byte 0\n");
440                                 ts.WriteLine ();
441                         }
442                         ts.Close ();
443
444                         if (compress)
445                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
446                         else
447                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
448
449                         foreach (string c in c_bundle_names){
450                                 tc.WriteLine ("\t&{0},", c);
451                         }
452                         tc.WriteLine ("\tNULL\n};\n");
453                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
454
455                         if (ctor_func != null) {
456                                 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
457                                 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
458                                 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
459                         }
460
461                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
462                         foreach (string[] ass in config_names){
463                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
464                         }
465                         if (config_file != null)
466                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
467                         if (machine_config_file != null)
468                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
469                         tc.WriteLine ("}\n");
470
471                         if (config_dir != null)
472                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
473                         else
474                                 tc.WriteLine ("static const char *config_dir = NULL;");
475
476                         Stream template_stream;
477                         if (compress) {
478                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
479                         } else {
480                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
481                         }
482
483                         StreamReader s = new StreamReader (template_stream);
484                         string template = s.ReadToEnd ();
485                         tc.Write (template);
486
487                         if (!nomain && custom_main == null) {
488                                 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
489                                 StreamReader st = new StreamReader (template_main_stream);
490                                 string maintemplate = st.ReadToEnd ();
491                                 tc.Write (maintemplate);
492                         }
493
494                         tc.Close ();
495
496                         string assembler = GetEnv("AS", "as");
497                         string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
498                         Execute(as_cmd);
499
500                         if (compile_only)
501                                 return;
502
503                         if (!quiet)
504                                 Console.WriteLine("Compiling:");
505
506                         if (style == "windows")
507                         {
508
509                                 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
510
511                                 string compiler = GetEnv("CC", "cl.exe");
512                                 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
513                                 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
514                                 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
515
516                                 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
517                                 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
518                                 var linkLibraries = new string[] {  "kernel32.lib",
519                                                                                                 "version.lib",
520                                                                                                 "Ws2_32.lib",
521                                                                                                 "Mswsock.lib",
522                                                                                                 "Psapi.lib",
523                                                                                                 "shell32.lib",
524                                                                                                 "OleAut32.lib",
525                                                                                                 "ole32.lib",
526                                                                                                 "winmm.lib",
527                                                                                                 "user32.lib",
528                                                                                                 "libvcruntime.lib",
529                                                                                                 "advapi32.lib",
530                                                                                                 "OLDNAMES.lib",
531                                                                                                 "libucrt.lib" };
532
533                                 string glue_obj = "mkbundle_glue.obj";
534                                 string monoLib;
535
536                                 if (static_link)
537                                         monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
538
539                                 else {
540                                         Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
541                                         monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
542                                         LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
543                                 }
544
545                                 var compilerArgs = new List<string>();
546                                 compilerArgs.Add("/MT");
547
548                                 foreach (string include in includes)
549                                         compilerArgs.Add(String.Format ("/I {0}", quote (include)));
550
551                                 if (!nomain || custom_main != null) {
552                                         compilerArgs.Add(quote(temp_c));
553                                         compilerArgs.Add(quote(temp_o));
554                                         if (custom_main != null)
555                                                 compilerArgs.Add(quote(custom_main));
556                                         compilerArgs.Add(quote(monoLib));
557                                         compilerArgs.Add("/link");
558                                         compilerArgs.Add("/NODEFAULTLIB");
559                                         compilerArgs.Add("/SUBSYSTEM:windows");
560                                         compilerArgs.Add("/ENTRY:mainCRTStartup");
561                                         compilerArgs.AddRange(linkLibraries);
562                                         compilerArgs.Add("/out:"+ output);
563
564                                         string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
565                                         Execute (cl_cmd);
566                                 }
567                                 else
568                                 {
569                                         // we are just creating a .lib
570                                         compilerArgs.Add("/c"); // compile only
571                                         compilerArgs.Add(temp_c);
572                                         compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
573
574                                         string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
575                                         Execute (cl_cmd);
576
577                                         string librarian = GetEnv ("LIB", "lib.exe");
578                                         var librarianArgs = new List<string> ();
579                                         librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
580                                         librarianArgs.Add (temp_o);
581                                         librarianArgs.Add (glue_obj);
582                                         librarianArgs.Add (monoLib);
583                                         string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
584                                         Execute (lib_cmd);
585                                 }
586                         }
587                         else
588                         {
589                                 string zlib = (compress ? "-lz" : "");
590                                 string debugging = "-g";
591                                 string cc = GetEnv("CC", "cc");
592                                 string cmd = null;
593
594                                 if (style == "linux")
595                                         debugging = "-ggdb";
596                                 if (static_link)
597                                 {
598                                         string smonolib;
599                                         if (style == "osx")
600                                                 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
601                                         else
602                                                 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
603                                         cmd = String.Format("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
604                                                 "`pkg-config --libs-only-L mono-2` " + smonolib +
605                                                 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
606                                                 temp_c, temp_o, output, zlib, cc);
607                                 }
608                                 else
609                                 {
610
611                                         cmd = String.Format("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
612                                                 temp_c, temp_o, output, zlib, cc);
613                                 }
614                                 Execute (cmd);
615                         }
616
617                         if (!quiet)
618                                 Console.WriteLine ("Done");
619                 }
620         }
621                 } finally {
622                         if (!keeptemp){
623                                 if (object_out == null){
624                                         File.Delete (temp_o);
625                                 }
626                                 if (!compile_only){
627                                         File.Delete (temp_c);
628                                 }
629                                 File.Delete (temp_s);
630                         }
631                 }
632         }
633         
634         static List<string> LoadAssemblies (List<string> sources)
635         {
636                 List<string> assemblies = new List<string> ();
637                 bool error = false;
638                 
639                 foreach (string name in sources){
640                         try {
641                                 Assembly a = LoadAssembly (name);
642
643                                 if (a == null){
644                                         error = true;
645                                         continue;
646                                 }
647                         
648                                 assemblies.Add (a.CodeBase);
649                         } catch (Exception) {
650                                 if (skip_scan) {
651                                         if (!quiet)
652                                                 Console.WriteLine ("File will not be scanned: {0}", name);
653                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
654                                 } else {
655                                         throw;
656                                 }
657                         }
658                 }
659
660                 if (error)
661                         Environment.Exit (1);
662
663                 return assemblies;
664         }
665         
666         static readonly Universe universe = new Universe ();
667         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
668         
669         static bool QueueAssembly (List<string> files, string codebase)
670         {
671                 // Console.WriteLine ("CODE BASE IS {0}", codebase);
672                 if (files.Contains (codebase))
673                         return true;
674
675                 var path = new Uri(codebase).LocalPath;
676                 var name = Path.GetFileName (path);
677                 string found;
678                 if (loaded_assemblies.TryGetValue (name, out found)) {
679                         Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
680                         return false;
681                 }
682
683                 loaded_assemblies.Add (name, path);
684
685                 files.Add (codebase);
686                 if (!autodeps)
687                         return true;
688                 try {
689                         Assembly a = universe.LoadFile (path);
690
691                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
692                                 a = universe.Load (an.FullName);
693                                 if (!QueueAssembly (files, a.CodeBase))
694                                         return false;
695                         }
696                 } catch (Exception) {
697                         if (!skip_scan)
698                                 throw;
699                 }
700
701                 return true;
702         }
703
704         static Assembly LoadAssembly (string assembly)
705         {
706                 Assembly a;
707                 
708                 try {
709                         char[] path_chars = { '/', '\\' };
710                         
711                         if (assembly.IndexOfAny (path_chars) != -1) {
712                                 a = universe.LoadFile (assembly);
713                         } else {
714                                 string ass = assembly;
715                                 if (ass.EndsWith (".dll"))
716                                         ass = assembly.Substring (0, assembly.Length - 4);
717                                 a = universe.Load (ass);
718                         }
719                         return a;
720                 } catch (FileNotFoundException){
721                         string total_log = "";
722                         
723                         foreach (string dir in link_paths){
724                                 string full_path = Path.Combine (dir, assembly);
725                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
726                                         full_path += ".dll";
727                                 
728                                 try {
729                                         a = universe.LoadFile (full_path);
730                                         return a;
731                                 } catch (FileNotFoundException ff) {
732                                         total_log += ff.FusionLog;
733                                         continue;
734                                 }
735                         }
736                         Error ("Cannot find assembly `" + assembly + "'" );
737                         if (!quiet)
738                                 Console.WriteLine ("Log: \n" + total_log);
739                 } catch (IKVM.Reflection.BadImageFormatException f) {
740                         if (skip_scan)
741                                 throw;
742                         Error ("Cannot load assembly (bad file format) " + f.Message);
743                 } catch (FileLoadException f){
744                         Error ("Cannot load assembly " + f.Message);
745                 } catch (ArgumentNullException){
746                         Error("Cannot load assembly (null argument)");
747                 }
748                 return null;
749         }
750
751         static void Error (string msg)
752         {
753                 Console.Error.WriteLine ("ERROR: " + msg);
754                 Environment.Exit (1);
755         }
756
757         static void Help ()
758         {
759                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
760                                    "Options:\n" +
761                                    "    -c                  Produce stub only, do not compile\n" +
762                                    "    -o out              Specifies output filename\n" +
763                                    "    -oo obj             Specifies output filename for helper object file\n" +
764                                    "    -L path             Adds `path' to the search path for assemblies\n" +
765                                    "    --nodeps            Turns off automatic dependency embedding (default)\n" +
766                                    "    --deps              Turns on automatic dependency embedding\n" +
767                                    "    --dos2unix[=true|false]\n" +
768                                    "                        When no value provided, or when `true` specified\n" +
769                                    "                        `dos2unix` will be invoked to convert paths on Windows.\n" +
770                                    "                        When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
771                                    "    --keeptemp          Keeps the temporary files\n" +
772                                    "    --config F          Bundle system config file `F'\n" +
773                                    "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
774                                    "    --machine-config F  Use the given file as the machine.config for the application.\n" +
775                                    "    --static            Statically link to mono libs\n" +
776                                    "    --nomain            Don't include a main() function, for libraries\n" +
777                                    "    --custom-main C         Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
778                                    "    -z                  Compress the assemblies before embedding.\n" +
779                                    "    --skip-scan         Skip scanning assemblies that could not be loaded (but still embed them).\n" +
780                                    "    --static-ctor ctor  Add a constructor call to the supplied function.\n" +
781                                    "                        You need zlib development headers and libraries.\n");
782         }
783
784         [DllImport ("libc")]
785         static extern int system (string s);
786         [DllImport ("libc")]
787         static extern int uname (IntPtr buf);
788                 
789         static void DetectOS ()
790         {
791                 if (!IsUnix) {
792                         os_message = "OS is: Windows";
793                         style = "windows";
794                         return;
795                 }
796
797                 IntPtr buf = Marshal.AllocHGlobal (8192);
798                 if (uname (buf) != 0){
799                         os_message = "Warning: Unable to detect OS";
800                         Marshal.FreeHGlobal (buf);
801                         return;
802                 }
803                 string os = Marshal.PtrToStringAnsi (buf);
804                 os_message = "OS is: " + os;
805                 if (os == "Darwin")
806                         style = "osx";
807                 
808                 Marshal.FreeHGlobal (buf);
809         }
810
811         static bool IsUnix {
812                 get {
813                         int p = (int) Environment.OSVersion.Platform;
814                         return ((p == 4) || (p == 128) || (p == 6));
815                 }
816         }
817
818         static void Execute (string cmdLine)
819         {
820                 if (IsUnix) {
821                         if (!quiet)
822                                 Console.WriteLine ("[execute cmd]: " + cmdLine);
823                         int ret = system (cmdLine);
824                         if (ret != 0)
825                         {
826                                 Error(String.Format("[Fail] {0}", ret));
827                         }
828                         return;
829                 }
830
831                 // on Windows, we have to pipe the output of a
832                 // `cmd` interpolation to dos2unix, because the shell does not
833                 // strip the CRLFs generated by the native pkg-config distributed
834                 // with Mono.
835                 //
836                 // But if it's *not* on cygwin, just skip it.
837
838                 // check if dos2unix is applicable.
839                 if (use_dos2unix == true)
840                         try {
841                         var info = new ProcessStartInfo ("dos2unix");
842                         info.CreateNoWindow = true;
843                         info.RedirectStandardInput = true;
844                         info.UseShellExecute = false;
845                         var dos2unix = Process.Start (info);
846                         dos2unix.StandardInput.WriteLine ("aaa");
847                         dos2unix.StandardInput.WriteLine ("\u0004");
848                         dos2unix.StandardInput.Close ();
849                         dos2unix.WaitForExit ();
850                         if (dos2unix.ExitCode == 0)
851                                 use_dos2unix = true;
852                 } catch {
853                         Console.WriteLine("Warning: dos2unix not found");
854                         use_dos2unix = false;
855                 }
856
857                 if (use_dos2unix == null)
858                         use_dos2unix = false;
859
860                 ProcessStartInfo psi = new ProcessStartInfo();
861                 psi.UseShellExecute = false;
862
863                 // if there is no dos2unix, just run cmd /c.
864                 if (use_dos2unix == false)
865                 {
866                         psi.FileName = "cmd";
867                         psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
868                 }
869                 else
870                 {
871                         psi.FileName = "sh";
872                         StringBuilder b = new StringBuilder();
873                         int count = 0;
874                         for (int i = 0; i < cmdLine.Length; i++)
875                         {
876                                 if (cmdLine[i] == '`')
877                                 {
878                                         if (count % 2 != 0)
879                                         {
880                                                 b.Append("|dos2unix");
881                                         }
882                                         count++;
883                                 }
884                                 b.Append(cmdLine[i]);
885                         }
886                         cmdLine = b.ToString();
887                         psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
888                 }
889
890                 if (!quiet)
891                         Console.WriteLine(cmdLine);
892                 using (Process p = Process.Start (psi)) {
893                         p.WaitForExit ();
894                         int ret = p.ExitCode;
895                         if (ret != 0){
896                                 Error (String.Format("[Fail] {0}", ret));
897                         }
898                 }
899         }
900
901         static string GetEnv(string name, string defaultValue)
902         {
903                 string val = Environment.GetEnvironmentVariable(name);
904                 if (val != null)
905                 {
906                         if (!quiet)
907                                 Console.WriteLine("{0} = {1}", name, val);
908                 }
909                 else
910                 {
911                         val = defaultValue;
912                         if (!quiet)
913                                 Console.WriteLine("{0} = {1} (default)", name, val);
914                 }
915                 return val;
916         }
917
918         static string LocateFile(string default_path)
919         {
920                 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
921                 if (File.Exists(override_path))
922                         return override_path;
923                 else if (File.Exists(default_path))
924                         return default_path;
925                 else
926                         throw new FileNotFoundException(default_path);
927         }
928 }