2 // mkbundle: tool to create bundles.
4 // Based on the `make-bundle' Perl script written by Paolo Molaro (lupus@debian.org)
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
19 // (C) Novell, Inc 2004
20 // (C) 2016 Xamarin Inc
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
27 using System.Diagnostics;
29 using System.Collections.Generic;
31 using System.IO.Compression;
32 using System.Runtime.InteropServices;
34 using IKVM.Reflection;
37 using System.Threading.Tasks;
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 = "";
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 [] {
73 static string [] i18n_all = new string [] {
81 static string target_server = "https://download.mono-project.com/runtimes/raw/";
83 static int Main (string [] args)
85 List<string> sources = new List<string> ();
86 int top = args.Length;
91 for (int i = 0; i < top; i++){
93 case "--help": case "-h": case "-?":
111 var iarg = args [++i];
114 else if (iarg == "none")
115 i18n = new string [0];
117 i18n = iarg.Split (',');
128 case "--local-targets":
129 CommandLocalTargets ();
137 if (sdk_path != null || runtime != null)
138 Error ("You can only specify one of --runtime, --sdk or --cross");
141 cross_target = args [++i];
150 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
154 var lspec = args [++i];
155 var p = lspec.IndexOf (",");
158 alias = Path.GetFileName (lspec);
161 alias = lspec.Substring (0, p);
162 path = lspec.Substring (p+1);
164 if (!File.Exists (path))
165 Error ($"The specified library file {path} does not exist");
166 libraries [alias] = path;
169 case "--fetch-target":
174 fetch_target = args [++i];
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);
184 case "--target-server":
189 target_server = args [++i];
205 embedded_options = args [++i];
214 sdk_path = args [++i];
215 if (cross_target != null || runtime != null)
216 Error ("You can only specify one of --runtime, --sdk or --cross");
223 if (sdk_path != null || cross_target != null)
224 Error ("You can only specify one of --runtime, --sdk or --cross");
227 runtime = args [++i];
234 object_out = args [++i];
242 link_paths.Add (args [++i]);
266 config_file = args [++i];
268 case "--machine-config":
274 machine_config_file = args [++i];
277 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
285 config_dir = args [++i];
293 case "--custom-main":
298 custom_main = args [++i];
312 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
320 case "--static-ctor":
325 ctor_func = args [++i];
328 case "--dos2unix=true":
331 case "--dos2unix=false":
332 use_dos2unix = false;
344 var env = args [++i];
345 p = env.IndexOf ('=');
347 environment.Add (env, "");
349 environment.Add (env.Substring (0, p), env.Substring (p+1));
351 case "--bundled-header":
352 bundled_header = true;
355 sources.Add (args [i]);
360 // Modern bundling starts here
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);
370 sdk_path = Path.Combine (targets_dir, cross_target);
371 Console.WriteLine ("From: " + sdk_path);
372 VerifySdk (sdk_path);
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}");
384 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
387 wc.DownloadFile (uri, zip_download);
388 ZipFile.ExtractToDirectory(zip_download, directory);
389 File.Delete (zip_download);
391 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
392 File.Delete (zip_download);
399 Console.WriteLine (os_message);
400 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
403 if (sources.Count == 0 || output == null) {
405 Environment.Exit (1);
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))
415 GenerateBundles (files);
417 GeneratePackage (files);
419 Console.WriteLine ("Generated {0}", output);
424 static void VerifySdk (string path)
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);
437 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
439 static void CommandLocalTargets ()
443 Console.WriteLine ("Available targets locally:");
444 Console.WriteLine ("\tdefault\t- Current System Mono");
446 targets = Directory.GetDirectories (targets_dir);
450 foreach (var target in targets){
451 var p = Path.Combine (target, "bin", "mono");
453 Console.WriteLine ("\t{0}", Path.GetFileName (target));
457 static void WriteSymbol (StreamWriter sw, string name, long size)
463 "\t.section .rodata\n" +
465 "\t.type {0}, \"object\"\n" +
466 "\t.size {0}, {1}\n" +
472 "\t.section __TEXT,__text,regular,pure_instructions\n" +
480 string mangled_symbol_name = "";
481 if (Target64BitApplication())
482 mangled_symbol_name = name;
484 mangled_symbol_name = "_" + name;
488 "\t.section .rdata,\"dr\"\n" +
491 mangled_symbol_name);
496 static string [] chars = new string [256];
498 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
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 ());
508 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
510 for (int i = 0; i < n; i++) {
511 if (count % 32 == 0) {
512 ts.Write ("\n\t.byte ");
516 ts.Write (chars [buffer [i]]);
525 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
526 const int align = 4096;
529 public PackageMaker (string output)
531 package = File.Create (output, 128*1024);
533 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
537 public int AddFile (string fname)
539 using (Stream fileStream = File.OpenRead (fname)){
540 var ret = fileStream.Length;
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));
551 public void Add (string entry, string fname)
553 var p = package.Position;
554 var size = AddFile (fname);
556 locations [entry] = Tuple.Create(p, size);
559 public void AddString (string entry, string text)
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));
567 public void AddStringPair (string entry, string key, string value)
569 var kbytes = Encoding.UTF8.GetBytes (key);
570 var vbytes = Encoding.UTF8.GetBytes (value);
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);
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));
591 foreach (var floc in locations.Keys){
592 Console.WriteLine ($"{floc} at {locations[floc]:x}");
596 public void WriteIndex ()
598 var indexStart = package.Position;
599 var binary = new BinaryWriter (package);
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);
610 binary.Write (indexStart);
611 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
623 static bool MaybeAddFile (PackageMaker maker, string code, string file)
628 if (!File.Exists (file)){
629 Error ("The file {0} does not exist", file);
632 maker.Add (code, file);
633 // add a space after code (="systemconfig:" or "machineconfig:")
634 Console.WriteLine (code + " " + file);
638 static bool GeneratePackage (List<string> files)
640 if (runtime == null){
642 runtime = Process.GetCurrentProcess().MainModule.FileName;
644 Error ("You must specify at least one runtime with --runtime or --cross");
645 Environment.Exit (1);
648 if (!File.Exists (runtime)){
649 Error ($"The specified runtime at {runtime} does not exist");
650 Environment.Exit (1);
653 if (ctor_func != null){
654 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
658 var maker = new PackageMaker (output);
659 Console.WriteLine ("Using runtime: " + runtime);
660 maker.AddFile (runtime);
662 foreach (var url in files){
663 string fname = LocateFile (new Uri (url).LocalPath);
664 string aname = MakeBundle.GetAssemblyName (fname);
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");
674 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
677 if (config_dir != null){
678 maker.Add ("config_dir:", config_dir);
679 Console.WriteLine (" Config_dir: " + config_dir );
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]);
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);
698 static void GenerateBundles (List<string> files)
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";
706 if (object_out != null)
710 List<string> c_bundle_names = new List<string> ();
711 List<string[]> config_names = new List<string[]> ();
713 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
714 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
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");
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);
730 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
731 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
735 tc.WriteLine ("typedef struct _compressed_data {");
736 tc.WriteLine ("\tMonoBundledAssembly assembly;");
737 tc.WriteLine ("\tint compressed_size;");
738 tc.WriteLine ("} CompressedAssembly;\n");
741 object monitor = new object ();
743 var streams = new Dictionary<string, Stream> ();
744 var sizes = new Dictionary<string, long> ();
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);
751 long real_size = stream.Length;
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);
762 byte [] bytes = ms.GetBuffer ();
763 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
767 streams [url] = stream;
768 sizes [url] = real_size;
774 Parallel.ForEach (files, body);
776 foreach (var url in files)
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, "_");
792 var stream = streams [url];
793 var real_size = sizes [url];
796 Console.WriteLine (" embedding: " + fname);
798 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
800 WriteBuffer (ts, stream, buffer);
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);
808 double ratio = ((double) stream.Length * 100) / real_size;
809 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
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);
818 c_bundle_names.Add ("assembly_bundle_" + encoded);
821 FileStream cf = File.OpenRead (fname + ".config");
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);
828 config_names.Add (new string[] {aname, encoded});
829 } catch (FileNotFoundException) {
830 /* we ignore if the config file doesn't exist */
834 if (config_file != null){
837 conf = File.OpenRead (config_file);
839 Error ("Failure to open {0}", config_file);
843 Console.WriteLine ("System config from: " + config_file);
844 tc.WriteLine ("extern const char system_config;");
845 WriteSymbol (ts, "system_config", config_file.Length);
847 WriteBuffer (ts, conf, buffer);
849 ts.Write ("\t.byte 0\n");
853 if (machine_config_file != null){
856 conf = File.OpenRead (machine_config_file);
858 Error ("Failure to open {0}", machine_config_file);
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);
866 WriteBuffer (ts, conf, buffer);
867 ts.Write ("\t.byte 0\n");
873 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
875 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
877 foreach (string c in c_bundle_names){
878 tc.WriteLine ("\t&{0},", c);
880 tc.WriteLine ("\tNULL\n};\n");
881 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
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);
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]);
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");
899 if (config_dir != null)
900 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
902 tc.WriteLine ("static const char *config_dir = NULL;");
904 Stream template_stream;
906 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
908 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
911 StreamReader s = new StreamReader (template_stream);
912 string template = s.ReadToEnd ();
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);
924 string as_cmd = GetAssemblerCommand (temp_s, temp_o);
931 Console.WriteLine("Compiling:");
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);
940 string temp_c_o = "";
942 string cl_cmd = GetLibrarianCompilerCommand (compiler, temp_c, static_link, staticLinkCRuntime, out temp_c_o);
945 ToolchainProgram librarian = GetLibrarian ();
946 string lib_cmd = GetLibrarianLinkerCommand (librarian, new string[] { temp_o, temp_c_o }, static_link, staticLinkCRuntime, output);
949 File.Delete (temp_c_o);
956 string zlib = (compress ? "-lz" : "");
957 string objc = (style == "osx" ? "-framework CoreFoundation -lobjc" : "");
958 string debugging = "-g";
959 string cc = GetEnv("CC", "cc");
962 if (style == "linux")
968 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
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);
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);
986 Console.WriteLine ("Done");
991 if (object_out == null){
992 File.Delete (temp_o);
995 File.Delete (temp_c);
997 File.Delete (temp_s);
1002 static List<string> LoadAssemblies (List<string> sources)
1004 List<string> assemblies = new List<string> ();
1007 foreach (string name in sources){
1009 Assembly a = LoadAssemblyFile (name);
1016 assemblies.Add (a.CodeBase);
1017 } catch (Exception) {
1020 Console.WriteLine ("File will not be scanned: {0}", name);
1021 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1029 Error ("Couldn't load one or more of the assemblies.");
1030 Environment.Exit (1);
1036 static void LoadLocalizedAssemblies (List<string> assemblies)
1038 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1039 string error = null;
1041 foreach (string name in other) {
1043 Assembly a = LoadAssembly (name);
1046 error = "Failed to load " + name;
1050 assemblies.Add (a.CodeBase);
1051 } catch (Exception) {
1054 Console.WriteLine ("File will not be scanned: {0}", name);
1055 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
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);
1068 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1071 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1072 Environment.Exit (1);
1077 static readonly Universe universe = new Universe ();
1078 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1080 public static string GetAssemblyName (string path)
1082 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1083 string name = Path.GetFileName (path);
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);
1092 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1093 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1095 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1101 static bool QueueAssembly (List<string> files, string codebase)
1103 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1104 if (files.Contains (codebase))
1107 var path = new Uri(codebase).LocalPath;
1108 var name = GetAssemblyName (path);
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);
1115 loaded_assemblies.Add (name, path);
1117 files.Add (codebase);
1121 Assembly a = universe.LoadFile (path);
1123 Error ("Unable to to load assembly `{0}'", path);
1127 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1128 a = LoadAssembly (an.Name);
1130 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1134 if (!QueueAssembly (files, a.CodeBase))
1137 } catch (Exception) {
1146 // Loads an assembly from a specific path
1148 static Assembly LoadAssemblyFile (string assembly)
1154 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1155 a = universe.LoadFile (assembly);
1157 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1159 } catch (FileNotFoundException){
1160 Error ($"Cannot find assembly `{assembly}'");
1161 } catch (IKVM.Reflection.BadImageFormatException f) {
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)");
1174 // Loads an assembly from any of the link directories provided
1176 static Assembly LoadAssembly (string assembly)
1178 string total_log = "";
1179 foreach (string dir in link_paths){
1180 string full_path = Path.Combine (dir, assembly);
1182 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1183 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1184 full_path += ".dll";
1187 var a = universe.LoadFile (full_path);
1189 } catch (FileNotFoundException ff) {
1190 total_log += ff.FusionLog;
1195 Console.WriteLine ("Log: \n" + total_log);
1199 static void Error (string msg, params object [] args)
1201 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1202 Environment.Exit (1);
1207 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\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" +
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" +
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");
1250 [DllImport ("libc")]
1251 static extern int system (string s);
1252 [DllImport ("libc")]
1253 static extern int uname (IntPtr buf);
1255 static void DetectOS ()
1258 os_message = "OS is: Windows";
1263 IntPtr buf = Marshal.AllocHGlobal (8192);
1264 if (uname (buf) != 0){
1265 os_message = "Warning: Unable to detect OS";
1266 Marshal.FreeHGlobal (buf);
1269 string os = Marshal.PtrToStringAnsi (buf);
1270 os_message = "OS is: " + os;
1274 Marshal.FreeHGlobal (buf);
1277 static bool IsUnix {
1279 int p = (int) Environment.OSVersion.Platform;
1280 return ((p == 4) || (p == 128) || (p == 6));
1284 static void Execute (string cmdLine)
1288 Console.WriteLine ("[execute cmd]: " + cmdLine);
1289 int ret = system (cmdLine);
1292 Error(String.Format("[Fail] {0}", ret));
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
1302 // But if it's *not* on cygwin, just skip it.
1304 // check if dos2unix is applicable.
1305 if (use_dos2unix == true)
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;
1319 Console.WriteLine("Warning: dos2unix not found");
1320 use_dos2unix = false;
1323 if (use_dos2unix == null)
1324 use_dos2unix = false;
1326 ProcessStartInfo psi = new ProcessStartInfo();
1327 psi.UseShellExecute = false;
1329 // if there is no dos2unix, just run cmd /c.
1330 if (use_dos2unix == false)
1332 psi.FileName = "cmd";
1333 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1337 psi.FileName = "sh";
1338 StringBuilder b = new StringBuilder();
1340 for (int i = 0; i < cmdLine.Length; i++)
1342 if (cmdLine[i] == '`')
1346 b.Append("|dos2unix");
1350 b.Append(cmdLine[i]);
1352 cmdLine = b.ToString();
1353 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1357 Console.WriteLine(cmdLine);
1358 using (Process p = Process.Start (psi)) {
1360 int ret = p.ExitCode;
1362 Error ("[Fail] {0}", ret);
1367 static string GetEnv(string name, string defaultValue)
1369 string val = Environment.GetEnvironmentVariable(name);
1373 Console.WriteLine("{0} = {1}", name, val);
1379 Console.WriteLine("{0} = {1} (default)", name, val);
1384 static string LocateFile(string default_path)
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;
1392 throw new FileNotFoundException(default_path);
1395 static string GetAssemblerCommand (string sourceFile, string objectFile)
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";
1404 return String.Format ("\"{0}\" {1} -o {2} {3} ", assembler.Path, additionalArguments, objectFile, sourceFile);
1406 return String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), objectFile, sourceFile);
1410 #region WindowsToolchainSupport
1412 class StringVersionComparer : IComparer<string> {
1413 public int Compare (string stringA, string stringB)
1418 var versionAMatch = System.Text.RegularExpressions.Regex.Match (stringA, @"\d+(\.\d +) + ");
1419 if (versionAMatch.Success)
1420 stringA = versionAMatch.ToString ();
1422 var versionBMatch = System.Text.RegularExpressions.Regex.Match (stringB, @"\d+(\.\d+)+");
1423 if (versionBMatch.Success)
1424 stringB = versionBMatch.ToString ();
1426 if (Version.TryParse (stringA, out versionA) && Version.TryParse (stringB, out versionB))
1427 return versionA.CompareTo (versionB);
1429 return string.Compare (stringA, stringB, StringComparison.OrdinalIgnoreCase);
1433 class InstalledSDKInfo {
1434 public InstalledSDKInfo (string name, string version, string installationFolder)
1437 this.Version = Version.Parse (version);
1438 this.InstallationFolder = installationFolder;
1439 this.AdditionalSDKs = new List<InstalledSDKInfo> ();
1442 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion)
1443 : this (name, version, installationFolder)
1445 this.IsSubVersion = isSubVersion;
1448 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion, InstalledSDKInfo parentSDK)
1449 : this (name, version, installationFolder, isSubVersion)
1451 this.ParentSDK = parentSDK;
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; }
1462 class ToolchainProgram {
1463 public ToolchainProgram (string name, string path)
1469 public ToolchainProgram (string name, string path, InstalledSDKInfo parentSDK)
1472 this.ParentSDK = parentSDK;
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; } }
1484 static protected Microsoft.Win32.RegistryKey GetToolchainRegistrySubKey (string subKey)
1486 Microsoft.Win32.RegistryKey key = null;
1488 if (Environment.Is64BitProcess) {
1489 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey) ??
1490 Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey);
1494 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE" + subKey) ??
1495 Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE" + subKey);
1502 class WindowsSDKHelper : SDKHelper {
1503 List<InstalledSDKInfo> installedWindowsSDKs;
1504 List<InstalledSDKInfo> installedCRuntimeSDKs;
1505 InstalledSDKInfo installedWindowsSDK;
1506 InstalledSDKInfo installedCRuntimeSDK;
1508 static WindowsSDKHelper singletonInstance = new WindowsSDKHelper ();
1509 static public WindowsSDKHelper GetInstance ()
1511 return singletonInstance;
1514 Dictionary<string, string> GetInstalledWindowsKitRootFolders ()
1516 var rootFolders = new Dictionary<string, string> ();
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 ());
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 ());
1542 rootFolders.Add (installFolder, "");
1552 void InitializeInstalledWindowsKits ()
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");
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 ());
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));
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));
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));
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 ();
1601 installedWindowsSDKs = windowsSDKs;
1602 installedCRuntimeSDKs = cRuntimeSDKs;
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);
1610 Console.WriteLine ("---------------");
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);
1623 Console.WriteLine ("---------------");
1630 List<InstalledSDKInfo> GetInstalledWindowsSDKs ()
1632 if (installedWindowsSDKs == null)
1633 InitializeInstalledWindowsKits ();
1635 return installedWindowsSDKs;
1638 List<InstalledSDKInfo> GetInstalledCRuntimeSDKs ()
1640 if (installedCRuntimeSDKs == null)
1641 InitializeInstalledWindowsKits ();
1643 return installedCRuntimeSDKs;
1646 InstalledSDKInfo GetInstalledWindowsSDK ()
1648 if (installedWindowsSDK == null) {
1649 string winSDKDir = "";
1650 InstalledSDKInfo windowsSDK = null;
1651 List<InstalledSDKInfo> windowsSDKs = GetInstalledWindowsSDKs ();
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", "");
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+)+");
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 ()));
1668 windowsSDK = windowsSDKs.Find (x => x.InstallationFolder == winSDKDir);
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 ());
1675 if (windowsSDK == null && windowsSDKs != null)
1676 // Get latest installed verison.
1677 windowsSDK = windowsSDKs.First ();
1679 installedWindowsSDK = windowsSDK;
1682 return installedWindowsSDK;
1685 string FindCRuntimeSDKIncludePath (InstalledSDKInfo sdk)
1687 string cRuntimeIncludePath = Path.Combine (sdk.InstallationFolder, "include");
1688 if (sdk.IsSubVersion)
1689 cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, sdk.Version.ToString ());
1691 cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, "ucrt");
1692 if (!Directory.Exists (cRuntimeIncludePath))
1693 cRuntimeIncludePath = "";
1695 return cRuntimeIncludePath;
1698 string FindCRuntimeSDKLibPath (InstalledSDKInfo sdk)
1700 string cRuntimeLibPath = Path.Combine (sdk.InstallationFolder, "lib");
1701 if (sdk.IsSubVersion)
1702 cRuntimeLibPath = Path.Combine (cRuntimeLibPath, sdk.Version.ToString ());
1704 cRuntimeLibPath = Path.Combine (cRuntimeLibPath, "ucrt", Target64BitApplication () ? "x64" : "x86");
1705 if (!Directory.Exists (cRuntimeLibPath))
1706 cRuntimeLibPath = "";
1708 return cRuntimeLibPath;
1711 InstalledSDKInfo GetInstalledCRuntimeSDK ()
1713 if (installedCRuntimeSDK == null) {
1714 InstalledSDKInfo cRuntimeSDK = null;
1715 var windowsSDK = GetInstalledWindowsSDK ();
1716 var cRuntimeSDKs = GetInstalledCRuntimeSDKs ();
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 ();
1723 installedCRuntimeSDK = cRuntimeSDK;
1727 return installedCRuntimeSDK;
1730 public void AddWindowsSDKIncludePaths (List<string> includePaths)
1732 InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1733 if (winSDK != null) {
1734 string winSDKIncludeDir = Path.Combine (winSDK.InstallationFolder, "include");
1736 if (winSDK.IsSubVersion)
1737 winSDKIncludeDir = Path.Combine (winSDKIncludeDir, winSDK.Version.ToString ());
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"));
1750 public void AddWindowsSDKLibPaths (List<string> libPaths)
1752 InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1753 if (winSDK != null) {
1754 string winSDKLibDir = Path.Combine (winSDK.InstallationFolder, "lib");
1756 if (winSDK.IsSubVersion) {
1757 winSDKLibDir = Path.Combine (winSDKLibDir, winSDK.Version.ToString ());
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;
1767 //Enumerat lib sub folders.
1768 if (Directory.Exists (winSDKLibDir))
1769 libPaths.Add (Path.Combine (winSDKLibDir, "um", Target64BitApplication () ? "x64" : "x86"));
1775 public void AddCRuntimeSDKIncludePaths (List<string> includePaths)
1777 InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1778 if (cRuntimeSDK != null) {
1779 string cRuntimeSDKIncludeDir = FindCRuntimeSDKIncludePath (cRuntimeSDK);
1781 if (cRuntimeSDKIncludeDir.Length != 0)
1782 includePaths.Add (cRuntimeSDKIncludeDir);
1788 public void AddCRuntimeSDKLibPaths (List<string> libPaths)
1790 InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1791 if (cRuntimeSDK != null) {
1792 string cRuntimeSDKLibDir = FindCRuntimeSDKLibPath (cRuntimeSDK);
1794 if (cRuntimeSDKLibDir.Length != 0)
1795 libPaths.Add (cRuntimeSDKLibDir);
1802 class VisualStudioSDKHelper : SDKHelper {
1803 List<InstalledSDKInfo> installedVisualStudioSDKs;
1804 InstalledSDKInfo installedVisualStudioSDK;
1806 static VisualStudioSDKHelper singletonInstance = new VisualStudioSDKHelper ();
1807 static public VisualStudioSDKHelper GetInstance ()
1809 return singletonInstance;
1812 List<InstalledSDKInfo> InitializeInstalledVisualStudioSDKs ()
1814 if (installedVisualStudioSDKs == null) {
1815 List<InstalledSDKInfo> sdks = new List<InstalledSDKInfo> ();
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");
1825 if (Directory.Exists (vcInstallationFolder))
1826 vsSDK.AdditionalSDKs.Add (new InstalledSDKInfo ("VisualStudioVC", keyName, vcInstallationFolder, false, vsSDK));
1834 // TODO: Add VS15 SetupConfiguration support.
1835 // To reduce dependecies use vswhere.exe, if available.
1837 // Sort based on version.
1838 sdks = sdks.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1839 installedVisualStudioSDKs = sdks;
1842 return installedVisualStudioSDKs;
1845 string FindVisualStudioVCFolderPath (InstalledSDKInfo vcSDK, string subPath)
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");
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 ());
1860 foreach (var version in versions) {
1861 msvcVersionPath = Path.Combine (version.FullName, subPath);
1862 if (Directory.Exists (msvcVersionPath)) {
1863 folderPath = msvcVersionPath;
1874 string FindVisualStudioVCLibSubPath (InstalledSDKInfo vcSDK)
1876 string subPath = "";
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";
1888 public InstalledSDKInfo GetInstalledVisualStudioSDK ()
1890 if (installedVisualStudioSDK == null) {
1891 List<InstalledSDKInfo> visualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1892 InstalledSDKInfo visualStudioSDK = null;
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", "");
1898 if (vsVersion.Length != 0 && visualStudioSDKs != null)
1899 // Find installed SDK based on requested info.
1900 visualStudioSDK = visualStudioSDKs.Find (x => x.Version.ToString () == vsVersion);
1902 if (visualStudioSDK == null && visualStudioSDKs != null)
1903 // Get latest installed verison.
1904 visualStudioSDK = visualStudioSDKs.First ();
1906 installedVisualStudioSDK = visualStudioSDK;
1909 return installedVisualStudioSDK;
1912 public InstalledSDKInfo GetInstalledVisualStudioVCSDK ()
1914 InstalledSDKInfo visualStudioVCSDK = null;
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)
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");
1938 return visualStudioVCSDK;
1941 public bool IsVisualStudio14 (InstalledSDKInfo vsSDK)
1943 return vsSDK.Version.Major == 14 || vsSDK.Version.Major == 2015;
1946 public bool IsVisualStudio15 (InstalledSDKInfo vsSDK)
1948 return vsSDK.Version.Major == 15 || vsSDK.Version.Major == 2017;
1951 public void AddVisualStudioVCIncludePaths (List<string> includePaths)
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");
1960 if (vcIncludeDir.Length != 0)
1961 includePaths.Add (vcIncludeDir);
1966 public void AddVisualStudioVCLibPaths (List<string> libPaths)
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));
1975 if (vcLibDir.Length != 0)
1976 libPaths.Add (vcLibDir);
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; }
1988 class VC14ToolchainProgram : VCToolchainProgram {
1989 public override bool IsVersion (InstalledSDKInfo vcSDK)
1991 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
1994 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
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 });
2002 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", tool });
2004 if (!File.Exists (toolPath))
2008 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2015 class VC15ToolchainProgram : VCToolchainProgram {
2016 public override bool IsVersion (InstalledSDKInfo vcSDK)
2018 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2021 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
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);
2030 if (Target64BitApplication ())
2031 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX64", "x64", tool);
2033 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX86", "x86", tool);
2036 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2043 class VC14Compiler : VC14ToolchainProgram {
2044 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2046 return FindVCToolchainProgram ("cl.exe", vcSDK);
2050 class VC15Compiler : VC15ToolchainProgram {
2051 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2053 return FindVCToolchainProgram ("cl.exe", vcSDK);
2057 class VC14Librarian : VC14ToolchainProgram {
2058 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2060 return FindVCToolchainProgram ("lib.exe", vcSDK);
2064 class VC15Librarian : VC15ToolchainProgram {
2065 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2067 return FindVCToolchainProgram ("lib.exe", vcSDK);
2071 class VC14Clang : VCToolchainProgram {
2072 public override bool IsVersion (InstalledSDKInfo vcSDK)
2074 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2077 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
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" });
2084 if (!File.Exists (clangPath))
2088 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2095 class VC15Clang : VCToolchainProgram {
2096 public override bool IsVersion (InstalledSDKInfo vcSDK)
2098 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2101 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
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);
2110 clangPath = Path.Combine (clangVersionPath, "bin", Target64BitApplication () ? "HostX64" : "HostX86", "clang.exe");
2113 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2120 class VisualStudioSDKToolchainHelper {
2121 List<VCToolchainProgram> vcCompilers = new List<VCToolchainProgram> ();
2122 List<VCToolchainProgram> vcLibrarians = new List<VCToolchainProgram> ();
2123 List<VCToolchainProgram> vcClangCompilers = new List<VCToolchainProgram> ();
2125 public VisualStudioSDKToolchainHelper ()
2127 vcCompilers.Add (new VC14Compiler ());
2128 vcCompilers.Add (new VC15Compiler ());
2130 vcLibrarians.Add (new VC14Librarian ());
2131 vcLibrarians.Add (new VC15Librarian ());
2133 vcClangCompilers.Add (new VC14Clang ());
2134 vcClangCompilers.Add (new VC15Clang ());
2137 static VisualStudioSDKToolchainHelper singletonInstance = new VisualStudioSDKToolchainHelper ();
2138 static public VisualStudioSDKToolchainHelper GetInstance ()
2140 return singletonInstance;
2143 ToolchainProgram GetVCToolChainProgram (List<VCToolchainProgram> programs)
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);
2157 public ToolchainProgram GetVCCompiler ()
2159 return GetVCToolChainProgram (vcCompilers);
2162 public ToolchainProgram GetVCLibrarian ()
2164 return GetVCToolChainProgram (vcLibrarians);
2167 public ToolchainProgram GetVCClangCompiler ()
2169 return GetVCToolChainProgram (vcClangCompilers);
2173 static bool Target64BitApplication ()
2175 // Should probably handled the --cross and sdk parameters.
2176 return Environment.Is64BitProcess;
2179 static string GetMonoDir ()
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)) {
2187 if (baseKey != null) {
2188 using (var subKey = baseKey.OpenSubKey (@"SOFTWARE\Mono")) {
2190 monoInstallDir = (string)subKey.GetValue ("SdkInstallRoot", "");
2196 return monoInstallDir;
2199 static void AddMonoIncludePaths (List<string> includePaths)
2201 includePaths.Add (Path.Combine (GetMonoDir (), @"include\mono-2.0"));
2205 static void AddMonoLibPaths (List<string> libPaths)
2207 libPaths.Add (Path.Combine (GetMonoDir (), "lib"));
2211 static void AddIncludePaths (List<string> includePaths)
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);
2222 AddMonoIncludePaths (includePaths);
2223 includePaths.Add (".");
2228 static void AddLibPaths (List<string> libPaths)
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);
2239 AddMonoLibPaths (libPaths);
2245 static void AddVCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
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");
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");
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");
2276 static void AddGCCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2278 if (MakeBundle.compress)
2279 linkerArgs.Add ("-lz");
2284 static void AddSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2286 if (program.IsVSToolChain)
2287 AddVCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2289 AddGCCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2294 static void AddMonoLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArguments)
2296 bool vsToolChain = program.IsVSToolChain;
2297 string libPrefix = !vsToolChain ? "-l" : "";
2298 string libExtension = vsToolChain ? ".lib" : "";
2299 string monoLibrary = GetEnv ("LIBMONO", "");
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.");
2307 monoLibrary = "libmono-static-sgen";
2309 monoLibrary = "mono-2.0-sgen";
2313 if (!Path.IsPathRooted (monoLibrary)) {
2314 if (!monoLibrary.EndsWith (libExtension))
2315 monoLibrary = monoLibrary + libExtension;
2317 linkerArguments.Add (libPrefix + monoLibrary);
2319 linkerArguments.Add (monoLibrary);
2325 static void AddVCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2327 List<string> includePaths = new List<string> ();
2328 AddIncludePaths (includePaths);
2330 if (staticLinkCRuntime)
2331 // Add targeted c-runtime (MT = static release).
2332 compilerArgs.Add ("/MT");
2334 // Add targeted c-runtime (MD = dynamic release).
2335 compilerArgs.Add ("/MD");
2337 // Add include search paths.
2338 foreach (string include in includePaths)
2339 compilerArgs.Add (String.Format("/I {0}", program.QuoteArg (include)));
2344 static void AddGCCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2346 List<string> includePaths = new List<string> ();
2347 AddMonoIncludePaths (includePaths);
2349 // Add include search paths.
2350 foreach (string include in includePaths)
2351 compilerArgs.Add (String.Format ("-I {0}", program.QuoteArg (include)));
2356 static void AddCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2358 if (program.IsVSToolChain)
2359 AddVCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2361 AddGCCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2366 static void AddVCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2368 linkerArgs.Add ("/link");
2370 var subsystem = GetEnv ("VCSUBSYSTEM", "windows");
2371 linkerArgs.Add ("/SUBSYSTEM:" + subsystem);
2373 if (customMain != null && customMain.Length != 0)
2374 linkerArgs.Add (linker.QuoteArg (customMain));
2376 linkerArgs.Add ("/ENTRY:mainCRTStartup");
2378 // Ignore other c-runtime directives from linked libraries.
2379 linkerArgs.Add ("/NODEFAULTLIB");
2381 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2382 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2384 // Add library search paths.
2385 List<string> libPaths = new List<string> ();
2386 AddLibPaths (libPaths);
2388 foreach (string lib in libPaths)
2389 linkerArgs.Add (String.Format ("/LIBPATH:{0}", linker.QuoteArg (lib)));
2391 // Linker output target.
2392 linkerArgs.Add ("/OUT:" + linker.QuoteArg (outputFile));
2397 static void AddGCCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2399 // Add library search paths.
2400 List<string> libPaths = new List<string> ();
2401 AddMonoLibPaths (libPaths);
2403 foreach (string lib in libPaths)
2404 linkerArgs.Add (String.Format ("-L {0}", linker.QuoteArg (lib)));
2408 linkerArgs.Add ("-Wl,-Bstatic");
2410 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2413 linkerArgs.Add ("-Wl,-Bdynamic");
2415 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2417 // Linker output target.
2418 linkerArgs.Add ("-o " + linker.QuoteArg (outputFile));
2421 static void AddLinkerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2423 if (program.IsVSToolChain)
2424 AddVCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2426 AddGCCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2431 static void AddVCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2433 compilerArgs.Add ("/c");
2434 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2436 objectFile = sourceFile + ".obj";
2437 compilerArgs.Add (String.Format ("/Fo" + compiler.QuoteArg (objectFile)));
2442 static void AddGCCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2444 compilerArgs.Add ("-c");
2445 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2447 objectFile = sourceFile + ".o";
2448 compilerArgs.Add (String.Format ("-o " + compiler.QuoteArg (objectFile)));
2453 static void AddVCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2455 foreach (var objectFile in objectFiles)
2456 librarianArgs.Add (librarian.QuoteArg (objectFile));
2458 // Add library search paths.
2459 List<string> libPaths = new List<string> ();
2460 AddLibPaths (libPaths);
2462 foreach (string lib in libPaths) {
2463 librarianArgs.Add (String.Format ("/LIBPATH:{0}", librarian.QuoteArg (lib)));
2466 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2468 librarianArgs.Add ("/OUT:" + librarian.QuoteArg (output));
2473 static void AddGCCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2475 foreach (var objectFile in objectFiles)
2476 librarianArgs.Add (librarian.QuoteArg (objectFile));
2478 // Add library search paths.
2479 List<string> libPaths = new List<string> ();
2480 AddMonoLibPaths (libPaths);
2482 foreach (string lib in libPaths)
2483 librarianArgs.Add (String.Format ("-L {0}", librarian.QuoteArg (lib)));
2485 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2487 librarianArgs.Add ("-o " + librarian.QuoteArg (output));
2492 static ToolchainProgram GetAssemblerCompiler ()
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);
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");
2507 return vcClangAssembler;
2510 static ToolchainProgram GetCCompiler ()
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);
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");
2527 static ToolchainProgram GetLibrarian ()
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");
2539 static string GetCompileAndLinkCommand (ToolchainProgram compiler, string sourceFile, string objectFile, string customMain, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2541 var compilerArgs = new List<string> ();
2543 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2545 // Add source file to compile.
2546 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2548 // Add assembled object file.
2549 compilerArgs.Add (compiler.QuoteArg (objectFile));
2551 // Add linker arguments.
2552 AddLinkerArguments (compiler, staticLinkMono, staticLinkCRuntime, customMain, outputFile, compilerArgs);
2554 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs));
2557 static string GetLibrarianCompilerCommand (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, out string objectFile)
2559 var compilerArgs = new List<string> ();
2561 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2563 if (compiler.IsVSToolChain)
2564 AddVCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2566 AddGCCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2568 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs));
2571 static string GetLibrarianLinkerCommand (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2573 var librarianArgs = new List<string> ();
2575 if (librarian.IsVSToolChain)
2576 AddVCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2578 AddGCCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2580 return String.Format ("{0} {1}", librarian.QuoteArg (librarian.Path), String.Join (" ", librarianArgs));