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;
68 static string runtime = null;
69 static bool aot_compile = false;
70 static string aot_args = "static";
71 static string aot_mode = "";
72 static string aot_runtime = null;
73 static int? aot_dedup_assembly = null;
74 static string sdk_path = null;
75 static string lib_path = null;
76 static Dictionary<string,string> environment = new Dictionary<string,string>();
77 static string [] i18n = new string [] {
81 static string [] i18n_all = new string [] {
89 static string target_server = "https://download.mono-project.com/runtimes/raw/";
91 static int Main (string [] args)
93 List<string> sources = new List<string> ();
94 int top = args.Length;
99 for (int i = 0; i < top; i++){
101 case "--help": case "-h": case "-?":
119 var iarg = args [++i];
122 else if (iarg == "none")
123 i18n = new string [0];
125 i18n = iarg.Split (',');
136 case "--local-targets":
137 CommandLocalTargets ();
145 if (sdk_path != null || runtime != null)
146 Error ("You can only specify one of --runtime, --sdk or --cross");
149 cross_target = args [++i];
158 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
162 var lspec = args [++i];
163 var p = lspec.IndexOf (",");
166 alias = Path.GetFileName (lspec);
169 alias = lspec.Substring (0, p);
170 path = lspec.Substring (p+1);
172 if (!File.Exists (path))
173 Error ($"The specified library file {path} does not exist");
174 libraries [alias] = path;
177 case "--fetch-target":
182 fetch_target = args [++i];
185 case "--list-targets":
186 CommandLocalTargets ();
187 var wc = new WebClient ();
188 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
189 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
192 case "--target-server":
197 target_server = args [++i];
213 embedded_options = args [++i];
222 sdk_path = args [++i];
223 if (cross_target != null || runtime != null)
224 Error ("You can only specify one of --runtime, --sdk or --cross");
231 if (sdk_path != null || cross_target != null)
232 Error ("You can only specify one of --runtime, --sdk or --cross");
235 runtime = args [++i];
242 object_out = args [++i];
250 link_paths.Add (args [++i]);
274 config_file = args [++i];
276 case "--machine-config":
282 machine_config_file = args [++i];
285 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
293 config_dir = args [++i];
301 case "--custom-main":
306 custom_main = args [++i];
320 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
328 case "--static-ctor":
333 ctor_func = args [++i];
336 case "--dos2unix=true":
339 case "--dos2unix=false":
340 use_dos2unix = false;
352 var env = args [++i];
353 p = env.IndexOf ('=');
355 environment.Add (env, "");
357 environment.Add (env.Substring (0, p), env.Substring (p+1));
359 case "--bundled-header":
360 bundled_header = true;
364 Console.WriteLine ("Usage: --in-tree <path/to/headers> ");
367 in_tree = args [++i];
369 case "--aot-runtime":
371 Console.WriteLine ("Usage: --aot-runtime <path/to/runtime> ");
374 aot_runtime = args [++i];
380 Console.WriteLine ("Usage: --aot-dedup <container_dll> ");
383 var dedup_file = args [++i];
384 sources.Add (dedup_file);
385 aot_dedup_assembly = sources.Count () - 1;
391 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
395 aot_mode = args [++i];
396 if (aot_mode != "full" && aot_mode != "llvmonly") {
397 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
406 Console.WriteLine ("AOT arguments are passed as a comma-delimited list");
409 if (args [i + 1].Contains ("outfile")) {
410 Console.WriteLine ("Per-aot-output arguments (ex: outfile, llvm-outfile) cannot be given");
413 aot_args = String.Format("static,{0}", args [++i]);
418 sources.Add (args [i]);
423 // Modern bundling starts here
425 if (runtime != null){
426 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
427 } else if (sdk_path != null) {
428 VerifySdk (sdk_path);
429 } else if (cross_target == "default" || cross_target == null){
430 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
431 VerifySdk (sdk_path);
433 sdk_path = Path.Combine (targets_dir, cross_target);
434 Console.WriteLine ("From: " + sdk_path);
435 VerifySdk (sdk_path);
439 if (fetch_target != null){
440 var directory = Path.Combine (targets_dir, fetch_target);
441 var zip_download = Path.Combine (directory, "sdk.zip");
442 Directory.CreateDirectory (directory);
443 var wc = new WebClient ();
444 var uri = new Uri ($"{target_server}{fetch_target}");
447 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
450 wc.DownloadFile (uri, zip_download);
451 ZipFile.ExtractToDirectory(zip_download, directory);
452 File.Delete (zip_download);
454 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
455 File.Delete (zip_download);
462 Console.WriteLine (os_message);
463 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
466 if (sources.Count == 0 || output == null) {
468 Environment.Exit (1);
471 List<string> assemblies = LoadAssemblies (sources);
472 LoadLocalizedAssemblies (assemblies);
473 List<string> files = new List<string> ();
474 foreach (string file in assemblies)
475 if (!QueueAssembly (files, file))
482 GenerateBundles (files);
484 GeneratePackage (files);
486 Console.WriteLine ("Generated {0}", output);
491 static void VerifySdk (string path)
493 if (!Directory.Exists (path))
494 Error ($"The specified SDK path does not exist: {path}");
495 runtime = Path.Combine (sdk_path, "bin", "mono");
496 if (!File.Exists (runtime))
497 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
498 lib_path = Path.Combine (path, "lib", "mono", "4.5");
499 if (!Directory.Exists (lib_path))
500 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
501 link_paths.Add (lib_path);
504 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
506 static void CommandLocalTargets ()
510 Console.WriteLine ("Available targets locally:");
511 Console.WriteLine ("\tdefault\t- Current System Mono");
513 targets = Directory.GetDirectories (targets_dir);
517 foreach (var target in targets){
518 var p = Path.Combine (target, "bin", "mono");
520 Console.WriteLine ("\t{0}", Path.GetFileName (target));
524 static void WriteSymbol (StreamWriter sw, string name, long size)
530 "\t.section .rodata\n" +
532 "\t.type {0}, \"object\"\n" +
533 "\t.size {0}, {1}\n" +
539 "\t.section __TEXT,__text,regular,pure_instructions\n" +
549 "\t.section .rdata,\"dr\"\n" +
557 static string [] chars = new string [256];
559 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
563 // Preallocate the strings we need.
564 if (chars [0] == null) {
565 for (int i = 0; i < chars.Length; i++)
566 chars [i] = string.Format ("{0}", i.ToString ());
569 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
571 for (int i = 0; i < n; i++) {
572 if (count % 32 == 0) {
573 ts.Write ("\n\t.byte ");
577 ts.Write (chars [buffer [i]]);
586 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
587 const int align = 4096;
590 public PackageMaker (string output)
592 package = File.Create (output, 128*1024);
594 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
598 public int AddFile (string fname)
600 using (Stream fileStream = File.OpenRead (fname)){
601 var ret = fileStream.Length;
604 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
605 fileStream.CopyTo (package);
606 package.Position = package.Position + (align - (package.Position % align));
611 public void Add (string entry, string fname)
613 var p = package.Position;
614 var size = AddFile (fname);
615 locations [entry] = Tuple.Create(p, size);
618 public void AddString (string entry, string text)
620 var bytes = Encoding.UTF8.GetBytes (text);
621 locations [entry] = Tuple.Create (package.Position, bytes.Length);
622 package.Write (bytes, 0, bytes.Length);
623 package.Position = package.Position + (align - (package.Position % align));
626 public void AddStringPair (string entry, string key, string value)
628 var kbytes = Encoding.UTF8.GetBytes (key);
629 var vbytes = Encoding.UTF8.GetBytes (value);
631 Console.WriteLine ("ADDING {0} to {1}", key, value);
632 if (kbytes.Length > 255){
633 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
634 Environment.Exit (1);
637 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
638 package.WriteByte ((byte)kbytes.Length);
639 package.Write (kbytes, 0, kbytes.Length);
640 package.WriteByte (0);
641 package.Write (vbytes, 0, vbytes.Length);
642 package.WriteByte (0);
643 package.Position = package.Position + (align - (package.Position % align));
650 foreach (var floc in locations.Keys){
651 Console.WriteLine ($"{floc} at {locations[floc]:x}");
655 public void WriteIndex ()
657 var indexStart = package.Position;
658 var binary = new BinaryWriter (package);
660 binary.Write (locations.Count);
661 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
662 var bytes = Encoding.UTF8.GetBytes (entry.Key);
663 binary.Write (bytes.Length+1);
664 binary.Write (bytes);
665 binary.Write ((byte) 0);
666 binary.Write (entry.Value.Item1);
667 binary.Write (entry.Value.Item2);
669 binary.Write (indexStart);
670 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
682 static bool MaybeAddFile (PackageMaker maker, string code, string file)
687 if (!File.Exists (file)){
688 Error ("The file {0} does not exist", file);
691 maker.Add (code, file);
695 static bool GeneratePackage (List<string> files)
697 if (runtime == null){
699 runtime = Process.GetCurrentProcess().MainModule.FileName;
701 Error ("You must specify at least one runtime with --runtime or --cross");
702 Environment.Exit (1);
705 if (!File.Exists (runtime)){
706 Error ($"The specified runtime at {runtime} does not exist");
707 Environment.Exit (1);
710 if (ctor_func != null){
711 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
715 var maker = new PackageMaker (output);
716 Console.WriteLine ("Using runtime: " + runtime);
717 maker.AddFile (runtime);
719 foreach (var url in files){
720 string fname = LocateFile (new Uri (url).LocalPath);
721 string aname = MakeBundle.GetAssemblyName (fname);
723 maker.Add ("assembly:" + aname, fname);
724 Console.WriteLine (" Assembly: " + fname);
725 if (File.Exists (fname + ".config")){
726 maker.Add ("config:" + aname, fname + ".config");
727 Console.WriteLine (" Config: " + runtime);
731 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
734 if (config_dir != null)
735 maker.Add ("config_dir:", config_dir);
736 if (embedded_options != null)
737 maker.AddString ("options:", embedded_options);
738 if (environment.Count > 0){
739 foreach (var key in environment.Keys)
740 maker.AddStringPair ("env:" + key, key, environment [key]);
742 if (libraries.Count > 0){
743 foreach (var alias_and_path in libraries){
744 Console.WriteLine (" Library: " + alias_and_path.Value);
745 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
753 static void GenerateBundles (List<string> files)
755 string temp_s = "temp.s"; // Path.GetTempFileName ();
756 string temp_c = "temp.c";
757 string temp_o = "temp.o";
761 if (object_out != null)
765 List<string> c_bundle_names = new List<string> ();
766 List<string[]> config_names = new List<string[]> ();
768 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
769 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
772 if (bundled_header) {
773 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
774 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
778 const unsigned char *data;
779 const unsigned int size;
780 } MonoBundledAssembly;
781 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
782 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
785 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
786 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
789 tc.WriteLine ("#include <mono/mini/jit.h>\n");
791 tc.WriteLine ("#include <mono/jit/jit.h>\n");
795 tc.WriteLine ("typedef struct _compressed_data {");
796 tc.WriteLine ("\tMonoBundledAssembly assembly;");
797 tc.WriteLine ("\tint compressed_size;");
798 tc.WriteLine ("} CompressedAssembly;\n");
801 object monitor = new object ();
803 var streams = new Dictionary<string, Stream> ();
804 var sizes = new Dictionary<string, long> ();
806 // Do the file reading and compression in parallel
807 Action<string> body = delegate (string url) {
808 string fname = LocateFile (new Uri (url).LocalPath);
809 Stream stream = File.OpenRead (fname);
811 long real_size = stream.Length;
814 byte[] cbuffer = new byte [8192];
815 MemoryStream ms = new MemoryStream ();
816 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
817 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
818 deflate.Write (cbuffer, 0, n);
822 byte [] bytes = ms.GetBuffer ();
823 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
827 streams [url] = stream;
828 sizes [url] = real_size;
834 Parallel.ForEach (files, body);
836 foreach (var url in files)
840 // The non-parallel part
841 byte [] buffer = new byte [8192];
842 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
843 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
844 foreach (var url in files) {
845 string fname = LocateFile (new Uri (url).LocalPath);
846 string aname = MakeBundle.GetAssemblyName (fname);
847 string encoded = symbolEscapeRE.Replace (aname, "_");
852 var stream = streams [url];
853 var real_size = sizes [url];
856 Console.WriteLine (" embedding: " + fname);
858 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
860 WriteBuffer (ts, stream, buffer);
863 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
864 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
865 " assembly_data_{0}, {2}}}, {3}}};",
866 encoded, aname, real_size, stream.Length);
868 double ratio = ((double) stream.Length * 100) / real_size;
869 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
872 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
873 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
874 encoded, aname, real_size);
878 c_bundle_names.Add ("assembly_bundle_" + encoded);
881 FileStream cf = File.OpenRead (fname + ".config");
883 Console.WriteLine (" config from: " + fname + ".config");
884 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
885 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
886 WriteBuffer (ts, cf, buffer);
888 config_names.Add (new string[] {aname, encoded});
889 } catch (FileNotFoundException) {
890 /* we ignore if the config file doesn't exist */
894 if (config_file != null){
897 conf = File.OpenRead (config_file);
899 Error ("Failure to open {0}", config_file);
903 Console.WriteLine ("System config from: " + config_file);
904 tc.WriteLine ("extern const char system_config;");
905 WriteSymbol (ts, "system_config", config_file.Length);
907 WriteBuffer (ts, conf, buffer);
909 ts.Write ("\t.byte 0\n");
913 if (machine_config_file != null){
916 conf = File.OpenRead (machine_config_file);
918 Error ("Failure to open {0}", machine_config_file);
922 Console.WriteLine ("Machine config from: " + machine_config_file);
923 tc.WriteLine ("extern const char machine_config;");
924 WriteSymbol (ts, "machine_config", machine_config_file.Length);
926 WriteBuffer (ts, conf, buffer);
927 ts.Write ("\t.byte 0\n");
932 // Managed assemblies baked in
934 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
936 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
938 foreach (string c in c_bundle_names){
939 tc.WriteLine ("\t&{0},", c);
941 tc.WriteLine ("\tNULL\n};\n");
944 // AOT baked in plus loader
945 foreach (string asm in aot_names){
946 tc.WriteLine ("\textern const void *mono_aot_module_{0}_info;", asm);
949 tc.WriteLine ("\nstatic void install_aot_modules (void) {\n");
950 foreach (string asm in aot_names){
951 tc.WriteLine ("\tmono_aot_register_module (mono_aot_module_{0}_info);\n", asm);
954 string enum_aot_mode;
957 enum_aot_mode = "MONO_AOT_MODE_FULL";
960 enum_aot_mode = "MONO_AOT_MODE_LLVMONLY";
963 enum_aot_mode = "MONO_AOT_MODE_NORMAL";
966 throw new Exception ("Unsupported AOT mode");
968 tc.WriteLine ("\tmono_jit_set_aot_mode ({0});", enum_aot_mode);
970 tc.WriteLine ("\n}\n");
973 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
975 if (ctor_func != null) {
976 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
977 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
978 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
981 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
982 foreach (string[] ass in config_names){
983 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
985 if (config_file != null)
986 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
987 if (machine_config_file != null)
988 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
989 tc.WriteLine ("}\n");
991 if (config_dir != null)
992 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
994 tc.WriteLine ("static const char *config_dir = NULL;");
996 Stream template_stream;
998 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
1000 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
1003 StreamReader s = new StreamReader (template_stream);
1004 string template = s.ReadToEnd ();
1005 tc.Write (template);
1007 if (!nomain && custom_main == null) {
1008 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
1009 StreamReader st = new StreamReader (template_main_stream);
1010 string maintemplate = st.ReadToEnd ();
1011 tc.Write (maintemplate);
1016 string assembler = GetEnv("AS", "as");
1017 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
1024 Console.WriteLine("Compiling:");
1026 if (style == "windows")
1029 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
1031 string compiler = GetEnv("CC", "cl.exe");
1032 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
1033 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
1034 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
1036 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
1037 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
1038 var linkLibraries = new string[] { "kernel32.lib",
1053 string glue_obj = "mkbundle_glue.obj";
1057 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
1060 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
1061 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
1062 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
1065 var compilerArgs = new List<string>();
1066 compilerArgs.Add("/MT");
1068 foreach (string include in includes)
1069 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
1071 if (!nomain || custom_main != null) {
1072 compilerArgs.Add(quote(temp_c));
1073 compilerArgs.Add(quote(temp_o));
1074 if (custom_main != null)
1075 compilerArgs.Add(quote(custom_main));
1076 compilerArgs.Add(quote(monoLib));
1077 compilerArgs.Add("/link");
1078 compilerArgs.Add("/NODEFAULTLIB");
1079 compilerArgs.Add("/SUBSYSTEM:windows");
1080 compilerArgs.Add("/ENTRY:mainCRTStartup");
1081 compilerArgs.AddRange(linkLibraries);
1082 compilerArgs.Add("/out:"+ output);
1084 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1089 // we are just creating a .lib
1090 compilerArgs.Add("/c"); // compile only
1091 compilerArgs.Add(temp_c);
1092 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
1094 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1097 string librarian = GetEnv ("LIB", "lib.exe");
1098 var librarianArgs = new List<string> ();
1099 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
1100 librarianArgs.Add (temp_o);
1101 librarianArgs.Add (glue_obj);
1102 librarianArgs.Add (monoLib);
1103 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1109 string zlib = (compress ? "-lz" : "");
1110 string debugging = "-g";
1111 string cc = GetEnv("CC", "cc");
1114 if (style == "linux")
1115 debugging = "-ggdb";
1118 string platform_libs;
1120 if (style == "osx") {
1121 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1122 platform_libs = "-liconv -framework Foundation ";
1124 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1128 string in_tree_include = "";
1130 if (in_tree != null) {
1131 smonolib = String.Format ("{0}/mono/mini/.libs/libmonosgen-2.0.a", in_tree);
1132 in_tree_include = String.Format (" -I{0} ", in_tree);
1135 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {7} {0} {3} " +
1136 "`pkg-config --libs-only-L mono-2` {5} {6} " + platform_libs +
1137 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1} -g ",
1138 temp_c, temp_o, output, zlib, cc, smonolib, String.Join (" ", aot_paths), in_tree_include);
1143 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1144 temp_c, temp_o, output, zlib, cc);
1150 Console.WriteLine ("Done");
1155 if (object_out == null){
1156 File.Delete (temp_o);
1159 File.Delete (temp_c);
1161 File.Delete (temp_s);
1166 static List<string> LoadAssemblies (List<string> sources)
1168 List<string> assemblies = new List<string> ();
1171 foreach (string name in sources){
1173 Assembly a = LoadAssemblyFile (name);
1180 assemblies.Add (a.CodeBase);
1181 } catch (Exception) {
1184 Console.WriteLine ("File will not be scanned: {0}", name);
1185 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1193 Error ("Couldn't load one or more of the assemblies.");
1194 Environment.Exit (1);
1200 static void LoadLocalizedAssemblies (List<string> assemblies)
1202 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1203 string error = null;
1205 foreach (string name in other) {
1207 Assembly a = LoadAssembly (name);
1210 error = "Failed to load " + name;
1214 assemblies.Add (a.CodeBase);
1215 } catch (Exception) {
1218 Console.WriteLine ("File will not be scanned: {0}", name);
1219 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1226 if (error != null) {
1227 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1228 foreach (var path in link_paths){
1229 Console.Error.WriteLine (" Path: " + path);
1232 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1235 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1236 Environment.Exit (1);
1241 static readonly Universe universe = new Universe ();
1242 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1244 public static string GetAssemblyName (string path)
1246 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1247 string name = Path.GetFileName (path);
1249 // A bit of a hack to support satellite assemblies. They all share the same name but
1250 // are placed in subdirectories named after the locale they implement. Also, all of
1251 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1252 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1253 string dir = Path.GetDirectoryName (path);
1254 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1256 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1257 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1259 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1265 static bool QueueAssembly (List<string> files, string codebase)
1267 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1268 if (files.Contains (codebase))
1271 var path = new Uri(codebase).LocalPath;
1272 var name = GetAssemblyName (path);
1274 if (loaded_assemblies.TryGetValue (name, out found)) {
1275 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1279 loaded_assemblies.Add (name, path);
1281 files.Add (codebase);
1285 Assembly a = universe.LoadFile (path);
1287 Error ("Unable to to load assembly `{0}'", path);
1291 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1292 a = LoadAssembly (an.Name);
1294 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1298 if (!QueueAssembly (files, a.CodeBase))
1301 } catch (Exception) {
1310 // Loads an assembly from a specific path
1312 static Assembly LoadAssemblyFile (string assembly)
1318 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1319 a = universe.LoadFile (assembly);
1321 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1323 } catch (FileNotFoundException){
1324 Error ($"Cannot find assembly `{assembly}'");
1325 } catch (IKVM.Reflection.BadImageFormatException f) {
1328 Error ($"Cannot load assembly (bad file format) " + f.Message);
1329 } catch (FileLoadException f){
1330 Error ($"Cannot load assembly " + f.Message);
1331 } catch (ArgumentNullException){
1332 Error( $"Cannot load assembly (null argument)");
1338 // Loads an assembly from any of the link directories provided
1340 static Assembly LoadAssembly (string assembly)
1342 string total_log = "";
1343 foreach (string dir in link_paths){
1344 string full_path = Path.Combine (dir, assembly);
1346 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1347 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1348 full_path += ".dll";
1351 var a = universe.LoadFile (full_path);
1353 } catch (FileNotFoundException ff) {
1354 total_log += ff.FusionLog;
1359 Console.WriteLine ("Log: \n" + total_log);
1363 static void Error (string msg, params object [] args)
1365 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1366 Environment.Exit (1);
1371 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1373 " --config F Bundle system config file `F'\n" +
1374 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1375 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1376 " -L path Adds `path' to the search path for assemblies\n" +
1377 " --machine-config F Use the given file as the machine.config for the application.\n" +
1378 " -o out Specifies output filename\n" +
1379 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1380 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1381 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1382 " -v Verbose output\n" +
1383 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1385 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1386 " --cross TARGET Generates a binary for the given TARGET\n"+
1387 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1388 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1389 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1390 " LIB is optional shortname for file located at PATH\n" +
1391 " --list-targets Lists available targets on the remote server\n" +
1392 " --local-targets Lists locally available targets\n" +
1393 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1394 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1395 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1396 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1398 "--custom Builds a custom launcher, options for --custom\n" +
1399 " -c Produce stub only, do not compile\n" +
1400 " -oo obj Specifies output filename for helper object file\n" +
1401 " --dos2unix[=true|false]\n" +
1402 " When no value provided, or when `true` specified\n" +
1403 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1404 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1405 " --keeptemp Keeps the temporary files\n" +
1406 " --static Statically link to mono libs\n" +
1407 " --nomain Don't include a main() function, for libraries\n" +
1408 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1409 " -z Compress the assemblies before embedding.\n" +
1410 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1411 " You need zlib development headers and libraries.\n");
1414 [DllImport ("libc")]
1415 static extern int system (string s);
1416 [DllImport ("libc")]
1417 static extern int uname (IntPtr buf);
1419 static void DetectOS ()
1422 os_message = "OS is: Windows";
1427 IntPtr buf = Marshal.AllocHGlobal (8192);
1428 if (uname (buf) != 0){
1429 os_message = "Warning: Unable to detect OS";
1430 Marshal.FreeHGlobal (buf);
1433 string os = Marshal.PtrToStringAnsi (buf);
1434 os_message = "OS is: " + os;
1438 Marshal.FreeHGlobal (buf);
1441 static bool IsUnix {
1443 int p = (int) Environment.OSVersion.Platform;
1444 return ((p == 4) || (p == 128) || (p == 6));
1449 static string EncodeAotSymbol (string symbol)
1451 var sb = new StringBuilder ();
1452 /* This mimics what the aot-compiler does */
1453 foreach (var b in System.Text.Encoding.UTF8.GetBytes (symbol)) {
1455 if ((c >= '0' && c <= '9') ||
1456 (c >= 'a' && c <= 'z') ||
1457 (c >= 'A' && c <= 'Z')) {
1463 return sb.ToString ();
1466 static void AotCompile (List<string> files)
1468 if (aot_runtime == null)
1469 aot_runtime = runtime;
1471 if (aot_runtime == null || aot_runtime.Length == 0){
1473 aot_runtime = Process.GetCurrentProcess().MainModule.FileName;
1475 Error ("You must specify at least one aot runtime with --runtime or --cross or --aot_runtime when AOT compiling");
1476 Environment.Exit (1);
1480 var aot_mode_string = "";
1481 if (aot_mode != null)
1482 aot_mode_string = "," + aot_mode;
1484 var dedup_mode_string = "";
1485 StringBuilder all_assemblies = null;
1486 if (aot_dedup_assembly != null) {
1487 dedup_mode_string = ",dedup-skip";
1488 all_assemblies = new StringBuilder("");
1491 for (int i=0; i < files.Count; i++) {
1492 var fileName = files [i];
1493 string path = LocateFile (new Uri (fileName).LocalPath);
1494 string outPath = String.Format ("{0}.aot_out", path);
1495 aot_paths.Add (outPath);
1496 var name = System.Reflection.Assembly.LoadFrom(path).GetName().Name;
1497 aot_names.Add (EncodeAotSymbol (name));
1499 if (aot_dedup_assembly != null && i != (int) aot_dedup_assembly) {
1500 all_assemblies.Append (path);
1501 all_assemblies.Append (" ");
1502 Execute (String.Format ("{0} --aot={1},outfile={2}{3}{4} {5}",
1503 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path));
1505 Execute (String.Format ("{0} --aot={1},outfile={2}{3} {4}",
1506 aot_runtime, aot_args, outPath, aot_mode_string, path));
1509 if (aot_dedup_assembly != null) {
1510 string fileName = files [(int) aot_dedup_assembly];
1511 var filePath = new Uri (fileName).LocalPath;
1512 string path = LocateFile (filePath);
1513 dedup_mode_string = String.Format (",dedup-include={0}", Path.GetFileName(filePath));
1514 string outPath = String.Format ("{0}.aot_out", path);
1515 Execute (String.Format ("{0} --aot={1},outfile={2}{3}{4} {5} {6}",
1516 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path, all_assemblies.ToString ()));
1521 static void Execute (string cmdLine)
1525 Console.WriteLine ("[execute cmd]: " + cmdLine);
1526 int ret = system (cmdLine);
1529 Error(String.Format("[Fail] {0}", ret));
1534 // on Windows, we have to pipe the output of a
1535 // `cmd` interpolation to dos2unix, because the shell does not
1536 // strip the CRLFs generated by the native pkg-config distributed
1539 // But if it's *not* on cygwin, just skip it.
1541 // check if dos2unix is applicable.
1542 if (use_dos2unix == true)
1544 var info = new ProcessStartInfo ("dos2unix");
1545 info.CreateNoWindow = true;
1546 info.RedirectStandardInput = true;
1547 info.UseShellExecute = false;
1548 var dos2unix = Process.Start (info);
1549 dos2unix.StandardInput.WriteLine ("aaa");
1550 dos2unix.StandardInput.WriteLine ("\u0004");
1551 dos2unix.StandardInput.Close ();
1552 dos2unix.WaitForExit ();
1553 if (dos2unix.ExitCode == 0)
1554 use_dos2unix = true;
1556 Console.WriteLine("Warning: dos2unix not found");
1557 use_dos2unix = false;
1560 if (use_dos2unix == null)
1561 use_dos2unix = false;
1563 ProcessStartInfo psi = new ProcessStartInfo();
1564 psi.UseShellExecute = false;
1566 // if there is no dos2unix, just run cmd /c.
1567 if (use_dos2unix == false)
1569 psi.FileName = "cmd";
1570 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1574 psi.FileName = "sh";
1575 StringBuilder b = new StringBuilder();
1577 for (int i = 0; i < cmdLine.Length; i++)
1579 if (cmdLine[i] == '`')
1583 b.Append("|dos2unix");
1587 b.Append(cmdLine[i]);
1589 cmdLine = b.ToString();
1590 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1594 Console.WriteLine(cmdLine);
1595 using (Process p = Process.Start (psi)) {
1597 int ret = p.ExitCode;
1599 Error ("[Fail] {0}", ret);
1604 static string GetEnv(string name, string defaultValue)
1606 string val = Environment.GetEnvironmentVariable(name);
1610 Console.WriteLine("{0} = {1}", name, val);
1616 Console.WriteLine("{0} = {1} (default)", name, val);
1621 static string LocateFile(string default_path)
1623 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1624 if (File.Exists(override_path))
1625 return override_path;
1626 else if (File.Exists(default_path))
1627 return default_path;
1629 throw new FileNotFoundException(default_path);