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 bool keeptemp = false;
48 static bool compile_only = false;
49 static bool static_link = false;
50 static string config_file = null;
51 static string machine_config_file = null;
52 static string config_dir = null;
53 static string style = "linux";
54 static bool bundled_header = false;
55 static string os_message = "";
58 static string custom_main = null;
59 static bool? use_dos2unix = null;
60 static bool skip_scan;
61 static string ctor_func;
62 static bool quiet = true;
63 static string cross_target = null;
64 static string fetch_target = null;
65 static bool custom_mode = true;
66 static string embedded_options = null;
67 static string runtime = null;
68 static bool aot_compile = false;
69 static string aot_args = "static";
70 static string aot_mode = "";
71 static string aot_runtime = null;
72 static int? aot_dedup_assembly = null;
73 static string sdk_path = null;
74 static string lib_path = null;
75 static Dictionary<string,string> environment = new Dictionary<string,string>();
76 static string [] i18n = new string [] {
80 static string [] i18n_all = new string [] {
88 static string target_server = "https://download.mono-project.com/runtimes/raw/";
90 static int Main (string [] args)
92 List<string> sources = new List<string> ();
93 int top = args.Length;
98 for (int i = 0; i < top; i++){
100 case "--help": case "-h": case "-?":
118 var iarg = args [++i];
121 else if (iarg == "none")
122 i18n = new string [0];
124 i18n = iarg.Split (',');
135 case "--local-targets":
136 CommandLocalTargets ();
144 if (sdk_path != null || runtime != null)
145 Error ("You can only specify one of --runtime, --sdk or --cross");
148 cross_target = args [++i];
157 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
161 var lspec = args [++i];
162 var p = lspec.IndexOf (",");
165 alias = Path.GetFileName (lspec);
168 alias = lspec.Substring (0, p);
169 path = lspec.Substring (p+1);
171 if (!File.Exists (path))
172 Error ($"The specified library file {path} does not exist");
173 libraries [alias] = path;
176 case "--fetch-target":
181 fetch_target = args [++i];
184 case "--list-targets":
185 CommandLocalTargets ();
186 var wc = new WebClient ();
187 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
188 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
191 case "--target-server":
196 target_server = args [++i];
212 embedded_options = args [++i];
221 sdk_path = args [++i];
222 if (cross_target != null || runtime != null)
223 Error ("You can only specify one of --runtime, --sdk or --cross");
230 if (sdk_path != null || cross_target != null)
231 Error ("You can only specify one of --runtime, --sdk or --cross");
234 runtime = args [++i];
241 object_out = args [++i];
249 link_paths.Add (args [++i]);
273 config_file = args [++i];
275 case "--machine-config":
281 machine_config_file = args [++i];
284 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
292 config_dir = args [++i];
300 case "--custom-main":
305 custom_main = args [++i];
319 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
327 case "--static-ctor":
332 ctor_func = args [++i];
335 case "--dos2unix=true":
338 case "--dos2unix=false":
339 use_dos2unix = false;
351 var env = args [++i];
352 p = env.IndexOf ('=');
354 environment.Add (env, "");
356 environment.Add (env.Substring (0, p), env.Substring (p+1));
358 case "--bundled-header":
359 bundled_header = true;
361 case "--aot-runtime":
362 aot_runtime = args [++i];
366 Console.WriteLine ("Usage: --aot-dedup <container_dll> ");
369 var dedup_file = args [++i];
370 sources.Add (dedup_file);
371 aot_dedup_assembly = sources.Count () - 1;
375 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
379 aot_mode = args [++i];
381 if (aot_mode != "full" && aot_mode != "llvmonly") {
382 Console.WriteLine ("Need string of aot mode (full, llvmonly). Omit for normal AOT.");
390 Console.WriteLine ("AOT arguments are passed as a comma-delimited list");
393 if (args [i + 1].Contains ("outfile")) {
394 Console.WriteLine ("Per-aot-output arguments (ex: outfile, llvm-outfile) cannot be given");
397 aot_args = String.Format("static,{0}", args [++i]);
401 sources.Add (args [i]);
405 // Modern bundling starts here
407 if (runtime != null){
408 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
409 } else if (sdk_path != null) {
410 VerifySdk (sdk_path);
411 } else if (cross_target == "default" || cross_target == null){
412 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
413 VerifySdk (sdk_path);
415 sdk_path = Path.Combine (targets_dir, cross_target);
416 Console.WriteLine ("From: " + sdk_path);
417 VerifySdk (sdk_path);
421 if (fetch_target != null){
422 var directory = Path.Combine (targets_dir, fetch_target);
423 var zip_download = Path.Combine (directory, "sdk.zip");
424 Directory.CreateDirectory (directory);
425 var wc = new WebClient ();
426 var uri = new Uri ($"{target_server}{fetch_target}");
429 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
432 wc.DownloadFile (uri, zip_download);
433 ZipFile.ExtractToDirectory(zip_download, directory);
434 File.Delete (zip_download);
436 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
437 File.Delete (zip_download);
444 Console.WriteLine (os_message);
445 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
448 if (sources.Count == 0 || output == null) {
450 Environment.Exit (1);
453 List<string> assemblies = LoadAssemblies (sources);
454 LoadLocalizedAssemblies (assemblies);
455 List<string> files = new List<string> ();
456 foreach (string file in assemblies)
457 if (!QueueAssembly (files, file))
464 GenerateBundles (files);
466 GeneratePackage (files);
468 Console.WriteLine ("Generated {0}", output);
473 static void VerifySdk (string path)
475 if (!Directory.Exists (path))
476 Error ($"The specified SDK path does not exist: {path}");
477 runtime = Path.Combine (sdk_path, "bin", "mono");
478 if (!File.Exists (runtime))
479 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
480 lib_path = Path.Combine (path, "lib", "mono", "4.5");
481 if (!Directory.Exists (lib_path))
482 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
483 link_paths.Add (lib_path);
486 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
488 static void CommandLocalTargets ()
492 Console.WriteLine ("Available targets locally:");
493 Console.WriteLine ("\tdefault\t- Current System Mono");
495 targets = Directory.GetDirectories (targets_dir);
499 foreach (var target in targets){
500 var p = Path.Combine (target, "bin", "mono");
502 Console.WriteLine ("\t{0}", Path.GetFileName (target));
506 static void WriteSymbol (StreamWriter sw, string name, long size)
512 "\t.section .rodata\n" +
514 "\t.type {0}, \"object\"\n" +
515 "\t.size {0}, {1}\n" +
521 "\t.section __TEXT,__text,regular,pure_instructions\n" +
531 "\t.section .rdata,\"dr\"\n" +
539 static string [] chars = new string [256];
541 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
545 // Preallocate the strings we need.
546 if (chars [0] == null) {
547 for (int i = 0; i < chars.Length; i++)
548 chars [i] = string.Format ("{0}", i.ToString ());
551 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
553 for (int i = 0; i < n; i++) {
554 if (count % 32 == 0) {
555 ts.Write ("\n\t.byte ");
559 ts.Write (chars [buffer [i]]);
568 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
569 const int align = 4096;
572 public PackageMaker (string output)
574 package = File.Create (output, 128*1024);
576 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
580 public int AddFile (string fname)
582 using (Stream fileStream = File.OpenRead (fname)){
583 var ret = fileStream.Length;
586 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
587 fileStream.CopyTo (package);
588 package.Position = package.Position + (align - (package.Position % align));
593 public void Add (string entry, string fname)
595 var p = package.Position;
596 var size = AddFile (fname);
597 locations [entry] = Tuple.Create(p, size);
600 public void AddString (string entry, string text)
602 var bytes = Encoding.UTF8.GetBytes (text);
603 locations [entry] = Tuple.Create (package.Position, bytes.Length);
604 package.Write (bytes, 0, bytes.Length);
605 package.Position = package.Position + (align - (package.Position % align));
608 public void AddStringPair (string entry, string key, string value)
610 var kbytes = Encoding.UTF8.GetBytes (key);
611 var vbytes = Encoding.UTF8.GetBytes (value);
613 Console.WriteLine ("ADDING {0} to {1}", key, value);
614 if (kbytes.Length > 255){
615 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
616 Environment.Exit (1);
619 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
620 package.WriteByte ((byte)kbytes.Length);
621 package.Write (kbytes, 0, kbytes.Length);
622 package.WriteByte (0);
623 package.Write (vbytes, 0, vbytes.Length);
624 package.WriteByte (0);
625 package.Position = package.Position + (align - (package.Position % align));
632 foreach (var floc in locations.Keys){
633 Console.WriteLine ($"{floc} at {locations[floc]:x}");
637 public void WriteIndex ()
639 var indexStart = package.Position;
640 var binary = new BinaryWriter (package);
642 binary.Write (locations.Count);
643 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
644 var bytes = Encoding.UTF8.GetBytes (entry.Key);
645 binary.Write (bytes.Length+1);
646 binary.Write (bytes);
647 binary.Write ((byte) 0);
648 binary.Write (entry.Value.Item1);
649 binary.Write (entry.Value.Item2);
651 binary.Write (indexStart);
652 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
664 static bool MaybeAddFile (PackageMaker maker, string code, string file)
669 if (!File.Exists (file)){
670 Error ("The file {0} does not exist", file);
673 maker.Add (code, file);
677 static bool GeneratePackage (List<string> files)
679 if (runtime == null){
681 runtime = Process.GetCurrentProcess().MainModule.FileName;
683 Error ("You must specify at least one runtime with --runtime or --cross");
684 Environment.Exit (1);
687 if (!File.Exists (runtime)){
688 Error ($"The specified runtime at {runtime} does not exist");
689 Environment.Exit (1);
692 if (ctor_func != null){
693 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
697 var maker = new PackageMaker (output);
698 Console.WriteLine ("Using runtime: " + runtime);
699 maker.AddFile (runtime);
701 foreach (var url in files){
702 string fname = LocateFile (new Uri (url).LocalPath);
703 string aname = MakeBundle.GetAssemblyName (fname);
705 maker.Add ("assembly:" + aname, fname);
706 Console.WriteLine (" Assembly: " + fname);
707 if (File.Exists (fname + ".config")){
708 maker.Add ("config:" + aname, fname + ".config");
709 Console.WriteLine (" Config: " + runtime);
713 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
716 if (config_dir != null)
717 maker.Add ("config_dir:", config_dir);
718 if (embedded_options != null)
719 maker.AddString ("options:", embedded_options);
720 if (environment.Count > 0){
721 foreach (var key in environment.Keys)
722 maker.AddStringPair ("env:" + key, key, environment [key]);
724 if (libraries.Count > 0){
725 foreach (var alias_and_path in libraries){
726 Console.WriteLine (" Library: " + alias_and_path.Value);
727 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
735 static void GenerateBundles (List<string> files)
737 string temp_s = "temp.s"; // Path.GetTempFileName ();
738 string temp_c = "temp.c";
739 string temp_o = "temp.o";
743 if (object_out != null)
747 List<string> c_bundle_names = new List<string> ();
748 List<string[]> config_names = new List<string[]> ();
750 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
751 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
754 if (bundled_header) {
755 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
756 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
760 const unsigned char *data;
761 const unsigned int size;
762 } MonoBundledAssembly;
763 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
764 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
767 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
768 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
769 tc.WriteLine ("#include <mono/jit/jit.h>\n");
773 tc.WriteLine ("typedef struct _compressed_data {");
774 tc.WriteLine ("\tMonoBundledAssembly assembly;");
775 tc.WriteLine ("\tint compressed_size;");
776 tc.WriteLine ("} CompressedAssembly;\n");
779 object monitor = new object ();
781 var streams = new Dictionary<string, Stream> ();
782 var sizes = new Dictionary<string, long> ();
784 // Do the file reading and compression in parallel
785 Action<string> body = delegate (string url) {
786 string fname = LocateFile (new Uri (url).LocalPath);
787 Stream stream = File.OpenRead (fname);
789 long real_size = stream.Length;
792 byte[] cbuffer = new byte [8192];
793 MemoryStream ms = new MemoryStream ();
794 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
795 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
796 deflate.Write (cbuffer, 0, n);
800 byte [] bytes = ms.GetBuffer ();
801 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
805 streams [url] = stream;
806 sizes [url] = real_size;
812 Parallel.ForEach (files, body);
814 foreach (var url in files)
818 // The non-parallel part
819 byte [] buffer = new byte [8192];
820 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
821 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
822 foreach (var url in files) {
823 string fname = LocateFile (new Uri (url).LocalPath);
824 string aname = MakeBundle.GetAssemblyName (fname);
825 string encoded = symbolEscapeRE.Replace (aname, "_");
830 var stream = streams [url];
831 var real_size = sizes [url];
834 Console.WriteLine (" embedding: " + fname);
836 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
838 WriteBuffer (ts, stream, buffer);
841 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
842 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
843 " assembly_data_{0}, {2}}}, {3}}};",
844 encoded, aname, real_size, stream.Length);
846 double ratio = ((double) stream.Length * 100) / real_size;
847 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
850 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
851 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
852 encoded, aname, real_size);
856 c_bundle_names.Add ("assembly_bundle_" + encoded);
859 FileStream cf = File.OpenRead (fname + ".config");
861 Console.WriteLine (" config from: " + fname + ".config");
862 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
863 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
864 WriteBuffer (ts, cf, buffer);
866 config_names.Add (new string[] {aname, encoded});
867 } catch (FileNotFoundException) {
868 /* we ignore if the config file doesn't exist */
872 if (config_file != null){
875 conf = File.OpenRead (config_file);
877 Error ("Failure to open {0}", config_file);
881 Console.WriteLine ("System config from: " + config_file);
882 tc.WriteLine ("extern const char system_config;");
883 WriteSymbol (ts, "system_config", config_file.Length);
885 WriteBuffer (ts, conf, buffer);
887 ts.Write ("\t.byte 0\n");
891 if (machine_config_file != null){
894 conf = File.OpenRead (machine_config_file);
896 Error ("Failure to open {0}", machine_config_file);
900 Console.WriteLine ("Machine config from: " + machine_config_file);
901 tc.WriteLine ("extern const char machine_config;");
902 WriteSymbol (ts, "machine_config", machine_config_file.Length);
904 WriteBuffer (ts, conf, buffer);
905 ts.Write ("\t.byte 0\n");
910 // Managed assemblies baked in
912 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
914 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
916 foreach (string c in c_bundle_names){
917 tc.WriteLine ("\t&{0},", c);
919 tc.WriteLine ("\tNULL\n};\n");
922 // AOT baked in plus loader
923 foreach (string asm in aot_names){
924 tc.WriteLine ("\textern const void *mono_aot_module_{0}_info;", asm);
927 tc.WriteLine ("\nstatic void install_aot_modules (void) {\n");
928 foreach (string asm in aot_names){
929 tc.WriteLine ("\tmono_aot_register_module (mono_aot_module_{0}_info);\n", asm);
932 string enum_aot_mode;
935 enum_aot_mode = "MONO_AOT_MODE_FULL";
938 enum_aot_mode = "MONO_AOT_MODE_LLVMONLY";
941 enum_aot_mode = "MONO_AOT_MODE_NORMAL";
944 throw new Exception ("Unsupported AOT mode");
946 tc.WriteLine ("\tmono_jit_set_aot_mode ({0});", enum_aot_mode);
948 tc.WriteLine ("\n}\n");
951 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
953 if (ctor_func != null) {
954 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
955 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
956 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
959 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
960 foreach (string[] ass in config_names){
961 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
963 if (config_file != null)
964 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
965 if (machine_config_file != null)
966 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
967 tc.WriteLine ("}\n");
969 if (config_dir != null)
970 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
972 tc.WriteLine ("static const char *config_dir = NULL;");
974 Stream template_stream;
976 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
978 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
981 StreamReader s = new StreamReader (template_stream);
982 string template = s.ReadToEnd ();
985 if (!nomain && custom_main == null) {
986 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
987 StreamReader st = new StreamReader (template_main_stream);
988 string maintemplate = st.ReadToEnd ();
989 tc.Write (maintemplate);
994 string assembler = GetEnv("AS", "as");
995 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
1002 Console.WriteLine("Compiling:");
1004 if (style == "windows")
1007 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
1009 string compiler = GetEnv("CC", "cl.exe");
1010 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
1011 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
1012 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
1014 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
1015 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
1016 var linkLibraries = new string[] { "kernel32.lib",
1031 string glue_obj = "mkbundle_glue.obj";
1035 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
1038 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
1039 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
1040 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
1043 var compilerArgs = new List<string>();
1044 compilerArgs.Add("/MT");
1046 foreach (string include in includes)
1047 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
1049 if (!nomain || custom_main != null) {
1050 compilerArgs.Add(quote(temp_c));
1051 compilerArgs.Add(quote(temp_o));
1052 if (custom_main != null)
1053 compilerArgs.Add(quote(custom_main));
1054 compilerArgs.Add(quote(monoLib));
1055 compilerArgs.Add("/link");
1056 compilerArgs.Add("/NODEFAULTLIB");
1057 compilerArgs.Add("/SUBSYSTEM:windows");
1058 compilerArgs.Add("/ENTRY:mainCRTStartup");
1059 compilerArgs.AddRange(linkLibraries);
1060 compilerArgs.Add("/out:"+ output);
1062 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1067 // we are just creating a .lib
1068 compilerArgs.Add("/c"); // compile only
1069 compilerArgs.Add(temp_c);
1070 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
1072 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1075 string librarian = GetEnv ("LIB", "lib.exe");
1076 var librarianArgs = new List<string> ();
1077 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
1078 librarianArgs.Add (temp_o);
1079 librarianArgs.Add (glue_obj);
1080 librarianArgs.Add (monoLib);
1081 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1087 string zlib = (compress ? "-lz" : "");
1088 string debugging = "-g";
1089 string cc = GetEnv("CC", "cc");
1092 if (style == "linux")
1093 debugging = "-ggdb";
1096 string platform_libs;
1098 if (style == "osx") {
1099 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1100 platform_libs = "-liconv -framework Foundation ";
1102 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1106 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
1107 "`pkg-config --libs-only-L mono-2` {5} {6} " + platform_libs +
1108 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1} -g ",
1109 temp_c, temp_o, output, zlib, cc, smonolib, String.Join (" ", aot_paths));
1114 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1115 temp_c, temp_o, output, zlib, cc);
1121 Console.WriteLine ("Done");
1126 if (object_out == null){
1127 File.Delete (temp_o);
1130 File.Delete (temp_c);
1132 File.Delete (temp_s);
1137 static List<string> LoadAssemblies (List<string> sources)
1139 List<string> assemblies = new List<string> ();
1142 foreach (string name in sources){
1144 Assembly a = LoadAssemblyFile (name);
1151 assemblies.Add (a.CodeBase);
1152 } catch (Exception) {
1155 Console.WriteLine ("File will not be scanned: {0}", name);
1156 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1164 Error ("Couldn't load one or more of the assemblies.");
1165 Environment.Exit (1);
1171 static void LoadLocalizedAssemblies (List<string> assemblies)
1173 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1174 string error = null;
1176 foreach (string name in other) {
1178 Assembly a = LoadAssembly (name);
1181 error = "Failed to load " + name;
1185 assemblies.Add (a.CodeBase);
1186 } catch (Exception) {
1189 Console.WriteLine ("File will not be scanned: {0}", name);
1190 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1197 if (error != null) {
1198 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1199 foreach (var path in link_paths){
1200 Console.Error.WriteLine (" Path: " + path);
1203 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1206 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1207 Environment.Exit (1);
1212 static readonly Universe universe = new Universe ();
1213 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1215 public static string GetAssemblyName (string path)
1217 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1218 string name = Path.GetFileName (path);
1220 // A bit of a hack to support satellite assemblies. They all share the same name but
1221 // are placed in subdirectories named after the locale they implement. Also, all of
1222 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1223 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1224 string dir = Path.GetDirectoryName (path);
1225 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1227 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1228 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1230 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1236 static bool QueueAssembly (List<string> files, string codebase)
1238 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1239 if (files.Contains (codebase))
1242 var path = new Uri(codebase).LocalPath;
1243 var name = GetAssemblyName (path);
1245 if (loaded_assemblies.TryGetValue (name, out found)) {
1246 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1250 loaded_assemblies.Add (name, path);
1252 files.Add (codebase);
1256 Assembly a = universe.LoadFile (path);
1258 Error ("Unable to to load assembly `{0}'", path);
1262 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1263 a = LoadAssembly (an.Name);
1265 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1269 if (!QueueAssembly (files, a.CodeBase))
1272 } catch (Exception) {
1281 // Loads an assembly from a specific path
1283 static Assembly LoadAssemblyFile (string assembly)
1289 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1290 a = universe.LoadFile (assembly);
1292 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1294 } catch (FileNotFoundException){
1295 Error ($"Cannot find assembly `{assembly}'");
1296 } catch (IKVM.Reflection.BadImageFormatException f) {
1299 Error ($"Cannot load assembly (bad file format) " + f.Message);
1300 } catch (FileLoadException f){
1301 Error ($"Cannot load assembly " + f.Message);
1302 } catch (ArgumentNullException){
1303 Error( $"Cannot load assembly (null argument)");
1309 // Loads an assembly from any of the link directories provided
1311 static Assembly LoadAssembly (string assembly)
1313 string total_log = "";
1314 foreach (string dir in link_paths){
1315 string full_path = Path.Combine (dir, assembly);
1317 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1318 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1319 full_path += ".dll";
1322 var a = universe.LoadFile (full_path);
1324 } catch (FileNotFoundException ff) {
1325 total_log += ff.FusionLog;
1330 Console.WriteLine ("Log: \n" + total_log);
1334 static void Error (string msg, params object [] args)
1336 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1337 Environment.Exit (1);
1342 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1344 " --config F Bundle system config file `F'\n" +
1345 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1346 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1347 " -L path Adds `path' to the search path for assemblies\n" +
1348 " --machine-config F Use the given file as the machine.config for the application.\n" +
1349 " -o out Specifies output filename\n" +
1350 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1351 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1352 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1353 " -v Verbose output\n" +
1354 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1356 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1357 " --cross TARGET Generates a binary for the given TARGET\n"+
1358 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1359 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1360 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1361 " LIB is optional shortname for file located at PATH\n" +
1362 " --list-targets Lists available targets on the remote server\n" +
1363 " --local-targets Lists locally available targets\n" +
1364 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1365 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1366 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1367 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1369 "--custom Builds a custom launcher, options for --custom\n" +
1370 " -c Produce stub only, do not compile\n" +
1371 " -oo obj Specifies output filename for helper object file\n" +
1372 " --dos2unix[=true|false]\n" +
1373 " When no value provided, or when `true` specified\n" +
1374 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1375 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1376 " --keeptemp Keeps the temporary files\n" +
1377 " --static Statically link to mono libs\n" +
1378 " --nomain Don't include a main() function, for libraries\n" +
1379 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1380 " -z Compress the assemblies before embedding.\n" +
1381 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1382 " You need zlib development headers and libraries.\n");
1385 [DllImport ("libc")]
1386 static extern int system (string s);
1387 [DllImport ("libc")]
1388 static extern int uname (IntPtr buf);
1390 static void DetectOS ()
1393 os_message = "OS is: Windows";
1398 IntPtr buf = Marshal.AllocHGlobal (8192);
1399 if (uname (buf) != 0){
1400 os_message = "Warning: Unable to detect OS";
1401 Marshal.FreeHGlobal (buf);
1404 string os = Marshal.PtrToStringAnsi (buf);
1405 os_message = "OS is: " + os;
1409 Marshal.FreeHGlobal (buf);
1412 static bool IsUnix {
1414 int p = (int) Environment.OSVersion.Platform;
1415 return ((p == 4) || (p == 128) || (p == 6));
1420 static string EncodeAotSymbol (string symbol)
1422 var sb = new StringBuilder ();
1423 /* This mimics what the aot-compiler does */
1424 foreach (var b in System.Text.Encoding.UTF8.GetBytes (symbol)) {
1426 if ((c >= '0' && c <= '9') ||
1427 (c >= 'a' && c <= 'z') ||
1428 (c >= 'A' && c <= 'Z')) {
1434 return sb.ToString ();
1437 static void AotCompile (List<string> files)
1439 if (aot_runtime == null)
1440 aot_runtime = runtime;
1442 var aot_mode_string = "";
1443 if (aot_mode != null)
1444 aot_mode_string = "," + aot_mode;
1446 var dedup_mode_string = "";
1447 StringBuilder all_assemblies = null;
1448 if (aot_dedup_assembly != null) {
1449 dedup_mode_string = ",dedup-skip";
1450 all_assemblies = new StringBuilder("");
1453 for (int i=0; i < files.Count; i++) {
1454 var fileName = files [i];
1455 string path = LocateFile (new Uri (fileName).LocalPath);
1456 string outPath = String.Format ("{0}.aot_out", path);
1457 aot_paths.Add (outPath);
1458 var name = System.Reflection.Assembly.LoadFrom(path).GetName().Name;
1459 aot_names.Add (EncodeAotSymbol (name));
1461 if (aot_dedup_assembly != null && i != (int) aot_dedup_assembly) {
1462 all_assemblies.Append (path);
1463 all_assemblies.Append (" ");
1464 Execute (String.Format ("{0} --aot={1},outfile={2}{3}{4} {5}",
1465 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path));
1468 if (aot_dedup_assembly != null) {
1469 string fileName = files [(int) aot_dedup_assembly];
1470 string path = LocateFile (new Uri (fileName).LocalPath);
1471 dedup_mode_string = String.Format (",dedup-include={0}", path);
1472 string outPath = String.Format ("{0}.aot_out", path);
1473 Execute (String.Format ("{0} --aot={1},outfile={2}{3}{4} {5} {6}",
1474 aot_runtime, aot_args, outPath, aot_mode_string, dedup_mode_string, path, all_assemblies.ToString ()));
1479 static void Execute (string cmdLine)
1483 Console.WriteLine ("[execute cmd]: " + cmdLine);
1484 int ret = system (cmdLine);
1487 Error(String.Format("[Fail] {0}", ret));
1492 // on Windows, we have to pipe the output of a
1493 // `cmd` interpolation to dos2unix, because the shell does not
1494 // strip the CRLFs generated by the native pkg-config distributed
1497 // But if it's *not* on cygwin, just skip it.
1499 // check if dos2unix is applicable.
1500 if (use_dos2unix == true)
1502 var info = new ProcessStartInfo ("dos2unix");
1503 info.CreateNoWindow = true;
1504 info.RedirectStandardInput = true;
1505 info.UseShellExecute = false;
1506 var dos2unix = Process.Start (info);
1507 dos2unix.StandardInput.WriteLine ("aaa");
1508 dos2unix.StandardInput.WriteLine ("\u0004");
1509 dos2unix.StandardInput.Close ();
1510 dos2unix.WaitForExit ();
1511 if (dos2unix.ExitCode == 0)
1512 use_dos2unix = true;
1514 Console.WriteLine("Warning: dos2unix not found");
1515 use_dos2unix = false;
1518 if (use_dos2unix == null)
1519 use_dos2unix = false;
1521 ProcessStartInfo psi = new ProcessStartInfo();
1522 psi.UseShellExecute = false;
1524 // if there is no dos2unix, just run cmd /c.
1525 if (use_dos2unix == false)
1527 psi.FileName = "cmd";
1528 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1532 psi.FileName = "sh";
1533 StringBuilder b = new StringBuilder();
1535 for (int i = 0; i < cmdLine.Length; i++)
1537 if (cmdLine[i] == '`')
1541 b.Append("|dos2unix");
1545 b.Append(cmdLine[i]);
1547 cmdLine = b.ToString();
1548 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1552 Console.WriteLine(cmdLine);
1553 using (Process p = Process.Start (psi)) {
1555 int ret = p.ExitCode;
1557 Error ("[Fail] {0}", ret);
1562 static string GetEnv(string name, string defaultValue)
1564 string val = Environment.GetEnvironmentVariable(name);
1568 Console.WriteLine("{0} = {1}", name, val);
1574 Console.WriteLine("{0} = {1} (default)", name, val);
1579 static string LocateFile(string default_path)
1581 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1582 if (File.Exists(override_path))
1583 return override_path;
1584 else if (File.Exists(default_path))
1585 return default_path;
1587 throw new FileNotFoundException(default_path);