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 if (compiler != null && compiler.ParentSDK != null) {
936 if (compiler.IsVSToolChain && VisualStudioSDKHelper.GetInstance ().IsVisualStudio12 (compiler.ParentSDK) && static_link)
937 Console.WriteLine ( @"Warning: Static linking the Mono runtime on Windows using VC " +
938 @"12.0, won't support static Mono runtime library distributed in Mono SDK since it has " +
939 @"been build using different C-runtime version. If build results in " +
940 @"link errors related to C-runtime functions, please rebuild mono runtime distribution " +
941 @"using targeted VC compiler and linker and rerun using MONOPREFIX.");
944 bool staticLinkCRuntime = GetEnv ("VCCRT", "MD") != "MD";
945 if (!nomain || custom_main != null) {
946 string cl_cmd = GetCompileAndLinkCommand (compiler, temp_c, temp_o, custom_main, static_link, staticLinkCRuntime, output);
949 string temp_c_o = "";
951 string cl_cmd = GetLibrarianCompilerCommand (compiler, temp_c, static_link, staticLinkCRuntime, out temp_c_o);
954 ToolchainProgram librarian = GetLibrarian ();
955 string lib_cmd = GetLibrarianLinkerCommand (librarian, new string[] { temp_o, temp_c_o }, static_link, staticLinkCRuntime, output);
958 File.Delete (temp_c_o);
965 string zlib = (compress ? "-lz" : "");
966 string objc = (style == "osx" ? "-framework CoreFoundation -lobjc" : "");
967 string debugging = "-g";
968 string cc = GetEnv("CC", "cc");
971 if (style == "linux")
977 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
979 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
980 cmd = String.Format("{4} -o '{2}' -Wall {5} `pkg-config --cflags mono-2` {0} {3} " +
981 "`pkg-config --libs-only-L mono-2` " + smonolib +
982 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
983 temp_c, temp_o, output, zlib, cc, objc);
988 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {5} {0} `pkg-config --cflags --libs mono-2` {3} {1}",
989 temp_c, temp_o, output, zlib, cc, objc);
995 Console.WriteLine ("Done");
1000 if (object_out == null){
1001 File.Delete (temp_o);
1004 File.Delete (temp_c);
1006 File.Delete (temp_s);
1011 static List<string> LoadAssemblies (List<string> sources)
1013 List<string> assemblies = new List<string> ();
1016 foreach (string name in sources){
1018 Assembly a = LoadAssemblyFile (name);
1025 assemblies.Add (a.CodeBase);
1026 } catch (Exception) {
1029 Console.WriteLine ("File will not be scanned: {0}", name);
1030 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1038 Error ("Couldn't load one or more of the assemblies.");
1039 Environment.Exit (1);
1045 static void LoadLocalizedAssemblies (List<string> assemblies)
1047 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1048 string error = null;
1050 foreach (string name in other) {
1052 Assembly a = LoadAssembly (name);
1055 error = "Failed to load " + name;
1059 assemblies.Add (a.CodeBase);
1060 } catch (Exception) {
1063 Console.WriteLine ("File will not be scanned: {0}", name);
1064 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1071 if (error != null) {
1072 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1073 foreach (var path in link_paths){
1074 Console.Error.WriteLine (" Path: " + path);
1077 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1080 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1081 Environment.Exit (1);
1086 static readonly Universe universe = new Universe ();
1087 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1089 public static string GetAssemblyName (string path)
1091 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1092 string name = Path.GetFileName (path);
1094 // A bit of a hack to support satellite assemblies. They all share the same name but
1095 // are placed in subdirectories named after the locale they implement. Also, all of
1096 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1097 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1098 string dir = Path.GetDirectoryName (path);
1099 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1101 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1102 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1104 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1110 static bool QueueAssembly (List<string> files, string codebase)
1112 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1113 if (files.Contains (codebase))
1116 var path = new Uri(codebase).LocalPath;
1117 var name = GetAssemblyName (path);
1119 if (loaded_assemblies.TryGetValue (name, out found)) {
1120 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1124 loaded_assemblies.Add (name, path);
1126 files.Add (codebase);
1130 Assembly a = universe.LoadFile (path);
1132 Error ("Unable to to load assembly `{0}'", path);
1136 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1137 a = LoadAssembly (an.Name);
1139 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1143 if (!QueueAssembly (files, a.CodeBase))
1146 } catch (Exception) {
1155 // Loads an assembly from a specific path
1157 static Assembly LoadAssemblyFile (string assembly)
1163 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1164 a = universe.LoadFile (assembly);
1166 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1168 } catch (FileNotFoundException){
1169 Error ($"Cannot find assembly `{assembly}'");
1170 } catch (IKVM.Reflection.BadImageFormatException f) {
1173 Error ($"Cannot load assembly (bad file format) " + f.Message);
1174 } catch (FileLoadException f){
1175 Error ($"Cannot load assembly " + f.Message);
1176 } catch (ArgumentNullException){
1177 Error( $"Cannot load assembly (null argument)");
1183 // Loads an assembly from any of the link directories provided
1185 static Assembly LoadAssembly (string assembly)
1187 string total_log = "";
1188 foreach (string dir in link_paths){
1189 string full_path = Path.Combine (dir, assembly);
1191 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1192 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1193 full_path += ".dll";
1196 var a = universe.LoadFile (full_path);
1198 } catch (FileNotFoundException ff) {
1199 total_log += ff.FusionLog;
1204 Console.WriteLine ("Log: \n" + total_log);
1208 static void Error (string msg, params object [] args)
1210 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1211 Environment.Exit (1);
1216 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1218 " --config F Bundle system config file `F'\n" +
1219 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1220 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1221 " -L path Adds `path' to the search path for assemblies\n" +
1222 " --machine-config F Use the given file as the machine.config for the application.\n" +
1223 " -o out Specifies output filename\n" +
1224 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1225 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1226 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1227 " -v Verbose output\n" +
1228 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1230 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1231 " --cross TARGET Generates a binary for the given TARGET\n"+
1232 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1233 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1234 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1235 " LIB is optional shortname for file located at PATH\n" +
1236 " --list-targets Lists available targets on the remote server\n" +
1237 " --local-targets Lists locally available targets\n" +
1238 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1239 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1240 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1241 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1243 "--custom Builds a custom launcher, options for --custom\n" +
1244 " -c Produce stub only, do not compile\n" +
1245 " -oo obj Specifies output filename for helper object file\n" +
1246 " --dos2unix[=true|false]\n" +
1247 " When no value provided, or when `true` specified\n" +
1248 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1249 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1250 " --keeptemp Keeps the temporary files\n" +
1251 " --static Statically link to mono libs\n" +
1252 " --nomain Don't include a main() function, for libraries\n" +
1253 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1254 " -z Compress the assemblies before embedding.\n" +
1255 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1256 " You need zlib development headers and libraries.\n");
1259 [DllImport ("libc")]
1260 static extern int system (string s);
1261 [DllImport ("libc")]
1262 static extern int uname (IntPtr buf);
1264 static void DetectOS ()
1267 os_message = "OS is: Windows";
1272 IntPtr buf = Marshal.AllocHGlobal (8192);
1273 if (uname (buf) != 0){
1274 os_message = "Warning: Unable to detect OS";
1275 Marshal.FreeHGlobal (buf);
1278 string os = Marshal.PtrToStringAnsi (buf);
1279 os_message = "OS is: " + os;
1283 Marshal.FreeHGlobal (buf);
1286 static bool IsUnix {
1288 int p = (int) Environment.OSVersion.Platform;
1289 return ((p == 4) || (p == 128) || (p == 6));
1293 static void Execute (string cmdLine)
1297 Console.WriteLine ("[execute cmd]: " + cmdLine);
1298 int ret = system (cmdLine);
1301 Error(String.Format("[Fail] {0}", ret));
1306 // on Windows, we have to pipe the output of a
1307 // `cmd` interpolation to dos2unix, because the shell does not
1308 // strip the CRLFs generated by the native pkg-config distributed
1311 // But if it's *not* on cygwin, just skip it.
1313 // check if dos2unix is applicable.
1314 if (use_dos2unix == true)
1316 var info = new ProcessStartInfo ("dos2unix");
1317 info.CreateNoWindow = true;
1318 info.RedirectStandardInput = true;
1319 info.UseShellExecute = false;
1320 var dos2unix = Process.Start (info);
1321 dos2unix.StandardInput.WriteLine ("aaa");
1322 dos2unix.StandardInput.WriteLine ("\u0004");
1323 dos2unix.StandardInput.Close ();
1324 dos2unix.WaitForExit ();
1325 if (dos2unix.ExitCode == 0)
1326 use_dos2unix = true;
1328 Console.WriteLine("Warning: dos2unix not found");
1329 use_dos2unix = false;
1332 if (use_dos2unix == null)
1333 use_dos2unix = false;
1335 ProcessStartInfo psi = new ProcessStartInfo();
1336 psi.UseShellExecute = false;
1338 // if there is no dos2unix, just run cmd /c.
1339 if (use_dos2unix == false)
1341 psi.FileName = "cmd";
1342 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1346 psi.FileName = "sh";
1347 StringBuilder b = new StringBuilder();
1349 for (int i = 0; i < cmdLine.Length; i++)
1351 if (cmdLine[i] == '`')
1355 b.Append("|dos2unix");
1359 b.Append(cmdLine[i]);
1361 cmdLine = b.ToString();
1362 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1366 Console.WriteLine(cmdLine);
1367 using (Process p = Process.Start (psi)) {
1369 int ret = p.ExitCode;
1371 Error ("[Fail] {0}", ret);
1376 static string GetEnv(string name, string defaultValue)
1378 string val = Environment.GetEnvironmentVariable(name);
1382 Console.WriteLine("{0} = {1}", name, val);
1388 Console.WriteLine("{0} = {1} (default)", name, val);
1393 static string LocateFile(string default_path)
1395 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1396 if (File.Exists(override_path))
1397 return override_path;
1398 else if (File.Exists(default_path))
1399 return default_path;
1401 throw new FileNotFoundException(default_path);
1404 static string GetAssemblerCommand (string sourceFile, string objectFile)
1406 if (style == "windows") {
1407 string additionalArguments = "";
1408 var assembler = GetAssemblerCompiler ();
1409 if (assembler.Name.Contains ("clang.exe"))
1410 //Clang uses additional arguments.
1411 additionalArguments = "-c -x assembler";
1413 return String.Format ("\"{0}\" {1} -o {2} {3} ", assembler.Path, additionalArguments, objectFile, sourceFile);
1415 return String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), objectFile, sourceFile);
1419 #region WindowsToolchainSupport
1421 class StringVersionComparer : IComparer<string> {
1422 public int Compare (string stringA, string stringB)
1427 var versionAMatch = System.Text.RegularExpressions.Regex.Match (stringA, @"\d+(\.\d +) + ");
1428 if (versionAMatch.Success)
1429 stringA = versionAMatch.ToString ();
1431 var versionBMatch = System.Text.RegularExpressions.Regex.Match (stringB, @"\d+(\.\d+)+");
1432 if (versionBMatch.Success)
1433 stringB = versionBMatch.ToString ();
1435 if (Version.TryParse (stringA, out versionA) && Version.TryParse (stringB, out versionB))
1436 return versionA.CompareTo (versionB);
1438 return string.Compare (stringA, stringB, StringComparison.OrdinalIgnoreCase);
1442 class InstalledSDKInfo {
1443 public InstalledSDKInfo (string name, string version, string installationFolder)
1446 this.Version = Version.Parse (version);
1447 this.InstallationFolder = installationFolder;
1448 this.IsSubVersion = false;
1449 this.AdditionalSDKs = new List<InstalledSDKInfo> ();
1452 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion)
1453 : this (name, version, installationFolder)
1455 this.IsSubVersion = isSubVersion;
1458 public InstalledSDKInfo (string name, string version, string installationFolder, bool isSubVersion, InstalledSDKInfo parentSDK)
1459 : this (name, version, installationFolder, isSubVersion)
1461 this.ParentSDK = parentSDK;
1464 public string Name { get; set; }
1465 public Version Version { get; set; }
1466 public string InstallationFolder { get; set; }
1467 public bool IsSubVersion { get; set; }
1468 public List<InstalledSDKInfo> AdditionalSDKs { get; }
1469 public InstalledSDKInfo ParentSDK { get; set; }
1472 class ToolchainProgram {
1473 public ToolchainProgram (string name, string path)
1479 public ToolchainProgram (string name, string path, InstalledSDKInfo parentSDK)
1482 this.ParentSDK = parentSDK;
1485 public Func<string, string> QuoteArg = arg => "\"" + arg + "\"";
1486 public string Name { get; set; }
1487 public string Path { get; set; }
1488 public InstalledSDKInfo ParentSDK { get; set; }
1489 public bool IsVSToolChain { get { return (Name.Contains ("cl.exe") || Name.Contains ("lib.exe")); } }
1490 public bool IsGCCToolChain { get { return !IsVSToolChain; } }
1495 protected Microsoft.Win32.RegistryKey GetToolchainRegistrySubKey (string subKey)
1497 Microsoft.Win32.RegistryKey key = null;
1499 if (Environment.Is64BitProcess) {
1500 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey) ??
1501 Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE\Wow6432Node" + subKey);
1505 key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SOFTWARE" + subKey) ??
1506 Microsoft.Win32.Registry.CurrentUser.OpenSubKey (@"SOFTWARE" + subKey);
1513 class WindowsSDKHelper : SDKHelper {
1515 List<InstalledSDKInfo> installedWindowsSDKs;
1516 List<InstalledSDKInfo> installedCRuntimeSDKs;
1517 InstalledSDKInfo installedWindowsSDK;
1518 InstalledSDKInfo installedCRuntimeSDK;
1520 static WindowsSDKHelper singletonInstance = new WindowsSDKHelper ();
1521 static public WindowsSDKHelper GetInstance ()
1523 return singletonInstance;
1526 Dictionary<string, string> GetInstalledWindowsKitRootFolders ()
1528 var rootFolders = new Dictionary<string, string> ();
1530 using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\Microsoft SDKs\Windows\")) {
1531 if (subKey != null) {
1532 foreach (var keyName in subKey.GetSubKeyNames ()) {
1533 var keyNameIsVersion = System.Text.RegularExpressions.Regex.Match (keyName, @"\d+(\.\d+)+");
1534 if (keyNameIsVersion.Success) {
1535 var installFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString () + @"\" + keyName, "InstallationFolder", "");
1536 if (!rootFolders.ContainsKey (installFolder))
1537 rootFolders.Add (installFolder, keyNameIsVersion.ToString ());
1543 using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\Windows Kits\Installed Roots")) {
1544 if (subKey != null) {
1545 foreach (var valueName in subKey.GetValueNames ()) {
1546 var valueNameIsKitsRoot = System.Text.RegularExpressions.Regex.Match (valueName, @"KitsRoot\d*");
1547 if (valueNameIsKitsRoot.Success) {
1548 var installFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString (), valueName, "");
1549 if (!rootFolders.ContainsKey (installFolder)) {
1550 var valueNameIsVersion = System.Text.RegularExpressions.Regex.Match (valueName, @"\d+(\.*\d+)+");
1551 if (valueNameIsVersion.Success)
1552 rootFolders.Add (installFolder, valueNameIsVersion.ToString ());
1554 rootFolders.Add (installFolder, "");
1564 void InitializeInstalledWindowsKits ()
1566 if (installedWindowsSDKs == null && installedCRuntimeSDKs == null) {
1567 List<InstalledSDKInfo> windowsSDKs = new List<InstalledSDKInfo> ();
1568 List<InstalledSDKInfo> cRuntimeSDKs = new List<InstalledSDKInfo> ();
1569 var rootFolders = GetInstalledWindowsKitRootFolders ();
1570 foreach (var winKitRoot in rootFolders) {
1571 // Try to locate Windows and CRuntime SDKs.
1572 string winKitRootDir = winKitRoot.Key;
1573 string winKitRootVersion = winKitRoot.Value;
1574 string winKitIncludeDir = Path.Combine (winKitRootDir, "include");
1576 //Search for installed SDK versions.
1577 if (Directory.Exists (winKitIncludeDir)) {
1578 var winKitIncludeDirInfo = new DirectoryInfo (winKitIncludeDir);
1579 var versions = winKitIncludeDirInfo.GetDirectories (
1580 "*.*", SearchOption.TopDirectoryOnly).OrderByDescending (p => p.Name, new StringVersionComparer ());
1582 foreach (var version in versions) {
1583 string versionedWindowsSDKHeaderPath = Path.Combine (version.FullName, "um", "windows.h");
1584 string versionedCRuntimeSDKHeaderPath = Path.Combine (version.FullName, "ucrt", "stdlib.h");
1585 var hasSubVersion = System.Text.RegularExpressions.Regex.Match (version.Name, @"\d+(\.\d+)+");
1586 if (hasSubVersion.Success) {
1587 if (File.Exists (versionedWindowsSDKHeaderPath))
1588 //Found a specific Windows SDK sub version.
1589 windowsSDKs.Add (new InstalledSDKInfo ("WindowsSDK", hasSubVersion.ToString (), winKitRootDir, true));
1590 if (File.Exists (versionedCRuntimeSDKHeaderPath))
1591 //Found a specific CRuntime SDK sub version.
1592 cRuntimeSDKs.Add (new InstalledSDKInfo ("CRuntimeSDK", hasSubVersion.ToString (), winKitRootDir, true));
1597 // Try to find SDK without specific sub version.
1598 string windowsSDKHeaderPath = Path.Combine (winKitIncludeDir, "um", "windows.h");
1599 if (File.Exists (windowsSDKHeaderPath))
1600 //Found a Windows SDK version.
1601 windowsSDKs.Add (new InstalledSDKInfo ("WindowsSDK", winKitRootVersion, winKitRootDir, false));
1603 string cRuntimeSDKHeaderPath = Path.Combine (winKitIncludeDir, "ucrt", "stdlib.h");
1604 if (File.Exists (cRuntimeSDKHeaderPath))
1605 //Found a CRuntime SDK version.
1606 cRuntimeSDKs.Add (new InstalledSDKInfo ("CRuntimeSDK", winKitRootVersion, winKitRootDir, false));
1609 // Sort based on version.
1610 windowsSDKs = windowsSDKs.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1611 cRuntimeSDKs = cRuntimeSDKs.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1613 installedWindowsSDKs = windowsSDKs;
1614 installedCRuntimeSDKs = cRuntimeSDKs;
1616 if (!quiet && installedWindowsSDKs != null) {
1617 Console.WriteLine ("--- Windows SDK's ---");
1618 foreach (var windowsSDK in installedWindowsSDKs) {
1619 Console.WriteLine ("Path: " + windowsSDK.InstallationFolder);
1620 Console.WriteLine ("Version: " + windowsSDK.Version);
1622 Console.WriteLine ("---------------");
1625 if (!quiet && installedCRuntimeSDKs != null) {
1626 Console.WriteLine ("--- C-Runtime SDK's ---");
1627 foreach (var cRuntimeSDK in installedCRuntimeSDKs) {
1628 Console.WriteLine ("Path: " + cRuntimeSDK.InstallationFolder);
1629 Console.WriteLine ("Version: " + cRuntimeSDK.Version);
1630 if (cRuntimeSDK.ParentSDK != null) {
1631 Console.WriteLine ("Parent SDK Path: " + cRuntimeSDK.ParentSDK.InstallationFolder);
1632 Console.WriteLine ("Parent SDK Version: " + cRuntimeSDK.ParentSDK.Version);
1635 Console.WriteLine ("---------------");
1642 List<InstalledSDKInfo> GetInstalledWindowsSDKs ()
1644 if (installedWindowsSDKs == null)
1645 InitializeInstalledWindowsKits ();
1647 return installedWindowsSDKs;
1650 List<InstalledSDKInfo> GetInstalledCRuntimeSDKs ()
1652 if (installedCRuntimeSDKs == null)
1653 InitializeInstalledWindowsKits ();
1655 return installedCRuntimeSDKs;
1658 InstalledSDKInfo GetInstalledWindowsSDK ()
1660 if (installedWindowsSDK == null) {
1661 string winSDKDir = "";
1662 InstalledSDKInfo windowsSDK = null;
1663 List<InstalledSDKInfo> windowsSDKs = GetInstalledWindowsSDKs ();
1665 // Check that env doesn't already include needed values.
1666 winSDKDir = GetEnv ("WINSDK", "");
1667 if (winSDKDir.Length == 0)
1668 // If executed from a VS developer command prompt, SDK dir set in env.
1669 winSDKDir = GetEnv ("WindowsSdkDir", "");
1671 // Check that env doesn't already include needed values.
1672 // If executed from a VS developer command prompt, SDK version set in env.
1673 var winSDKVersion = System.Text.RegularExpressions.Regex.Match (GetEnv ("WindowsSdkVersion", ""), @"\d+(\.\d+)+");
1675 if (winSDKDir.Length != 0 && windowsSDKs != null) {
1676 // Find installed SDK based on requested info.
1677 if (winSDKVersion.Success)
1678 windowsSDK = windowsSDKs.Find (x => (x.InstallationFolder == winSDKDir && x.Version.ToString () == winSDKVersion.ToString ()));
1680 windowsSDK = windowsSDKs.Find (x => x.InstallationFolder == winSDKDir);
1683 if (windowsSDK == null && winSDKVersion.Success && windowsSDKs != null)
1684 // Find installed SDK based on requested info.
1685 windowsSDK = windowsSDKs.Find (x => x.Version.ToString () == winSDKVersion.ToString ());
1687 if (windowsSDK == null && windowsSDKs != null)
1688 // Get latest installed verison.
1689 windowsSDK = windowsSDKs.First ();
1691 installedWindowsSDK = windowsSDK;
1694 return installedWindowsSDK;
1697 string FindCRuntimeSDKIncludePath (InstalledSDKInfo sdk)
1699 string cRuntimeIncludePath = Path.Combine (sdk.InstallationFolder, "include");
1700 if (sdk.IsSubVersion)
1701 cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, sdk.Version.ToString ());
1703 cRuntimeIncludePath = Path.Combine (cRuntimeIncludePath, "ucrt");
1704 if (!Directory.Exists (cRuntimeIncludePath))
1705 cRuntimeIncludePath = "";
1707 return cRuntimeIncludePath;
1710 string FindCRuntimeSDKLibPath (InstalledSDKInfo sdk)
1712 string cRuntimeLibPath = Path.Combine (sdk.InstallationFolder, "lib");
1713 if (sdk.IsSubVersion)
1714 cRuntimeLibPath = Path.Combine (cRuntimeLibPath, sdk.Version.ToString ());
1716 cRuntimeLibPath = Path.Combine (cRuntimeLibPath, "ucrt", Target64BitApplication () ? "x64" : "x86");
1717 if (!Directory.Exists (cRuntimeLibPath))
1718 cRuntimeLibPath = "";
1720 return cRuntimeLibPath;
1723 InstalledSDKInfo GetInstalledCRuntimeSDK ()
1725 if (installedCRuntimeSDK == null) {
1726 InstalledSDKInfo cRuntimeSDK = null;
1727 var windowsSDK = GetInstalledWindowsSDK ();
1728 var cRuntimeSDKs = GetInstalledCRuntimeSDKs ();
1730 if (windowsSDK != null && cRuntimeSDKs != null) {
1731 cRuntimeSDK = cRuntimeSDKs.Find (x => x.Version.ToString () == windowsSDK.Version.ToString ());
1732 if (cRuntimeSDK == null && cRuntimeSDKs.Count != 0)
1733 cRuntimeSDK = cRuntimeSDKs.First ();
1735 installedCRuntimeSDK = cRuntimeSDK;
1739 return installedCRuntimeSDK;
1742 public void AddWindowsSDKIncludePaths (List<string> includePaths)
1744 InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1745 if (winSDK != null) {
1746 string winSDKIncludeDir = Path.Combine (winSDK.InstallationFolder, "include");
1748 if (winSDK.IsSubVersion)
1749 winSDKIncludeDir = Path.Combine (winSDKIncludeDir, winSDK.Version.ToString ());
1751 // Include sub folders.
1752 if (Directory.Exists (winSDKIncludeDir)) {
1753 includePaths.Add (Path.Combine (winSDKIncludeDir, "um"));
1754 includePaths.Add (Path.Combine (winSDKIncludeDir, "shared"));
1755 includePaths.Add (Path.Combine (winSDKIncludeDir, "winrt"));
1762 public void AddWindowsSDKLibPaths (List<string> libPaths)
1764 InstalledSDKInfo winSDK = GetInstalledWindowsSDK ();
1765 if (winSDK != null) {
1766 string winSDKLibDir = Path.Combine (winSDK.InstallationFolder, "lib");
1768 if (winSDK.IsSubVersion) {
1769 winSDKLibDir = Path.Combine (winSDKLibDir, winSDK.Version.ToString ());
1771 // Older WinSDK's header folders are not versioned, but installed libraries are, use latest availalble version for now.
1772 var winSDKLibDirInfo = new DirectoryInfo (winSDKLibDir);
1773 var versions = winSDKLibDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly).OrderByDescending (p => p.Name, new StringVersionComparer ());
1774 if (versions != null && versions.First () != null)
1775 winSDKLibDir = versions.First ().FullName;
1778 //Enumerat lib sub folders.
1779 if (Directory.Exists (winSDKLibDir))
1780 libPaths.Add (Path.Combine (winSDKLibDir, "um", Target64BitApplication () ? "x64" : "x86"));
1786 public void AddCRuntimeSDKIncludePaths (List<string> includePaths)
1788 InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1789 if (cRuntimeSDK != null) {
1790 string cRuntimeSDKIncludeDir = FindCRuntimeSDKIncludePath (cRuntimeSDK);
1792 if (cRuntimeSDKIncludeDir.Length != 0)
1793 includePaths.Add (cRuntimeSDKIncludeDir);
1799 public void AddCRuntimeSDKLibPaths (List<string> libPaths)
1801 InstalledSDKInfo cRuntimeSDK = GetInstalledCRuntimeSDK ();
1802 if (cRuntimeSDK != null) {
1803 string cRuntimeSDKLibDir = FindCRuntimeSDKLibPath (cRuntimeSDK);
1805 if (cRuntimeSDKLibDir.Length != 0)
1806 libPaths.Add (cRuntimeSDKLibDir);
1813 class VisualStudioSDKHelper : SDKHelper {
1815 List<InstalledSDKInfo> installedVisualStudioSDKs;
1816 InstalledSDKInfo installedVisualStudioSDK;
1818 static VisualStudioSDKHelper singletonInstance = new VisualStudioSDKHelper ();
1819 static public VisualStudioSDKHelper GetInstance ()
1821 return singletonInstance;
1824 List<InstalledSDKInfo> InitializeInstalledVisualStudioSDKs ()
1826 if (installedVisualStudioSDKs == null) {
1827 List<InstalledSDKInfo> sdks = new List<InstalledSDKInfo> ();
1829 using (var subKey = GetToolchainRegistrySubKey (@"\Microsoft\VisualStudio\SxS\VS7")) {
1830 if (subKey != null) {
1831 foreach (var keyName in subKey.GetValueNames ()) {
1832 var vsInstalltionFolder = (string)Microsoft.Win32.Registry.GetValue (subKey.ToString (), keyName, "");
1833 if (Directory.Exists (vsInstalltionFolder)) {
1834 var vsSDK = new InstalledSDKInfo ("VisualStudio", keyName, vsInstalltionFolder, false);
1835 var vcInstallationFolder = Path.Combine (vsInstalltionFolder, "VC");
1837 if (Directory.Exists (vcInstallationFolder))
1838 vsSDK.AdditionalSDKs.Add (new InstalledSDKInfo ("VisualStudioVC", keyName, vcInstallationFolder, false, vsSDK));
1846 // TODO: Add VS15 SetupConfiguration support.
1847 // To reduce dependecies use vswhere.exe, if available.
1849 // Sort based on version.
1850 sdks = sdks.OrderByDescending (p => p.Version.ToString (), new StringVersionComparer ()).ToList ();
1851 installedVisualStudioSDKs = sdks;
1854 return installedVisualStudioSDKs;
1857 string FindVisualStudioVCFolderPath (InstalledSDKInfo vcSDK, string subPath)
1859 string folderPath = "";
1860 if (vcSDK != null && vcSDK.ParentSDK != null) {
1861 if (IsVisualStudio12 (vcSDK.ParentSDK) || IsVisualStudio14 (vcSDK.ParentSDK)) {
1862 folderPath = Path.Combine (vcSDK.InstallationFolder, subPath);
1863 } else if (IsVisualStudio15 (vcSDK.ParentSDK)) {
1864 string msvcVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "MSVC");
1866 // Add latest found version of MSVC toolchain.
1867 if (Directory.Exists (msvcVersionPath)) {
1868 var msvcVersionDirInfo = new DirectoryInfo (msvcVersionPath);
1869 var versions = msvcVersionDirInfo.GetDirectories ("*.*", SearchOption.TopDirectoryOnly).OrderByDescending (p => p.Name, new StringVersionComparer ());
1871 foreach (var version in versions) {
1872 msvcVersionPath = Path.Combine (version.FullName, subPath);
1873 if (Directory.Exists (msvcVersionPath)) {
1874 folderPath = msvcVersionPath;
1885 string FindVisualStudioVCLibSubPath (InstalledSDKInfo vcSDK)
1887 string subPath = "";
1889 if (vcSDK != null && vcSDK.ParentSDK != null) {
1890 if (IsVisualStudio12 (vcSDK.ParentSDK) || IsVisualStudio14 (vcSDK.ParentSDK))
1891 subPath = Target64BitApplication () ? @"lib\amd64" : "lib";
1892 else if (IsVisualStudio15 (vcSDK.ParentSDK))
1893 subPath = Target64BitApplication () ? @"lib\x64" : @"lib\x86";
1899 public InstalledSDKInfo GetInstalledVisualStudioSDK ()
1901 if (installedVisualStudioSDK == null) {
1902 List<InstalledSDKInfo> visualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1903 InstalledSDKInfo visualStudioSDK = null;
1905 // Check that env doesn't already include needed values.
1906 // If executed from a VS developer command prompt, Visual Studio install dir set in env.
1907 string vsVersion = GetEnv ("VisualStudioVersion", "");
1909 if (vsVersion.Length != 0 && visualStudioSDKs != null)
1910 // Find installed SDK based on requested info.
1911 visualStudioSDK = visualStudioSDKs.Find (x => x.Version.ToString () == vsVersion);
1913 if (visualStudioSDK == null && visualStudioSDKs != null)
1914 // Get latest installed verison.
1915 visualStudioSDK = visualStudioSDKs.First ();
1917 installedVisualStudioSDK = visualStudioSDK;
1920 return installedVisualStudioSDK;
1923 public InstalledSDKInfo GetInstalledVisualStudioVCSDK ()
1925 InstalledSDKInfo visualStudioVCSDK = null;
1927 // Check that env doesn't already include needed values.
1928 // If executed from a VS developer command prompt, Visual Studio install dir set in env.
1929 string vcInstallDir = GetEnv ("VCINSTALLDIR", "");
1930 if (vcInstallDir.Length != 0) {
1931 List<InstalledSDKInfo> installedVisualStudioSDKs = InitializeInstalledVisualStudioSDKs ();
1932 if (installedVisualStudioSDKs != null) {
1933 foreach (var currentInstalledSDK in installedVisualStudioSDKs) {
1934 // Find installed SDK based on requested info.
1935 visualStudioVCSDK = currentInstalledSDK.AdditionalSDKs.Find (x => x.InstallationFolder == vcInstallDir);
1936 if (visualStudioVCSDK != null)
1942 // Get latest installed VS VC SDK version.
1943 if (visualStudioVCSDK == null) {
1944 var visualStudioSDK = GetInstalledVisualStudioSDK ();
1945 if (visualStudioSDK != null)
1946 visualStudioVCSDK = visualStudioSDK.AdditionalSDKs.Find (x => x.Name == "VisualStudioVC");
1949 return visualStudioVCSDK;
1952 public bool IsVisualStudio12 (InstalledSDKInfo vsSDK)
1954 return vsSDK.Version.Major == 12 || vsSDK.Version.Major == 2013;
1957 public bool IsVisualStudio14 (InstalledSDKInfo vsSDK)
1959 return vsSDK.Version.Major == 14 || vsSDK.Version.Major == 2015;
1962 public bool IsVisualStudio15 (InstalledSDKInfo vsSDK)
1964 return vsSDK.Version.Major == 15 || vsSDK.Version.Major == 2017;
1967 public void AddVisualStudioVCIncludePaths (List<string> includePaths)
1969 // Check that env doesn't already include needed values.
1970 string vcIncludeDir = GetEnv ("VSINCLUDE", "");
1971 if (vcIncludeDir.Length == 0) {
1972 var visualStudioVCSDK = GetInstalledVisualStudioVCSDK ();
1973 vcIncludeDir = FindVisualStudioVCFolderPath (visualStudioVCSDK, "include");
1976 if (vcIncludeDir.Length != 0)
1977 includePaths.Add (vcIncludeDir);
1982 public void AddVisualStudioVCLibPaths (List<string> libPaths)
1984 // Check that env doesn't already include needed values.
1985 string vcLibDir = GetEnv ("VSLIB", "");
1986 if (vcLibDir.Length == 0) {
1987 var vcSDK = GetInstalledVisualStudioVCSDK ();
1988 vcLibDir = FindVisualStudioVCFolderPath (vcSDK, FindVisualStudioVCLibSubPath (vcSDK));
1991 if (vcLibDir.Length != 0)
1992 libPaths.Add (vcLibDir);
1998 class VCToolchainProgram {
2000 protected ToolchainProgram toolchain;
2001 public virtual bool IsVersion (InstalledSDKInfo vcSDK) { return false; }
2002 public virtual ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK) { return null; }
2005 class VC12ToolchainProgram : VCToolchainProgram {
2007 public override bool IsVersion (InstalledSDKInfo vcSDK)
2009 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio12 (vcSDK);
2012 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
2014 if (toolchain == null) {
2015 string toolPath = "";
2016 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2017 if (Target64BitApplication ())
2018 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", "amd64", tool });
2020 toolPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "bin", tool });
2022 if (!File.Exists (toolPath))
2026 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2033 class VC15ToolchainProgram : VCToolchainProgram {
2034 public override bool IsVersion (InstalledSDKInfo vcSDK)
2036 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2039 protected ToolchainProgram FindVCToolchainProgram (string tool, InstalledSDKInfo vcSDK)
2041 if (toolchain == null) {
2042 string toolPath = "";
2043 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2044 string toolsVersionFilePath = Path.Combine (vcSDK.InstallationFolder, "Auxiliary", "Build", "Microsoft.VCToolsVersion.default.txt");
2045 string toolsVersion = File.ReadAllLines (toolsVersionFilePath).ElementAt (0).Trim ();
2046 string toolsVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "MSVC", toolsVersion);
2048 if (Target64BitApplication ())
2049 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX64", "x64", tool);
2051 toolPath = Path.Combine (toolsVersionPath, "bin", "HostX86", "x86", tool);
2054 toolchain = new ToolchainProgram (tool, toolPath, vcSDK);
2061 class VC12Compiler : VC12ToolchainProgram {
2062 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2064 return FindVCToolchainProgram ("cl.exe", vcSDK);
2068 class VC14Compiler : VC12Compiler {
2069 public override bool IsVersion (InstalledSDKInfo vcSDK)
2071 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2075 class VC15Compiler : VC15ToolchainProgram {
2076 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2078 return FindVCToolchainProgram ("cl.exe", vcSDK);
2082 class VC12Librarian : VC12ToolchainProgram {
2083 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2085 return FindVCToolchainProgram ("lib.exe", vcSDK);
2089 class VC14Librarian : VC12Compiler {
2090 public override bool IsVersion (InstalledSDKInfo vcSDK)
2092 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2096 class VC15Librarian : VC15ToolchainProgram {
2097 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2099 return FindVCToolchainProgram ("lib.exe", vcSDK);
2103 class VC14Clang : VCToolchainProgram {
2104 public override bool IsVersion (InstalledSDKInfo vcSDK)
2106 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio14 (vcSDK);
2109 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2111 if (toolchain == null) {
2112 string clangPath = "";
2113 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2114 clangPath = Path.Combine (new string [] { vcSDK.InstallationFolder, "ClangC2", "bin", Target64BitApplication () ? "amd64" : "x86", "clang.exe" });
2116 if (!File.Exists (clangPath))
2120 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2127 class VC15Clang : VCToolchainProgram {
2128 public override bool IsVersion (InstalledSDKInfo vcSDK)
2130 return VisualStudioSDKHelper.GetInstance ().IsVisualStudio15 (vcSDK);
2133 public override ToolchainProgram FindVCToolchainProgram (InstalledSDKInfo vcSDK)
2135 if (toolchain == null) {
2136 string clangPath = "";
2137 if (!string.IsNullOrEmpty (vcSDK?.InstallationFolder)) {
2138 string clangVersionFilePath = Path.Combine (vcSDK.InstallationFolder, "Auxiliary", "Build", "Microsoft.ClangC2Version.default.txt");
2139 string clangVersion = File.ReadAllLines (clangVersionFilePath).ElementAt (0).Trim ();
2140 string clangVersionPath = Path.Combine (vcSDK.InstallationFolder, "Tools", "ClangC2", clangVersion);
2142 clangPath = Path.Combine (clangVersionPath, "bin", Target64BitApplication () ? "HostX64" : "HostX86", "clang.exe");
2145 toolchain = new ToolchainProgram ("clang.exe", clangPath, vcSDK);
2152 class VisualStudioSDKToolchainHelper {
2153 List<VCToolchainProgram> vcCompilers = new List<VCToolchainProgram> ();
2154 List<VCToolchainProgram> vcLibrarians = new List<VCToolchainProgram> ();
2155 List<VCToolchainProgram> vcClangCompilers = new List<VCToolchainProgram> ();
2157 public VisualStudioSDKToolchainHelper ()
2159 vcCompilers.Add (new VC12Compiler ());
2160 vcCompilers.Add (new VC14Compiler ());
2161 vcCompilers.Add (new VC15Compiler ());
2163 vcLibrarians.Add (new VC12Librarian ());
2164 vcLibrarians.Add (new VC14Librarian ());
2165 vcLibrarians.Add (new VC15Librarian ());
2167 vcClangCompilers.Add (new VC14Clang ());
2168 vcClangCompilers.Add (new VC15Clang ());
2171 static VisualStudioSDKToolchainHelper singletonInstance = new VisualStudioSDKToolchainHelper ();
2172 static public VisualStudioSDKToolchainHelper GetInstance ()
2174 return singletonInstance;
2177 ToolchainProgram GetVCToolChainProgram (List<VCToolchainProgram> programs)
2179 ToolchainProgram program = null;
2180 var vcSDK = VisualStudioSDKHelper.GetInstance ().GetInstalledVisualStudioVCSDK ();
2181 if (vcSDK?.ParentSDK != null) {
2182 foreach (var item in programs) {
2183 if (item.IsVersion (vcSDK.ParentSDK)) {
2184 program = item.FindVCToolchainProgram (vcSDK);
2193 public ToolchainProgram GetVCCompiler ()
2195 return GetVCToolChainProgram (vcCompilers);
2198 public ToolchainProgram GetVCLibrarian ()
2200 return GetVCToolChainProgram (vcLibrarians);
2203 public ToolchainProgram GetVCClangCompiler ()
2205 return GetVCToolChainProgram (vcClangCompilers);
2209 static bool Target64BitApplication ()
2211 // Should probably handled the --cross and sdk parameters.
2212 return Environment.Is64BitProcess;
2215 static string GetMonoDir ()
2217 // Check that env doesn't already include needed values.
2218 string monoInstallDir = GetEnv ("MONOPREFIX", "");
2219 if (monoInstallDir.Length == 0) {
2220 using (var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey (Microsoft.Win32.RegistryHive.LocalMachine,
2221 Target64BitApplication () ? Microsoft.Win32.RegistryView.Registry64 : Microsoft.Win32.RegistryView.Registry32)) {
2223 if (baseKey != null) {
2224 using (var subKey = baseKey.OpenSubKey (@"SOFTWARE\Mono")) {
2226 monoInstallDir = (string)subKey.GetValue ("SdkInstallRoot", "");
2232 return monoInstallDir;
2235 static void AddMonoIncludePaths (List<string> includePaths)
2237 includePaths.Add (Path.Combine (GetMonoDir (), @"include\mono-2.0"));
2241 static void AddMonoLibPaths (List<string> libPaths)
2243 libPaths.Add (Path.Combine (GetMonoDir (), "lib"));
2247 static void AddIncludePaths (List<string> includePaths)
2249 // Check that env doesn't already include needed values.
2250 // If executed from a VS developer command prompt, all includes are already setup in env.
2251 string includeEnv = GetEnv ("INCLUDE", "");
2252 if (includeEnv.Length == 0) {
2253 VisualStudioSDKHelper.GetInstance ().AddVisualStudioVCIncludePaths (includePaths);
2254 WindowsSDKHelper.GetInstance ().AddCRuntimeSDKIncludePaths (includePaths);
2255 WindowsSDKHelper.GetInstance ().AddWindowsSDKIncludePaths (includePaths);
2258 AddMonoIncludePaths (includePaths);
2259 includePaths.Add (".");
2264 static void AddLibPaths (List<string> libPaths)
2266 // Check that env doesn't already include needed values.
2267 // If executed from a VS developer command prompt, all libs are already setup in env.
2268 string libEnv = GetEnv ("LIB", "");
2269 if (libEnv.Length == 0) {
2270 VisualStudioSDKHelper.GetInstance ().AddVisualStudioVCLibPaths (libPaths);
2271 WindowsSDKHelper.GetInstance ().AddCRuntimeSDKLibPaths (libPaths);
2272 WindowsSDKHelper.GetInstance ().AddWindowsSDKLibPaths (libPaths);
2275 AddMonoLibPaths (libPaths);
2281 static void AddVCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2283 linkerArgs.Add ("kernel32.lib");
2284 linkerArgs.Add ("version.lib");
2285 linkerArgs.Add ("ws2_32.lib");
2286 linkerArgs.Add ("mswsock.lib");
2287 linkerArgs.Add ("psapi.lib");
2288 linkerArgs.Add ("shell32.lib");
2289 linkerArgs.Add ("oleaut32.lib");
2290 linkerArgs.Add ("ole32.lib");
2291 linkerArgs.Add ("winmm.lib");
2292 linkerArgs.Add ("user32.lib");
2293 linkerArgs.Add ("advapi32.lib");
2295 if (program != null && program.ParentSDK != null && VisualStudioSDKHelper.GetInstance ().IsVisualStudio12 (program.ParentSDK)) {
2296 if (staticLinkCRuntime) {
2297 // Static release c-runtime support.
2298 linkerArgs.Add ("libcmt.lib");
2299 linkerArgs.Add ("oldnames.lib");
2301 // Dynamic release c-runtime support.
2302 linkerArgs.Add ("msvcrt.lib");
2303 linkerArgs.Add ("oldnames.lib");
2306 if (staticLinkCRuntime) {
2307 // Static release c-runtime support.
2308 linkerArgs.Add ("libucrt.lib");
2309 linkerArgs.Add ("libvcruntime.lib");
2310 linkerArgs.Add ("libcmt.lib");
2311 linkerArgs.Add ("oldnames.lib");
2313 // Dynamic release c-runtime support.
2314 linkerArgs.Add ("ucrt.lib");
2315 linkerArgs.Add ("vcruntime.lib");
2316 linkerArgs.Add ("msvcrt.lib");
2317 linkerArgs.Add ("oldnames.lib");
2324 static void AddGCCSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2326 if (MakeBundle.compress)
2327 linkerArgs.Add ("-lz");
2332 static void AddSystemLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArgs)
2334 if (program.IsVSToolChain)
2335 AddVCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2337 AddGCCSystemLibraries (program, staticLinkMono, staticLinkCRuntime, linkerArgs);
2342 static void AddMonoLibraries (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> linkerArguments)
2344 bool vsToolChain = program.IsVSToolChain;
2345 string libPrefix = !vsToolChain ? "-l" : "";
2346 string libExtension = vsToolChain ? ".lib" : "";
2347 string monoLibrary = GetEnv ("LIBMONO", "");
2349 if (monoLibrary.Length == 0) {
2350 if (staticLinkMono) {
2351 if (program.IsGCCToolChain) {
2352 Console.WriteLine ( @"Warning: Static linking using default Visual Studio build libmono-static-sgen" +
2353 @"might cause link errors when using GCC toolchain.");
2355 monoLibrary = "libmono-static-sgen";
2357 monoLibrary = "mono-2.0-sgen";
2361 if (!Path.IsPathRooted (monoLibrary)) {
2362 if (!monoLibrary.EndsWith (libExtension))
2363 monoLibrary = monoLibrary + libExtension;
2365 linkerArguments.Add (libPrefix + monoLibrary);
2367 linkerArguments.Add (monoLibrary);
2373 static void AddVCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2375 List<string> includePaths = new List<string> ();
2376 AddIncludePaths (includePaths);
2378 if (staticLinkCRuntime)
2379 // Add targeted c-runtime (MT = static release).
2380 compilerArgs.Add ("/MT");
2382 // Add targeted c-runtime (MD = dynamic release).
2383 compilerArgs.Add ("/MD");
2385 // Add include search paths.
2386 foreach (string include in includePaths)
2387 compilerArgs.Add (String.Format("/I {0}", program.QuoteArg (include)));
2392 static void AddGCCCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2394 List<string> includePaths = new List<string> ();
2395 AddMonoIncludePaths (includePaths);
2397 // Add include search paths.
2398 foreach (string include in includePaths)
2399 compilerArgs.Add (String.Format ("-I {0}", program.QuoteArg (include)));
2404 static void AddCompilerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs)
2406 if (program.IsVSToolChain)
2407 AddVCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2409 AddGCCCompilerArguments (program, staticLinkMono, staticLinkCRuntime, compilerArgs);
2414 static void AddVCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2416 linkerArgs.Add ("/link");
2418 var subsystem = GetEnv ("VCSUBSYSTEM", "windows");
2419 linkerArgs.Add ("/SUBSYSTEM:" + subsystem);
2421 if (customMain != null && customMain.Length != 0)
2422 linkerArgs.Add (linker.QuoteArg (customMain));
2424 linkerArgs.Add ("/ENTRY:mainCRTStartup");
2426 // Ignore other c-runtime directives from linked libraries.
2427 linkerArgs.Add ("/NODEFAULTLIB");
2429 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2430 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2432 // Add library search paths.
2433 List<string> libPaths = new List<string> ();
2434 AddLibPaths (libPaths);
2436 foreach (string lib in libPaths)
2437 linkerArgs.Add (String.Format ("/LIBPATH:{0}", linker.QuoteArg (lib)));
2439 // Linker output target.
2440 linkerArgs.Add ("/OUT:" + linker.QuoteArg (outputFile));
2445 static void AddGCCLinkerArguments (ToolchainProgram linker, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2447 // Add library search paths.
2448 List<string> libPaths = new List<string> ();
2449 AddMonoLibPaths (libPaths);
2451 foreach (string lib in libPaths)
2452 linkerArgs.Add (String.Format ("-L {0}", linker.QuoteArg (lib)));
2456 linkerArgs.Add ("-Wl,-Bstatic");
2458 AddMonoLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2461 linkerArgs.Add ("-Wl,-Bdynamic");
2463 AddSystemLibraries (linker, staticLinkMono, staticLinkCRuntime, linkerArgs);
2465 // Linker output target.
2466 linkerArgs.Add ("-o " + linker.QuoteArg (outputFile));
2469 static void AddLinkerArguments (ToolchainProgram program, bool staticLinkMono, bool staticLinkCRuntime, string customMain, string outputFile, List<string> linkerArgs)
2471 if (program.IsVSToolChain)
2472 AddVCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2474 AddGCCLinkerArguments (program, staticLinkMono, staticLinkCRuntime, customMain, outputFile, linkerArgs);
2479 static void AddVCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2481 compilerArgs.Add ("/c");
2482 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2484 objectFile = sourceFile + ".obj";
2485 compilerArgs.Add (String.Format ("/Fo" + compiler.QuoteArg (objectFile)));
2490 static void AddGCCLibrarianCompilerArguments (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, List<string> compilerArgs, out string objectFile)
2492 compilerArgs.Add ("-c");
2493 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2495 objectFile = sourceFile + ".o";
2496 compilerArgs.Add (String.Format ("-o " + compiler.QuoteArg (objectFile)));
2501 static void AddVCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2503 foreach (var objectFile in objectFiles)
2504 librarianArgs.Add (librarian.QuoteArg (objectFile));
2506 // Add library search paths.
2507 List<string> libPaths = new List<string> ();
2508 AddLibPaths (libPaths);
2510 foreach (string lib in libPaths) {
2511 librarianArgs.Add (String.Format ("/LIBPATH:{0}", librarian.QuoteArg (lib)));
2514 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2516 librarianArgs.Add ("/OUT:" + librarian.QuoteArg (output));
2521 static void AddGCCLibrarianLinkerArguments (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile, List<string> librarianArgs)
2523 foreach (var objectFile in objectFiles)
2524 librarianArgs.Add (librarian.QuoteArg (objectFile));
2526 // Add library search paths.
2527 List<string> libPaths = new List<string> ();
2528 AddMonoLibPaths (libPaths);
2530 foreach (string lib in libPaths)
2531 librarianArgs.Add (String.Format ("-L {0}", librarian.QuoteArg (lib)));
2533 AddMonoLibraries (librarian, staticLinkMono, staticLinkCRuntime, librarianArgs);
2535 librarianArgs.Add ("-o " + librarian.QuoteArg (output));
2540 static ToolchainProgram GetAssemblerCompiler ()
2542 // First check if env is set (old behavior) and use that.
2543 string assembler = GetEnv ("AS", "");
2544 if (assembler.Length != 0)
2545 return new ToolchainProgram ("AS", assembler);
2547 var vcClangAssembler = VisualStudioSDKToolchainHelper.GetInstance ().GetVCClangCompiler ();
2548 if (vcClangAssembler == null)
2549 // Fallback to GNU assembler if clang for VS was not installed.
2550 // Why? because mkbundle generates GNU assembler not compilable by VS tools like ml.
2551 return new ToolchainProgram ("AS", "as.exe");
2553 return vcClangAssembler;
2556 static ToolchainProgram GetCCompiler ()
2558 // First check if env is set (old behavior) and use that.
2559 string compiler = GetEnv ("CC", "");
2560 if (compiler.Length != 0)
2561 return new ToolchainProgram ("CC", compiler);
2563 var vcCompiler = VisualStudioSDKToolchainHelper.GetInstance ().GetVCCompiler ();
2564 if (vcCompiler == null)
2565 // Fallback to cl.exe if VC compiler was not installed.
2566 return new ToolchainProgram ("cl.exe", "cl.exe");
2571 static ToolchainProgram GetLibrarian ()
2573 ToolchainProgram vcLibrarian = VisualStudioSDKToolchainHelper.GetInstance ().GetVCLibrarian ();
2574 if (vcLibrarian == null)
2575 // Fallback to lib.exe if VS was not installed.
2576 return new ToolchainProgram ("lib.exe", "lib.exe");
2581 static string GetCompileAndLinkCommand (ToolchainProgram compiler, string sourceFile, string objectFile, string customMain, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2583 var compilerArgs = new List<string> ();
2585 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2587 // Add source file to compile.
2588 compilerArgs.Add (compiler.QuoteArg (sourceFile));
2590 // Add assembled object file.
2591 compilerArgs.Add (compiler.QuoteArg (objectFile));
2593 // Add linker arguments.
2594 AddLinkerArguments (compiler, staticLinkMono, staticLinkCRuntime, customMain, outputFile, compilerArgs);
2596 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs.ToArray ()));
2599 static string GetLibrarianCompilerCommand (ToolchainProgram compiler, string sourceFile, bool staticLinkMono, bool staticLinkCRuntime, out string objectFile)
2601 var compilerArgs = new List<string> ();
2603 AddCompilerArguments (compiler, staticLinkMono, staticLinkCRuntime, compilerArgs);
2605 if (compiler.IsVSToolChain)
2606 AddVCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2608 AddGCCLibrarianCompilerArguments (compiler, sourceFile, staticLinkMono, staticLinkCRuntime, compilerArgs, out objectFile);
2610 return String.Format ("{0} {1}", compiler.QuoteArg (compiler.Path), String.Join (" ", compilerArgs.ToArray ()));
2613 static string GetLibrarianLinkerCommand (ToolchainProgram librarian, string [] objectFiles, bool staticLinkMono, bool staticLinkCRuntime, string outputFile)
2615 var librarianArgs = new List<string> ();
2617 if (librarian.IsVSToolChain)
2618 AddVCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2620 AddGCCLibrarianLinkerArguments (librarian, objectFiles, staticLinkMono, staticLinkCRuntime, outputFile, librarianArgs);
2622 return String.Format ("{0} {1}", librarian.QuoteArg (librarian.Path), String.Join (" ", librarianArgs.ToArray ()));