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