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