[runtime] Updates comments.
[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                         default:
160                                 sources.Add (args [i]);
161                                 break;
162                         }
163                         
164                         if (static_link && style == "windows") {
165                                 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
166                                 return 1;
167                         }
168                 }
169
170                 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
171                 if (sources.Count == 0 || output == null) {
172                         Help ();
173                         Environment.Exit (1);
174                 }
175
176                 List<string> assemblies = LoadAssemblies (sources);
177                 List<string> files = new List<string> ();
178                 foreach (string file in assemblies)
179                         if (!QueueAssembly (files, file))
180                                 return 1;
181                         
182                 GenerateBundles (files);
183                 //GenerateJitWrapper ();
184                 
185                 return 0;
186         }
187
188         static void WriteSymbol (StreamWriter sw, string name, long size)
189         {
190                 switch (style){
191                 case "linux":
192                         sw.WriteLine (
193                                 ".globl {0}\n" +
194                                 "\t.section .rodata\n" +
195                                 "\t.p2align 5\n" +
196                                 "\t.type {0}, \"object\"\n" +
197                                 "\t.size {0}, {1}\n" +
198                                 "{0}:\n",
199                                 name, size);
200                         break;
201                 case "osx":
202                         sw.WriteLine (
203                                 "\t.section __TEXT,__text,regular,pure_instructions\n" + 
204                                 "\t.globl _{0}\n" +
205                                 "\t.data\n" +
206                                 "\t.align 4\n" +
207                                 "_{0}:\n",
208                                 name, size);
209                         break;
210                 case "windows":
211                         sw.WriteLine (
212                                 ".globl _{0}\n" +
213                                 "\t.section .rdata,\"dr\"\n" +
214                                 "\t.align 32\n" +
215                                 "_{0}:\n",
216                                 name, size);
217                         break;
218                 }
219         }
220         
221         static string [] chars = new string [256];
222         
223         static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
224         {
225                 int n;
226                 
227                 // Preallocate the strings we need.
228                 if (chars [0] == null) {
229                         for (int i = 0; i < chars.Length; i++)
230                                 chars [i] = string.Format ("{0}", i.ToString ());
231                 }
232
233                 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
234                         int count = 0;
235                         for (int i = 0; i < n; i++) {
236                                 if (count % 32 == 0) {
237                                         ts.Write ("\n\t.byte ");
238                                 } else {
239                                         ts.Write (",");
240                                 }
241                                 ts.Write (chars [buffer [i]]);
242                                 count ++;
243                         }
244                 }
245
246                 ts.WriteLine ();
247         }
248         
249         static void GenerateBundles (List<string> files)
250         {
251                 string temp_s = "temp.s"; // Path.GetTempFileName ();
252                 string temp_c = "temp.c";
253                 string temp_o = "temp.o";
254
255                 if (compile_only)
256                         temp_c = output;
257                 if (object_out != null)
258                         temp_o = object_out;
259                 
260                 try {
261                         List<string> c_bundle_names = new List<string> ();
262                         List<string[]> config_names = new List<string[]> ();
263
264                         using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
265                         using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
266                         string prog = null;
267
268 #if XAMARIN_ANDROID
269                         tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
270                         tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
271                         tc.WriteLine (@"
272 typedef struct {
273         const char *name;
274         const unsigned char *data;
275         const unsigned int size;
276 } MonoBundledAssembly;
277 void          mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
278 void          mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
279 ");
280 #else
281                         tc.WriteLine ("#include <mono/metadata/mono-config.h>");
282                         tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
283 #endif
284
285                         if (compress) {
286                                 tc.WriteLine ("typedef struct _compressed_data {");
287                                 tc.WriteLine ("\tMonoBundledAssembly assembly;");
288                                 tc.WriteLine ("\tint compressed_size;");
289                                 tc.WriteLine ("} CompressedAssembly;\n");
290                         }
291
292                         object monitor = new object ();
293
294                         var streams = new Dictionary<string, Stream> ();
295                         var sizes = new Dictionary<string, long> ();
296
297                         // Do the file reading and compression in parallel
298                         Action<string> body = delegate (string url) {
299                                 string fname = new Uri (url).LocalPath;
300                                 Stream stream = File.OpenRead (fname);
301
302                                 long real_size = stream.Length;
303                                 int n;
304                                 if (compress) {
305                                         byte[] cbuffer = new byte [8192];
306                                         MemoryStream ms = new MemoryStream ();
307                                         GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
308                                         while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
309                                                 deflate.Write (cbuffer, 0, n);
310                                         }
311                                         stream.Close ();
312                                         deflate.Close ();
313                                         byte [] bytes = ms.GetBuffer ();
314                                         stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
315                                 }
316
317                                 lock (monitor) {
318                                         streams [url] = stream;
319                                         sizes [url] = real_size;
320                                 }
321                         };
322
323                         //#if NET_4_5
324 #if FALSE
325                         Parallel.ForEach (files, body);
326 #else
327                         foreach (var url in files)
328                                 body (url);
329 #endif
330
331                         // The non-parallel part
332                         byte [] buffer = new byte [8192];
333                         foreach (var url in files) {
334                                 string fname = new Uri (url).LocalPath;
335                                 string aname = Path.GetFileName (fname);
336                                 string encoded = aname.Replace ("-", "_").Replace (".", "_");
337
338                                 if (prog == null)
339                                         prog = aname;
340
341                                 var stream = streams [url];
342                                 var real_size = sizes [url];
343
344                                 Console.WriteLine ("   embedding: " + fname);
345
346                                 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
347                         
348                                 WriteBuffer (ts, stream, buffer);
349
350                                 if (compress) {
351                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
352                                         tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
353                                                                   " assembly_data_{0}, {2}}}, {3}}};",
354                                                                   encoded, aname, real_size, stream.Length);
355                                         double ratio = ((double) stream.Length * 100) / real_size;
356                                         Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
357                                 } else {
358                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
359                                         tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
360                                                                   encoded, aname, real_size);
361                                 }
362                                 stream.Close ();
363
364                                 c_bundle_names.Add ("assembly_bundle_" + encoded);
365
366                                 try {
367                                         FileStream cf = File.OpenRead (fname + ".config");
368                                         Console.WriteLine (" config from: " + fname + ".config");
369                                         tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
370                                         WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
371                                         WriteBuffer (ts, cf, buffer);
372                                         ts.WriteLine ();
373                                         config_names.Add (new string[] {aname, encoded});
374                                 } catch (FileNotFoundException) {
375                                         /* we ignore if the config file doesn't exist */
376                                 }
377                         }
378
379                         if (config_file != null){
380                                 FileStream conf;
381                                 try {
382                                         conf = File.OpenRead (config_file);
383                                 } catch {
384                                         Error (String.Format ("Failure to open {0}", config_file));
385                                         return;
386                                 }
387                                 Console.WriteLine ("System config from: " + config_file);
388                                 tc.WriteLine ("extern const char system_config;");
389                                 WriteSymbol (ts, "system_config", config_file.Length);
390
391                                 WriteBuffer (ts, conf, buffer);
392                                 // null terminator
393                                 ts.Write ("\t.byte 0\n");
394                                 ts.WriteLine ();
395                         }
396
397                         if (machine_config_file != null){
398                                 FileStream conf;
399                                 try {
400                                         conf = File.OpenRead (machine_config_file);
401                                 } catch {
402                                         Error (String.Format ("Failure to open {0}", machine_config_file));
403                                         return;
404                                 }
405                                 Console.WriteLine ("Machine config from: " + machine_config_file);
406                                 tc.WriteLine ("extern const char machine_config;");
407                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
408
409                                 WriteBuffer (ts, conf, buffer);
410                                 ts.Write ("\t.byte 0\n");
411                                 ts.WriteLine ();
412                         }
413                         ts.Close ();
414                         
415                         Console.WriteLine ("Compiling:");
416                         string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
417                         int ret = Execute (cmd);
418                         if (ret != 0){
419                                 Error ("[Fail]");
420                                 return;
421                         }
422
423                         if (compress)
424                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
425                         else
426                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
427
428                         foreach (string c in c_bundle_names){
429                                 tc.WriteLine ("\t&{0},", c);
430                         }
431                         tc.WriteLine ("\tNULL\n};\n");
432                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
433
434                         if (ctor_func != null) {
435                                 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
436                                 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
437                                 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
438                         }
439
440                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
441                         foreach (string[] ass in config_names){
442                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
443                         }
444                         if (config_file != null)
445                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
446                         if (machine_config_file != null)
447                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
448                         tc.WriteLine ("}\n");
449
450                         if (config_dir != null)
451                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
452                         else
453                                 tc.WriteLine ("static const char *config_dir = NULL;");
454
455                         Stream template_stream;
456                         if (compress) {
457                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
458                         } else {
459                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
460                         }
461
462                         StreamReader s = new StreamReader (template_stream);
463                         string template = s.ReadToEnd ();
464                         tc.Write (template);
465
466                         if (!nomain) {
467                                 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
468                                 StreamReader st = new StreamReader (template_main_stream);
469                                 string maintemplate = st.ReadToEnd ();
470                                 tc.Write (maintemplate);
471                         }
472                         
473                         tc.Close ();
474
475                         if (compile_only)
476                                 return;
477
478                         string zlib = (compress ? "-lz" : "");
479                         string debugging = "-g";
480                         string cc = GetEnv ("CC", IsUnix ? "cc" : "i686-pc-mingw32-gcc");
481
482                         if (style == "linux")
483                                 debugging = "-ggdb";
484                         if (static_link) {
485                                 string smonolib;
486                                 if (style == "osx")
487                                         smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
488                                 else
489                                         smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
490                                 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
491                                                      "`pkg-config --libs-only-L mono-2` " + smonolib +
492                                                      "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
493                                                      temp_c, temp_o, output, zlib, cc);
494                         } else {
495                                 
496                                 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
497                                                      temp_c, temp_o, output, zlib, cc);
498                         }
499                             
500                         ret = Execute (cmd);
501                         if (ret != 0){
502                                 Error ("[Fail]");
503                                 return;
504                         }
505                         Console.WriteLine ("Done");
506                         }
507                         }
508                 } finally {
509                         if (!keeptemp){
510                                 if (object_out == null){
511                                         File.Delete (temp_o);
512                                 }
513                                 if (!compile_only){
514                                         File.Delete (temp_c);
515                                 }
516                                 File.Delete (temp_s);
517                         }
518                 }
519         }
520         
521         static List<string> LoadAssemblies (List<string> sources)
522         {
523                 List<string> assemblies = new List<string> ();
524                 bool error = false;
525                 
526                 foreach (string name in sources){
527                         try {
528                                 Assembly a = LoadAssembly (name);
529
530                                 if (a == null){
531                                         error = true;
532                                         continue;
533                                 }
534                         
535                                 assemblies.Add (a.CodeBase);
536                         } catch (Exception e) {
537                                 if (skip_scan) {
538                                         Console.WriteLine ("File will not be scanned: {0}", name);
539                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
540                                 } else {
541                                         throw;
542                                 }
543                         }
544                 }
545
546                 if (error)
547                         Environment.Exit (1);
548
549                 return assemblies;
550         }
551         
552         static readonly Universe universe = new Universe ();
553         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
554         
555         static bool QueueAssembly (List<string> files, string codebase)
556         {
557                 // Console.WriteLine ("CODE BASE IS {0}", codebase);
558                 if (files.Contains (codebase))
559                         return true;
560
561                 var path = new Uri(codebase).LocalPath;
562                 var name = Path.GetFileName (path);
563                 string found;
564                 if (loaded_assemblies.TryGetValue (name, out found)) {
565                         Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
566                         return false;
567                 }
568
569                 loaded_assemblies.Add (name, path);
570
571                 files.Add (codebase);
572                 if (!autodeps)
573                         return true;
574                 try {
575                         Assembly a = universe.LoadFile (path);
576
577                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
578                                 a = universe.Load (an.FullName);
579                                 if (!QueueAssembly (files, a.CodeBase))
580                                         return false;
581                         }
582                 } catch (Exception e) {
583                         if (!skip_scan)
584                                 throw;
585                 }
586
587                 return true;
588         }
589
590         static Assembly LoadAssembly (string assembly)
591         {
592                 Assembly a;
593                 
594                 try {
595                         char[] path_chars = { '/', '\\' };
596                         
597                         if (assembly.IndexOfAny (path_chars) != -1) {
598                                 a = universe.LoadFile (assembly);
599                         } else {
600                                 string ass = assembly;
601                                 if (ass.EndsWith (".dll"))
602                                         ass = assembly.Substring (0, assembly.Length - 4);
603                                 a = universe.Load (ass);
604                         }
605                         return a;
606                 } catch (FileNotFoundException){
607                         string total_log = "";
608                         
609                         foreach (string dir in link_paths){
610                                 string full_path = Path.Combine (dir, assembly);
611                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
612                                         full_path += ".dll";
613                                 
614                                 try {
615                                         a = universe.LoadFile (full_path);
616                                         return a;
617                                 } catch (FileNotFoundException ff) {
618                                         total_log += ff.FusionLog;
619                                         continue;
620                                 }
621                         }
622                         Error ("Cannot find assembly `" + assembly + "'" );
623                         Console.WriteLine ("Log: \n" + total_log);
624                 } catch (IKVM.Reflection.BadImageFormatException f) {
625                         if (skip_scan)
626                                 throw;
627                         Error ("Cannot load assembly (bad file format) " + f.Message);
628                 } catch (FileLoadException f){
629                         Error ("Cannot load assembly " + f.Message);
630                 } catch (ArgumentNullException){
631                         Error("Cannot load assembly (null argument)");
632                 }
633                 return null;
634         }
635
636         static void Error (string msg)
637         {
638                 Console.Error.WriteLine ("ERROR: " + msg);
639                 Environment.Exit (1);
640         }
641
642         static void Help ()
643         {
644                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
645                                    "Options:\n" +
646                                    "    -c                  Produce stub only, do not compile\n" +
647                                    "    -o out              Specifies output filename\n" +
648                                    "    -oo obj             Specifies output filename for helper object file\n" +
649                                    "    -L path             Adds `path' to the search path for assemblies\n" +
650                                    "    --nodeps            Turns off automatic dependency embedding (default)\n" +
651                                    "    --deps              Turns on automatic dependency embedding\n" +
652                                    "    --keeptemp          Keeps the temporary files\n" +
653                                    "    --config F          Bundle system config file `F'\n" +
654                                    "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
655                                    "    --machine-config F  Use the given file as the machine.config for the application.\n" +
656                                    "    --static            Statically link to mono libs\n" +
657                                    "    --nomain            Don't include a main() function, for libraries\n" +
658                                    "    -z                  Compress the assemblies before embedding.\n" +
659                                    "    --skip-scan         Skip scanning assemblies that could not be loaded (but still embed them).\n" +
660                                    "    --static-ctor ctor  Add a constructor call to the supplied function.\n" +
661                                    "                        You need zlib development headers and libraries.\n");
662         }
663
664         [DllImport ("libc")]
665         static extern int system (string s);
666         [DllImport ("libc")]
667         static extern int uname (IntPtr buf);
668                 
669         static void DetectOS ()
670         {
671                 if (!IsUnix) {
672                         Console.WriteLine ("OS is: Windows");
673                         style = "windows";
674                         return;
675                 }
676
677                 IntPtr buf = Marshal.AllocHGlobal (8192);
678                 if (uname (buf) != 0){
679                         Console.WriteLine ("Warning: Unable to detect OS");
680                         Marshal.FreeHGlobal (buf);
681                         return;
682                 }
683                 string os = Marshal.PtrToStringAnsi (buf);
684                 Console.WriteLine ("OS is: " + os);
685                 if (os == "Darwin")
686                         style = "osx";
687                 
688                 Marshal.FreeHGlobal (buf);
689         }
690
691         static bool IsUnix {
692                 get {
693                         int p = (int) Environment.OSVersion.Platform;
694                         return ((p == 4) || (p == 128) || (p == 6));
695                 }
696         }
697
698         static int Execute (string cmdLine)
699         {
700                 if (IsUnix) {
701                         Console.WriteLine (cmdLine);
702                         return system (cmdLine);
703                 }
704                 
705 #if XAMARIN_ANDROID
706                 // on Windows, we have to pipe the output of a
707                 // `cmd` interpolation to dos2unix, because the shell does not
708                 // strip the CRLFs generated by the native pkg-config distributed
709                 // with Mono.
710                 //
711                 // But if it's *not* on cygwin, just skip it.
712                 
713                 // check if dos2unix is applicable.
714                 if (use_dos2unix == null) {
715                         use_dos2unix = false;
716                         try {
717                                 var info = new ProcessStartInfo ("dos2unix");
718                                 info.CreateNoWindow = true;
719                                 info.RedirectStandardInput = true;
720                                 info.UseShellExecute = false;
721                                 var dos2unix = Process.Start (info);
722                                 dos2unix.StandardInput.WriteLine ("aaa");
723                                 dos2unix.StandardInput.WriteLine ("\u0004");
724                                 dos2unix.StandardInput.Close ();
725                                 dos2unix.WaitForExit ();
726                                 if (dos2unix.ExitCode == 0)
727                                         use_dos2unix = true;
728                         } catch {
729                                 // ignore
730                         }
731                 }
732                 // and if there is no dos2unix, just run cmd /c.
733                 if (use_dos2unix == false) {
734 #endif
735                         Console.WriteLine (cmdLine);
736                         ProcessStartInfo dos2unix = new ProcessStartInfo ();
737                         dos2unix.UseShellExecute = false;
738                         dos2unix.FileName = "cmd";
739                         dos2unix.Arguments = String.Format ("/c \"{0}\"", cmdLine);
740
741                         using (Process p = Process.Start (dos2unix)) {
742                                 p.WaitForExit ();
743                                 return p.ExitCode;
744                         }
745 #if XAMARIN_ANDROID
746                 }
747 #endif
748
749                 StringBuilder b = new StringBuilder ();
750                 int count = 0;
751                 for (int i = 0; i < cmdLine.Length; i++) {
752                         if (cmdLine [i] == '`') {
753 #if XAMARIN_ANDROID
754                                 if (count % 2 != 0) {
755                                         b.Append ("|dos2unix");
756                                 }
757 #endif
758                                 count++;
759                         }
760                         b.Append (cmdLine [i]);
761                 }
762                 cmdLine = b.ToString ();
763                 Console.WriteLine (cmdLine);
764                         
765                 ProcessStartInfo psi = new ProcessStartInfo ();
766                 psi.UseShellExecute = false;
767                 psi.FileName = "sh";
768                 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
769
770                 using (Process p = Process.Start (psi)) {
771                         p.WaitForExit ();
772                         return p.ExitCode;
773                 }
774         }
775
776         static string GetEnv (string name, string defaultValue) 
777         {
778                 string s = Environment.GetEnvironmentVariable (name);
779                 return s != null ? s : defaultValue;
780         }
781 }