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