Review feedback + drop VS2013 support.
[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                                 bool staticLinkCRuntime = GetEnv ("VCCRT", "MD") != "MD";
936                                 if (!nomain || custom_main != null) {
937                                         string cl_cmd = GetCompileAndLinkCommand (compiler, temp_c, temp_o, custom_main, static_link, staticLinkCRuntime, output);
938                                         Execute (cl_cmd);
939                                 } else {
940                                         string temp_c_o = "";
941                                         try {
942                                                 string cl_cmd = GetLibrarianCompilerCommand (compiler, temp_c, static_link, staticLinkCRuntime, out temp_c_o);
943                                                 Execute(cl_cmd);
944
945                                                 ToolchainProgram librarian = GetLibrarian ();
946                                                 string lib_cmd = GetLibrarianLinkerCommand (librarian, new string[] { temp_o, temp_c_o }, static_link, staticLinkCRuntime, output);
947                                                 Execute (lib_cmd);
948                                         } finally {
949                                                 File.Delete (temp_c_o);
950                                         }
951
952                                 }
953                         }
954                         else
955                         {
956                                 string zlib = (compress ? "-lz" : "");
957                                 string objc = (style == "osx" ? "-framework CoreFoundation -lobjc" : "");
958                                 string debugging = "-g";
959                                 string cc = GetEnv("CC", "cc");
960                                 string cmd = null;
961
962                                 if (style == "linux")
963                                         debugging = "-ggdb";
964                                 if (static_link)
965                                 {
966                                         string smonolib;
967                                         if (style == "osx")
968                                                 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
969                                         else
970                                                 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
971                                         cmd = String.Format("{4} -o '{2}' -Wall {5} `pkg-config --cflags mono-2` {0} {3} " +
972                                                 "`pkg-config --libs-only-L mono-2` " + smonolib +
973                                                 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
974                                                 temp_c, temp_o, output, zlib, cc, objc);
975                                 }
976                                 else
977                                 {
978
979                                         cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {5} {0} `pkg-config --cflags --libs mono-2` {3} {1}",
980                                                 temp_c, temp_o, output, zlib, cc, objc);
981                                 }
982                                 Execute (cmd);
983                         }
984
985                         if (!quiet)
986                                 Console.WriteLine ("Done");
987                 }
988         }
989                 } finally {
990                         if (!keeptemp){
991                                 if (object_out == null){
992                                         File.Delete (temp_o);
993                                 }
994                                 if (!compile_only){
995                                         File.Delete (temp_c);
996                                 }
997                                 File.Delete (temp_s);
998                         }
999                 }
1000         }
1001         
1002         static List<string> LoadAssemblies (List<string> sources)
1003         {
1004                 List<string> assemblies = new List<string> ();
1005                 bool error = false;
1006
1007                 foreach (string name in sources){
1008                         try {
1009                                 Assembly a = LoadAssemblyFile (name);
1010
1011                                 if (a == null){
1012                                         error = true;
1013                                         continue;
1014                                 }
1015                         
1016                                 assemblies.Add (a.CodeBase);
1017                         } catch (Exception) {
1018                                 if (skip_scan) {
1019                                         if (!quiet)
1020                                                 Console.WriteLine ("File will not be scanned: {0}", name);
1021                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1022                                 } else {
1023                                         throw;
1024                                 }
1025                         }
1026                 }
1027
1028                 if (error) {
1029                         Error ("Couldn't load one or more of the assemblies.");
1030                         Environment.Exit (1);
1031                 }
1032
1033                 return assemblies;
1034         }
1035
1036         static void LoadLocalizedAssemblies (List<string> assemblies)
1037         {
1038                 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1039                 string error = null;
1040
1041                 foreach (string name in other) {
1042                         try {
1043                                 Assembly a = LoadAssembly (name);
1044
1045                                 if (a == null) {
1046                                         error = "Failed to load " + name;
1047                                         continue;
1048                                 }
1049
1050                                 assemblies.Add (a.CodeBase);
1051                         } catch (Exception) {
1052                                 if (skip_scan) {
1053                                         if (!quiet)
1054                                                 Console.WriteLine ("File will not be scanned: {0}", name);
1055                                         assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1056                                 } else {
1057                                         throw;
1058                                 }
1059                         }
1060                 }
1061
1062                 if (error != null) {
1063                         Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1064                         foreach (var path in link_paths){
1065                                 Console.Error.WriteLine ("   Path: " + path);
1066                         }
1067                         if (custom_mode){
1068                                 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1069                         }
1070
1071                         Error ("Couldn't load one or more of the i18n assemblies: " + error);
1072                         Environment.Exit (1);
1073                 }
1074         }
1075
1076         
1077         static readonly Universe universe = new Universe ();
1078         static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1079
1080         public static string GetAssemblyName (string path)
1081         {
1082                 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1083                 string name = Path.GetFileName (path);
1084
1085                 // A bit of a hack to support satellite assemblies. They all share the same name but
1086                 // are placed in subdirectories named after the locale they implement. Also, all of
1087                 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1088                 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1089                         string dir = Path.GetDirectoryName (path);
1090                         int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1091                         if (idx >= 0) {
1092                                 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1093                                 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1094                         } else if (!quiet)
1095                                 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1096                 }
1097
1098                 return name;
1099         }
1100
1101         static bool QueueAssembly (List<string> files, string codebase)
1102         {
1103                 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1104                 if (files.Contains (codebase))
1105                         return true;
1106
1107                 var path = new Uri(codebase).LocalPath;
1108                 var name = GetAssemblyName (path);
1109                 string found;
1110                 if (loaded_assemblies.TryGetValue (name, out found)) {
1111                         Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1112                         return false;
1113                 }
1114
1115                 loaded_assemblies.Add (name, path);
1116
1117                 files.Add (codebase);
1118                 if (!autodeps)
1119                         return true;
1120                 try {
1121                         Assembly a = universe.LoadFile (path);
1122                         if (a == null) {
1123                                 Error ("Unable to to load assembly `{0}'", path);
1124                                 return false;
1125                         }
1126
1127                         foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1128                                 a = LoadAssembly (an.Name);
1129                                 if (a == null) {
1130                                         Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1131                                         return false;
1132                                 }
1133
1134                                 if (!QueueAssembly (files, a.CodeBase))
1135                                         return false;
1136                         }
1137                 } catch (Exception) {
1138                         if (!skip_scan)
1139                                 throw;
1140                 }
1141
1142                 return true;
1143         }
1144
1145         //
1146         // Loads an assembly from a specific path
1147         //
1148         static Assembly LoadAssemblyFile (string assembly)
1149         {
1150                 Assembly a = null;
1151                 
1152                 try {
1153                         if (!quiet)
1154                                 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1155                         a = universe.LoadFile (assembly);
1156                         if (!quiet)
1157                                 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1158
1159                 } catch (FileNotFoundException){
1160                         Error ($"Cannot find assembly `{assembly}'");
1161                 } catch (IKVM.Reflection.BadImageFormatException f) {
1162                         if (skip_scan)
1163                                 throw;
1164                         Error ($"Cannot load assembly (bad file format) " + f.Message);
1165                 } catch (FileLoadException f){
1166                         Error ($"Cannot load assembly " + f.Message);
1167                 } catch (ArgumentNullException){
1168                         Error( $"Cannot load assembly (null argument)");
1169                 }
1170                 return a;
1171         }
1172
1173         //
1174         // Loads an assembly from any of the link directories provided
1175         //
1176         static Assembly LoadAssembly (string assembly)
1177         {
1178                 string total_log = "";
1179                 foreach (string dir in link_paths){
1180                         string full_path = Path.Combine (dir, assembly);
1181                         if (!quiet)
1182                                 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1183                         if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1184                                 full_path += ".dll";
1185                         
1186                         try {
1187                                 var a = universe.LoadFile (full_path);
1188                                 return a;
1189                         } catch (FileNotFoundException ff) {
1190                                 total_log += ff.FusionLog;
1191                                 continue;
1192                         }
1193                 }
1194                 if (!quiet)
1195                         Console.WriteLine ("Log: \n" + total_log);
1196                 return null;
1197         }
1198         
1199         static void Error (string msg, params object [] args)
1200         {
1201                 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1202                 Environment.Exit (1);
1203         }
1204
1205         static void Help ()
1206         {
1207                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1208                                    "Options:\n" +
1209                                    "    --config F           Bundle system config file `F'\n" +
1210                                    "    --config-dir D       Set MONO_CFG_DIR to `D'\n" +
1211                                    "    --deps               Turns on automatic dependency embedding (default on simple)\n" +
1212                                    "    -L path              Adds `path' to the search path for assemblies\n" +
1213                                    "    --machine-config F   Use the given file as the machine.config for the application.\n" +
1214                                    "    -o out               Specifies output filename\n" +
1215                                    "    --nodeps             Turns off automatic dependency embedding (default on custom)\n" +
1216                                    "    --skip-scan          Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1217                                    "    --i18n ENCODING      none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1218                                    "    -v                   Verbose output\n" + 
1219                                    "    --bundled-header     Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1220                                    "\n" + 
1221                                    "--simple   Simple mode does not require a C toolchain and can cross compile\n" + 
1222                                    "    --cross TARGET       Generates a binary for the given TARGET\n"+
1223                                    "    --env KEY=VALUE      Hardcodes an environment variable for the target\n" +
1224                                    "    --fetch-target NAME  Downloads the target SDK from the remote server\n" + 
1225                                    "    --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1226                                    "                         LIB is optional shortname for file located at PATH\n" + 
1227                                    "    --list-targets       Lists available targets on the remote server\n" +
1228                                    "    --local-targets      Lists locally available targets\n" +
1229                                    "    --options OPTIONS    Embed the specified Mono command line options on target\n" +
1230                                    "    --runtime RUNTIME    Manually specifies the Mono runtime to use\n" +
1231                                    "    --sdk PATH           Use a Mono SDK root location instead of a target\n" + 
1232                                    "    --target-server URL  Specified a server to download targets from, default is " + target_server + "\n" +
1233                                    "\n" +
1234                                    "--custom   Builds a custom launcher, options for --custom\n" +
1235                                    "    -c                   Produce stub only, do not compile\n" +
1236                                    "    -oo obj              Specifies output filename for helper object file\n" +
1237                                    "    --dos2unix[=true|false]\n" +
1238                                    "                         When no value provided, or when `true` specified\n" +
1239                                    "                         `dos2unix` will be invoked to convert paths on Windows.\n" +
1240                                    "                         When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1241                                    "    --keeptemp           Keeps the temporary files\n" +
1242                                    "    --static             Statically link to mono libs\n" +
1243                                    "    --nomain             Don't include a main() function, for libraries\n" +
1244                                    "    --custom-main C      Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1245                                    "    -z                   Compress the assemblies before embedding.\n" +
1246                                    "    --static-ctor ctor   Add a constructor call to the supplied function.\n" +
1247                                    "                         You need zlib development headers and libraries.\n");
1248         }
1249
1250         [DllImport ("libc")]
1251         static extern int system (string s);
1252         [DllImport ("libc")]
1253         static extern int uname (IntPtr buf);
1254                 
1255         static void DetectOS ()
1256         {
1257                 if (!IsUnix) {
1258                         os_message = "OS is: Windows";
1259                         style = "windows";
1260                         return;
1261                 }
1262
1263                 IntPtr buf = Marshal.AllocHGlobal (8192);
1264                 if (uname (buf) != 0){
1265                         os_message = "Warning: Unable to detect OS";
1266                         Marshal.FreeHGlobal (buf);
1267                         return;
1268                 }
1269                 string os = Marshal.PtrToStringAnsi (buf);
1270                 os_message = "OS is: " + os;
1271                 if (os == "Darwin")
1272                         style = "osx";
1273                 
1274                 Marshal.FreeHGlobal (buf);
1275         }
1276
1277         static bool IsUnix {
1278                 get {
1279                         int p = (int) Environment.OSVersion.Platform;
1280                         return ((p == 4) || (p == 128) || (p == 6));
1281                 }
1282         }
1283
1284         static void Execute (string cmdLine)
1285         {
1286                 if (IsUnix) {
1287                         if (!quiet)
1288                                 Console.WriteLine ("[execute cmd]: " + cmdLine);
1289                         int ret = system (cmdLine);
1290                         if (ret != 0)
1291                         {
1292                                 Error(String.Format("[Fail] {0}", ret));
1293                         }
1294                         return;
1295                 }
1296
1297                 // on Windows, we have to pipe the output of a
1298                 // `cmd` interpolation to dos2unix, because the shell does not
1299                 // strip the CRLFs generated by the native pkg-config distributed
1300                 // with Mono.
1301                 //
1302                 // But if it's *not* on cygwin, just skip it.
1303
1304                 // check if dos2unix is applicable.
1305                 if (use_dos2unix == true)
1306                         try {
1307                         var info = new ProcessStartInfo ("dos2unix");
1308                         info.CreateNoWindow = true;
1309                         info.RedirectStandardInput = true;
1310                         info.UseShellExecute = false;
1311                         var dos2unix = Process.Start (info);
1312                         dos2unix.StandardInput.WriteLine ("aaa");
1313                         dos2unix.StandardInput.WriteLine ("\u0004");
1314                         dos2unix.StandardInput.Close ();
1315                         dos2unix.WaitForExit ();
1316                         if (dos2unix.ExitCode == 0)
1317                                 use_dos2unix = true;
1318                 } catch {
1319                         Console.WriteLine("Warning: dos2unix not found");
1320                         use_dos2unix = false;
1321                 }
1322
1323                 if (use_dos2unix == null)
1324                         use_dos2unix = false;
1325
1326                 ProcessStartInfo psi = new ProcessStartInfo();
1327                 psi.UseShellExecute = false;
1328
1329                 // if there is no dos2unix, just run cmd /c.
1330                 if (use_dos2unix == false)
1331                 {
1332                         psi.FileName = "cmd";
1333                         psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1334                 }
1335                 else
1336                 {
1337                         psi.FileName = "sh";
1338                         StringBuilder b = new StringBuilder();
1339                         int count = 0;
1340                         for (int i = 0; i < cmdLine.Length; i++)
1341                         {
1342                                 if (cmdLine[i] == '`')
1343                                 {
1344                                         if (count % 2 != 0)
1345                                         {
1346                                                 b.Append("|dos2unix");
1347                                         }
1348                                         count++;
1349                                 }
1350                                 b.Append(cmdLine[i]);
1351                         }
1352                         cmdLine = b.ToString();
1353                         psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1354                 }
1355
1356                 if (!quiet)
1357                         Console.WriteLine(cmdLine);
1358                 using (Process p = Process.Start (psi)) {
1359                         p.WaitForExit ();
1360                         int ret = p.ExitCode;
1361                         if (ret != 0){
1362                                 Error ("[Fail] {0}", ret);
1363                         }
1364                 }
1365         }
1366
1367         static string GetEnv(string name, string defaultValue)
1368         {
1369                 string val = Environment.GetEnvironmentVariable(name);
1370                 if (val != null)
1371                 {
1372                         if (!quiet)
1373                                 Console.WriteLine("{0} = {1}", name, val);
1374                 }
1375                 else
1376                 {
1377                         val = defaultValue;
1378                         if (!quiet)
1379                                 Console.WriteLine("{0} = {1} (default)", name, val);
1380                 }
1381                 return val;
1382         }
1383
1384         static string LocateFile(string default_path)
1385         {
1386                 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1387                 if (File.Exists(override_path))
1388                         return override_path;
1389                 else if (File.Exists(default_path))
1390                         return default_path;
1391                 else
1392                         throw new FileNotFoundException(default_path);
1393         }
1394
1395         static string GetAssemblerCommand (string sourceFile, string objectFile)
1396         {
1397                 if (style == "windows") {
1398                         string additionalArguments = "";
1399                         var assembler = GetAssemblerCompiler ();
1400                         if (assembler.Name.Contains ("clang.exe"))
1401                                 //Clang uses additional arguments.
1402                                 additionalArguments = "-c -x assembler";
1403
1404                         return String.Format ("\"{0}\" {1} -o {2} {3} ", assembler.Path, additionalArguments, objectFile, sourceFile);
1405                 } else {
1406                         return String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), objectFile, sourceFile);
1407                 }
1408         }
1409
1410 #region WindowsToolchainSupport
1411
1412         class StringVersionComparer : IComparer<string> {
1413                 public int Compare (string stringA, string stringB)
1414                 {
1415                         Version versionA;
1416                         Version versionB;
1417
1418                         var versionAMatch = System.Text.RegularExpressions.Regex.Match (stringA, @"\d+(\.\d +) + ");
1419                         if (versionAMatch.Success)
1420                                 stringA = versionAMatch.ToString ();
1421
1422                         var versionBMatch = System.Text.RegularExpressions.Regex.Match (stringB, @"\d+(\.\d+)+");
1423                         if (versionBMatch.Success)
1424                                 stringB = versionBMatch.ToString ();
1425
1426                         if (Version.TryParse (stringA, out versionA) && Version.TryParse (stringB, out versionB))
1427                                 return versionA.CompareTo (versionB);
1428
1429                         return string.Compare (stringA, stringB, StringComparison.OrdinalIgnoreCase);
1430                 }
1431         }
1432
1433         class InstalledSDKInfo {
1434                 public InstalledSDKInfo (string name, string version, string installationFolder)
1435                 {
1436                         this.Name = name;
1437                         this.Version = Version.Parse (version);
1438                         this.InstallationFolder = installationFolder;
1439                         this.AdditionalSDKs = new List<InstalledSDKInfo> ();
1440                 }
1441
1442                 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion)
1443                         : this (name, version, installationFolder)
1444                 {
1445                         this.IsSubVersion = isSubVersion;
1446                 }
1447
1448                 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion, InstalledSDKInfo parentSDK)
1449                         : this (name, version, installationFolder, isSubVersion)
1450                 {
1451                         this.ParentSDK = parentSDK;
1452                 }
1453
1454                 public string Name { get; set; }
1455                 public Version Version { get; set; }
1456                 public string InstallationFolder { get; set; }
1457                 public bool IsSubVersion { get; set; }
1458                 public List<InstalledSDKInfo> AdditionalSDKs { get; }
1459                 public InstalledSDKInfo ParentSDK { get; set; }
1460         }
1461
1462         class ToolchainProgram {
1463                 public ToolchainProgram (string name, string path)
1464                 {
1465                         this.Name = name;
1466                         this.Path = path;
1467                 }
1468
1469                 public ToolchainProgram (string name, string path, InstalledSDKInfo parentSDK)
1470                         : this (name, path)
1471                 {
1472                         this.ParentSDK = parentSDK;
1473                 }
1474
1475                 public Func<string, string> QuoteArg = arg => "\"" + arg + "\"";
1476                 public string Name { get; set; }
1477                 public string Path { get; set; }
1478                 public InstalledSDKInfo ParentSDK { get; set; }
1479                 public bool IsVSToolChain { get { return (Name.Contains ("cl.exe") || Name.Contains ("lib.exe")); } }
1480                 public bool IsGCCToolChain { get { return !IsVSToolChain;  } }
1481         }
1482
1483         class SDKHelper {
1484                 static protected Microsoft.Win32.RegistryKey GetToolchainRegistrySubKey (string subKey)
1485                 {
1486                         Microsoft.Win32.RegistryKey key = null;
1487
1488                         if (Environment.Is64BitProcess) {
1489                                 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey) ??
1490                                         Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey);
1491                         }
1492
1493                         if (key == null) {
1494                                 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE" + subKey) ??
1495                                         Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE" + subKey);
1496                         }
1497
1498                         return key;
1499                 }
1500         }
1501
1502         class WindowsSDKHelper : SDKHelper {
1503                 List<InstalledSDKInfo> installedWindowsSDKs;
1504                 List<InstalledSDKInfo> installedCRuntimeSDKs;
1505                 InstalledSDKInfo installedWindowsSDK;
1506                 InstalledSDKInfo installedCRuntimeSDK;
1507
1508                 static WindowsSDKHelper singletonInstance = new WindowsSDKHelper ();
1509                 static public WindowsSDKHelper GetInstance ()
1510                 {
1511                         return singletonInstance;
1512                 }
1513
1514                 Dictionary<string, string> GetInstalledWindowsKitRootFolders ()
1515                 {
1516                         var rootFolders = new Dictionary<string, string> ();
1517
1518                         using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\Microsoft SDKs\Windows\")) {
1519                                 if (subKey != null) {
1520                                         foreach (var keyName in subKey.GetSubKeyNames ()) {
1521                                                 var keyNameIsVersion = System.Text.RegularExpressions.Regex.Match (keyName, @"\d+(\.\d+)+");
1522                                                 if (keyNameIsVersion.Success) {
1523                                                         var installFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString () + @"\" + keyName, "InstallationFolder", "");
1524                                                         if (!rootFolders.ContainsKey (installFolder))
1525                                                                 rootFolders.Add (installFolder, keyNameIsVersion.ToString ());
1526                                                 }
1527                                         }
1528                                 }
1529                         }
1530
1531                         using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\Windows Kits\Installed Roots")) {
1532                                 if (subKey != null) {
1533                                         foreach (var valueName in subKey.GetValueNames ()) {
1534                                                 var valueNameIsKitsRoot = System.Text.RegularExpressions.Regex.Match (valueName, @"KitsRoot\d*");
1535                                                 if (valueNameIsKitsRoot.Success) {
1536                                                         var installFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString (), valueName, "");
1537                                                         if (!rootFolders.ContainsKey (installFolder)) {
1538                                                                 var valueNameIsVersion = System.Text.RegularExpressions.Regex.Match (valueName, @"\d+(\.*\d+)+");
1539                                                                 if (valueNameIsVersion.Success)
1540                                                                         rootFolders.Add (installFolder, valueNameIsVersion.ToString ());
1541                                                                 else
1542                                                                         rootFolders.Add (installFolder, "");
1543                                                         }
1544                                                 }
1545                                         }
1546                                 }
1547                         }
1548
1549                         return rootFolders;
1550                 }
1551
1552                 void InitializeInstalledWindowsKits ()
1553                 {
1554                         if (installedWindowsSDKs == null && installedCRuntimeSDKs == null) {
1555                                 List<InstalledSDKInfo> windowsSDKs = new List<InstalledSDKInfo> ();
1556                                 List<InstalledSDKInfo> cRuntimeSDKs = new List<InstalledSDKInfo> ();
1557                                 var rootFolders = GetInstalledWindowsKitRootFolders ();
1558                                 foreach (var winKitRoot in rootFolders) {
1559                                         // Try to locate Windows and CRuntime SDKs.
1560                                         string winKitRootDir = winKitRoot.Key;
1561                                         string winKitRootVersion = winKitRoot.Value;
1562                                         string winKitIncludeDir = Path.Combine (winKitRootDir, "include");
1563
1564                                         //Search for installed SDK versions.
1565                                         if (Directory.Exists (winKitIncludeDir)) {
1566                                                 var winKitIncludeDirInfo = new DirectoryInfo (winKitIncludeDir);
1567                                                 var versions = winKitIncludeDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly)
1568                                                         .OrderByDescending (p => p.Name, new StringVersionComparer ());
1569
1570                                                 foreach (var version in versions) {
1571                                                         string versionedWindowsSDKHeaderPath = Path.Combine (version.FullName, "um", "windows.h");
1572                                                         string versionedCRuntimeSDKHeaderPath = Path.Combine (version.FullName, "ucrt", "stdlib.h");
1573                                                         var hasSubVersion = System.Text.RegularExpressions.Regex.Match (version.Name, @"\d+(\.\d+)+");
1574                                                         if (hasSubVersion.Success) {
1575                                                                 if (File.Exists (versionedWindowsSDKHeaderPath))
1576                                                                         //Found a specific Windows SDK sub version.
1577                                                                         windowsSDKs.Add (new InstalledSDKInfo ("WindowsSDK", hasSubVersion.ToString (), winKitRootDir, true));
1578                                                                 if (File.Exists (versionedCRuntimeSDKHeaderPath))
1579                                                                         //Found a specific CRuntime SDK sub version.
1580                                                                         cRuntimeSDKs.Add (new InstalledSDKInfo ("CRuntimeSDK", hasSubVersion.ToString (), winKitRootDir, true));
1581                                                         }
1582                                                 }
1583                                         }
1584
1585                                         // Try to find SDK without specific sub version.
1586                                         string windowsSDKHeaderPath = Path.Combine (winKitIncludeDir, "um", "windows.h");
1587                                         if (File.Exists (windowsSDKHeaderPath))
1588                                                 //Found a Windows SDK version.
1589                                                 windowsSDKs.Add (new InstalledSDKInfo ("WindowsSDK", winKitRootVersion, winKitRootDir, false));
1590
1591                                         string cRuntimeSDKHeaderPath = Path.Combine (winKitIncludeDir, "ucrt", "stdlib.h");
1592                                         if (File.Exists (cRuntimeSDKHeaderPath))
1593                                                 //Found a CRuntime SDK version.
1594                                                 cRuntimeSDKs.Add (new InstalledSDKInfo ("CRuntimeSDK", winKitRootVersion, winKitRootDir, false));
1595                                 }
1596
1597                                 // Sort based on version.
1598                                 windowsSDKs = windowsSDKs.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1599                                 cRuntimeSDKs = cRuntimeSDKs.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1600
1601                                 installedWindowsSDKs = windowsSDKs;
1602                                 installedCRuntimeSDKs = cRuntimeSDKs;
1603
1604                                 if (!quiet && installedWindowsSDKs != null) {
1605                                         Console.WriteLine ("--- Windows SDK's ---");
1606                                         foreach (var windowsSDK in installedWindowsSDKs) {
1607                                                 Console.WriteLine ("Path: " + windowsSDK.InstallationFolder);
1608                                                 Console.WriteLine ("Version: " + windowsSDK.Version);
1609                                         }
1610                                         Console.WriteLine ("---------------");
1611                                 }
1612
1613                                 if (!quiet && installedCRuntimeSDKs != null) {
1614                                         Console.WriteLine ("--- C-Runtime SDK's ---");
1615                                         foreach (var cRuntimeSDK in installedCRuntimeSDKs) {
1616                                                 Console.WriteLine ("Path: " + cRuntimeSDK.InstallationFolder);
1617                                                 Console.WriteLine ("Version: " + cRuntimeSDK.Version);
1618                                                 if (cRuntimeSDK.ParentSDK != null) {
1619                                                         Console.WriteLine ("Parent SDK Path: " + cRuntimeSDK.ParentSDK.InstallationFolder);
1620                                                         Console.WriteLine ("Parent SDK Version: " + cRuntimeSDK.ParentSDK.Version);
1621                                                 }
1622                                         }
1623                                         Console.WriteLine ("---------------");
1624                                 }
1625                         }
1626
1627                         return;
1628                 }
1629
1630                 List<InstalledSDKInfo> GetInstalledWindowsSDKs ()
1631                 {
1632                         if (installedWindowsSDKs == null)
1633                                 InitializeInstalledWindowsKits ();
1634
1635                         return installedWindowsSDKs;
1636                 }
1637
1638                 List<InstalledSDKInfo> GetInstalledCRuntimeSDKs ()
1639                 {
1640                         if (installedCRuntimeSDKs == null)
1641                                 InitializeInstalledWindowsKits ();
1642
1643                         return installedCRuntimeSDKs;
1644                 }
1645
1646                 InstalledSDKInfo GetInstalledWindowsSDK ()
1647                 {
1648                         if (installedWindowsSDK == null) {
1649                                 string winSDKDir = "";
1650                                 InstalledSDKInfo windowsSDK = null;
1651                                 List<InstalledSDKInfo> windowsSDKs = GetInstalledWindowsSDKs ();
1652
1653                                 // Check that env doesn't already include needed values.
1654                                 winSDKDir = GetEnv ("WINSDK", "");
1655                                 if (winSDKDir.Length == 0)
1656                                         // If executed from a VS developer command prompt, SDK dir set in env.
1657                                         winSDKDir = GetEnv ("WindowsSdkDir", "");
1658
1659                                 // Check that env doesn't already include needed values.
1660                                 // If executed from a VS developer command prompt, SDK version set in env.
1661                                 var winSDKVersion = System.Text.RegularExpressions.Regex.Match (GetEnv ("WindowsSdkVersion", ""), @"\d+(\.\d+)+");
1662
1663                                 if (winSDKDir.Length != 0 && windowsSDKs != null) {
1664                                         // Find installed SDK based on requested info.
1665                                         if (winSDKVersion.Success)
1666                                                 windowsSDK = windowsSDKs.Find (x => (x.InstallationFolder == winSDKDir && x.Version.ToString () == winSDKVersion.ToString ()));
1667                                         else
1668                                                 windowsSDK = windowsSDKs.Find (x => x.InstallationFolder == winSDKDir);
1669                                 }
1670
1671                                 if (windowsSDK == null && winSDKVersion.Success && windowsSDKs != null)
1672                                         // Find installed SDK based on requested info.
1673                                         windowsSDK = windowsSDKs.Find (x => x.Version.ToString () == winSDKVersion.ToString ());
1674
1675                                 if (windowsSDK == null && windowsSDKs != null)
1676                                         // Get latest installed verison.
1677                                         windowsSDK = windowsSDKs.First ();
1678
1679                                 installedWindowsSDK = windowsSDK;
1680                         }
1681
1682                         return installedWindowsSDK;
1683                 }
1684
1685                 string FindCRuntimeSDKIncludePath (InstalledSDKInfo sdk)
1686                 {
1687                         string cRuntimeIncludePath = Path.Combine (sdk.InstallationFolder, "include");
1688                         if (sdk.IsSubVersion)
1689                                 cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, sdk.Version.ToString ());
1690
1691                         cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, "ucrt");
1692                         if (!Directory.Exists (cRuntimeIncludePath))
1693                                 cRuntimeIncludePath = "";
1694
1695                         return cRuntimeIncludePath;
1696                 }
1697
1698                 string FindCRuntimeSDKLibPath (InstalledSDKInfo sdk)
1699                 {
1700                         string cRuntimeLibPath = Path.Combine (sdk.InstallationFolder, "lib");
1701                         if (sdk.IsSubVersion)
1702                                 cRuntimeLibPath = Path.Combine (cRuntimeLibPath, sdk.Version.ToString ());
1703
1704                         cRuntimeLibPath = Path.Combine (cRuntimeLibPath, "ucrt", Target64BitApplication () ? "x64" : "x86");
1705                         if (!Directory.Exists (cRuntimeLibPath))
1706                                 cRuntimeLibPath = "";
1707
1708                         return cRuntimeLibPath;
1709                 }
1710
1711                 InstalledSDKInfo GetInstalledCRuntimeSDK ()
1712                 {
1713                         if (installedCRuntimeSDK == null) {
1714                                 InstalledSDKInfo cRuntimeSDK = null;
1715                                 var windowsSDK = GetInstalledWindowsSDK ();
1716                                 var cRuntimeSDKs = GetInstalledCRuntimeSDKs ();
1717
1718                                 if (windowsSDK != null && cRuntimeSDKs != null) {
1719                                         cRuntimeSDK = cRuntimeSDKs.Find (x => x.Version.ToString () == windowsSDK.Version.ToString ());
1720                                         if (cRuntimeSDK == null && cRuntimeSDKs.Count != 0)
1721                                                 cRuntimeSDK = cRuntimeSDKs.First ();
1722
1723                                         installedCRuntimeSDK = cRuntimeSDK;
1724                                 }
1725                         }
1726
1727                         return installedCRuntimeSDK;
1728                 }
1729
1730                 public void AddWindowsSDKIncludePaths (List<string> includePaths)
1731                 {
1732                         InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1733                         if (winSDK != null) {
1734                                 string winSDKIncludeDir = Path.Combine (winSDK.InstallationFolder, "include");
1735
1736                                 if (winSDK.IsSubVersion)
1737                                         winSDKIncludeDir = Path.Combine (winSDKIncludeDir, winSDK.Version.ToString ());
1738
1739                                 // Include sub folders.
1740                                 if (Directory.Exists (winSDKIncludeDir)) {
1741                                         includePaths.Add (Path.Combine (winSDKIncludeDir, "um"));
1742                                         includePaths.Add (Path.Combine (winSDKIncludeDir, "shared"));
1743                                         includePaths.Add (Path.Combine (winSDKIncludeDir, "winrt"));
1744                                 }
1745                         }
1746
1747                         return;
1748                 }
1749
1750                 public void AddWindowsSDKLibPaths (List<string> libPaths)
1751                 {
1752                         InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1753                         if (winSDK != null) {
1754                                 string winSDKLibDir = Path.Combine (winSDK.InstallationFolder, "lib");
1755
1756                                 if (winSDK.IsSubVersion) {
1757                                         winSDKLibDir = Path.Combine (winSDKLibDir, winSDK.Version.ToString ());
1758                                 } else {
1759                                         // Older WinSDK's header folders are not versioned, but installed libraries are, use latest available version for now.
1760                                         var winSDKLibDirInfo = new DirectoryInfo (winSDKLibDir);
1761                                         var version = winSDKLibDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly)
1762                                                 .OrderByDescending (p => p.Name, new StringVersionComparer ()).FirstOrDefault ();
1763                                         if (version != null)
1764                                                 winSDKLibDir = version.FullName;
1765                                 }
1766
1767                                 //Enumerat lib sub folders.
1768                                 if (Directory.Exists (winSDKLibDir))
1769                                         libPaths.Add (Path.Combine (winSDKLibDir, "um", Target64BitApplication () ? "x64" : "x86"));
1770                         }
1771
1772                         return;
1773                 }
1774
1775                 public void AddCRuntimeSDKIncludePaths (List<string> includePaths)
1776                 {
1777                         InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1778                         if (cRuntimeSDK != null) {
1779                                 string cRuntimeSDKIncludeDir = FindCRuntimeSDKIncludePath (cRuntimeSDK);
1780
1781                                 if (cRuntimeSDKIncludeDir.Length != 0)
1782                                         includePaths.Add (cRuntimeSDKIncludeDir);
1783                         }
1784
1785                         return;
1786                 }
1787
1788                 public void AddCRuntimeSDKLibPaths (List<string> libPaths)
1789                 {
1790                         InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1791                         if (cRuntimeSDK != null) {
1792                                 string cRuntimeSDKLibDir = FindCRuntimeSDKLibPath (cRuntimeSDK);
1793
1794                                 if (cRuntimeSDKLibDir.Length != 0)
1795                                         libPaths.Add (cRuntimeSDKLibDir);
1796                         }
1797
1798                         return;
1799                 }
1800         }
1801
1802         class VisualStudioSDKHelper : SDKHelper {
1803                 List<InstalledSDKInfo> installedVisualStudioSDKs;
1804                 InstalledSDKInfo installedVisualStudioSDK;
1805
1806                 static VisualStudioSDKHelper singletonInstance = new VisualStudioSDKHelper ();
1807                 static public VisualStudioSDKHelper GetInstance ()
1808                 {
1809                         return singletonInstance;
1810                 }
1811
1812                 List<InstalledSDKInfo> InitializeInstalledVisualStudioSDKs ()
1813                 {
1814                         if (installedVisualStudioSDKs == null) {
1815                                 List<InstalledSDKInfo> sdks = new List<InstalledSDKInfo> ();
1816
1817                                 using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\VisualStudio\SxS\VS7")) {
1818                                         if (subKey != null) {
1819                                                 foreach (var keyName in subKey.GetValueNames ()) {
1820                                                         var vsInstalltionFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString (), keyName, "");
1821                                                         if (Directory.Exists (vsInstalltionFolder)) {
1822                                                                 var vsSDK = new InstalledSDKInfo ("VisualStudio", keyName, vsInstalltionFolder, false);
1823                                                                 var vcInstallationFolder = Path.Combine (vsInstalltionFolder, "VC");
1824
1825                                                                 if (Directory.Exists (vcInstallationFolder))
1826                                                                         vsSDK.AdditionalSDKs.Add (new InstalledSDKInfo ("VisualStudioVC", keyName, vcInstallationFolder, false, vsSDK));
1827
1828                                                                 sdks.Add (vsSDK);
1829                                                         }
1830                                                 }
1831                                         }
1832                                 }
1833
1834                                 // TODO: Add VS15 SetupConfiguration support.
1835                                 // To reduce dependecies use vswhere.exe, if available.
1836
1837                                 // Sort based on version.
1838                                 sdks = sdks.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1839                                 installedVisualStudioSDKs = sdks;
1840                         }
1841
1842                         return installedVisualStudioSDKs;
1843                 }
1844
1845                 string FindVisualStudioVCFolderPath (InstalledSDKInfo vcSDK, string subPath)
1846                 {
1847                         string folderPath = "";
1848                         if (vcSDK != null && vcSDK.ParentSDK != null) {
1849                                 if (IsVisualStudio14 (vcSDK.ParentSDK)) {
1850                                         folderPath = Path.Combine (vcSDK.InstallationFolder, subPath);
1851                                 } else if (IsVisualStudio15 (vcSDK.ParentSDK)) {
1852                                         string msvcVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "MSVC");
1853
1854                                         // Add latest found version of MSVC toolchain.
1855                                         if (Directory.Exists (msvcVersionPath)) {
1856                                                 var msvcVersionDirInfo = new DirectoryInfo (msvcVersionPath);
1857                                                 var versions = msvcVersionDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly)
1858                                                         .OrderByDescending (p => p.Name, new StringVersionComparer ());
1859
1860                                                 foreach (var version in versions) {
1861                                                         msvcVersionPath = Path.Combine (version.FullName, subPath);
1862                                                         if (Directory.Exists (msvcVersionPath)) {
1863                                                                 folderPath = msvcVersionPath;
1864                                                                 break;
1865                                                         }
1866                                                 }
1867                                         }
1868                                 }
1869                         }
1870
1871                         return folderPath;
1872                 }
1873
1874                 string FindVisualStudioVCLibSubPath (InstalledSDKInfo vcSDK)
1875                 {
1876                         string subPath = "";
1877
1878                         if (vcSDK != null && vcSDK.ParentSDK != null) {
1879                                 if (IsVisualStudio14 (vcSDK.ParentSDK))
1880                                         subPath = Target64BitApplication () ? @"lib\amd64" : "lib";
1881                                 else if (IsVisualStudio15 (vcSDK.ParentSDK))
1882                                         subPath = Target64BitApplication () ? @"lib\x64" : @"lib\x86";
1883                         }
1884
1885                         return subPath;
1886                 }
1887
1888                 public InstalledSDKInfo GetInstalledVisualStudioSDK ()
1889                 {
1890                         if (installedVisualStudioSDK == null) {
1891                                 List<InstalledSDKInfo> visualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1892                                 InstalledSDKInfo visualStudioSDK = null;
1893
1894                                 // Check that env doesn't already include needed values.
1895                                 // If executed from a VS developer command prompt, Visual Studio install dir set in env.
1896                                 string vsVersion = GetEnv ("VisualStudioVersion", "");
1897
1898                                 if (vsVersion.Length != 0 && visualStudioSDKs != null)
1899                                         // Find installed SDK based on requested info.
1900                                         visualStudioSDK = visualStudioSDKs.Find (x => x.Version.ToString () == vsVersion);
1901
1902                                 if (visualStudioSDK == null && visualStudioSDKs != null)
1903                                         // Get latest installed verison.
1904                                         visualStudioSDK = visualStudioSDKs.First ();
1905
1906                                 installedVisualStudioSDK = visualStudioSDK;
1907                         }
1908
1909                         return installedVisualStudioSDK;
1910                 }
1911
1912                 public InstalledSDKInfo GetInstalledVisualStudioVCSDK ()
1913                 {
1914                         InstalledSDKInfo visualStudioVCSDK = null;
1915
1916                         // Check that env doesn't already include needed values.
1917                         // If executed from a VS developer command prompt, Visual Studio install dir set in env.
1918                         string vcInstallDir = GetEnv ("VCINSTALLDIR", "");
1919                         if (vcInstallDir.Length != 0) {
1920                                 List<InstalledSDKInfo> installedVisualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1921                                 if (installedVisualStudioSDKs != null) {
1922                                         foreach (var currentInstalledSDK in installedVisualStudioSDKs) {
1923                                                 // Find installed SDK based on requested info.
1924                                                 visualStudioVCSDK = currentInstalledSDK.AdditionalSDKs.Find (x => x.InstallationFolder == vcInstallDir);
1925                                                 if (visualStudioVCSDK != null)
1926                                                         break;
1927                                         }
1928                                 }
1929                         }
1930
1931                         // Get latest installed VS VC SDK version.
1932                         if (visualStudioVCSDK == null) {
1933                                 var visualStudioSDK = GetInstalledVisualStudioSDK ();
1934                                 if (visualStudioSDK != null)
1935                                         visualStudioVCSDK = visualStudioSDK.AdditionalSDKs.Find (x => x.Name == "VisualStudioVC");
1936                         }
1937
1938                         return visualStudioVCSDK;
1939                 }
1940
1941                 public bool IsVisualStudio14 (InstalledSDKInfo vsSDK)
1942                 {
1943                         return vsSDK.Version.Major == 14 || vsSDK.Version.Major == 2015;
1944                 }
1945
1946                 public bool IsVisualStudio15 (InstalledSDKInfo vsSDK)
1947                 {
1948                         return vsSDK.Version.Major == 15 || vsSDK.Version.Major == 2017;
1949                 }
1950
1951                 public void AddVisualStudioVCIncludePaths (List<string> includePaths)
1952                 {
1953                         // Check that env doesn't already include needed values.
1954                         string vcIncludeDir = GetEnv ("VSINCLUDE", "");
1955                         if (vcIncludeDir.Length == 0) {
1956                                 var visualStudioVCSDK = GetInstalledVisualStudioVCSDK ();
1957                                 vcIncludeDir = FindVisualStudioVCFolderPath (visualStudioVCSDK, "include");
1958                         }
1959
1960                         if (vcIncludeDir.Length != 0)
1961                                 includePaths.Add (vcIncludeDir);
1962
1963                         return;
1964                 }
1965
1966                 public void AddVisualStudioVCLibPaths (List<string> libPaths)
1967                 {
1968                         // Check that env doesn't already include needed values.
1969                         string vcLibDir = GetEnv ("VSLIB", "");
1970                         if (vcLibDir.Length == 0) {
1971                                 var vcSDK = GetInstalledVisualStudioVCSDK ();
1972                                 vcLibDir = FindVisualStudioVCFolderPath (vcSDK, FindVisualStudioVCLibSubPath (vcSDK));
1973                         }
1974
1975                         if (vcLibDir.Length != 0)
1976                                 libPaths.Add (vcLibDir);
1977
1978                         return;
1979                 }
1980         }
1981
1982         class VCToolchainProgram {
1983                 protected ToolchainProgram toolchain;
1984                 public virtual bool IsVersion (InstalledSDKInfo vcSDK) { return false; }
1985                 public virtual ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK) { return null; }
1986         }
1987
1988         class VC14ToolchainProgram : VCToolchainProgram {
1989                 public override bool IsVersion (InstalledSDKInfo vcSDK)
1990                 {
1991                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
1992                 }
1993
1994                 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
1995                 {
1996                         if (toolchain == null) {
1997                                 string toolPath = "";
1998                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
1999                                         if (Target64BitApplication ())
2000                                                 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", "amd64", tool });
2001                                         else
2002                                                 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", tool });
2003
2004                                         if (!File.Exists (toolPath))
2005                                                 toolPath = "";
2006                                 }
2007
2008                                 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2009                         }
2010
2011                         return toolchain;
2012                 }
2013         }
2014
2015         class VC15ToolchainProgram : VCToolchainProgram {
2016                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2017                 {
2018                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2019                 }
2020
2021                 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
2022                 {
2023                         if (toolchain == null) {
2024                                 string toolPath = "";
2025                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2026                                         string toolsVersionFilePath = Path.Combine (vcSDK.InstallationFolder, "Auxiliary", "Build", "Microsoft.VCToolsVersion.default.txt");
2027                                         string toolsVersion = File.ReadAllLines (toolsVersionFilePath).ElementAt (0).Trim ();
2028                                         string toolsVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "MSVC", toolsVersion);
2029
2030                                         if (Target64BitApplication ())
2031                                                 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX64", "x64", tool);
2032                                         else
2033                                                 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX86", "x86", tool);
2034                                 }
2035
2036                                 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2037                         }
2038
2039                         return toolchain;
2040                 }
2041         }
2042
2043         class VC14Compiler : VC14ToolchainProgram {
2044                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2045                 {
2046                         return FindVCToolchainProgram ("cl.exe", vcSDK);
2047                 }
2048         }
2049
2050         class VC15Compiler : VC15ToolchainProgram {
2051                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2052                 {
2053                         return FindVCToolchainProgram ("cl.exe", vcSDK);
2054                 }
2055         }
2056
2057         class VC14Librarian : VC14ToolchainProgram {
2058                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2059                 {
2060                         return FindVCToolchainProgram ("lib.exe", vcSDK);
2061                 }
2062         }
2063
2064         class VC15Librarian : VC15ToolchainProgram {
2065                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2066                 {
2067                         return FindVCToolchainProgram ("lib.exe", vcSDK);
2068                 }
2069         }
2070
2071         class VC14Clang : VCToolchainProgram {
2072                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2073                 {
2074                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2075                 }
2076
2077                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2078                 {
2079                         if (toolchain == null) {
2080                                 string clangPath = "";
2081                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2082                                         clangPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "ClangC2", "bin", Target64BitApplication () ? "amd64" : "x86", "clang.exe" });
2083
2084                                         if (!File.Exists (clangPath))
2085                                                 clangPath = "";
2086                                 }
2087
2088                                 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2089                         }
2090
2091                         return toolchain;
2092                 }
2093         }
2094
2095         class VC15Clang : VCToolchainProgram {
2096                 public override bool IsVersion (InstalledSDKInfo vcSDK)
2097                 {
2098                         return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2099                 }
2100
2101                 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2102                 {
2103                         if (toolchain == null) {
2104                                 string clangPath = "";
2105                                 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2106                                         string clangVersionFilePath = Path.Combine (vcSDK.InstallationFolder, "Auxiliary", "Build", "Microsoft.ClangC2Version.default.txt");
2107                                         string clangVersion = File.ReadAllLines (clangVersionFilePath).ElementAt (0).Trim ();
2108                                         string clangVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "ClangC2", clangVersion);
2109
2110                                         clangPath = Path.Combine (clangVersionPath, "bin", Target64BitApplication () ? "HostX64" : "HostX86", "clang.exe");
2111                                 }
2112
2113                                 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2114                         }
2115
2116                         return toolchain;
2117                 }
2118         }
2119
2120         class VisualStudioSDKToolchainHelper {
2121                 List<VCToolchainProgram> vcCompilers = new List<VCToolchainProgram> ();
2122                 List<VCToolchainProgram> vcLibrarians = new List<VCToolchainProgram> ();
2123                 List<VCToolchainProgram> vcClangCompilers = new List<VCToolchainProgram> ();
2124
2125                 public VisualStudioSDKToolchainHelper ()
2126                 {
2127                         vcCompilers.Add (new VC14Compiler ());
2128                         vcCompilers.Add (new VC15Compiler ());
2129
2130                         vcLibrarians.Add (new VC14Librarian ());
2131                         vcLibrarians.Add (new VC15Librarian ());
2132
2133                         vcClangCompilers.Add (new VC14Clang ());
2134                         vcClangCompilers.Add (new VC15Clang ());
2135                 }
2136
2137                 static VisualStudioSDKToolchainHelper singletonInstance = new VisualStudioSDKToolchainHelper ();
2138                 static public VisualStudioSDKToolchainHelper GetInstance ()
2139                 {
2140                         return singletonInstance;
2141                 }
2142
2143                 ToolchainProgram GetVCToolChainProgram (List<VCToolchainProgram> programs)
2144                 {
2145                         var vcSDK = VisualStudioSDKHelper.GetInstance ().GetInstalledVisualStudioVCSDK ();
2146                         if (vcSDK?.ParentSDK != null) {
2147                                 foreach (var item in programs) {
2148                                         if (item.IsVersion (vcSDK.ParentSDK)) {
2149                                                 return item.FindVCToolchainProgram (vcSDK);
2150                                         }
2151                                 }
2152                         }
2153
2154                         return null;
2155                 }
2156
2157                 public ToolchainProgram GetVCCompiler ()
2158                 {
2159                         return GetVCToolChainProgram (vcCompilers);
2160                 }
2161
2162                 public ToolchainProgram GetVCLibrarian ()
2163                 {
2164                         return GetVCToolChainProgram (vcLibrarians);
2165                 }
2166
2167                 public ToolchainProgram GetVCClangCompiler ()
2168                 {
2169                         return GetVCToolChainProgram (vcClangCompilers);
2170                 }
2171         }
2172
2173         static bool Target64BitApplication ()
2174         {
2175                 // Should probably handled the --cross and sdk parameters.
2176                 return Environment.Is64BitProcess;
2177         }
2178
2179         static string GetMonoDir ()
2180         {
2181                 // Check that env doesn't already include needed values.
2182                 string monoInstallDir = GetEnv ("MONOPREFIX", "");
2183                 if (monoInstallDir.Length == 0) {
2184                         using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey (Microsoft.Win32.RegistryHive.LocalMachine,
2185                                 Target64BitApplication () ? Microsoft.Win32.RegistryView.Registry64 : Microsoft.Win32.RegistryView.Registry32)) {
2186
2187                                 if (baseKey != null) {
2188                                         using (var subKey = baseKey.OpenSubKey (@"SOFTWARE\Mono")) {
2189                                                 if (subKey != null)
2190                                                         monoInstallDir = (string)subKey.GetValue ("SdkInstallRoot", "");
2191                                         }
2192                                 }
2193                         }
2194                 }
2195
2196                 return monoInstallDir;
2197         }
2198
2199         static void AddMonoIncludePaths (List<string> includePaths)
2200         {
2201                 includePaths.Add (Path.Combine (GetMonoDir (), @"include\mono-2.0"));
2202                 return;
2203         }
2204
2205         static void AddMonoLibPaths (List<string> libPaths)
2206         {
2207                 libPaths.Add (Path.Combine (GetMonoDir (), "lib"));
2208                 return;
2209         }
2210
2211         static void AddIncludePaths (List<string> includePaths)
2212         {
2213                 // Check that env doesn't already include needed values.
2214                 // If executed from a VS developer command prompt, all includes are already setup in env.
2215                 string includeEnv = GetEnv ("INCLUDE", "");
2216                 if (includeEnv.Length == 0) {
2217                         VisualStudioSDKHelper.GetInstance ().AddVisualStudioVCIncludePaths (includePaths);
2218                         WindowsSDKHelper.GetInstance ().AddCRuntimeSDKIncludePaths (includePaths);
2219                         WindowsSDKHelper.GetInstance ().AddWindowsSDKIncludePaths (includePaths);
2220                 }
2221
2222                 AddMonoIncludePaths (includePaths);
2223                 includePaths.Add (".");
2224
2225                 return;
2226         }
2227
2228         static void AddLibPaths (List<string> libPaths)
2229         {
2230                 // Check that env doesn't already include needed values.
2231                 // If executed from a VS developer command prompt, all libs are already setup in env.
2232                 string libEnv = GetEnv ("LIB", "");
2233                 if (libEnv.Length == 0) {
2234                         VisualStudioSDKHelper.GetInstance ().AddVisualStudioVCLibPaths (libPaths);
2235                         WindowsSDKHelper.GetInstance ().AddCRuntimeSDKLibPaths (libPaths);
2236                         WindowsSDKHelper.GetInstance ().AddWindowsSDKLibPaths (libPaths);
2237                 }
2238
2239                 AddMonoLibPaths (libPaths);
2240                 libPaths.Add (".");
2241
2242                 return;
2243         }
2244
2245         static void AddVCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2246         {
2247                 linkerArgs.Add ("kernel32.lib");
2248                 linkerArgs.Add ("version.lib");
2249                 linkerArgs.Add ("ws2_32.lib");
2250                 linkerArgs.Add ("mswsock.lib");
2251                 linkerArgs.Add ("psapi.lib");
2252                 linkerArgs.Add ("shell32.lib");
2253                 linkerArgs.Add ("oleaut32.lib");
2254                 linkerArgs.Add ("ole32.lib");
2255                 linkerArgs.Add ("winmm.lib");
2256                 linkerArgs.Add ("user32.lib");
2257                 linkerArgs.Add ("advapi32.lib");
2258
2259                 if (staticLinkCRuntime) {
2260                         // Static release c-runtime support.
2261                         linkerArgs.Add ("libucrt.lib");
2262                         linkerArgs.Add ("libvcruntime.lib");
2263                         linkerArgs.Add ("libcmt.lib");
2264                         linkerArgs.Add ("oldnames.lib");
2265                 } else {
2266                         // Dynamic release c-runtime support.
2267                         linkerArgs.Add ("ucrt.lib");
2268                         linkerArgs.Add ("vcruntime.lib");
2269                         linkerArgs.Add ("msvcrt.lib");
2270                         linkerArgs.Add ("oldnames.lib");
2271                 }
2272
2273                 return;
2274         }
2275
2276         static void AddGCCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2277         {
2278                 if (MakeBundle.compress)
2279                         linkerArgs.Add ("-lz");
2280
2281                 return;
2282         }
2283
2284         static void AddSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2285         {
2286                 if (program.IsVSToolChain)
2287                         AddVCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2288                 else
2289                         AddGCCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2290
2291                 return;
2292         }
2293
2294         static void AddMonoLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArguments)
2295         {
2296                 bool vsToolChain = program.IsVSToolChain;
2297                 string libPrefix = !vsToolChain ? "-l" : "";
2298                 string libExtension = vsToolChain ? ".lib" : "";
2299                 string monoLibrary = GetEnv ("LIBMONO", "");
2300
2301                 if (monoLibrary.Length == 0) {
2302                         if (staticLinkMono) {
2303                                 if (program.IsGCCToolChain) {
2304                                         Console.WriteLine (     @"Warning: Static linking using default Visual Studio build libmono-static-sgen" +
2305                                                                 @"might cause link errors when using GCC toolchain.");
2306                                 }
2307                                 monoLibrary = "libmono-static-sgen";
2308                         } else {
2309                                 monoLibrary = "mono-2.0-sgen";
2310                         }
2311                 }
2312
2313                 if (!Path.IsPathRooted (monoLibrary)) {
2314                         if (!monoLibrary.EndsWith (libExtension))
2315                                 monoLibrary = monoLibrary + libExtension;
2316
2317                         linkerArguments.Add (libPrefix + monoLibrary);
2318                 } else {
2319                         linkerArguments.Add (monoLibrary);
2320                 }
2321
2322                 return;
2323         }
2324
2325         static void AddVCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2326         {
2327                 List<string> includePaths = new List<string> ();
2328                 AddIncludePaths (includePaths);
2329
2330                 if (staticLinkCRuntime)
2331                         // Add targeted c-runtime (MT = static release).
2332                         compilerArgs.Add ("/MT");
2333                 else
2334                         // Add targeted c-runtime (MD = dynamic release).
2335                         compilerArgs.Add ("/MD");
2336
2337                 // Add include search paths.
2338                 foreach (string include in includePaths)
2339                         compilerArgs.Add (String.Format("/I {0}", program.QuoteArg (include)));
2340
2341                 return;
2342         }
2343
2344         static void AddGCCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2345         {
2346                 List<string> includePaths = new List<string> ();
2347                 AddMonoIncludePaths (includePaths);
2348
2349                 // Add include search paths.
2350                 foreach (string include in includePaths)
2351                         compilerArgs.Add (String.Format ("-I {0}", program.QuoteArg (include)));
2352
2353                 return;
2354         }
2355
2356         static void AddCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2357         {
2358                 if (program.IsVSToolChain)
2359                         AddVCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2360                 else
2361                         AddGCCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2362
2363                 return;
2364         }
2365
2366         static void AddVCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2367         {
2368                 linkerArgs.Add ("/link");
2369
2370                 var subsystem = GetEnv ("VCSUBSYSTEM", "windows");
2371                 linkerArgs.Add ("/SUBSYSTEM:" + subsystem);
2372
2373                 if (customMain != null && customMain.Length != 0)
2374                         linkerArgs.Add (linker.QuoteArg (customMain));
2375                 else
2376                         linkerArgs.Add ("/ENTRY:mainCRTStartup");
2377
2378                 // Ignore other c-runtime directives from linked libraries.
2379                 linkerArgs.Add ("/NODEFAULTLIB");
2380
2381                 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2382                 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2383
2384                 // Add library search paths.
2385                 List<string> libPaths = new List<string> ();
2386                 AddLibPaths (libPaths);
2387
2388                 foreach (string lib in libPaths)
2389                         linkerArgs.Add (String.Format ("/LIBPATH:{0}", linker.QuoteArg (lib)));
2390
2391                 // Linker output target.
2392                 linkerArgs.Add ("/OUT:" + linker.QuoteArg (outputFile));
2393
2394                 return;
2395         }
2396
2397         static void AddGCCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2398         {
2399                 // Add library search paths.
2400                 List<string> libPaths = new List<string> ();
2401                 AddMonoLibPaths (libPaths);
2402
2403                 foreach (string lib in libPaths)
2404                         linkerArgs.Add (String.Format ("-L {0}", linker.QuoteArg (lib)));
2405
2406                 // Add libraries.
2407                 if (staticLinkMono)
2408                         linkerArgs.Add ("-Wl,-Bstatic");
2409
2410                 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2411
2412                 if (staticLinkMono)
2413                         linkerArgs.Add ("-Wl,-Bdynamic");
2414
2415                 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2416
2417                 // Linker output target.
2418                 linkerArgs.Add ("-o " + linker.QuoteArg (outputFile));
2419         }
2420
2421         static void AddLinkerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2422         {
2423                 if (program.IsVSToolChain)
2424                         AddVCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2425                 else
2426                         AddGCCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2427
2428                 return;
2429         }
2430
2431         static void AddVCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2432         {
2433                 compilerArgs.Add ("/c");
2434                 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2435
2436                 objectFile = sourceFile + ".obj";
2437                 compilerArgs.Add (String.Format ("/Fo" + compiler.QuoteArg (objectFile)));
2438
2439                 return;
2440         }
2441
2442         static void AddGCCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2443         {
2444                 compilerArgs.Add ("-c");
2445                 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2446
2447                 objectFile = sourceFile + ".o";
2448                 compilerArgs.Add (String.Format ("-o " + compiler.QuoteArg (objectFile)));
2449
2450                 return;
2451         }
2452
2453         static void AddVCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2454         {
2455                 foreach (var objectFile in objectFiles)
2456                         librarianArgs.Add (librarian.QuoteArg (objectFile));
2457
2458                 // Add library search paths.
2459                 List<string> libPaths = new List<string> ();
2460                 AddLibPaths (libPaths);
2461
2462                 foreach (string lib in libPaths) {
2463                         librarianArgs.Add (String.Format ("/LIBPATH:{0}", librarian.QuoteArg (lib)));
2464                 }
2465
2466                 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2467
2468                 librarianArgs.Add ("/OUT:" + librarian.QuoteArg (output));
2469
2470                 return;
2471         }
2472
2473         static void AddGCCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2474         {
2475                 foreach (var objectFile in objectFiles)
2476                         librarianArgs.Add (librarian.QuoteArg (objectFile));
2477
2478                 // Add library search paths.
2479                 List<string> libPaths = new List<string> ();
2480                 AddMonoLibPaths (libPaths);
2481
2482                 foreach (string lib in libPaths)
2483                         librarianArgs.Add (String.Format ("-L {0}", librarian.QuoteArg (lib)));
2484
2485                 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2486
2487                 librarianArgs.Add ("-o " + librarian.QuoteArg (output));
2488
2489                 return;
2490         }
2491
2492         static ToolchainProgram GetAssemblerCompiler ()
2493         {
2494                 // First check if env is set (old behavior) and use that.
2495                 string assembler = GetEnv ("AS", "");
2496                 if (assembler.Length != 0)
2497                         return new ToolchainProgram ("AS", assembler);
2498
2499                 var vcClangAssembler = VisualStudioSDKToolchainHelper.GetInstance ().GetVCClangCompiler ();
2500                 if (vcClangAssembler == null) {
2501                         // Fallback to GNU assembler if clang for VS was not installed.
2502                         // Why? because mkbundle generates GNU assembler not compilable by VS tools like ml.
2503                         Console.WriteLine (@"Warning: Couldn't find installed Visual Studio SDK, fallback to as.exe and default environment.");
2504                         return new ToolchainProgram ("AS", "as.exe");
2505                 }
2506
2507                 return vcClangAssembler;
2508         }
2509
2510         static ToolchainProgram GetCCompiler ()
2511         {
2512                 // First check if env is set (old behavior) and use that.
2513                 string compiler = GetEnv ("CC", "");
2514                 if (compiler.Length != 0)
2515                         return new ToolchainProgram ("CC", compiler);
2516
2517                 var vcCompiler = VisualStudioSDKToolchainHelper.GetInstance ().GetVCCompiler ();
2518                 if (vcCompiler == null) {
2519                         // Fallback to cl.exe if VC compiler was not installed.
2520                         Console.WriteLine (@"Warning: Couldn't find installed Visual Studio SDK, fallback to cl.exe and default environment.");
2521                         return new ToolchainProgram ("cl.exe", "cl.exe");
2522                 }
2523
2524                 return vcCompiler;
2525         }
2526
2527         static ToolchainProgram GetLibrarian ()
2528         {
2529                 ToolchainProgram vcLibrarian = VisualStudioSDKToolchainHelper.GetInstance ().GetVCLibrarian ();
2530                 if (vcLibrarian == null) {
2531                         // Fallback to lib.exe if VS was not installed.
2532                         Console.WriteLine (@"Warning: Couldn't find installed Visual Studio SDK, fallback to lib.exe and default environment.");
2533                         return new ToolchainProgram ("lib.exe", "lib.exe");
2534                 }
2535
2536                 return vcLibrarian;
2537         }
2538
2539         static string GetCompileAndLinkCommand (ToolchainProgram compiler, string sourceFile, string objectFile, string customMain, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2540         {
2541                 var compilerArgs = new List<string> ();
2542
2543                 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2544
2545                 // Add source file to compile.
2546                 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2547
2548                 // Add assembled object file.
2549                 compilerArgs.Add (compiler.QuoteArg (objectFile));
2550
2551                 // Add linker arguments.
2552                 AddLinkerArguments (compiler, staticLinkMono, staticLinkCRuntime, customMain, outputFile, compilerArgs);
2553
2554                 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs));
2555         }
2556
2557         static string GetLibrarianCompilerCommand (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, out string objectFile)
2558         {
2559                 var compilerArgs = new List<string> ();
2560
2561                 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2562
2563                 if (compiler.IsVSToolChain)
2564                         AddVCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2565                 else
2566                         AddGCCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2567
2568                 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs));
2569         }
2570
2571         static string GetLibrarianLinkerCommand (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2572         {
2573                 var librarianArgs = new List<string> ();
2574
2575                 if (librarian.IsVSToolChain)
2576                         AddVCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2577                 else
2578                         AddGCCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2579
2580                 return String.Format ("{0} {1}", librarian.QuoteArg (librarian.Path), String.Join (" ", librarianArgs));
2581         }
2582 #endregion
2583 }