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