Improve a safety check when writing data into StatBuffer
[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                         // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
357                         var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
358                         foreach (var url in files) {
359                                 string fname = LocateFile (new Uri (url).LocalPath);
360                                 string aname = Path.GetFileName (fname);
361                                 string encoded = symbolEscapeRE.Replace (aname, "_");
362
363                                 if (prog == null)
364                                         prog = aname;
365
366                                 var stream = streams [url];
367                                 var real_size = sizes [url];
368
369                                 if (!quiet)
370                                         Console.WriteLine ("   embedding: " + fname);
371
372                                 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
373                         
374                                 WriteBuffer (ts, stream, buffer);
375
376                                 if (compress) {
377                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
378                                         tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
379                                                                   " assembly_data_{0}, {2}}}, {3}}};",
380                                                                   encoded, aname, real_size, stream.Length);
381                                         if (!quiet) {
382                                                 double ratio = ((double) stream.Length * 100) / real_size;
383                                                 Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
384                                         }
385                                 } else {
386                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
387                                         tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
388                                                                   encoded, aname, real_size);
389                                 }
390                                 stream.Close ();
391
392                                 c_bundle_names.Add ("assembly_bundle_" + encoded);
393
394                                 try {
395                                         FileStream cf = File.OpenRead (fname + ".config");
396                                         if (!quiet)
397                                                 Console.WriteLine (" config from: " + fname + ".config");
398                                         tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
399                                         WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
400                                         WriteBuffer (ts, cf, buffer);
401                                         ts.WriteLine ();
402                                         config_names.Add (new string[] {aname, encoded});
403                                 } catch (FileNotFoundException) {
404                                         /* we ignore if the config file doesn't exist */
405                                 }
406                         }
407
408                         if (config_file != null){
409                                 FileStream conf;
410                                 try {
411                                         conf = File.OpenRead (config_file);
412                                 } catch {
413                                         Error (String.Format ("Failure to open {0}", config_file));
414                                         return;
415                                 }
416                                 if (!quiet)
417                                         Console.WriteLine ("System config from: " + config_file);
418                                 tc.WriteLine ("extern const char system_config;");
419                                 WriteSymbol (ts, "system_config", config_file.Length);
420
421                                 WriteBuffer (ts, conf, buffer);
422                                 // null terminator
423                                 ts.Write ("\t.byte 0\n");
424                                 ts.WriteLine ();
425                         }
426
427                         if (machine_config_file != null){
428                                 FileStream conf;
429                                 try {
430                                         conf = File.OpenRead (machine_config_file);
431                                 } catch {
432                                         Error (String.Format ("Failure to open {0}", machine_config_file));
433                                         return;
434                                 }
435                                 if (!quiet)
436                                         Console.WriteLine ("Machine config from: " + machine_config_file);
437                                 tc.WriteLine ("extern const char machine_config;");
438                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
439
440                                 WriteBuffer (ts, conf, buffer);
441                                 ts.Write ("\t.byte 0\n");
442                                 ts.WriteLine ();
443                         }
444                         ts.Close ();
445
446                         if (compress)
447                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
448                         else
449                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
450
451                         foreach (string c in c_bundle_names){
452                                 tc.WriteLine ("\t&{0},", c);
453                         }
454                         tc.WriteLine ("\tNULL\n};\n");
455                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
456
457                         if (ctor_func != null) {
458                                 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
459                                 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
460                                 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
461                         }
462
463                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
464                         foreach (string[] ass in config_names){
465                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
466                         }
467                         if (config_file != null)
468                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
469                         if (machine_config_file != null)
470                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
471                         tc.WriteLine ("}\n");
472
473                         if (config_dir != null)
474                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
475                         else
476                                 tc.WriteLine ("static const char *config_dir = NULL;");
477
478                         Stream template_stream;
479                         if (compress) {
480                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
481                         } else {
482                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
483                         }
484
485                         StreamReader s = new StreamReader (template_stream);
486                         string template = s.ReadToEnd ();
487                         tc.Write (template);
488
489                         if (!nomain && custom_main == null) {
490                                 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
491                                 StreamReader st = new StreamReader (template_main_stream);
492                                 string maintemplate = st.ReadToEnd ();
493                                 tc.Write (maintemplate);
494                         }
495
496                         tc.Close ();
497
498                         string assembler = GetEnv("AS", "as");
499                         string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
500                         Execute(as_cmd);
501
502                         if (compile_only)
503                                 return;
504
505                         if (!quiet)
506                                 Console.WriteLine("Compiling:");
507
508                         if (style == "windows")
509                         {
510
511                                 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
512
513                                 string compiler = GetEnv("CC", "cl.exe");
514                                 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
515                                 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
516                                 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
517
518                                 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
519                                 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
520                                 var linkLibraries = new string[] {  "kernel32.lib",
521                                                                                                 "version.lib",
522                                                                                                 "Ws2_32.lib",
523                                                                                                 "Mswsock.lib",
524                                                                                                 "Psapi.lib",
525                                                                                                 "shell32.lib",
526                                                                                                 "OleAut32.lib",
527                                                                                                 "ole32.lib",
528                                                                                                 "winmm.lib",
529                                                                                                 "user32.lib",
530                                                                                                 "libvcruntime.lib",
531                                                                                                 "advapi32.lib",
532                                                                                                 "OLDNAMES.lib",
533                                                                                                 "libucrt.lib" };
534
535                                 string glue_obj = "mkbundle_glue.obj";
536                                 string monoLib;
537
538                                 if (static_link)
539                                         monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
540
541                                 else {
542                                         Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
543                                         monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
544                                         LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
545                                 }
546
547                                 var compilerArgs = new List<string>();
548                                 compilerArgs.Add("/MT");
549
550                                 foreach (string include in includes)
551                                         compilerArgs.Add(String.Format ("/I {0}", quote (include)));
552
553                                 if (!nomain || custom_main != null) {
554                                         compilerArgs.Add(quote(temp_c));
555                                         compilerArgs.Add(quote(temp_o));
556                                         if (custom_main != null)
557                                                 compilerArgs.Add(quote(custom_main));
558                                         compilerArgs.Add(quote(monoLib));
559                                         compilerArgs.Add("/link");
560                                         compilerArgs.Add("/NODEFAULTLIB");
561                                         compilerArgs.Add("/SUBSYSTEM:windows");
562                                         compilerArgs.Add("/ENTRY:mainCRTStartup");
563                                         compilerArgs.AddRange(linkLibraries);
564                                         compilerArgs.Add("/out:"+ output);
565
566                                         string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
567                                         Execute (cl_cmd);
568                                 }
569                                 else
570                                 {
571                                         // we are just creating a .lib
572                                         compilerArgs.Add("/c"); // compile only
573                                         compilerArgs.Add(temp_c);
574                                         compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
575
576                                         string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
577                                         Execute (cl_cmd);
578
579                                         string librarian = GetEnv ("LIB", "lib.exe");
580                                         var librarianArgs = new List<string> ();
581                                         librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
582                                         librarianArgs.Add (temp_o);
583                                         librarianArgs.Add (glue_obj);
584                                         librarianArgs.Add (monoLib);
585                                         string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
586                                         Execute (lib_cmd);
587                                 }
588                         }
589                         else
590                         {
591                                 string zlib = (compress ? "-lz" : "");
592                                 string debugging = "-g";
593                                 string cc = GetEnv("CC", "cc");
594                                 string cmd = null;
595
596                                 if (style == "linux")
597                                         debugging = "-ggdb";
598                                 if (static_link)
599                                 {
600                                         string smonolib;
601                                         if (style == "osx")
602                                                 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
603                                         else
604                                                 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
605                                         cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
606                                                 "`pkg-config --libs-only-L mono-2` " + smonolib +
607                                                 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
608                                                 temp_c, temp_o, output, zlib, cc);
609                                 }
610                                 else
611                                 {
612
613                                         cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
614                                                 temp_c, temp_o, output, zlib, cc);
615                                 }
616                                 Execute (cmd);
617                         }
618
619                         if (!quiet)
620                                 Console.WriteLine ("Done");
621                 }
622         }
623                 } finally {
624                         if (!keeptemp){
625                                 if (object_out == null){
626                                         File.Delete (temp_o);
627                                 }
628                                 if (!compile_only){
629                                         File.Delete (temp_c);
630                                 }
631                                 File.Delete (temp_s);
632                         }
633                 }
634         }
635         
636         static List<string> LoadAssemblies (List<string> sources)
637         {
638                 List<string> assemblies = new List<string> ();
639                 bool error = false;
640                 
641                 foreach (string name in sources){
642                         try {
643                                 Assembly a = LoadAssembly (name);
644
645                                 if (a == null){
646                                         error = true;
647                                         continue;
648                                 }
649                         
650                                 assemblies.Add (a.CodeBase);
651                         } catch (Exception) {
652                                 if (skip_scan) {
653                                         if (!quiet)
654                                                 Console.WriteLine ("File will not be scanned: {0}", name);
655                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
656                                 } else {
657                                         throw;
658                                 }
659                         }
660                 }
661
662                 if (error)
663                         Environment.Exit (1);
664
665                 return assemblies;
666         }
667         
668         static readonly Universe universe = new Universe ();
669         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
670         
671         static bool QueueAssembly (List<string> files, string codebase)
672         {
673                 // Console.WriteLine ("CODE BASE IS {0}", codebase);
674                 if (files.Contains (codebase))
675                         return true;
676
677                 var path = new Uri(codebase).LocalPath;
678                 var name = Path.GetFileName (path);
679                 string found;
680                 if (loaded_assemblies.TryGetValue (name, out found)) {
681                         Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
682                         return false;
683                 }
684
685                 loaded_assemblies.Add (name, path);
686
687                 files.Add (codebase);
688                 if (!autodeps)
689                         return true;
690                 try {
691                         Assembly a = universe.LoadFile (path);
692
693                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
694                                 a = universe.Load (an.FullName);
695                                 if (!QueueAssembly (files, a.CodeBase))
696                                         return false;
697                         }
698                 } catch (Exception) {
699                         if (!skip_scan)
700                                 throw;
701                 }
702
703                 return true;
704         }
705
706         static Assembly LoadAssembly (string assembly)
707         {
708                 Assembly a;
709                 
710                 try {
711                         char[] path_chars = { '/', '\\' };
712                         
713                         if (assembly.IndexOfAny (path_chars) != -1) {
714                                 a = universe.LoadFile (assembly);
715                         } else {
716                                 string ass = assembly;
717                                 if (ass.EndsWith (".dll"))
718                                         ass = assembly.Substring (0, assembly.Length - 4);
719                                 a = universe.Load (ass);
720                         }
721                         return a;
722                 } catch (FileNotFoundException){
723                         string total_log = "";
724                         
725                         foreach (string dir in link_paths){
726                                 string full_path = Path.Combine (dir, assembly);
727                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
728                                         full_path += ".dll";
729                                 
730                                 try {
731                                         a = universe.LoadFile (full_path);
732                                         return a;
733                                 } catch (FileNotFoundException ff) {
734                                         total_log += ff.FusionLog;
735                                         continue;
736                                 }
737                         }
738                         Error ("Cannot find assembly `" + assembly + "'" );
739                         if (!quiet)
740                                 Console.WriteLine ("Log: \n" + total_log);
741                 } catch (IKVM.Reflection.BadImageFormatException f) {
742                         if (skip_scan)
743                                 throw;
744                         Error ("Cannot load assembly (bad file format) " + f.Message);
745                 } catch (FileLoadException f){
746                         Error ("Cannot load assembly " + f.Message);
747                 } catch (ArgumentNullException){
748                         Error("Cannot load assembly (null argument)");
749                 }
750                 return null;
751         }
752
753         static void Error (string msg)
754         {
755                 Console.Error.WriteLine ("ERROR: " + msg);
756                 Environment.Exit (1);
757         }
758
759         static void Help ()
760         {
761                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
762                                    "Options:\n" +
763                                    "    -c                  Produce stub only, do not compile\n" +
764                                    "    -o out              Specifies output filename\n" +
765                                    "    -oo obj             Specifies output filename for helper object file\n" +
766                                    "    -L path             Adds `path' to the search path for assemblies\n" +
767                                    "    --nodeps            Turns off automatic dependency embedding (default)\n" +
768                                    "    --deps              Turns on automatic dependency embedding\n" +
769                                    "    --dos2unix[=true|false]\n" +
770                                    "                        When no value provided, or when `true` specified\n" +
771                                    "                        `dos2unix` will be invoked to convert paths on Windows.\n" +
772                                    "                        When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
773                                    "    --keeptemp          Keeps the temporary files\n" +
774                                    "    --config F          Bundle system config file `F'\n" +
775                                    "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
776                                    "    --machine-config F  Use the given file as the machine.config for the application.\n" +
777                                    "    --static            Statically link to mono libs\n" +
778                                    "    --nomain            Don't include a main() function, for libraries\n" +
779                                    "    --custom-main C         Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
780                                    "    -z                  Compress the assemblies before embedding.\n" +
781                                    "    --skip-scan         Skip scanning assemblies that could not be loaded (but still embed them).\n" +
782                                    "    --static-ctor ctor  Add a constructor call to the supplied function.\n" +
783                                    "                        You need zlib development headers and libraries.\n");
784         }
785
786         [DllImport ("libc")]
787         static extern int system (string s);
788         [DllImport ("libc")]
789         static extern int uname (IntPtr buf);
790                 
791         static void DetectOS ()
792         {
793                 if (!IsUnix) {
794                         os_message = "OS is: Windows";
795                         style = "windows";
796                         return;
797                 }
798
799                 IntPtr buf = Marshal.AllocHGlobal (8192);
800                 if (uname (buf) != 0){
801                         os_message = "Warning: Unable to detect OS";
802                         Marshal.FreeHGlobal (buf);
803                         return;
804                 }
805                 string os = Marshal.PtrToStringAnsi (buf);
806                 os_message = "OS is: " + os;
807                 if (os == "Darwin")
808                         style = "osx";
809                 
810                 Marshal.FreeHGlobal (buf);
811         }
812
813         static bool IsUnix {
814                 get {
815                         int p = (int) Environment.OSVersion.Platform;
816                         return ((p == 4) || (p == 128) || (p == 6));
817                 }
818         }
819
820         static void Execute (string cmdLine)
821         {
822                 if (IsUnix) {
823                         if (!quiet)
824                                 Console.WriteLine ("[execute cmd]: " + cmdLine);
825                         int ret = system (cmdLine);
826                         if (ret != 0)
827                         {
828                                 Error(String.Format("[Fail] {0}", ret));
829                         }
830                         return;
831                 }
832
833                 // on Windows, we have to pipe the output of a
834                 // `cmd` interpolation to dos2unix, because the shell does not
835                 // strip the CRLFs generated by the native pkg-config distributed
836                 // with Mono.
837                 //
838                 // But if it's *not* on cygwin, just skip it.
839
840                 // check if dos2unix is applicable.
841                 if (use_dos2unix == true)
842                         try {
843                         var info = new ProcessStartInfo ("dos2unix");
844                         info.CreateNoWindow = true;
845                         info.RedirectStandardInput = true;
846                         info.UseShellExecute = false;
847                         var dos2unix = Process.Start (info);
848                         dos2unix.StandardInput.WriteLine ("aaa");
849                         dos2unix.StandardInput.WriteLine ("\u0004");
850                         dos2unix.StandardInput.Close ();
851                         dos2unix.WaitForExit ();
852                         if (dos2unix.ExitCode == 0)
853                                 use_dos2unix = true;
854                 } catch {
855                         Console.WriteLine("Warning: dos2unix not found");
856                         use_dos2unix = false;
857                 }
858
859                 if (use_dos2unix == null)
860                         use_dos2unix = false;
861
862                 ProcessStartInfo psi = new ProcessStartInfo();
863                 psi.UseShellExecute = false;
864
865                 // if there is no dos2unix, just run cmd /c.
866                 if (use_dos2unix == false)
867                 {
868                         psi.FileName = "cmd";
869                         psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
870                 }
871                 else
872                 {
873                         psi.FileName = "sh";
874                         StringBuilder b = new StringBuilder();
875                         int count = 0;
876                         for (int i = 0; i < cmdLine.Length; i++)
877                         {
878                                 if (cmdLine[i] == '`')
879                                 {
880                                         if (count % 2 != 0)
881                                         {
882                                                 b.Append("|dos2unix");
883                                         }
884                                         count++;
885                                 }
886                                 b.Append(cmdLine[i]);
887                         }
888                         cmdLine = b.ToString();
889                         psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
890                 }
891
892                 if (!quiet)
893                         Console.WriteLine(cmdLine);
894                 using (Process p = Process.Start (psi)) {
895                         p.WaitForExit ();
896                         int ret = p.ExitCode;
897                         if (ret != 0){
898                                 Error (String.Format("[Fail] {0}", ret));
899                         }
900                 }
901         }
902
903         static string GetEnv(string name, string defaultValue)
904         {
905                 string val = Environment.GetEnvironmentVariable(name);
906                 if (val != null)
907                 {
908                         if (!quiet)
909                                 Console.WriteLine("{0} = {1}", name, val);
910                 }
911                 else
912                 {
913                         val = defaultValue;
914                         if (!quiet)
915                                 Console.WriteLine("{0} = {1} (default)", name, val);
916                 }
917                 return val;
918         }
919
920         static string LocateFile(string default_path)
921         {
922                 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
923                 if (File.Exists(override_path))
924                         return override_path;
925                 else if (File.Exists(default_path))
926                         return default_path;
927                 else
928                         throw new FileNotFoundException(default_path);
929         }
930 }