Merge pull request #1659 from alexanderkyte/stringbuilder-referencesource
[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                         string assembler = GetEnv ("AS", IsUnix ? "as" : "i686-pc-mingw32-as");
416                         
417                         Console.WriteLine ("Compiling:");
418                         string cmd = String.Format ("{0} -o {1} {2} ", assembler, temp_o, temp_s);
419                         int ret = Execute (cmd);
420                         if (ret != 0){
421                                 Error ("[Fail]");
422                                 return;
423                         }
424
425                         if (compress)
426                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
427                         else
428                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
429
430                         foreach (string c in c_bundle_names){
431                                 tc.WriteLine ("\t&{0},", c);
432                         }
433                         tc.WriteLine ("\tNULL\n};\n");
434                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
435
436                         if (ctor_func != null) {
437                                 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
438                                 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
439                                 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
440                         }
441
442                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
443                         foreach (string[] ass in config_names){
444                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
445                         }
446                         if (config_file != null)
447                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
448                         if (machine_config_file != null)
449                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
450                         tc.WriteLine ("}\n");
451
452                         if (config_dir != null)
453                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
454                         else
455                                 tc.WriteLine ("static const char *config_dir = NULL;");
456
457                         Stream template_stream;
458                         if (compress) {
459                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
460                         } else {
461                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
462                         }
463
464                         StreamReader s = new StreamReader (template_stream);
465                         string template = s.ReadToEnd ();
466                         tc.Write (template);
467
468                         if (!nomain) {
469                                 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
470                                 StreamReader st = new StreamReader (template_main_stream);
471                                 string maintemplate = st.ReadToEnd ();
472                                 tc.Write (maintemplate);
473                         }
474                         
475                         tc.Close ();
476
477                         if (compile_only)
478                                 return;
479
480                         string zlib = (compress ? "-lz" : "");
481                         string debugging = "-g";
482                         string cc = GetEnv ("CC", IsUnix ? "cc" : "i686-pc-mingw32-gcc");
483
484                         if (style == "linux")
485                                 debugging = "-ggdb";
486                         if (static_link) {
487                                 string smonolib;
488                                 if (style == "osx")
489                                         smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
490                                 else
491                                         smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
492                                 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
493                                                      "`pkg-config --libs-only-L mono-2` " + smonolib +
494                                                      "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
495                                                      temp_c, temp_o, output, zlib, cc);
496                         } else {
497                                 
498                                 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
499                                                      temp_c, temp_o, output, zlib, cc);
500                         }
501                             
502                         ret = Execute (cmd);
503                         if (ret != 0){
504                                 Error ("[Fail]");
505                                 return;
506                         }
507                         Console.WriteLine ("Done");
508                         }
509                         }
510                 } finally {
511                         if (!keeptemp){
512                                 if (object_out == null){
513                                         File.Delete (temp_o);
514                                 }
515                                 if (!compile_only){
516                                         File.Delete (temp_c);
517                                 }
518                                 File.Delete (temp_s);
519                         }
520                 }
521         }
522         
523         static List<string> LoadAssemblies (List<string> sources)
524         {
525                 List<string> assemblies = new List<string> ();
526                 bool error = false;
527                 
528                 foreach (string name in sources){
529                         try {
530                                 Assembly a = LoadAssembly (name);
531
532                                 if (a == null){
533                                         error = true;
534                                         continue;
535                                 }
536                         
537                                 assemblies.Add (a.CodeBase);
538                         } catch (Exception e) {
539                                 if (skip_scan) {
540                                         Console.WriteLine ("File will not be scanned: {0}", name);
541                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
542                                 } else {
543                                         throw;
544                                 }
545                         }
546                 }
547
548                 if (error)
549                         Environment.Exit (1);
550
551                 return assemblies;
552         }
553         
554         static readonly Universe universe = new Universe ();
555         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
556         
557         static bool QueueAssembly (List<string> files, string codebase)
558         {
559                 // Console.WriteLine ("CODE BASE IS {0}", codebase);
560                 if (files.Contains (codebase))
561                         return true;
562
563                 var path = new Uri(codebase).LocalPath;
564                 var name = Path.GetFileName (path);
565                 string found;
566                 if (loaded_assemblies.TryGetValue (name, out found)) {
567                         Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
568                         return false;
569                 }
570
571                 loaded_assemblies.Add (name, path);
572
573                 files.Add (codebase);
574                 if (!autodeps)
575                         return true;
576                 try {
577                         Assembly a = universe.LoadFile (path);
578
579                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
580                                 a = universe.Load (an.FullName);
581                                 if (!QueueAssembly (files, a.CodeBase))
582                                         return false;
583                         }
584                 } catch (Exception e) {
585                         if (!skip_scan)
586                                 throw;
587                 }
588
589                 return true;
590         }
591
592         static Assembly LoadAssembly (string assembly)
593         {
594                 Assembly a;
595                 
596                 try {
597                         char[] path_chars = { '/', '\\' };
598                         
599                         if (assembly.IndexOfAny (path_chars) != -1) {
600                                 a = universe.LoadFile (assembly);
601                         } else {
602                                 string ass = assembly;
603                                 if (ass.EndsWith (".dll"))
604                                         ass = assembly.Substring (0, assembly.Length - 4);
605                                 a = universe.Load (ass);
606                         }
607                         return a;
608                 } catch (FileNotFoundException){
609                         string total_log = "";
610                         
611                         foreach (string dir in link_paths){
612                                 string full_path = Path.Combine (dir, assembly);
613                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
614                                         full_path += ".dll";
615                                 
616                                 try {
617                                         a = universe.LoadFile (full_path);
618                                         return a;
619                                 } catch (FileNotFoundException ff) {
620                                         total_log += ff.FusionLog;
621                                         continue;
622                                 }
623                         }
624                         Error ("Cannot find assembly `" + assembly + "'" );
625                         Console.WriteLine ("Log: \n" + total_log);
626                 } catch (IKVM.Reflection.BadImageFormatException f) {
627                         if (skip_scan)
628                                 throw;
629                         Error ("Cannot load assembly (bad file format) " + f.Message);
630                 } catch (FileLoadException f){
631                         Error ("Cannot load assembly " + f.Message);
632                 } catch (ArgumentNullException){
633                         Error("Cannot load assembly (null argument)");
634                 }
635                 return null;
636         }
637
638         static void Error (string msg)
639         {
640                 Console.Error.WriteLine ("ERROR: " + msg);
641                 Environment.Exit (1);
642         }
643
644         static void Help ()
645         {
646                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
647                                    "Options:\n" +
648                                    "    -c                  Produce stub only, do not compile\n" +
649                                    "    -o out              Specifies output filename\n" +
650                                    "    -oo obj             Specifies output filename for helper object file\n" +
651                                    "    -L path             Adds `path' to the search path for assemblies\n" +
652                                    "    --nodeps            Turns off automatic dependency embedding (default)\n" +
653                                    "    --deps              Turns on automatic dependency embedding\n" +
654                                    "    --keeptemp          Keeps the temporary files\n" +
655                                    "    --config F          Bundle system config file `F'\n" +
656                                    "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
657                                    "    --machine-config F  Use the given file as the machine.config for the application.\n" +
658                                    "    --static            Statically link to mono libs\n" +
659                                    "    --nomain            Don't include a main() function, for libraries\n" +
660                                    "    -z                  Compress the assemblies before embedding.\n" +
661                                    "    --skip-scan         Skip scanning assemblies that could not be loaded (but still embed them).\n" +
662                                    "    --static-ctor ctor  Add a constructor call to the supplied function.\n" +
663                                    "                        You need zlib development headers and libraries.\n");
664         }
665
666         [DllImport ("libc")]
667         static extern int system (string s);
668         [DllImport ("libc")]
669         static extern int uname (IntPtr buf);
670                 
671         static void DetectOS ()
672         {
673                 if (!IsUnix) {
674                         Console.WriteLine ("OS is: Windows");
675                         style = "windows";
676                         return;
677                 }
678
679                 IntPtr buf = Marshal.AllocHGlobal (8192);
680                 if (uname (buf) != 0){
681                         Console.WriteLine ("Warning: Unable to detect OS");
682                         Marshal.FreeHGlobal (buf);
683                         return;
684                 }
685                 string os = Marshal.PtrToStringAnsi (buf);
686                 Console.WriteLine ("OS is: " + os);
687                 if (os == "Darwin")
688                         style = "osx";
689                 
690                 Marshal.FreeHGlobal (buf);
691         }
692
693         static bool IsUnix {
694                 get {
695                         int p = (int) Environment.OSVersion.Platform;
696                         return ((p == 4) || (p == 128) || (p == 6));
697                 }
698         }
699
700         static int Execute (string cmdLine)
701         {
702                 if (IsUnix) {
703                         Console.WriteLine (cmdLine);
704                         return system (cmdLine);
705                 }
706                 
707 #if XAMARIN_ANDROID
708                 // on Windows, we have to pipe the output of a
709                 // `cmd` interpolation to dos2unix, because the shell does not
710                 // strip the CRLFs generated by the native pkg-config distributed
711                 // with Mono.
712                 //
713                 // But if it's *not* on cygwin, just skip it.
714                 
715                 // check if dos2unix is applicable.
716                 if (use_dos2unix == null) {
717                         use_dos2unix = false;
718                         try {
719                                 var info = new ProcessStartInfo ("dos2unix");
720                                 info.CreateNoWindow = true;
721                                 info.RedirectStandardInput = true;
722                                 info.UseShellExecute = false;
723                                 var dos2unix = Process.Start (info);
724                                 dos2unix.StandardInput.WriteLine ("aaa");
725                                 dos2unix.StandardInput.WriteLine ("\u0004");
726                                 dos2unix.StandardInput.Close ();
727                                 dos2unix.WaitForExit ();
728                                 if (dos2unix.ExitCode == 0)
729                                         use_dos2unix = true;
730                         } catch {
731                                 // ignore
732                         }
733                 }
734                 // and if there is no dos2unix, just run cmd /c.
735                 if (use_dos2unix == false) {
736 #endif
737                         Console.WriteLine (cmdLine);
738                         ProcessStartInfo dos2unix = new ProcessStartInfo ();
739                         dos2unix.UseShellExecute = false;
740                         dos2unix.FileName = "cmd";
741                         dos2unix.Arguments = String.Format ("/c \"{0}\"", cmdLine);
742
743                         using (Process p = Process.Start (dos2unix)) {
744                                 p.WaitForExit ();
745                                 return p.ExitCode;
746                         }
747 #if XAMARIN_ANDROID
748                 }
749 #endif
750
751                 StringBuilder b = new StringBuilder ();
752                 int count = 0;
753                 for (int i = 0; i < cmdLine.Length; i++) {
754                         if (cmdLine [i] == '`') {
755 #if XAMARIN_ANDROID
756                                 if (count % 2 != 0) {
757                                         b.Append ("|dos2unix");
758                                 }
759 #endif
760                                 count++;
761                         }
762                         b.Append (cmdLine [i]);
763                 }
764                 cmdLine = b.ToString ();
765                 Console.WriteLine (cmdLine);
766                         
767                 ProcessStartInfo psi = new ProcessStartInfo ();
768                 psi.UseShellExecute = false;
769                 psi.FileName = "sh";
770                 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
771
772                 using (Process p = Process.Start (psi)) {
773                         p.WaitForExit ();
774                         return p.ExitCode;
775                 }
776         }
777
778         static string GetEnv (string name, string defaultValue) 
779         {
780                 string s = Environment.GetEnvironmentVariable (name);
781                 return s != null ? s : defaultValue;
782         }
783 }