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