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
12 using System.Diagnostics;
14 using System.Collections.Generic;
16 using System.IO.Compression;
17 using System.Runtime.InteropServices;
19 using IKVM.Reflection;
22 using System.Threading.Tasks;
25 static string output = "a.out";
26 static string object_out = null;
27 static List<string> link_paths = new List<string> ();
28 static bool autodeps = false;
29 static bool keeptemp = false;
30 static bool compile_only = false;
31 static bool static_link = false;
32 static string config_file = null;
33 static string machine_config_file = null;
34 static string config_dir = null;
35 static string style = "linux";
36 static string os_message = "";
39 static string custom_main = null;
40 static bool? use_dos2unix = null;
41 static bool skip_scan;
42 static string ctor_func;
45 static int Main (string [] args)
47 List<string> sources = new List<string> ();
48 int top = args.Length;
53 for (int i = 0; i < top; i++){
55 case "--help": case "-h": case "-?":
76 object_out = args [++i];
84 link_paths.Add (args [++i]);
107 config_file = args [++i];
109 case "--machine-config":
115 machine_config_file = args [++i];
118 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
126 config_dir = args [++i];
134 case "--custom-main":
139 custom_main = args [++i];
153 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
161 case "--static-ctor":
166 ctor_func = args [++i];
169 case "--dos2unix=true":
172 case "--dos2unix=false":
173 use_dos2unix = false;
180 sources.Add (args [i]);
187 Console.WriteLine (os_message);
188 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
190 if (sources.Count == 0 || output == null) {
192 Environment.Exit (1);
195 List<string> assemblies = LoadAssemblies (sources);
196 List<string> files = new List<string> ();
197 foreach (string file in assemblies)
198 if (!QueueAssembly (files, file))
201 GenerateBundles (files);
202 //GenerateJitWrapper ();
207 static void WriteSymbol (StreamWriter sw, string name, long size)
213 "\t.section .rodata\n" +
215 "\t.type {0}, \"object\"\n" +
216 "\t.size {0}, {1}\n" +
222 "\t.section __TEXT,__text,regular,pure_instructions\n" +
232 "\t.section .rdata,\"dr\"\n" +
240 static string [] chars = new string [256];
242 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
246 // Preallocate the strings we need.
247 if (chars [0] == null) {
248 for (int i = 0; i < chars.Length; i++)
249 chars [i] = string.Format ("{0}", i.ToString ());
252 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
254 for (int i = 0; i < n; i++) {
255 if (count % 32 == 0) {
256 ts.Write ("\n\t.byte ");
260 ts.Write (chars [buffer [i]]);
268 static void GenerateBundles (List<string> files)
270 string temp_s = "temp.s"; // Path.GetTempFileName ();
271 string temp_c = "temp.c";
272 string temp_o = "temp.o";
276 if (object_out != null)
280 List<string> c_bundle_names = new List<string> ();
281 List<string[]> config_names = new List<string[]> ();
283 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
284 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
288 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
289 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
293 const unsigned char *data;
294 const unsigned int size;
295 } MonoBundledAssembly;
296 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
297 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
300 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
301 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
305 tc.WriteLine ("typedef struct _compressed_data {");
306 tc.WriteLine ("\tMonoBundledAssembly assembly;");
307 tc.WriteLine ("\tint compressed_size;");
308 tc.WriteLine ("} CompressedAssembly;\n");
311 object monitor = new object ();
313 var streams = new Dictionary<string, Stream> ();
314 var sizes = new Dictionary<string, long> ();
316 // Do the file reading and compression in parallel
317 Action<string> body = delegate (string url) {
318 string fname = LocateFile (new Uri (url).LocalPath);
319 Stream stream = File.OpenRead (fname);
321 long real_size = stream.Length;
324 byte[] cbuffer = new byte [8192];
325 MemoryStream ms = new MemoryStream ();
326 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
327 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
328 deflate.Write (cbuffer, 0, n);
332 byte [] bytes = ms.GetBuffer ();
333 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
337 streams [url] = stream;
338 sizes [url] = real_size;
344 Parallel.ForEach (files, body);
346 foreach (var url in files)
350 // The non-parallel part
351 byte [] buffer = new byte [8192];
352 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
353 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
354 foreach (var url in files) {
355 string fname = LocateFile (new Uri (url).LocalPath);
356 string aname = Path.GetFileName (fname);
357 string encoded = symbolEscapeRE.Replace (aname, "_");
362 var stream = streams [url];
363 var real_size = sizes [url];
366 Console.WriteLine (" embedding: " + fname);
368 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
370 WriteBuffer (ts, stream, buffer);
373 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
374 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
375 " assembly_data_{0}, {2}}}, {3}}};",
376 encoded, aname, real_size, stream.Length);
378 double ratio = ((double) stream.Length * 100) / real_size;
379 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
382 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
383 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
384 encoded, aname, real_size);
388 c_bundle_names.Add ("assembly_bundle_" + encoded);
391 FileStream cf = File.OpenRead (fname + ".config");
393 Console.WriteLine (" config from: " + fname + ".config");
394 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
395 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
396 WriteBuffer (ts, cf, buffer);
398 config_names.Add (new string[] {aname, encoded});
399 } catch (FileNotFoundException) {
400 /* we ignore if the config file doesn't exist */
404 if (config_file != null){
407 conf = File.OpenRead (config_file);
409 Error (String.Format ("Failure to open {0}", config_file));
413 Console.WriteLine ("System config from: " + config_file);
414 tc.WriteLine ("extern const char system_config;");
415 WriteSymbol (ts, "system_config", config_file.Length);
417 WriteBuffer (ts, conf, buffer);
419 ts.Write ("\t.byte 0\n");
423 if (machine_config_file != null){
426 conf = File.OpenRead (machine_config_file);
428 Error (String.Format ("Failure to open {0}", machine_config_file));
432 Console.WriteLine ("Machine config from: " + machine_config_file);
433 tc.WriteLine ("extern const char machine_config;");
434 WriteSymbol (ts, "machine_config", machine_config_file.Length);
436 WriteBuffer (ts, conf, buffer);
437 ts.Write ("\t.byte 0\n");
443 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
445 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
447 foreach (string c in c_bundle_names){
448 tc.WriteLine ("\t&{0},", c);
450 tc.WriteLine ("\tNULL\n};\n");
451 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
453 if (ctor_func != null) {
454 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
455 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
456 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
459 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
460 foreach (string[] ass in config_names){
461 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
463 if (config_file != null)
464 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
465 if (machine_config_file != null)
466 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
467 tc.WriteLine ("}\n");
469 if (config_dir != null)
470 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
472 tc.WriteLine ("static const char *config_dir = NULL;");
474 Stream template_stream;
476 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
478 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
481 StreamReader s = new StreamReader (template_stream);
482 string template = s.ReadToEnd ();
485 if (!nomain && custom_main == null) {
486 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
487 StreamReader st = new StreamReader (template_main_stream);
488 string maintemplate = st.ReadToEnd ();
489 tc.Write (maintemplate);
494 string assembler = GetEnv("AS", "as");
495 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
502 Console.WriteLine("Compiling:");
504 if (style == "windows")
507 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
509 string compiler = GetEnv("CC", "cl.exe");
510 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
511 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
512 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
514 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
515 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
516 var linkLibraries = new string[] { "kernel32.lib",
531 string glue_obj = "mkbundle_glue.obj";
535 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
538 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
539 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
540 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
543 var compilerArgs = new List<string>();
544 compilerArgs.Add("/MT");
546 foreach (string include in includes)
547 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
549 if (!nomain || custom_main != null) {
550 compilerArgs.Add(quote(temp_c));
551 compilerArgs.Add(quote(temp_o));
552 if (custom_main != null)
553 compilerArgs.Add(quote(custom_main));
554 compilerArgs.Add(quote(monoLib));
555 compilerArgs.Add("/link");
556 compilerArgs.Add("/NODEFAULTLIB");
557 compilerArgs.Add("/SUBSYSTEM:windows");
558 compilerArgs.Add("/ENTRY:mainCRTStartup");
559 compilerArgs.AddRange(linkLibraries);
560 compilerArgs.Add("/out:"+ output);
562 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
567 // we are just creating a .lib
568 compilerArgs.Add("/c"); // compile only
569 compilerArgs.Add(temp_c);
570 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
572 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
575 string librarian = GetEnv ("LIB", "lib.exe");
576 var librarianArgs = new List<string> ();
577 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
578 librarianArgs.Add (temp_o);
579 librarianArgs.Add (glue_obj);
580 librarianArgs.Add (monoLib);
581 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
587 string zlib = (compress ? "-lz" : "");
588 string debugging = "-g";
589 string cc = GetEnv("CC", "cc");
592 if (style == "linux")
598 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
600 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
601 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
602 "`pkg-config --libs-only-L mono-2` " + smonolib +
603 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
604 temp_c, temp_o, output, zlib, cc);
609 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
610 temp_c, temp_o, output, zlib, cc);
616 Console.WriteLine ("Done");
621 if (object_out == null){
622 File.Delete (temp_o);
625 File.Delete (temp_c);
627 File.Delete (temp_s);
632 static List<string> LoadAssemblies (List<string> sources)
634 List<string> assemblies = new List<string> ();
637 foreach (string name in sources){
639 Assembly a = LoadAssembly (name);
646 assemblies.Add (a.CodeBase);
647 } catch (Exception) {
650 Console.WriteLine ("File will not be scanned: {0}", name);
651 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
659 Environment.Exit (1);
664 static readonly Universe universe = new Universe ();
665 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
667 static bool QueueAssembly (List<string> files, string codebase)
669 // Console.WriteLine ("CODE BASE IS {0}", codebase);
670 if (files.Contains (codebase))
673 var path = new Uri(codebase).LocalPath;
674 var name = Path.GetFileName (path);
676 if (loaded_assemblies.TryGetValue (name, out found)) {
677 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
681 loaded_assemblies.Add (name, path);
683 files.Add (codebase);
687 Assembly a = universe.LoadFile (path);
689 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
690 a = universe.Load (an.FullName);
691 if (!QueueAssembly (files, a.CodeBase))
694 } catch (Exception) {
702 static Assembly LoadAssembly (string assembly)
707 char[] path_chars = { '/', '\\' };
709 if (assembly.IndexOfAny (path_chars) != -1) {
710 a = universe.LoadFile (assembly);
712 string ass = assembly;
713 if (ass.EndsWith (".dll"))
714 ass = assembly.Substring (0, assembly.Length - 4);
715 a = universe.Load (ass);
718 } catch (FileNotFoundException){
719 string total_log = "";
721 foreach (string dir in link_paths){
722 string full_path = Path.Combine (dir, assembly);
723 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
727 a = universe.LoadFile (full_path);
729 } catch (FileNotFoundException ff) {
730 total_log += ff.FusionLog;
734 Error ("Cannot find assembly `" + assembly + "'" );
736 Console.WriteLine ("Log: \n" + total_log);
737 } catch (IKVM.Reflection.BadImageFormatException f) {
740 Error ("Cannot load assembly (bad file format) " + f.Message);
741 } catch (FileLoadException f){
742 Error ("Cannot load assembly " + f.Message);
743 } catch (ArgumentNullException){
744 Error("Cannot load assembly (null argument)");
749 static void Error (string msg)
751 Console.Error.WriteLine ("ERROR: " + msg);
752 Environment.Exit (1);
757 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
759 " -c Produce stub only, do not compile\n" +
760 " -o out Specifies output filename\n" +
761 " -oo obj Specifies output filename for helper object file\n" +
762 " -L path Adds `path' to the search path for assemblies\n" +
763 " --nodeps Turns off automatic dependency embedding (default)\n" +
764 " --deps Turns on automatic dependency embedding\n" +
765 " --dos2unix[=true|false]\n" +
766 " When no value provided, or when `true` specified\n" +
767 " `dos2unix` will be invoked to convert paths on Windows.\n" +
768 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
769 " --keeptemp Keeps the temporary files\n" +
770 " --config F Bundle system config file `F'\n" +
771 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
772 " --machine-config F Use the given file as the machine.config for the application.\n" +
773 " --static Statically link to mono libs\n" +
774 " --nomain Don't include a main() function, for libraries\n" +
775 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
776 " -z Compress the assemblies before embedding.\n" +
777 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
778 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
779 " You need zlib development headers and libraries.\n");
783 static extern int system (string s);
785 static extern int uname (IntPtr buf);
787 static void DetectOS ()
790 os_message = "OS is: Windows";
795 IntPtr buf = Marshal.AllocHGlobal (8192);
796 if (uname (buf) != 0){
797 os_message = "Warning: Unable to detect OS";
798 Marshal.FreeHGlobal (buf);
801 string os = Marshal.PtrToStringAnsi (buf);
802 os_message = "OS is: " + os;
806 Marshal.FreeHGlobal (buf);
811 int p = (int) Environment.OSVersion.Platform;
812 return ((p == 4) || (p == 128) || (p == 6));
816 static void Execute (string cmdLine)
820 Console.WriteLine ("[execute cmd]: " + cmdLine);
821 int ret = system (cmdLine);
824 Error(String.Format("[Fail] {0}", ret));
829 // on Windows, we have to pipe the output of a
830 // `cmd` interpolation to dos2unix, because the shell does not
831 // strip the CRLFs generated by the native pkg-config distributed
834 // But if it's *not* on cygwin, just skip it.
836 // check if dos2unix is applicable.
837 if (use_dos2unix == true)
839 var info = new ProcessStartInfo ("dos2unix");
840 info.CreateNoWindow = true;
841 info.RedirectStandardInput = true;
842 info.UseShellExecute = false;
843 var dos2unix = Process.Start (info);
844 dos2unix.StandardInput.WriteLine ("aaa");
845 dos2unix.StandardInput.WriteLine ("\u0004");
846 dos2unix.StandardInput.Close ();
847 dos2unix.WaitForExit ();
848 if (dos2unix.ExitCode == 0)
851 Console.WriteLine("Warning: dos2unix not found");
852 use_dos2unix = false;
855 if (use_dos2unix == null)
856 use_dos2unix = false;
858 ProcessStartInfo psi = new ProcessStartInfo();
859 psi.UseShellExecute = false;
861 // if there is no dos2unix, just run cmd /c.
862 if (use_dos2unix == false)
864 psi.FileName = "cmd";
865 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
870 StringBuilder b = new StringBuilder();
872 for (int i = 0; i < cmdLine.Length; i++)
874 if (cmdLine[i] == '`')
878 b.Append("|dos2unix");
882 b.Append(cmdLine[i]);
884 cmdLine = b.ToString();
885 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
889 Console.WriteLine(cmdLine);
890 using (Process p = Process.Start (psi)) {
892 int ret = p.ExitCode;
894 Error (String.Format("[Fail] {0}", ret));
899 static string GetEnv(string name, string defaultValue)
901 string val = Environment.GetEnvironmentVariable(name);
905 Console.WriteLine("{0} = {1}", name, val);
911 Console.WriteLine("{0} = {1} (default)", name, val);
916 static string LocateFile(string default_path)
918 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
919 if (File.Exists(override_path))
920 return override_path;
921 else if (File.Exists(default_path))
924 throw new FileNotFoundException(default_path);