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