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