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 only 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 only 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);
627 // add a space after code (="systemconfig:" or "machineconfig:")
628 Console.WriteLine (code + " " + file);
632 static bool GeneratePackage (List<string> files)
634 if (runtime == null){
636 runtime = Process.GetCurrentProcess().MainModule.FileName;
638 Error ("You must specify at least one runtime with --runtime or --cross");
639 Environment.Exit (1);
642 if (!File.Exists (runtime)){
643 Error ($"The specified runtime at {runtime} does not exist");
644 Environment.Exit (1);
647 if (ctor_func != null){
648 Error ("--static-ctor not supported with package bundling, you must use native compilation for this");
652 var maker = new PackageMaker (output);
653 Console.WriteLine ("Using runtime: " + runtime);
654 maker.AddFile (runtime);
656 foreach (var url in files){
657 string fname = LocateFile (new Uri (url).LocalPath);
658 string aname = MakeBundle.GetAssemblyName (fname);
660 maker.Add ("assembly:" + aname, fname);
661 Console.WriteLine (" Assembly: " + fname);
662 if (File.Exists (fname + ".config")){
663 maker.Add ("config:" + aname, fname + ".config");
664 Console.WriteLine (" Config: " + fname + ".config");
668 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
671 if (config_dir != null){
672 maker.Add ("config_dir:", config_dir);
673 Console.WriteLine (" Config_dir: " + config_dir );
675 if (embedded_options != null)
676 maker.AddString ("options:", embedded_options);
677 if (environment.Count > 0){
678 foreach (var key in environment.Keys)
679 maker.AddStringPair ("env:" + key, key, environment [key]);
681 if (libraries.Count > 0){
682 foreach (var alias_and_path in libraries){
683 Console.WriteLine (" Library: " + alias_and_path.Value);
684 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
692 static void GenerateBundles (List<string> files)
694 string temp_s = "temp.s"; // Path.GetTempFileName ();
695 string temp_c = "temp.c";
696 string temp_o = "temp.o";
700 if (object_out != null)
704 List<string> c_bundle_names = new List<string> ();
705 List<string[]> config_names = new List<string[]> ();
707 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
708 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
711 if (bundled_header) {
712 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
713 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
717 const unsigned char *data;
718 const unsigned int size;
719 } MonoBundledAssembly;
720 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
721 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
724 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
725 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
729 tc.WriteLine ("typedef struct _compressed_data {");
730 tc.WriteLine ("\tMonoBundledAssembly assembly;");
731 tc.WriteLine ("\tint compressed_size;");
732 tc.WriteLine ("} CompressedAssembly;\n");
735 object monitor = new object ();
737 var streams = new Dictionary<string, Stream> ();
738 var sizes = new Dictionary<string, long> ();
740 // Do the file reading and compression in parallel
741 Action<string> body = delegate (string url) {
742 string fname = LocateFile (new Uri (url).LocalPath);
743 Stream stream = File.OpenRead (fname);
745 long real_size = stream.Length;
748 byte[] cbuffer = new byte [8192];
749 MemoryStream ms = new MemoryStream ();
750 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
751 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
752 deflate.Write (cbuffer, 0, n);
756 byte [] bytes = ms.GetBuffer ();
757 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
761 streams [url] = stream;
762 sizes [url] = real_size;
768 Parallel.ForEach (files, body);
770 foreach (var url in files)
774 // The non-parallel part
775 byte [] buffer = new byte [8192];
776 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
777 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
778 foreach (var url in files) {
779 string fname = LocateFile (new Uri (url).LocalPath);
780 string aname = MakeBundle.GetAssemblyName (fname);
781 string encoded = symbolEscapeRE.Replace (aname, "_");
786 var stream = streams [url];
787 var real_size = sizes [url];
790 Console.WriteLine (" embedding: " + fname);
792 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
794 WriteBuffer (ts, stream, buffer);
797 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
798 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
799 " assembly_data_{0}, {2}}}, {3}}};",
800 encoded, aname, real_size, stream.Length);
802 double ratio = ((double) stream.Length * 100) / real_size;
803 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
806 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
807 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
808 encoded, aname, real_size);
812 c_bundle_names.Add ("assembly_bundle_" + encoded);
815 FileStream cf = File.OpenRead (fname + ".config");
817 Console.WriteLine (" config from: " + fname + ".config");
818 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
819 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
820 WriteBuffer (ts, cf, buffer);
822 config_names.Add (new string[] {aname, encoded});
823 } catch (FileNotFoundException) {
824 /* we ignore if the config file doesn't exist */
828 if (config_file != null){
831 conf = File.OpenRead (config_file);
833 Error ("Failure to open {0}", config_file);
837 Console.WriteLine ("System config from: " + config_file);
838 tc.WriteLine ("extern const char system_config;");
839 WriteSymbol (ts, "system_config", config_file.Length);
841 WriteBuffer (ts, conf, buffer);
843 ts.Write ("\t.byte 0\n");
847 if (machine_config_file != null){
850 conf = File.OpenRead (machine_config_file);
852 Error ("Failure to open {0}", machine_config_file);
856 Console.WriteLine ("Machine config from: " + machine_config_file);
857 tc.WriteLine ("extern const char machine_config;");
858 WriteSymbol (ts, "machine_config", machine_config_file.Length);
860 WriteBuffer (ts, conf, buffer);
861 ts.Write ("\t.byte 0\n");
867 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
869 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
871 foreach (string c in c_bundle_names){
872 tc.WriteLine ("\t&{0},", c);
874 tc.WriteLine ("\tNULL\n};\n");
875 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
877 if (ctor_func != null) {
878 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
879 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
880 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
883 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
884 foreach (string[] ass in config_names){
885 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
887 if (config_file != null)
888 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
889 if (machine_config_file != null)
890 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
891 tc.WriteLine ("}\n");
893 if (config_dir != null)
894 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
896 tc.WriteLine ("static const char *config_dir = NULL;");
898 Stream template_stream;
900 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
902 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
905 StreamReader s = new StreamReader (template_stream);
906 string template = s.ReadToEnd ();
909 if (!nomain && custom_main == null) {
910 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
911 StreamReader st = new StreamReader (template_main_stream);
912 string maintemplate = st.ReadToEnd ();
913 tc.Write (maintemplate);
918 string assembler = GetEnv("AS", "as");
919 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
926 Console.WriteLine("Compiling:");
928 if (style == "windows")
931 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
933 string compiler = GetEnv("CC", "cl.exe");
934 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
935 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
936 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
938 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
939 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
940 var linkLibraries = new string[] { "kernel32.lib",
955 string glue_obj = "mkbundle_glue.obj";
959 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
962 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
963 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
964 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
967 var compilerArgs = new List<string>();
968 compilerArgs.Add("/MT");
970 foreach (string include in includes)
971 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
973 if (!nomain || custom_main != null) {
974 compilerArgs.Add(quote(temp_c));
975 compilerArgs.Add(quote(temp_o));
976 if (custom_main != null)
977 compilerArgs.Add(quote(custom_main));
978 compilerArgs.Add(quote(monoLib));
979 compilerArgs.Add("/link");
980 compilerArgs.Add("/NODEFAULTLIB");
981 compilerArgs.Add("/SUBSYSTEM:windows");
982 compilerArgs.Add("/ENTRY:mainCRTStartup");
983 compilerArgs.AddRange(linkLibraries);
984 compilerArgs.Add("/out:"+ output);
986 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
991 // we are just creating a .lib
992 compilerArgs.Add("/c"); // compile only
993 compilerArgs.Add(temp_c);
994 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
996 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
999 string librarian = GetEnv ("LIB", "lib.exe");
1000 var librarianArgs = new List<string> ();
1001 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
1002 librarianArgs.Add (temp_o);
1003 librarianArgs.Add (glue_obj);
1004 librarianArgs.Add (monoLib);
1005 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
1011 string zlib = (compress ? "-lz" : "");
1012 string debugging = "-g";
1013 string cc = GetEnv("CC", "cc");
1016 if (style == "linux")
1017 debugging = "-ggdb";
1022 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
1024 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
1025 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
1026 "`pkg-config --libs-only-L mono-2` " + smonolib +
1027 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
1028 temp_c, temp_o, output, zlib, cc);
1033 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
1034 temp_c, temp_o, output, zlib, cc);
1040 Console.WriteLine ("Done");
1045 if (object_out == null){
1046 File.Delete (temp_o);
1049 File.Delete (temp_c);
1051 File.Delete (temp_s);
1056 static List<string> LoadAssemblies (List<string> sources)
1058 List<string> assemblies = new List<string> ();
1061 foreach (string name in sources){
1063 Assembly a = LoadAssemblyFile (name);
1070 assemblies.Add (a.CodeBase);
1071 } catch (Exception) {
1074 Console.WriteLine ("File will not be scanned: {0}", name);
1075 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1083 Error ("Couldn't load one or more of the assemblies.");
1084 Environment.Exit (1);
1090 static void LoadLocalizedAssemblies (List<string> assemblies)
1092 var other = i18n.Select (x => "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1093 string error = null;
1095 foreach (string name in other) {
1097 Assembly a = LoadAssembly (name);
1100 error = "Failed to load " + name;
1104 assemblies.Add (a.CodeBase);
1105 } catch (Exception) {
1108 Console.WriteLine ("File will not be scanned: {0}", name);
1109 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1116 if (error != null) {
1117 Console.Error.WriteLine ("Failure to load i18n assemblies, the following directories were searched for the assemblies:");
1118 foreach (var path in link_paths){
1119 Console.Error.WriteLine (" Path: " + path);
1122 Console.WriteLine ("In Custom mode, you need to provide the directory to lookup assemblies from using -L");
1125 Error ("Couldn't load one or more of the i18n assemblies: " + error);
1126 Environment.Exit (1);
1131 static readonly Universe universe = new Universe ();
1132 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1134 public static string GetAssemblyName (string path)
1136 string resourcePathSeparator = style == "windows" ? "\\\\" : "/";
1137 string name = Path.GetFileName (path);
1139 // A bit of a hack to support satellite assemblies. They all share the same name but
1140 // are placed in subdirectories named after the locale they implement. Also, all of
1141 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1142 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1143 string dir = Path.GetDirectoryName (path);
1144 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1146 name = dir.Substring (idx + 1) + resourcePathSeparator + name;
1147 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1149 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1155 static bool QueueAssembly (List<string> files, string codebase)
1157 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1158 if (files.Contains (codebase))
1161 var path = new Uri(codebase).LocalPath;
1162 var name = GetAssemblyName (path);
1164 if (loaded_assemblies.TryGetValue (name, out found)) {
1165 Error ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found);
1169 loaded_assemblies.Add (name, path);
1171 files.Add (codebase);
1175 Assembly a = universe.LoadFile (path);
1177 Error ("Unable to to load assembly `{0}'", path);
1181 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1182 a = LoadAssembly (an.Name);
1184 Error ("Unable to load assembly `{0}' referenced by `{1}'", an.Name, path);
1188 if (!QueueAssembly (files, a.CodeBase))
1191 } catch (Exception) {
1200 // Loads an assembly from a specific path
1202 static Assembly LoadAssemblyFile (string assembly)
1208 Console.WriteLine ("Attempting to load assembly: {0}", assembly);
1209 a = universe.LoadFile (assembly);
1211 Console.WriteLine ("Assembly {0} loaded successfully.", assembly);
1213 } catch (FileNotFoundException){
1214 Error ($"Cannot find assembly `{assembly}'");
1215 } catch (IKVM.Reflection.BadImageFormatException f) {
1218 Error ($"Cannot load assembly (bad file format) " + f.Message);
1219 } catch (FileLoadException f){
1220 Error ($"Cannot load assembly " + f.Message);
1221 } catch (ArgumentNullException){
1222 Error( $"Cannot load assembly (null argument)");
1228 // Loads an assembly from any of the link directories provided
1230 static Assembly LoadAssembly (string assembly)
1232 string total_log = "";
1233 foreach (string dir in link_paths){
1234 string full_path = Path.Combine (dir, assembly);
1236 Console.WriteLine ("Attempting to load assembly from: " + full_path);
1237 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1238 full_path += ".dll";
1241 var a = universe.LoadFile (full_path);
1243 } catch (FileNotFoundException ff) {
1244 total_log += ff.FusionLog;
1249 Console.WriteLine ("Log: \n" + total_log);
1253 static void Error (string msg, params object [] args)
1255 Console.Error.WriteLine ("ERROR: {0}", string.Format (msg, args));
1256 Environment.Exit (1);
1261 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1263 " --config F Bundle system config file `F'\n" +
1264 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1265 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1266 " -L path Adds `path' to the search path for assemblies\n" +
1267 " --machine-config F Use the given file as the machine.config for the application.\n" +
1268 " -o out Specifies output filename\n" +
1269 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1270 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1271 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1272 " -v Verbose output\n" +
1273 " --bundled-header Do not attempt to include 'mono-config.h'. Define the entry points directly in the generated code\n" +
1275 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1276 " --cross TARGET Generates a binary for the given TARGET\n"+
1277 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1278 " --fetch-target NAME Downloads the target SDK from the remote server\n" +
1279 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1280 " LIB is optional shortname for file located at PATH\n" +
1281 " --list-targets Lists available targets on the remote server\n" +
1282 " --local-targets Lists locally available targets\n" +
1283 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1284 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1285 " --sdk PATH Use a Mono SDK root location instead of a target\n" +
1286 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1288 "--custom Builds a custom launcher, options for --custom\n" +
1289 " -c Produce stub only, do not compile\n" +
1290 " -oo obj Specifies output filename for helper object file\n" +
1291 " --dos2unix[=true|false]\n" +
1292 " When no value provided, or when `true` specified\n" +
1293 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1294 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1295 " --keeptemp Keeps the temporary files\n" +
1296 " --static Statically link to mono libs\n" +
1297 " --nomain Don't include a main() function, for libraries\n" +
1298 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1299 " -z Compress the assemblies before embedding.\n" +
1300 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1301 " You need zlib development headers and libraries.\n");
1304 [DllImport ("libc")]
1305 static extern int system (string s);
1306 [DllImport ("libc")]
1307 static extern int uname (IntPtr buf);
1309 static void DetectOS ()
1312 os_message = "OS is: Windows";
1317 IntPtr buf = Marshal.AllocHGlobal (8192);
1318 if (uname (buf) != 0){
1319 os_message = "Warning: Unable to detect OS";
1320 Marshal.FreeHGlobal (buf);
1323 string os = Marshal.PtrToStringAnsi (buf);
1324 os_message = "OS is: " + os;
1328 Marshal.FreeHGlobal (buf);
1331 static bool IsUnix {
1333 int p = (int) Environment.OSVersion.Platform;
1334 return ((p == 4) || (p == 128) || (p == 6));
1338 static void Execute (string cmdLine)
1342 Console.WriteLine ("[execute cmd]: " + cmdLine);
1343 int ret = system (cmdLine);
1346 Error(String.Format("[Fail] {0}", ret));
1351 // on Windows, we have to pipe the output of a
1352 // `cmd` interpolation to dos2unix, because the shell does not
1353 // strip the CRLFs generated by the native pkg-config distributed
1356 // But if it's *not* on cygwin, just skip it.
1358 // check if dos2unix is applicable.
1359 if (use_dos2unix == true)
1361 var info = new ProcessStartInfo ("dos2unix");
1362 info.CreateNoWindow = true;
1363 info.RedirectStandardInput = true;
1364 info.UseShellExecute = false;
1365 var dos2unix = Process.Start (info);
1366 dos2unix.StandardInput.WriteLine ("aaa");
1367 dos2unix.StandardInput.WriteLine ("\u0004");
1368 dos2unix.StandardInput.Close ();
1369 dos2unix.WaitForExit ();
1370 if (dos2unix.ExitCode == 0)
1371 use_dos2unix = true;
1373 Console.WriteLine("Warning: dos2unix not found");
1374 use_dos2unix = false;
1377 if (use_dos2unix == null)
1378 use_dos2unix = false;
1380 ProcessStartInfo psi = new ProcessStartInfo();
1381 psi.UseShellExecute = false;
1383 // if there is no dos2unix, just run cmd /c.
1384 if (use_dos2unix == false)
1386 psi.FileName = "cmd";
1387 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1391 psi.FileName = "sh";
1392 StringBuilder b = new StringBuilder();
1394 for (int i = 0; i < cmdLine.Length; i++)
1396 if (cmdLine[i] == '`')
1400 b.Append("|dos2unix");
1404 b.Append(cmdLine[i]);
1406 cmdLine = b.ToString();
1407 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1411 Console.WriteLine(cmdLine);
1412 using (Process p = Process.Start (psi)) {
1414 int ret = p.ExitCode;
1416 Error ("[Fail] {0}", ret);
1421 static string GetEnv(string name, string defaultValue)
1423 string val = Environment.GetEnvironmentVariable(name);
1427 Console.WriteLine("{0} = {1}", name, val);
1433 Console.WriteLine("{0} = {1} (default)", name, val);
1438 static string LocateFile(string default_path)
1440 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1441 if (File.Exists(override_path))
1442 return override_path;
1443 else if (File.Exists(default_path))
1444 return default_path;
1446 throw new FileNotFoundException(default_path);