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 bool? use_dos2unix = null;
40 static bool skip_scan;
41 static string ctor_func;
44 static int Main (string [] args)
46 List<string> sources = new List<string> ();
47 int top = args.Length;
52 for (int i = 0; i < top; i++){
54 case "--help": case "-h": case "-?":
75 object_out = args [++i];
83 link_paths.Add (args [++i]);
100 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
101 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
110 config_file = args [++i];
112 case "--machine-config":
118 machine_config_file = args [++i];
121 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
129 config_dir = args [++i];
149 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
157 case "--static-ctor":
162 ctor_func = args [++i];
165 case "--dos2unix=true":
168 case "--dos2unix=false":
169 use_dos2unix = false;
176 sources.Add (args [i]);
183 Console.WriteLine (os_message);
184 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
186 if (sources.Count == 0 || output == null) {
188 Environment.Exit (1);
191 List<string> assemblies = LoadAssemblies (sources);
192 List<string> files = new List<string> ();
193 foreach (string file in assemblies)
194 if (!QueueAssembly (files, file))
197 GenerateBundles (files);
198 //GenerateJitWrapper ();
203 static void WriteSymbol (StreamWriter sw, string name, long size)
209 "\t.section .rodata\n" +
211 "\t.type {0}, \"object\"\n" +
212 "\t.size {0}, {1}\n" +
218 "\t.section __TEXT,__text,regular,pure_instructions\n" +
228 "\t.section .rdata,\"dr\"\n" +
236 static string [] chars = new string [256];
238 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
242 // Preallocate the strings we need.
243 if (chars [0] == null) {
244 for (int i = 0; i < chars.Length; i++)
245 chars [i] = string.Format ("{0}", i.ToString ());
248 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
250 for (int i = 0; i < n; i++) {
251 if (count % 32 == 0) {
252 ts.Write ("\n\t.byte ");
256 ts.Write (chars [buffer [i]]);
264 static void GenerateBundles (List<string> files)
266 string temp_s = "temp.s"; // Path.GetTempFileName ();
267 string temp_c = "temp.c";
268 string temp_o = "temp.o";
272 if (object_out != null)
276 List<string> c_bundle_names = new List<string> ();
277 List<string[]> config_names = new List<string[]> ();
279 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
280 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
284 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
285 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
289 const unsigned char *data;
290 const unsigned int size;
291 } MonoBundledAssembly;
292 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
293 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
296 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
297 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
301 tc.WriteLine ("typedef struct _compressed_data {");
302 tc.WriteLine ("\tMonoBundledAssembly assembly;");
303 tc.WriteLine ("\tint compressed_size;");
304 tc.WriteLine ("} CompressedAssembly;\n");
307 object monitor = new object ();
309 var streams = new Dictionary<string, Stream> ();
310 var sizes = new Dictionary<string, long> ();
312 // Do the file reading and compression in parallel
313 Action<string> body = delegate (string url) {
314 string fname = LocateFile (new Uri (url).LocalPath);
315 Stream stream = File.OpenRead (fname);
317 long real_size = stream.Length;
320 byte[] cbuffer = new byte [8192];
321 MemoryStream ms = new MemoryStream ();
322 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
323 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
324 deflate.Write (cbuffer, 0, n);
328 byte [] bytes = ms.GetBuffer ();
329 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
333 streams [url] = stream;
334 sizes [url] = real_size;
340 Parallel.ForEach (files, body);
342 foreach (var url in files)
346 // The non-parallel part
347 byte [] buffer = new byte [8192];
348 foreach (var url in files) {
349 string fname = LocateFile (new Uri (url).LocalPath);
350 string aname = Path.GetFileName (fname);
351 string encoded = aname.Replace ("-", "_").Replace (".", "_");
356 var stream = streams [url];
357 var real_size = sizes [url];
360 Console.WriteLine (" embedding: " + fname);
362 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
364 WriteBuffer (ts, stream, buffer);
367 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
368 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
369 " assembly_data_{0}, {2}}}, {3}}};",
370 encoded, aname, real_size, stream.Length);
372 double ratio = ((double) stream.Length * 100) / real_size;
373 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
376 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
377 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
378 encoded, aname, real_size);
382 c_bundle_names.Add ("assembly_bundle_" + encoded);
385 FileStream cf = File.OpenRead (fname + ".config");
387 Console.WriteLine (" config from: " + fname + ".config");
388 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
389 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
390 WriteBuffer (ts, cf, buffer);
392 config_names.Add (new string[] {aname, encoded});
393 } catch (FileNotFoundException) {
394 /* we ignore if the config file doesn't exist */
398 if (config_file != null){
401 conf = File.OpenRead (config_file);
403 Error (String.Format ("Failure to open {0}", config_file));
407 Console.WriteLine ("System config from: " + config_file);
408 tc.WriteLine ("extern const char system_config;");
409 WriteSymbol (ts, "system_config", config_file.Length);
411 WriteBuffer (ts, conf, buffer);
413 ts.Write ("\t.byte 0\n");
417 if (machine_config_file != null){
420 conf = File.OpenRead (machine_config_file);
422 Error (String.Format ("Failure to open {0}", machine_config_file));
426 Console.WriteLine ("Machine config from: " + machine_config_file);
427 tc.WriteLine ("extern const char machine_config;");
428 WriteSymbol (ts, "machine_config", machine_config_file.Length);
430 WriteBuffer (ts, conf, buffer);
431 ts.Write ("\t.byte 0\n");
437 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
439 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
441 foreach (string c in c_bundle_names){
442 tc.WriteLine ("\t&{0},", c);
444 tc.WriteLine ("\tNULL\n};\n");
445 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
447 if (ctor_func != null) {
448 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
449 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
450 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
453 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
454 foreach (string[] ass in config_names){
455 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
457 if (config_file != null)
458 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
459 if (machine_config_file != null)
460 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
461 tc.WriteLine ("}\n");
463 if (config_dir != null)
464 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
466 tc.WriteLine ("static const char *config_dir = NULL;");
468 Stream template_stream;
470 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
472 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
475 StreamReader s = new StreamReader (template_stream);
476 string template = s.ReadToEnd ();
480 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
481 StreamReader st = new StreamReader (template_main_stream);
482 string maintemplate = st.ReadToEnd ();
483 tc.Write (maintemplate);
488 string assembler = GetEnv("AS", "as");
489 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
496 Console.WriteLine("Compiling:");
498 if (style == "windows")
501 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
503 string compiler = GetEnv("CC", "cl.exe");
504 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
505 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC");
506 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
508 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0"};
509 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
512 var compilerArgs = new List<string>();
513 foreach (string include in includes)
514 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
517 monoFile = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
519 monoFile = LocateFile (monoPath + @"\lib\monosgen-2.0.dll");
521 compilerArgs.Add("/MD");
522 compilerArgs.Add(temp_c);
523 compilerArgs.Add(temp_o);
524 compilerArgs.Add("/link");
527 compilerArgs.Add("/NOENTRY");
528 compilerArgs.Add("/DLL");
530 foreach (string lib in libs)
531 compilerArgs.Add(String.Format ("/LIBPATH:{0}", quote(lib)));
532 compilerArgs.Add (quote(monoFile));
534 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
539 string zlib = (compress ? "-lz" : "");
540 string debugging = "-g";
541 string cc = GetEnv("CC", "cc");
544 if (style == "linux")
550 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
552 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
553 cmd = String.Format("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
554 "`pkg-config --libs-only-L mono-2` " + smonolib +
555 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
556 temp_c, temp_o, output, zlib, cc);
561 cmd = String.Format("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
562 temp_c, temp_o, output, zlib, cc);
568 Console.WriteLine ("Done");
573 if (object_out == null){
574 File.Delete (temp_o);
577 File.Delete (temp_c);
579 File.Delete (temp_s);
584 static List<string> LoadAssemblies (List<string> sources)
586 List<string> assemblies = new List<string> ();
589 foreach (string name in sources){
591 Assembly a = LoadAssembly (name);
598 assemblies.Add (a.CodeBase);
599 } catch (Exception) {
602 Console.WriteLine ("File will not be scanned: {0}", name);
603 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
611 Environment.Exit (1);
616 static readonly Universe universe = new Universe ();
617 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
619 static bool QueueAssembly (List<string> files, string codebase)
621 // Console.WriteLine ("CODE BASE IS {0}", codebase);
622 if (files.Contains (codebase))
625 var path = new Uri(codebase).LocalPath;
626 var name = Path.GetFileName (path);
628 if (loaded_assemblies.TryGetValue (name, out found)) {
629 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
633 loaded_assemblies.Add (name, path);
635 files.Add (codebase);
639 Assembly a = universe.LoadFile (path);
641 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
642 a = universe.Load (an.FullName);
643 if (!QueueAssembly (files, a.CodeBase))
646 } catch (Exception) {
654 static Assembly LoadAssembly (string assembly)
659 char[] path_chars = { '/', '\\' };
661 if (assembly.IndexOfAny (path_chars) != -1) {
662 a = universe.LoadFile (assembly);
664 string ass = assembly;
665 if (ass.EndsWith (".dll"))
666 ass = assembly.Substring (0, assembly.Length - 4);
667 a = universe.Load (ass);
670 } catch (FileNotFoundException){
671 string total_log = "";
673 foreach (string dir in link_paths){
674 string full_path = Path.Combine (dir, assembly);
675 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
679 a = universe.LoadFile (full_path);
681 } catch (FileNotFoundException ff) {
682 total_log += ff.FusionLog;
686 Error ("Cannot find assembly `" + assembly + "'" );
688 Console.WriteLine ("Log: \n" + total_log);
689 } catch (IKVM.Reflection.BadImageFormatException f) {
692 Error ("Cannot load assembly (bad file format) " + f.Message);
693 } catch (FileLoadException f){
694 Error ("Cannot load assembly " + f.Message);
695 } catch (ArgumentNullException){
696 Error("Cannot load assembly (null argument)");
701 static void Error (string msg)
703 Console.Error.WriteLine ("ERROR: " + msg);
704 Environment.Exit (1);
709 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
711 " -c Produce stub only, do not compile\n" +
712 " -o out Specifies output filename\n" +
713 " -oo obj Specifies output filename for helper object file\n" +
714 " -L path Adds `path' to the search path for assemblies\n" +
715 " --nodeps Turns off automatic dependency embedding (default)\n" +
716 " --deps Turns on automatic dependency embedding\n" +
717 " --dos2unix[=true|false]\n" +
718 " When no value provided, or when `true` specified\n" +
719 " `dos2unix` will be invoked to convert paths on Windows.\n" +
720 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
721 " --keeptemp Keeps the temporary files\n" +
722 " --config F Bundle system config file `F'\n" +
723 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
724 " --machine-config F Use the given file as the machine.config for the application.\n" +
725 " --static Statically link to mono libs\n" +
726 " --nomain Don't include a main() function, for libraries\n" +
727 " -z Compress the assemblies before embedding.\n" +
728 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
729 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
730 " You need zlib development headers and libraries.\n");
734 static extern int system (string s);
736 static extern int uname (IntPtr buf);
738 static void DetectOS ()
741 os_message = "OS is: Windows";
746 IntPtr buf = Marshal.AllocHGlobal (8192);
747 if (uname (buf) != 0){
748 os_message = "Warning: Unable to detect OS";
749 Marshal.FreeHGlobal (buf);
752 string os = Marshal.PtrToStringAnsi (buf);
753 os_message = "OS is: " + os;
757 Marshal.FreeHGlobal (buf);
762 int p = (int) Environment.OSVersion.Platform;
763 return ((p == 4) || (p == 128) || (p == 6));
767 static void Execute (string cmdLine)
771 Console.WriteLine ("[execute cmd]: " + cmdLine);
772 int ret = system (cmdLine);
775 Error(String.Format("[Fail] {0}", ret));
780 // on Windows, we have to pipe the output of a
781 // `cmd` interpolation to dos2unix, because the shell does not
782 // strip the CRLFs generated by the native pkg-config distributed
785 // But if it's *not* on cygwin, just skip it.
787 // check if dos2unix is applicable.
788 if (use_dos2unix == true)
790 var info = new ProcessStartInfo ("dos2unix");
791 info.CreateNoWindow = true;
792 info.RedirectStandardInput = true;
793 info.UseShellExecute = false;
794 var dos2unix = Process.Start (info);
795 dos2unix.StandardInput.WriteLine ("aaa");
796 dos2unix.StandardInput.WriteLine ("\u0004");
797 dos2unix.StandardInput.Close ();
798 dos2unix.WaitForExit ();
799 if (dos2unix.ExitCode == 0)
802 Console.WriteLine("Warning: dos2unix not found");
803 use_dos2unix = false;
806 if (use_dos2unix == null)
807 use_dos2unix = false;
809 ProcessStartInfo psi = new ProcessStartInfo();
810 psi.UseShellExecute = false;
812 // if there is no dos2unix, just run cmd /c.
813 if (use_dos2unix == false)
815 psi.FileName = "cmd";
816 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
821 StringBuilder b = new StringBuilder();
823 for (int i = 0; i < cmdLine.Length; i++)
825 if (cmdLine[i] == '`')
829 b.Append("|dos2unix");
833 b.Append(cmdLine[i]);
835 cmdLine = b.ToString();
836 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
840 Console.WriteLine(cmdLine);
841 using (Process p = Process.Start (psi)) {
843 int ret = p.ExitCode;
845 Error (String.Format("[Fail] {0}", ret));
850 static string GetEnv(string name, string defaultValue)
852 string val = Environment.GetEnvironmentVariable(name);
856 Console.WriteLine("{0} = {1}", name, val);
862 Console.WriteLine("{0} = {1} (default)", name, val);
867 static string LocateFile(string default_path)
869 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
870 if (File.Exists(override_path))
871 return override_path;
872 else if (File.Exists(default_path))
875 throw new FileNotFoundException(default_path);