2 // mkbundle: tool to create bundles.
4 // Based on the `make-bundle' Perl script written by Paolo Molaro (lupus@debian.org)
9 // (C) Novell, Inc 2004
10 // (C) 2016 Xamarin Inc
13 // * Add support for packaging native libraries, extracting at runtime and setting the library path.
14 // * Implement --list-targets lists all the available remote targets
17 using System.Diagnostics;
19 using System.Collections.Generic;
21 using System.IO.Compression;
22 using System.Runtime.InteropServices;
24 using IKVM.Reflection;
27 using System.Threading.Tasks;
30 static string output = "a.out";
31 static string object_out = null;
32 static List<string> link_paths = new List<string> ();
33 static Dictionary<string,string> libraries = new Dictionary<string,string> ();
34 static bool autodeps = false;
35 static bool keeptemp = false;
36 static bool compile_only = false;
37 static bool static_link = false;
38 static string config_file = null;
39 static string machine_config_file = null;
40 static string config_dir = null;
41 static string style = "linux";
42 static string os_message = "";
45 static string custom_main = null;
46 static bool? use_dos2unix = null;
47 static bool skip_scan;
48 static string ctor_func;
49 static bool quiet = true;
50 static string cross_target = null;
51 static string fetch_target = null;
52 static bool custom_mode = true;
53 static string embedded_options = null;
54 static string runtime = null;
55 static Dictionary<string,string> environment = new Dictionary<string,string>();
56 static string [] i18n = new string [] {
60 static string [] i18n_all = new string [] {
68 static string target_server = "https://download.mono-project.com/runtimes/raw/";
70 static int Main (string [] args)
72 List<string> sources = new List<string> ();
73 int top = args.Length;
78 for (int i = 0; i < top; i++){
80 case "--help": case "-h": case "-?":
98 var iarg = args [++i];
101 else if (iarg == "none")
102 i18n = new string [0];
104 i18n = iarg.Split (',');
115 case "--local-targets":
116 CommandLocalTargets ();
126 cross_target = args [++i];
135 Console.Error.WriteLine ("--library can only be used with --simple/--runtime/--cross mode");
139 var lspec = args [++i];
140 var p = lspec.IndexOf (",");
143 alias = Path.GetFileName (lspec);
146 alias = lspec.Substring (0, p);
147 path = lspec.Substring (p+1);
149 if (!File.Exists (path)){
150 Console.Error.WriteLine ($"The specified library file {path} does not exist");
153 libraries [alias] = path;
156 case "--fetch-target":
161 fetch_target = args [++i];
164 case "--list-targets":
165 var wc = new WebClient ();
166 var s = wc.DownloadString (new Uri (target_server + "target-list.txt"));
167 Console.WriteLine ("Cross-compilation targets available:\n" + s);
171 case "--target-server":
176 target_server = args [++i];
192 embedded_options = args [++i];
201 runtime = args [++i];
208 object_out = args [++i];
216 link_paths.Add (args [++i]);
240 config_file = args [++i];
242 case "--machine-config":
248 machine_config_file = args [++i];
251 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
259 config_dir = args [++i];
267 case "--custom-main":
272 custom_main = args [++i];
286 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
294 case "--static-ctor":
299 ctor_func = args [++i];
302 case "--dos2unix=true":
305 case "--dos2unix=false":
306 use_dos2unix = false;
318 var env = args [++i];
319 p = env.IndexOf ('=');
321 environment.Add (env, "");
323 environment.Add (env.Substring (0, p), env.Substring (p+1));
326 sources.Add (args [i]);
332 if (fetch_target != null){
333 var truntime = Path.Combine (targets_dir, fetch_target, "mono");
334 Directory.CreateDirectory (Path.GetDirectoryName (truntime));
335 var wc = new WebClient ();
336 var uri = new Uri ($"{target_server}{fetch_target}");
339 Console.WriteLine ($"Downloading runtime {uri} to {truntime}");
342 wc.DownloadFile (uri, truntime);
344 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
345 File.Delete (truntime);
352 Console.WriteLine (os_message);
353 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
356 if (sources.Count == 0 || output == null) {
358 Environment.Exit (1);
361 List<string> assemblies = LoadAssemblies (sources);
362 List<string> files = new List<string> ();
363 foreach (string file in assemblies)
364 if (!QueueAssembly (files, file))
367 GenerateBundles (files);
369 if (cross_target == "default")
372 if (runtime == null){
373 if (cross_target == null){
374 Console.Error.WriteLine ("you should specify either a --runtime or a --cross compilation target");
375 Environment.Exit (1);
377 runtime = Path.Combine (targets_dir, cross_target, "mono");
378 if (!File.Exists (runtime)){
379 Console.Error.WriteLine ($"The runtime for the {cross_target} does not exist, use --fetch-target {cross_target} to download first");
383 if (!File.Exists (runtime)){
384 Console.Error.WriteLine ($"The Mono runtime specified with --runtime does not exist");
389 Console.WriteLine ("Using runtime {0} for {1}", runtime, output);
391 GeneratePackage (files);
397 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
399 static void CommandLocalTargets ()
403 Console.WriteLine ("Available targets:");
404 Console.WriteLine ("\tdefault\t- Current System Mono");
406 targets = Directory.GetDirectories (targets_dir);
410 foreach (var target in targets){
411 var p = Path.Combine (target, "mono");
413 Console.WriteLine ("\t{0}", Path.GetFileName (target));
417 static void WriteSymbol (StreamWriter sw, string name, long size)
423 "\t.section .rodata\n" +
425 "\t.type {0}, \"object\"\n" +
426 "\t.size {0}, {1}\n" +
432 "\t.section __TEXT,__text,regular,pure_instructions\n" +
442 "\t.section .rdata,\"dr\"\n" +
450 static string [] chars = new string [256];
452 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
456 // Preallocate the strings we need.
457 if (chars [0] == null) {
458 for (int i = 0; i < chars.Length; i++)
459 chars [i] = string.Format ("{0}", i.ToString ());
462 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
464 for (int i = 0; i < n; i++) {
465 if (count % 32 == 0) {
466 ts.Write ("\n\t.byte ");
470 ts.Write (chars [buffer [i]]);
479 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
480 const int align = 4096;
483 public PackageMaker (string output)
485 package = File.Create (output, 128*1024);
487 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
491 public int AddFile (string fname)
493 using (Stream fileStream = File.OpenRead (fname)){
494 var ret = fileStream.Length;
497 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
498 fileStream.CopyTo (package);
499 package.Position = package.Position + (align - (package.Position % align));
505 public void Add (string entry, string fname)
507 var p = package.Position;
508 var size = AddFile (fname);
510 locations [entry] = Tuple.Create(p, size);
513 public void AddString (string entry, string text)
515 var bytes = Encoding.UTF8.GetBytes (text);
516 locations [entry] = Tuple.Create (package.Position, bytes.Length);
517 package.Write (bytes, 0, bytes.Length);
518 package.Position = package.Position + (align - (package.Position % align));
521 public void AddStringPair (string entry, string key, string value)
523 var kbytes = Encoding.UTF8.GetBytes (key);
524 var vbytes = Encoding.UTF8.GetBytes (value);
526 Console.WriteLine ("ADDING {0} to {1}", key, value);
527 if (kbytes.Length > 255){
528 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
529 Environment.Exit (1);
532 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
533 package.WriteByte ((byte)kbytes.Length);
534 package.Write (kbytes, 0, kbytes.Length);
535 package.WriteByte (0);
536 package.Write (vbytes, 0, vbytes.Length);
537 package.WriteByte (0);
538 package.Position = package.Position + (align - (package.Position % align));
545 foreach (var floc in locations.Keys){
546 Console.WriteLine ($"{floc} at {locations[floc]:x}");
550 public void WriteIndex ()
552 var indexStart = package.Position;
553 var binary = new BinaryWriter (package);
555 binary.Write (locations.Count);
556 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
557 var bytes = Encoding.UTF8.GetBytes (entry.Key);
558 binary.Write (bytes.Length+1);
559 binary.Write (bytes);
560 binary.Write ((byte) 0);
561 binary.Write (entry.Value.Item1);
562 binary.Write (entry.Value.Item2);
564 binary.Write (indexStart);
565 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
577 static bool MaybeAddFile (PackageMaker maker, string code, string file)
582 if (!File.Exists (file)){
583 Console.Error.WriteLine ("The file {0} does not exist", file);
586 maker.Add (code, file);
590 static bool GeneratePackage (List<string> files)
592 if (runtime == null){
594 runtime = Process.GetCurrentProcess().MainModule.FileName;
596 Console.Error.WriteLine ("You must specify at least one runtime with --runtime or --cross");
597 Environment.Exit (1);
600 if (!File.Exists (runtime)){
601 Console.Error.WriteLine ($"The specified runtime at {runtime} does not exist");
602 Environment.Exit (1);
605 if (ctor_func != null){
606 Console.Error.WriteLine ("--static-ctor not supported with package bundling, you must use native compilation for this");
610 var maker = new PackageMaker (output);
611 maker.AddFile (runtime);
613 foreach (var url in files){
614 string fname = LocateFile (new Uri (url).LocalPath);
615 string aname = MakeBundle.GetAssemblyName (fname);
617 maker.Add ("assembly:" + aname, fname);
618 if (File.Exists (fname + ".config"))
619 maker.Add ("config:" + aname, fname + ".config");
621 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
624 if (config_dir != null)
625 maker.Add ("config_dir:", config_dir);
626 if (embedded_options != null)
627 maker.AddString ("options:", embedded_options);
628 if (environment.Count > 0){
629 foreach (var key in environment.Keys)
630 maker.AddStringPair ("env:" + key, key, environment [key]);
632 if (libraries.Count > 0){
633 foreach (var alias_and_path in libraries){
634 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
642 static void GenerateBundles (List<string> files)
644 string temp_s = "temp.s"; // Path.GetTempFileName ();
645 string temp_c = "temp.c";
646 string temp_o = "temp.o";
650 if (object_out != null)
654 List<string> c_bundle_names = new List<string> ();
655 List<string[]> config_names = new List<string[]> ();
657 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
658 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
662 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
663 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
667 const unsigned char *data;
668 const unsigned int size;
669 } MonoBundledAssembly;
670 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
671 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
674 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
675 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
679 tc.WriteLine ("typedef struct _compressed_data {");
680 tc.WriteLine ("\tMonoBundledAssembly assembly;");
681 tc.WriteLine ("\tint compressed_size;");
682 tc.WriteLine ("} CompressedAssembly;\n");
685 object monitor = new object ();
687 var streams = new Dictionary<string, Stream> ();
688 var sizes = new Dictionary<string, long> ();
690 // Do the file reading and compression in parallel
691 Action<string> body = delegate (string url) {
692 string fname = LocateFile (new Uri (url).LocalPath);
693 Stream stream = File.OpenRead (fname);
695 long real_size = stream.Length;
698 byte[] cbuffer = new byte [8192];
699 MemoryStream ms = new MemoryStream ();
700 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
701 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
702 deflate.Write (cbuffer, 0, n);
706 byte [] bytes = ms.GetBuffer ();
707 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
711 streams [url] = stream;
712 sizes [url] = real_size;
718 Parallel.ForEach (files, body);
720 foreach (var url in files)
724 // The non-parallel part
725 byte [] buffer = new byte [8192];
726 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
727 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
728 foreach (var url in files) {
729 string fname = LocateFile (new Uri (url).LocalPath);
730 string aname = MakeBundle.GetAssemblyName (fname);
731 string encoded = symbolEscapeRE.Replace (aname, "_");
736 var stream = streams [url];
737 var real_size = sizes [url];
740 Console.WriteLine (" embedding: " + fname);
742 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
744 WriteBuffer (ts, stream, buffer);
747 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
748 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
749 " assembly_data_{0}, {2}}}, {3}}};",
750 encoded, aname, real_size, stream.Length);
752 double ratio = ((double) stream.Length * 100) / real_size;
753 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
756 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
757 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
758 encoded, aname, real_size);
762 c_bundle_names.Add ("assembly_bundle_" + encoded);
765 FileStream cf = File.OpenRead (fname + ".config");
767 Console.WriteLine (" config from: " + fname + ".config");
768 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
769 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
770 WriteBuffer (ts, cf, buffer);
772 config_names.Add (new string[] {aname, encoded});
773 } catch (FileNotFoundException) {
774 /* we ignore if the config file doesn't exist */
778 if (config_file != null){
781 conf = File.OpenRead (config_file);
783 Error (String.Format ("Failure to open {0}", config_file));
787 Console.WriteLine ("System config from: " + config_file);
788 tc.WriteLine ("extern const char system_config;");
789 WriteSymbol (ts, "system_config", config_file.Length);
791 WriteBuffer (ts, conf, buffer);
793 ts.Write ("\t.byte 0\n");
797 if (machine_config_file != null){
800 conf = File.OpenRead (machine_config_file);
802 Error (String.Format ("Failure to open {0}", machine_config_file));
806 Console.WriteLine ("Machine config from: " + machine_config_file);
807 tc.WriteLine ("extern const char machine_config;");
808 WriteSymbol (ts, "machine_config", machine_config_file.Length);
810 WriteBuffer (ts, conf, buffer);
811 ts.Write ("\t.byte 0\n");
817 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
819 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
821 foreach (string c in c_bundle_names){
822 tc.WriteLine ("\t&{0},", c);
824 tc.WriteLine ("\tNULL\n};\n");
825 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
827 if (ctor_func != null) {
828 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
829 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
830 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
833 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
834 foreach (string[] ass in config_names){
835 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
837 if (config_file != null)
838 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
839 if (machine_config_file != null)
840 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
841 tc.WriteLine ("}\n");
843 if (config_dir != null)
844 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
846 tc.WriteLine ("static const char *config_dir = NULL;");
848 Stream template_stream;
850 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
852 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
855 StreamReader s = new StreamReader (template_stream);
856 string template = s.ReadToEnd ();
859 if (!nomain && custom_main == null) {
860 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
861 StreamReader st = new StreamReader (template_main_stream);
862 string maintemplate = st.ReadToEnd ();
863 tc.Write (maintemplate);
868 string assembler = GetEnv("AS", "as");
869 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
876 Console.WriteLine("Compiling:");
878 if (style == "windows")
881 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
883 string compiler = GetEnv("CC", "cl.exe");
884 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
885 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
886 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
888 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
889 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
890 var linkLibraries = new string[] { "kernel32.lib",
905 string glue_obj = "mkbundle_glue.obj";
909 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
912 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
913 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
914 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
917 var compilerArgs = new List<string>();
918 compilerArgs.Add("/MT");
920 foreach (string include in includes)
921 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
923 if (!nomain || custom_main != null) {
924 compilerArgs.Add(quote(temp_c));
925 compilerArgs.Add(quote(temp_o));
926 if (custom_main != null)
927 compilerArgs.Add(quote(custom_main));
928 compilerArgs.Add(quote(monoLib));
929 compilerArgs.Add("/link");
930 compilerArgs.Add("/NODEFAULTLIB");
931 compilerArgs.Add("/SUBSYSTEM:windows");
932 compilerArgs.Add("/ENTRY:mainCRTStartup");
933 compilerArgs.AddRange(linkLibraries);
934 compilerArgs.Add("/out:"+ output);
936 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
941 // we are just creating a .lib
942 compilerArgs.Add("/c"); // compile only
943 compilerArgs.Add(temp_c);
944 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
946 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
949 string librarian = GetEnv ("LIB", "lib.exe");
950 var librarianArgs = new List<string> ();
951 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
952 librarianArgs.Add (temp_o);
953 librarianArgs.Add (glue_obj);
954 librarianArgs.Add (monoLib);
955 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
961 string zlib = (compress ? "-lz" : "");
962 string debugging = "-g";
963 string cc = GetEnv("CC", "cc");
966 if (style == "linux")
972 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
974 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
975 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
976 "`pkg-config --libs-only-L mono-2` " + smonolib +
977 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
978 temp_c, temp_o, output, zlib, cc);
983 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
984 temp_c, temp_o, output, zlib, cc);
990 Console.WriteLine ("Done");
995 if (object_out == null){
996 File.Delete (temp_o);
999 File.Delete (temp_c);
1001 File.Delete (temp_s);
1006 static List<string> LoadAssemblies (List<string> sources)
1008 List<string> assemblies = new List<string> ();
1011 var other = i18n.Select (x=> "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1013 foreach (string name in sources.Concat (other)){
1015 Assembly a = LoadAssembly (name);
1022 assemblies.Add (a.CodeBase);
1023 } catch (Exception) {
1026 Console.WriteLine ("File will not be scanned: {0}", name);
1027 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1035 Environment.Exit (1);
1040 static readonly Universe universe = new Universe ();
1041 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1043 public static string GetAssemblyName (string path)
1045 string name = Path.GetFileName (path);
1047 // A bit of a hack to support satellite assemblies. They all share the same name but
1048 // are placed in subdirectories named after the locale they implement. Also, all of
1049 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1050 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1051 string dir = Path.GetDirectoryName (path);
1052 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1054 name = dir.Substring (idx + 1) + Path.DirectorySeparatorChar + name;
1055 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1057 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1063 static bool QueueAssembly (List<string> files, string codebase)
1065 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1066 if (files.Contains (codebase))
1069 var path = new Uri(codebase).LocalPath;
1070 var name = GetAssemblyName (path);
1072 if (loaded_assemblies.TryGetValue (name, out found)) {
1073 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
1077 loaded_assemblies.Add (name, path);
1079 files.Add (codebase);
1083 Assembly a = universe.LoadFile (path);
1085 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1086 a = universe.Load (an.FullName);
1087 if (!QueueAssembly (files, a.CodeBase))
1090 } catch (Exception) {
1098 static Assembly LoadAssembly (string assembly)
1103 char[] path_chars = { '/', '\\' };
1105 if (assembly.IndexOfAny (path_chars) != -1) {
1106 a = universe.LoadFile (assembly);
1108 string ass = assembly;
1109 if (ass.EndsWith (".dll"))
1110 ass = assembly.Substring (0, assembly.Length - 4);
1111 a = universe.Load (ass);
1114 } catch (FileNotFoundException){
1115 string total_log = "";
1117 foreach (string dir in link_paths){
1118 string full_path = Path.Combine (dir, assembly);
1119 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1120 full_path += ".dll";
1123 a = universe.LoadFile (full_path);
1125 } catch (FileNotFoundException ff) {
1126 total_log += ff.FusionLog;
1130 Error ("Cannot find assembly `" + assembly + "'" );
1132 Console.WriteLine ("Log: \n" + total_log);
1133 } catch (IKVM.Reflection.BadImageFormatException f) {
1136 Error ("Cannot load assembly (bad file format) " + f.Message);
1137 } catch (FileLoadException f){
1138 Error ("Cannot load assembly " + f.Message);
1139 } catch (ArgumentNullException){
1140 Error("Cannot load assembly (null argument)");
1145 static void Error (string msg)
1147 Console.Error.WriteLine ("ERROR: " + msg);
1148 Environment.Exit (1);
1153 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1155 " --config F Bundle system config file `F'\n" +
1156 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1157 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1158 " -L path Adds `path' to the search path for assemblies\n" +
1159 " --machine-config F Use the given file as the machine.config for the application.\n" +
1160 " -o out Specifies output filename\n" +
1161 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1162 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1163 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1164 " -v Verbose output\n" +
1166 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1167 " --cross TARGET Generates a binary for the given TARGET\n"+
1168 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1169 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1170 " LIB is optional shortname for file located at PATH\n" +
1171 " --list-targets Lists available targets on the remote server\n" +
1172 " --local-targets Lists locally available targets\n" +
1173 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1174 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1175 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1177 "--custom Builds a custom launcher, options for --custom\n" +
1178 " -c Produce stub only, do not compile\n" +
1179 " -oo obj Specifies output filename for helper object file\n" +
1180 " --dos2unix[=true|false]\n" +
1181 " When no value provided, or when `true` specified\n" +
1182 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1183 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1184 " --keeptemp Keeps the temporary files\n" +
1185 " --static Statically link to mono libs\n" +
1186 " --nomain Don't include a main() function, for libraries\n" +
1187 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1188 " -z Compress the assemblies before embedding.\n" +
1189 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1190 " You need zlib development headers and libraries.\n");
1193 [DllImport ("libc")]
1194 static extern int system (string s);
1195 [DllImport ("libc")]
1196 static extern int uname (IntPtr buf);
1198 static void DetectOS ()
1201 os_message = "OS is: Windows";
1206 IntPtr buf = Marshal.AllocHGlobal (8192);
1207 if (uname (buf) != 0){
1208 os_message = "Warning: Unable to detect OS";
1209 Marshal.FreeHGlobal (buf);
1212 string os = Marshal.PtrToStringAnsi (buf);
1213 os_message = "OS is: " + os;
1217 Marshal.FreeHGlobal (buf);
1220 static bool IsUnix {
1222 int p = (int) Environment.OSVersion.Platform;
1223 return ((p == 4) || (p == 128) || (p == 6));
1227 static void Execute (string cmdLine)
1231 Console.WriteLine ("[execute cmd]: " + cmdLine);
1232 int ret = system (cmdLine);
1235 Error(String.Format("[Fail] {0}", ret));
1240 // on Windows, we have to pipe the output of a
1241 // `cmd` interpolation to dos2unix, because the shell does not
1242 // strip the CRLFs generated by the native pkg-config distributed
1245 // But if it's *not* on cygwin, just skip it.
1247 // check if dos2unix is applicable.
1248 if (use_dos2unix == true)
1250 var info = new ProcessStartInfo ("dos2unix");
1251 info.CreateNoWindow = true;
1252 info.RedirectStandardInput = true;
1253 info.UseShellExecute = false;
1254 var dos2unix = Process.Start (info);
1255 dos2unix.StandardInput.WriteLine ("aaa");
1256 dos2unix.StandardInput.WriteLine ("\u0004");
1257 dos2unix.StandardInput.Close ();
1258 dos2unix.WaitForExit ();
1259 if (dos2unix.ExitCode == 0)
1260 use_dos2unix = true;
1262 Console.WriteLine("Warning: dos2unix not found");
1263 use_dos2unix = false;
1266 if (use_dos2unix == null)
1267 use_dos2unix = false;
1269 ProcessStartInfo psi = new ProcessStartInfo();
1270 psi.UseShellExecute = false;
1272 // if there is no dos2unix, just run cmd /c.
1273 if (use_dos2unix == false)
1275 psi.FileName = "cmd";
1276 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1280 psi.FileName = "sh";
1281 StringBuilder b = new StringBuilder();
1283 for (int i = 0; i < cmdLine.Length; i++)
1285 if (cmdLine[i] == '`')
1289 b.Append("|dos2unix");
1293 b.Append(cmdLine[i]);
1295 cmdLine = b.ToString();
1296 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1300 Console.WriteLine(cmdLine);
1301 using (Process p = Process.Start (psi)) {
1303 int ret = p.ExitCode;
1305 Error (String.Format("[Fail] {0}", ret));
1310 static string GetEnv(string name, string defaultValue)
1312 string val = Environment.GetEnvironmentVariable(name);
1316 Console.WriteLine("{0} = {1}", name, val);
1322 Console.WriteLine("{0} = {1} (default)", name, val);
1327 static string LocateFile(string default_path)
1329 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1330 if (File.Exists(override_path))
1331 return override_path;
1332 else if (File.Exists(default_path))
1333 return default_path;
1335 throw new FileNotFoundException(default_path);