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");
390 GeneratePackage (files);
392 Console.WriteLine ("Generated {0}", output);
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 Console.WriteLine ("Using runtime: " + runtime);
612 maker.AddFile (runtime);
614 foreach (var url in files){
615 string fname = LocateFile (new Uri (url).LocalPath);
616 string aname = MakeBundle.GetAssemblyName (fname);
618 maker.Add ("assembly:" + aname, fname);
619 Console.WriteLine (" Assembly: " + fname);
620 if (File.Exists (fname + ".config")){
621 maker.Add ("config:" + aname, fname + ".config");
622 Console.WriteLine (" Config: " + runtime);
626 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
629 if (config_dir != null)
630 maker.Add ("config_dir:", config_dir);
631 if (embedded_options != null)
632 maker.AddString ("options:", embedded_options);
633 if (environment.Count > 0){
634 foreach (var key in environment.Keys)
635 maker.AddStringPair ("env:" + key, key, environment [key]);
637 if (libraries.Count > 0){
638 foreach (var alias_and_path in libraries){
639 Console.WriteLine (" Library: " + alias_and_path.Value);
640 maker.Add ("library:" + alias_and_path.Key, alias_and_path.Value);
648 static void GenerateBundles (List<string> files)
650 string temp_s = "temp.s"; // Path.GetTempFileName ();
651 string temp_c = "temp.c";
652 string temp_o = "temp.o";
656 if (object_out != null)
660 List<string> c_bundle_names = new List<string> ();
661 List<string[]> config_names = new List<string[]> ();
663 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
664 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
668 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
669 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
673 const unsigned char *data;
674 const unsigned int size;
675 } MonoBundledAssembly;
676 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
677 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
680 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
681 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
685 tc.WriteLine ("typedef struct _compressed_data {");
686 tc.WriteLine ("\tMonoBundledAssembly assembly;");
687 tc.WriteLine ("\tint compressed_size;");
688 tc.WriteLine ("} CompressedAssembly;\n");
691 object monitor = new object ();
693 var streams = new Dictionary<string, Stream> ();
694 var sizes = new Dictionary<string, long> ();
696 // Do the file reading and compression in parallel
697 Action<string> body = delegate (string url) {
698 string fname = LocateFile (new Uri (url).LocalPath);
699 Stream stream = File.OpenRead (fname);
701 long real_size = stream.Length;
704 byte[] cbuffer = new byte [8192];
705 MemoryStream ms = new MemoryStream ();
706 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
707 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
708 deflate.Write (cbuffer, 0, n);
712 byte [] bytes = ms.GetBuffer ();
713 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
717 streams [url] = stream;
718 sizes [url] = real_size;
724 Parallel.ForEach (files, body);
726 foreach (var url in files)
730 // The non-parallel part
731 byte [] buffer = new byte [8192];
732 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
733 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
734 foreach (var url in files) {
735 string fname = LocateFile (new Uri (url).LocalPath);
736 string aname = MakeBundle.GetAssemblyName (fname);
737 string encoded = symbolEscapeRE.Replace (aname, "_");
742 var stream = streams [url];
743 var real_size = sizes [url];
746 Console.WriteLine (" embedding: " + fname);
748 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
750 WriteBuffer (ts, stream, buffer);
753 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
754 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
755 " assembly_data_{0}, {2}}}, {3}}};",
756 encoded, aname, real_size, stream.Length);
758 double ratio = ((double) stream.Length * 100) / real_size;
759 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
762 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
763 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
764 encoded, aname, real_size);
768 c_bundle_names.Add ("assembly_bundle_" + encoded);
771 FileStream cf = File.OpenRead (fname + ".config");
773 Console.WriteLine (" config from: " + fname + ".config");
774 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
775 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
776 WriteBuffer (ts, cf, buffer);
778 config_names.Add (new string[] {aname, encoded});
779 } catch (FileNotFoundException) {
780 /* we ignore if the config file doesn't exist */
784 if (config_file != null){
787 conf = File.OpenRead (config_file);
789 Error (String.Format ("Failure to open {0}", config_file));
793 Console.WriteLine ("System config from: " + config_file);
794 tc.WriteLine ("extern const char system_config;");
795 WriteSymbol (ts, "system_config", config_file.Length);
797 WriteBuffer (ts, conf, buffer);
799 ts.Write ("\t.byte 0\n");
803 if (machine_config_file != null){
806 conf = File.OpenRead (machine_config_file);
808 Error (String.Format ("Failure to open {0}", machine_config_file));
812 Console.WriteLine ("Machine config from: " + machine_config_file);
813 tc.WriteLine ("extern const char machine_config;");
814 WriteSymbol (ts, "machine_config", machine_config_file.Length);
816 WriteBuffer (ts, conf, buffer);
817 ts.Write ("\t.byte 0\n");
823 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
825 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
827 foreach (string c in c_bundle_names){
828 tc.WriteLine ("\t&{0},", c);
830 tc.WriteLine ("\tNULL\n};\n");
831 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
833 if (ctor_func != null) {
834 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
835 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
836 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
839 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
840 foreach (string[] ass in config_names){
841 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
843 if (config_file != null)
844 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
845 if (machine_config_file != null)
846 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
847 tc.WriteLine ("}\n");
849 if (config_dir != null)
850 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
852 tc.WriteLine ("static const char *config_dir = NULL;");
854 Stream template_stream;
856 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
858 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
861 StreamReader s = new StreamReader (template_stream);
862 string template = s.ReadToEnd ();
865 if (!nomain && custom_main == null) {
866 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
867 StreamReader st = new StreamReader (template_main_stream);
868 string maintemplate = st.ReadToEnd ();
869 tc.Write (maintemplate);
874 string assembler = GetEnv("AS", "as");
875 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
882 Console.WriteLine("Compiling:");
884 if (style == "windows")
887 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
889 string compiler = GetEnv("CC", "cl.exe");
890 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
891 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
892 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
894 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
895 // string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
896 var linkLibraries = new string[] { "kernel32.lib",
911 string glue_obj = "mkbundle_glue.obj";
915 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
918 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
919 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
920 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
923 var compilerArgs = new List<string>();
924 compilerArgs.Add("/MT");
926 foreach (string include in includes)
927 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
929 if (!nomain || custom_main != null) {
930 compilerArgs.Add(quote(temp_c));
931 compilerArgs.Add(quote(temp_o));
932 if (custom_main != null)
933 compilerArgs.Add(quote(custom_main));
934 compilerArgs.Add(quote(monoLib));
935 compilerArgs.Add("/link");
936 compilerArgs.Add("/NODEFAULTLIB");
937 compilerArgs.Add("/SUBSYSTEM:windows");
938 compilerArgs.Add("/ENTRY:mainCRTStartup");
939 compilerArgs.AddRange(linkLibraries);
940 compilerArgs.Add("/out:"+ output);
942 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
947 // we are just creating a .lib
948 compilerArgs.Add("/c"); // compile only
949 compilerArgs.Add(temp_c);
950 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
952 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
955 string librarian = GetEnv ("LIB", "lib.exe");
956 var librarianArgs = new List<string> ();
957 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
958 librarianArgs.Add (temp_o);
959 librarianArgs.Add (glue_obj);
960 librarianArgs.Add (monoLib);
961 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
967 string zlib = (compress ? "-lz" : "");
968 string debugging = "-g";
969 string cc = GetEnv("CC", "cc");
972 if (style == "linux")
978 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
980 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
981 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
982 "`pkg-config --libs-only-L mono-2` " + smonolib +
983 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
984 temp_c, temp_o, output, zlib, cc);
989 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
990 temp_c, temp_o, output, zlib, cc);
996 Console.WriteLine ("Done");
1001 if (object_out == null){
1002 File.Delete (temp_o);
1005 File.Delete (temp_c);
1007 File.Delete (temp_s);
1012 static List<string> LoadAssemblies (List<string> sources)
1014 List<string> assemblies = new List<string> ();
1017 var other = i18n.Select (x=> "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
1019 foreach (string name in sources.Concat (other)){
1021 Assembly a = LoadAssembly (name);
1028 assemblies.Add (a.CodeBase);
1029 } catch (Exception) {
1032 Console.WriteLine ("File will not be scanned: {0}", name);
1033 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1041 Environment.Exit (1);
1046 static readonly Universe universe = new Universe ();
1047 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1049 public static string GetAssemblyName (string path)
1051 string name = Path.GetFileName (path);
1053 // A bit of a hack to support satellite assemblies. They all share the same name but
1054 // are placed in subdirectories named after the locale they implement. Also, all of
1055 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1056 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1057 string dir = Path.GetDirectoryName (path);
1058 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1060 name = dir.Substring (idx + 1) + Path.DirectorySeparatorChar + name;
1061 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1063 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1069 static bool QueueAssembly (List<string> files, string codebase)
1071 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1072 if (files.Contains (codebase))
1075 var path = new Uri(codebase).LocalPath;
1076 var name = GetAssemblyName (path);
1078 if (loaded_assemblies.TryGetValue (name, out found)) {
1079 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
1083 loaded_assemblies.Add (name, path);
1085 files.Add (codebase);
1089 Assembly a = universe.LoadFile (path);
1091 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1092 a = universe.Load (an.FullName);
1093 if (!QueueAssembly (files, a.CodeBase))
1096 } catch (Exception) {
1104 static Assembly LoadAssembly (string assembly)
1109 char[] path_chars = { '/', '\\' };
1111 if (assembly.IndexOfAny (path_chars) != -1) {
1112 a = universe.LoadFile (assembly);
1114 string ass = assembly;
1115 if (ass.EndsWith (".dll"))
1116 ass = assembly.Substring (0, assembly.Length - 4);
1117 a = universe.Load (ass);
1120 } catch (FileNotFoundException){
1121 string total_log = "";
1123 foreach (string dir in link_paths){
1124 string full_path = Path.Combine (dir, assembly);
1125 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1126 full_path += ".dll";
1129 a = universe.LoadFile (full_path);
1131 } catch (FileNotFoundException ff) {
1132 total_log += ff.FusionLog;
1136 Error ("Cannot find assembly `" + assembly + "'" );
1138 Console.WriteLine ("Log: \n" + total_log);
1139 } catch (IKVM.Reflection.BadImageFormatException f) {
1142 Error ("Cannot load assembly (bad file format) " + f.Message);
1143 } catch (FileLoadException f){
1144 Error ("Cannot load assembly " + f.Message);
1145 } catch (ArgumentNullException){
1146 Error("Cannot load assembly (null argument)");
1151 static void Error (string msg)
1153 Console.Error.WriteLine ("ERROR: " + msg);
1154 Environment.Exit (1);
1159 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1161 " --config F Bundle system config file `F'\n" +
1162 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1163 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1164 " -L path Adds `path' to the search path for assemblies\n" +
1165 " --machine-config F Use the given file as the machine.config for the application.\n" +
1166 " -o out Specifies output filename\n" +
1167 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1168 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1169 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1170 " -v Verbose output\n" +
1172 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1173 " --cross TARGET Generates a binary for the given TARGET\n"+
1174 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1175 " --library [LIB,]PATH Bundles the specified dynamic library to be used at runtime\n" +
1176 " LIB is optional shortname for file located at PATH\n" +
1177 " --list-targets Lists available targets on the remote server\n" +
1178 " --local-targets Lists locally available targets\n" +
1179 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1180 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1181 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1183 "--custom Builds a custom launcher, options for --custom\n" +
1184 " -c Produce stub only, do not compile\n" +
1185 " -oo obj Specifies output filename for helper object file\n" +
1186 " --dos2unix[=true|false]\n" +
1187 " When no value provided, or when `true` specified\n" +
1188 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1189 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1190 " --keeptemp Keeps the temporary files\n" +
1191 " --static Statically link to mono libs\n" +
1192 " --nomain Don't include a main() function, for libraries\n" +
1193 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1194 " -z Compress the assemblies before embedding.\n" +
1195 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1196 " You need zlib development headers and libraries.\n");
1199 [DllImport ("libc")]
1200 static extern int system (string s);
1201 [DllImport ("libc")]
1202 static extern int uname (IntPtr buf);
1204 static void DetectOS ()
1207 os_message = "OS is: Windows";
1212 IntPtr buf = Marshal.AllocHGlobal (8192);
1213 if (uname (buf) != 0){
1214 os_message = "Warning: Unable to detect OS";
1215 Marshal.FreeHGlobal (buf);
1218 string os = Marshal.PtrToStringAnsi (buf);
1219 os_message = "OS is: " + os;
1223 Marshal.FreeHGlobal (buf);
1226 static bool IsUnix {
1228 int p = (int) Environment.OSVersion.Platform;
1229 return ((p == 4) || (p == 128) || (p == 6));
1233 static void Execute (string cmdLine)
1237 Console.WriteLine ("[execute cmd]: " + cmdLine);
1238 int ret = system (cmdLine);
1241 Error(String.Format("[Fail] {0}", ret));
1246 // on Windows, we have to pipe the output of a
1247 // `cmd` interpolation to dos2unix, because the shell does not
1248 // strip the CRLFs generated by the native pkg-config distributed
1251 // But if it's *not* on cygwin, just skip it.
1253 // check if dos2unix is applicable.
1254 if (use_dos2unix == true)
1256 var info = new ProcessStartInfo ("dos2unix");
1257 info.CreateNoWindow = true;
1258 info.RedirectStandardInput = true;
1259 info.UseShellExecute = false;
1260 var dos2unix = Process.Start (info);
1261 dos2unix.StandardInput.WriteLine ("aaa");
1262 dos2unix.StandardInput.WriteLine ("\u0004");
1263 dos2unix.StandardInput.Close ();
1264 dos2unix.WaitForExit ();
1265 if (dos2unix.ExitCode == 0)
1266 use_dos2unix = true;
1268 Console.WriteLine("Warning: dos2unix not found");
1269 use_dos2unix = false;
1272 if (use_dos2unix == null)
1273 use_dos2unix = false;
1275 ProcessStartInfo psi = new ProcessStartInfo();
1276 psi.UseShellExecute = false;
1278 // if there is no dos2unix, just run cmd /c.
1279 if (use_dos2unix == false)
1281 psi.FileName = "cmd";
1282 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1286 psi.FileName = "sh";
1287 StringBuilder b = new StringBuilder();
1289 for (int i = 0; i < cmdLine.Length; i++)
1291 if (cmdLine[i] == '`')
1295 b.Append("|dos2unix");
1299 b.Append(cmdLine[i]);
1301 cmdLine = b.ToString();
1302 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1306 Console.WriteLine(cmdLine);
1307 using (Process p = Process.Start (psi)) {
1309 int ret = p.ExitCode;
1311 Error (String.Format("[Fail] {0}", ret));
1316 static string GetEnv(string name, string defaultValue)
1318 string val = Environment.GetEnvironmentVariable(name);
1322 Console.WriteLine("{0} = {1}", name, val);
1328 Console.WriteLine("{0} = {1} (default)", name, val);
1333 static string LocateFile(string default_path)
1335 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1336 if (File.Exists(override_path))
1337 return override_path;
1338 else if (File.Exists(default_path))
1339 return default_path;
1341 throw new FileNotFoundException(default_path);