[mkbundle] Add support for generating monodroid compatible mkbundle code at runtime...
[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 // TODO:
7 //   [x] Rename the paths for the zip file that is downloaded
8 //   [x] Update documentation with new flag
9 //   [x] Load internationalized assemblies
10 //   [x] Dependencies - if System.dll -> include Mono.Security.* (not needed, automatic)
11 //   [x] --list-targets should download from a different url
12 //   [x] --fetch-target should unpack zip file
13 //   [x] Update --cross to use not a runtime, but an SDK
14 //   [x] Update --local-targets to show the downloaded SDKs
15 //
16 // Author:
17 //   Miguel de Icaza
18 //
19 // (C) Novell, Inc 2004
20 // (C) 2016 Xamarin Inc
21 //
22 // Missing features:
23 // * Add support for packaging native libraries, extracting at runtime and setting the library path.
24 // * Implement --list-targets lists all the available remote targets
25 //
26 using System;
27 using System.Diagnostics;
28 using System.Xml;
29 using System.Collections.Generic;
30 using System.IO;
31 using System.IO.Compression;
32 using System.Runtime.InteropServices;
33 using System.Text;
34 using IKVM.Reflection;
35 using System.Linq;
36 using System.Net;
37 using System.Threading.Tasks;
38
39 class MakeBundle {
40         static string output = "a.out";
41         static string object_out = null;
42         static List<string> link_paths = new List<string> ();
43         static Dictionary<string,string> libraries = new Dictionary<string,string> ();
44         static bool autodeps = false;
45         static bool keeptemp = false;
46         static bool compile_only = false;
47         static bool static_link = false;
48         static string config_file = null;
49         static string machine_config_file = null;
50         static string config_dir = null;
51         static string style = "linux";
52         static bool bundled_header = false;
53         static string os_message = "";
54         static bool compress;
55         static bool nomain;
56         static string custom_main = null;
57         static bool? use_dos2unix = null;
58         static bool skip_scan;
59         static string ctor_func;
60         static bool quiet = true;
61         static string cross_target = null;
62         static string fetch_target = null;
63         static bool custom_mode = true;
64         static string embedded_options = null;
65         static string runtime = null;
66         static string sdk_path = null;
67         static string lib_path = null;
68         static Dictionary<string,string> environment = new Dictionary<string,string>();
69         static string [] i18n = new string [] {
70                 "West",
71                 ""
72         };
73         static string [] i18n_all = new string [] {
74                 "CJK", 
75                 "MidEast",
76                 "Other",
77                 "Rare",
78                 "West",
79                 ""
80         };
81         static string target_server = "https://download.mono-project.com/runtimes/raw/";
82         
83         static int Main (string [] args)
84         {
85                 List<string> sources = new List<string> ();
86                 int top = args.Length;
87                 link_paths.Add (".");
88
89                 DetectOS ();
90
91                 for (int i = 0; i < top; i++){
92                         switch (args [i]){
93                         case "--help": case "-h": case "-?":
94                                 Help ();
95                                 return 1;
96
97                         case "--simple":
98                                 custom_mode = false;
99                                 autodeps = true;
100                                 break;
101
102                         case "-v":
103                                 quiet = false;
104                                 break;
105                                 
106                         case "--i18n":
107                                 if (i+1 == top){
108                                         Help ();
109                                         return 1;
110                                 }
111                                 var iarg = args [++i];
112                                 if (iarg == "all")
113                                         i18n = i18n_all;
114                                 else if (iarg == "none")
115                                         i18n = new string [0];
116                                 else
117                                         i18n = iarg.Split (',');
118                                 break;
119                                 
120                         case "--custom":
121                                 custom_mode = true;
122                                 break;
123                                 
124                         case "-c":
125                                 compile_only = true;
126                                 break;
127
128                         case "--local-targets":
129                                 CommandLocalTargets ();
130                                 return 0;
131
132                         case "--cross":
133                                 if (i+1 == top){
134                                         Help (); 
135                                         return 1;
136                                 }
137                                 if (sdk_path != null || runtime != null)
138                                         Error ("You can not specify one of --runtime, --sdk or --cross");
139                                 custom_mode = false;
140                                 autodeps = true;
141                                 cross_target = args [++i];
142                                 break;
143
144                         case "--library":
145                                 if (i+1 == top){
146                                         Help (); 
147                                         return 1;
148                                 }
149                                 if (custom_mode){
150                                         Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
151                                         Help ();
152                                         return 1;
153                                 }
154                                 var lspec = args [++i];
155                                 var p = lspec.IndexOf (",");
156                                 string alias, path;
157                                 if (p == -1){
158                                         alias = Path.GetFileName (lspec);
159                                         path = lspec;
160                                 } else {
161                                         alias = lspec.Substring (0, p);
162                                         path = lspec.Substring (p+1);
163                                 }
164                                 if (!File.Exists (path))
165                                         Error ($"The specified library file {path} does not exist");
166                                 libraries [alias] = path;
167                                 break;
168
169                         case "--fetch-target":
170                                 if (i+1 == top){
171                                         Help (); 
172                                         return 1;
173                                 }
174                                 fetch_target = args [++i];
175                                 break;
176
177                         case "--list-targets":
178                                 CommandLocalTargets ();
179                                 var wc = new WebClient ();
180                                 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
181                                 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
182                                 return 0;
183                                 
184                         case "--target-server":
185                                 if (i+1 == top){
186                                         Help (); 
187                                         return 1;
188                                 }
189                                 target_server = args [++i];
190                                 break;
191
192                         case "-o": 
193                                 if (i+1 == top){
194                                         Help (); 
195                                         return 1;
196                                 }
197                                 output = args [++i];
198                                 break;
199
200                         case "--options":
201                                 if (i+1 == top){
202                                         Help (); 
203                                         return 1;
204                                 }
205                                 embedded_options = args [++i];
206                                 break;
207                         case "--sdk":
208                                 if (i + 1 == top) {
209                                         Help ();
210                                         return 1;
211                                 }
212                                 custom_mode = false;
213                                 autodeps = true;
214                                 sdk_path = args [++i];
215                                 if (cross_target != null || runtime != null)
216                                         Error ("You can not specify one of --runtime, --sdk or --cross");
217                                 break;
218                         case "--runtime":
219                                 if (i+1 == top){
220                                         Help (); 
221                                         return 1;
222                                 }
223                                 if (sdk_path != null || cross_target != null)
224                                         Error ("You can only specify one of --runtime, --sdk or --cross");
225                                 custom_mode = false;
226                                 autodeps = true;
227                                 runtime = args [++i];
228                                 break;
229                         case "-oo":
230                                 if (i+1 == top){
231                                         Help (); 
232                                         return 1;
233                                 }
234                                 object_out = args [++i];
235                                 break;
236
237                         case "-L":
238                                 if (i+1 == top){
239                                         Help (); 
240                                         return 1;
241                                 }
242                                 link_paths.Add (args [++i]);
243                                 break;
244
245                         case "--nodeps":
246                                 autodeps = false;
247                                 break;
248
249                         case "--deps":
250                                 autodeps = true;
251                                 break;
252
253                         case "--keeptemp":
254                                 keeptemp = true;
255                                 break;
256                                 
257                         case "--static":
258                                 static_link = true;
259                                 break;
260                         case "--config":
261                                 if (i+1 == top) {
262                                         Help ();
263                                         return 1;
264                                 }
265
266                                 config_file = args [++i];
267                                 break;
268                         case "--machine-config":
269                                 if (i+1 == top) {
270                                         Help ();
271                                         return 1;
272                                 }
273
274                                 machine_config_file = args [++i];
275
276                                 if (!quiet)
277                                         Console.WriteLine ("WARNING:\n  Check that the machine.config file you are bundling\n  doesn't contain sensitive information specific to this machine.");
278                                 break;
279                         case "--config-dir":
280                                 if (i+1 == top) {
281                                         Help ();
282                                         return 1;
283                                 }
284
285                                 config_dir = args [++i];
286                                 break;
287                         case "-z":
288                                 compress = true;
289                                 break;
290                         case "--nomain":
291                                 nomain = true;
292                                 break;
293                         case "--custom-main":
294                                 if (i+1 == top) {
295                                         Help ();
296                                         return 1;
297                                 }
298                                 custom_main = args [++i];
299                                 break;
300                         case "--style":
301                                 if (i+1 == top) {
302                                         Help ();
303                                         return 1;
304                                 }
305                                 style = args [++i];
306                                 switch (style) {
307                                 case "windows":
308                                 case "mac":
309                                 case "linux":
310                                         break;
311                                 default:
312                                         Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
313                                         return 1;
314                                 }
315                                         
316                                 break;
317                         case "--skip-scan":
318                                 skip_scan = true;
319                                 break;
320                         case "--static-ctor":
321                                 if (i+1 == top) {
322                                         Help ();
323                                         return 1;
324                                 }
325                                 ctor_func = args [++i];
326                                 break;
327                         case "--dos2unix":
328                         case "--dos2unix=true":
329                                 use_dos2unix = true;
330                                 break;
331                         case "--dos2unix=false":
332                                 use_dos2unix = false;
333                                 break;
334                         case "-q":
335                         case "--quiet":
336                                 quiet = true;
337                                 break;
338                         case "-e":
339                         case "--env":
340                                 if (i+1 == top) {
341                                         Help ();
342                                         return 1;
343                                 }
344                                 var env = args [++i];
345                                 p = env.IndexOf ('=');
346                                 if (p == -1)
347                                         environment.Add (env, "");
348                                 else
349                                         environment.Add (env.Substring (0, p), env.Substring (p+1));
350                                 break;
351                         case "--bundled-header":
352                                 bundled_header = true;
353                                 break;
354                         default:
355                                 sources.Add (args [i]);
356                                 break;
357                         }
358
359                 }
360                 // Modern bundling starts here
361                 if (!custom_mode){
362                         if (runtime != null){
363                                 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
364                         } else if (sdk_path != null) {
365                                 VerifySdk (sdk_path);
366                         } else if (cross_target == "default" || cross_target == null){
367                                 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
368                                 VerifySdk (sdk_path);
369                         } else {
370                                 sdk_path = Path.Combine (targets_dir, cross_target);
371                                 Console.WriteLine ("From: " + sdk_path);
372                                 VerifySdk (sdk_path);
373                         }
374                 }
375
376                 if (fetch_target != null){
377                         var directory = Path.Combine (targets_dir, fetch_target);
378                         var zip_download = Path.Combine (directory, "sdk.zip");
379                         Directory.CreateDirectory (directory);
380                         var wc = new WebClient ();
381                         var uri = new Uri ($"{target_server}{fetch_target}");
382                         try {
383                                 if (!quiet){
384                                         Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
385                                 }
386                                 
387                                 wc.DownloadFile (uri, zip_download);
388                                 ZipFile.ExtractToDirectory(zip_download, directory);
389                                 File.Delete (zip_download);
390                         } catch {
391                                 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
392                                 File.Delete (zip_download);
393                                 return 1;
394                         }
395                         return 0;
396                 }
397                 
398                 if (!quiet) {
399                         Console.WriteLine (os_message);
400                         Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
401                 }
402
403                 if (sources.Count == 0 || output == null) {
404                         Help ();
405                         Environment.Exit (1);
406                 }
407
408                 List<string> assemblies = LoadAssemblies (sources);
409                 LoadLocalizedAssemblies (assemblies);
410                 List<string> files = new List<string> ();
411                 foreach (string file in assemblies)
412                         if (!QueueAssembly (files, file))
413                                 return 1;
414                 if (custom_mode)
415                         GenerateBundles (files);
416                 else 
417                         GeneratePackage (files);
418
419                 Console.WriteLine ("Generated {0}", output);
420
421                 return 0;
422         }
423
424         static void VerifySdk (string path)
425         {
426                 if (!Directory.Exists (path))
427                         Error ($"The specified SDK path does not exist: {path}");
428                 runtime = Path.Combine (sdk_path, "bin", "mono");
429                 if (!File.Exists (runtime))
430                         Error ($"The SDK location does not contain a {path}/bin/mono runtime");
431                 lib_path = Path.Combine (path, "lib", "mono", "4.5");
432                 if (!Directory.Exists (lib_path))
433                         Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
434                 link_paths.Add (lib_path);
435         }
436
437         static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
438         
439         static void CommandLocalTargets ()
440         {
441                 string [] targets;
442
443                 Console.WriteLine ("Available targets locally:");
444                 Console.WriteLine ("\tdefault\t- Current System Mono");
445                 try {
446                         targets = Directory.GetDirectories (targets_dir);
447                 } catch {
448                         return;
449                 }
450                 foreach (var target in targets){
451                         var p = Path.Combine (target, "bin", "mono");
452                         if (File.Exists (p))
453                                 Console.WriteLine ("\t{0}", Path.GetFileName (target));
454                 }
455         }
456
457         static void WriteSymbol (StreamWriter sw, string name, long size)
458         {
459                 switch (style){
460                 case "linux":
461                         sw.WriteLine (
462                                 ".globl {0}\n" +
463                                 "\t.section .rodata\n" +
464                                 "\t.p2align 5\n" +
465                                 "\t.type {0}, \"object\"\n" +
466                                 "\t.size {0}, {1}\n" +
467                                 "{0}:\n",
468                                 name, size);
469                         break;
470                 case "osx":
471                         sw.WriteLine (
472                                 "\t.section __TEXT,__text,regular,pure_instructions\n" + 
473                                 "\t.globl _{0}\n" +
474                                 "\t.data\n" +
475                                 "\t.align 4\n" +
476                                 "_{0}:\n",
477                                 name, size);
478                         break;
479                 case "windows":
480                         sw.WriteLine (
481                                 ".globl _{0}\n" +
482                                 "\t.section .rdata,\"dr\"\n" +
483                                 "\t.align 32\n" +
484                                 "_{0}:\n",
485                                 name, size);
486                         break;
487                 }
488         }
489         
490         static string [] chars = new string [256];
491         
492         static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
493         {
494                 int n;
495                 
496                 // Preallocate the strings we need.
497                 if (chars [0] == null) {
498                         for (int i = 0; i < chars.Length; i++)
499                                 chars [i] = string.Format ("{0}", i.ToString ());
500                 }
501
502                 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
503                         int count = 0;
504                         for (int i = 0; i < n; i++) {
505                                 if (count % 32 == 0) {
506                                         ts.Write ("\n\t.byte ");
507                                 } else {
508                                         ts.Write (",");
509                                 }
510                                 ts.Write (chars [buffer [i]]);
511                                 count ++;
512                         }
513                 }
514
515                 ts.WriteLine ();
516         }
517
518         class PackageMaker {
519                 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
520                 const int align = 4096;
521                 Stream package;
522                 
523                 public PackageMaker (string output)
524                 {
525                         package = File.Create (output, 128*1024);
526                         if (IsUnix){
527                                 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
528                         }
529                 }
530
531                 public int AddFile (string fname)
532                 {
533                         using (Stream fileStream = File.OpenRead (fname)){
534                                 var ret = fileStream.Length;
535
536                                 if (!quiet)
537                                         Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
538                                 fileStream.CopyTo (package);
539                                 package.Position = package.Position + (align - (package.Position % align));
540
541                                 return (int) ret;
542                         }
543                 }
544                 
545                 public void Add (string entry, string fname)
546                 {
547                         var p = package.Position;
548                         var size = AddFile (fname);
549                         
550                         locations [entry] = Tuple.Create(p, size);
551                 }
552
553                 public void AddString (string entry, string text)
554                 {
555                         var bytes = Encoding.UTF8.GetBytes (text);
556                         locations [entry] = Tuple.Create (package.Position, bytes.Length);
557                         package.Write (bytes, 0, bytes.Length);
558                         package.Position = package.Position + (align - (package.Position % align));
559                 }
560
561                 public void AddStringPair (string entry, string key, string value)
562                 {
563                         var kbytes = Encoding.UTF8.GetBytes (key);
564                         var vbytes = Encoding.UTF8.GetBytes (value);
565
566                         Console.WriteLine ("ADDING {0} to {1}", key, value);
567                         if (kbytes.Length > 255){
568                                 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
569                                 Environment.Exit (1);
570                         }
571                                 
572                         locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
573                         package.WriteByte ((byte)kbytes.Length);
574                         package.Write (kbytes, 0, kbytes.Length);
575                         package.WriteByte (0);
576                         package.Write (vbytes, 0, vbytes.Length);
577                         package.WriteByte (0);
578                         package.Position = package.Position + (align - (package.Position % align));
579                 }
580
581                 public void Dump ()
582                 {
583                         if (quiet)
584                                 return;
585                         foreach (var floc in locations.Keys){
586                                 Console.WriteLine ($"{floc} at {locations[floc]:x}");
587                         }
588                 }
589
590                 public void WriteIndex ()
591                 {
592                         var indexStart = package.Position;
593                         var binary = new BinaryWriter (package);
594
595                         binary.Write (locations.Count);
596                         foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
597                                 var bytes = Encoding.UTF8.GetBytes (entry.Key);
598                                 binary.Write (bytes.Length+1);
599                                 binary.Write (bytes);
600                                 binary.Write ((byte) 0);
601                                 binary.Write (entry.Value.Item1);
602                                 binary.Write (entry.Value.Item2);
603                         }
604                         binary.Write (indexStart);
605                         binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
606                         binary.Flush ();
607                 }
608                 
609                 public void Close ()
610                 {
611                         WriteIndex ();
612                         package.Close ();
613                         package = null;
614                 }
615         }
616
617         static bool MaybeAddFile (PackageMaker maker, string code, string file)
618         {
619                 if (file == null)
620                         return true;
621                 
622                 if (!File.Exists (file)){
623                         Error ("The file {0} does not exist", file);
624                         return false;
625                 }
626                 maker.Add (code, file);
627                 return true;
628         }
629         
630         static bool GeneratePackage (List<string> files)
631         {
632                 if (runtime == null){
633                         if (IsUnix)
634                                 runtime = Process.GetCurrentProcess().MainModule.FileName;
635                         else {
636                                 Error ("You must specify at least one runtime with --runtime or --cross");
637                                 Environment.Exit (1);
638                         }
639                 }
640                 if (!File.Exists (runtime)){
641                         Error ($"The specified runtime at {runtime} does not exist");
642                         Environment.Exit (1);
643                 }
644                 
645                 if (ctor_func != null){
646                         Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
647                         return false;
648                 }
649                 
650                 var maker = new PackageMaker (output);
651                 Console.WriteLine ("Using runtime: " + runtime);
652                 maker.AddFile (runtime);
653                 
654                 foreach (var url in files){
655                         string fname = LocateFile (new Uri (url).LocalPath);
656                         string aname = MakeBundle.GetAssemblyName (fname);
657
658                         maker.Add ("assembly:" + aname, fname);
659                         Console.WriteLine ("     Assembly: " + fname);
660                         if (File.Exists (fname + ".config")){
661                                 maker.Add ("config:" + aname, fname + ".config");
662                                 Console.WriteLine ("       Config: " + runtime);
663                         }
664                 }
665                 
666                 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
667                         return false;
668
669                 if (config_dir != null)
670                         maker.Add ("config_dir:", config_dir);
671                 if (embedded_options != null)
672                         maker.AddString ("options:", embedded_options);
673                 if (environment.Count > 0){
674                         foreach (var key in environment.Keys)
675                                 maker.AddStringPair ("env:" + key, key, environment [key]);
676                 }
677                 if (libraries.Count > 0){
678                         foreach (var alias_and_path in libraries){
679                                 Console.WriteLine ("     Library:  " + alias_and_path.Value);
680                                 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
681                         }
682                 }
683                 maker.Dump ();
684                 maker.Close ();
685                 return true;
686         }
687         
688         static void GenerateBundles (List<string> files)
689         {
690                 string temp_s = "temp.s"; // Path.GetTempFileName ();
691                 string temp_c = "temp.c";
692                 string temp_o = "temp.o";
693
694                 if (compile_only)
695                         temp_c = output;
696                 if (object_out != null)
697                         temp_o = object_out;
698                 
699                 try {
700                         List<string> c_bundle_names = new List<string> ();
701                         List<string[]> config_names = new List<string[]> ();
702
703                         using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
704                         using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
705                         string prog = null;
706
707                         if (bundled_header) {
708                                 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
709                                 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
710                                 tc.WriteLine (@"
711 typedef struct {
712         const char *name;
713         const unsigned char *data;
714         const unsigned int size;
715 } MonoBundledAssembly;
716 void          mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
717 void          mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
718 ");
719                         } else {
720                                 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
721                                 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
722                         }
723
724                         if (compress) {
725                                 tc.WriteLine ("typedef struct _compressed_data {");
726                                 tc.WriteLine ("\tMonoBundledAssembly assembly;");
727                                 tc.WriteLine ("\tint compressed_size;");
728                                 tc.WriteLine ("} CompressedAssembly;\n");
729                         }
730
731                         object monitor = new object ();
732
733                         var streams = new Dictionary<string, Stream> ();
734                         var sizes = new Dictionary<string, long> ();
735
736                         // Do the file reading and compression in parallel
737                         Action<string> body = delegate (string url) {
738                                 string fname = LocateFile (new Uri (url).LocalPath);
739                                 Stream stream = File.OpenRead (fname);
740
741                                 long real_size = stream.Length;
742                                 int n;
743                                 if (compress) {
744                                         byte[] cbuffer = new byte [8192];
745                                         MemoryStream ms = new MemoryStream ();
746                                         GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
747                                         while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
748                                                 deflate.Write (cbuffer, 0, n);
749                                         }
750                                         stream.Close ();
751                                         deflate.Close ();
752                                         byte [] bytes = ms.GetBuffer ();
753                                         stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
754                                 }
755
756                                 lock (monitor) {
757                                         streams [url] = stream;
758                                         sizes [url] = real_size;
759                                 }
760                         };
761
762                         //#if NET_4_5
763 #if FALSE
764                         Parallel.ForEach (files, body);
765 #else
766                         foreach (var url in files)
767                                 body (url);
768 #endif
769
770                         // The non-parallel part
771                         byte [] buffer = new byte [8192];
772                         // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
773                         var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
774                         foreach (var url in files) {
775                                 string fname = LocateFile (new Uri (url).LocalPath);
776                                 string aname = MakeBundle.GetAssemblyName (fname);
777                                 string encoded = symbolEscapeRE.Replace (aname, "_");
778
779                                 if (prog == null)
780                                         prog = aname;
781
782                                 var stream = streams [url];
783                                 var real_size = sizes [url];
784
785                                 if (!quiet)
786                                         Console.WriteLine ("   embedding: " + fname);
787
788                                 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
789                         
790                                 WriteBuffer (ts, stream, buffer);
791
792                                 if (compress) {
793                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
794                                         tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
795                                                                   " assembly_data_{0}, {2}}}, {3}}};",
796                                                                   encoded, aname, real_size, stream.Length);
797                                         if (!quiet) {
798                                                 double ratio = ((double) stream.Length * 100) / real_size;
799                                                 Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
800                                         }
801                                 } else {
802                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
803                                         tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
804                                                                   encoded, aname, real_size);
805                                 }
806                                 stream.Close ();
807
808                                 c_bundle_names.Add ("assembly_bundle_" + encoded);
809
810                                 try {
811                                         FileStream cf = File.OpenRead (fname + ".config");
812                                         if (!quiet)
813                                                 Console.WriteLine (" config from: " + fname + ".config");
814                                         tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
815                                         WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
816                                         WriteBuffer (ts, cf, buffer);
817                                         ts.WriteLine ();
818                                         config_names.Add (new string[] {aname, encoded});
819                                 } catch (FileNotFoundException) {
820                                         /* we ignore if the config file doesn't exist */
821                                 }
822                         }
823
824                         if (config_file != null){
825                                 FileStream conf;
826                                 try {
827                                         conf = File.OpenRead (config_file);
828                                 } catch {
829                                         Error ("Failure to open {0}", config_file);
830                                         return;
831                                 }
832                                 if (!quiet)
833                                         Console.WriteLine ("System config from: " + config_file);
834                                 tc.WriteLine ("extern const char system_config;");
835                                 WriteSymbol (ts, "system_config", config_file.Length);
836
837                                 WriteBuffer (ts, conf, buffer);
838                                 // null terminator
839                                 ts.Write ("\t.byte 0\n");
840                                 ts.WriteLine ();
841                         }
842
843                         if (machine_config_file != null){
844                                 FileStream conf;
845                                 try {
846                                         conf = File.OpenRead (machine_config_file);
847                                 } catch {
848                                         Error ("Failure to open {0}", machine_config_file);
849                                         return;
850                                 }
851                                 if (!quiet)
852                                         Console.WriteLine ("Machine config from: " + machine_config_file);
853                                 tc.WriteLine ("extern const char machine_config;");
854                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
855
856                                 WriteBuffer (ts, conf, buffer);
857                                 ts.Write ("\t.byte 0\n");
858                                 ts.WriteLine ();
859                         }
860                         ts.Close ();
861
862                         if (compress)
863                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
864                         else
865                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
866
867                         foreach (string c in c_bundle_names){
868                                 tc.WriteLine ("\t&{0},", c);
869                         }
870                         tc.WriteLine ("\tNULL\n};\n");
871                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
872
873                         if (ctor_func != null) {
874                                 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
875                                 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
876                                 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
877                         }
878
879                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
880                         foreach (string[] ass in config_names){
881                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
882                         }
883                         if (config_file != null)
884                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
885                         if (machine_config_file != null)
886                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
887                         tc.WriteLine ("}\n");
888
889                         if (config_dir != null)
890                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
891                         else
892                                 tc.WriteLine ("static const char *config_dir = NULL;");
893
894                         Stream template_stream;
895                         if (compress) {
896                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
897                         } else {
898                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
899                         }
900
901                         StreamReader s = new StreamReader (template_stream);
902                         string template = s.ReadToEnd ();
903                         tc.Write (template);
904
905                         if (!nomain && custom_main == null) {
906                                 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
907                                 StreamReader st = new StreamReader (template_main_stream);
908                                 string maintemplate = st.ReadToEnd ();
909                                 tc.Write (maintemplate);
910                         }
911
912                         tc.Close ();
913
914                         string assembler = GetEnv("AS", "as");
915                         string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
916                         Execute(as_cmd);
917
918                         if (compile_only)
919                                 return;
920
921                         if (!quiet)
922                                 Console.WriteLine("Compiling:");
923
924                         if (style == "windows")
925                         {
926
927                                 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
928
929                                 string compiler = GetEnv("CC", "cl.exe");
930                                 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
931                                 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
932                                 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
933
934                                 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
935                                 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
936                                 var linkLibraries = new string[] {  "kernel32.lib",
937                                                                                                 "version.lib",
938                                                                                                 "Ws2_32.lib",
939                                                                                                 "Mswsock.lib",
940                                                                                                 "Psapi.lib",
941                                                                                                 "shell32.lib",
942                                                                                                 "OleAut32.lib",
943                                                                                                 "ole32.lib",
944                                                                                                 "winmm.lib",
945                                                                                                 "user32.lib",
946                                                                                                 "libvcruntime.lib",
947                                                                                                 "advapi32.lib",
948                                                                                                 "OLDNAMES.lib",
949                                                                                                 "libucrt.lib" };
950
951                                 string glue_obj = "mkbundle_glue.obj";
952                                 string monoLib;
953
954                                 if (static_link)
955                                         monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
956
957                                 else {
958                                         Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
959                                         monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
960                                         LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
961                                 }
962
963                                 var compilerArgs = new List<string>();
964                                 compilerArgs.Add("/MT");
965
966                                 foreach (string include in includes)
967                                         compilerArgs.Add(String.Format ("/I {0}", quote (include)));
968
969                                 if (!nomain || custom_main != null) {
970                                         compilerArgs.Add(quote(temp_c));
971                                         compilerArgs.Add(quote(temp_o));
972                                         if (custom_main != null)
973                                                 compilerArgs.Add(quote(custom_main));
974                                         compilerArgs.Add(quote(monoLib));
975                                         compilerArgs.Add("/link");
976                                         compilerArgs.Add("/NODEFAULTLIB");
977                                         compilerArgs.Add("/SUBSYSTEM:windows");
978                                         compilerArgs.Add("/ENTRY:mainCRTStartup");
979                                         compilerArgs.AddRange(linkLibraries);
980                                         compilerArgs.Add("/out:"+ output);
981
982                                         string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
983                                         Execute (cl_cmd);
984                                 }
985                                 else
986                                 {
987                                         // we are just creating a .lib
988                                         compilerArgs.Add("/c"); // compile only
989                                         compilerArgs.Add(temp_c);
990                                         compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
991
992                                         string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
993                                         Execute (cl_cmd);
994
995                                         string librarian = GetEnv ("LIB", "lib.exe");
996                                         var librarianArgs = new List<string> ();
997                                         librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
998                                         librarianArgs.Add (temp_o);
999                                         librarianArgs.Add (glue_obj);
1000                                         librarianArgs.Add (monoLib);
1001                                         string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1002                                         Execute (lib_cmd);
1003                                 }
1004                         }
1005                         else
1006                         {
1007                                 string zlib = (compress ? "-lz" : "");
1008                                 string debugging = "-g";
1009                                 string cc = GetEnv("CC", "cc");
1010                                 string cmd = null;
1011
1012                                 if (style == "linux")
1013                                         debugging = "-ggdb";
1014                                 if (static_link)
1015                                 {
1016                                         string smonolib;
1017                                         if (style == "osx")
1018                                                 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1019                                         else
1020                                                 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1021                                         cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
1022                                                 "`pkg-config --libs-only-L mono-2` " + smonolib +
1023                                                 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
1024                                                 temp_c, temp_o, output, zlib, cc);
1025                                 }
1026                                 else
1027                                 {
1028
1029                                         cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1030                                                 temp_c, temp_o, output, zlib, cc);
1031                                 }
1032                                 Execute (cmd);
1033                         }
1034
1035                         if (!quiet)
1036                                 Console.WriteLine ("Done");
1037                 }
1038         }
1039                 } finally {
1040                         if (!keeptemp){
1041                                 if (object_out == null){
1042                                         File.Delete (temp_o);
1043                                 }
1044                                 if (!compile_only){
1045                                         File.Delete (temp_c);
1046                                 }
1047                                 File.Delete (temp_s);
1048                         }
1049                 }
1050         }
1051         
1052         static List<string> LoadAssemblies (List<string> sources)
1053         {
1054                 List<string> assemblies = new List<string> ();
1055                 bool error = false;
1056
1057                 foreach (string name in sources){
1058                         try {
1059                                 Assembly a = LoadAssemblyFile (name);
1060
1061                                 if (a == null){
1062                                         error = true;
1063                                         continue;
1064                                 }
1065                         
1066                                 assemblies.Add (a.CodeBase);
1067                         } catch (Exception) {
1068                                 if (skip_scan) {
1069                                         if (!quiet)
1070                                                 Console.WriteLine ("File will not be scanned: {0}", name);
1071                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1072                                 } else {
1073                                         throw;
1074                                 }
1075                         }
1076                 }
1077
1078                 if (error) {
1079                         Error ("Couldn't load one or more of the assemblies.");
1080                         Environment.Exit (1);
1081                 }
1082
1083                 return assemblies;
1084         }
1085
1086         static void LoadLocalizedAssemblies (List<string> assemblies)
1087         {
1088                 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1089                 string error = null;
1090
1091                 foreach (string name in other) {
1092                         try {
1093                                 Assembly a = LoadAssembly (name);
1094
1095                                 if (a == null) {
1096                                         error = "Failed to load " + name;
1097                                         continue;
1098                                 }
1099
1100                                 assemblies.Add (a.CodeBase);
1101                         } catch (Exception) {
1102                                 if (skip_scan) {
1103                                         if (!quiet)
1104                                                 Console.WriteLine ("File will not be scanned: {0}", name);
1105                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1106                                 } else {
1107                                         throw;
1108                                 }
1109                         }
1110                 }
1111
1112                 if (error != null) {
1113                         Error ("Couldn't load one or more of the i18n assemblies: " + error);
1114                         Environment.Exit (1);
1115                 }
1116         }
1117
1118         
1119         static readonly Universe universe = new Universe ();
1120         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1121         static readonly string resourcePathSeparator = (Path.DirectorySeparatorChar == '\\') ? $"\\{Path.DirectorySeparatorChar}" : $"{Path.DirectorySeparatorChar}";
1122
1123         public static string GetAssemblyName (string path)
1124         {
1125                 string name = Path.GetFileName (path);
1126
1127                 // A bit of a hack to support satellite assemblies. They all share the same name but
1128                 // are placed in subdirectories named after the locale they implement. Also, all of
1129                 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1130                 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1131                         string dir = Path.GetDirectoryName (path);
1132                         int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1133                         if (idx >= 0) {
1134                                 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1135                                 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1136                         } else if (!quiet)
1137                                 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1138                 }
1139
1140                 return name;
1141         }
1142
1143         static bool QueueAssembly (List<string> files, string codebase)
1144         {
1145                 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1146                 if (files.Contains (codebase))
1147                         return true;
1148
1149                 var path = new Uri(codebase).LocalPath;
1150                 var name = GetAssemblyName (path);
1151                 string found;
1152                 if (loaded_assemblies.TryGetValue (name, out found)) {
1153                         Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1154                         return false;
1155                 }
1156
1157                 loaded_assemblies.Add (name, path);
1158
1159                 files.Add (codebase);
1160                 if (!autodeps)
1161                         return true;
1162                 try {
1163                         Assembly a = universe.LoadFile (path);
1164
1165                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1166                                 a = LoadAssembly (an.Name);
1167                                 if (!QueueAssembly (files, a.CodeBase))
1168                                         return false;
1169                         }
1170                 } catch (Exception) {
1171                         if (!skip_scan)
1172                                 throw;
1173                 }
1174
1175                 return true;
1176         }
1177
1178         //
1179         // Loads an assembly from a specific path
1180         //
1181         static Assembly LoadAssemblyFile (string assembly)
1182         {
1183                 Assembly a = null;
1184                 
1185                 try {
1186                         a = universe.LoadFile (assembly);
1187                 } catch (FileNotFoundException){
1188                         Error ($"Cannot find assembly `{assembly}'");
1189                 } catch (IKVM.Reflection.BadImageFormatException f) {
1190                         if (skip_scan)
1191                                 throw;
1192                         Error ($"Cannot load assembly (bad file format) " + f.Message);
1193                 } catch (FileLoadException f){
1194                         Error ($"Cannot load assembly " + f.Message);
1195                 } catch (ArgumentNullException){
1196                         Error( $"Cannot load assembly (null argument)");
1197                 }
1198                 return a;
1199         }
1200
1201         //
1202         // Loads an assembly from any of the link directories provided
1203         //
1204         static Assembly LoadAssembly (string assembly)
1205         {
1206                 string total_log = "";
1207                 foreach (string dir in link_paths){
1208                         string full_path = Path.Combine (dir, assembly);
1209                         if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1210                                 full_path += ".dll";
1211                         
1212                         try {
1213                                 var a = universe.LoadFile (full_path);
1214                                 return a;
1215                         } catch (FileNotFoundException ff) {
1216                                 total_log += ff.FusionLog;
1217                                 continue;
1218                         }
1219                 }
1220                 if (!quiet)
1221                         Console.WriteLine ("Log: \n" + total_log);
1222                 return null;
1223         }
1224         
1225         static void Error (string msg, params object [] args)
1226         {
1227                 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1228                 Environment.Exit (1);
1229         }
1230
1231         static void Help ()
1232         {
1233                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1234                                    "Options:\n" +
1235                                    "    --config F           Bundle system config file `F'\n" +
1236                                    "    --config-dir D       Set MONO_CFG_DIR to `D'\n" +
1237                                    "    --deps               Turns on automatic dependency embedding (default on simple)\n" +
1238                                    "    -L path              Adds `path' to the search path for assemblies\n" +
1239                                    "    --machine-config F   Use the given file as the machine.config for the application.\n" +
1240                                    "    -o out               Specifies output filename\n" +
1241                                    "    --nodeps             Turns off automatic dependency embedding (default on custom)\n" +
1242                                    "    --skip-scan          Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1243                                    "    --i18n ENCODING      none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1244                                    "    -v                   Verbose output\n" + 
1245                                    "    --bundled-header     Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1246                                    "\n" + 
1247                                    "--simple   Simple mode does not require a C toolchain and can cross compile\n" + 
1248                                    "    --cross TARGET       Generates a binary for the given TARGET\n"+
1249                                    "    --env KEY=VALUE      Hardcodes an environment variable for the target\n" +
1250                                    "    --fetch-target NAME  Downloads the target SDK from the remote server\n" + 
1251                                    "    --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1252                                    "                         LIB is optional shortname for file located at PATH\n" + 
1253                                    "    --list-targets       Lists available targets on the remote server\n" +
1254                                    "    --local-targets      Lists locally available targets\n" +
1255                                    "    --options OPTIONS    Embed the specified Mono command line options on target\n" +
1256                                    "    --runtime RUNTIME    Manually specifies the Mono runtime to use\n" +
1257                                    "    --sdk PATH           Use a Mono SDK root location instead of a target\n" + 
1258                                    "    --target-server URL  Specified a server to download targets from, default is " + target_server + "\n" +
1259                                    "\n" +
1260                                    "--custom   Builds a custom launcher, options for --custom\n" +
1261                                    "    -c                   Produce stub only, do not compile\n" +
1262                                    "    -oo obj              Specifies output filename for helper object file\n" +
1263                                    "    --dos2unix[=true|false]\n" +
1264                                    "                         When no value provided, or when `true` specified\n" +
1265                                    "                         `dos2unix` will be invoked to convert paths on Windows.\n" +
1266                                    "                         When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1267                                    "    --keeptemp           Keeps the temporary files\n" +
1268                                    "    --static             Statically link to mono libs\n" +
1269                                    "    --nomain             Don't include a main() function, for libraries\n" +
1270                                    "    --custom-main C      Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1271                                    "    -z                   Compress the assemblies before embedding.\n" +
1272                                    "    --static-ctor ctor   Add a constructor call to the supplied function.\n" +
1273                                    "                         You need zlib development headers and libraries.\n");
1274         }
1275
1276         [DllImport ("libc")]
1277         static extern int system (string s);
1278         [DllImport ("libc")]
1279         static extern int uname (IntPtr buf);
1280                 
1281         static void DetectOS ()
1282         {
1283                 if (!IsUnix) {
1284                         os_message = "OS is: Windows";
1285                         style = "windows";
1286                         return;
1287                 }
1288
1289                 IntPtr buf = Marshal.AllocHGlobal (8192);
1290                 if (uname (buf) != 0){
1291                         os_message = "Warning: Unable to detect OS";
1292                         Marshal.FreeHGlobal (buf);
1293                         return;
1294                 }
1295                 string os = Marshal.PtrToStringAnsi (buf);
1296                 os_message = "OS is: " + os;
1297                 if (os == "Darwin")
1298                         style = "osx";
1299                 
1300                 Marshal.FreeHGlobal (buf);
1301         }
1302
1303         static bool IsUnix {
1304                 get {
1305                         int p = (int) Environment.OSVersion.Platform;
1306                         return ((p == 4) || (p == 128) || (p == 6));
1307                 }
1308         }
1309
1310         static void Execute (string cmdLine)
1311         {
1312                 if (IsUnix) {
1313                         if (!quiet)
1314                                 Console.WriteLine ("[execute cmd]: " + cmdLine);
1315                         int ret = system (cmdLine);
1316                         if (ret != 0)
1317                         {
1318                                 Error(String.Format("[Fail] {0}", ret));
1319                         }
1320                         return;
1321                 }
1322
1323                 // on Windows, we have to pipe the output of a
1324                 // `cmd` interpolation to dos2unix, because the shell does not
1325                 // strip the CRLFs generated by the native pkg-config distributed
1326                 // with Mono.
1327                 //
1328                 // But if it's *not* on cygwin, just skip it.
1329
1330                 // check if dos2unix is applicable.
1331                 if (use_dos2unix == true)
1332                         try {
1333                         var info = new ProcessStartInfo ("dos2unix");
1334                         info.CreateNoWindow = true;
1335                         info.RedirectStandardInput = true;
1336                         info.UseShellExecute = false;
1337                         var dos2unix = Process.Start (info);
1338                         dos2unix.StandardInput.WriteLine ("aaa");
1339                         dos2unix.StandardInput.WriteLine ("\u0004");
1340                         dos2unix.StandardInput.Close ();
1341                         dos2unix.WaitForExit ();
1342                         if (dos2unix.ExitCode == 0)
1343                                 use_dos2unix = true;
1344                 } catch {
1345                         Console.WriteLine("Warning: dos2unix not found");
1346                         use_dos2unix = false;
1347                 }
1348
1349                 if (use_dos2unix == null)
1350                         use_dos2unix = false;
1351
1352                 ProcessStartInfo psi = new ProcessStartInfo();
1353                 psi.UseShellExecute = false;
1354
1355                 // if there is no dos2unix, just run cmd /c.
1356                 if (use_dos2unix == false)
1357                 {
1358                         psi.FileName = "cmd";
1359                         psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1360                 }
1361                 else
1362                 {
1363                         psi.FileName = "sh";
1364                         StringBuilder b = new StringBuilder();
1365                         int count = 0;
1366                         for (int i = 0; i < cmdLine.Length; i++)
1367                         {
1368                                 if (cmdLine[i] == '`')
1369                                 {
1370                                         if (count % 2 != 0)
1371                                         {
1372                                                 b.Append("|dos2unix");
1373                                         }
1374                                         count++;
1375                                 }
1376                                 b.Append(cmdLine[i]);
1377                         }
1378                         cmdLine = b.ToString();
1379                         psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1380                 }
1381
1382                 if (!quiet)
1383                         Console.WriteLine(cmdLine);
1384                 using (Process p = Process.Start (psi)) {
1385                         p.WaitForExit ();
1386                         int ret = p.ExitCode;
1387                         if (ret != 0){
1388                                 Error ("[Fail] {0}", ret);
1389                         }
1390                 }
1391         }
1392
1393         static string GetEnv(string name, string defaultValue)
1394         {
1395                 string val = Environment.GetEnvironmentVariable(name);
1396                 if (val != null)
1397                 {
1398                         if (!quiet)
1399                                 Console.WriteLine("{0} = {1}", name, val);
1400                 }
1401                 else
1402                 {
1403                         val = defaultValue;
1404                         if (!quiet)
1405                                 Console.WriteLine("{0} = {1} (default)", name, val);
1406                 }
1407                 return val;
1408         }
1409
1410         static string LocateFile(string default_path)
1411         {
1412                 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1413                 if (File.Exists(override_path))
1414                         return override_path;
1415                 else if (File.Exists(default_path))
1416                         return default_path;
1417                 else
1418                         throw new FileNotFoundException(default_path);
1419         }
1420 }