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 int? 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 dedup_file = args [++i];
413 sources.Add (dedup_file);
414 aot_dedup_assembly = sources.Count () - 1;
420 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
424 aot_mode = args [++i];
425 if (aot_mode != "full" && aot_mode != "llvmonly") {
426 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
435 Console.WriteLine ("AOT arguments are passed as a comma-delimited list");
438 if (args [i + 1].Contains ("outfile")) {
439 Console.WriteLine ("Per-aot-output arguments (ex: outfile, llvm-outfile) cannot be given");
442 aot_args = String.Format("static,{0}", args [++i]);
447 sources.Add (args [i]);
452 // Modern bundling starts here
454 if (runtime != null){
455 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
456 } else if (sdk_path != null) {
457 VerifySdk (sdk_path);
458 } else if (cross_target == "default" || cross_target == null){
459 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
460 VerifySdk (sdk_path);
462 sdk_path = Path.Combine (targets_dir, cross_target);
463 Console.WriteLine ("From: " + sdk_path);
464 VerifySdk (sdk_path);
468 if (fetch_target != null){
469 var directory = Path.Combine (targets_dir, fetch_target);
470 var zip_download = Path.Combine (directory, "sdk.zip");
471 Directory.CreateDirectory (directory);
472 var wc = new WebClient ();
473 var uri = new Uri ($"{target_server}{fetch_target}");
476 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
479 wc.DownloadFile (uri, zip_download);
480 ZipFile.ExtractToDirectory(zip_download, directory);
481 File.Delete (zip_download);
483 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
484 File.Delete (zip_download);
491 Console.WriteLine (os_message);
492 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
495 if (sources.Count == 0 || output == null) {
497 Environment.Exit (1);
500 List<string> assemblies = LoadAssemblies (sources);
501 LoadLocalizedAssemblies (assemblies);
502 List<string> files = new List<string> ();
503 foreach (string file in assemblies)
504 if (!QueueAssembly (files, file))
507 PreprocessAssemblies (assemblies, files);
513 GenerateBundles (files);
515 GeneratePackage (files);
517 Console.WriteLine ("Generated {0}", output);
522 static void VerifySdk (string path)
524 if (!Directory.Exists (path))
525 Error ($"The specified SDK path does not exist: {path}");
526 runtime = Path.Combine (sdk_path, "bin", "mono");
527 if (!File.Exists (runtime))
528 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
529 lib_path = Path.Combine (path, "lib", "mono", "4.5");
530 if (!Directory.Exists (lib_path))
531 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
532 link_paths.Add (lib_path);
535 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
537 static void CommandLocalTargets ()
541 Console.WriteLine ("Available targets locally:");
542 Console.WriteLine ("\tdefault\t- Current System Mono");
544 targets = Directory.GetDirectories (targets_dir);
548 foreach (var target in targets){
549 var p = Path.Combine (target, "bin", "mono");
551 Console.WriteLine ("\t{0}", Path.GetFileName (target));
555 static void WriteSymbol (StreamWriter sw, string name, long size)
561 "\t.section .rodata\n" +
563 "\t.type {0}, \"object\"\n" +
564 "\t.size {0}, {1}\n" +
570 "\t.section __TEXT,__text,regular,pure_instructions\n" +
580 "\t.section .rdata,\"dr\"\n" +
588 static string [] chars = new string [256];
590 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
594 // Preallocate the strings we need.
595 if (chars [0] == null) {
596 for (int i = 0; i < chars.Length; i++)
597 chars [i] = string.Format ("{0}", i.ToString ());
600 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
602 for (int i = 0; i < n; i++) {
603 if (count % 32 == 0) {
604 ts.Write ("\n\t.byte ");
608 ts.Write (chars [buffer [i]]);
617 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
618 const int align = 4096;
621 public PackageMaker (string output)
623 package = File.Create (output, 128*1024);
625 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
629 public int AddFile (string fname)
631 using (Stream fileStream = File.OpenRead (fname)){
632 var ret = fileStream.Length;
635 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
636 fileStream.CopyTo (package);
637 package.Position = package.Position + (align - (package.Position % align));
642 public void Add (string entry, string fname)
644 var p = package.Position;
645 var size = AddFile (fname);
646 locations [entry] = Tuple.Create(p, size);
649 public void AddString (string entry, string text)
651 var bytes = Encoding.UTF8.GetBytes (text);
652 locations [entry] = Tuple.Create (package.Position, bytes.Length);
653 package.Write (bytes, 0, bytes.Length);
654 package.Position = package.Position + (align - (package.Position % align));
657 public void AddStringPair (string entry, string key, string value)
659 var kbytes = Encoding.UTF8.GetBytes (key);
660 var vbytes = Encoding.UTF8.GetBytes (value);
662 Console.WriteLine ("ADDING {0} to {1}", key, value);
663 if (kbytes.Length > 255){
664 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
665 Environment.Exit (1);
668 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
669 package.WriteByte ((byte)kbytes.Length);
670 package.Write (kbytes, 0, kbytes.Length);
671 package.WriteByte (0);
672 package.Write (vbytes, 0, vbytes.Length);
673 package.WriteByte (0);
674 package.Position = package.Position + (align - (package.Position % align));
681 foreach (var floc in locations.Keys){
682 Console.WriteLine ($"{floc} at {locations[floc]:x}");
686 public void WriteIndex ()
688 var indexStart = package.Position;
689 var binary = new BinaryWriter (package);
691 binary.Write (locations.Count);
692 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
693 var bytes = Encoding.UTF8.GetBytes (entry.Key);
694 binary.Write (bytes.Length+1);
695 binary.Write (bytes);
696 binary.Write ((byte) 0);
697 binary.Write (entry.Value.Item1);
698 binary.Write (entry.Value.Item2);
700 binary.Write (indexStart);
701 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
713 static bool MaybeAddFile (PackageMaker maker, string code, string file)
718 if (!File.Exists (file)){
719 Error ("The file {0} does not exist", file);
722 maker.Add (code, file);
726 static bool GeneratePackage (List<string> files)
728 if (runtime == null){
729 Error ("You must specify at least one runtime with --runtime or --cross");
730 Environment.Exit (1);
732 if (!File.Exists (runtime)){
733 Error ($"The specified runtime at {runtime} does not exist");
734 Environment.Exit (1);
737 if (ctor_func != null){
738 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
742 var maker = new PackageMaker (output);
743 Console.WriteLine ("Using runtime: " + runtime);
744 maker.AddFile (runtime);
746 foreach (var url in files){
747 string fname = LocateFile (new Uri (url).LocalPath);
748 string aname = MakeBundle.GetAssemblyName (fname);
750 maker.Add ("assembly:" + aname, fname);
751 Console.WriteLine (" Assembly: " + fname);
752 if (File.Exists (fname + ".config")){
753 maker.Add ("config:" + aname, fname + ".config");
754 Console.WriteLine (" Config: " + runtime);
758 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
761 if (config_dir != null)
762 maker.Add ("config_dir:", config_dir);
763 if (embedded_options != null)
764 maker.AddString ("options:", embedded_options);
765 if (environment.Count > 0){
766 foreach (var key in environment.Keys)
767 maker.AddStringPair ("env:" + key, key, environment [key]);
769 if (libraries.Count > 0){
770 foreach (var alias_and_path in libraries){
771 Console.WriteLine (" Library: " + alias_and_path.Value);
772 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
780 static void GenerateBundles (List<string> files)
782 string temp_s = "temp.s"; // Path.GetTempFileName ();
783 string temp_c = "temp.c";
784 string temp_o = "temp.o";
788 if (object_out != null)
792 List<string> c_bundle_names = new List<string> ();
793 List<string[]> config_names = new List<string[]> ();
795 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
796 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
799 if (bundled_header) {
800 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
801 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
805 const unsigned char *data;
806 const unsigned int size;
807 } MonoBundledAssembly;
808 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
809 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
812 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
813 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
816 tc.WriteLine ("#include <mono/mini/jit.h>\n");
818 tc.WriteLine ("#include <mono/jit/jit.h>\n");
822 tc.WriteLine ("typedef struct _compressed_data {");
823 tc.WriteLine ("\tMonoBundledAssembly assembly;");
824 tc.WriteLine ("\tint compressed_size;");
825 tc.WriteLine ("} CompressedAssembly;\n");
828 object monitor = new object ();
830 var streams = new Dictionary<string, Stream> ();
831 var sizes = new Dictionary<string, long> ();
833 // Do the file reading and compression in parallel
834 Action<string> body = delegate (string url) {
835 string fname = LocateFile (new Uri (url).LocalPath);
836 Stream stream = File.OpenRead (fname);
838 long real_size = stream.Length;
841 byte[] cbuffer = new byte [8192];
842 MemoryStream ms = new MemoryStream ();
843 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
844 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
845 deflate.Write (cbuffer, 0, n);
849 byte [] bytes = ms.GetBuffer ();
850 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
854 streams [url] = stream;
855 sizes [url] = real_size;
861 Parallel.ForEach (files, body);
863 foreach (var url in files)
867 // The non-parallel part
868 byte [] buffer = new byte [8192];
869 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
870 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
871 foreach (var url in files) {
872 string fname = LocateFile (new Uri (url).LocalPath);
873 string aname = MakeBundle.GetAssemblyName (fname);
874 string encoded = symbolEscapeRE.Replace (aname, "_");
879 var stream = streams [url];
880 var real_size = sizes [url];
883 Console.WriteLine (" embedding: " + fname);
885 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
887 WriteBuffer (ts, stream, buffer);
890 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
891 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
892 " assembly_data_{0}, {2}}}, {3}}};",
893 encoded, aname, real_size, stream.Length);
895 double ratio = ((double) stream.Length * 100) / real_size;
896 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
899 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
900 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
901 encoded, aname, real_size);
905 c_bundle_names.Add ("assembly_bundle_" + encoded);
908 FileStream cf = File.OpenRead (fname + ".config");
910 Console.WriteLine (" config from: " + fname + ".config");
911 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
912 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
913 WriteBuffer (ts, cf, buffer);
915 config_names.Add (new string[] {aname, encoded});
916 } catch (FileNotFoundException) {
917 /* we ignore if the config file doesn't exist */
921 if (config_file != null){
924 conf = File.OpenRead (config_file);
926 Error ("Failure to open {0}", config_file);
930 Console.WriteLine ("System config from: " + config_file);
931 tc.WriteLine ("extern const char system_config;");
932 WriteSymbol (ts, "system_config", config_file.Length);
934 WriteBuffer (ts, conf, buffer);
936 ts.Write ("\t.byte 0\n");
940 if (machine_config_file != null){
943 conf = File.OpenRead (machine_config_file);
945 Error ("Failure to open {0}", machine_config_file);
949 Console.WriteLine ("Machine config from: " + machine_config_file);
950 tc.WriteLine ("extern const char machine_config;");
951 WriteSymbol (ts, "machine_config", machine_config_file.Length);
953 WriteBuffer (ts, conf, buffer);
954 ts.Write ("\t.byte 0\n");
959 // Managed assemblies baked in
961 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
963 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
965 foreach (string c in c_bundle_names){
966 tc.WriteLine ("\t&{0},", c);
968 tc.WriteLine ("\tNULL\n};\n");
971 // AOT baked in plus loader
972 foreach (string asm in aot_names){
973 tc.WriteLine ("\textern const void *mono_aot_module_{0}_info;", asm);
976 tc.WriteLine ("\nstatic void install_aot_modules (void) {\n");
977 foreach (string asm in aot_names){
978 tc.WriteLine ("\tmono_aot_register_module (mono_aot_module_{0}_info);\n", asm);
981 string enum_aot_mode;
984 enum_aot_mode = "MONO_AOT_MODE_FULL";
987 enum_aot_mode = "MONO_AOT_MODE_LLVMONLY";
990 enum_aot_mode = "MONO_AOT_MODE_NORMAL";
993 throw new Exception ("Unsupported AOT mode");
995 tc.WriteLine ("\tmono_jit_set_aot_mode ({0});", enum_aot_mode);
997 tc.WriteLine ("\n}\n");
1000 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
1002 if (ctor_func != null) {
1003 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
1004 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
1005 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
1008 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
1009 foreach (string[] ass in config_names){
1010 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
1012 if (config_file != null)
1013 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
1014 if (machine_config_file != null)
1015 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
1016 tc.WriteLine ("}\n");
1018 if (config_dir != null)
1019 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
1021 tc.WriteLine ("static const char *config_dir = NULL;");
1023 Stream template_stream;
1025 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
1027 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
1030 StreamReader s = new StreamReader (template_stream);
1031 string template = s.ReadToEnd ();
1032 tc.Write (template);
1034 if (!nomain && custom_main == null) {
1035 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
1036 StreamReader st = new StreamReader (template_main_stream);
1037 string maintemplate = st.ReadToEnd ();
1038 tc.Write (maintemplate);
1043 string assembler = GetEnv("AS", "as");
1044 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
1051 Console.WriteLine("Compiling:");
1053 if (style == "windows")
1056 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
1058 string compiler = GetEnv("CC", "cl.exe");
1059 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
1060 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
1061 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
1063 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
1064 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
1065 var linkLibraries = new string[] { "kernel32.lib",
1080 string glue_obj = "mkbundle_glue.obj";
1084 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
1087 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
1088 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
1089 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
1092 var compilerArgs = new List<string>();
1093 compilerArgs.Add("/MT");
1095 foreach (string include in includes)
1096 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
1098 if (!nomain || custom_main != null) {
1099 compilerArgs.Add(quote(temp_c));
1100 compilerArgs.Add(quote(temp_o));
1101 if (custom_main != null)
1102 compilerArgs.Add(quote(custom_main));
1103 compilerArgs.Add(quote(monoLib));
1104 compilerArgs.Add("/link");
1105 compilerArgs.Add("/NODEFAULTLIB");
1106 compilerArgs.Add("/SUBSYSTEM:windows");
1107 compilerArgs.Add("/ENTRY:mainCRTStartup");
1108 compilerArgs.AddRange(linkLibraries);
1109 compilerArgs.Add("/out:"+ output);
1111 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1116 // we are just creating a .lib
1117 compilerArgs.Add("/c"); // compile only
1118 compilerArgs.Add(temp_c);
1119 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
1121 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1124 string librarian = GetEnv ("LIB", "lib.exe");
1125 var librarianArgs = new List<string> ();
1126 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
1127 librarianArgs.Add (temp_o);
1128 librarianArgs.Add (glue_obj);
1129 librarianArgs.Add (monoLib);
1130 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1136 string zlib = (compress ? "-lz" : "");
1137 string debugging = "-g";
1138 string cc = GetEnv("CC", "cc");
1141 if (style == "linux")
1142 debugging = "-ggdb";
1145 string platform_libs;
1147 if (style == "osx") {
1148 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1149 platform_libs = "-liconv -framework Foundation ";
1151 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1155 string in_tree_include = "";
1157 if (in_tree != null) {
1158 smonolib = String.Format ("{0}/mono/mini/.libs/libmonosgen-2.0.a", in_tree);
1159 in_tree_include = String.Format (" -I{0} ", in_tree);
1162 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {7} {0} {3} " +
1163 "`pkg-config --libs-only-L mono-2` {5} {6} " + platform_libs +
1164 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1} -g ",
1165 temp_c, temp_o, output, zlib, cc, smonolib, String.Join (" ", aot_paths), in_tree_include);
1170 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1171 temp_c, temp_o, output, zlib, cc);
1177 Console.WriteLine ("Done");
1182 if (object_out == null){
1183 File.Delete (temp_o);
1186 File.Delete (temp_c);
1188 if (aot_temp_dir != null)
1189 aot_temp_dir.Delete (true);
1190 File.Delete (temp_s);
1195 static List<string> LoadAssemblies (List<string> sources)
1197 List<string> assemblies = new List<string> ();
1200 foreach (string name in sources){
1202 Assembly a = LoadAssemblyFile (name);
1209 assemblies.Add (a.CodeBase);
1210 } catch (Exception) {
1213 Console.WriteLine ("File will not be scanned: {0}", name);
1214 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1222 Error ("Couldn't load one or more of the assemblies.");
1223 Environment.Exit (1);
1229 static void LoadLocalizedAssemblies (List<string> assemblies)
1231 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1232 string error = null;
1234 foreach (string name in other) {
1236 Assembly a = LoadAssembly (name);
1239 error = "Failed to load " + name;
1243 assemblies.Add (a.CodeBase);
1244 } catch (Exception) {
1247 Console.WriteLine ("File will not be scanned: {0}", name);
1248 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1255 if (error != null) {
1256 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1257 foreach (var path in link_paths){
1258 Console.Error.WriteLine (" Path: " + path);
1261 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1264 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1265 Environment.Exit (1);
1270 static readonly Universe universe = new Universe ();
1271 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1273 public static string GetAssemblyName (string path)
1275 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1276 string name = Path.GetFileName (path);
1278 // A bit of a hack to support satellite assemblies. They all share the same name but
1279 // are placed in subdirectories named after the locale they implement. Also, all of
1280 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1281 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1282 string dir = Path.GetDirectoryName (path);
1283 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1285 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1286 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1288 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1294 static bool QueueAssembly (List<string> files, string codebase)
1296 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1297 if (files.Contains (codebase))
1300 var path = new Uri(codebase).LocalPath;
1301 var name = GetAssemblyName (path);
1303 if (loaded_assemblies.TryGetValue (name, out found)) {
1304 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1308 loaded_assemblies.Add (name, path);
1310 files.Add (codebase);
1314 Assembly a = universe.LoadFile (path);
1316 Error ("Unable to to load assembly `{0}'", path);
1320 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1321 a = LoadAssembly (an.Name);
1323 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1327 if (!QueueAssembly (files, a.CodeBase))
1330 } catch (Exception) {
1339 // Loads an assembly from a specific path
1341 static Assembly LoadAssemblyFile (string assembly)
1347 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1348 a = universe.LoadFile (assembly);
1350 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1352 } catch (FileNotFoundException){
1353 Error ($"Cannot find assembly `{assembly}'");
1354 } catch (IKVM.Reflection.BadImageFormatException f) {
1357 Error ($"Cannot load assembly (bad file format) " + f.Message);
1358 } catch (FileLoadException f){
1359 Error ($"Cannot load assembly " + f.Message);
1360 } catch (ArgumentNullException){
1361 Error( $"Cannot load assembly (null argument)");
1367 // Loads an assembly from any of the link directories provided
1369 static Assembly LoadAssembly (string assembly)
1371 string total_log = "";
1372 foreach (string dir in link_paths){
1373 string full_path = Path.Combine (dir, assembly);
1375 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1376 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1377 full_path += ".dll";
1380 var a = universe.LoadFile (full_path);
1382 } catch (FileNotFoundException ff) {
1383 total_log += ff.FusionLog;
1388 Console.WriteLine ("Log: \n" + total_log);
1392 static void Error (string msg, params object [] args)
1394 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1395 Environment.Exit (1);
1400 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1402 " --config F Bundle system config file `F'\n" +
1403 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1404 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1405 " -L path Adds `path' to the search path for assemblies\n" +
1406 " --machine-config F Use the given file as the machine.config for the application.\n" +
1407 " -o out Specifies output filename\n" +
1408 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1409 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1410 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1411 " -v Verbose output\n" +
1412 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1414 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1415 " --cross TARGET Generates a binary for the given TARGET\n"+
1416 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1417 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1418 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1419 " LIB is optional shortname for file located at PATH\n" +
1420 " --list-targets Lists available targets on the remote server\n" +
1421 " --local-targets Lists locally available targets\n" +
1422 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1423 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1424 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1425 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1427 "--custom Builds a custom launcher, options for --custom\n" +
1428 " -c Produce stub only, do not compile\n" +
1429 " -oo obj Specifies output filename for helper object file\n" +
1430 " --dos2unix[=true|false]\n" +
1431 " When no value provided, or when `true` specified\n" +
1432 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1433 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1434 " --keeptemp Keeps the temporary files\n" +
1435 " --static Statically link to mono libs\n" +
1436 " --nomain Don't include a main() function, for libraries\n" +
1437 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1438 " -z Compress the assemblies before embedding.\n" +
1439 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1440 " You need zlib development headers and libraries.\n");
1443 [DllImport ("libc")]
1444 static extern int system (string s);
1445 [DllImport ("libc")]
1446 static extern int uname (IntPtr buf);
1448 static void DetectOS ()
1451 os_message = "OS is: Windows";
1456 IntPtr buf = Marshal.AllocHGlobal (8192);
1457 if (uname (buf) != 0){
1458 os_message = "Warning: Unable to detect OS";
1459 Marshal.FreeHGlobal (buf);
1462 string os = Marshal.PtrToStringAnsi (buf);
1463 os_message = "OS is: " + os;
1467 Marshal.FreeHGlobal (buf);
1470 static bool IsUnix {
1472 int p = (int) Environment.OSVersion.Platform;
1473 return ((p == 4) || (p == 128) || (p == 6));
1478 static string EncodeAotSymbol (string symbol)
1480 var sb = new StringBuilder ();
1481 /* This mimics what the aot-compiler does */
1482 foreach (var b in System.Text.Encoding.UTF8.GetBytes (symbol)) {
1484 if ((c >= '0' && c <= '9') ||
1485 (c >= 'a' && c <= 'z') ||
1486 (c >= 'A' && c <= 'Z')) {
1492 return sb.ToString ();
1495 static void AotCompile (List<string> files)
1497 if (aot_runtime == null)
1498 aot_runtime = runtime;
1500 if (aot_runtime == null) {
1501 Error ("You must specify at least one aot runtime with --runtime or --cross or --aot_runtime when AOT compiling");
1502 Environment.Exit (1);
1505 var aot_mode_string = "";
1506 if (aot_mode != null)
1507 aot_mode_string = "," + aot_mode;
1509 var dedup_mode_string = "";
1510 StringBuilder all_assemblies = null;
1511 if (aot_dedup_assembly != null) {
1512 dedup_mode_string = ",dedup-skip";
1513 all_assemblies = new StringBuilder("");
1516 Console.WriteLine ("Aoting files:");
1518 for (int i=0; i < files.Count; i++) {
1519 var fileName = files [i];
1520 string path = LocateFile (new Uri (fileName).LocalPath);
1521 string outPath = String.Format ("{0}.aot_out", path);
1522 aot_paths.Add (outPath);
1523 var name = System.Reflection.Assembly.LoadFrom(path).GetName().Name;
1524 aot_names.Add (EncodeAotSymbol (name));
1526 if (aot_dedup_assembly != null && i != (int) aot_dedup_assembly) {
1527 all_assemblies.Append (path);
1528 all_assemblies.Append (" ");
1529 Execute (String.Format ("MONO_PATH={6} {0} --aot={1},outfile={2}{3}{4} {5}",
1530 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path, Path.GetDirectoryName (path)));
1532 Execute (String.Format ("MONO_PATH={5} {0} --aot={1},outfile={2}{3} {4}",
1533 aot_runtime, aot_args, outPath, aot_mode_string, path, Path.GetDirectoryName (path)));
1536 if (aot_dedup_assembly != null) {
1537 string fileName = files [(int) aot_dedup_assembly];
1538 var filePath = new Uri (fileName).LocalPath;
1539 string path = LocateFile (filePath);
1540 dedup_mode_string = String.Format (",dedup-include={0}", Path.GetFileName(filePath));
1541 string outPath = String.Format ("{0}.aot_out", path);
1542 Execute (String.Format ("MONO_PATH={7} {0} --aot={1},outfile={2}{3}{4} {5} {6}",
1543 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path, all_assemblies.ToString (), Path.GetDirectoryName (path)));
1546 if ((aot_mode == "full" || aot_mode == "llvmonly") && cil_strip_path != null) {
1547 for (int i=0; i < files.Count; i++) {
1548 var inName = new Uri (files [i]).LocalPath;
1549 var cmd = String.Format ("{0} {1} {2}", aot_runtime, cil_strip_path, inName);
1555 static void LinkManaged (List <string> files, string outDir)
1557 if (managed_linker_path == null)
1560 var paths = new StringBuilder ("");
1561 foreach (var file in files) {
1562 paths.Append (" -a ");
1563 paths.Append (new Uri (file).LocalPath);
1566 var cmd = String.Format ("{0} {1} -b true -out {2} {3} -c link -p copy ", runtime, managed_linker_path, outDir, paths.ToString ());
1570 static void PreprocessAssemblies (List <string> chosenFiles, List <string> files)
1572 if (aot_mode == "" || (cil_strip_path == null && managed_linker_path == null))
1575 var temp_dir_name = Path.Combine(Directory.GetCurrentDirectory(), "temp_assemblies");
1576 aot_temp_dir = new DirectoryInfo (temp_dir_name);
1577 if (aot_temp_dir.Exists) {
1578 Console.WriteLine ("Removing previous build cache at {0}", temp_dir_name);
1579 aot_temp_dir.Delete (true);
1581 aot_temp_dir.Create ();
1583 //if (managed_linker_path != null) {
1584 //LinkManaged (chosenFiles, temp_dir);
1586 //// Replace list with new list of files
1588 //Console.WriteLine ("Iterating {0}", temp_dir);
1589 //aot_temp_dir = new DirectoryInfo (temp_dir);
1590 //foreach (var file in aot_temp_dir.GetFiles ()) {
1591 //files.Append (String.Format ("file:///{0}", file));
1592 //Console.WriteLine (String.Format ("file:///{0}", file));
1597 // Fix file references
1598 for (int i=0; i < files.Count; i++) {
1599 var inName = new Uri (files [i]).LocalPath;
1600 var outName = Path.Combine (temp_dir_name, Path.GetFileName (inName));
1601 File.Copy (inName, outName);
1602 files [i] = outName;
1607 static void Execute (string cmdLine)
1611 Console.WriteLine ("[execute cmd]: " + cmdLine);
1612 int ret = system (cmdLine);
1615 Error(String.Format("[Fail] {0}", ret));
1620 // on Windows, we have to pipe the output of a
1621 // `cmd` interpolation to dos2unix, because the shell does not
1622 // strip the CRLFs generated by the native pkg-config distributed
1625 // But if it's *not* on cygwin, just skip it.
1627 // check if dos2unix is applicable.
1628 if (use_dos2unix == true)
1630 var info = new ProcessStartInfo ("dos2unix");
1631 info.CreateNoWindow = true;
1632 info.RedirectStandardInput = true;
1633 info.UseShellExecute = false;
1634 var dos2unix = Process.Start (info);
1635 dos2unix.StandardInput.WriteLine ("aaa");
1636 dos2unix.StandardInput.WriteLine ("\u0004");
1637 dos2unix.StandardInput.Close ();
1638 dos2unix.WaitForExit ();
1639 if (dos2unix.ExitCode == 0)
1640 use_dos2unix = true;
1642 Console.WriteLine("Warning: dos2unix not found");
1643 use_dos2unix = false;
1646 if (use_dos2unix == null)
1647 use_dos2unix = false;
1649 ProcessStartInfo psi = new ProcessStartInfo();
1650 psi.UseShellExecute = false;
1652 // if there is no dos2unix, just run cmd /c.
1653 if (use_dos2unix == false)
1655 psi.FileName = "cmd";
1656 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1660 psi.FileName = "sh";
1661 StringBuilder b = new StringBuilder();
1663 for (int i = 0; i < cmdLine.Length; i++)
1665 if (cmdLine[i] == '`')
1669 b.Append("|dos2unix");
1673 b.Append(cmdLine[i]);
1675 cmdLine = b.ToString();
1676 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1680 Console.WriteLine(cmdLine);
1681 using (Process p = Process.Start (psi)) {
1683 int ret = p.ExitCode;
1685 Error ("[Fail] {0}", ret);
1690 static string GetEnv(string name, string defaultValue)
1692 string val = Environment.GetEnvironmentVariable(name);
1696 Console.WriteLine("{0} = {1}", name, val);
1702 Console.WriteLine("{0} = {1} (default)", name, val);
1707 static string LocateFile(string default_path)
1709 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1710 if (File.Exists(override_path))
1711 return override_path;
1712 else if (File.Exists(default_path))
1713 return default_path;
1715 throw new FileNotFoundException(default_path);