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