Merge pull request #901 from Blewzman/FixAggregateExceptionGetBaseException
[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 #if NET_4_5
23 using System.Threading.Tasks;
24 #endif
25
26 class MakeBundle {
27         static string output = "a.out";
28         static string object_out = null;
29         static List<string> link_paths = new List<string> ();
30         static bool autodeps = false;
31         static bool keeptemp = false;
32         static bool compile_only = false;
33         static bool static_link = false;
34         static string config_file = null;
35         static string machine_config_file = null;
36         static string config_dir = null;
37         static string style = "linux";
38         static bool compress;
39         static bool nomain;
40         static bool? use_dos2unix = null;
41         static bool skip_scan;
42         static string ctor_func;
43         
44         static int Main (string [] args)
45         {
46                 List<string> sources = new List<string> ();
47                 int top = args.Length;
48                 link_paths.Add (".");
49
50                 DetectOS ();
51                 
52                 for (int i = 0; i < top; i++){
53                         switch (args [i]){
54                         case "--help": case "-h": case "-?":
55                                 Help ();
56                                 return 1;
57
58                         case "-c":
59                                 compile_only = true;
60                                 break;
61                                 
62                         case "-o": 
63                                 if (i+1 == top){
64                                         Help (); 
65                                         return 1;
66                                 }
67                                 output = args [++i];
68                                 break;
69
70                         case "-oo":
71                                 if (i+1 == top){
72                                         Help (); 
73                                         return 1;
74                                 }
75                                 object_out = args [++i];
76                                 break;
77
78                         case "-L":
79                                 if (i+1 == top){
80                                         Help (); 
81                                         return 1;
82                                 }
83                                 link_paths.Add (args [++i]);
84                                 break;
85
86                         case "--nodeps":
87                                 autodeps = false;
88                                 break;
89
90                         case "--deps":
91                                 autodeps = true;
92                                 break;
93
94                         case "--keeptemp":
95                                 keeptemp = true;
96                                 break;
97                         case "--static":
98                                 static_link = true;
99                                 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
100                                 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
101                                 break;
102                         case "--config":
103                                 if (i+1 == top) {
104                                         Help ();
105                                         return 1;
106                                 }
107
108                                 config_file = args [++i];
109                                 break;
110                         case "--machine-config":
111                                 if (i+1 == top) {
112                                         Help ();
113                                         return 1;
114                                 }
115
116                                 machine_config_file = args [++i];
117
118                                 Console.WriteLine ("WARNING:\n  Check that the machine.config file you are bundling\n  doesn't contain sensitive information specific to this machine.");
119                                 break;
120                         case "--config-dir":
121                                 if (i+1 == top) {
122                                         Help ();
123                                         return 1;
124                                 }
125
126                                 config_dir = args [++i];
127                                 break;
128                         case "-z":
129                                 compress = true;
130                                 break;
131                         case "--nomain":
132                                 nomain = true;
133                                 break;
134                         case "--style":
135                                 if (i+1 == top) {
136                                         Help ();
137                                         return 1;
138                                 }
139                                 style = args [++i];
140                                 switch (style) {
141                                 case "windows":
142                                 case "mac":
143                                 case "linux":
144                                         break;
145                                 default:
146                                         Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
147                                         return 1;
148                                 }
149                                         
150                                 break;
151                         case "--skip-scan":
152                                 skip_scan = true;
153                                 break;
154                         case "--static-ctor":
155                                 if (i+1 == top) {
156                                         Help ();
157                                         return 1;
158                                 }
159                                 ctor_func = args [++i];
160                                 break;
161                         default:
162                                 sources.Add (args [i]);
163                                 break;
164                         }
165                         
166                         if (static_link && style == "windows") {
167                                 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
168                                 return 1;
169                         }
170                 }
171
172                 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
173                 if (sources.Count == 0 || output == null) {
174                         Help ();
175                         Environment.Exit (1);
176                 }
177
178                 List<string> assemblies = LoadAssemblies (sources);
179                 List<string> files = new List<string> ();
180                 foreach (string file in assemblies)
181                         if (!QueueAssembly (files, file))
182                                 return 1;
183                         
184                 GenerateBundles (files);
185                 //GenerateJitWrapper ();
186                 
187                 return 0;
188         }
189
190         static void WriteSymbol (StreamWriter sw, string name, long size)
191         {
192                 switch (style){
193                 case "linux":
194                         sw.WriteLine (
195                                 ".globl {0}\n" +
196                                 "\t.section .rodata\n" +
197                                 "\t.p2align 5\n" +
198                                 "\t.type {0}, \"object\"\n" +
199                                 "\t.size {0}, {1}\n" +
200                                 "{0}:\n",
201                                 name, size);
202                         break;
203                 case "osx":
204                         sw.WriteLine (
205                                 "\t.section __TEXT,__text,regular,pure_instructions\n" + 
206                                 "\t.globl _{0}\n" +
207                                 "\t.data\n" +
208                                 "\t.align 4\n" +
209                                 "_{0}:\n",
210                                 name, size);
211                         break;
212                 case "windows":
213                         sw.WriteLine (
214                                 ".globl _{0}\n" +
215                                 "\t.section .rdata,\"dr\"\n" +
216                                 "\t.align 32\n" +
217                                 "_{0}:\n",
218                                 name, size);
219                         break;
220                 }
221         }
222         
223         static string [] chars = new string [256];
224         
225         static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
226         {
227                 int n;
228                 
229                 // Preallocate the strings we need.
230                 if (chars [0] == null) {
231                         for (int i = 0; i < chars.Length; i++)
232                                 chars [i] = string.Format ("{0}", i.ToString ());
233                 }
234
235                 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
236                         int count = 0;
237                         for (int i = 0; i < n; i++) {
238                                 if (count % 32 == 0) {
239                                         ts.Write ("\n\t.byte ");
240                                 } else {
241                                         ts.Write (",");
242                                 }
243                                 ts.Write (chars [buffer [i]]);
244                                 count ++;
245                         }
246                 }
247
248                 ts.WriteLine ();
249         }
250         
251         static void GenerateBundles (List<string> files)
252         {
253                 string temp_s = "temp.s"; // Path.GetTempFileName ();
254                 string temp_c = "temp.c";
255                 string temp_o = "temp.o";
256
257                 if (compile_only)
258                         temp_c = output;
259                 if (object_out != null)
260                         temp_o = object_out;
261                 
262                 try {
263                         List<string> c_bundle_names = new List<string> ();
264                         List<string[]> config_names = new List<string[]> ();
265
266                         using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
267                         using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
268                         string prog = null;
269
270 #if XAMARIN_ANDROID
271                         tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
272                         tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
273                         tc.WriteLine (@"
274 typedef struct {
275         const char *name;
276         const unsigned char *data;
277         const unsigned int size;
278 } MonoBundledAssembly;
279 void          mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
280 void          mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
281 ");
282 #else
283                         tc.WriteLine ("#include <mono/metadata/mono-config.h>");
284                         tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
285 #endif
286
287                         if (compress) {
288                                 tc.WriteLine ("typedef struct _compressed_data {");
289                                 tc.WriteLine ("\tMonoBundledAssembly assembly;");
290                                 tc.WriteLine ("\tint compressed_size;");
291                                 tc.WriteLine ("} CompressedAssembly;\n");
292                         }
293
294                         object monitor = new object ();
295
296                         var streams = new Dictionary<string, Stream> ();
297                         var sizes = new Dictionary<string, long> ();
298
299                         // Do the file reading and compression in parallel
300                         Action<string> body = delegate (string url) {
301                                 string fname = new Uri (url).LocalPath;
302                                 Stream stream = File.OpenRead (fname);
303
304                                 long real_size = stream.Length;
305                                 int n;
306                                 if (compress) {
307                                         byte[] cbuffer = new byte [8192];
308                                         MemoryStream ms = new MemoryStream ();
309                                         GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
310                                         while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
311                                                 deflate.Write (cbuffer, 0, n);
312                                         }
313                                         stream.Close ();
314                                         deflate.Close ();
315                                         byte [] bytes = ms.GetBuffer ();
316                                         stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
317                                 }
318
319                                 lock (monitor) {
320                                         streams [url] = stream;
321                                         sizes [url] = real_size;
322                                 }
323                         };
324
325                         //#if NET_4_5
326 #if FALSE
327                         Parallel.ForEach (files, body);
328 #else
329                         foreach (var url in files)
330                                 body (url);
331 #endif
332
333                         // The non-parallel part
334                         byte [] buffer = new byte [8192];
335                         foreach (var url in files) {
336                                 string fname = new Uri (url).LocalPath;
337                                 string aname = Path.GetFileName (fname);
338                                 string encoded = aname.Replace ("-", "_").Replace (".", "_");
339
340                                 if (prog == null)
341                                         prog = aname;
342
343                                 var stream = streams [url];
344                                 var real_size = sizes [url];
345
346                                 Console.WriteLine ("   embedding: " + fname);
347
348                                 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
349                         
350                                 WriteBuffer (ts, stream, buffer);
351
352                                 if (compress) {
353                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
354                                         tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
355                                                                   " assembly_data_{0}, {2}}}, {3}}};",
356                                                                   encoded, aname, real_size, stream.Length);
357                                         double ratio = ((double) stream.Length * 100) / real_size;
358                                         Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
359                                 } else {
360                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
361                                         tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
362                                                                   encoded, aname, real_size);
363                                 }
364                                 stream.Close ();
365
366                                 c_bundle_names.Add ("assembly_bundle_" + encoded);
367
368                                 try {
369                                         FileStream cf = File.OpenRead (fname + ".config");
370                                         Console.WriteLine (" config from: " + fname + ".config");
371                                         tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
372                                         WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
373                                         WriteBuffer (ts, cf, buffer);
374                                         ts.WriteLine ();
375                                         config_names.Add (new string[] {aname, encoded});
376                                 } catch (FileNotFoundException) {
377                                         /* we ignore if the config file doesn't exist */
378                                 }
379                         }
380
381                         if (config_file != null){
382                                 FileStream conf;
383                                 try {
384                                         conf = File.OpenRead (config_file);
385                                 } catch {
386                                         Error (String.Format ("Failure to open {0}", config_file));
387                                         return;
388                                 }
389                                 Console.WriteLine ("System config from: " + config_file);
390                                 tc.WriteLine ("extern const char system_config;");
391                                 WriteSymbol (ts, "system_config", config_file.Length);
392
393                                 WriteBuffer (ts, conf, buffer);
394                                 // null terminator
395                                 ts.Write ("\t.byte 0\n");
396                                 ts.WriteLine ();
397                         }
398
399                         if (machine_config_file != null){
400                                 FileStream conf;
401                                 try {
402                                         conf = File.OpenRead (machine_config_file);
403                                 } catch {
404                                         Error (String.Format ("Failure to open {0}", machine_config_file));
405                                         return;
406                                 }
407                                 Console.WriteLine ("Machine config from: " + machine_config_file);
408                                 tc.WriteLine ("extern const char machine_config;");
409                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
410
411                                 WriteBuffer (ts, conf, buffer);
412                                 ts.Write ("\t.byte 0\n");
413                                 ts.WriteLine ();
414                         }
415                         ts.Close ();
416                         
417                         Console.WriteLine ("Compiling:");
418                         string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), 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                 // on Windows, we have to pipe the output of a
708                 // `cmd` interpolation to dos2unix, because the shell does not
709                 // strip the CRLFs generated by the native pkg-config distributed
710                 // with Mono.
711                 //
712                 // But if it's *not* on cygwin, just skip it.
713                 
714                 // check if dos2unix is applicable.
715                 if (use_dos2unix == null) {
716                         use_dos2unix = false;
717                         try {
718                                 var dos2unix = Process.Start ("dos2unix");
719                                 dos2unix.StandardInput.WriteLine ("aaa");
720                                 dos2unix.StandardInput.WriteLine ("\u0004");
721                                 dos2unix.WaitForExit ();
722                                 if (dos2unix.ExitCode == 0)
723                                         use_dos2unix = true;
724                         } catch {
725                                 // ignore
726                         }
727                 }
728                 // and if there is no dos2unix, just run cmd /c.
729                 if (use_dos2unix == false) {
730                         Console.WriteLine (cmdLine);
731                         ProcessStartInfo dos2unix = new ProcessStartInfo ();
732                         dos2unix.UseShellExecute = false;
733                         dos2unix.FileName = "cmd";
734                         dos2unix.Arguments = String.Format ("/c \"{0}\"", cmdLine);
735
736                         using (Process p = Process.Start (dos2unix)) {
737                                 p.WaitForExit ();
738                                 return p.ExitCode;
739                         }
740                 }
741
742                 StringBuilder b = new StringBuilder ();
743                 int count = 0;
744                 for (int i = 0; i < cmdLine.Length; i++) {
745                         if (cmdLine [i] == '`') {
746                                 if (count % 2 != 0) {
747                                         b.Append ("|dos2unix");
748                                 }
749                                 count++;
750                         }
751                         b.Append (cmdLine [i]);
752                 }
753                 cmdLine = b.ToString ();
754                 Console.WriteLine (cmdLine);
755                         
756                 ProcessStartInfo psi = new ProcessStartInfo ();
757                 psi.UseShellExecute = false;
758                 psi.FileName = "sh";
759                 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
760
761                 using (Process p = Process.Start (psi)) {
762                         p.WaitForExit ();
763                         return p.ExitCode;
764                 }
765         }
766
767         static string GetEnv (string name, string defaultValue) 
768         {
769                 string s = Environment.GetEnvironmentVariable (name);
770                 return s != null ? s : defaultValue;
771         }
772 }