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;
26 using System.Diagnostics;
28 using System.Threading.Tasks;
31 static string output = "a.out";
32 static string object_out = null;
33 static List<string> link_paths = new List<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];
129 case "--fetch-target":
134 fetch_target = args [++i];
137 case "--list-targets":
138 var wc = new WebClient ();
139 var s = wc.DownloadString (new Uri (target_server + "target-list.txt"));
140 Console.WriteLine ("Cross-compilation targets available:\n" + s);
144 case "--target-server":
149 target_server = args [++i];
165 embedded_options = args [++i];
174 runtime = args [++i];
181 object_out = args [++i];
189 link_paths.Add (args [++i]);
213 config_file = args [++i];
215 case "--machine-config":
221 machine_config_file = args [++i];
224 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
232 config_dir = args [++i];
240 case "--custom-main":
245 custom_main = args [++i];
259 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
267 case "--static-ctor":
272 ctor_func = args [++i];
275 case "--dos2unix=true":
278 case "--dos2unix=false":
279 use_dos2unix = false;
291 var env = args [++i];
292 var p = env.IndexOf ('=');
294 environment.Add (env, "");
296 environment.Add (env.Substring (0, p), env.Substring (p+1));
299 sources.Add (args [i]);
305 if (fetch_target != null){
306 var truntime = Path.Combine (targets_dir, fetch_target, "mono");
307 Directory.CreateDirectory (Path.GetDirectoryName (truntime));
308 var wc = new WebClient ();
309 var uri = new Uri ($"{target_server}{fetch_target}");
312 Console.WriteLine ($"Downloading runtime {uri} to {truntime}");
315 wc.DownloadFile (uri, truntime);
317 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
318 File.Delete (truntime);
325 Console.WriteLine (os_message);
326 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
329 if (sources.Count == 0 || output == null) {
331 Environment.Exit (1);
334 List<string> assemblies = LoadAssemblies (sources);
335 List<string> files = new List<string> ();
336 foreach (string file in assemblies)
337 if (!QueueAssembly (files, file))
340 GenerateBundles (files);
342 if (cross_target == "default")
345 if (runtime == null){
346 if (cross_target == null){
347 Console.Error.WriteLine ("you should specify either a --runtime or a --cross compilation target");
348 Environment.Exit (1);
350 runtime = Path.Combine (targets_dir, cross_target, "mono");
351 if (!File.Exists (runtime)){
352 Console.Error.WriteLine ($"The runtime for the {cross_target} does not exist, use --fetch-target {cross_target} to download first");
356 if (!File.Exists (runtime)){
357 Console.Error.WriteLine ($"The Mono runtime specified with --runtime does not exist");
362 Console.WriteLine ("Using runtime {0} for {1}", runtime, output);
364 GeneratePackage (files);
370 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
372 static void CommandLocalTargets ()
376 Console.WriteLine ("Available targets:");
377 Console.WriteLine ("\tdefault\t- Current System Mono");
379 targets = Directory.GetDirectories (targets_dir);
383 foreach (var target in targets){
384 var p = Path.Combine (target, "mono");
386 Console.WriteLine ("\t{0}", Path.GetFileName (target));
390 static void WriteSymbol (StreamWriter sw, string name, long size)
396 "\t.section .rodata\n" +
398 "\t.type {0}, \"object\"\n" +
399 "\t.size {0}, {1}\n" +
405 "\t.section __TEXT,__text,regular,pure_instructions\n" +
415 "\t.section .rdata,\"dr\"\n" +
423 static string [] chars = new string [256];
425 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
429 // Preallocate the strings we need.
430 if (chars [0] == null) {
431 for (int i = 0; i < chars.Length; i++)
432 chars [i] = string.Format ("{0}", i.ToString ());
435 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
437 for (int i = 0; i < n; i++) {
438 if (count % 32 == 0) {
439 ts.Write ("\n\t.byte ");
443 ts.Write (chars [buffer [i]]);
452 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
453 const int align = 4096;
456 public PackageMaker (string output)
458 package = File.Create (output, 128*1024);
460 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
464 public int AddFile (string fname)
466 using (Stream fileStream = File.OpenRead (fname)){
467 var ret = fileStream.Length;
470 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
471 fileStream.CopyTo (package);
472 package.Position = package.Position + (align - (package.Position % align));
478 public void Add (string entry, string fname)
480 var p = package.Position;
481 var size = AddFile (fname);
483 locations [entry] = Tuple.Create(p, size);
486 public void AddString (string entry, string text)
488 var bytes = Encoding.UTF8.GetBytes (text);
489 locations [entry] = Tuple.Create (package.Position, bytes.Length);
490 package.Write (bytes, 0, bytes.Length);
491 package.Position = package.Position + (align - (package.Position % align));
494 public void AddStringPair (string entry, string key, string value)
496 var kbytes = Encoding.UTF8.GetBytes (key);
497 var vbytes = Encoding.UTF8.GetBytes (value);
499 Console.WriteLine ("ADDING {0} to {1}", key, value);
500 if (kbytes.Length > 255){
501 Console.WriteLine ("The key value can not exceed 255 characters: " + key);
502 Environment.Exit (1);
505 locations [entry] = Tuple.Create (package.Position, kbytes.Length+vbytes.Length+3);
506 package.WriteByte ((byte)kbytes.Length);
507 package.Write (kbytes, 0, kbytes.Length);
508 package.WriteByte (0);
509 package.Write (vbytes, 0, vbytes.Length);
510 package.WriteByte (0);
511 package.Position = package.Position + (align - (package.Position % align));
518 foreach (var floc in locations.Keys){
519 Console.WriteLine ($"{floc} at {locations[floc]:x}");
523 public void WriteIndex ()
525 var indexStart = package.Position;
526 var binary = new BinaryWriter (package);
528 binary.Write (locations.Count);
529 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
530 var bytes = Encoding.UTF8.GetBytes (entry.Key);
531 binary.Write (bytes.Length+1);
532 binary.Write (bytes);
533 binary.Write ((byte) 0);
534 binary.Write (entry.Value.Item1);
535 binary.Write (entry.Value.Item2);
537 binary.Write (indexStart);
538 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
550 static bool MaybeAddFile (PackageMaker maker, string code, string file)
555 if (!File.Exists (file)){
556 Console.Error.WriteLine ("The file {0} does not exist", file);
559 maker.Add (code, file);
563 static bool GeneratePackage (List<string> files)
565 if (runtime == null){
567 runtime = Process.GetCurrentProcess().MainModule.FileName;
569 Console.Error.WriteLine ("You must specify at least one runtime with --runtime or --cross");
570 Environment.Exit (1);
573 if (!File.Exists (runtime)){
574 Console.Error.WriteLine ($"The specified runtime at {runtime} does not exist");
575 Environment.Exit (1);
578 if (ctor_func != null){
579 Console.Error.WriteLine ("--static-ctor not supported with package bundling, you must use native compilation for this");
583 var maker = new PackageMaker (output);
584 maker.AddFile (runtime);
586 foreach (var url in files){
587 string fname = LocateFile (new Uri (url).LocalPath);
588 string aname = MakeBundle.GetAssemblyName (fname);
590 maker.Add ("assembly:" + aname, fname);
591 if (File.Exists (fname + ".config"))
592 maker.Add ("config:" + aname, fname + ".config");
594 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
597 if (config_dir != null)
598 maker.Add ("config_dir:", config_dir);
599 if (embedded_options != null)
600 maker.AddString ("options:", embedded_options);
601 if (environment.Count > 0){
602 foreach (var key in environment.Keys)
603 maker.AddStringPair ("env:" + key, key, environment [key]);
610 static void GenerateBundles (List<string> files)
612 string temp_s = "temp.s"; // Path.GetTempFileName ();
613 string temp_c = "temp.c";
614 string temp_o = "temp.o";
618 if (object_out != null)
622 List<string> c_bundle_names = new List<string> ();
623 List<string[]> config_names = new List<string[]> ();
625 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
626 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
630 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
631 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
635 const unsigned char *data;
636 const unsigned int size;
637 } MonoBundledAssembly;
638 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
639 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
642 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
643 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
647 tc.WriteLine ("typedef struct _compressed_data {");
648 tc.WriteLine ("\tMonoBundledAssembly assembly;");
649 tc.WriteLine ("\tint compressed_size;");
650 tc.WriteLine ("} CompressedAssembly;\n");
653 object monitor = new object ();
655 var streams = new Dictionary<string, Stream> ();
656 var sizes = new Dictionary<string, long> ();
658 // Do the file reading and compression in parallel
659 Action<string> body = delegate (string url) {
660 string fname = LocateFile (new Uri (url).LocalPath);
661 Stream stream = File.OpenRead (fname);
663 long real_size = stream.Length;
666 byte[] cbuffer = new byte [8192];
667 MemoryStream ms = new MemoryStream ();
668 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
669 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
670 deflate.Write (cbuffer, 0, n);
674 byte [] bytes = ms.GetBuffer ();
675 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
679 streams [url] = stream;
680 sizes [url] = real_size;
686 Parallel.ForEach (files, body);
688 foreach (var url in files)
692 // The non-parallel part
693 byte [] buffer = new byte [8192];
694 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
695 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
696 foreach (var url in files) {
697 string fname = LocateFile (new Uri (url).LocalPath);
698 string aname = MakeBundle.GetAssemblyName (fname);
699 string encoded = symbolEscapeRE.Replace (aname, "_");
704 var stream = streams [url];
705 var real_size = sizes [url];
708 Console.WriteLine (" embedding: " + fname);
710 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
712 WriteBuffer (ts, stream, buffer);
715 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
716 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
717 " assembly_data_{0}, {2}}}, {3}}};",
718 encoded, aname, real_size, stream.Length);
720 double ratio = ((double) stream.Length * 100) / real_size;
721 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
724 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
725 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
726 encoded, aname, real_size);
730 c_bundle_names.Add ("assembly_bundle_" + encoded);
733 FileStream cf = File.OpenRead (fname + ".config");
735 Console.WriteLine (" config from: " + fname + ".config");
736 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
737 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
738 WriteBuffer (ts, cf, buffer);
740 config_names.Add (new string[] {aname, encoded});
741 } catch (FileNotFoundException) {
742 /* we ignore if the config file doesn't exist */
746 if (config_file != null){
749 conf = File.OpenRead (config_file);
751 Error (String.Format ("Failure to open {0}", config_file));
755 Console.WriteLine ("System config from: " + config_file);
756 tc.WriteLine ("extern const char system_config;");
757 WriteSymbol (ts, "system_config", config_file.Length);
759 WriteBuffer (ts, conf, buffer);
761 ts.Write ("\t.byte 0\n");
765 if (machine_config_file != null){
768 conf = File.OpenRead (machine_config_file);
770 Error (String.Format ("Failure to open {0}", machine_config_file));
774 Console.WriteLine ("Machine config from: " + machine_config_file);
775 tc.WriteLine ("extern const char machine_config;");
776 WriteSymbol (ts, "machine_config", machine_config_file.Length);
778 WriteBuffer (ts, conf, buffer);
779 ts.Write ("\t.byte 0\n");
785 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
787 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
789 foreach (string c in c_bundle_names){
790 tc.WriteLine ("\t&{0},", c);
792 tc.WriteLine ("\tNULL\n};\n");
793 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
795 if (ctor_func != null) {
796 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
797 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
798 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
801 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
802 foreach (string[] ass in config_names){
803 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
805 if (config_file != null)
806 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
807 if (machine_config_file != null)
808 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
809 tc.WriteLine ("}\n");
811 if (config_dir != null)
812 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
814 tc.WriteLine ("static const char *config_dir = NULL;");
816 Stream template_stream;
818 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
820 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
823 StreamReader s = new StreamReader (template_stream);
824 string template = s.ReadToEnd ();
827 if (!nomain && custom_main == null) {
828 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
829 StreamReader st = new StreamReader (template_main_stream);
830 string maintemplate = st.ReadToEnd ();
831 tc.Write (maintemplate);
836 string assembler = GetEnv("AS", "as");
837 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
844 Console.WriteLine("Compiling:");
846 if (style == "windows")
849 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
851 string compiler = GetEnv("CC", "cl.exe");
852 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
853 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
854 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
856 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
857 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
858 var linkLibraries = new string[] { "kernel32.lib",
873 string glue_obj = "mkbundle_glue.obj";
877 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
880 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
881 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
882 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
885 var compilerArgs = new List<string>();
886 compilerArgs.Add("/MT");
888 foreach (string include in includes)
889 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
891 if (!nomain || custom_main != null) {
892 compilerArgs.Add(quote(temp_c));
893 compilerArgs.Add(quote(temp_o));
894 if (custom_main != null)
895 compilerArgs.Add(quote(custom_main));
896 compilerArgs.Add(quote(monoLib));
897 compilerArgs.Add("/link");
898 compilerArgs.Add("/NODEFAULTLIB");
899 compilerArgs.Add("/SUBSYSTEM:windows");
900 compilerArgs.Add("/ENTRY:mainCRTStartup");
901 compilerArgs.AddRange(linkLibraries);
902 compilerArgs.Add("/out:"+ output);
904 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
909 // we are just creating a .lib
910 compilerArgs.Add("/c"); // compile only
911 compilerArgs.Add(temp_c);
912 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
914 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
917 string librarian = GetEnv ("LIB", "lib.exe");
918 var librarianArgs = new List<string> ();
919 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
920 librarianArgs.Add (temp_o);
921 librarianArgs.Add (glue_obj);
922 librarianArgs.Add (monoLib);
923 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
929 string zlib = (compress ? "-lz" : "");
930 string debugging = "-g";
931 string cc = GetEnv("CC", "cc");
934 if (style == "linux")
940 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
942 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
943 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
944 "`pkg-config --libs-only-L mono-2` " + smonolib +
945 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
946 temp_c, temp_o, output, zlib, cc);
951 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
952 temp_c, temp_o, output, zlib, cc);
958 Console.WriteLine ("Done");
963 if (object_out == null){
964 File.Delete (temp_o);
967 File.Delete (temp_c);
969 File.Delete (temp_s);
974 static List<string> LoadAssemblies (List<string> sources)
976 List<string> assemblies = new List<string> ();
979 var other = i18n.Select (x=> "I18N." + x + (x.Length > 0 ? "." : "") + "dll");
981 foreach (string name in sources.Concat (other)){
983 Assembly a = LoadAssembly (name);
990 assemblies.Add (a.CodeBase);
991 } catch (Exception) {
994 Console.WriteLine ("File will not be scanned: {0}", name);
995 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
1003 Environment.Exit (1);
1008 static readonly Universe universe = new Universe ();
1009 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
1011 public static string GetAssemblyName (string path)
1013 string name = Path.GetFileName (path);
1015 // A bit of a hack to support satellite assemblies. They all share the same name but
1016 // are placed in subdirectories named after the locale they implement. Also, all of
1017 // them end in .resources.dll, therefore we can use that to detect the circumstances.
1018 if (name.EndsWith (".resources.dll", StringComparison.OrdinalIgnoreCase)) {
1019 string dir = Path.GetDirectoryName (path);
1020 int idx = dir.LastIndexOf (Path.DirectorySeparatorChar);
1022 name = dir.Substring (idx + 1) + Path.DirectorySeparatorChar + name;
1023 Console.WriteLine ($"Storing satellite assembly '{path}' with name '{name}'");
1025 Console.WriteLine ($"Warning: satellite assembly {path} doesn't have locale path prefix, name conflicts possible");
1031 static bool QueueAssembly (List<string> files, string codebase)
1033 //Console.WriteLine ("CODE BASE IS {0}", codebase);
1034 if (files.Contains (codebase))
1037 var path = new Uri(codebase).LocalPath;
1038 var name = GetAssemblyName (path);
1040 if (loaded_assemblies.TryGetValue (name, out found)) {
1041 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
1045 loaded_assemblies.Add (name, path);
1047 files.Add (codebase);
1051 Assembly a = universe.LoadFile (path);
1053 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
1054 a = universe.Load (an.FullName);
1055 if (!QueueAssembly (files, a.CodeBase))
1058 } catch (Exception) {
1066 static Assembly LoadAssembly (string assembly)
1071 char[] path_chars = { '/', '\\' };
1073 if (assembly.IndexOfAny (path_chars) != -1) {
1074 a = universe.LoadFile (assembly);
1076 string ass = assembly;
1077 if (ass.EndsWith (".dll"))
1078 ass = assembly.Substring (0, assembly.Length - 4);
1079 a = universe.Load (ass);
1082 } catch (FileNotFoundException){
1083 string total_log = "";
1085 foreach (string dir in link_paths){
1086 string full_path = Path.Combine (dir, assembly);
1087 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
1088 full_path += ".dll";
1091 a = universe.LoadFile (full_path);
1093 } catch (FileNotFoundException ff) {
1094 total_log += ff.FusionLog;
1098 Error ("Cannot find assembly `" + assembly + "'" );
1100 Console.WriteLine ("Log: \n" + total_log);
1101 } catch (IKVM.Reflection.BadImageFormatException f) {
1104 Error ("Cannot load assembly (bad file format) " + f.Message);
1105 } catch (FileLoadException f){
1106 Error ("Cannot load assembly " + f.Message);
1107 } catch (ArgumentNullException){
1108 Error("Cannot load assembly (null argument)");
1113 static void Error (string msg)
1115 Console.Error.WriteLine ("ERROR: " + msg);
1116 Environment.Exit (1);
1121 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1123 " --config F Bundle system config file `F'\n" +
1124 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1125 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1126 " -L path Adds `path' to the search path for assemblies\n" +
1127 " --machine-config F Use the given file as the machine.config for the application.\n" +
1128 " -o out Specifies output filename\n" +
1129 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1130 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1131 " --i18n ENCODING none, all or comma separated list of CJK, MidWest, Other, Rare, West.\n" +
1132 " -v Verbose output\n" +
1134 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1135 " --cross TARGET Generates a binary for the given TARGET\n"+
1136 " --local-targets Lists locally available targets\n" +
1137 " --list-targets Lists available targets on the remote server\n" +
1138 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1139 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1140 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1141 " --env KEY=VALUE Hardcodes an environment variable for the target\n" +
1143 "--custom Builds a custom launcher, options for --custom\n" +
1144 " -c Produce stub only, do not compile\n" +
1145 " -oo obj Specifies output filename for helper object file\n" +
1146 " --dos2unix[=true|false]\n" +
1147 " When no value provided, or when `true` specified\n" +
1148 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1149 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1150 " --keeptemp Keeps the temporary files\n" +
1151 " --static Statically link to mono libs\n" +
1152 " --nomain Don't include a main() function, for libraries\n" +
1153 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1154 " -z Compress the assemblies before embedding.\n" +
1155 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1156 " You need zlib development headers and libraries.\n");
1159 [DllImport ("libc")]
1160 static extern int system (string s);
1161 [DllImport ("libc")]
1162 static extern int uname (IntPtr buf);
1164 static void DetectOS ()
1167 os_message = "OS is: Windows";
1172 IntPtr buf = Marshal.AllocHGlobal (8192);
1173 if (uname (buf) != 0){
1174 os_message = "Warning: Unable to detect OS";
1175 Marshal.FreeHGlobal (buf);
1178 string os = Marshal.PtrToStringAnsi (buf);
1179 os_message = "OS is: " + os;
1183 Marshal.FreeHGlobal (buf);
1186 static bool IsUnix {
1188 int p = (int) Environment.OSVersion.Platform;
1189 return ((p == 4) || (p == 128) || (p == 6));
1193 static void Execute (string cmdLine)
1197 Console.WriteLine ("[execute cmd]: " + cmdLine);
1198 int ret = system (cmdLine);
1201 Error(String.Format("[Fail] {0}", ret));
1206 // on Windows, we have to pipe the output of a
1207 // `cmd` interpolation to dos2unix, because the shell does not
1208 // strip the CRLFs generated by the native pkg-config distributed
1211 // But if it's *not* on cygwin, just skip it.
1213 // check if dos2unix is applicable.
1214 if (use_dos2unix == true)
1216 var info = new ProcessStartInfo ("dos2unix");
1217 info.CreateNoWindow = true;
1218 info.RedirectStandardInput = true;
1219 info.UseShellExecute = false;
1220 var dos2unix = Process.Start (info);
1221 dos2unix.StandardInput.WriteLine ("aaa");
1222 dos2unix.StandardInput.WriteLine ("\u0004");
1223 dos2unix.StandardInput.Close ();
1224 dos2unix.WaitForExit ();
1225 if (dos2unix.ExitCode == 0)
1226 use_dos2unix = true;
1228 Console.WriteLine("Warning: dos2unix not found");
1229 use_dos2unix = false;
1232 if (use_dos2unix == null)
1233 use_dos2unix = false;
1235 ProcessStartInfo psi = new ProcessStartInfo();
1236 psi.UseShellExecute = false;
1238 // if there is no dos2unix, just run cmd /c.
1239 if (use_dos2unix == false)
1241 psi.FileName = "cmd";
1242 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1246 psi.FileName = "sh";
1247 StringBuilder b = new StringBuilder();
1249 for (int i = 0; i < cmdLine.Length; i++)
1251 if (cmdLine[i] == '`')
1255 b.Append("|dos2unix");
1259 b.Append(cmdLine[i]);
1261 cmdLine = b.ToString();
1262 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1266 Console.WriteLine(cmdLine);
1267 using (Process p = Process.Start (psi)) {
1269 int ret = p.ExitCode;
1271 Error (String.Format("[Fail] {0}", ret));
1276 static string GetEnv(string name, string defaultValue)
1278 string val = Environment.GetEnvironmentVariable(name);
1282 Console.WriteLine("{0} = {1}", name, val);
1288 Console.WriteLine("{0} = {1} (default)", name, val);
1293 static string LocateFile(string default_path)
1295 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1296 if (File.Exists(override_path))
1297 return override_path;
1298 else if (File.Exists(default_path))
1299 return default_path;
1301 throw new FileNotFoundException(default_path);