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 List<string> aot_paths = new List<string> ();
44 static List<string> aot_names = new List<string> ();
45 static Dictionary<string,string> libraries = new Dictionary<string,string> ();
46 static bool autodeps = false;
47 static string in_tree = null;
48 static bool keeptemp = false;
49 static bool compile_only = false;
50 static bool static_link = false;
51 static string config_file = null;
52 static string machine_config_file = null;
53 static string config_dir = null;
54 static string style = "linux";
55 static bool bundled_header = false;
56 static string os_message = "";
59 static string custom_main = null;
60 static bool? use_dos2unix = null;
61 static bool skip_scan;
62 static string ctor_func;
63 static bool quiet = true;
64 static string cross_target = null;
65 static string fetch_target = null;
66 static bool custom_mode = true;
67 static string embedded_options = null;
69 static string runtime_bin = null;
71 static string runtime {
73 if (runtime_bin == null && IsUnix)
74 runtime_bin = Process.GetCurrentProcess().MainModule.FileName;
78 set { runtime_bin = value; }
81 static bool aot_compile = false;
82 static string aot_args = "static";
83 static DirectoryInfo aot_temp_dir = null;
84 static string aot_mode = "";
85 static string aot_runtime = null;
86 static string aot_dedup_assembly = null;
87 static string cil_strip_path = null;
88 static string managed_linker_path = null;
89 static string sdk_path = null;
90 static string lib_path = null;
91 static Dictionary<string,string> environment = new Dictionary<string,string>();
92 static string [] i18n = new string [] {
96 static string [] i18n_all = new string [] {
104 static string target_server = "https://download.mono-project.com/runtimes/raw/";
106 static int Main (string [] args)
108 List<string> sources = new List<string> ();
109 int top = args.Length;
110 link_paths.Add (".");
114 for (int i = 0; i < top; i++){
116 case "--help": case "-h": case "-?":
134 var iarg = args [++i];
137 else if (iarg == "none")
138 i18n = new string [0];
140 i18n = iarg.Split (',');
151 case "--local-targets":
152 CommandLocalTargets ();
160 if (sdk_path != null || runtime != null)
161 Error ("You can only specify one of --runtime, --sdk or --cross");
164 cross_target = args [++i];
173 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
177 var lspec = args [++i];
178 var p = lspec.IndexOf (",");
181 alias = Path.GetFileName (lspec);
184 alias = lspec.Substring (0, p);
185 path = lspec.Substring (p+1);
187 if (!File.Exists (path))
188 Error ($"The specified library file {path} does not exist");
189 libraries [alias] = path;
192 case "--fetch-target":
197 fetch_target = args [++i];
200 case "--list-targets":
201 CommandLocalTargets ();
202 var wc = new WebClient ();
203 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
204 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
207 case "--target-server":
212 target_server = args [++i];
228 embedded_options = args [++i];
237 sdk_path = args [++i];
238 if (cross_target != null || runtime != null)
239 Error ("You can only specify one of --runtime, --sdk or --cross");
246 if (sdk_path != null || cross_target != null)
247 Error ("You can only specify one of --runtime, --sdk or --cross");
250 runtime = args [++i];
257 object_out = args [++i];
265 link_paths.Add (args [++i]);
289 config_file = args [++i];
291 case "--machine-config":
297 machine_config_file = args [++i];
300 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
308 config_dir = args [++i];
316 case "--custom-main":
321 custom_main = args [++i];
335 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
343 case "--static-ctor":
348 ctor_func = args [++i];
351 case "--dos2unix=true":
354 case "--dos2unix=false":
355 use_dos2unix = false;
367 var env = args [++i];
368 p = env.IndexOf ('=');
370 environment.Add (env, "");
372 environment.Add (env.Substring (0, p), env.Substring (p+1));
374 case "--bundled-header":
375 bundled_header = true;
379 Console.WriteLine ("Usage: --in-tree <path/to/headers> ");
382 in_tree = args [++i];
384 case "--managed-linker":
386 Console.WriteLine ("Usage: --managed-linker <path/to/exe> ");
389 managed_linker_path = args [++i];
393 Console.WriteLine ("Usage: --cil-strip <path/to/exe> ");
396 cil_strip_path = args [++i];
398 case "--aot-runtime":
400 Console.WriteLine ("Usage: --aot-runtime <path/to/runtime> ");
403 aot_runtime = args [++i];
409 Console.WriteLine ("Usage: --aot-dedup <container_dll> ");
412 var rel_path = args [++i];
413 var asm = LoadAssembly (rel_path);
415 aot_dedup_assembly = new Uri(asm.CodeBase).LocalPath;
417 sources.Add (rel_path);
423 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
427 aot_mode = args [++i];
428 if (aot_mode != "full" && aot_mode != "llvmonly") {
429 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
438 Console.WriteLine ("AOT arguments are passed as a comma-delimited list");
441 if (args [i + 1].Contains ("outfile")) {
442 Console.WriteLine ("Per-aot-output arguments (ex: outfile, llvm-outfile) cannot be given");
445 aot_args = String.Format("static,{0}", args [++i]);
450 sources.Add (args [i]);
455 // Modern bundling starts here
457 if (runtime != null){
458 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
459 } else if (sdk_path != null) {
460 VerifySdk (sdk_path);
461 } else if (cross_target == "default" || cross_target == null){
462 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
463 VerifySdk (sdk_path);
465 sdk_path = Path.Combine (targets_dir, cross_target);
466 Console.WriteLine ("From: " + sdk_path);
467 VerifySdk (sdk_path);
471 if (fetch_target != null){
472 var directory = Path.Combine (targets_dir, fetch_target);
473 var zip_download = Path.Combine (directory, "sdk.zip");
474 Directory.CreateDirectory (directory);
475 var wc = new WebClient ();
476 var uri = new Uri ($"{target_server}{fetch_target}");
479 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
482 wc.DownloadFile (uri, zip_download);
483 ZipFile.ExtractToDirectory(zip_download, directory);
484 File.Delete (zip_download);
486 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
487 File.Delete (zip_download);
494 Console.WriteLine (os_message);
495 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
498 if (sources.Count == 0 || output == null) {
500 Environment.Exit (1);
503 List<string> assemblies = LoadAssemblies (sources);
504 LoadLocalizedAssemblies (assemblies);
505 List<string> files = new List<string> ();
506 foreach (string file in assemblies)
507 if (!QueueAssembly (files, file))
510 PreprocessAssemblies (assemblies, files);
516 GenerateBundles (files);
518 GeneratePackage (files);
520 Console.WriteLine ("Generated {0}", output);
525 static void VerifySdk (string path)
527 if (!Directory.Exists (path))
528 Error ($"The specified SDK path does not exist: {path}");
529 runtime = Path.Combine (sdk_path, "bin", "mono");
530 if (!File.Exists (runtime))
531 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
532 lib_path = Path.Combine (path, "lib", "mono", "4.5");
533 if (!Directory.Exists (lib_path))
534 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
535 link_paths.Add (lib_path);
538 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
540 static void CommandLocalTargets ()
544 Console.WriteLine ("Available targets locally:");
545 Console.WriteLine ("\tdefault\t- Current System Mono");
547 targets = Directory.GetDirectories (targets_dir);
551 foreach (var target in targets){
552 var p = Path.Combine (target, "bin", "mono");
554 Console.WriteLine ("\t{0}", Path.GetFileName (target));
558 static void WriteSymbol (StreamWriter sw, string name, long size)
564 "\t.section .rodata\n" +
566 "\t.type {0}, \"object\"\n" +
567 "\t.size {0}, {1}\n" +
573 "\t.section __TEXT,__text,regular,pure_instructions\n" +
583 "\t.section .rdata,\"dr\"\n" +
591 static string [] chars = new string [256];
593 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
597 // Preallocate the strings we need.
598 if (chars [0] == null) {
599 for (int i = 0; i < chars.Length; i++)
600 chars [i] = string.Format ("{0}", i.ToString ());
603 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
605 for (int i = 0; i < n; i++) {
606 if (count % 32 == 0) {
607 ts.Write ("\n\t.byte ");
611 ts.Write (chars [buffer [i]]);
620 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
621 const int align = 4096;
624 public PackageMaker (string output)
626 package = File.Create (output, 128*1024);
628 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
632 public int AddFile (string fname)
634 using (Stream fileStream = File.OpenRead (fname)){
635 var ret = fileStream.Length;
638 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
639 fileStream.CopyTo (package);
640 package.Position = package.Position + (align - (package.Position % align));
645 public void Add (string entry, string fname)
647 var p = package.Position;
648 var size = AddFile (fname);
649 locations [entry] = Tuple.Create(p, size);
652 public void AddString (string entry, string text)
654 var bytes = Encoding.UTF8.GetBytes (text);
655 locations [entry] = Tuple.Create (package.Position, bytes.Length);
656 package.Write (bytes, 0, bytes.Length);
657 package.Position = package.Position + (align - (package.Position % align));
660 public void AddStringPair (string entry, string key, string value)
662 var kbytes = Encoding.UTF8.GetBytes (key);
663 var vbytes = Encoding.UTF8.GetBytes (value);
665 Console.WriteLine ("ADDING {0} to {1}", key, value);
666 if (kbytes.Length > 255){
667 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
668 Environment.Exit (1);
671 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
672 package.WriteByte ((byte)kbytes.Length);
673 package.Write (kbytes, 0, kbytes.Length);
674 package.WriteByte (0);
675 package.Write (vbytes, 0, vbytes.Length);
676 package.WriteByte (0);
677 package.Position = package.Position + (align - (package.Position % align));
684 foreach (var floc in locations.Keys){
685 Console.WriteLine ($"{floc} at {locations[floc]:x}");
689 public void WriteIndex ()
691 var indexStart = package.Position;
692 var binary = new BinaryWriter (package);
694 binary.Write (locations.Count);
695 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
696 var bytes = Encoding.UTF8.GetBytes (entry.Key);
697 binary.Write (bytes.Length+1);
698 binary.Write (bytes);
699 binary.Write ((byte) 0);
700 binary.Write (entry.Value.Item1);
701 binary.Write (entry.Value.Item2);
703 binary.Write (indexStart);
704 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
716 static bool MaybeAddFile (PackageMaker maker, string code, string file)
721 if (!File.Exists (file)){
722 Error ("The file {0} does not exist", file);
725 maker.Add (code, file);
729 static bool GeneratePackage (List<string> files)
731 if (runtime == null){
732 Error ("You must specify at least one runtime with --runtime or --cross");
733 Environment.Exit (1);
735 if (!File.Exists (runtime)){
736 Error ($"The specified runtime at {runtime} does not exist");
737 Environment.Exit (1);
740 if (ctor_func != null){
741 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
745 var maker = new PackageMaker (output);
746 Console.WriteLine ("Using runtime: " + runtime);
747 maker.AddFile (runtime);
749 foreach (var url in files){
750 string fname = LocateFile (new Uri (url).LocalPath);
751 string aname = MakeBundle.GetAssemblyName (fname);
753 maker.Add ("assembly:" + aname, fname);
754 Console.WriteLine (" Assembly: " + fname);
755 if (File.Exists (fname + ".config")){
756 maker.Add ("config:" + aname, fname + ".config");
757 Console.WriteLine (" Config: " + runtime);
761 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
764 if (config_dir != null)
765 maker.Add ("config_dir:", config_dir);
766 if (embedded_options != null)
767 maker.AddString ("options:", embedded_options);
768 if (environment.Count > 0){
769 foreach (var key in environment.Keys)
770 maker.AddStringPair ("env:" + key, key, environment [key]);
772 if (libraries.Count > 0){
773 foreach (var alias_and_path in libraries){
774 Console.WriteLine (" Library: " + alias_and_path.Value);
775 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
783 static void GenerateBundles (List<string> files)
785 string temp_s = "temp.s"; // Path.GetTempFileName ();
786 string temp_c = "temp.c";
787 string temp_o = "temp.o";
791 if (object_out != null)
795 List<string> c_bundle_names = new List<string> ();
796 List<string[]> config_names = new List<string[]> ();
798 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
799 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
802 if (bundled_header) {
803 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
804 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
808 const unsigned char *data;
809 const unsigned int size;
810 } MonoBundledAssembly;
811 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
812 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
815 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
816 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
819 tc.WriteLine ("#include <mono/mini/jit.h>\n");
821 tc.WriteLine ("#include <mono/jit/jit.h>\n");
825 tc.WriteLine ("typedef struct _compressed_data {");
826 tc.WriteLine ("\tMonoBundledAssembly assembly;");
827 tc.WriteLine ("\tint compressed_size;");
828 tc.WriteLine ("} CompressedAssembly;\n");
831 object monitor = new object ();
833 var streams = new Dictionary<string, Stream> ();
834 var sizes = new Dictionary<string, long> ();
836 // Do the file reading and compression in parallel
837 Action<string> body = delegate (string url) {
838 string fname = LocateFile (new Uri (url).LocalPath);
839 Stream stream = File.OpenRead (fname);
841 long real_size = stream.Length;
844 byte[] cbuffer = new byte [8192];
845 MemoryStream ms = new MemoryStream ();
846 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
847 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
848 deflate.Write (cbuffer, 0, n);
852 byte [] bytes = ms.GetBuffer ();
853 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
857 streams [url] = stream;
858 sizes [url] = real_size;
864 Parallel.ForEach (files, body);
866 foreach (var url in files)
870 // The non-parallel part
871 byte [] buffer = new byte [8192];
872 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
873 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
874 foreach (var url in files) {
875 string fname = LocateFile (new Uri (url).LocalPath);
876 string aname = MakeBundle.GetAssemblyName (fname);
877 string encoded = symbolEscapeRE.Replace (aname, "_");
882 var stream = streams [url];
883 var real_size = sizes [url];
886 Console.WriteLine (" embedding: " + fname);
888 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
890 WriteBuffer (ts, stream, buffer);
893 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
894 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
895 " assembly_data_{0}, {2}}}, {3}}};",
896 encoded, aname, real_size, stream.Length);
898 double ratio = ((double) stream.Length * 100) / real_size;
899 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
902 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
903 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
904 encoded, aname, real_size);
908 c_bundle_names.Add ("assembly_bundle_" + encoded);
911 FileStream cf = File.OpenRead (fname + ".config");
913 Console.WriteLine (" config from: " + fname + ".config");
914 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
915 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
916 WriteBuffer (ts, cf, buffer);
918 config_names.Add (new string[] {aname, encoded});
919 } catch (FileNotFoundException) {
920 /* we ignore if the config file doesn't exist */
924 if (config_file != null){
927 conf = File.OpenRead (config_file);
929 Error ("Failure to open {0}", config_file);
933 Console.WriteLine ("System config from: " + config_file);
934 tc.WriteLine ("extern const char system_config;");
935 WriteSymbol (ts, "system_config", config_file.Length);
937 WriteBuffer (ts, conf, buffer);
939 ts.Write ("\t.byte 0\n");
943 if (machine_config_file != null){
946 conf = File.OpenRead (machine_config_file);
948 Error ("Failure to open {0}", machine_config_file);
952 Console.WriteLine ("Machine config from: " + machine_config_file);
953 tc.WriteLine ("extern const char machine_config;");
954 WriteSymbol (ts, "machine_config", machine_config_file.Length);
956 WriteBuffer (ts, conf, buffer);
957 ts.Write ("\t.byte 0\n");
962 // Managed assemblies baked in
964 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
966 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
968 foreach (string c in c_bundle_names){
969 tc.WriteLine ("\t&{0},", c);
971 tc.WriteLine ("\tNULL\n};\n");
974 // AOT baked in plus loader
975 foreach (string asm in aot_names){
976 tc.WriteLine ("\textern const void *mono_aot_module_{0}_info;", asm);
979 tc.WriteLine ("\nstatic void install_aot_modules (void) {\n");
980 foreach (string asm in aot_names){
981 tc.WriteLine ("\tmono_aot_register_module (mono_aot_module_{0}_info);\n", asm);
984 string enum_aot_mode;
987 enum_aot_mode = "MONO_AOT_MODE_FULL";
990 enum_aot_mode = "MONO_AOT_MODE_LLVMONLY";
993 enum_aot_mode = "MONO_AOT_MODE_NORMAL";
996 throw new Exception ("Unsupported AOT mode");
998 tc.WriteLine ("\tmono_jit_set_aot_mode ({0});", enum_aot_mode);
1000 tc.WriteLine ("\n}\n");
1003 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
1005 if (ctor_func != null) {
1006 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
1007 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
1008 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
1011 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
1012 foreach (string[] ass in config_names){
1013 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
1015 if (config_file != null)
1016 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
1017 if (machine_config_file != null)
1018 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
1019 tc.WriteLine ("}\n");
1021 if (config_dir != null)
1022 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
1024 tc.WriteLine ("static const char *config_dir = NULL;");
1026 Stream template_stream;
1028 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
1030 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
1033 StreamReader s = new StreamReader (template_stream);
1034 string template = s.ReadToEnd ();
1035 tc.Write (template);
1037 if (!nomain && custom_main == null) {
1038 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
1039 StreamReader st = new StreamReader (template_main_stream);
1040 string maintemplate = st.ReadToEnd ();
1041 tc.Write (maintemplate);
1046 string assembler = GetEnv("AS", "as");
1047 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
1054 Console.WriteLine("Compiling:");
1056 if (style == "windows")
1059 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
1061 string compiler = GetEnv("CC", "cl.exe");
1062 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
1063 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
1064 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
1066 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
1067 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
1068 var linkLibraries = new string[] { "kernel32.lib",
1083 string glue_obj = "mkbundle_glue.obj";
1087 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
1090 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
1091 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
1092 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
1095 var compilerArgs = new List<string>();
1096 compilerArgs.Add("/MT");
1098 foreach (string include in includes)
1099 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
1101 if (!nomain || custom_main != null) {
1102 compilerArgs.Add(quote(temp_c));
1103 compilerArgs.Add(quote(temp_o));
1104 if (custom_main != null)
1105 compilerArgs.Add(quote(custom_main));
1106 compilerArgs.Add(quote(monoLib));
1107 compilerArgs.Add("/link");
1108 compilerArgs.Add("/NODEFAULTLIB");
1109 compilerArgs.Add("/SUBSYSTEM:windows");
1110 compilerArgs.Add("/ENTRY:mainCRTStartup");
1111 compilerArgs.AddRange(linkLibraries);
1112 compilerArgs.Add("/out:"+ output);
1114 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1119 // we are just creating a .lib
1120 compilerArgs.Add("/c"); // compile only
1121 compilerArgs.Add(temp_c);
1122 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
1124 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1127 string librarian = GetEnv ("LIB", "lib.exe");
1128 var librarianArgs = new List<string> ();
1129 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
1130 librarianArgs.Add (temp_o);
1131 librarianArgs.Add (glue_obj);
1132 librarianArgs.Add (monoLib);
1133 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1139 string zlib = (compress ? "-lz" : "");
1140 string debugging = "-g";
1141 string cc = GetEnv("CC", "cc");
1144 if (style == "linux")
1145 debugging = "-ggdb";
1148 string platform_libs;
1150 if (style == "osx") {
1151 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1152 platform_libs = "-liconv -framework Foundation ";
1154 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1158 string in_tree_include = "";
1160 if (in_tree != null) {
1161 smonolib = String.Format ("{0}/mono/mini/.libs/libmonosgen-2.0.a", in_tree);
1162 in_tree_include = String.Format (" -I{0} ", in_tree);
1165 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {7} {0} {3} " +
1166 "`pkg-config --libs-only-L mono-2` {5} {6} " + platform_libs +
1167 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1} -g ",
1168 temp_c, temp_o, output, zlib, cc, smonolib, String.Join (" ", aot_paths), in_tree_include);
1173 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1174 temp_c, temp_o, output, zlib, cc);
1180 Console.WriteLine ("Done");
1185 if (object_out == null){
1186 File.Delete (temp_o);
1189 File.Delete (temp_c);
1191 if (aot_temp_dir != null)
1192 aot_temp_dir.Delete (true);
1193 File.Delete (temp_s);
1198 static List<string> LoadAssemblies (List<string> sources)
1200 List<string> assemblies = new List<string> ();
1203 foreach (string name in sources){
1205 Assembly a = LoadAssemblyFile (name);
1212 assemblies.Add (a.CodeBase);
1213 } catch (Exception) {
1216 Console.WriteLine ("File will not be scanned: {0}", name);
1217 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1225 Error ("Couldn't load one or more of the assemblies.");
1226 Environment.Exit (1);
1232 static void LoadLocalizedAssemblies (List<string> assemblies)
1234 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1235 string error = null;
1237 foreach (string name in other) {
1239 Assembly a = LoadAssembly (name);
1242 error = "Failed to load " + name;
1246 assemblies.Add (a.CodeBase);
1247 } catch (Exception) {
1250 Console.WriteLine ("File will not be scanned: {0}", name);
1251 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1258 if (error != null) {
1259 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1260 foreach (var path in link_paths){
1261 Console.Error.WriteLine (" Path: " + path);
1264 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1267 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1268 Environment.Exit (1);
1273 static readonly Universe universe = new Universe ();
1274 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1276 public static string GetAssemblyName (string path)
1278 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1279 string name = Path.GetFileName (path);
1281 // A bit of a hack to support satellite assemblies. They all share the same name but
1282 // are placed in subdirectories named after the locale they implement. Also, all of
1283 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1284 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1285 string dir = Path.GetDirectoryName (path);
1286 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1288 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1289 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1291 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1297 static bool QueueAssembly (List<string> files, string codebase)
1299 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1300 if (files.Contains (codebase))
1303 var path = new Uri(codebase).LocalPath;
1304 var name = GetAssemblyName (path);
1306 if (loaded_assemblies.TryGetValue (name, out found)) {
1307 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1311 loaded_assemblies.Add (name, path);
1313 files.Add (codebase);
1317 Assembly a = universe.LoadFile (path);
1319 Error ("Unable to to load assembly `{0}'", path);
1323 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1324 a = LoadAssembly (an.Name);
1326 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1330 if (!QueueAssembly (files, a.CodeBase))
1333 } catch (Exception) {
1342 // Loads an assembly from a specific path
1344 static Assembly LoadAssemblyFile (string assembly)
1350 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1351 a = universe.LoadFile (assembly);
1353 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1355 } catch (FileNotFoundException){
1356 Error ($"Cannot find assembly `{assembly}'");
1357 } catch (IKVM.Reflection.BadImageFormatException f) {
1360 Error ($"Cannot load assembly (bad file format) " + f.Message);
1361 } catch (FileLoadException f){
1362 Error ($"Cannot load assembly " + f.Message);
1363 } catch (ArgumentNullException){
1364 Error( $"Cannot load assembly (null argument)");
1370 // Loads an assembly from any of the link directories provided
1372 static Assembly LoadAssembly (string assembly)
1374 string total_log = "";
1375 foreach (string dir in link_paths){
1376 string full_path = Path.Combine (dir, assembly);
1378 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1379 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1380 full_path += ".dll";
1383 var a = universe.LoadFile (full_path);
1385 } catch (FileNotFoundException ff) {
1386 total_log += ff.FusionLog;
1391 Console.WriteLine ("Log: \n" + total_log);
1395 static void Error (string msg, params object [] args)
1397 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1398 Environment.Exit (1);
1403 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1405 " --config F Bundle system config file `F'\n" +
1406 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1407 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1408 " -L path Adds `path' to the search path for assemblies\n" +
1409 " --machine-config F Use the given file as the machine.config for the application.\n" +
1410 " -o out Specifies output filename\n" +
1411 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1412 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1413 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1414 " -v Verbose output\n" +
1415 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1417 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1418 " --cross TARGET Generates a binary for the given TARGET\n"+
1419 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1420 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1421 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1422 " LIB is optional shortname for file located at PATH\n" +
1423 " --list-targets Lists available targets on the remote server\n" +
1424 " --local-targets Lists locally available targets\n" +
1425 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1426 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1427 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1428 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1430 "--custom Builds a custom launcher, options for --custom\n" +
1431 " -c Produce stub only, do not compile\n" +
1432 " -oo obj Specifies output filename for helper object file\n" +
1433 " --dos2unix[=true|false]\n" +
1434 " When no value provided, or when `true` specified\n" +
1435 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1436 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1437 " --keeptemp Keeps the temporary files\n" +
1438 " --static Statically link to mono libs\n" +
1439 " --nomain Don't include a main() function, for libraries\n" +
1440 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1441 " -z Compress the assemblies before embedding.\n" +
1442 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1443 " You need zlib development headers and libraries.\n");
1446 [DllImport ("libc")]
1447 static extern int system (string s);
1448 [DllImport ("libc")]
1449 static extern int uname (IntPtr buf);
1451 static void DetectOS ()
1454 os_message = "OS is: Windows";
1459 IntPtr buf = Marshal.AllocHGlobal (8192);
1460 if (uname (buf) != 0){
1461 os_message = "Warning: Unable to detect OS";
1462 Marshal.FreeHGlobal (buf);
1465 string os = Marshal.PtrToStringAnsi (buf);
1466 os_message = "OS is: " + os;
1470 Marshal.FreeHGlobal (buf);
1473 static bool IsUnix {
1475 int p = (int) Environment.OSVersion.Platform;
1476 return ((p == 4) || (p == 128) || (p == 6));
1481 static string EncodeAotSymbol (string symbol)
1483 var sb = new StringBuilder ();
1484 /* This mimics what the aot-compiler does */
1485 foreach (var b in System.Text.Encoding.UTF8.GetBytes (symbol)) {
1487 if ((c >= '0' && c <= '9') ||
1488 (c >= 'a' && c <= 'z') ||
1489 (c >= 'A' && c <= 'Z')) {
1495 return sb.ToString ();
1498 static void AotCompile (List<string> files)
1500 if (aot_runtime == null)
1501 aot_runtime = runtime;
1503 if (aot_runtime == null) {
1504 Error ("You must specify at least one aot runtime with --runtime or --cross or --aot_runtime when AOT compiling");
1505 Environment.Exit (1);
1508 var aot_mode_string = "";
1509 if (aot_mode != null)
1510 aot_mode_string = "," + aot_mode;
1512 var dedup_mode_string = "";
1513 StringBuilder all_assemblies = null;
1514 if (aot_dedup_assembly != null) {
1515 dedup_mode_string = ",dedup-skip";
1516 all_assemblies = new StringBuilder("");
1519 Console.WriteLine ("Aoting files:");
1521 for (int i=0; i < files.Count; i++) {
1522 var file_name = files [i];
1523 string path = LocateFile (new Uri (file_name).LocalPath);
1524 string outPath = String.Format ("{0}.aot_out", path);
1525 aot_paths.Add (outPath);
1526 var name = System.Reflection.Assembly.LoadFrom(path).GetName().Name;
1527 aot_names.Add (EncodeAotSymbol (name));
1529 if (aot_dedup_assembly != null) {
1530 all_assemblies.Append (path);
1531 all_assemblies.Append (" ");
1532 Execute (String.Format ("MONO_PATH={0} {1} --aot={2},outfile={3}{4}{5} {6}",
1533 Path.GetDirectoryName (path), aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path));
1535 Execute (String.Format ("MONO_PATH={0} {1} --aot={2},outfile={3}{4} {5}",
1536 Path.GetDirectoryName (path), aot_runtime, aot_args, outPath, aot_mode_string, path));
1539 if (aot_dedup_assembly != null) {
1540 var filePath = new Uri (aot_dedup_assembly).LocalPath;
1541 string path = LocateFile (filePath);
1542 dedup_mode_string = String.Format (",dedup-include={0}", Path.GetFileName(filePath));
1543 string outPath = String.Format ("{0}.aot_out", path);
1544 Execute (String.Format ("MONO_PATH={7} {0} --aot={1},outfile={2}{3}{4} {5} {6}",
1545 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path, all_assemblies.ToString (), Path.GetDirectoryName (path)));
1548 if ((aot_mode == "full" || aot_mode == "llvmonly") && cil_strip_path != null) {
1549 for (int i=0; i < files.Count; i++) {
1550 var in_name = new Uri (files [i]).LocalPath;
1551 var cmd = String.Format ("{0} {1} {2}", aot_runtime, cil_strip_path, in_name);
1557 static void LinkManaged (List <string> files, string outDir)
1559 if (managed_linker_path == null)
1562 var paths = new StringBuilder ("");
1563 foreach (var file in files) {
1564 paths.Append (" -a ");
1565 paths.Append (new Uri (file).LocalPath);
1568 var cmd = String.Format ("{0} {1} -b true -out {2} {3} -c link -p copy ", runtime, managed_linker_path, outDir, paths.ToString ());
1572 static void PreprocessAssemblies (List <string> chosenFiles, List <string> files)
1574 if (aot_mode == "" || (cil_strip_path == null && managed_linker_path == null))
1577 var temp_dir_name = Path.Combine(Directory.GetCurrentDirectory(), "temp_assemblies");
1578 aot_temp_dir = new DirectoryInfo (temp_dir_name);
1579 if (aot_temp_dir.Exists) {
1580 Console.WriteLine ("Removing previous build cache at {0}", temp_dir_name);
1581 aot_temp_dir.Delete (true);
1583 aot_temp_dir.Create ();
1585 //if (managed_linker_path != null) {
1586 //LinkManaged (chosenFiles, temp_dir);
1588 //// Replace list with new list of files
1590 //Console.WriteLine ("Iterating {0}", temp_dir);
1591 //aot_temp_dir = new DirectoryInfo (temp_dir);
1592 //foreach (var file in aot_temp_dir.GetFiles ()) {
1593 //files.Append (String.Format ("file:///{0}", file));
1594 //Console.WriteLine (String.Format ("file:///{0}", file));
1599 // Fix file references
1600 for (int i=0; i < files.Count; i++) {
1601 var in_name = new Uri (files [i]).LocalPath;
1602 var out_name = Path.Combine (temp_dir_name, Path.GetFileName (in_name));
1603 File.Copy (in_name, out_name);
1604 files [i] = out_name;
1605 if (in_name == aot_dedup_assembly)
1606 aot_dedup_assembly = out_name;
1611 static void Execute (string cmdLine)
1615 Console.WriteLine ("[execute cmd]: " + cmdLine);
1616 int ret = system (cmdLine);
1619 Error(String.Format("[Fail] {0}", ret));
1624 // on Windows, we have to pipe the output of a
1625 // `cmd` interpolation to dos2unix, because the shell does not
1626 // strip the CRLFs generated by the native pkg-config distributed
1629 // But if it's *not* on cygwin, just skip it.
1631 // check if dos2unix is applicable.
1632 if (use_dos2unix == true)
1634 var info = new ProcessStartInfo ("dos2unix");
1635 info.CreateNoWindow = true;
1636 info.RedirectStandardInput = true;
1637 info.UseShellExecute = false;
1638 var dos2unix = Process.Start (info);
1639 dos2unix.StandardInput.WriteLine ("aaa");
1640 dos2unix.StandardInput.WriteLine ("\u0004");
1641 dos2unix.StandardInput.Close ();
1642 dos2unix.WaitForExit ();
1643 if (dos2unix.ExitCode == 0)
1644 use_dos2unix = true;
1646 Console.WriteLine("Warning: dos2unix not found");
1647 use_dos2unix = false;
1650 if (use_dos2unix == null)
1651 use_dos2unix = false;
1653 ProcessStartInfo psi = new ProcessStartInfo();
1654 psi.UseShellExecute = false;
1656 // if there is no dos2unix, just run cmd /c.
1657 if (use_dos2unix == false)
1659 psi.FileName = "cmd";
1660 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1664 psi.FileName = "sh";
1665 StringBuilder b = new StringBuilder();
1667 for (int i = 0; i < cmdLine.Length; i++)
1669 if (cmdLine[i] == '`')
1673 b.Append("|dos2unix");
1677 b.Append(cmdLine[i]);
1679 cmdLine = b.ToString();
1680 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1684 Console.WriteLine(cmdLine);
1685 using (Process p = Process.Start (psi)) {
1687 int ret = p.ExitCode;
1689 Error ("[Fail] {0}", ret);
1694 static string GetEnv(string name, string defaultValue)
1696 string val = Environment.GetEnvironmentVariable(name);
1700 Console.WriteLine("{0} = {1}", name, val);
1706 Console.WriteLine("{0} = {1} (default)", name, val);
1711 static string LocateFile(string default_path)
1713 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1714 if (File.Exists(override_path))
1715 return override_path;
1716 else if (File.Exists(default_path))
1717 return default_path;
1719 throw new FileNotFoundException(default_path);