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 string sdk_path = null;
73 static string lib_path = null;
74 static Dictionary<string,string> environment = new Dictionary<string,string>();
75 static string [] i18n = new string [] {
79 static string [] i18n_all = new string [] {
87 static string target_server = "https://download.mono-project.com/runtimes/raw/";
89 static int Main (string [] args)
91 List<string> sources = new List<string> ();
92 int top = args.Length;
97 for (int i = 0; i < top; i++){
99 case "--help": case "-h": case "-?":
117 var iarg = args [++i];
120 else if (iarg == "none")
121 i18n = new string [0];
123 i18n = iarg.Split (',');
134 case "--local-targets":
135 CommandLocalTargets ();
143 if (sdk_path != null || runtime != null)
144 Error ("You can only specify one of --runtime, --sdk or --cross");
147 cross_target = args [++i];
156 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
160 var lspec = args [++i];
161 var p = lspec.IndexOf (",");
164 alias = Path.GetFileName (lspec);
167 alias = lspec.Substring (0, p);
168 path = lspec.Substring (p+1);
170 if (!File.Exists (path))
171 Error ($"The specified library file {path} does not exist");
172 libraries [alias] = path;
175 case "--fetch-target":
180 fetch_target = args [++i];
183 case "--list-targets":
184 CommandLocalTargets ();
185 var wc = new WebClient ();
186 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
187 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
190 case "--target-server":
195 target_server = args [++i];
211 embedded_options = args [++i];
220 sdk_path = args [++i];
221 if (cross_target != null || runtime != null)
222 Error ("You can only specify one of --runtime, --sdk or --cross");
229 if (sdk_path != null || cross_target != null)
230 Error ("You can only specify one of --runtime, --sdk or --cross");
233 runtime = args [++i];
240 object_out = args [++i];
248 link_paths.Add (args [++i]);
272 config_file = args [++i];
274 case "--machine-config":
280 machine_config_file = args [++i];
283 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
291 config_dir = args [++i];
299 case "--custom-main":
304 custom_main = args [++i];
318 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
326 case "--static-ctor":
331 ctor_func = args [++i];
334 case "--dos2unix=true":
337 case "--dos2unix=false":
338 use_dos2unix = false;
350 var env = args [++i];
351 p = env.IndexOf ('=');
353 environment.Add (env, "");
355 environment.Add (env.Substring (0, p), env.Substring (p+1));
357 case "--bundled-header":
358 bundled_header = true;
360 case "--aot-runtime":
361 aot_runtime = args [++i];
365 Console.WriteLine ("Need string of aot mode");
368 aot_mode = args [++i];
373 Console.WriteLine ("AOT arguments are passed as a comma-delimited list");
376 if (args [i + 1].Contains ("outfile")) {
377 Console.WriteLine ("Per-aot-output arguments (ex: outfile, llvm-outfile) cannot be given");
380 aot_args = String.Format("static,{0}", args [++i]);
384 sources.Add (args [i]);
388 // Modern bundling starts here
390 if (runtime != null){
391 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
392 } else if (sdk_path != null) {
393 VerifySdk (sdk_path);
394 } else if (cross_target == "default" || cross_target == null){
395 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
396 VerifySdk (sdk_path);
398 sdk_path = Path.Combine (targets_dir, cross_target);
399 Console.WriteLine ("From: " + sdk_path);
400 VerifySdk (sdk_path);
404 if (fetch_target != null){
405 var directory = Path.Combine (targets_dir, fetch_target);
406 var zip_download = Path.Combine (directory, "sdk.zip");
407 Directory.CreateDirectory (directory);
408 var wc = new WebClient ();
409 var uri = new Uri ($"{target_server}{fetch_target}");
412 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
415 wc.DownloadFile (uri, zip_download);
416 ZipFile.ExtractToDirectory(zip_download, directory);
417 File.Delete (zip_download);
419 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
420 File.Delete (zip_download);
427 Console.WriteLine (os_message);
428 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
431 if (sources.Count == 0 || output == null) {
433 Environment.Exit (1);
436 List<string> assemblies = LoadAssemblies (sources);
437 LoadLocalizedAssemblies (assemblies);
438 List<string> files = new List<string> ();
439 foreach (string file in assemblies)
440 if (!QueueAssembly (files, file))
447 GenerateBundles (files);
449 GeneratePackage (files);
451 Console.WriteLine ("Generated {0}", output);
456 static void VerifySdk (string path)
458 if (!Directory.Exists (path))
459 Error ($"The specified SDK path does not exist: {path}");
460 runtime = Path.Combine (sdk_path, "bin", "mono");
461 if (!File.Exists (runtime))
462 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
463 lib_path = Path.Combine (path, "lib", "mono", "4.5");
464 if (!Directory.Exists (lib_path))
465 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
466 link_paths.Add (lib_path);
469 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
471 static void CommandLocalTargets ()
475 Console.WriteLine ("Available targets locally:");
476 Console.WriteLine ("\tdefault\t- Current System Mono");
478 targets = Directory.GetDirectories (targets_dir);
482 foreach (var target in targets){
483 var p = Path.Combine (target, "bin", "mono");
485 Console.WriteLine ("\t{0}", Path.GetFileName (target));
489 static void WriteSymbol (StreamWriter sw, string name, long size)
495 "\t.section .rodata\n" +
497 "\t.type {0}, \"object\"\n" +
498 "\t.size {0}, {1}\n" +
504 "\t.section __TEXT,__text,regular,pure_instructions\n" +
514 "\t.section .rdata,\"dr\"\n" +
522 static string [] chars = new string [256];
524 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
528 // Preallocate the strings we need.
529 if (chars [0] == null) {
530 for (int i = 0; i < chars.Length; i++)
531 chars [i] = string.Format ("{0}", i.ToString ());
534 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
536 for (int i = 0; i < n; i++) {
537 if (count % 32 == 0) {
538 ts.Write ("\n\t.byte ");
542 ts.Write (chars [buffer [i]]);
551 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
552 const int align = 4096;
555 public PackageMaker (string output)
557 package = File.Create (output, 128*1024);
559 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
563 public int AddFile (string fname)
565 using (Stream fileStream = File.OpenRead (fname)){
566 var ret = fileStream.Length;
569 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
570 fileStream.CopyTo (package);
571 package.Position = package.Position + (align - (package.Position % align));
576 public void Add (string entry, string fname)
578 var p = package.Position;
579 var size = AddFile (fname);
580 locations [entry] = Tuple.Create(p, size);
583 public void AddString (string entry, string text)
585 var bytes = Encoding.UTF8.GetBytes (text);
586 locations [entry] = Tuple.Create (package.Position, bytes.Length);
587 package.Write (bytes, 0, bytes.Length);
588 package.Position = package.Position + (align - (package.Position % align));
591 public void AddStringPair (string entry, string key, string value)
593 var kbytes = Encoding.UTF8.GetBytes (key);
594 var vbytes = Encoding.UTF8.GetBytes (value);
596 Console.WriteLine ("ADDING {0} to {1}", key, value);
597 if (kbytes.Length > 255){
598 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
599 Environment.Exit (1);
602 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
603 package.WriteByte ((byte)kbytes.Length);
604 package.Write (kbytes, 0, kbytes.Length);
605 package.WriteByte (0);
606 package.Write (vbytes, 0, vbytes.Length);
607 package.WriteByte (0);
608 package.Position = package.Position + (align - (package.Position % align));
615 foreach (var floc in locations.Keys){
616 Console.WriteLine ($"{floc} at {locations[floc]:x}");
620 public void WriteIndex ()
622 var indexStart = package.Position;
623 var binary = new BinaryWriter (package);
625 binary.Write (locations.Count);
626 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
627 var bytes = Encoding.UTF8.GetBytes (entry.Key);
628 binary.Write (bytes.Length+1);
629 binary.Write (bytes);
630 binary.Write ((byte) 0);
631 binary.Write (entry.Value.Item1);
632 binary.Write (entry.Value.Item2);
634 binary.Write (indexStart);
635 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
647 static bool MaybeAddFile (PackageMaker maker, string code, string file)
652 if (!File.Exists (file)){
653 Error ("The file {0} does not exist", file);
656 maker.Add (code, file);
660 static bool GeneratePackage (List<string> files)
662 if (runtime == null){
664 runtime = Process.GetCurrentProcess().MainModule.FileName;
666 Error ("You must specify at least one runtime with --runtime or --cross");
667 Environment.Exit (1);
670 if (!File.Exists (runtime)){
671 Error ($"The specified runtime at {runtime} does not exist");
672 Environment.Exit (1);
675 if (ctor_func != null){
676 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
680 var maker = new PackageMaker (output);
681 Console.WriteLine ("Using runtime: " + runtime);
682 maker.AddFile (runtime);
684 foreach (var url in files){
685 string fname = LocateFile (new Uri (url).LocalPath);
686 string aname = MakeBundle.GetAssemblyName (fname);
688 maker.Add ("assembly:" + aname, fname);
689 Console.WriteLine (" Assembly: " + fname);
690 if (File.Exists (fname + ".config")){
691 maker.Add ("config:" + aname, fname + ".config");
692 Console.WriteLine (" Config: " + runtime);
696 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
699 if (config_dir != null)
700 maker.Add ("config_dir:", config_dir);
701 if (embedded_options != null)
702 maker.AddString ("options:", embedded_options);
703 if (environment.Count > 0){
704 foreach (var key in environment.Keys)
705 maker.AddStringPair ("env:" + key, key, environment [key]);
707 if (libraries.Count > 0){
708 foreach (var alias_and_path in libraries){
709 Console.WriteLine (" Library: " + alias_and_path.Value);
710 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
718 static void GenerateBundles (List<string> files)
720 string temp_s = "temp.s"; // Path.GetTempFileName ();
721 string temp_c = "temp.c";
722 string temp_o = "temp.o";
726 if (object_out != null)
730 List<string> c_bundle_names = new List<string> ();
731 List<string[]> config_names = new List<string[]> ();
733 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
734 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
737 if (bundled_header) {
738 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
739 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
743 const unsigned char *data;
744 const unsigned int size;
745 } MonoBundledAssembly;
746 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
747 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
750 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
751 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
752 tc.WriteLine ("#include <mono/jit/jit.h>\n");
756 tc.WriteLine ("typedef struct _compressed_data {");
757 tc.WriteLine ("\tMonoBundledAssembly assembly;");
758 tc.WriteLine ("\tint compressed_size;");
759 tc.WriteLine ("} CompressedAssembly;\n");
762 object monitor = new object ();
764 var streams = new Dictionary<string, Stream> ();
765 var sizes = new Dictionary<string, long> ();
767 // Do the file reading and compression in parallel
768 Action<string> body = delegate (string url) {
769 string fname = LocateFile (new Uri (url).LocalPath);
770 Stream stream = File.OpenRead (fname);
772 long real_size = stream.Length;
775 byte[] cbuffer = new byte [8192];
776 MemoryStream ms = new MemoryStream ();
777 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
778 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
779 deflate.Write (cbuffer, 0, n);
783 byte [] bytes = ms.GetBuffer ();
784 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
788 streams [url] = stream;
789 sizes [url] = real_size;
795 Parallel.ForEach (files, body);
797 foreach (var url in files)
801 // The non-parallel part
802 byte [] buffer = new byte [8192];
803 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
804 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
805 foreach (var url in files) {
806 string fname = LocateFile (new Uri (url).LocalPath);
807 string aname = MakeBundle.GetAssemblyName (fname);
808 string encoded = symbolEscapeRE.Replace (aname, "_");
813 var stream = streams [url];
814 var real_size = sizes [url];
817 Console.WriteLine (" embedding: " + fname);
819 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
821 WriteBuffer (ts, stream, buffer);
824 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
825 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
826 " assembly_data_{0}, {2}}}, {3}}};",
827 encoded, aname, real_size, stream.Length);
829 double ratio = ((double) stream.Length * 100) / real_size;
830 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
833 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
834 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
835 encoded, aname, real_size);
839 c_bundle_names.Add ("assembly_bundle_" + encoded);
842 FileStream cf = File.OpenRead (fname + ".config");
844 Console.WriteLine (" config from: " + fname + ".config");
845 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
846 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
847 WriteBuffer (ts, cf, buffer);
849 config_names.Add (new string[] {aname, encoded});
850 } catch (FileNotFoundException) {
851 /* we ignore if the config file doesn't exist */
855 if (config_file != null){
858 conf = File.OpenRead (config_file);
860 Error ("Failure to open {0}", config_file);
864 Console.WriteLine ("System config from: " + config_file);
865 tc.WriteLine ("extern const char system_config;");
866 WriteSymbol (ts, "system_config", config_file.Length);
868 WriteBuffer (ts, conf, buffer);
870 ts.Write ("\t.byte 0\n");
874 if (machine_config_file != null){
877 conf = File.OpenRead (machine_config_file);
879 Error ("Failure to open {0}", machine_config_file);
883 Console.WriteLine ("Machine config from: " + machine_config_file);
884 tc.WriteLine ("extern const char machine_config;");
885 WriteSymbol (ts, "machine_config", machine_config_file.Length);
887 WriteBuffer (ts, conf, buffer);
888 ts.Write ("\t.byte 0\n");
893 // Managed assemblies baked in
895 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
897 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
899 foreach (string c in c_bundle_names){
900 tc.WriteLine ("\t&{0},", c);
902 tc.WriteLine ("\tNULL\n};\n");
905 // AOT baked in plus loader
906 foreach (string asm in aot_names){
907 tc.WriteLine ("\textern const void *mono_aot_module_{0}_info;", asm);
910 tc.WriteLine ("\nstatic void install_aot_modules (void) {\n");
911 foreach (string asm in aot_names){
912 tc.WriteLine ("\tmono_aot_register_module (mono_aot_module_{0}_info);\n", asm);
915 string enum_aot_mode;
918 enum_aot_mode = "MONO_AOT_MODE_FULL";
921 enum_aot_mode = "MONO_AOT_MODE_LLVMONLY";
924 enum_aot_mode = "MONO_AOT_MODE_NORMAL";
927 throw new Exception ("Unsupported AOT mode");
929 tc.WriteLine ("\tmono_jit_set_aot_mode ({0});", enum_aot_mode);
931 tc.WriteLine ("\n}\n");
934 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
936 if (ctor_func != null) {
937 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
938 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
939 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
942 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
943 foreach (string[] ass in config_names){
944 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
946 if (config_file != null)
947 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
948 if (machine_config_file != null)
949 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
950 tc.WriteLine ("}\n");
952 if (config_dir != null)
953 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
955 tc.WriteLine ("static const char *config_dir = NULL;");
957 Stream template_stream;
959 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
961 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
964 StreamReader s = new StreamReader (template_stream);
965 string template = s.ReadToEnd ();
968 if (!nomain && custom_main == null) {
969 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
970 StreamReader st = new StreamReader (template_main_stream);
971 string maintemplate = st.ReadToEnd ();
972 tc.Write (maintemplate);
977 string assembler = GetEnv("AS", "as");
978 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
985 Console.WriteLine("Compiling:");
987 if (style == "windows")
990 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
992 string compiler = GetEnv("CC", "cl.exe");
993 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
994 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
995 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
997 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
998 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
999 var linkLibraries = new string[] { "kernel32.lib",
1014 string glue_obj = "mkbundle_glue.obj";
1018 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
1021 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
1022 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
1023 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
1026 var compilerArgs = new List<string>();
1027 compilerArgs.Add("/MT");
1029 foreach (string include in includes)
1030 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
1032 if (!nomain || custom_main != null) {
1033 compilerArgs.Add(quote(temp_c));
1034 compilerArgs.Add(quote(temp_o));
1035 if (custom_main != null)
1036 compilerArgs.Add(quote(custom_main));
1037 compilerArgs.Add(quote(monoLib));
1038 compilerArgs.Add("/link");
1039 compilerArgs.Add("/NODEFAULTLIB");
1040 compilerArgs.Add("/SUBSYSTEM:windows");
1041 compilerArgs.Add("/ENTRY:mainCRTStartup");
1042 compilerArgs.AddRange(linkLibraries);
1043 compilerArgs.Add("/out:"+ output);
1045 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1050 // we are just creating a .lib
1051 compilerArgs.Add("/c"); // compile only
1052 compilerArgs.Add(temp_c);
1053 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
1055 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
1058 string librarian = GetEnv ("LIB", "lib.exe");
1059 var librarianArgs = new List<string> ();
1060 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
1061 librarianArgs.Add (temp_o);
1062 librarianArgs.Add (glue_obj);
1063 librarianArgs.Add (monoLib);
1064 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1070 string zlib = (compress ? "-lz" : "");
1071 string debugging = "-g";
1072 string cc = GetEnv("CC", "cc");
1075 if (style == "linux")
1076 debugging = "-ggdb";
1079 string platform_libs;
1081 if (style == "osx") {
1082 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1083 platform_libs = "-liconv -framework Foundation ";
1085 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1089 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
1090 "`pkg-config --libs-only-L mono-2` {5} {6} " + platform_libs +
1091 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1} -g ",
1092 temp_c, temp_o, output, zlib, cc, smonolib, String.Join (" ", aot_paths));
1097 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1098 temp_c, temp_o, output, zlib, cc);
1104 Console.WriteLine ("Done");
1109 if (object_out == null){
1110 File.Delete (temp_o);
1113 File.Delete (temp_c);
1115 File.Delete (temp_s);
1120 static List<string> LoadAssemblies (List<string> sources)
1122 List<string> assemblies = new List<string> ();
1125 foreach (string name in sources){
1127 Assembly a = LoadAssemblyFile (name);
1134 assemblies.Add (a.CodeBase);
1135 } catch (Exception) {
1138 Console.WriteLine ("File will not be scanned: {0}", name);
1139 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1147 Error ("Couldn't load one or more of the assemblies.");
1148 Environment.Exit (1);
1154 static void LoadLocalizedAssemblies (List<string> assemblies)
1156 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1157 string error = null;
1159 foreach (string name in other) {
1161 Assembly a = LoadAssembly (name);
1164 error = "Failed to load " + name;
1168 assemblies.Add (a.CodeBase);
1169 } catch (Exception) {
1172 Console.WriteLine ("File will not be scanned: {0}", name);
1173 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1180 if (error != null) {
1181 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1182 foreach (var path in link_paths){
1183 Console.Error.WriteLine (" Path: " + path);
1186 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1189 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1190 Environment.Exit (1);
1195 static readonly Universe universe = new Universe ();
1196 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1198 public static string GetAssemblyName (string path)
1200 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1201 string name = Path.GetFileName (path);
1203 // A bit of a hack to support satellite assemblies. They all share the same name but
1204 // are placed in subdirectories named after the locale they implement. Also, all of
1205 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1206 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1207 string dir = Path.GetDirectoryName (path);
1208 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1210 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1211 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1213 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1219 static bool QueueAssembly (List<string> files, string codebase)
1221 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1222 if (files.Contains (codebase))
1225 var path = new Uri(codebase).LocalPath;
1226 var name = GetAssemblyName (path);
1228 if (loaded_assemblies.TryGetValue (name, out found)) {
1229 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1233 loaded_assemblies.Add (name, path);
1235 files.Add (codebase);
1239 Assembly a = universe.LoadFile (path);
1241 Error ("Unable to to load assembly `{0}'", path);
1245 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1246 a = LoadAssembly (an.Name);
1248 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1252 if (!QueueAssembly (files, a.CodeBase))
1255 } catch (Exception) {
1264 // Loads an assembly from a specific path
1266 static Assembly LoadAssemblyFile (string assembly)
1272 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1273 a = universe.LoadFile (assembly);
1275 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1277 } catch (FileNotFoundException){
1278 Error ($"Cannot find assembly `{assembly}'");
1279 } catch (IKVM.Reflection.BadImageFormatException f) {
1282 Error ($"Cannot load assembly (bad file format) " + f.Message);
1283 } catch (FileLoadException f){
1284 Error ($"Cannot load assembly " + f.Message);
1285 } catch (ArgumentNullException){
1286 Error( $"Cannot load assembly (null argument)");
1292 // Loads an assembly from any of the link directories provided
1294 static Assembly LoadAssembly (string assembly)
1296 string total_log = "";
1297 foreach (string dir in link_paths){
1298 string full_path = Path.Combine (dir, assembly);
1300 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1301 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1302 full_path += ".dll";
1305 var a = universe.LoadFile (full_path);
1307 } catch (FileNotFoundException ff) {
1308 total_log += ff.FusionLog;
1313 Console.WriteLine ("Log: \n" + total_log);
1317 static void Error (string msg, params object [] args)
1319 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1320 Environment.Exit (1);
1325 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1327 " --config F Bundle system config file `F'\n" +
1328 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1329 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1330 " -L path Adds `path' to the search path for assemblies\n" +
1331 " --machine-config F Use the given file as the machine.config for the application.\n" +
1332 " -o out Specifies output filename\n" +
1333 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1334 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1335 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1336 " -v Verbose output\n" +
1337 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1339 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1340 " --cross TARGET Generates a binary for the given TARGET\n"+
1341 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1342 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1343 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1344 " LIB is optional shortname for file located at PATH\n" +
1345 " --list-targets Lists available targets on the remote server\n" +
1346 " --local-targets Lists locally available targets\n" +
1347 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1348 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1349 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1350 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1352 "--custom Builds a custom launcher, options for --custom\n" +
1353 " -c Produce stub only, do not compile\n" +
1354 " -oo obj Specifies output filename for helper object file\n" +
1355 " --dos2unix[=true|false]\n" +
1356 " When no value provided, or when `true` specified\n" +
1357 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1358 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1359 " --keeptemp Keeps the temporary files\n" +
1360 " --static Statically link to mono libs\n" +
1361 " --nomain Don't include a main() function, for libraries\n" +
1362 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1363 " -z Compress the assemblies before embedding.\n" +
1364 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1365 " You need zlib development headers and libraries.\n");
1368 [DllImport ("libc")]
1369 static extern int system (string s);
1370 [DllImport ("libc")]
1371 static extern int uname (IntPtr buf);
1373 static void DetectOS ()
1376 os_message = "OS is: Windows";
1381 IntPtr buf = Marshal.AllocHGlobal (8192);
1382 if (uname (buf) != 0){
1383 os_message = "Warning: Unable to detect OS";
1384 Marshal.FreeHGlobal (buf);
1387 string os = Marshal.PtrToStringAnsi (buf);
1388 os_message = "OS is: " + os;
1392 Marshal.FreeHGlobal (buf);
1395 static bool IsUnix {
1397 int p = (int) Environment.OSVersion.Platform;
1398 return ((p == 4) || (p == 128) || (p == 6));
1403 static string EncodeAotSymbol (string symbol)
1405 var sb = new StringBuilder ();
1406 /* This mimics what the aot-compiler does */
1407 foreach (var b in System.Text.Encoding.UTF8.GetBytes (symbol)) {
1409 if ((c >= '0' && c <= '9') ||
1410 (c >= 'a' && c <= 'z') ||
1411 (c >= 'A' && c <= 'Z')) {
1417 return sb.ToString ();
1420 static void AotCompile (List<string> files)
1422 if (aot_runtime == null)
1423 aot_runtime = runtime;
1425 foreach (var fileName in files) {
1426 string path = LocateFile (new Uri (fileName).LocalPath);
1427 string outPath = String.Format ("{0}.aot_out", path);
1428 aot_paths.Add (outPath);
1429 var name = System.Reflection.Assembly.LoadFrom(path).GetName().Name;
1430 aot_names.Add (EncodeAotSymbol (name));
1431 var aot_mode_string = "";
1432 if (aot_mode != null)
1433 aot_mode_string = "," + aot_mode;
1434 Execute (String.Format ("{0} --aot={1},outfile={2}{3} {4}", aot_runtime, aot_args, outPath, aot_mode_string, path));
1438 static void Execute (string cmdLine)
1442 Console.WriteLine ("[execute cmd]: " + cmdLine);
1443 int ret = system (cmdLine);
1446 Error(String.Format("[Fail] {0}", ret));
1451 // on Windows, we have to pipe the output of a
1452 // `cmd` interpolation to dos2unix, because the shell does not
1453 // strip the CRLFs generated by the native pkg-config distributed
1456 // But if it's *not* on cygwin, just skip it.
1458 // check if dos2unix is applicable.
1459 if (use_dos2unix == true)
1461 var info = new ProcessStartInfo ("dos2unix");
1462 info.CreateNoWindow = true;
1463 info.RedirectStandardInput = true;
1464 info.UseShellExecute = false;
1465 var dos2unix = Process.Start (info);
1466 dos2unix.StandardInput.WriteLine ("aaa");
1467 dos2unix.StandardInput.WriteLine ("\u0004");
1468 dos2unix.StandardInput.Close ();
1469 dos2unix.WaitForExit ();
1470 if (dos2unix.ExitCode == 0)
1471 use_dos2unix = true;
1473 Console.WriteLine("Warning: dos2unix not found");
1474 use_dos2unix = false;
1477 if (use_dos2unix == null)
1478 use_dos2unix = false;
1480 ProcessStartInfo psi = new ProcessStartInfo();
1481 psi.UseShellExecute = false;
1483 // if there is no dos2unix, just run cmd /c.
1484 if (use_dos2unix == false)
1486 psi.FileName = "cmd";
1487 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1491 psi.FileName = "sh";
1492 StringBuilder b = new StringBuilder();
1494 for (int i = 0; i < cmdLine.Length; i++)
1496 if (cmdLine[i] == '`')
1500 b.Append("|dos2unix");
1504 b.Append(cmdLine[i]);
1506 cmdLine = b.ToString();
1507 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1511 Console.WriteLine(cmdLine);
1512 using (Process p = Process.Start (psi)) {
1514 int ret = p.ExitCode;
1516 Error ("[Fail] {0}", ret);
1521 static string GetEnv(string name, string defaultValue)
1523 string val = Environment.GetEnvironmentVariable(name);
1527 Console.WriteLine("{0} = {1}", name, val);
1533 Console.WriteLine("{0} = {1} (default)", name, val);
1538 static string LocateFile(string default_path)
1540 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1541 if (File.Exists(override_path))
1542 return override_path;
1543 else if (File.Exists(default_path))
1544 return default_path;
1546 throw new FileNotFoundException(default_path);