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";
38 static bool? use_dos2unix = null;
39 static bool skip_scan;
40 static string ctor_func;
42 static int Main (string [] args)
44 List<string> sources = new List<string> ();
45 int top = args.Length;
50 for (int i = 0; i < top; i++){
52 case "--help": case "-h": case "-?":
73 object_out = args [++i];
81 link_paths.Add (args [++i]);
97 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
98 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
106 config_file = args [++i];
108 case "--machine-config":
114 machine_config_file = args [++i];
116 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
124 config_dir = args [++i];
144 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
152 case "--static-ctor":
157 ctor_func = args [++i];
160 case "--dos2unix=true":
163 case "--dos2unix=false":
164 use_dos2unix = false;
167 sources.Add (args [i]);
171 if (static_link && style == "windows") {
172 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
177 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
178 if (sources.Count == 0 || output == null) {
180 Environment.Exit (1);
183 List<string> assemblies = LoadAssemblies (sources);
184 List<string> files = new List<string> ();
185 foreach (string file in assemblies)
186 if (!QueueAssembly (files, file))
189 GenerateBundles (files);
190 //GenerateJitWrapper ();
195 static void WriteSymbol (StreamWriter sw, string name, long size)
201 "\t.section .rodata\n" +
203 "\t.type {0}, \"object\"\n" +
204 "\t.size {0}, {1}\n" +
210 "\t.section __TEXT,__text,regular,pure_instructions\n" +
220 "\t.section .rdata,\"dr\"\n" +
228 static string [] chars = new string [256];
230 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
234 // Preallocate the strings we need.
235 if (chars [0] == null) {
236 for (int i = 0; i < chars.Length; i++)
237 chars [i] = string.Format ("{0}", i.ToString ());
240 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
242 for (int i = 0; i < n; i++) {
243 if (count % 32 == 0) {
244 ts.Write ("\n\t.byte ");
248 ts.Write (chars [buffer [i]]);
256 static void GenerateBundles (List<string> files)
258 string temp_s = "temp.s"; // Path.GetTempFileName ();
259 string temp_c = "temp.c";
260 string temp_o = "temp.o";
264 if (object_out != null)
268 List<string> c_bundle_names = new List<string> ();
269 List<string[]> config_names = new List<string[]> ();
271 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
272 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
276 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
277 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
281 const unsigned char *data;
282 const unsigned int size;
283 } MonoBundledAssembly;
284 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
285 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
288 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
289 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
293 tc.WriteLine ("typedef struct _compressed_data {");
294 tc.WriteLine ("\tMonoBundledAssembly assembly;");
295 tc.WriteLine ("\tint compressed_size;");
296 tc.WriteLine ("} CompressedAssembly;\n");
299 object monitor = new object ();
301 var streams = new Dictionary<string, Stream> ();
302 var sizes = new Dictionary<string, long> ();
304 // Do the file reading and compression in parallel
305 Action<string> body = delegate (string url) {
306 string fname = new Uri (url).LocalPath;
307 Stream stream = File.OpenRead (fname);
309 long real_size = stream.Length;
312 byte[] cbuffer = new byte [8192];
313 MemoryStream ms = new MemoryStream ();
314 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
315 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
316 deflate.Write (cbuffer, 0, n);
320 byte [] bytes = ms.GetBuffer ();
321 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
325 streams [url] = stream;
326 sizes [url] = real_size;
332 Parallel.ForEach (files, body);
334 foreach (var url in files)
338 // The non-parallel part
339 byte [] buffer = new byte [8192];
340 foreach (var url in files) {
341 string fname = new Uri (url).LocalPath;
342 string aname = Path.GetFileName (fname);
343 string encoded = aname.Replace ("-", "_").Replace (".", "_");
348 var stream = streams [url];
349 var real_size = sizes [url];
351 Console.WriteLine (" embedding: " + fname);
353 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
355 WriteBuffer (ts, stream, buffer);
358 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
359 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
360 " assembly_data_{0}, {2}}}, {3}}};",
361 encoded, aname, real_size, stream.Length);
362 double ratio = ((double) stream.Length * 100) / real_size;
363 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
365 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
366 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
367 encoded, aname, real_size);
371 c_bundle_names.Add ("assembly_bundle_" + encoded);
374 FileStream cf = File.OpenRead (fname + ".config");
375 Console.WriteLine (" config from: " + fname + ".config");
376 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
377 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
378 WriteBuffer (ts, cf, buffer);
380 config_names.Add (new string[] {aname, encoded});
381 } catch (FileNotFoundException) {
382 /* we ignore if the config file doesn't exist */
386 if (config_file != null){
389 conf = File.OpenRead (config_file);
391 Error (String.Format ("Failure to open {0}", config_file));
394 Console.WriteLine ("System config from: " + config_file);
395 tc.WriteLine ("extern const char system_config;");
396 WriteSymbol (ts, "system_config", config_file.Length);
398 WriteBuffer (ts, conf, buffer);
400 ts.Write ("\t.byte 0\n");
404 if (machine_config_file != null){
407 conf = File.OpenRead (machine_config_file);
409 Error (String.Format ("Failure to open {0}", machine_config_file));
412 Console.WriteLine ("Machine config from: " + machine_config_file);
413 tc.WriteLine ("extern const char machine_config;");
414 WriteSymbol (ts, "machine_config", machine_config_file.Length);
416 WriteBuffer (ts, conf, buffer);
417 ts.Write ("\t.byte 0\n");
422 string assembler = GetEnv ("AS", IsUnix ? "as" : "i686-pc-mingw32-as");
424 Console.WriteLine ("Compiling:");
425 string cmd = String.Format ("{0} -o {1} {2} ", assembler, temp_o, temp_s);
426 int ret = Execute (cmd);
433 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
435 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
437 foreach (string c in c_bundle_names){
438 tc.WriteLine ("\t&{0},", c);
440 tc.WriteLine ("\tNULL\n};\n");
441 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
443 if (ctor_func != null) {
444 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
445 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
446 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
449 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
450 foreach (string[] ass in config_names){
451 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
453 if (config_file != null)
454 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
455 if (machine_config_file != null)
456 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
457 tc.WriteLine ("}\n");
459 if (config_dir != null)
460 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
462 tc.WriteLine ("static const char *config_dir = NULL;");
464 Stream template_stream;
466 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
468 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
471 StreamReader s = new StreamReader (template_stream);
472 string template = s.ReadToEnd ();
476 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
477 StreamReader st = new StreamReader (template_main_stream);
478 string maintemplate = st.ReadToEnd ();
479 tc.Write (maintemplate);
487 string zlib = (compress ? "-lz" : "");
488 string debugging = "-g";
489 string cc = GetEnv ("CC", IsUnix ? "cc" : "i686-pc-mingw32-gcc");
491 if (style == "linux")
496 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
498 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
499 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
500 "`pkg-config --libs-only-L mono-2` " + smonolib +
501 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
502 temp_c, temp_o, output, zlib, cc);
505 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
506 temp_c, temp_o, output, zlib, cc);
514 Console.WriteLine ("Done");
519 if (object_out == null){
520 File.Delete (temp_o);
523 File.Delete (temp_c);
525 File.Delete (temp_s);
530 static List<string> LoadAssemblies (List<string> sources)
532 List<string> assemblies = new List<string> ();
535 foreach (string name in sources){
537 Assembly a = LoadAssembly (name);
544 assemblies.Add (a.CodeBase);
545 } catch (Exception e) {
547 Console.WriteLine ("File will not be scanned: {0}", name);
548 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
556 Environment.Exit (1);
561 static readonly Universe universe = new Universe ();
562 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
564 static bool QueueAssembly (List<string> files, string codebase)
566 // Console.WriteLine ("CODE BASE IS {0}", codebase);
567 if (files.Contains (codebase))
570 var path = new Uri(codebase).LocalPath;
571 var name = Path.GetFileName (path);
573 if (loaded_assemblies.TryGetValue (name, out found)) {
574 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
578 loaded_assemblies.Add (name, path);
580 files.Add (codebase);
584 Assembly a = universe.LoadFile (path);
586 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
587 a = universe.Load (an.FullName);
588 if (!QueueAssembly (files, a.CodeBase))
591 } catch (Exception e) {
599 static Assembly LoadAssembly (string assembly)
604 char[] path_chars = { '/', '\\' };
606 if (assembly.IndexOfAny (path_chars) != -1) {
607 a = universe.LoadFile (assembly);
609 string ass = assembly;
610 if (ass.EndsWith (".dll"))
611 ass = assembly.Substring (0, assembly.Length - 4);
612 a = universe.Load (ass);
615 } catch (FileNotFoundException){
616 string total_log = "";
618 foreach (string dir in link_paths){
619 string full_path = Path.Combine (dir, assembly);
620 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
624 a = universe.LoadFile (full_path);
626 } catch (FileNotFoundException ff) {
627 total_log += ff.FusionLog;
631 Error ("Cannot find assembly `" + assembly + "'" );
632 Console.WriteLine ("Log: \n" + total_log);
633 } catch (IKVM.Reflection.BadImageFormatException f) {
636 Error ("Cannot load assembly (bad file format) " + f.Message);
637 } catch (FileLoadException f){
638 Error ("Cannot load assembly " + f.Message);
639 } catch (ArgumentNullException){
640 Error("Cannot load assembly (null argument)");
645 static void Error (string msg)
647 Console.Error.WriteLine ("ERROR: " + msg);
648 Environment.Exit (1);
653 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
655 " -c Produce stub only, do not compile\n" +
656 " -o out Specifies output filename\n" +
657 " -oo obj Specifies output filename for helper object file\n" +
658 " -L path Adds `path' to the search path for assemblies\n" +
659 " --nodeps Turns off automatic dependency embedding (default)\n" +
660 " --deps Turns on automatic dependency embedding\n" +
661 " --dos2unix[=true|false]\n" +
662 " When no value provided, or when `true` specified\n" +
663 " `dos2unix` will be invoked to convert paths on Windows.\n" +
664 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
665 " --keeptemp Keeps the temporary files\n" +
666 " --config F Bundle system config file `F'\n" +
667 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
668 " --machine-config F Use the given file as the machine.config for the application.\n" +
669 " --static Statically link to mono libs\n" +
670 " --nomain Don't include a main() function, for libraries\n" +
671 " -z Compress the assemblies before embedding.\n" +
672 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
673 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
674 " You need zlib development headers and libraries.\n");
678 static extern int system (string s);
680 static extern int uname (IntPtr buf);
682 static void DetectOS ()
685 Console.WriteLine ("OS is: Windows");
690 IntPtr buf = Marshal.AllocHGlobal (8192);
691 if (uname (buf) != 0){
692 Console.WriteLine ("Warning: Unable to detect OS");
693 Marshal.FreeHGlobal (buf);
696 string os = Marshal.PtrToStringAnsi (buf);
697 Console.WriteLine ("OS is: " + os);
701 Marshal.FreeHGlobal (buf);
706 int p = (int) Environment.OSVersion.Platform;
707 return ((p == 4) || (p == 128) || (p == 6));
711 static int Execute (string cmdLine)
714 Console.WriteLine (cmdLine);
715 return system (cmdLine);
718 // on Windows, we have to pipe the output of a
719 // `cmd` interpolation to dos2unix, because the shell does not
720 // strip the CRLFs generated by the native pkg-config distributed
723 // But if it's *not* on cygwin, just skip it.
725 // check if dos2unix is applicable.
726 if (use_dos2unix == null) {
727 use_dos2unix = false;
729 var info = new ProcessStartInfo ("dos2unix");
730 info.CreateNoWindow = true;
731 info.RedirectStandardInput = true;
732 info.UseShellExecute = false;
733 var dos2unix = Process.Start (info);
734 dos2unix.StandardInput.WriteLine ("aaa");
735 dos2unix.StandardInput.WriteLine ("\u0004");
736 dos2unix.StandardInput.Close ();
737 dos2unix.WaitForExit ();
738 if (dos2unix.ExitCode == 0)
744 // and if there is no dos2unix, just run cmd /c.
745 if (use_dos2unix == false) {
746 Console.WriteLine (cmdLine);
747 ProcessStartInfo dos2unix = new ProcessStartInfo ();
748 dos2unix.UseShellExecute = false;
749 dos2unix.FileName = "cmd";
750 dos2unix.Arguments = String.Format ("/c \"{0}\"", cmdLine);
752 using (Process p = Process.Start (dos2unix)) {
758 StringBuilder b = new StringBuilder ();
760 for (int i = 0; i < cmdLine.Length; i++) {
761 if (cmdLine [i] == '`') {
762 if (count % 2 != 0) {
763 b.Append ("|dos2unix");
767 b.Append (cmdLine [i]);
769 cmdLine = b.ToString ();
770 Console.WriteLine (cmdLine);
772 ProcessStartInfo psi = new ProcessStartInfo ();
773 psi.UseShellExecute = false;
775 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
777 using (Process p = Process.Start (psi)) {
783 static string GetEnv (string name, string defaultValue)
785 string s = Environment.GetEnvironmentVariable (name);
786 return s != null ? s : defaultValue;