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 Dictionary<string,string> libraries = new Dictionary<string,string> ();
44 static bool autodeps = false;
45 static bool keeptemp = false;
46 static bool compile_only = false;
47 static bool static_link = false;
48 static string config_file = null;
49 static string machine_config_file = null;
50 static string config_dir = null;
51 static string style = "linux";
52 static bool bundled_header = false;
53 static string os_message = "";
56 static string custom_main = null;
57 static bool? use_dos2unix = null;
58 static bool skip_scan;
59 static string ctor_func;
60 static bool quiet = true;
61 static string cross_target = null;
62 static string fetch_target = null;
63 static bool custom_mode = true;
64 static string embedded_options = null;
65 static string runtime = null;
66 static string sdk_path = null;
67 static string lib_path = null;
68 static Dictionary<string,string> environment = new Dictionary<string,string>();
69 static string [] i18n = new string [] {
73 static string [] i18n_all = new string [] {
81 static string target_server = "https://download.mono-project.com/runtimes/raw/";
83 static int Main (string [] args)
85 List<string> sources = new List<string> ();
86 int top = args.Length;
91 for (int i = 0; i < top; i++){
93 case "--help": case "-h": case "-?":
111 var iarg = args [++i];
114 else if (iarg == "none")
115 i18n = new string [0];
117 i18n = iarg.Split (',');
128 case "--local-targets":
129 CommandLocalTargets ();
137 if (sdk_path != null || runtime != null)
138 Error ("You can not specify one of --runtime, --sdk or --cross");
141 cross_target = args [++i];
150 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
154 var lspec = args [++i];
155 var p = lspec.IndexOf (",");
158 alias = Path.GetFileName (lspec);
161 alias = lspec.Substring (0, p);
162 path = lspec.Substring (p+1);
164 if (!File.Exists (path))
165 Error ($"The specified library file {path} does not exist");
166 libraries [alias] = path;
169 case "--fetch-target":
174 fetch_target = args [++i];
177 case "--list-targets":
178 CommandLocalTargets ();
179 var wc = new WebClient ();
180 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
181 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
184 case "--target-server":
189 target_server = args [++i];
205 embedded_options = args [++i];
214 sdk_path = args [++i];
215 if (cross_target != null || runtime != null)
216 Error ("You can not specify one of --runtime, --sdk or --cross");
223 if (sdk_path != null || cross_target != null)
224 Error ("You can only specify one of --runtime, --sdk or --cross");
227 runtime = args [++i];
234 object_out = args [++i];
242 link_paths.Add (args [++i]);
266 config_file = args [++i];
268 case "--machine-config":
274 machine_config_file = args [++i];
277 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
285 config_dir = args [++i];
293 case "--custom-main":
298 custom_main = args [++i];
312 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
320 case "--static-ctor":
325 ctor_func = args [++i];
328 case "--dos2unix=true":
331 case "--dos2unix=false":
332 use_dos2unix = false;
344 var env = args [++i];
345 p = env.IndexOf ('=');
347 environment.Add (env, "");
349 environment.Add (env.Substring (0, p), env.Substring (p+1));
351 case "--bundled-header":
352 bundled_header = true;
355 sources.Add (args [i]);
360 // Modern bundling starts here
362 if (runtime != null){
363 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
364 } else if (sdk_path != null) {
365 VerifySdk (sdk_path);
366 } else if (cross_target == "default" || cross_target == null){
367 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
368 VerifySdk (sdk_path);
370 sdk_path = Path.Combine (targets_dir, cross_target);
371 Console.WriteLine ("From: " + sdk_path);
372 VerifySdk (sdk_path);
376 if (fetch_target != null){
377 var directory = Path.Combine (targets_dir, fetch_target);
378 var zip_download = Path.Combine (directory, "sdk.zip");
379 Directory.CreateDirectory (directory);
380 var wc = new WebClient ();
381 var uri = new Uri ($"{target_server}{fetch_target}");
384 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
387 wc.DownloadFile (uri, zip_download);
388 ZipFile.ExtractToDirectory(zip_download, directory);
389 File.Delete (zip_download);
391 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
392 File.Delete (zip_download);
399 Console.WriteLine (os_message);
400 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
403 if (sources.Count == 0 || output == null) {
405 Environment.Exit (1);
408 List<string> assemblies = LoadAssemblies (sources);
409 LoadLocalizedAssemblies (assemblies);
410 List<string> files = new List<string> ();
411 foreach (string file in assemblies)
412 if (!QueueAssembly (files, file))
415 GenerateBundles (files);
417 GeneratePackage (files);
419 Console.WriteLine ("Generated {0}", output);
424 static void VerifySdk (string path)
426 if (!Directory.Exists (path))
427 Error ($"The specified SDK path does not exist: {path}");
428 runtime = Path.Combine (sdk_path, "bin", "mono");
429 if (!File.Exists (runtime))
430 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
431 lib_path = Path.Combine (path, "lib", "mono", "4.5");
432 if (!Directory.Exists (lib_path))
433 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
434 link_paths.Add (lib_path);
437 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
439 static void CommandLocalTargets ()
443 Console.WriteLine ("Available targets locally:");
444 Console.WriteLine ("\tdefault\t- Current System Mono");
446 targets = Directory.GetDirectories (targets_dir);
450 foreach (var target in targets){
451 var p = Path.Combine (target, "bin", "mono");
453 Console.WriteLine ("\t{0}", Path.GetFileName (target));
457 static void WriteSymbol (StreamWriter sw, string name, long size)
463 "\t.section .rodata\n" +
465 "\t.type {0}, \"object\"\n" +
466 "\t.size {0}, {1}\n" +
472 "\t.section __TEXT,__text,regular,pure_instructions\n" +
482 "\t.section .rdata,\"dr\"\n" +
490 static string [] chars = new string [256];
492 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
496 // Preallocate the strings we need.
497 if (chars [0] == null) {
498 for (int i = 0; i < chars.Length; i++)
499 chars [i] = string.Format ("{0}", i.ToString ());
502 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
504 for (int i = 0; i < n; i++) {
505 if (count % 32 == 0) {
506 ts.Write ("\n\t.byte ");
510 ts.Write (chars [buffer [i]]);
519 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
520 const int align = 4096;
523 public PackageMaker (string output)
525 package = File.Create (output, 128*1024);
527 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
531 public int AddFile (string fname)
533 using (Stream fileStream = File.OpenRead (fname)){
534 var ret = fileStream.Length;
537 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
538 fileStream.CopyTo (package);
539 package.Position = package.Position + (align - (package.Position % align));
545 public void Add (string entry, string fname)
547 var p = package.Position;
548 var size = AddFile (fname);
550 locations [entry] = Tuple.Create(p, size);
553 public void AddString (string entry, string text)
555 var bytes = Encoding.UTF8.GetBytes (text);
556 locations [entry] = Tuple.Create (package.Position, bytes.Length);
557 package.Write (bytes, 0, bytes.Length);
558 package.Position = package.Position + (align - (package.Position % align));
561 public void AddStringPair (string entry, string key, string value)
563 var kbytes = Encoding.UTF8.GetBytes (key);
564 var vbytes = Encoding.UTF8.GetBytes (value);
566 Console.WriteLine ("ADDING {0} to {1}", key, value);
567 if (kbytes.Length > 255){
568 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
569 Environment.Exit (1);
572 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
573 package.WriteByte ((byte)kbytes.Length);
574 package.Write (kbytes, 0, kbytes.Length);
575 package.WriteByte (0);
576 package.Write (vbytes, 0, vbytes.Length);
577 package.WriteByte (0);
578 package.Position = package.Position + (align - (package.Position % align));
585 foreach (var floc in locations.Keys){
586 Console.WriteLine ($"{floc} at {locations[floc]:x}");
590 public void WriteIndex ()
592 var indexStart = package.Position;
593 var binary = new BinaryWriter (package);
595 binary.Write (locations.Count);
596 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
597 var bytes = Encoding.UTF8.GetBytes (entry.Key);
598 binary.Write (bytes.Length+1);
599 binary.Write (bytes);
600 binary.Write ((byte) 0);
601 binary.Write (entry.Value.Item1);
602 binary.Write (entry.Value.Item2);
604 binary.Write (indexStart);
605 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
617 static bool MaybeAddFile (PackageMaker maker, string code, string file)
622 if (!File.Exists (file)){
623 Error ("The file {0} does not exist", file);
626 maker.Add (code, file);
630 static bool GeneratePackage (List<string> files)
632 if (runtime == null){
634 runtime = Process.GetCurrentProcess().MainModule.FileName;
636 Error ("You must specify at least one runtime with --runtime or --cross");
637 Environment.Exit (1);
640 if (!File.Exists (runtime)){
641 Error ($"The specified runtime at {runtime} does not exist");
642 Environment.Exit (1);
645 if (ctor_func != null){
646 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
650 var maker = new PackageMaker (output);
651 Console.WriteLine ("Using runtime: " + runtime);
652 maker.AddFile (runtime);
654 foreach (var url in files){
655 string fname = LocateFile (new Uri (url).LocalPath);
656 string aname = MakeBundle.GetAssemblyName (fname);
658 maker.Add ("assembly:" + aname, fname);
659 Console.WriteLine (" Assembly: " + fname);
660 if (File.Exists (fname + ".config")){
661 maker.Add ("config:" + aname, fname + ".config");
662 Console.WriteLine (" Config: " + runtime);
666 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
669 if (config_dir != null)
670 maker.Add ("config_dir:", config_dir);
671 if (embedded_options != null)
672 maker.AddString ("options:", embedded_options);
673 if (environment.Count > 0){
674 foreach (var key in environment.Keys)
675 maker.AddStringPair ("env:" + key, key, environment [key]);
677 if (libraries.Count > 0){
678 foreach (var alias_and_path in libraries){
679 Console.WriteLine (" Library: " + alias_and_path.Value);
680 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
688 static void GenerateBundles (List<string> files)
690 string temp_s = "temp.s"; // Path.GetTempFileName ();
691 string temp_c = "temp.c";
692 string temp_o = "temp.o";
696 if (object_out != null)
700 List<string> c_bundle_names = new List<string> ();
701 List<string[]> config_names = new List<string[]> ();
703 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
704 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
707 if (bundled_header) {
708 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
709 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
713 const unsigned char *data;
714 const unsigned int size;
715 } MonoBundledAssembly;
716 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
717 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
720 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
721 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
725 tc.WriteLine ("typedef struct _compressed_data {");
726 tc.WriteLine ("\tMonoBundledAssembly assembly;");
727 tc.WriteLine ("\tint compressed_size;");
728 tc.WriteLine ("} CompressedAssembly;\n");
731 object monitor = new object ();
733 var streams = new Dictionary<string, Stream> ();
734 var sizes = new Dictionary<string, long> ();
736 // Do the file reading and compression in parallel
737 Action<string> body = delegate (string url) {
738 string fname = LocateFile (new Uri (url).LocalPath);
739 Stream stream = File.OpenRead (fname);
741 long real_size = stream.Length;
744 byte[] cbuffer = new byte [8192];
745 MemoryStream ms = new MemoryStream ();
746 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
747 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
748 deflate.Write (cbuffer, 0, n);
752 byte [] bytes = ms.GetBuffer ();
753 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
757 streams [url] = stream;
758 sizes [url] = real_size;
764 Parallel.ForEach (files, body);
766 foreach (var url in files)
770 // The non-parallel part
771 byte [] buffer = new byte [8192];
772 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
773 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
774 foreach (var url in files) {
775 string fname = LocateFile (new Uri (url).LocalPath);
776 string aname = MakeBundle.GetAssemblyName (fname);
777 string encoded = symbolEscapeRE.Replace (aname, "_");
782 var stream = streams [url];
783 var real_size = sizes [url];
786 Console.WriteLine (" embedding: " + fname);
788 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
790 WriteBuffer (ts, stream, buffer);
793 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
794 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
795 " assembly_data_{0}, {2}}}, {3}}};",
796 encoded, aname, real_size, stream.Length);
798 double ratio = ((double) stream.Length * 100) / real_size;
799 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
802 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
803 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
804 encoded, aname, real_size);
808 c_bundle_names.Add ("assembly_bundle_" + encoded);
811 FileStream cf = File.OpenRead (fname + ".config");
813 Console.WriteLine (" config from: " + fname + ".config");
814 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
815 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
816 WriteBuffer (ts, cf, buffer);
818 config_names.Add (new string[] {aname, encoded});
819 } catch (FileNotFoundException) {
820 /* we ignore if the config file doesn't exist */
824 if (config_file != null){
827 conf = File.OpenRead (config_file);
829 Error ("Failure to open {0}", config_file);
833 Console.WriteLine ("System config from: " + config_file);
834 tc.WriteLine ("extern const char system_config;");
835 WriteSymbol (ts, "system_config", config_file.Length);
837 WriteBuffer (ts, conf, buffer);
839 ts.Write ("\t.byte 0\n");
843 if (machine_config_file != null){
846 conf = File.OpenRead (machine_config_file);
848 Error ("Failure to open {0}", machine_config_file);
852 Console.WriteLine ("Machine config from: " + machine_config_file);
853 tc.WriteLine ("extern const char machine_config;");
854 WriteSymbol (ts, "machine_config", machine_config_file.Length);
856 WriteBuffer (ts, conf, buffer);
857 ts.Write ("\t.byte 0\n");
863 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
865 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
867 foreach (string c in c_bundle_names){
868 tc.WriteLine ("\t&{0},", c);
870 tc.WriteLine ("\tNULL\n};\n");
871 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
873 if (ctor_func != null) {
874 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
875 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
876 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
879 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
880 foreach (string[] ass in config_names){
881 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
883 if (config_file != null)
884 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
885 if (machine_config_file != null)
886 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
887 tc.WriteLine ("}\n");
889 if (config_dir != null)
890 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
892 tc.WriteLine ("static const char *config_dir = NULL;");
894 Stream template_stream;
896 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
898 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
901 StreamReader s = new StreamReader (template_stream);
902 string template = s.ReadToEnd ();
905 if (!nomain && custom_main == null) {
906 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
907 StreamReader st = new StreamReader (template_main_stream);
908 string maintemplate = st.ReadToEnd ();
909 tc.Write (maintemplate);
914 string assembler = GetEnv("AS", "as");
915 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
922 Console.WriteLine("Compiling:");
924 if (style == "windows")
927 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
929 string compiler = GetEnv("CC", "cl.exe");
930 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
931 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
932 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
934 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
935 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
936 var linkLibraries = new string[] { "kernel32.lib",
951 string glue_obj = "mkbundle_glue.obj";
955 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
958 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
959 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
960 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
963 var compilerArgs = new List<string>();
964 compilerArgs.Add("/MT");
966 foreach (string include in includes)
967 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
969 if (!nomain || custom_main != null) {
970 compilerArgs.Add(quote(temp_c));
971 compilerArgs.Add(quote(temp_o));
972 if (custom_main != null)
973 compilerArgs.Add(quote(custom_main));
974 compilerArgs.Add(quote(monoLib));
975 compilerArgs.Add("/link");
976 compilerArgs.Add("/NODEFAULTLIB");
977 compilerArgs.Add("/SUBSYSTEM:windows");
978 compilerArgs.Add("/ENTRY:mainCRTStartup");
979 compilerArgs.AddRange(linkLibraries);
980 compilerArgs.Add("/out:"+ output);
982 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
987 // we are just creating a .lib
988 compilerArgs.Add("/c"); // compile only
989 compilerArgs.Add(temp_c);
990 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
992 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
995 string librarian = GetEnv ("LIB", "lib.exe");
996 var librarianArgs = new List<string> ();
997 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
998 librarianArgs.Add (temp_o);
999 librarianArgs.Add (glue_obj);
1000 librarianArgs.Add (monoLib);
1001 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1007 string zlib = (compress ? "-lz" : "");
1008 string debugging = "-g";
1009 string cc = GetEnv("CC", "cc");
1012 if (style == "linux")
1013 debugging = "-ggdb";
1018 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1020 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1021 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
1022 "`pkg-config --libs-only-L mono-2` " + smonolib +
1023 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
1024 temp_c, temp_o, output, zlib, cc);
1029 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1030 temp_c, temp_o, output, zlib, cc);
1036 Console.WriteLine ("Done");
1041 if (object_out == null){
1042 File.Delete (temp_o);
1045 File.Delete (temp_c);
1047 File.Delete (temp_s);
1052 static List<string> LoadAssemblies (List<string> sources)
1054 List<string> assemblies = new List<string> ();
1057 foreach (string name in sources){
1059 Assembly a = LoadAssemblyFile (name);
1066 assemblies.Add (a.CodeBase);
1067 } catch (Exception) {
1070 Console.WriteLine ("File will not be scanned: {0}", name);
1071 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1079 Error ("Couldn't load one or more of the assemblies.");
1080 Environment.Exit (1);
1086 static void LoadLocalizedAssemblies (List<string> assemblies)
1088 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1089 string error = null;
1091 foreach (string name in other) {
1093 Assembly a = LoadAssembly (name);
1096 error = "Failed to load " + name;
1100 assemblies.Add (a.CodeBase);
1101 } catch (Exception) {
1104 Console.WriteLine ("File will not be scanned: {0}", name);
1105 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1112 if (error != null) {
1113 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1114 Environment.Exit (1);
1119 static readonly Universe universe = new Universe ();
1120 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1121 static readonly string resourcePathSeparator = (Path.DirectorySeparatorChar == '\\') ? $"\\{Path.DirectorySeparatorChar}" : $"{Path.DirectorySeparatorChar}";
1123 public static string GetAssemblyName (string path)
1125 string name = Path.GetFileName (path);
1127 // A bit of a hack to support satellite assemblies. They all share the same name but
1128 // are placed in subdirectories named after the locale they implement. Also, all of
1129 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1130 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1131 string dir = Path.GetDirectoryName (path);
1132 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1134 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1135 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1137 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1143 static bool QueueAssembly (List<string> files, string codebase)
1145 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1146 if (files.Contains (codebase))
1149 var path = new Uri(codebase).LocalPath;
1150 var name = GetAssemblyName (path);
1152 if (loaded_assemblies.TryGetValue (name, out found)) {
1153 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1157 loaded_assemblies.Add (name, path);
1159 files.Add (codebase);
1163 Assembly a = universe.LoadFile (path);
1165 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1166 a = LoadAssembly (an.Name);
1167 if (!QueueAssembly (files, a.CodeBase))
1170 } catch (Exception) {
1179 // Loads an assembly from a specific path
1181 static Assembly LoadAssemblyFile (string assembly)
1186 a = universe.LoadFile (assembly);
1187 } catch (FileNotFoundException){
1188 Error ($"Cannot find assembly `{assembly}'");
1189 } catch (IKVM.Reflection.BadImageFormatException f) {
1192 Error ($"Cannot load assembly (bad file format) " + f.Message);
1193 } catch (FileLoadException f){
1194 Error ($"Cannot load assembly " + f.Message);
1195 } catch (ArgumentNullException){
1196 Error( $"Cannot load assembly (null argument)");
1202 // Loads an assembly from any of the link directories provided
1204 static Assembly LoadAssembly (string assembly)
1206 string total_log = "";
1207 foreach (string dir in link_paths){
1208 string full_path = Path.Combine (dir, assembly);
1209 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1210 full_path += ".dll";
1213 var a = universe.LoadFile (full_path);
1215 } catch (FileNotFoundException ff) {
1216 total_log += ff.FusionLog;
1221 Console.WriteLine ("Log: \n" + total_log);
1225 static void Error (string msg, params object [] args)
1227 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1228 Environment.Exit (1);
1233 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1235 " --config F Bundle system config file `F'\n" +
1236 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1237 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1238 " -L path Adds `path' to the search path for assemblies\n" +
1239 " --machine-config F Use the given file as the machine.config for the application.\n" +
1240 " -o out Specifies output filename\n" +
1241 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1242 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1243 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1244 " -v Verbose output\n" +
1245 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1247 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1248 " --cross TARGET Generates a binary for the given TARGET\n"+
1249 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1250 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1251 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1252 " LIB is optional shortname for file located at PATH\n" +
1253 " --list-targets Lists available targets on the remote server\n" +
1254 " --local-targets Lists locally available targets\n" +
1255 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1256 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1257 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1258 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1260 "--custom Builds a custom launcher, options for --custom\n" +
1261 " -c Produce stub only, do not compile\n" +
1262 " -oo obj Specifies output filename for helper object file\n" +
1263 " --dos2unix[=true|false]\n" +
1264 " When no value provided, or when `true` specified\n" +
1265 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1266 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1267 " --keeptemp Keeps the temporary files\n" +
1268 " --static Statically link to mono libs\n" +
1269 " --nomain Don't include a main() function, for libraries\n" +
1270 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1271 " -z Compress the assemblies before embedding.\n" +
1272 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1273 " You need zlib development headers and libraries.\n");
1276 [DllImport ("libc")]
1277 static extern int system (string s);
1278 [DllImport ("libc")]
1279 static extern int uname (IntPtr buf);
1281 static void DetectOS ()
1284 os_message = "OS is: Windows";
1289 IntPtr buf = Marshal.AllocHGlobal (8192);
1290 if (uname (buf) != 0){
1291 os_message = "Warning: Unable to detect OS";
1292 Marshal.FreeHGlobal (buf);
1295 string os = Marshal.PtrToStringAnsi (buf);
1296 os_message = "OS is: " + os;
1300 Marshal.FreeHGlobal (buf);
1303 static bool IsUnix {
1305 int p = (int) Environment.OSVersion.Platform;
1306 return ((p == 4) || (p == 128) || (p == 6));
1310 static void Execute (string cmdLine)
1314 Console.WriteLine ("[execute cmd]: " + cmdLine);
1315 int ret = system (cmdLine);
1318 Error(String.Format("[Fail] {0}", ret));
1323 // on Windows, we have to pipe the output of a
1324 // `cmd` interpolation to dos2unix, because the shell does not
1325 // strip the CRLFs generated by the native pkg-config distributed
1328 // But if it's *not* on cygwin, just skip it.
1330 // check if dos2unix is applicable.
1331 if (use_dos2unix == true)
1333 var info = new ProcessStartInfo ("dos2unix");
1334 info.CreateNoWindow = true;
1335 info.RedirectStandardInput = true;
1336 info.UseShellExecute = false;
1337 var dos2unix = Process.Start (info);
1338 dos2unix.StandardInput.WriteLine ("aaa");
1339 dos2unix.StandardInput.WriteLine ("\u0004");
1340 dos2unix.StandardInput.Close ();
1341 dos2unix.WaitForExit ();
1342 if (dos2unix.ExitCode == 0)
1343 use_dos2unix = true;
1345 Console.WriteLine("Warning: dos2unix not found");
1346 use_dos2unix = false;
1349 if (use_dos2unix == null)
1350 use_dos2unix = false;
1352 ProcessStartInfo psi = new ProcessStartInfo();
1353 psi.UseShellExecute = false;
1355 // if there is no dos2unix, just run cmd /c.
1356 if (use_dos2unix == false)
1358 psi.FileName = "cmd";
1359 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1363 psi.FileName = "sh";
1364 StringBuilder b = new StringBuilder();
1366 for (int i = 0; i < cmdLine.Length; i++)
1368 if (cmdLine[i] == '`')
1372 b.Append("|dos2unix");
1376 b.Append(cmdLine[i]);
1378 cmdLine = b.ToString();
1379 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1383 Console.WriteLine(cmdLine);
1384 using (Process p = Process.Start (psi)) {
1386 int ret = p.ExitCode;
1388 Error ("[Fail] {0}", ret);
1393 static string GetEnv(string name, string defaultValue)
1395 string val = Environment.GetEnvironmentVariable(name);
1399 Console.WriteLine("{0} = {1}", name, val);
1405 Console.WriteLine("{0} = {1} (default)", name, val);
1410 static string LocateFile(string default_path)
1412 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1413 if (File.Exists(override_path))
1414 return override_path;
1415 else if (File.Exists(default_path))
1416 return default_path;
1418 throw new FileNotFoundException(default_path);