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 string os_message = "";
55 static string custom_main = null;
56 static bool? use_dos2unix = null;
57 static bool skip_scan;
58 static string ctor_func;
59 static bool quiet = true;
60 static string cross_target = null;
61 static string fetch_target = null;
62 static bool custom_mode = true;
63 static string embedded_options = null;
64 static string runtime = null;
65 static string sdk_path = null;
66 static string lib_path = null;
67 static Dictionary<string,string> environment = new Dictionary<string,string>();
68 static string [] i18n = new string [] {
72 static string [] i18n_all = new string [] {
80 static string target_server = "https://download.mono-project.com/runtimes/raw/";
82 static int Main (string [] args)
84 List<string> sources = new List<string> ();
85 int top = args.Length;
90 for (int i = 0; i < top; i++){
92 case "--help": case "-h": case "-?":
110 var iarg = args [++i];
113 else if (iarg == "none")
114 i18n = new string [0];
116 i18n = iarg.Split (',');
127 case "--local-targets":
128 CommandLocalTargets ();
136 if (sdk_path != null || runtime != null)
137 Error ("You can not specify one of --runtime, --sdk or --cross");
140 cross_target = args [++i];
149 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
153 var lspec = args [++i];
154 var p = lspec.IndexOf (",");
157 alias = Path.GetFileName (lspec);
160 alias = lspec.Substring (0, p);
161 path = lspec.Substring (p+1);
163 if (!File.Exists (path))
164 Error ($"The specified library file {path} does not exist");
165 libraries [alias] = path;
168 case "--fetch-target":
173 fetch_target = args [++i];
176 case "--list-targets":
177 CommandLocalTargets ();
178 var wc = new WebClient ();
179 var s = wc.DownloadString (new Uri (target_server + "target-sdks.txt"));
180 Console.WriteLine ("Targets available for download with --fetch-target:\n" + s);
183 case "--target-server":
188 target_server = args [++i];
204 embedded_options = args [++i];
213 sdk_path = args [++i];
214 if (cross_target != null || runtime != null)
215 Error ("You can not specify one of --runtime, --sdk or --cross");
222 if (sdk_path != null || cross_target != null)
223 Error ("You can only specify one of --runtime, --sdk or --cross");
226 runtime = args [++i];
233 object_out = args [++i];
241 link_paths.Add (args [++i]);
265 config_file = args [++i];
267 case "--machine-config":
273 machine_config_file = args [++i];
276 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
284 config_dir = args [++i];
292 case "--custom-main":
297 custom_main = args [++i];
311 Error ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
319 case "--static-ctor":
324 ctor_func = args [++i];
327 case "--dos2unix=true":
330 case "--dos2unix=false":
331 use_dos2unix = false;
343 var env = args [++i];
344 p = env.IndexOf ('=');
346 environment.Add (env, "");
348 environment.Add (env.Substring (0, p), env.Substring (p+1));
351 sources.Add (args [i]);
356 // Modern bundling starts here
358 if (runtime != null){
359 // Nothing to do here, the user has chosen to manually specify --runtime nad libraries
360 } else if (sdk_path != null) {
361 VerifySdk (sdk_path);
362 } else if (cross_target == "default" || cross_target == null){
363 sdk_path = Path.GetFullPath (Path.Combine (Process.GetCurrentProcess().MainModule.FileName, "..", ".."));
364 VerifySdk (sdk_path);
366 sdk_path = Path.Combine (targets_dir, cross_target);
367 Console.WriteLine ("From: " + sdk_path);
368 VerifySdk (sdk_path);
372 if (fetch_target != null){
373 var directory = Path.Combine (targets_dir, fetch_target);
374 var zip_download = Path.Combine (directory, "sdk.zip");
375 Directory.CreateDirectory (Path.GetDirectoryName (directory));
376 var wc = new WebClient ();
377 var uri = new Uri ($"{target_server}{fetch_target}");
380 Console.WriteLine ($"Downloading runtime {uri} to {zip_download}");
383 wc.DownloadFile (uri, zip_download);
384 ZipFile.ExtractToDirectory(zip_download, directory);
385 File.Delete (zip_download);
387 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
388 File.Delete (zip_download);
395 Console.WriteLine (os_message);
396 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
399 if (sources.Count == 0 || output == null) {
401 Environment.Exit (1);
404 List<string> assemblies = LoadAssemblies (sources);
405 LoadLocalizedAssemblies (assemblies);
406 List<string> files = new List<string> ();
407 foreach (string file in assemblies)
408 if (!QueueAssembly (files, file))
411 GenerateBundles (files);
413 GeneratePackage (files);
415 Console.WriteLine ("Generated {0}", output);
420 static void VerifySdk (string path)
422 if (!Directory.Exists (path))
423 Error ($"The specified SDK path does not exist: {path}");
424 runtime = Path.Combine (sdk_path, "bin", "mono");
425 if (!File.Exists (runtime))
426 Error ($"The SDK location does not contain a {path}/bin/mono runtime");
427 lib_path = Path.Combine (path, "lib", "mono", "4.5");
428 if (!Directory.Exists (lib_path))
429 Error ($"The SDK location does not contain a {path}/lib/mono/4.5 directory");
430 link_paths.Add (lib_path);
433 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
435 static void CommandLocalTargets ()
439 Console.WriteLine ("Available targets locally:");
440 Console.WriteLine ("\tdefault\t- Current System Mono");
442 targets = Directory.GetDirectories (targets_dir);
446 foreach (var target in targets){
447 var p = Path.Combine (target, "bin", "mono");
449 Console.WriteLine ("\t{0}", Path.GetFileName (target));
453 static void WriteSymbol (StreamWriter sw, string name, long size)
459 "\t.section .rodata\n" +
461 "\t.type {0}, \"object\"\n" +
462 "\t.size {0}, {1}\n" +
468 "\t.section __TEXT,__text,regular,pure_instructions\n" +
478 "\t.section .rdata,\"dr\"\n" +
486 static string [] chars = new string [256];
488 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
492 // Preallocate the strings we need.
493 if (chars [0] == null) {
494 for (int i = 0; i < chars.Length; i++)
495 chars [i] = string.Format ("{0}", i.ToString ());
498 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
500 for (int i = 0; i < n; i++) {
501 if (count % 32 == 0) {
502 ts.Write ("\n\t.byte ");
506 ts.Write (chars [buffer [i]]);
515 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
516 const int align = 4096;
519 public PackageMaker (string output)
521 package = File.Create (output, 128*1024);
523 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
527 public int AddFile (string fname)
529 using (Stream fileStream = File.OpenRead (fname)){
530 var ret = fileStream.Length;
533 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
534 fileStream.CopyTo (package);
535 package.Position = package.Position + (align - (package.Position % align));
541 public void Add (string entry, string fname)
543 var p = package.Position;
544 var size = AddFile (fname);
546 locations [entry] = Tuple.Create(p, size);
549 public void AddString (string entry, string text)
551 var bytes = Encoding.UTF8.GetBytes (text);
552 locations [entry] = Tuple.Create (package.Position, bytes.Length);
553 package.Write (bytes, 0, bytes.Length);
554 package.Position = package.Position + (align - (package.Position % align));
557 public void AddStringPair (string entry, string key, string value)
559 var kbytes = Encoding.UTF8.GetBytes (key);
560 var vbytes = Encoding.UTF8.GetBytes (value);
562 Console.WriteLine ("ADDING {0} to {1}", key, value);
563 if (kbytes.Length > 255){
564 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
565 Environment.Exit (1);
568 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
569 package.WriteByte ((byte)kbytes.Length);
570 package.Write (kbytes, 0, kbytes.Length);
571 package.WriteByte (0);
572 package.Write (vbytes, 0, vbytes.Length);
573 package.WriteByte (0);
574 package.Position = package.Position + (align - (package.Position % align));
581 foreach (var floc in locations.Keys){
582 Console.WriteLine ($"{floc} at {locations[floc]:x}");
586 public void WriteIndex ()
588 var indexStart = package.Position;
589 var binary = new BinaryWriter (package);
591 binary.Write (locations.Count);
592 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
593 var bytes = Encoding.UTF8.GetBytes (entry.Key);
594 binary.Write (bytes.Length+1);
595 binary.Write (bytes);
596 binary.Write ((byte) 0);
597 binary.Write (entry.Value.Item1);
598 binary.Write (entry.Value.Item2);
600 binary.Write (indexStart);
601 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
613 static bool MaybeAddFile (PackageMaker maker, string code, string file)
618 if (!File.Exists (file)){
619 Error ("The file {0} does not exist", file);
622 maker.Add (code, file);
626 static bool GeneratePackage (List<string> files)
628 if (runtime == null){
630 runtime = Process.GetCurrentProcess().MainModule.FileName;
632 Error ("You must specify at least one runtime with --runtime or --cross");
633 Environment.Exit (1);
636 if (!File.Exists (runtime)){
637 Error ($"The specified runtime at {runtime} does not exist");
638 Environment.Exit (1);
641 if (ctor_func != null){
642 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
646 var maker = new PackageMaker (output);
647 Console.WriteLine ("Using runtime: " + runtime);
648 maker.AddFile (runtime);
650 foreach (var url in files){
651 string fname = LocateFile (new Uri (url).LocalPath);
652 string aname = MakeBundle.GetAssemblyName (fname);
654 maker.Add ("assembly:" + aname, fname);
655 Console.WriteLine (" Assembly: " + fname);
656 if (File.Exists (fname + ".config")){
657 maker.Add ("config:" + aname, fname + ".config");
658 Console.WriteLine (" Config: " + runtime);
662 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
665 if (config_dir != null)
666 maker.Add ("config_dir:", config_dir);
667 if (embedded_options != null)
668 maker.AddString ("options:", embedded_options);
669 if (environment.Count > 0){
670 foreach (var key in environment.Keys)
671 maker.AddStringPair ("env:" + key, key, environment [key]);
673 if (libraries.Count > 0){
674 foreach (var alias_and_path in libraries){
675 Console.WriteLine (" Library: " + alias_and_path.Value);
676 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
684 static void GenerateBundles (List<string> files)
686 string temp_s = "temp.s"; // Path.GetTempFileName ();
687 string temp_c = "temp.c";
688 string temp_o = "temp.o";
692 if (object_out != null)
696 List<string> c_bundle_names = new List<string> ();
697 List<string[]> config_names = new List<string[]> ();
699 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
700 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
704 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
705 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
709 const unsigned char *data;
710 const unsigned int size;
711 } MonoBundledAssembly;
712 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
713 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
716 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
717 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
721 tc.WriteLine ("typedef struct _compressed_data {");
722 tc.WriteLine ("\tMonoBundledAssembly assembly;");
723 tc.WriteLine ("\tint compressed_size;");
724 tc.WriteLine ("} CompressedAssembly;\n");
727 object monitor = new object ();
729 var streams = new Dictionary<string, Stream> ();
730 var sizes = new Dictionary<string, long> ();
732 // Do the file reading and compression in parallel
733 Action<string> body = delegate (string url) {
734 string fname = LocateFile (new Uri (url).LocalPath);
735 Stream stream = File.OpenRead (fname);
737 long real_size = stream.Length;
740 byte[] cbuffer = new byte [8192];
741 MemoryStream ms = new MemoryStream ();
742 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
743 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
744 deflate.Write (cbuffer, 0, n);
748 byte [] bytes = ms.GetBuffer ();
749 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
753 streams [url] = stream;
754 sizes [url] = real_size;
760 Parallel.ForEach (files, body);
762 foreach (var url in files)
766 // The non-parallel part
767 byte [] buffer = new byte [8192];
768 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
769 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
770 foreach (var url in files) {
771 string fname = LocateFile (new Uri (url).LocalPath);
772 string aname = MakeBundle.GetAssemblyName (fname);
773 string encoded = symbolEscapeRE.Replace (aname, "_");
778 var stream = streams [url];
779 var real_size = sizes [url];
782 Console.WriteLine (" embedding: " + fname);
784 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
786 WriteBuffer (ts, stream, buffer);
789 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
790 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
791 " assembly_data_{0}, {2}}}, {3}}};",
792 encoded, aname, real_size, stream.Length);
794 double ratio = ((double) stream.Length * 100) / real_size;
795 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
798 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
799 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
800 encoded, aname, real_size);
804 c_bundle_names.Add ("assembly_bundle_" + encoded);
807 FileStream cf = File.OpenRead (fname + ".config");
809 Console.WriteLine (" config from: " + fname + ".config");
810 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
811 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
812 WriteBuffer (ts, cf, buffer);
814 config_names.Add (new string[] {aname, encoded});
815 } catch (FileNotFoundException) {
816 /* we ignore if the config file doesn't exist */
820 if (config_file != null){
823 conf = File.OpenRead (config_file);
825 Error ("Failure to open {0}", config_file);
829 Console.WriteLine ("System config from: " + config_file);
830 tc.WriteLine ("extern const char system_config;");
831 WriteSymbol (ts, "system_config", config_file.Length);
833 WriteBuffer (ts, conf, buffer);
835 ts.Write ("\t.byte 0\n");
839 if (machine_config_file != null){
842 conf = File.OpenRead (machine_config_file);
844 Error ("Failure to open {0}", machine_config_file);
848 Console.WriteLine ("Machine config from: " + machine_config_file);
849 tc.WriteLine ("extern const char machine_config;");
850 WriteSymbol (ts, "machine_config", machine_config_file.Length);
852 WriteBuffer (ts, conf, buffer);
853 ts.Write ("\t.byte 0\n");
859 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
861 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
863 foreach (string c in c_bundle_names){
864 tc.WriteLine ("\t&{0},", c);
866 tc.WriteLine ("\tNULL\n};\n");
867 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
869 if (ctor_func != null) {
870 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
871 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
872 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
875 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
876 foreach (string[] ass in config_names){
877 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
879 if (config_file != null)
880 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
881 if (machine_config_file != null)
882 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
883 tc.WriteLine ("}\n");
885 if (config_dir != null)
886 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
888 tc.WriteLine ("static const char *config_dir = NULL;");
890 Stream template_stream;
892 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
894 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
897 StreamReader s = new StreamReader (template_stream);
898 string template = s.ReadToEnd ();
901 if (!nomain && custom_main == null) {
902 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
903 StreamReader st = new StreamReader (template_main_stream);
904 string maintemplate = st.ReadToEnd ();
905 tc.Write (maintemplate);
910 string assembler = GetEnv("AS", "as");
911 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
918 Console.WriteLine("Compiling:");
920 if (style == "windows")
923 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
925 string compiler = GetEnv("CC", "cl.exe");
926 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
927 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
928 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
930 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
931 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
932 var linkLibraries = new string[] { "kernel32.lib",
947 string glue_obj = "mkbundle_glue.obj";
951 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
954 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
955 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
956 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
959 var compilerArgs = new List<string>();
960 compilerArgs.Add("/MT");
962 foreach (string include in includes)
963 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
965 if (!nomain || custom_main != null) {
966 compilerArgs.Add(quote(temp_c));
967 compilerArgs.Add(quote(temp_o));
968 if (custom_main != null)
969 compilerArgs.Add(quote(custom_main));
970 compilerArgs.Add(quote(monoLib));
971 compilerArgs.Add("/link");
972 compilerArgs.Add("/NODEFAULTLIB");
973 compilerArgs.Add("/SUBSYSTEM:windows");
974 compilerArgs.Add("/ENTRY:mainCRTStartup");
975 compilerArgs.AddRange(linkLibraries);
976 compilerArgs.Add("/out:"+ output);
978 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
983 // we are just creating a .lib
984 compilerArgs.Add("/c"); // compile only
985 compilerArgs.Add(temp_c);
986 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
988 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
991 string librarian = GetEnv ("LIB", "lib.exe");
992 var librarianArgs = new List<string> ();
993 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
994 librarianArgs.Add (temp_o);
995 librarianArgs.Add (glue_obj);
996 librarianArgs.Add (monoLib);
997 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1003 string zlib = (compress ? "-lz" : "");
1004 string debugging = "-g";
1005 string cc = GetEnv("CC", "cc");
1008 if (style == "linux")
1009 debugging = "-ggdb";
1014 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1016 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1017 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
1018 "`pkg-config --libs-only-L mono-2` " + smonolib +
1019 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
1020 temp_c, temp_o, output, zlib, cc);
1025 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1026 temp_c, temp_o, output, zlib, cc);
1032 Console.WriteLine ("Done");
1037 if (object_out == null){
1038 File.Delete (temp_o);
1041 File.Delete (temp_c);
1043 File.Delete (temp_s);
1048 static List<string> LoadAssemblies (List<string> sources)
1050 List<string> assemblies = new List<string> ();
1053 foreach (string name in sources){
1055 Assembly a = LoadAssemblyFile (name);
1062 assemblies.Add (a.CodeBase);
1063 } catch (Exception) {
1066 Console.WriteLine ("File will not be scanned: {0}", name);
1067 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1075 Error ("Couldn't load one or more of the assemblies.");
1076 Environment.Exit (1);
1082 static void LoadLocalizedAssemblies (List<string> assemblies)
1084 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1087 foreach (string name in other) {
1089 Assembly a = LoadAssembly (name);
1096 assemblies.Add (a.CodeBase);
1097 } catch (Exception) {
1100 Console.WriteLine ("File will not be scanned: {0}", name);
1101 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1109 Error ("Couldn't load one or more of the i18n assemblies.");
1110 Environment.Exit (1);
1115 static readonly Universe universe = new Universe ();
1116 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1118 public static string GetAssemblyName (string path)
1120 string name = Path.GetFileName (path);
1122 // A bit of a hack to support satellite assemblies. They all share the same name but
1123 // are placed in subdirectories named after the locale they implement. Also, all of
1124 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1125 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1126 string dir = Path.GetDirectoryName (path);
1127 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1129 name = dir.Substring (idx + 1) + Path.DirectorySeparatorChar + name;
1130 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1132 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1138 static bool QueueAssembly (List<string> files, string codebase)
1140 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1141 if (files.Contains (codebase))
1144 var path = new Uri(codebase).LocalPath;
1145 var name = GetAssemblyName (path);
1147 if (loaded_assemblies.TryGetValue (name, out found)) {
1148 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1152 loaded_assemblies.Add (name, path);
1154 files.Add (codebase);
1158 Assembly a = universe.LoadFile (path);
1160 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1161 LoadAssembly (an.FullName);
1162 if (!QueueAssembly (files, a.CodeBase))
1165 } catch (Exception) {
1174 // Loads an assembly from a specific path
1176 static Assembly LoadAssemblyFile (string assembly)
1181 a = universe.LoadFile (assembly);
1182 } catch (FileNotFoundException){
1183 Error ($"Cannot find assembly `{assembly}'");
1184 } catch (IKVM.Reflection.BadImageFormatException f) {
1187 Error ($"Cannot load assembly (bad file format) " + f.Message);
1188 } catch (FileLoadException f){
1189 Error ($"Cannot load assembly " + f.Message);
1190 } catch (ArgumentNullException){
1191 Error( $"Cannot load assembly (null argument)");
1197 // Loads an assembly from any of the link directories provided
1199 static Assembly LoadAssembly (string assembly)
1201 string total_log = "";
1202 foreach (string dir in link_paths){
1203 string full_path = Path.Combine (dir, assembly);
1204 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1205 full_path += ".dll";
1208 var a = universe.LoadFile (full_path);
1210 } catch (FileNotFoundException ff) {
1211 total_log += ff.FusionLog;
1216 Console.WriteLine ("Log: \n" + total_log);
1220 static void Error (string msg, params object [] args)
1222 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1223 throw new Exception ();
1224 Environment.Exit (1);
1229 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1231 " --config F Bundle system config file `F'\n" +
1232 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1233 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1234 " -L path Adds `path' to the search path for assemblies\n" +
1235 " --machine-config F Use the given file as the machine.config for the application.\n" +
1236 " -o out Specifies output filename\n" +
1237 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1238 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1239 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1240 " -v Verbose output\n" +
1242 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1243 " --cross TARGET Generates a binary for the given TARGET\n"+
1244 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1245 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1246 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1247 " LIB is optional shortname for file located at PATH\n" +
1248 " --list-targets Lists available targets on the remote server\n" +
1249 " --local-targets Lists locally available targets\n" +
1250 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1251 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1252 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1253 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1255 "--custom Builds a custom launcher, options for --custom\n" +
1256 " -c Produce stub only, do not compile\n" +
1257 " -oo obj Specifies output filename for helper object file\n" +
1258 " --dos2unix[=true|false]\n" +
1259 " When no value provided, or when `true` specified\n" +
1260 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1261 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1262 " --keeptemp Keeps the temporary files\n" +
1263 " --static Statically link to mono libs\n" +
1264 " --nomain Don't include a main() function, for libraries\n" +
1265 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1266 " -z Compress the assemblies before embedding.\n" +
1267 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1268 " You need zlib development headers and libraries.\n");
1271 [DllImport ("libc")]
1272 static extern int system (string s);
1273 [DllImport ("libc")]
1274 static extern int uname (IntPtr buf);
1276 static void DetectOS ()
1279 os_message = "OS is: Windows";
1284 IntPtr buf = Marshal.AllocHGlobal (8192);
1285 if (uname (buf) != 0){
1286 os_message = "Warning: Unable to detect OS";
1287 Marshal.FreeHGlobal (buf);
1290 string os = Marshal.PtrToStringAnsi (buf);
1291 os_message = "OS is: " + os;
1295 Marshal.FreeHGlobal (buf);
1298 static bool IsUnix {
1300 int p = (int) Environment.OSVersion.Platform;
1301 return ((p == 4) || (p == 128) || (p == 6));
1305 static void Execute (string cmdLine)
1309 Console.WriteLine ("[execute cmd]: " + cmdLine);
1310 int ret = system (cmdLine);
1313 Error(String.Format("[Fail] {0}", ret));
1318 // on Windows, we have to pipe the output of a
1319 // `cmd` interpolation to dos2unix, because the shell does not
1320 // strip the CRLFs generated by the native pkg-config distributed
1323 // But if it's *not* on cygwin, just skip it.
1325 // check if dos2unix is applicable.
1326 if (use_dos2unix == true)
1328 var info = new ProcessStartInfo ("dos2unix");
1329 info.CreateNoWindow = true;
1330 info.RedirectStandardInput = true;
1331 info.UseShellExecute = false;
1332 var dos2unix = Process.Start (info);
1333 dos2unix.StandardInput.WriteLine ("aaa");
1334 dos2unix.StandardInput.WriteLine ("\u0004");
1335 dos2unix.StandardInput.Close ();
1336 dos2unix.WaitForExit ();
1337 if (dos2unix.ExitCode == 0)
1338 use_dos2unix = true;
1340 Console.WriteLine("Warning: dos2unix not found");
1341 use_dos2unix = false;
1344 if (use_dos2unix == null)
1345 use_dos2unix = false;
1347 ProcessStartInfo psi = new ProcessStartInfo();
1348 psi.UseShellExecute = false;
1350 // if there is no dos2unix, just run cmd /c.
1351 if (use_dos2unix == false)
1353 psi.FileName = "cmd";
1354 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1358 psi.FileName = "sh";
1359 StringBuilder b = new StringBuilder();
1361 for (int i = 0; i < cmdLine.Length; i++)
1363 if (cmdLine[i] == '`')
1367 b.Append("|dos2unix");
1371 b.Append(cmdLine[i]);
1373 cmdLine = b.ToString();
1374 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1378 Console.WriteLine(cmdLine);
1379 using (Process p = Process.Start (psi)) {
1381 int ret = p.ExitCode;
1383 Error ("[Fail] {0}", ret);
1388 static string GetEnv(string name, string defaultValue)
1390 string val = Environment.GetEnvironmentVariable(name);
1394 Console.WriteLine("{0} = {1}", name, val);
1400 Console.WriteLine("{0} = {1} (default)", name, val);
1405 static string LocateFile(string default_path)
1407 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1408 if (File.Exists(override_path))
1409 return override_path;
1410 else if (File.Exists(default_path))
1411 return default_path;
1413 throw new FileNotFoundException(default_path);