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