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]);
101 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
102 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
111 config_file = args [++i];
113 case "--machine-config":
119 machine_config_file = args [++i];
122 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
130 config_dir = args [++i];
138 case "--custom-main":
143 custom_main = args [++i];
157 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
165 case "--static-ctor":
170 ctor_func = args [++i];
173 case "--dos2unix=true":
176 case "--dos2unix=false":
177 use_dos2unix = false;
184 sources.Add (args [i]);
191 Console.WriteLine (os_message);
192 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
194 if (sources.Count == 0 || output == null) {
196 Environment.Exit (1);
199 List<string> assemblies = LoadAssemblies (sources);
200 List<string> files = new List<string> ();
201 foreach (string file in assemblies)
202 if (!QueueAssembly (files, file))
205 GenerateBundles (files);
206 //GenerateJitWrapper ();
211 static void WriteSymbol (StreamWriter sw, string name, long size)
217 "\t.section .rodata\n" +
219 "\t.type {0}, \"object\"\n" +
220 "\t.size {0}, {1}\n" +
226 "\t.section __TEXT,__text,regular,pure_instructions\n" +
236 "\t.section .rdata,\"dr\"\n" +
244 static string [] chars = new string [256];
246 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
250 // Preallocate the strings we need.
251 if (chars [0] == null) {
252 for (int i = 0; i < chars.Length; i++)
253 chars [i] = string.Format ("{0}", i.ToString ());
256 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
258 for (int i = 0; i < n; i++) {
259 if (count % 32 == 0) {
260 ts.Write ("\n\t.byte ");
264 ts.Write (chars [buffer [i]]);
272 static void GenerateBundles (List<string> files)
274 string temp_s = "temp.s"; // Path.GetTempFileName ();
275 string temp_c = "temp.c";
276 string temp_o = "temp.o";
280 if (object_out != null)
284 List<string> c_bundle_names = new List<string> ();
285 List<string[]> config_names = new List<string[]> ();
287 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
288 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
292 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
293 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
297 const unsigned char *data;
298 const unsigned int size;
299 } MonoBundledAssembly;
300 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
301 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
304 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
305 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
309 tc.WriteLine ("typedef struct _compressed_data {");
310 tc.WriteLine ("\tMonoBundledAssembly assembly;");
311 tc.WriteLine ("\tint compressed_size;");
312 tc.WriteLine ("} CompressedAssembly;\n");
315 object monitor = new object ();
317 var streams = new Dictionary<string, Stream> ();
318 var sizes = new Dictionary<string, long> ();
320 // Do the file reading and compression in parallel
321 Action<string> body = delegate (string url) {
322 string fname = LocateFile (new Uri (url).LocalPath);
323 Stream stream = File.OpenRead (fname);
325 long real_size = stream.Length;
328 byte[] cbuffer = new byte [8192];
329 MemoryStream ms = new MemoryStream ();
330 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
331 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
332 deflate.Write (cbuffer, 0, n);
336 byte [] bytes = ms.GetBuffer ();
337 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
341 streams [url] = stream;
342 sizes [url] = real_size;
348 Parallel.ForEach (files, body);
350 foreach (var url in files)
354 // The non-parallel part
355 byte [] buffer = new byte [8192];
356 foreach (var url in files) {
357 string fname = LocateFile (new Uri (url).LocalPath);
358 string aname = Path.GetFileName (fname);
359 string encoded = aname.Replace ("-", "_").Replace (".", "_");
364 var stream = streams [url];
365 var real_size = sizes [url];
368 Console.WriteLine (" embedding: " + fname);
370 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
372 WriteBuffer (ts, stream, buffer);
375 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
376 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
377 " assembly_data_{0}, {2}}}, {3}}};",
378 encoded, aname, real_size, stream.Length);
380 double ratio = ((double) stream.Length * 100) / real_size;
381 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
384 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
385 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
386 encoded, aname, real_size);
390 c_bundle_names.Add ("assembly_bundle_" + encoded);
393 FileStream cf = File.OpenRead (fname + ".config");
395 Console.WriteLine (" config from: " + fname + ".config");
396 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
397 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
398 WriteBuffer (ts, cf, buffer);
400 config_names.Add (new string[] {aname, encoded});
401 } catch (FileNotFoundException) {
402 /* we ignore if the config file doesn't exist */
406 if (config_file != null){
409 conf = File.OpenRead (config_file);
411 Error (String.Format ("Failure to open {0}", config_file));
415 Console.WriteLine ("System config from: " + config_file);
416 tc.WriteLine ("extern const char system_config;");
417 WriteSymbol (ts, "system_config", config_file.Length);
419 WriteBuffer (ts, conf, buffer);
421 ts.Write ("\t.byte 0\n");
425 if (machine_config_file != null){
428 conf = File.OpenRead (machine_config_file);
430 Error (String.Format ("Failure to open {0}", machine_config_file));
434 Console.WriteLine ("Machine config from: " + machine_config_file);
435 tc.WriteLine ("extern const char machine_config;");
436 WriteSymbol (ts, "machine_config", machine_config_file.Length);
438 WriteBuffer (ts, conf, buffer);
439 ts.Write ("\t.byte 0\n");
445 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
447 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
449 foreach (string c in c_bundle_names){
450 tc.WriteLine ("\t&{0},", c);
452 tc.WriteLine ("\tNULL\n};\n");
453 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
455 if (ctor_func != null) {
456 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
457 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
458 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
461 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
462 foreach (string[] ass in config_names){
463 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
465 if (config_file != null)
466 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
467 if (machine_config_file != null)
468 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
469 tc.WriteLine ("}\n");
471 if (config_dir != null)
472 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
474 tc.WriteLine ("static const char *config_dir = NULL;");
476 Stream template_stream;
478 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
480 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
483 StreamReader s = new StreamReader (template_stream);
484 string template = s.ReadToEnd ();
487 if (!nomain && custom_main == null) {
488 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
489 StreamReader st = new StreamReader (template_main_stream);
490 string maintemplate = st.ReadToEnd ();
491 tc.Write (maintemplate);
496 string assembler = GetEnv("AS", "as");
497 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
504 Console.WriteLine("Compiling:");
506 if (style == "windows")
509 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
511 string compiler = GetEnv("CC", "cl.exe");
512 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
513 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
514 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
516 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
517 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
518 var linkLibraries = new string[] { "kernel32.lib",
533 string glue_obj = "mkbundle_glue.obj";
537 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
540 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
541 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
542 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
545 var compilerArgs = new List<string>();
546 compilerArgs.Add("/MT");
548 foreach (string include in includes)
549 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
551 if (!nomain || custom_main != null) {
552 compilerArgs.Add(temp_c);
553 compilerArgs.Add(temp_o);
554 if (custom_main != null)
555 compilerArgs.Add(quote(custom_main));
556 compilerArgs.Add(monoLib);
557 compilerArgs.Add("/link");
558 compilerArgs.Add("/NODEFAULTLIB");
559 compilerArgs.Add("/SUBSYSTEM:CONSOLE");
560 compilerArgs.AddRange(linkLibraries);
561 compilerArgs.Add("/out:"+ output);
563 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
568 // we are just creating a .lib
569 compilerArgs.Add("/c"); // compile only
570 compilerArgs.Add(temp_c);
571 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
573 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
576 string librarian = GetEnv ("LIB", "lib.exe");
577 var librarianArgs = new List<string> ();
578 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
579 librarianArgs.Add (temp_o);
580 librarianArgs.Add (glue_obj);
581 librarianArgs.Add (monoLib);
582 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
588 string zlib = (compress ? "-lz" : "");
589 string debugging = "-g";
590 string cc = GetEnv("CC", "cc");
593 if (style == "linux")
599 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
601 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
602 cmd = String.Format("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
603 "`pkg-config --libs-only-L mono-2` " + smonolib +
604 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
605 temp_c, temp_o, output, zlib, cc);
610 cmd = String.Format("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
611 temp_c, temp_o, output, zlib, cc);
617 Console.WriteLine ("Done");
622 if (object_out == null){
623 File.Delete (temp_o);
626 File.Delete (temp_c);
628 File.Delete (temp_s);
633 static List<string> LoadAssemblies (List<string> sources)
635 List<string> assemblies = new List<string> ();
638 foreach (string name in sources){
640 Assembly a = LoadAssembly (name);
647 assemblies.Add (a.CodeBase);
648 } catch (Exception) {
651 Console.WriteLine ("File will not be scanned: {0}", name);
652 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
660 Environment.Exit (1);
665 static readonly Universe universe = new Universe ();
666 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
668 static bool QueueAssembly (List<string> files, string codebase)
670 // Console.WriteLine ("CODE BASE IS {0}", codebase);
671 if (files.Contains (codebase))
674 var path = new Uri(codebase).LocalPath;
675 var name = Path.GetFileName (path);
677 if (loaded_assemblies.TryGetValue (name, out found)) {
678 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
682 loaded_assemblies.Add (name, path);
684 files.Add (codebase);
688 Assembly a = universe.LoadFile (path);
690 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
691 a = universe.Load (an.FullName);
692 if (!QueueAssembly (files, a.CodeBase))
695 } catch (Exception) {
703 static Assembly LoadAssembly (string assembly)
708 char[] path_chars = { '/', '\\' };
710 if (assembly.IndexOfAny (path_chars) != -1) {
711 a = universe.LoadFile (assembly);
713 string ass = assembly;
714 if (ass.EndsWith (".dll"))
715 ass = assembly.Substring (0, assembly.Length - 4);
716 a = universe.Load (ass);
719 } catch (FileNotFoundException){
720 string total_log = "";
722 foreach (string dir in link_paths){
723 string full_path = Path.Combine (dir, assembly);
724 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
728 a = universe.LoadFile (full_path);
730 } catch (FileNotFoundException ff) {
731 total_log += ff.FusionLog;
735 Error ("Cannot find assembly `" + assembly + "'" );
737 Console.WriteLine ("Log: \n" + total_log);
738 } catch (IKVM.Reflection.BadImageFormatException f) {
741 Error ("Cannot load assembly (bad file format) " + f.Message);
742 } catch (FileLoadException f){
743 Error ("Cannot load assembly " + f.Message);
744 } catch (ArgumentNullException){
745 Error("Cannot load assembly (null argument)");
750 static void Error (string msg)
752 Console.Error.WriteLine ("ERROR: " + msg);
753 Environment.Exit (1);
758 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
760 " -c Produce stub only, do not compile\n" +
761 " -o out Specifies output filename\n" +
762 " -oo obj Specifies output filename for helper object file\n" +
763 " -L path Adds `path' to the search path for assemblies\n" +
764 " --nodeps Turns off automatic dependency embedding (default)\n" +
765 " --deps Turns on automatic dependency embedding\n" +
766 " --dos2unix[=true|false]\n" +
767 " When no value provided, or when `true` specified\n" +
768 " `dos2unix` will be invoked to convert paths on Windows.\n" +
769 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
770 " --keeptemp Keeps the temporary files\n" +
771 " --config F Bundle system config file `F'\n" +
772 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
773 " --machine-config F Use the given file as the machine.config for the application.\n" +
774 " --static Statically link to mono libs\n" +
775 " --nomain Don't include a main() function, for libraries\n" +
776 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
777 " -z Compress the assemblies before embedding.\n" +
778 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
779 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
780 " You need zlib development headers and libraries.\n");
784 static extern int system (string s);
786 static extern int uname (IntPtr buf);
788 static void DetectOS ()
791 os_message = "OS is: Windows";
796 IntPtr buf = Marshal.AllocHGlobal (8192);
797 if (uname (buf) != 0){
798 os_message = "Warning: Unable to detect OS";
799 Marshal.FreeHGlobal (buf);
802 string os = Marshal.PtrToStringAnsi (buf);
803 os_message = "OS is: " + os;
807 Marshal.FreeHGlobal (buf);
812 int p = (int) Environment.OSVersion.Platform;
813 return ((p == 4) || (p == 128) || (p == 6));
817 static void Execute (string cmdLine)
821 Console.WriteLine ("[execute cmd]: " + cmdLine);
822 int ret = system (cmdLine);
825 Error(String.Format("[Fail] {0}", ret));
830 // on Windows, we have to pipe the output of a
831 // `cmd` interpolation to dos2unix, because the shell does not
832 // strip the CRLFs generated by the native pkg-config distributed
835 // But if it's *not* on cygwin, just skip it.
837 // check if dos2unix is applicable.
838 if (use_dos2unix == true)
840 var info = new ProcessStartInfo ("dos2unix");
841 info.CreateNoWindow = true;
842 info.RedirectStandardInput = true;
843 info.UseShellExecute = false;
844 var dos2unix = Process.Start (info);
845 dos2unix.StandardInput.WriteLine ("aaa");
846 dos2unix.StandardInput.WriteLine ("\u0004");
847 dos2unix.StandardInput.Close ();
848 dos2unix.WaitForExit ();
849 if (dos2unix.ExitCode == 0)
852 Console.WriteLine("Warning: dos2unix not found");
853 use_dos2unix = false;
856 if (use_dos2unix == null)
857 use_dos2unix = false;
859 ProcessStartInfo psi = new ProcessStartInfo();
860 psi.UseShellExecute = false;
862 // if there is no dos2unix, just run cmd /c.
863 if (use_dos2unix == false)
865 psi.FileName = "cmd";
866 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
871 StringBuilder b = new StringBuilder();
873 for (int i = 0; i < cmdLine.Length; i++)
875 if (cmdLine[i] == '`')
879 b.Append("|dos2unix");
883 b.Append(cmdLine[i]);
885 cmdLine = b.ToString();
886 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
890 Console.WriteLine(cmdLine);
891 using (Process p = Process.Start (psi)) {
893 int ret = p.ExitCode;
895 Error (String.Format("[Fail] {0}", ret));
900 static string GetEnv(string name, string defaultValue)
902 string val = Environment.GetEnvironmentVariable(name);
906 Console.WriteLine("{0} = {1}", name, val);
912 Console.WriteLine("{0} = {1} (default)", name, val);
917 static string LocateFile(string default_path)
919 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
920 if (File.Exists(override_path))
921 return override_path;
922 else if (File.Exists(default_path))
925 throw new FileNotFoundException(default_path);