[mkbundle] restore old behavior of -c flag
[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 = 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 = 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                                         compilerArgs.Add("/MT");
498                                         monoFile = monoPath + @"\lib\mono-2.0.lib";
499                                 }
500                                 else {
501                                         compilerArgs.Add("/MD");
502                                         monoFile = monoPath + @"\lib\mono-2.0.dll";
503                                 }
504
505                                 compilerArgs.Add(temp_c);
506                                 compilerArgs.Add(temp_o);
507                                 compilerArgs.Add("/link");
508
509                                 foreach (string lib in libs)
510                                         compilerArgs.Add(String.Format ("/LIBPATH:{0}", quote(lib)));
511                                 compilerArgs.Add (quote(monoFile));
512
513                                 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
514                                 Execute (cl_cmd);
515                         }
516                         else
517                         {
518                                 string zlib = (compress ? "-lz" : "");
519                                 string debugging = "-g";
520                                 string cc = GetEnv("CC", "cc");
521                                 string cmd = null;
522
523                                 if (style == "linux")
524                                         debugging = "-ggdb";
525                                 if (static_link)
526                                 {
527                                         string smonolib;
528                                         if (style == "osx")
529                                                 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
530                                         else
531                                                 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
532                                         cmd = String.Format("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
533                                                 "`pkg-config --libs-only-L mono-2` " + smonolib +
534                                                 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
535                                                 temp_c, temp_o, output, zlib, cc);
536                                 }
537                                 else
538                                 {
539
540                                         cmd = String.Format("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
541                                                 temp_c, temp_o, output, zlib, cc);
542                                 }
543                                 Execute (cmd);
544                         }
545
546                         Console.WriteLine ("Done");
547                 }
548         }
549                 } finally {
550                         if (!keeptemp){
551                                 if (object_out == null){
552                                         File.Delete (temp_o);
553                                 }
554                                 if (!compile_only){
555                                         File.Delete (temp_c);
556                                 }
557                                 File.Delete (temp_s);
558                         }
559                 }
560         }
561         
562         static List<string> LoadAssemblies (List<string> sources)
563         {
564                 List<string> assemblies = new List<string> ();
565                 bool error = false;
566                 
567                 foreach (string name in sources){
568                         try {
569                                 Assembly a = LoadAssembly (name);
570
571                                 if (a == null){
572                                         error = true;
573                                         continue;
574                                 }
575                         
576                                 assemblies.Add (a.CodeBase);
577                         } catch (Exception e) {
578                                 if (skip_scan) {
579                                         Console.WriteLine ("File will not be scanned: {0}", name);
580                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
581                                 } else {
582                                         throw;
583                                 }
584                         }
585                 }
586
587                 if (error)
588                         Environment.Exit (1);
589
590                 return assemblies;
591         }
592         
593         static readonly Universe universe = new Universe ();
594         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
595         
596         static bool QueueAssembly (List<string> files, string codebase)
597         {
598                 // Console.WriteLine ("CODE BASE IS {0}", codebase);
599                 if (files.Contains (codebase))
600                         return true;
601
602                 var path = new Uri(codebase).LocalPath;
603                 var name = Path.GetFileName (path);
604                 string found;
605                 if (loaded_assemblies.TryGetValue (name, out found)) {
606                         Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
607                         return false;
608                 }
609
610                 loaded_assemblies.Add (name, path);
611
612                 files.Add (codebase);
613                 if (!autodeps)
614                         return true;
615                 try {
616                         Assembly a = universe.LoadFile (path);
617
618                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
619                                 a = universe.Load (an.FullName);
620                                 if (!QueueAssembly (files, a.CodeBase))
621                                         return false;
622                         }
623                 } catch (Exception e) {
624                         if (!skip_scan)
625                                 throw;
626                 }
627
628                 return true;
629         }
630
631         static Assembly LoadAssembly (string assembly)
632         {
633                 Assembly a;
634                 
635                 try {
636                         char[] path_chars = { '/', '\\' };
637                         
638                         if (assembly.IndexOfAny (path_chars) != -1) {
639                                 a = universe.LoadFile (assembly);
640                         } else {
641                                 string ass = assembly;
642                                 if (ass.EndsWith (".dll"))
643                                         ass = assembly.Substring (0, assembly.Length - 4);
644                                 a = universe.Load (ass);
645                         }
646                         return a;
647                 } catch (FileNotFoundException){
648                         string total_log = "";
649                         
650                         foreach (string dir in link_paths){
651                                 string full_path = Path.Combine (dir, assembly);
652                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
653                                         full_path += ".dll";
654                                 
655                                 try {
656                                         a = universe.LoadFile (full_path);
657                                         return a;
658                                 } catch (FileNotFoundException ff) {
659                                         total_log += ff.FusionLog;
660                                         continue;
661                                 }
662                         }
663                         Error ("Cannot find assembly `" + assembly + "'" );
664                         Console.WriteLine ("Log: \n" + total_log);
665                 } catch (IKVM.Reflection.BadImageFormatException f) {
666                         if (skip_scan)
667                                 throw;
668                         Error ("Cannot load assembly (bad file format) " + f.Message);
669                 } catch (FileLoadException f){
670                         Error ("Cannot load assembly " + f.Message);
671                 } catch (ArgumentNullException){
672                         Error("Cannot load assembly (null argument)");
673                 }
674                 return null;
675         }
676
677         static void Error (string msg)
678         {
679                 Console.Error.WriteLine ("ERROR: " + msg);
680                 Environment.Exit (1);
681         }
682
683         static void Help ()
684         {
685                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
686                                    "Options:\n" +
687                                    "    -c                  Produce stub only, do not compile\n" +
688                                    "    -o out              Specifies output filename\n" +
689                                    "    -oo obj             Specifies output filename for helper object file\n" +
690                                    "    -L path             Adds `path' to the search path for assemblies\n" +
691                                    "    --nodeps            Turns off automatic dependency embedding (default)\n" +
692                                    "    --deps              Turns on automatic dependency embedding\n" +
693                                    "    --dos2unix[=true|false]\n" +
694                                    "                        When no value provided, or when `true` specified\n" +
695                                    "                        `dos2unix` will be invoked to convert paths on Windows.\n" +
696                                    "                        When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
697                                    "    --keeptemp          Keeps the temporary files\n" +
698                                    "    --config F          Bundle system config file `F'\n" +
699                                    "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
700                                    "    --machine-config F  Use the given file as the machine.config for the application.\n" +
701                                    "    --static            Statically link to mono libs\n" +
702                                    "    --nomain            Don't include a main() function, for libraries\n" +
703                                    "    -z                  Compress the assemblies before embedding.\n" +
704                                    "    --skip-scan         Skip scanning assemblies that could not be loaded (but still embed them).\n" +
705                                    "    --static-ctor ctor  Add a constructor call to the supplied function.\n" +
706                                    "                        You need zlib development headers and libraries.\n");
707         }
708
709         [DllImport ("libc")]
710         static extern int system (string s);
711         [DllImport ("libc")]
712         static extern int uname (IntPtr buf);
713                 
714         static void DetectOS ()
715         {
716                 if (!IsUnix) {
717                         Console.WriteLine ("OS is: Windows");
718                         style = "windows";
719                         return;
720                 }
721
722                 IntPtr buf = Marshal.AllocHGlobal (8192);
723                 if (uname (buf) != 0){
724                         Console.WriteLine ("Warning: Unable to detect OS");
725                         Marshal.FreeHGlobal (buf);
726                         return;
727                 }
728                 string os = Marshal.PtrToStringAnsi (buf);
729                 Console.WriteLine ("OS is: " + os);
730                 if (os == "Darwin")
731                         style = "osx";
732                 
733                 Marshal.FreeHGlobal (buf);
734         }
735
736         static bool IsUnix {
737                 get {
738                         int p = (int) Environment.OSVersion.Platform;
739                         return ((p == 4) || (p == 128) || (p == 6));
740                 }
741         }
742
743         static void Execute (string cmdLine)
744         {
745                 if (IsUnix) {
746                         Console.WriteLine ("[execute cmd]: " + cmdLine);
747                         int ret = system (cmdLine);
748                         if (ret != 0)
749                         {
750                                 Error(String.Format("[Fail] {0}", ret));
751                         }
752                         return;
753                 }
754
755                 // on Windows, we have to pipe the output of a
756                 // `cmd` interpolation to dos2unix, because the shell does not
757                 // strip the CRLFs generated by the native pkg-config distributed
758                 // with Mono.
759                 //
760                 // But if it's *not* on cygwin, just skip it.
761
762                 // check if dos2unix is applicable.
763                 if (use_dos2unix == true)
764                         try {
765                         var info = new ProcessStartInfo ("dos2unix");
766                         info.CreateNoWindow = true;
767                         info.RedirectStandardInput = true;
768                         info.UseShellExecute = false;
769                         var dos2unix = Process.Start (info);
770                         dos2unix.StandardInput.WriteLine ("aaa");
771                         dos2unix.StandardInput.WriteLine ("\u0004");
772                         dos2unix.StandardInput.Close ();
773                         dos2unix.WaitForExit ();
774                         if (dos2unix.ExitCode == 0)
775                                 use_dos2unix = true;
776                 } catch {
777                         Console.WriteLine("Warning: dos2unix not found");
778                         use_dos2unix = false;
779                 }
780
781                 if (use_dos2unix == null)
782                         use_dos2unix = false;
783
784                 ProcessStartInfo psi = new ProcessStartInfo();
785                 psi.UseShellExecute = false;
786
787                 // if there is no dos2unix, just run cmd /c.
788                 if (use_dos2unix == false)
789                 {
790                         psi.FileName = "cmd";
791                         psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
792                 }
793                 else
794                 {
795                         psi.FileName = "sh";
796                         StringBuilder b = new StringBuilder();
797                         int count = 0;
798                         for (int i = 0; i < cmdLine.Length; i++)
799                         {
800                                 if (cmdLine[i] == '`')
801                                 {
802                                         if (count % 2 != 0)
803                                         {
804                                                 b.Append("|dos2unix");
805                                         }
806                                         count++;
807                                 }
808                                 b.Append(cmdLine[i]);
809                         }
810                         cmdLine = b.ToString();
811                         psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
812                 }
813
814                 Console.WriteLine(cmdLine);
815                 using (Process p = Process.Start (psi)) {
816                         p.WaitForExit ();
817                         int ret = p.ExitCode;
818                         if (ret != 0){
819                                 Error (String.Format("[Fail] {0}", ret));
820                         }
821                 }
822         }
823
824         static string GetEnv(string name, string defaultValue)
825         {
826                 string val = Environment.GetEnvironmentVariable(name);
827                 if (val != null)
828                 {
829                         Console.WriteLine("{0} = {1}", name, val);
830                 }
831                 else
832                 {
833                         val = defaultValue;
834                         Console.WriteLine("{0} = {1} (default)", name, val);
835                 }
836                 return val;
837         }
838 }