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