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