8603736b26bb75cbbb90176beb7240c386a5df01
[mono.git] / mcs / tools / mkbundle / mkbundle.cs
1 //
2 // mkbundle: tool to create bundles.
3 //
4 // Based on the `make-bundle' Perl script written by Paolo Molaro (lupus@debian.org)
5 //
6 // TODO:
7 //   [x] Rename the paths for the zip file that is downloaded
8 //   [x] Update documentation with new flag
9 //   [x] Load internationalized assemblies
10 //   [x] Dependencies - if System.dll -> include Mono.Security.* (not needed, automatic)
11 //   [x] --list-targets should download from a different url
12 //   [x] --fetch-target should unpack zip file
13 //   [x] Update --cross to use not a runtime, but an SDK
14 //   [x] Update --local-targets to show the downloaded SDKs
15 //
16 // Author:
17 //   Miguel de Icaza
18 //
19 // (C) Novell, Inc 2004
20 // (C) 2016 Xamarin Inc
21 //
22 // Missing features:
23 // * Add support for packaging native libraries, extracting at runtime and setting the library path.
24 // * Implement --list-targets lists all the available remote targets
25 //
26 using System;
27 using System.Diagnostics;
28 using System.Xml;
29 using System.Collections.Generic;
30 using System.IO;
31 using System.IO.Compression;
32 using System.Runtime.InteropServices;
33 using System.Text;
34 using IKVM.Reflection;
35 using System.Linq;
36 using System.Net;
37 using System.Threading.Tasks;
38
39 class MakeBundle {
40         static string output = "a.out";
41         static string object_out = null;
42         static List<string> link_paths = new List<string> ();
43         static Dictionary<string,string> libraries = new Dictionary<string,string> ();
44         static bool autodeps = false;
45         static bool keeptemp = false;
46         static bool compile_only = false;
47         static bool static_link = false;
48         static string config_file = null;
49         static string machine_config_file = null;
50         static string config_dir = null;
51         static string style = "linux";
52         static bool bundled_header = false;
53         static string os_message = "";
54         static bool compress;
55         static bool nomain;
56         static string custom_main = null;
57         static bool? use_dos2unix = null;
58         static bool skip_scan;
59         static string ctor_func;
60         static bool quiet = true;
61         static string cross_target = null;
62         static string fetch_target = null;
63         static bool custom_mode = true;
64         static string embedded_options = null;
65         static string runtime = null;
66         static string sdk_path = null;
67         static string lib_path = null;
68         static Dictionary<string,string> environment = new Dictionary<string,string>();
69         static string [] i18n = new string [] {
70                 "West",
71                 ""
72         };
73         static string [] i18n_all = new string [] {
74                 "CJK", 
75                 "MidEast",
76                 "Other",
77                 "Rare",
78                 "West",
79                 ""
80         };
81         static string target_server = "https://download.mono-project.com/runtimes/raw/";
82         
83         static int Main (string [] args)
84         {
85                 List<string> sources = new List<string> ();
86                 int top = args.Length;
87                 link_paths.Add (".");
88
89                 DetectOS ();
90
91                 for (int i = 0; i < top; i++){
92                         switch (args [i]){
93                         case "--help": case "-h": case "-?":
94                                 Help ();
95                                 return 1;
96
97                         case "--simple":
98                                 custom_mode = false;
99                                 autodeps = true;
100                                 break;
101
102                         case "-v":
103                                 quiet = false;
104                                 break;
105                                 
106                         case "--i18n":
107                                 if (i+1 == top){
108                                         Help ();
109                                         return 1;
110                                 }
111                                 var iarg = args [++i];
112                                 if (iarg == "all")
113                                         i18n = i18n_all;
114                                 else if (iarg == "none")
115                                         i18n = new string [0];
116                                 else
117                                         i18n = iarg.Split (',');
118                                 break;
119                                 
120                         case "--custom":
121                                 custom_mode = true;
122                                 break;
123                                 
124                         case "-c":
125                                 compile_only = true;
126                                 break;
127
128                         case "--local-targets":
129                                 CommandLocalTargets ();
130                                 return 0;
131
132                         case "--cross":
133                                 if (i+1 == top){
134                                         Help (); 
135                                         return 1;
136                                 }
137                                 if (sdk_path != null || runtime != null)
138                                         Error ("You can only specify one of --runtime, --sdk or --cross");
139                                 custom_mode = false;
140                                 autodeps = true;
141                                 cross_target = args [++i];
142                                 break;
143
144                         case "--library":
145                                 if (i+1 == top){
146                                         Help (); 
147                                         return 1;
148                                 }
149                                 if (custom_mode){
150                                         Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
151                                         Help ();
152                                         return 1;
153                                 }
154                                 var lspec = args [++i];
155                                 var p = lspec.IndexOf (",");
156                                 string alias, path;
157                                 if (p == -1){
158                                         alias = Path.GetFileName (lspec);
159                                         path = lspec;
160                                 } else {
161                                         alias = lspec.Substring (0, p);
162                                         path = lspec.Substring (p+1);
163                                 }
164                                 if (!File.Exists (path))
165                                         Error ($"The specified library file {path} does not exist");
166                                 libraries [alias] = path;
167                                 break;
168
169                         case "--fetch-target":
170                                 if (i+1 == top){
171                                         Help (); 
172                                         return 1;
173                                 }
174                                 fetch_target = args [++i];
175                                 break;
176
177                         case "--list-targets":
178                                 CommandLocalTargets ();
179                                 var wc = new WebClient ();
180                                 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
181                                 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
182                                 return 0;
183                                 
184                         case "--target-server":
185                                 if (i+1 == top){
186                                         Help (); 
187                                         return 1;
188                                 }
189                                 target_server = args [++i];
190                                 break;
191
192                         case "-o": 
193                                 if (i+1 == top){
194                                         Help (); 
195                                         return 1;
196                                 }
197                                 output = args [++i];
198                                 break;
199
200                         case "--options":
201                                 if (i+1 == top){
202                                         Help (); 
203                                         return 1;
204                                 }
205                                 embedded_options = args [++i];
206                                 break;
207                         case "--sdk":
208                                 if (i + 1 == top) {
209                                         Help ();
210                                         return 1;
211                                 }
212                                 custom_mode = false;
213                                 autodeps = true;
214                                 sdk_path = args [++i];
215                                 if (cross_target != null || runtime != null)
216                                         Error ("You can only specify one of --runtime, --sdk or --cross");
217                                 break;
218                         case "--runtime":
219                                 if (i+1 == top){
220                                         Help (); 
221                                         return 1;
222                                 }
223                                 if (sdk_path != null || cross_target != null)
224                                         Error ("You can only specify one of --runtime, --sdk or --cross");
225                                 custom_mode = false;
226                                 autodeps = true;
227                                 runtime = args [++i];
228                                 break;
229                         case "-oo":
230                                 if (i+1 == top){
231                                         Help (); 
232                                         return 1;
233                                 }
234                                 object_out = args [++i];
235                                 break;
236
237                         case "-L":
238                                 if (i+1 == top){
239                                         Help (); 
240                                         return 1;
241                                 }
242                                 link_paths.Add (args [++i]);
243                                 break;
244
245                         case "--nodeps":
246                                 autodeps = false;
247                                 break;
248
249                         case "--deps":
250                                 autodeps = true;
251                                 break;
252
253                         case "--keeptemp":
254                                 keeptemp = true;
255                                 break;
256                                 
257                         case "--static":
258                                 static_link = true;
259                                 break;
260                         case "--config":
261                                 if (i+1 == top) {
262                                         Help ();
263                                         return 1;
264                                 }
265
266                                 config_file = args [++i];
267                                 break;
268                         case "--machine-config":
269                                 if (i+1 == top) {
270                                         Help ();
271                                         return 1;
272                                 }
273
274                                 machine_config_file = args [++i];
275
276                                 if (!quiet)
277                                         Console.WriteLine ("WARNING:\n  Check that the machine.config file you are bundling\n  doesn't contain sensitive information specific to this machine.");
278                                 break;
279                         case "--config-dir":
280                                 if (i+1 == top) {
281                                         Help ();
282                                         return 1;
283                                 }
284
285                                 config_dir = args [++i];
286                                 break;
287                         case "-z":
288                                 compress = true;
289                                 break;
290                         case "--nomain":
291                                 nomain = true;
292                                 break;
293                         case "--custom-main":
294                                 if (i+1 == top) {
295                                         Help ();
296                                         return 1;
297                                 }
298                                 custom_main = args [++i];
299                                 break;
300                         case "--style":
301                                 if (i+1 == top) {
302                                         Help ();
303                                         return 1;
304                                 }
305                                 style = args [++i];
306                                 switch (style) {
307                                 case "windows":
308                                 case "mac":
309                                 case "linux":
310                                         break;
311                                 default:
312                                         Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
313                                         return 1;
314                                 }
315                                         
316                                 break;
317                         case "--skip-scan":
318                                 skip_scan = true;
319                                 break;
320                         case "--static-ctor":
321                                 if (i+1 == top) {
322                                         Help ();
323                                         return 1;
324                                 }
325                                 ctor_func = args [++i];
326                                 break;
327                         case "--dos2unix":
328                         case "--dos2unix=true":
329                                 use_dos2unix = true;
330                                 break;
331                         case "--dos2unix=false":
332                                 use_dos2unix = false;
333                                 break;
334                         case "-q":
335                         case "--quiet":
336                                 quiet = true;
337                                 break;
338                         case "-e":
339                         case "--env":
340                                 if (i+1 == top) {
341                                         Help ();
342                                         return 1;
343                                 }
344                                 var env = args [++i];
345                                 p = env.IndexOf ('=');
346                                 if (p == -1)
347                                         environment.Add (env, "");
348                                 else
349                                         environment.Add (env.Substring (0, p), env.Substring (p+1));
350                                 break;
351                         case "--bundled-header":
352                                 bundled_header = true;
353                                 break;
354                         default:
355                                 sources.Add (args [i]);
356                                 break;
357                         }
358
359                 }
360                 // Modern bundling starts here
361                 if (!custom_mode){
362                         if (runtime != null){
363                                 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
364                         } else if (sdk_path != null) {
365                                 VerifySdk (sdk_path);
366                         } else if (cross_target == "default" || cross_target == null){
367                                 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
368                                 VerifySdk (sdk_path);
369                         } else {
370                                 sdk_path = Path.Combine (targets_dir, cross_target);
371                                 Console.WriteLine ("From: " + sdk_path);
372                                 VerifySdk (sdk_path);
373                         }
374                 }
375
376                 if (fetch_target != null){
377                         var directory = Path.Combine (targets_dir, fetch_target);
378                         var zip_download = Path.Combine (directory, "sdk.zip");
379                         Directory.CreateDirectory (directory);
380                         var wc = new WebClient ();
381                         var uri = new Uri ($"{target_server}{fetch_target}");
382                         try {
383                                 if (!quiet){
384                                         Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
385                                 }
386                                 
387                                 wc.DownloadFile (uri, zip_download);
388                                 ZipFile.ExtractToDirectory(zip_download, directory);
389                                 File.Delete (zip_download);
390                         } catch {
391                                 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
392                                 File.Delete (zip_download);
393                                 return 1;
394                         }
395                         return 0;
396                 }
397                 
398                 if (!quiet) {
399                         Console.WriteLine (os_message);
400                         Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
401                 }
402
403                 if (sources.Count == 0 || output == null) {
404                         Help ();
405                         Environment.Exit (1);
406                 }
407
408                 List<string> assemblies = LoadAssemblies (sources);
409                 LoadLocalizedAssemblies (assemblies);
410                 List<string> files = new List<string> ();
411                 foreach (string file in assemblies)
412                         if (!QueueAssembly (files, file))
413                                 return 1;
414                 if (custom_mode)
415                         GenerateBundles (files);
416                 else 
417                         GeneratePackage (files);
418
419                 Console.WriteLine ("Generated {0}", output);
420
421                 return 0;
422         }
423
424         static void VerifySdk (string path)
425         {
426                 if (!Directory.Exists (path))
427                         Error ($"The specified SDK path does not exist: {path}");
428                 runtime = Path.Combine (sdk_path, "bin", "mono");
429                 if (!File.Exists (runtime))
430                         Error ($"The SDK location does not contain a {path}/bin/mono runtime");
431                 lib_path = Path.Combine (path, "lib", "mono", "4.5");
432                 if (!Directory.Exists (lib_path))
433                         Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
434                 link_paths.Add (lib_path);
435         }
436
437         static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
438         
439         static void CommandLocalTargets ()
440         {
441                 string [] targets;
442
443                 Console.WriteLine ("Available targets locally:");
444                 Console.WriteLine ("\tdefault\t- Current System Mono");
445                 try {
446                         targets = Directory.GetDirectories (targets_dir);
447                 } catch {
448                         return;
449                 }
450                 foreach (var target in targets){
451                         var p = Path.Combine (target, "bin", "mono");
452                         if (File.Exists (p))
453                                 Console.WriteLine ("\t{0}", Path.GetFileName (target));
454                 }
455         }
456
457         static void WriteSymbol (StreamWriter sw, string name, long size)
458         {
459                 switch (style){
460                 case "linux":
461                         sw.WriteLine (
462                                 ".globl {0}\n" +
463                                 "\t.section .rodata\n" +
464                                 "\t.p2align 5\n" +
465                                 "\t.type {0}, \"object\"\n" +
466                                 "\t.size {0}, {1}\n" +
467                                 "{0}:\n",
468                                 name, size);
469                         break;
470                 case "osx":
471                         sw.WriteLine (
472                                 "\t.section __TEXT,__text,regular,pure_instructions\n" + 
473                                 "\t.globl _{0}\n" +
474                                 "\t.data\n" +
475                                 "\t.align 4\n" +
476                                 "_{0}:\n",
477                                 name, size);
478                         break;
479                 case "windows":
480                         string mangled_symbol_name = "";
481                         if (Target64BitApplication())
482                                 mangled_symbol_name = name;
483                         else
484                                 mangled_symbol_name = "_" + name;
485
486                         sw.WriteLine (
487                                 ".globl {0}\n" +
488                                 "\t.section .rdata,\"dr\"\n" +
489                                 "\t.align 32\n" +
490                                 "{0}:\n",
491                                 mangled_symbol_name);
492                         break;
493                 }
494         }
495         
496         static string [] chars = new string [256];
497         
498         static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
499         {
500                 int n;
501                 
502                 // Preallocate the strings we need.
503                 if (chars [0] == null) {
504                         for (int i = 0; i < chars.Length; i++)
505                                 chars [i] = string.Format ("{0}", i.ToString ());
506                 }
507
508                 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
509                         int count = 0;
510                         for (int i = 0; i < n; i++) {
511                                 if (count % 32 == 0) {
512                                         ts.Write ("\n\t.byte ");
513                                 } else {
514                                         ts.Write (",");
515                                 }
516                                 ts.Write (chars [buffer [i]]);
517                                 count ++;
518                         }
519                 }
520
521                 ts.WriteLine ();
522         }
523
524         class PackageMaker {
525                 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
526                 const int align = 4096;
527                 Stream package;
528                 
529                 public PackageMaker (string output)
530                 {
531                         package = File.Create (output, 128*1024);
532                         if (IsUnix){
533                                 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
534                         }
535                 }
536
537                 public int AddFile (string fname)
538                 {
539                         using (Stream fileStream = File.OpenRead (fname)){
540                                 var ret = fileStream.Length;
541
542                                 if (!quiet)
543                                         Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
544                                 fileStream.CopyTo (package);
545                                 package.Position = package.Position + (align - (package.Position % align));
546
547                                 return (int) ret;
548                         }
549                 }
550                 
551                 public void Add (string entry, string fname)
552                 {
553                         var p = package.Position;
554                         var size = AddFile (fname);
555                         
556                         locations [entry] = Tuple.Create(p, size);
557                 }
558
559                 public void AddString (string entry, string text)
560                 {
561                         var bytes = Encoding.UTF8.GetBytes (text);
562                         locations [entry] = Tuple.Create (package.Position, bytes.Length);
563                         package.Write (bytes, 0, bytes.Length);
564                         package.Position = package.Position + (align - (package.Position % align));
565                 }
566
567                 public void AddStringPair (string entry, string key, string value)
568                 {
569                         var kbytes = Encoding.UTF8.GetBytes (key);
570                         var vbytes = Encoding.UTF8.GetBytes (value);
571
572                         Console.WriteLine ("ADDING {0} to {1}", key, value);
573                         if (kbytes.Length > 255){
574                                 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
575                                 Environment.Exit (1);
576                         }
577                                 
578                         locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
579                         package.WriteByte ((byte)kbytes.Length);
580                         package.Write (kbytes, 0, kbytes.Length);
581                         package.WriteByte (0);
582                         package.Write (vbytes, 0, vbytes.Length);
583                         package.WriteByte (0);
584                         package.Position = package.Position + (align - (package.Position % align));
585                 }
586
587                 public void Dump ()
588                 {
589                         if (quiet)
590                                 return;
591                         foreach (var floc in locations.Keys){
592                                 Console.WriteLine ($"{floc} at {locations[floc]:x}");
593                         }
594                 }
595
596                 public void WriteIndex ()
597                 {
598                         var indexStart = package.Position;
599                         var binary = new BinaryWriter (package);
600
601                         binary.Write (locations.Count);
602                         foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
603                                 var bytes = Encoding.UTF8.GetBytes (entry.Key);
604                                 binary.Write (bytes.Length+1);
605                                 binary.Write (bytes);
606                                 binary.Write ((byte) 0);
607                                 binary.Write (entry.Value.Item1);
608                                 binary.Write (entry.Value.Item2);
609                         }
610                         binary.Write (indexStart);
611                         binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
612                         binary.Flush ();
613                 }
614                 
615                 public void Close ()
616                 {
617                         WriteIndex ();
618                         package.Close ();
619                         package = null;
620                 }
621         }
622
623         static bool MaybeAddFile (PackageMaker maker, string code, string file)
624         {
625                 if (file == null)
626                         return true;
627                 
628                 if (!File.Exists (file)){
629                         Error ("The file {0} does not exist", file);
630                         return false;
631                 }
632                 maker.Add (code, file);
633                 // add a space after code (="systemconfig:" or "machineconfig:")
634                 Console.WriteLine (code + " " + file);
635                 return true;
636         }
637         
638         static bool GeneratePackage (List<string> files)
639         {
640                 if (runtime == null){
641                         if (IsUnix)
642                                 runtime = Process.GetCurrentProcess().MainModule.FileName;
643                         else {
644                                 Error ("You must specify at least one runtime with --runtime or --cross");
645                                 Environment.Exit (1);
646                         }
647                 }
648                 if (!File.Exists (runtime)){
649                         Error ($"The specified runtime at {runtime} does not exist");
650                         Environment.Exit (1);
651                 }
652                 
653                 if (ctor_func != null){
654                         Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
655                         return false;
656                 }
657                 
658                 var maker = new PackageMaker (output);
659                 Console.WriteLine ("Using runtime: " + runtime);
660                 maker.AddFile (runtime);
661                 
662                 foreach (var url in files){
663                         string fname = LocateFile (new Uri (url).LocalPath);
664                         string aname = MakeBundle.GetAssemblyName (fname);
665
666                         maker.Add ("assembly:" + aname, fname);
667                         Console.WriteLine ("     Assembly: " + fname);
668                         if (File.Exists (fname + ".config")){
669                                 maker.Add ("config:" + aname, fname + ".config");
670                                 Console.WriteLine ("       Config: " + fname + ".config");
671                         }
672                 }
673                 
674                 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
675                         return false;
676
677                 if (config_dir != null){
678                         maker.Add ("config_dir:", config_dir);
679                         Console.WriteLine ("   Config_dir: " + config_dir );
680                 }
681                 if (embedded_options != null)
682                         maker.AddString ("options:", embedded_options);
683                 if (environment.Count > 0){
684                         foreach (var key in environment.Keys)
685                                 maker.AddStringPair ("env:" + key, key, environment [key]);
686                 }
687                 if (libraries.Count > 0){
688                         foreach (var alias_and_path in libraries){
689                                 Console.WriteLine ("     Library:  " + alias_and_path.Value);
690                                 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
691                         }
692                 }
693                 maker.Dump ();
694                 maker.Close ();
695                 return true;
696         }
697         
698         static void GenerateBundles (List<string> files)
699         {
700                 string temp_s = "temp.s"; // Path.GetTempFileName ();
701                 string temp_c = "temp.c";
702                 string temp_o = (style != "windows") ? "temp.o" : "temp.s.obj";
703
704                 if (compile_only)
705                         temp_c = output;
706                 if (object_out != null)
707                         temp_o = object_out;
708                 
709                 try {
710                         List<string> c_bundle_names = new List<string> ();
711                         List<string[]> config_names = new List<string[]> ();
712
713                         using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
714                         using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
715                         string prog = null;
716
717                         if (bundled_header) {
718                                 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
719                                 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
720                                 tc.WriteLine (@"
721 typedef struct {
722         const char *name;
723         const unsigned char *data;
724         const unsigned int size;
725 } MonoBundledAssembly;
726 void          mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
727 void          mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
728 ");
729                         } else {
730                                 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
731                                 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
732                         }
733
734                         if (compress) {
735                                 tc.WriteLine ("typedef struct _compressed_data {");
736                                 tc.WriteLine ("\tMonoBundledAssembly assembly;");
737                                 tc.WriteLine ("\tint compressed_size;");
738                                 tc.WriteLine ("} CompressedAssembly;\n");
739                         }
740
741                         object monitor = new object ();
742
743                         var streams = new Dictionary<string, Stream> ();
744                         var sizes = new Dictionary<string, long> ();
745
746                         // Do the file reading and compression in parallel
747                         Action<string> body = delegate (string url) {
748                                 string fname = LocateFile (new Uri (url).LocalPath);
749                                 Stream stream = File.OpenRead (fname);
750
751                                 long real_size = stream.Length;
752                                 int n;
753                                 if (compress) {
754                                         byte[] cbuffer = new byte [8192];
755                                         MemoryStream ms = new MemoryStream ();
756                                         GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
757                                         while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
758                                                 deflate.Write (cbuffer, 0, n);
759                                         }
760                                         stream.Close ();
761                                         deflate.Close ();
762                                         byte [] bytes = ms.GetBuffer ();
763                                         stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
764                                 }
765
766                                 lock (monitor) {
767                                         streams [url] = stream;
768                                         sizes [url] = real_size;
769                                 }
770                         };
771
772                         //#if NET_4_5
773 #if FALSE
774                         Parallel.ForEach (files, body);
775 #else
776                         foreach (var url in files)
777                                 body (url);
778 #endif
779
780                         // The non-parallel part
781                         byte [] buffer = new byte [8192];
782                         // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
783                         var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
784                         foreach (var url in files) {
785                                 string fname = LocateFile (new Uri (url).LocalPath);
786                                 string aname = MakeBundle.GetAssemblyName (fname);
787                                 string encoded = symbolEscapeRE.Replace (aname, "_");
788
789                                 if (prog == null)
790                                         prog = aname;
791
792                                 var stream = streams [url];
793                                 var real_size = sizes [url];
794
795                                 if (!quiet)
796                                         Console.WriteLine ("   embedding: " + fname);
797
798                                 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
799                         
800                                 WriteBuffer (ts, stream, buffer);
801
802                                 if (compress) {
803                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
804                                         tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
805                                                                   " assembly_data_{0}, {2}}}, {3}}};",
806                                                                   encoded, aname, real_size, stream.Length);
807                                         if (!quiet) {
808                                                 double ratio = ((double) stream.Length * 100) / real_size;
809                                                 Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
810                                         }
811                                 } else {
812                                         tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
813                                         tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
814                                                                   encoded, aname, real_size);
815                                 }
816                                 stream.Close ();
817
818                                 c_bundle_names.Add ("assembly_bundle_" + encoded);
819
820                                 try {
821                                         FileStream cf = File.OpenRead (fname + ".config");
822                                         if (!quiet)
823                                                 Console.WriteLine (" config from: " + fname + ".config");
824                                         tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
825                                         WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
826                                         WriteBuffer (ts, cf, buffer);
827                                         ts.WriteLine ();
828                                         config_names.Add (new string[] {aname, encoded});
829                                 } catch (FileNotFoundException) {
830                                         /* we ignore if the config file doesn't exist */
831                                 }
832                         }
833
834                         if (config_file != null){
835                                 FileStream conf;
836                                 try {
837                                         conf = File.OpenRead (config_file);
838                                 } catch {
839                                         Error ("Failure to open {0}", config_file);
840                                         return;
841                                 }
842                                 if (!quiet)
843                                         Console.WriteLine ("System config from: " + config_file);
844                                 tc.WriteLine ("extern const char system_config;");
845                                 WriteSymbol (ts, "system_config", config_file.Length);
846
847                                 WriteBuffer (ts, conf, buffer);
848                                 // null terminator
849                                 ts.Write ("\t.byte 0\n");
850                                 ts.WriteLine ();
851                         }
852
853                         if (machine_config_file != null){
854                                 FileStream conf;
855                                 try {
856                                         conf = File.OpenRead (machine_config_file);
857                                 } catch {
858                                         Error ("Failure to open {0}", machine_config_file);
859                                         return;
860                                 }
861                                 if (!quiet)
862                                         Console.WriteLine ("Machine config from: " + machine_config_file);
863                                 tc.WriteLine ("extern const char machine_config;");
864                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
865
866                                 WriteBuffer (ts, conf, buffer);
867                                 ts.Write ("\t.byte 0\n");
868                                 ts.WriteLine ();
869                         }
870                         ts.Close ();
871
872                         if (compress)
873                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
874                         else
875                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
876
877                         foreach (string c in c_bundle_names){
878                                 tc.WriteLine ("\t&{0},", c);
879                         }
880                         tc.WriteLine ("\tNULL\n};\n");
881                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
882
883                         if (ctor_func != null) {
884                                 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
885                                 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
886                                 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
887                         }
888
889                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
890                         foreach (string[] ass in config_names){
891                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
892                         }
893                         if (config_file != null)
894                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
895                         if (machine_config_file != null)
896                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
897                         tc.WriteLine ("}\n");
898
899                         if (config_dir != null)
900                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
901                         else
902                                 tc.WriteLine ("static const char *config_dir = NULL;");
903
904                         Stream template_stream;
905                         if (compress) {
906                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
907                         } else {
908                                 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
909                         }
910
911                         StreamReader s = new StreamReader (template_stream);
912                         string template = s.ReadToEnd ();
913                         tc.Write (template);
914
915                         if (!nomain && custom_main == null) {
916                                 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
917                                 StreamReader st = new StreamReader (template_main_stream);
918                                 string maintemplate = st.ReadToEnd ();
919                                 tc.Write (maintemplate);
920                         }
921
922                         tc.Close ();
923
924                         string as_cmd = GetAssemblerCommand (temp_s, temp_o);
925                         Execute(as_cmd);
926
927                         if (compile_only)
928                                 return;
929
930                         if (!quiet)
931                                 Console.WriteLine("Compiling:");
932
933                         if (style == "windows") {
934                                 ToolchainProgram compiler = GetCCompiler ();
935                                 if (compiler != null && compiler.ParentSDK != null) {
936                                         if (compiler.IsVSToolChain && VisualStudioSDKHelper.GetInstance ().IsVisualStudio12 (compiler.ParentSDK) && static_link)
937                                                 Console.WriteLine (     @"Warning: Static linking the Mono runtime on Windows using VC " +
938                                                                         @"12.0, won't support static Mono runtime library distributed in Mono SDK since it has " +
939                                                                         @"been build using different C-runtime version. If build results in " +
940                                                                         @"link errors related to C-runtime functions, please rebuild mono runtime distribution " +
941                                                                         @"using targeted VC compiler and linker and rerun using MONOPREFIX.");
942                                 }
943
944                                 bool staticLinkCRuntime = GetEnv ("VCCRT", "MD") != "MD";
945                                 if (!nomain || custom_main != null) {
946                                         string cl_cmd = GetCompileAndLinkCommand (compiler, temp_c, temp_o, custom_main, static_link, staticLinkCRuntime, output);
947                                         Execute (cl_cmd);
948                                 } else {
949                                         string temp_c_o = "";
950                                         try {
951                                                 string cl_cmd = GetLibrarianCompilerCommand (compiler, temp_c, static_link, staticLinkCRuntime, out temp_c_o);
952                                                 Execute(cl_cmd);
953
954                                                 ToolchainProgram librarian = GetLibrarian ();
955                                                 string lib_cmd = GetLibrarianLinkerCommand (librarian, new string[] { temp_o, temp_c_o }, static_link, staticLinkCRuntime, output);
956                                                 Execute (lib_cmd);
957                                         } finally {
958                                                 File.Delete (temp_c_o);
959                                         }
960
961                                 }
962                         }
963                         else
964                         {
965                                 string zlib = (compress ? "-lz" : "");
966                                 string objc = (style == "osx" ? "-framework CoreFoundation -lobjc" : "");
967                                 string debugging = "-g";
968                                 string cc = GetEnv("CC", "cc");
969                                 string cmd = null;
970
971                                 if (style == "linux")
972                                         debugging = "-ggdb";
973                                 if (static_link)
974                                 {
975                                         string smonolib;
976                                         if (style == "osx")
977                                                 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
978                                         else
979                                                 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
980                                         cmd = String.Format("{4} -o '{2}' -Wall {5} `pkg-config --cflags mono-2` {0} {3} " +
981                                                 "`pkg-config --libs-only-L mono-2` " + smonolib +
982                                                 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
983                                                 temp_c, temp_o, output, zlib, cc, objc);
984                                 }
985                                 else
986                                 {
987
988                                         cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {5} {0} `pkg-config --cflags --libs mono-2` {3} {1}",
989                                                 temp_c, temp_o, output, zlib, cc, objc);
990                                 }
991                                 Execute (cmd);
992                         }
993
994                         if (!quiet)
995                                 Console.WriteLine ("Done");
996                 }
997         }
998                 } finally {
999                         if (!keeptemp){
1000                                 if (object_out == null){
1001                                         File.Delete (temp_o);
1002                                 }
1003                                 if (!compile_only){
1004                                         File.Delete (temp_c);
1005                                 }
1006                                 File.Delete (temp_s);
1007                         }
1008                 }
1009         }
1010         
1011         static List<string> LoadAssemblies (List<string> sources)
1012         {
1013                 List<string> assemblies = new List<string> ();
1014                 bool error = false;
1015
1016                 foreach (string name in sources){
1017                         try {
1018                                 Assembly a = LoadAssemblyFile (name);
1019
1020                                 if (a == null){
1021                                         error = true;
1022                                         continue;
1023                                 }
1024                         
1025                                 assemblies.Add (a.CodeBase);
1026                         } catch (Exception) {
1027                                 if (skip_scan) {
1028                                         if (!quiet)
1029                                                 Console.WriteLine ("File will not be scanned: {0}", name);
1030                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1031                                 } else {
1032                                         throw;
1033                                 }
1034                         }
1035                 }
1036
1037                 if (error) {
1038                         Error ("Couldn't load one or more of the assemblies.");
1039                         Environment.Exit (1);
1040                 }
1041
1042                 return assemblies;
1043         }
1044
1045         static void LoadLocalizedAssemblies (List<string> assemblies)
1046         {
1047                 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1048                 string error = null;
1049
1050                 foreach (string name in other) {
1051                         try {
1052                                 Assembly a = LoadAssembly (name);
1053
1054                                 if (a == null) {
1055                                         error = "Failed to load " + name;
1056                                         continue;
1057                                 }
1058
1059                                 assemblies.Add (a.CodeBase);
1060                         } catch (Exception) {
1061                                 if (skip_scan) {
1062                                         if (!quiet)
1063                                                 Console.WriteLine ("File will not be scanned: {0}", name);
1064                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1065                                 } else {
1066                                         throw;
1067                                 }
1068                         }
1069                 }
1070
1071                 if (error != null) {
1072                         Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1073                         foreach (var path in link_paths){
1074                                 Console.Error.WriteLine ("   Path: " + path);
1075                         }
1076                         if (custom_mode){
1077                                 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1078                         }
1079
1080                         Error ("Couldn't load one or more of the i18n assemblies: " + error);
1081                         Environment.Exit (1);
1082                 }
1083         }
1084
1085         
1086         static readonly Universe universe = new Universe ();
1087         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1088
1089         public static string GetAssemblyName (string path)
1090         {
1091                 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1092                 string name = Path.GetFileName (path);
1093
1094                 // A bit of a hack to support satellite assemblies. They all share the same name but
1095                 // are placed in subdirectories named after the locale they implement. Also, all of
1096                 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1097                 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1098                         string dir = Path.GetDirectoryName (path);
1099                         int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1100                         if (idx >= 0) {
1101                                 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1102                                 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1103                         } else if (!quiet)
1104                                 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1105                 }
1106
1107                 return name;
1108         }
1109
1110         static bool QueueAssembly (List<string> files, string codebase)
1111         {
1112                 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1113                 if (files.Contains (codebase))
1114                         return true;
1115
1116                 var path = new Uri(codebase).LocalPath;
1117                 var name = GetAssemblyName (path);
1118                 string found;
1119                 if (loaded_assemblies.TryGetValue (name, out found)) {
1120                         Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1121                         return false;
1122                 }
1123
1124                 loaded_assemblies.Add (name, path);
1125
1126                 files.Add (codebase);
1127                 if (!autodeps)
1128                         return true;
1129                 try {
1130                         Assembly a = universe.LoadFile (path);
1131                         if (a == null) {
1132                                 Error ("Unable to to load assembly `{0}'", path);
1133                                 return false;
1134                         }
1135
1136                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1137                                 a = LoadAssembly (an.Name);
1138                                 if (a == null) {
1139                                         Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1140                                         return false;
1141                                 }
1142
1143                                 if (!QueueAssembly (files, a.CodeBase))
1144                                         return false;
1145                         }
1146                 } catch (Exception) {
1147                         if (!skip_scan)
1148                                 throw;
1149                 }
1150
1151                 return true;
1152         }
1153
1154         //
1155         // Loads an assembly from a specific path
1156         //
1157         static Assembly LoadAssemblyFile (string assembly)
1158         {
1159                 Assembly a = null;
1160                 
1161                 try {
1162                         if (!quiet)
1163                                 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1164                         a = universe.LoadFile (assembly);
1165                         if (!quiet)
1166                                 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1167
1168                 } catch (FileNotFoundException){
1169                         Error ($"Cannot find assembly `{assembly}'");
1170                 } catch (IKVM.Reflection.BadImageFormatException f) {
1171                         if (skip_scan)
1172                                 throw;
1173                         Error ($"Cannot load assembly (bad file format) " + f.Message);
1174                 } catch (FileLoadException f){
1175                         Error ($"Cannot load assembly " + f.Message);
1176                 } catch (ArgumentNullException){
1177                         Error( $"Cannot load assembly (null argument)");
1178                 }
1179                 return a;
1180         }
1181
1182         //
1183         // Loads an assembly from any of the link directories provided
1184         //
1185         static Assembly LoadAssembly (string assembly)
1186         {
1187                 string total_log = "";
1188                 foreach (string dir in link_paths){
1189                         string full_path = Path.Combine (dir, assembly);
1190                         if (!quiet)
1191                                 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1192                         if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1193                                 full_path += ".dll";
1194                         
1195                         try {
1196                                 var a = universe.LoadFile (full_path);
1197                                 return a;
1198                         } catch (FileNotFoundException ff) {
1199                                 total_log += ff.FusionLog;
1200                                 continue;
1201                         }
1202                 }
1203                 if (!quiet)
1204                         Console.WriteLine ("Log: \n" + total_log);
1205                 return null;
1206         }
1207         
1208         static void Error (string msg, params object [] args)
1209         {
1210                 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1211                 Environment.Exit (1);
1212         }
1213
1214         static void Help ()
1215         {
1216                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1217                                    "Options:\n" +
1218                                    "    --config F           Bundle system config file `F'\n" +
1219                                    "    --config-dir D       Set MONO_CFG_DIR to `D'\n" +
1220                                    "    --deps               Turns on automatic dependency embedding (default on simple)\n" +
1221                                    "    -L path              Adds `path' to the search path for assemblies\n" +
1222                                    "    --machine-config F   Use the given file as the machine.config for the application.\n" +
1223                                    "    -o out               Specifies output filename\n" +
1224                                    "    --nodeps             Turns off automatic dependency embedding (default on custom)\n" +
1225                                    "    --skip-scan          Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1226                                    "    --i18n ENCODING      none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1227                                    "    -v                   Verbose output\n" + 
1228                                    "    --bundled-header     Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1229                                    "\n" + 
1230                                    "--simple   Simple mode does not require a C toolchain and can cross compile\n" + 
1231                                    "    --cross TARGET       Generates a binary for the given TARGET\n"+
1232                                    "    --env KEY=VALUE      Hardcodes an environment variable for the target\n" +
1233                                    "    --fetch-target NAME  Downloads the target SDK from the remote server\n" + 
1234                                    "    --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1235                                    "                         LIB is optional shortname for file located at PATH\n" + 
1236                                    "    --list-targets       Lists available targets on the remote server\n" +
1237                                    "    --local-targets      Lists locally available targets\n" +
1238                                    "    --options OPTIONS    Embed the specified Mono command line options on target\n" +
1239                                    "    --runtime RUNTIME    Manually specifies the Mono runtime to use\n" +
1240                                    "    --sdk PATH           Use a Mono SDK root location instead of a target\n" + 
1241                                    "    --target-server URL  Specified a server to download targets from, default is " + target_server + "\n" +
1242                                    "\n" +
1243                                    "--custom   Builds a custom launcher, options for --custom\n" +
1244                                    "    -c                   Produce stub only, do not compile\n" +
1245                                    "    -oo obj              Specifies output filename for helper object file\n" +
1246                                    "    --dos2unix[=true|false]\n" +
1247                                    "                         When no value provided, or when `true` specified\n" +
1248                                    "                         `dos2unix` will be invoked to convert paths on Windows.\n" +
1249                                    "                         When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1250                                    "    --keeptemp           Keeps the temporary files\n" +
1251                                    "    --static             Statically link to mono libs\n" +
1252                                    "    --nomain             Don't include a main() function, for libraries\n" +
1253                                    "    --custom-main C      Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1254                                    "    -z                   Compress the assemblies before embedding.\n" +
1255                                    "    --static-ctor ctor   Add a constructor call to the supplied function.\n" +
1256                                    "                         You need zlib development headers and libraries.\n");
1257         }
1258
1259         [DllImport ("libc")]
1260         static extern int system (string s);
1261         [DllImport ("libc")]
1262         static extern int uname (IntPtr buf);
1263                 
1264         static void DetectOS ()
1265         {
1266                 if (!IsUnix) {
1267                         os_message = "OS is: Windows";
1268                         style = "windows";
1269                         return;
1270                 }
1271
1272                 IntPtr buf = Marshal.AllocHGlobal (8192);
1273                 if (uname (buf) != 0){
1274                         os_message = "Warning: Unable to detect OS";
1275                         Marshal.FreeHGlobal (buf);
1276                         return;
1277                 }
1278                 string os = Marshal.PtrToStringAnsi (buf);
1279                 os_message = "OS is: " + os;
1280                 if (os == "Darwin")
1281                         style = "osx";
1282                 
1283                 Marshal.FreeHGlobal (buf);
1284         }
1285
1286         static bool IsUnix {
1287                 get {
1288                         int p = (int) Environment.OSVersion.Platform;
1289                         return ((p == 4) || (p == 128) || (p == 6));
1290                 }
1291         }
1292
1293         static void Execute (string cmdLine)
1294         {
1295                 if (IsUnix) {
1296                         if (!quiet)
1297                                 Console.WriteLine ("[execute cmd]: " + cmdLine);
1298                         int ret = system (cmdLine);
1299                         if (ret != 0)
1300                         {
1301                                 Error(String.Format("[Fail] {0}", ret));
1302                         }
1303                         return;
1304                 }
1305
1306                 // on Windows, we have to pipe the output of a
1307                 // `cmd` interpolation to dos2unix, because the shell does not
1308                 // strip the CRLFs generated by the native pkg-config distributed
1309                 // with Mono.
1310                 //
1311                 // But if it's *not* on cygwin, just skip it.
1312
1313                 // check if dos2unix is applicable.
1314                 if (use_dos2unix == true)
1315                         try {
1316                         var info = new ProcessStartInfo ("dos2unix");
1317                         info.CreateNoWindow = true;
1318                         info.RedirectStandardInput = true;
1319                         info.UseShellExecute = false;
1320                         var dos2unix = Process.Start (info);
1321                         dos2unix.StandardInput.WriteLine ("aaa");
1322                         dos2unix.StandardInput.WriteLine ("\u0004");
1323                         dos2unix.StandardInput.Close ();
1324                         dos2unix.WaitForExit ();
1325                         if (dos2unix.ExitCode == 0)
1326                                 use_dos2unix = true;
1327                 } catch {
1328                         Console.WriteLine("Warning: dos2unix not found");
1329                         use_dos2unix = false;
1330                 }
1331
1332                 if (use_dos2unix == null)
1333                         use_dos2unix = false;
1334
1335                 ProcessStartInfo psi = new ProcessStartInfo();
1336                 psi.UseShellExecute = false;
1337
1338                 // if there is no dos2unix, just run cmd /c.
1339                 if (use_dos2unix == false)
1340                 {
1341                         psi.FileName = "cmd";
1342                         psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1343                 }
1344                 else
1345                 {
1346                         psi.FileName = "sh";
1347                         StringBuilder b = new StringBuilder();
1348                         int count = 0;
1349                         for (int i = 0; i < cmdLine.Length; i++)
1350                         {
1351                                 if (cmdLine[i] == '`')
1352                                 {
1353                                         if (count % 2 != 0)
1354                                         {
1355                                                 b.Append("|dos2unix");
1356                                         }
1357                                         count++;
1358                                 }
1359                                 b.Append(cmdLine[i]);
1360                         }
1361                         cmdLine = b.ToString();
1362                         psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1363                 }
1364
1365                 if (!quiet)
1366                         Console.WriteLine(cmdLine);
1367                 using (Process p = Process.Start (psi)) {
1368                         p.WaitForExit ();
1369                         int ret = p.ExitCode;
1370                         if (ret != 0){
1371                                 Error ("[Fail] {0}", ret);
1372                         }
1373                 }
1374         }
1375
1376         static string GetEnv(string name, string defaultValue)
1377         {
1378                 string val = Environment.GetEnvironmentVariable(name);
1379                 if (val != null)
1380                 {
1381                         if (!quiet)
1382                                 Console.WriteLine("{0} = {1}", name, val);
1383                 }
1384                 else
1385                 {
1386                         val = defaultValue;
1387                         if (!quiet)
1388                                 Console.WriteLine("{0} = {1} (default)", name, val);
1389                 }
1390                 return val;
1391         }
1392
1393         static string LocateFile(string default_path)
1394         {
1395                 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1396                 if (File.Exists(override_path))
1397                         return override_path;
1398                 else if (File.Exists(default_path))
1399                         return default_path;
1400                 else
1401                         throw new FileNotFoundException(default_path);
1402         }
1403
1404         static string GetAssemblerCommand (string sourceFile, string objectFile)
1405         {
1406                 if (style == "windows") {
1407                         string additionalArguments = "";
1408                         var assembler = GetAssemblerCompiler ();
1409                         if (assembler.Name.Contains ("clang.exe"))
1410                                 //Clang uses additional arguments.
1411                                 additionalArguments = "-c -x assembler";
1412
1413                         return String.Format ("\"{0}\" {1} -o {2} {3} ", assembler.Path, additionalArguments, objectFile, sourceFile);
1414                 } else {
1415                         return String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), objectFile, sourceFile);
1416                 }
1417         }
1418
1419 #region WindowsToolchainSupport
1420
1421         class StringVersionComparer : IComparer<string> {
1422                 public int Compare (string stringA, string stringB)
1423                 {
1424                         Version versionA;
1425                         Version versionB;
1426
1427                         var versionAMatch = System.Text.RegularExpressions.Regex.Match (stringA, @"\d+(\.\d +) + ");
1428                         if (versionAMatch.Success)
1429                                 stringA = versionAMatch.ToString ();
1430
1431                         var versionBMatch = System.Text.RegularExpressions.Regex.Match (stringB, @"\d+(\.\d+)+");
1432                         if (versionBMatch.Success)
1433                                 stringB = versionBMatch.ToString ();
1434
1435                         if (Version.TryParse (stringA, out versionA) && Version.TryParse (stringB, out versionB))
1436                                 return versionA.CompareTo (versionB);
1437
1438                         return string.Compare (stringA, stringB, StringComparison.OrdinalIgnoreCase);
1439                 }
1440         }
1441
1442         class InstalledSDKInfo {
1443                 public InstalledSDKInfo (string name, string version, string installationFolder)
1444                 {
1445                         this.Name = name;
1446                         this.Version = Version.Parse (version);
1447                         this.InstallationFolder = installationFolder;
1448                         this.IsSubVersion = false;
1449                         this.AdditionalSDKs = new List<InstalledSDKInfo> ();
1450                 }
1451
1452                 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion)
1453                         : this (name, version, installationFolder)
1454                 {
1455                         this.IsSubVersion = isSubVersion;
1456                 }
1457
1458                 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion, InstalledSDKInfo parentSDK)
1459                         : this (name, version, installationFolder, isSubVersion)
1460                 {
1461                         this.ParentSDK = parentSDK;
1462                 }
1463
1464                 public string Name { get; set; }
1465                 public Version Version { get; set; }
1466                 public string InstallationFolder { get; set; }
1467                 public bool IsSubVersion { get; set; }
1468                 public List<InstalledSDKInfo> AdditionalSDKs { get; }
1469                 public InstalledSDKInfo ParentSDK { get; set; }
1470         }
1471
1472         class ToolchainProgram {
1473                 public ToolchainProgram (string name, string path)
1474                 {
1475                         this.Name = name;
1476                         this.Path = path;
1477                 }
1478
1479                 public ToolchainProgram (string name, string path, InstalledSDKInfo parentSDK)
1480                         : this (name, path)
1481                 {
1482                         this.ParentSDK = parentSDK;
1483                 }
1484
1485                 public Func<string, string> QuoteArg = arg => "\"" + arg + "\"";
1486                 public string Name { get; set; }
1487                 public string Path { get; set; }
1488                 public InstalledSDKInfo ParentSDK { get; set; }
1489                 public bool IsVSToolChain { get { return (Name.Contains ("cl.exe") || Name.Contains ("lib.exe")); } }
1490                 public bool IsGCCToolChain { get { return !IsVSToolChain;  } }
1491         }
1492
1493         class SDKHelper {
1494
1495                 protected Microsoft.Win32.RegistryKey GetToolchainRegistrySubKey (string subKey)
1496                 {
1497                         Microsoft.Win32.RegistryKey key = null;
1498
1499                         if (Environment.Is64BitProcess) {
1500                                 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey) ??
1501                                         Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey);
1502                         }
1503
1504                         if (key == null) {
1505                                 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE" + subKey) ??
1506                                         Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE" + subKey);
1507                         }
1508
1509                         return key;
1510                 }
1511         }
1512
1513         class WindowsSDKHelper : SDKHelper {
1514
1515                 List<InstalledSDKInfo> installedWindowsSDKs;
1516                 List<InstalledSDKInfo> installedCRuntimeSDKs;
1517                 InstalledSDKInfo installedWindowsSDK;
1518                 InstalledSDKInfo installedCRuntimeSDK;
1519
1520                 static WindowsSDKHelper singletonInstance = new WindowsSDKHelper ();
1521                 static public WindowsSDKHelper GetInstance ()
1522                 {
1523                         return singletonInstance;
1524                 }
1525
1526                 Dictionary<string, string> GetInstalledWindowsKitRootFolders ()
1527                 {
1528                         var rootFolders = new Dictionary<string, string> ();
1529
1530                         using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\Microsoft SDKs\Windows\")) {
1531                                 if (subKey != null) {
1532                                         foreach (var keyName in subKey.GetSubKeyNames ()) {
1533                                                 var keyNameIsVersion = System.Text.RegularExpressions.Regex.Match (keyName, @"\d+(\.\d+)+");
1534                                                 if (keyNameIsVersion.Success) {
1535                                                         var installFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString () + @"\" + keyName, "InstallationFolder", "");
1536                                                         if (!rootFolders.ContainsKey (installFolder))
1537                                                                 rootFolders.Add (installFolder, keyNameIsVersion.ToString ());
1538                                                 }
1539                                         }
1540                                 }
1541                         }
1542
1543                         using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\Windows Kits\Installed Roots")) {
1544                                 if (subKey != null) {
1545                                         foreach (var valueName in subKey.GetValueNames ()) {
1546                                                 var valueNameIsKitsRoot = System.Text.RegularExpressions.Regex.Match (valueName, @"KitsRoot\d*");
1547                                                 if (valueNameIsKitsRoot.Success) {
1548                                                         var installFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString (), valueName, "");
1549                                                         if (!rootFolders.ContainsKey (installFolder)) {
1550                                                                 var valueNameIsVersion = System.Text.RegularExpressions.Regex.Match (valueName, @"\d+(\.*\d+)+");
1551                                                                 if (valueNameIsVersion.Success)
1552                                                                         rootFolders.Add (installFolder, valueNameIsVersion.ToString ());
1553                                                                 else
1554                                                                         rootFolders.Add (installFolder, "");
1555                                                         }
1556                                                 }
1557                                         }
1558                                 }
1559                         }
1560
1561                         return rootFolders;
1562                 }
1563
1564                 void InitializeInstalledWindowsKits ()
1565                 {
1566                         if (installedWindowsSDKs == null && installedCRuntimeSDKs == null) {
1567                                 List<InstalledSDKInfo> windowsSDKs = new List<InstalledSDKInfo> ();
1568                                 List<InstalledSDKInfo> cRuntimeSDKs = new List<InstalledSDKInfo> ();
1569                                 var rootFolders = GetInstalledWindowsKitRootFolders ();
1570                                 foreach (var winKitRoot in rootFolders) {
1571                                         // Try to locate Windows and CRuntime SDKs.
1572                                         string winKitRootDir = winKitRoot.Key;
1573                                         string winKitRootVersion = winKitRoot.Value;
1574                                         string winKitIncludeDir = Path.Combine (winKitRootDir, "include");
1575
1576                                         //Search for installed SDK versions.
1577                                         if (Directory.Exists (winKitIncludeDir)) {
1578                                                 var winKitIncludeDirInfo = new DirectoryInfo (winKitIncludeDir);
1579                                                 var versions = winKitIncludeDirInfo.GetDirectories (
1580                                                         "*.*", SearchOption.TopDirectoryOnly).OrderByDescending (p => p.Name, new StringVersionComparer ());
1581
1582                                                 foreach (var version in versions) {
1583                                                         string versionedWindowsSDKHeaderPath = Path.Combine (version.FullName, "um", "windows.h");
1584                                                         string versionedCRuntimeSDKHeaderPath = Path.Combine (version.FullName, "ucrt", "stdlib.h");
1585                                                         var hasSubVersion = System.Text.RegularExpressions.Regex.Match (version.Name, @"\d+(\.\d+)+");
1586                                                         if (hasSubVersion.Success) {
1587                                                                 if (File.Exists (versionedWindowsSDKHeaderPath))
1588                                                                         //Found a specific Windows SDK sub version.
1589                                                                         windowsSDKs.Add (new InstalledSDKInfo ("WindowsSDK", hasSubVersion.ToString (), winKitRootDir, true));
1590                                                                 if (File.Exists (versionedCRuntimeSDKHeaderPath))
1591                                                                         //Found a specific CRuntime SDK sub version.
1592                                                                         cRuntimeSDKs.Add (new InstalledSDKInfo ("CRuntimeSDK", hasSubVersion.ToString (), winKitRootDir, true));
1593                                                         }
1594                                                 }
1595                                         }
1596
1597                                         // Try to find SDK without specific sub version.
1598                                         string windowsSDKHeaderPath = Path.Combine (winKitIncludeDir, "um", "windows.h");
1599                                         if (File.Exists (windowsSDKHeaderPath))
1600                                                 //Found a Windows SDK version.
1601                                                 windowsSDKs.Add (new InstalledSDKInfo ("WindowsSDK", winKitRootVersion, winKitRootDir, false));
1602
1603                                         string cRuntimeSDKHeaderPath = Path.Combine (winKitIncludeDir, "ucrt", "stdlib.h");
1604                                         if (File.Exists (cRuntimeSDKHeaderPath))
1605                                                 //Found a CRuntime SDK version.
1606                                                 cRuntimeSDKs.Add (new InstalledSDKInfo ("CRuntimeSDK", winKitRootVersion, winKitRootDir, false));
1607                                 }
1608
1609                                 // Sort based on version.
1610                                 windowsSDKs = windowsSDKs.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1611                                 cRuntimeSDKs = cRuntimeSDKs.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1612
1613                                 installedWindowsSDKs = windowsSDKs;
1614                                 installedCRuntimeSDKs = cRuntimeSDKs;
1615
1616                                 if (!quiet && installedWindowsSDKs != null) {
1617                                         Console.WriteLine ("--- Windows SDK's ---");
1618                                         foreach (var windowsSDK in installedWindowsSDKs) {
1619                                                 Console.WriteLine ("Path: " + windowsSDK.InstallationFolder);
1620                                                 Console.WriteLine ("Version: " + windowsSDK.Version);
1621                                         }
1622                                         Console.WriteLine ("---------------");
1623                                 }
1624
1625                                 if (!quiet && installedCRuntimeSDKs != null) {
1626                                         Console.WriteLine ("--- C-Runtime SDK's ---");
1627                                         foreach (var cRuntimeSDK in installedCRuntimeSDKs) {
1628                                                 Console.WriteLine ("Path: " + cRuntimeSDK.InstallationFolder);
1629                                                 Console.WriteLine ("Version: " + cRuntimeSDK.Version);
1630                                                 if (cRuntimeSDK.ParentSDK != null) {
1631                                                         Console.WriteLine ("Parent SDK Path: " + cRuntimeSDK.ParentSDK.InstallationFolder);
1632                                                         Console.WriteLine ("Parent SDK Version: " + cRuntimeSDK.ParentSDK.Version);
1633                                                 }
1634                                         }
1635                                         Console.WriteLine ("---------------");
1636                                 }
1637                         }
1638
1639                         return;
1640                 }
1641
1642                 List<InstalledSDKInfo> GetInstalledWindowsSDKs ()
1643                 {
1644                         if (installedWindowsSDKs == null)
1645                                 InitializeInstalledWindowsKits ();
1646
1647                         return installedWindowsSDKs;
1648                 }
1649
1650                 List<InstalledSDKInfo> GetInstalledCRuntimeSDKs ()
1651                 {
1652                         if (installedCRuntimeSDKs == null)
1653                                 InitializeInstalledWindowsKits ();
1654
1655                         return installedCRuntimeSDKs;
1656                 }
1657
1658                 InstalledSDKInfo GetInstalledWindowsSDK ()
1659                 {
1660                         if (installedWindowsSDK == null) {
1661                                 string winSDKDir = "";
1662                                 InstalledSDKInfo windowsSDK = null;
1663                                 List<InstalledSDKInfo> windowsSDKs = GetInstalledWindowsSDKs ();
1664
1665                                 // Check that env doesn't already include needed values.
1666                                 winSDKDir = GetEnv ("WINSDK", "");
1667                                 if (winSDKDir.Length == 0)
1668                                         // If executed from a VS developer command prompt, SDK dir set in env.
1669                                         winSDKDir = GetEnv ("WindowsSdkDir", "");
1670
1671                                 // Check that env doesn't already include needed values.
1672                                 // If executed from a VS developer command prompt, SDK version set in env.
1673                                 var winSDKVersion = System.Text.RegularExpressions.Regex.Match (GetEnv ("WindowsSdkVersion", ""), @"\d+(\.\d+)+");
1674
1675                                 if (winSDKDir.Length != 0 && windowsSDKs != null) {
1676                                         // Find installed SDK based on requested info.
1677                                         if (winSDKVersion.Success)
1678                                                 windowsSDK = windowsSDKs.Find (x => (x.InstallationFolder == winSDKDir && x.Version.ToString () == winSDKVersion.ToString ()));
1679                                         else
1680                                                 windowsSDK = windowsSDKs.Find (x => x.InstallationFolder == winSDKDir);
1681                                 }
1682
1683                                 if (windowsSDK == null && winSDKVersion.Success && windowsSDKs != null)
1684                                         // Find installed SDK based on requested info.
1685                                         windowsSDK = windowsSDKs.Find (x => x.Version.ToString () == winSDKVersion.ToString ());
1686
1687                                 if (windowsSDK == null && windowsSDKs != null)
1688                                         // Get latest installed verison.
1689                                         windowsSDK = windowsSDKs.First ();
1690
1691                                 installedWindowsSDK = windowsSDK;
1692                         }
1693
1694                         return installedWindowsSDK;
1695                 }
1696
1697                 string FindCRuntimeSDKIncludePath (InstalledSDKInfo sdk)
1698                 {
1699                         string cRuntimeIncludePath = Path.Combine (sdk.InstallationFolder, "include");
1700                         if (sdk.IsSubVersion)
1701                                 cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, sdk.Version.ToString ());
1702
1703                         cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, "ucrt");
1704                         if (!Directory.Exists (cRuntimeIncludePath))
1705                                 cRuntimeIncludePath = "";
1706
1707                         return cRuntimeIncludePath;
1708                 }
1709
1710                 string FindCRuntimeSDKLibPath (InstalledSDKInfo sdk)
1711                 {
1712                         string cRuntimeLibPath = Path.Combine (sdk.InstallationFolder, "lib");
1713                         if (sdk.IsSubVersion)
1714                                 cRuntimeLibPath = Path.Combine (cRuntimeLibPath, sdk.Version.ToString ());
1715
1716                         cRuntimeLibPath = Path.Combine (cRuntimeLibPath, "ucrt", Target64BitApplication () ? "x64" : "x86");
1717                         if (!Directory.Exists (cRuntimeLibPath))
1718                                 cRuntimeLibPath = "";
1719
1720                         return cRuntimeLibPath;
1721                 }
1722
1723                 InstalledSDKInfo GetInstalledCRuntimeSDK ()
1724                 {
1725                         if (installedCRuntimeSDK == null) {
1726                                 InstalledSDKInfo cRuntimeSDK = null;
1727                                 var windowsSDK = GetInstalledWindowsSDK ();
1728                                 var cRuntimeSDKs = GetInstalledCRuntimeSDKs ();
1729
1730                                 if (windowsSDK != null && cRuntimeSDKs != null) {
1731                                         cRuntimeSDK = cRuntimeSDKs.Find (x => x.Version.ToString () == windowsSDK.Version.ToString ());
1732                                         if (cRuntimeSDK == null && cRuntimeSDKs.Count != 0)
1733                                                 cRuntimeSDK = cRuntimeSDKs.First ();
1734
1735                                         installedCRuntimeSDK = cRuntimeSDK;
1736                                 }
1737                         }
1738
1739                         return installedCRuntimeSDK;
1740                 }
1741
1742                 public void AddWindowsSDKIncludePaths (List<string> includePaths)
1743                 {
1744                         InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1745                         if (winSDK != null) {
1746                                 string winSDKIncludeDir = Path.Combine (winSDK.InstallationFolder, "include");
1747
1748                                 if (winSDK.IsSubVersion)
1749                                         winSDKIncludeDir = Path.Combine (winSDKIncludeDir, winSDK.Version.ToString ());
1750
1751                                 // Include sub folders.
1752                                 if (Directory.Exists (winSDKIncludeDir)) {
1753                                         includePaths.Add (Path.Combine (winSDKIncludeDir, "um"));
1754                                         includePaths.Add (Path.Combine (winSDKIncludeDir, "shared"));
1755                                         includePaths.Add (Path.Combine (winSDKIncludeDir, "winrt"));
1756                                 }
1757                         }
1758
1759                         return;
1760                 }
1761
1762                 public void AddWindowsSDKLibPaths (List<string> libPaths)
1763                 {
1764                         InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1765                         if (winSDK != null) {
1766                                 string winSDKLibDir = Path.Combine (winSDK.InstallationFolder, "lib");
1767
1768                                 if (winSDK.IsSubVersion) {
1769                                         winSDKLibDir = Path.Combine (winSDKLibDir, winSDK.Version.ToString ());
1770                                 } else {
1771                                         // Older WinSDK's header folders are not versioned, but installed libraries are, use latest availalble version for now.
1772                                         var winSDKLibDirInfo = new DirectoryInfo (winSDKLibDir);
1773                                         var versions = winSDKLibDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly).OrderByDescending (p => p.Name, new StringVersionComparer ());
1774                                         if (versions != null && versions.First () != null)
1775                                                 winSDKLibDir = versions.First ().FullName;
1776                                 }
1777
1778                                 //Enumerat lib sub folders.
1779                                 if (Directory.Exists (winSDKLibDir))
1780                                         libPaths.Add (Path.Combine (winSDKLibDir, "um", Target64BitApplication () ? "x64" : "x86"));
1781                         }
1782
1783                         return;
1784                 }
1785
1786                 public void AddCRuntimeSDKIncludePaths (List<string> includePaths)
1787                 {
1788                         InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1789                         if (cRuntimeSDK != null) {
1790                                 string cRuntimeSDKIncludeDir = FindCRuntimeSDKIncludePath (cRuntimeSDK);
1791
1792                                 if (cRuntimeSDKIncludeDir.Length != 0)
1793                                         includePaths.Add (cRuntimeSDKIncludeDir);
1794                         }
1795
1796                         return;
1797                 }
1798
1799                 public void AddCRuntimeSDKLibPaths (List<string> libPaths)
1800                 {
1801                         InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1802                         if (cRuntimeSDK != null) {
1803                                 string cRuntimeSDKLibDir = FindCRuntimeSDKLibPath (cRuntimeSDK);
1804
1805                                 if (cRuntimeSDKLibDir.Length != 0)
1806                                         libPaths.Add (cRuntimeSDKLibDir);
1807                         }
1808
1809                         return;
1810                 }
1811         }
1812
1813         class VisualStudioSDKHelper : SDKHelper {
1814
1815                 List<InstalledSDKInfo> installedVisualStudioSDKs;
1816                 InstalledSDKInfo installedVisualStudioSDK;
1817
1818                 static VisualStudioSDKHelper singletonInstance = new VisualStudioSDKHelper ();
1819                 static public VisualStudioSDKHelper GetInstance ()
1820                 {
1821                         return singletonInstance;
1822                 }
1823
1824                 List<InstalledSDKInfo> InitializeInstalledVisualStudioSDKs ()
1825                 {
1826                         if (installedVisualStudioSDKs == null) {
1827                                 List<InstalledSDKInfo> sdks = new List<InstalledSDKInfo> ();
1828
1829                                 using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\VisualStudio\SxS\VS7")) {
1830                                         if (subKey != null) {
1831                                                 foreach (var keyName in subKey.GetValueNames ()) {
1832                                                         var vsInstalltionFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString (), keyName, "");
1833                                                         if (Directory.Exists (vsInstalltionFolder)) {
1834                                                                 var vsSDK = new InstalledSDKInfo ("VisualStudio", keyName, vsInstalltionFolder, false);
1835                                                                 var vcInstallationFolder = Path.Combine (vsInstalltionFolder, "VC");
1836
1837                                                                 if (Directory.Exists (vcInstallationFolder))
1838                                                                         vsSDK.AdditionalSDKs.Add (new InstalledSDKInfo ("VisualStudioVC", keyName, vcInstallationFolder, false, vsSDK));
1839
1840                                                                 sdks.Add (vsSDK);
1841                                                         }
1842                                                 }
1843                                         }
1844                                 }
1845
1846                                 // TODO: Add VS15 SetupConfiguration support.
1847                                 // To reduce dependecies use vswhere.exe, if available.
1848
1849                                 // Sort based on version.
1850                                 sdks = sdks.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1851                                 installedVisualStudioSDKs = sdks;
1852                         }
1853
1854                         return installedVisualStudioSDKs;
1855                 }
1856
1857                 string FindVisualStudioVCFolderPath (InstalledSDKInfo vcSDK, string subPath)
1858                 {
1859                         string folderPath = "";
1860                         if (vcSDK != null && vcSDK.ParentSDK != null) {
1861                                 if (IsVisualStudio12 (vcSDK.ParentSDK) || IsVisualStudio14 (vcSDK.ParentSDK)) {
1862                                         folderPath = Path.Combine (vcSDK.InstallationFolder, subPath);
1863                                 } else if (IsVisualStudio15 (vcSDK.ParentSDK)) {
1864                                         string msvcVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "MSVC");
1865
1866                                         // Add latest found version of MSVC toolchain.
1867                                         if (Directory.Exists (msvcVersionPath)) {
1868                                                 var msvcVersionDirInfo = new DirectoryInfo (msvcVersionPath);
1869                                                 var versions = msvcVersionDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly).OrderByDescending (p => p.Name, new StringVersionComparer ());
1870
1871                                                 foreach (var version in versions) {
1872                                                         msvcVersionPath = Path.Combine (version.FullName, subPath);
1873                                                         if (Directory.Exists (msvcVersionPath)) {
1874                                                                 folderPath = msvcVersionPath;
1875                                                                 break;
1876                                                         }
1877                                                 }
1878                                         }
1879                                 }
1880                         }
1881
1882                         return folderPath;
1883                 }
1884
1885                 string FindVisualStudioVCLibSubPath (InstalledSDKInfo vcSDK)
1886                 {
1887                         string subPath = "";
1888
1889                         if (vcSDK != null && vcSDK.ParentSDK != null) {
1890                                 if (IsVisualStudio12 (vcSDK.ParentSDK) || IsVisualStudio14 (vcSDK.ParentSDK))
1891                                         subPath = Target64BitApplication () ? @"lib\amd64" : "lib";
1892                                 else if (IsVisualStudio15 (vcSDK.ParentSDK))
1893                                         subPath = Target64BitApplication () ? @"lib\x64" : @"lib\x86";
1894                         }
1895
1896                         return subPath;
1897                 }
1898
1899                 public InstalledSDKInfo GetInstalledVisualStudioSDK ()
1900                 {
1901                         if (installedVisualStudioSDK == null) {
1902                                 List<InstalledSDKInfo> visualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1903                                 InstalledSDKInfo visualStudioSDK = null;
1904
1905                                 // Check that env doesn't already include needed values.
1906                                 // If executed from a VS developer command prompt, Visual Studio install dir set in env.
1907                                 string vsVersion = GetEnv ("VisualStudioVersion", "");
1908
1909                                 if (vsVersion.Length != 0 && visualStudioSDKs != null)
1910                                         // Find installed SDK based on requested info.
1911                                         visualStudioSDK = visualStudioSDKs.Find (x => x.Version.ToString () == vsVersion);
1912
1913                                 if (visualStudioSDK == null && visualStudioSDKs != null)
1914                                         // Get latest installed verison.
1915                                         visualStudioSDK = visualStudioSDKs.First ();
1916
1917                                 installedVisualStudioSDK = visualStudioSDK;
1918                         }
1919
1920                         return installedVisualStudioSDK;
1921                 }
1922
1923                 public InstalledSDKInfo GetInstalledVisualStudioVCSDK ()
1924                 {
1925                         InstalledSDKInfo visualStudioVCSDK = null;
1926
1927                         // Check that env doesn't already include needed values.
1928                         // If executed from a VS developer command prompt, Visual Studio install dir set in env.
1929                         string vcInstallDir = GetEnv ("VCINSTALLDIR", "");
1930                         if (vcInstallDir.Length != 0) {
1931                                 List<InstalledSDKInfo> installedVisualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1932                                 if (installedVisualStudioSDKs != null) {
1933                                         foreach (var currentInstalledSDK in installedVisualStudioSDKs) {
1934                                                 // Find installed SDK based on requested info.
1935                                                 visualStudioVCSDK = currentInstalledSDK.AdditionalSDKs.Find (x => x.InstallationFolder == vcInstallDir);
1936                                                 if (visualStudioVCSDK != null)
1937                                                         break;
1938                                         }
1939                                 }
1940                         }
1941
1942                         // Get latest installed VS VC SDK version.
1943                         if (visualStudioVCSDK == null) {
1944                                 var visualStudioSDK = GetInstalledVisualStudioSDK ();
1945                                 if (visualStudioSDK != null)
1946                                         visualStudioVCSDK = visualStudioSDK.AdditionalSDKs.Find (x => x.Name == "VisualStudioVC");
1947                         }
1948
1949                         return visualStudioVCSDK;
1950                 }
1951
1952                 public bool IsVisualStudio12 (InstalledSDKInfo vsSDK)
1953                 {
1954                         return vsSDK.Version.Major == 12 || vsSDK.Version.Major == 2013;
1955                 }
1956
1957                 public bool IsVisualStudio14 (InstalledSDKInfo vsSDK)
1958                 {
1959                         return vsSDK.Version.Major == 14 || vsSDK.Version.Major == 2015;
1960                 }
1961
1962                 public bool IsVisualStudio15 (InstalledSDKInfo vsSDK)
1963                 {
1964                         return vsSDK.Version.Major == 15 || vsSDK.Version.Major == 2017;
1965                 }
1966
1967                 public void AddVisualStudioVCIncludePaths (List<string> includePaths)
1968                 {
1969                         // Check that env doesn't already include needed values.
1970                         string vcIncludeDir = GetEnv ("VSINCLUDE", "");
1971                         if (vcIncludeDir.Length == 0) {
1972                                 var visualStudioVCSDK = GetInstalledVisualStudioVCSDK ();
1973                                 vcIncludeDir = FindVisualStudioVCFolderPath (visualStudioVCSDK, "include");
1974                         }
1975
1976                         if (vcIncludeDir.Length != 0)
1977                                 includePaths.Add (vcIncludeDir);
1978
1979                         return;
1980                 }
1981
1982                 public void AddVisualStudioVCLibPaths (List<string> libPaths)
1983                 {
1984                         // Check that env doesn't already include needed values.
1985                         string vcLibDir = GetEnv ("VSLIB", "");
1986                         if (vcLibDir.Length == 0) {
1987                                 var vcSDK = GetInstalledVisualStudioVCSDK ();
1988                                 vcLibDir = FindVisualStudioVCFolderPath (vcSDK, FindVisualStudioVCLibSubPath (vcSDK));
1989                         }
1990
1991                         if (vcLibDir.Length != 0)
1992                                 libPaths.Add (vcLibDir);
1993
1994                         return;
1995                 }
1996         }
1997
1998         class VCToolchainProgram {
1999
2000                 protected ToolchainProgram toolchain;
2001                 public virtual bool IsVersion (InstalledSDKInfo vcSDK) { return false; }
2002                 public virtual ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK) { return null; }
2003         }
2004
2005         class VC12ToolchainProgram : VCToolchainProgram {
2006
2007                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2008                 {
2009                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio12 (vcSDK);
2010                 }
2011
2012                 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
2013                 {
2014                         if (toolchain == null) {
2015                                 string toolPath = "";
2016                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2017                                         if (Target64BitApplication ())
2018                                                 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", "amd64", tool });
2019                                         else
2020                                                 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", tool });
2021
2022                                         if (!File.Exists (toolPath))
2023                                                 toolPath = "";
2024                                 }
2025
2026                                 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2027                         }
2028
2029                         return toolchain;
2030                 }
2031         }
2032
2033         class VC15ToolchainProgram : VCToolchainProgram {
2034                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2035                 {
2036                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2037                 }
2038
2039                 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
2040                 {
2041                         if (toolchain == null) {
2042                                 string toolPath = "";
2043                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2044                                         string toolsVersionFilePath = Path.Combine (vcSDK.InstallationFolder, "Auxiliary", "Build", "Microsoft.VCToolsVersion.default.txt");
2045                                         string toolsVersion = File.ReadAllLines (toolsVersionFilePath).ElementAt (0).Trim ();
2046                                         string toolsVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "MSVC", toolsVersion);
2047
2048                                         if (Target64BitApplication ())
2049                                                 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX64", "x64", tool);
2050                                         else
2051                                                 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX86", "x86", tool);
2052                                 }
2053
2054                                 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2055                         }
2056
2057                         return toolchain;
2058                 }
2059         }
2060
2061         class VC12Compiler : VC12ToolchainProgram {
2062                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2063                 {
2064                         return FindVCToolchainProgram ("cl.exe", vcSDK);
2065                 }
2066         }
2067
2068         class VC14Compiler : VC12Compiler {
2069                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2070                 {
2071                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2072                 }
2073         }
2074
2075         class VC15Compiler : VC15ToolchainProgram {
2076                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2077                 {
2078                         return FindVCToolchainProgram ("cl.exe", vcSDK);
2079                 }
2080         }
2081
2082         class VC12Librarian : VC12ToolchainProgram {
2083                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2084                 {
2085                         return FindVCToolchainProgram ("lib.exe", vcSDK);
2086                 }
2087         }
2088
2089         class VC14Librarian : VC12Compiler {
2090                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2091                 {
2092                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2093                 }
2094         }
2095
2096         class VC15Librarian : VC15ToolchainProgram {
2097                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2098                 {
2099                         return FindVCToolchainProgram ("lib.exe", vcSDK);
2100                 }
2101         }
2102
2103         class VC14Clang : VCToolchainProgram {
2104                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2105                 {
2106                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2107                 }
2108
2109                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2110                 {
2111                         if (toolchain == null) {
2112                                 string clangPath = "";
2113                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2114                                         clangPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "ClangC2", "bin", Target64BitApplication () ? "amd64" : "x86", "clang.exe" });
2115
2116                                         if (!File.Exists (clangPath))
2117                                                 clangPath = "";
2118                                 }
2119
2120                                 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2121                         }
2122
2123                         return toolchain;
2124                 }
2125         }
2126
2127         class VC15Clang : VCToolchainProgram {
2128                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2129                 {
2130                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2131                 }
2132
2133                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2134                 {
2135                         if (toolchain == null) {
2136                                 string clangPath = "";
2137                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2138                                         string clangVersionFilePath = Path.Combine (vcSDK.InstallationFolder, "Auxiliary", "Build", "Microsoft.ClangC2Version.default.txt");
2139                                         string clangVersion = File.ReadAllLines (clangVersionFilePath).ElementAt (0).Trim ();
2140                                         string clangVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "ClangC2", clangVersion);
2141
2142                                         clangPath = Path.Combine (clangVersionPath, "bin", Target64BitApplication () ? "HostX64" : "HostX86", "clang.exe");
2143                                 }
2144
2145                                 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2146                         }
2147
2148                         return toolchain;
2149                 }
2150         }
2151
2152         class VisualStudioSDKToolchainHelper {
2153                 List<VCToolchainProgram> vcCompilers = new List<VCToolchainProgram> ();
2154                 List<VCToolchainProgram> vcLibrarians = new List<VCToolchainProgram> ();
2155                 List<VCToolchainProgram> vcClangCompilers = new List<VCToolchainProgram> ();
2156
2157                 public VisualStudioSDKToolchainHelper ()
2158                 {
2159                         vcCompilers.Add (new VC12Compiler ());
2160                         vcCompilers.Add (new VC14Compiler ());
2161                         vcCompilers.Add (new VC15Compiler ());
2162
2163                         vcLibrarians.Add (new VC12Librarian ());
2164                         vcLibrarians.Add (new VC14Librarian ());
2165                         vcLibrarians.Add (new VC15Librarian ());
2166
2167                         vcClangCompilers.Add (new VC14Clang ());
2168                         vcClangCompilers.Add (new VC15Clang ());
2169                 }
2170
2171                 static VisualStudioSDKToolchainHelper singletonInstance = new VisualStudioSDKToolchainHelper ();
2172                 static public VisualStudioSDKToolchainHelper GetInstance ()
2173                 {
2174                         return singletonInstance;
2175                 }
2176
2177                 ToolchainProgram GetVCToolChainProgram (List<VCToolchainProgram> programs)
2178                 {
2179                         ToolchainProgram program = null;
2180                         var vcSDK = VisualStudioSDKHelper.GetInstance ().GetInstalledVisualStudioVCSDK ();
2181                         if (vcSDK?.ParentSDK != null) {
2182                                 foreach (var item in programs) {
2183                                         if (item.IsVersion (vcSDK.ParentSDK)) {
2184                                                 program = item.FindVCToolchainProgram (vcSDK);
2185                                                 break;
2186                                         }
2187                                 }
2188                         }
2189
2190                         return program;
2191                 }
2192
2193                 public ToolchainProgram GetVCCompiler ()
2194                 {
2195                         return GetVCToolChainProgram (vcCompilers);
2196                 }
2197
2198                 public ToolchainProgram GetVCLibrarian ()
2199                 {
2200                         return GetVCToolChainProgram (vcLibrarians);
2201                 }
2202
2203                 public ToolchainProgram GetVCClangCompiler ()
2204                 {
2205                         return GetVCToolChainProgram (vcClangCompilers);
2206                 }
2207         }
2208
2209         static bool Target64BitApplication ()
2210         {
2211                 // Should probably handled the --cross and sdk parameters.
2212                 return Environment.Is64BitProcess;
2213         }
2214
2215         static string GetMonoDir ()
2216         {
2217                 // Check that env doesn't already include needed values.
2218                 string monoInstallDir = GetEnv ("MONOPREFIX", "");
2219                 if (monoInstallDir.Length == 0) {
2220                         using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey (Microsoft.Win32.RegistryHive.LocalMachine,
2221                                 Target64BitApplication () ? Microsoft.Win32.RegistryView.Registry64 : Microsoft.Win32.RegistryView.Registry32)) {
2222
2223                                 if (baseKey != null) {
2224                                         using (var subKey = baseKey.OpenSubKey (@"SOFTWARE\Mono")) {
2225                                                 if (subKey != null)
2226                                                         monoInstallDir = (string)subKey.GetValue ("SdkInstallRoot", "");
2227                                         }
2228                                 }
2229                         }
2230                 }
2231
2232                 return monoInstallDir;
2233         }
2234
2235         static void AddMonoIncludePaths (List<string> includePaths)
2236         {
2237                 includePaths.Add (Path.Combine (GetMonoDir (), @"include\mono-2.0"));
2238                 return;
2239         }
2240
2241         static void AddMonoLibPaths (List<string> libPaths)
2242         {
2243                 libPaths.Add (Path.Combine (GetMonoDir (), "lib"));
2244                 return;
2245         }
2246
2247         static void AddIncludePaths (List<string> includePaths)
2248         {
2249                 // Check that env doesn't already include needed values.
2250                 // If executed from a VS developer command prompt, all includes are already setup in env.
2251                 string includeEnv = GetEnv ("INCLUDE", "");
2252                 if (includeEnv.Length == 0) {
2253                         VisualStudioSDKHelper.GetInstance ().AddVisualStudioVCIncludePaths (includePaths);
2254                         WindowsSDKHelper.GetInstance ().AddCRuntimeSDKIncludePaths (includePaths);
2255                         WindowsSDKHelper.GetInstance ().AddWindowsSDKIncludePaths (includePaths);
2256                 }
2257
2258                 AddMonoIncludePaths (includePaths);
2259                 includePaths.Add (".");
2260
2261                 return;
2262         }
2263
2264         static void AddLibPaths (List<string> libPaths)
2265         {
2266                 // Check that env doesn't already include needed values.
2267                 // If executed from a VS developer command prompt, all libs are already setup in env.
2268                 string libEnv = GetEnv ("LIB", "");
2269                 if (libEnv.Length == 0) {
2270                         VisualStudioSDKHelper.GetInstance ().AddVisualStudioVCLibPaths (libPaths);
2271                         WindowsSDKHelper.GetInstance ().AddCRuntimeSDKLibPaths (libPaths);
2272                         WindowsSDKHelper.GetInstance ().AddWindowsSDKLibPaths (libPaths);
2273                 }
2274
2275                 AddMonoLibPaths (libPaths);
2276                 libPaths.Add (".");
2277
2278                 return;
2279         }
2280
2281         static void AddVCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2282         {
2283                 linkerArgs.Add ("kernel32.lib");
2284                 linkerArgs.Add ("version.lib");
2285                 linkerArgs.Add ("ws2_32.lib");
2286                 linkerArgs.Add ("mswsock.lib");
2287                 linkerArgs.Add ("psapi.lib");
2288                 linkerArgs.Add ("shell32.lib");
2289                 linkerArgs.Add ("oleaut32.lib");
2290                 linkerArgs.Add ("ole32.lib");
2291                 linkerArgs.Add ("winmm.lib");
2292                 linkerArgs.Add ("user32.lib");
2293                 linkerArgs.Add ("advapi32.lib");
2294
2295                 if (program != null && program.ParentSDK != null && VisualStudioSDKHelper.GetInstance ().IsVisualStudio12 (program.ParentSDK)) {
2296                         if (staticLinkCRuntime) {
2297                                 // Static release c-runtime support.
2298                                 linkerArgs.Add ("libcmt.lib");
2299                                 linkerArgs.Add ("oldnames.lib");
2300                         } else {
2301                                 // Dynamic release c-runtime support.
2302                                 linkerArgs.Add ("msvcrt.lib");
2303                                 linkerArgs.Add ("oldnames.lib");
2304                         }
2305                 } else {
2306                         if (staticLinkCRuntime) {
2307                                 // Static release c-runtime support.
2308                                 linkerArgs.Add ("libucrt.lib");
2309                                 linkerArgs.Add ("libvcruntime.lib");
2310                                 linkerArgs.Add ("libcmt.lib");
2311                                 linkerArgs.Add ("oldnames.lib");
2312                         } else {
2313                                 // Dynamic release c-runtime support.
2314                                 linkerArgs.Add ("ucrt.lib");
2315                                 linkerArgs.Add ("vcruntime.lib");
2316                                 linkerArgs.Add ("msvcrt.lib");
2317                                 linkerArgs.Add ("oldnames.lib");
2318                         }
2319                 }
2320
2321                 return;
2322         }
2323
2324         static void AddGCCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2325         {
2326                 if (MakeBundle.compress)
2327                         linkerArgs.Add ("-lz");
2328
2329                 return;
2330         }
2331
2332         static void AddSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2333         {
2334                 if (program.IsVSToolChain)
2335                         AddVCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2336                 else
2337                         AddGCCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2338
2339                 return;
2340         }
2341
2342         static void AddMonoLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArguments)
2343         {
2344                 bool vsToolChain = program.IsVSToolChain;
2345                 string libPrefix = !vsToolChain ? "-l" : "";
2346                 string libExtension = vsToolChain ? ".lib" : "";
2347                 string monoLibrary = GetEnv ("LIBMONO", "");
2348
2349                 if (monoLibrary.Length == 0) {
2350                         if (staticLinkMono) {
2351                                 if (program.IsGCCToolChain) {
2352                                         Console.WriteLine (     @"Warning: Static linking using default Visual Studio build libmono-static-sgen" +
2353                                                                 @"might cause link errors when using GCC toolchain.");
2354                                 }
2355                                 monoLibrary = "libmono-static-sgen";
2356                         } else {
2357                                 monoLibrary = "mono-2.0-sgen";
2358                         }
2359                 }
2360
2361                 if (!Path.IsPathRooted (monoLibrary)) {
2362                         if (!monoLibrary.EndsWith (libExtension))
2363                                 monoLibrary = monoLibrary + libExtension;
2364
2365                         linkerArguments.Add (libPrefix + monoLibrary);
2366                 } else {
2367                         linkerArguments.Add (monoLibrary);
2368                 }
2369
2370                 return;
2371         }
2372
2373         static void AddVCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2374         {
2375                 List<string> includePaths = new List<string> ();
2376                 AddIncludePaths (includePaths);
2377
2378                 if (staticLinkCRuntime)
2379                         // Add targeted c-runtime (MT = static release).
2380                         compilerArgs.Add ("/MT");
2381                 else
2382                         // Add targeted c-runtime (MD = dynamic release).
2383                         compilerArgs.Add ("/MD");
2384
2385                 // Add include search paths.
2386                 foreach (string include in includePaths)
2387                         compilerArgs.Add (String.Format("/I {0}", program.QuoteArg (include)));
2388
2389                 return;
2390         }
2391
2392         static void AddGCCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2393         {
2394                 List<string> includePaths = new List<string> ();
2395                 AddMonoIncludePaths (includePaths);
2396
2397                 // Add include search paths.
2398                 foreach (string include in includePaths)
2399                         compilerArgs.Add (String.Format ("-I {0}", program.QuoteArg (include)));
2400
2401                 return;
2402         }
2403
2404         static void AddCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2405         {
2406                 if (program.IsVSToolChain)
2407                         AddVCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2408                 else
2409                         AddGCCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2410
2411                 return;
2412         }
2413
2414         static void AddVCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2415         {
2416                 linkerArgs.Add ("/link");
2417
2418                 var subsystem = GetEnv ("VCSUBSYSTEM", "windows");
2419                 linkerArgs.Add ("/SUBSYSTEM:" + subsystem);
2420
2421                 if (customMain != null && customMain.Length != 0)
2422                         linkerArgs.Add (linker.QuoteArg (customMain));
2423                 else
2424                         linkerArgs.Add ("/ENTRY:mainCRTStartup");
2425
2426                 // Ignore other c-runtime directives from linked libraries.
2427                 linkerArgs.Add ("/NODEFAULTLIB");
2428
2429                 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2430                 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2431
2432                 // Add library search paths.
2433                 List<string> libPaths = new List<string> ();
2434                 AddLibPaths (libPaths);
2435
2436                 foreach (string lib in libPaths)
2437                         linkerArgs.Add (String.Format ("/LIBPATH:{0}", linker.QuoteArg (lib)));
2438
2439                 // Linker output target.
2440                 linkerArgs.Add ("/OUT:" + linker.QuoteArg (outputFile));
2441
2442                 return;
2443         }
2444
2445         static void AddGCCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2446         {
2447                 // Add library search paths.
2448                 List<string> libPaths = new List<string> ();
2449                 AddMonoLibPaths (libPaths);
2450
2451                 foreach (string lib in libPaths)
2452                         linkerArgs.Add (String.Format ("-L {0}", linker.QuoteArg (lib)));
2453
2454                 // Add libraries.
2455                 if (staticLinkMono)
2456                         linkerArgs.Add ("-Wl,-Bstatic");
2457
2458                 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2459
2460                 if (staticLinkMono)
2461                         linkerArgs.Add ("-Wl,-Bdynamic");
2462
2463                 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2464
2465                 // Linker output target.
2466                 linkerArgs.Add ("-o " + linker.QuoteArg (outputFile));
2467         }
2468
2469         static void AddLinkerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2470         {
2471                 if (program.IsVSToolChain)
2472                         AddVCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2473                 else
2474                         AddGCCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2475
2476                 return;
2477         }
2478
2479         static void AddVCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2480         {
2481                 compilerArgs.Add ("/c");
2482                 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2483
2484                 objectFile = sourceFile + ".obj";
2485                 compilerArgs.Add (String.Format ("/Fo" + compiler.QuoteArg (objectFile)));
2486
2487                 return;
2488         }
2489
2490         static void AddGCCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2491         {
2492                 compilerArgs.Add ("-c");
2493                 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2494
2495                 objectFile = sourceFile + ".o";
2496                 compilerArgs.Add (String.Format ("-o " + compiler.QuoteArg (objectFile)));
2497
2498                 return;
2499         }
2500
2501         static void AddVCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2502         {
2503                 foreach (var objectFile in objectFiles)
2504                         librarianArgs.Add (librarian.QuoteArg (objectFile));
2505
2506                 // Add library search paths.
2507                 List<string> libPaths = new List<string> ();
2508                 AddLibPaths (libPaths);
2509
2510                 foreach (string lib in libPaths) {
2511                         librarianArgs.Add (String.Format ("/LIBPATH:{0}", librarian.QuoteArg (lib)));
2512                 }
2513
2514                 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2515
2516                 librarianArgs.Add ("/OUT:" + librarian.QuoteArg (output));
2517
2518                 return;
2519         }
2520
2521         static void AddGCCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2522         {
2523                 foreach (var objectFile in objectFiles)
2524                         librarianArgs.Add (librarian.QuoteArg (objectFile));
2525
2526                 // Add library search paths.
2527                 List<string> libPaths = new List<string> ();
2528                 AddMonoLibPaths (libPaths);
2529
2530                 foreach (string lib in libPaths)
2531                         librarianArgs.Add (String.Format ("-L {0}", librarian.QuoteArg (lib)));
2532
2533                 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2534
2535                 librarianArgs.Add ("-o " + librarian.QuoteArg (output));
2536
2537                 return;
2538         }
2539
2540         static ToolchainProgram GetAssemblerCompiler ()
2541         {
2542                 // First check if env is set (old behavior) and use that.
2543                 string assembler = GetEnv ("AS", "");
2544                 if (assembler.Length != 0)
2545                         return new ToolchainProgram ("AS", assembler);
2546
2547                 var vcClangAssembler = VisualStudioSDKToolchainHelper.GetInstance ().GetVCClangCompiler ();
2548                 if (vcClangAssembler == null)
2549                         // Fallback to GNU assembler if clang for VS was not installed.
2550                         // Why? because mkbundle generates GNU assembler not compilable by VS tools like ml.
2551                         return new ToolchainProgram ("AS", "as.exe");
2552
2553                 return vcClangAssembler;
2554         }
2555
2556         static ToolchainProgram GetCCompiler ()
2557         {
2558                 // First check if env is set (old behavior) and use that.
2559                 string compiler = GetEnv ("CC", "");
2560                 if (compiler.Length != 0)
2561                         return new ToolchainProgram ("CC", compiler);
2562
2563                 var vcCompiler = VisualStudioSDKToolchainHelper.GetInstance ().GetVCCompiler ();
2564                 if (vcCompiler == null)
2565                         // Fallback to cl.exe if VC compiler was not installed.
2566                         return new ToolchainProgram ("cl.exe", "cl.exe");
2567
2568                 return vcCompiler;
2569         }
2570
2571         static ToolchainProgram GetLibrarian ()
2572         {
2573                 ToolchainProgram vcLibrarian = VisualStudioSDKToolchainHelper.GetInstance ().GetVCLibrarian ();
2574                 if (vcLibrarian == null)
2575                         // Fallback to lib.exe if VS was not installed.
2576                         return new ToolchainProgram ("lib.exe", "lib.exe");
2577
2578                 return vcLibrarian;
2579         }
2580
2581         static string GetCompileAndLinkCommand (ToolchainProgram compiler, string sourceFile, string objectFile, string customMain, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2582         {
2583                 var compilerArgs = new List<string> ();
2584
2585                 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2586
2587                 // Add source file to compile.
2588                 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2589
2590                 // Add assembled object file.
2591                 compilerArgs.Add (compiler.QuoteArg (objectFile));
2592
2593                 // Add linker arguments.
2594                 AddLinkerArguments (compiler, staticLinkMono, staticLinkCRuntime, customMain, outputFile, compilerArgs);
2595
2596                 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs.ToArray ()));
2597         }
2598
2599         static string GetLibrarianCompilerCommand (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, out string objectFile)
2600         {
2601                 var compilerArgs = new List<string> ();
2602
2603                 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2604
2605                 if (compiler.IsVSToolChain)
2606                         AddVCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2607                 else
2608                         AddGCCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2609
2610                 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs.ToArray ()));
2611         }
2612
2613         static string GetLibrarianLinkerCommand (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2614         {
2615                 var librarianArgs = new List<string> ();
2616
2617                 if (librarian.IsVSToolChain)
2618                         AddVCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2619                 else
2620                         AddGCCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2621
2622                 return String.Format ("{0} {1}", librarian.QuoteArg (librarian.Path), String.Join (" ", librarianArgs.ToArray ()));
2623         }
2624 #endregion
2625 }