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