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;
23 using System.Threading.Tasks;
27 static string output = "a.out";
28 static string object_out = null;
29 static List<string> link_paths = new List<string> ();
30 static bool autodeps = false;
31 static bool keeptemp = false;
32 static bool compile_only = false;
33 static bool static_link = false;
34 static string config_file = null;
35 static string machine_config_file = null;
36 static string config_dir = null;
37 static string style = "linux";
40 static bool? use_dos2unix = null;
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);
150 sources.Add (args [i]);
154 if (static_link && style == "windows") {
155 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
160 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
161 if (sources.Count == 0 || output == null) {
163 Environment.Exit (1);
166 List<Assembly> assemblies = LoadAssemblies (sources);
167 List<string> files = new List<string> ();
168 foreach (Assembly a in assemblies)
169 QueueAssembly (files, a.CodeBase);
171 // Special casing mscorlib.dll: any specified mscorlib.dll cannot be loaded
172 // by Assembly.ReflectionFromLoadFrom(). Instead the fx assembly which runs
173 // mkbundle.exe is loaded, which is not what we want.
174 // So, replace it with whatever actually specified.
175 foreach (string srcfile in sources) {
176 if (Path.GetFileName (srcfile) == "mscorlib.dll") {
177 foreach (string file in files) {
178 if (Path.GetFileName (new Uri (file).LocalPath) == "mscorlib.dll") {
180 files.Add (new Uri (Path.GetFullPath (srcfile)).LocalPath);
188 GenerateBundles (files);
189 //GenerateJitWrapper ();
194 static void WriteSymbol (StreamWriter sw, string name, long size)
200 "\t.section .rodata\n" +
202 "\t.type {0}, \"object\"\n" +
203 "\t.size {0}, {1}\n" +
209 "\t.section __TEXT,__text,regular,pure_instructions\n" +
219 "\t.section .rdata,\"dr\"\n" +
227 static string [] chars = new string [256];
229 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
233 // Preallocate the strings we need.
234 if (chars [0] == null) {
235 for (int i = 0; i < chars.Length; i++)
236 chars [i] = string.Format ("{0}", i.ToString ());
239 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
241 for (int i = 0; i < n; i++) {
242 if (count % 32 == 0) {
243 ts.Write ("\n\t.byte ");
247 ts.Write (chars [buffer [i]]);
255 static void GenerateBundles (List<string> files)
257 string temp_s = "temp.s"; // Path.GetTempFileName ();
258 string temp_c = "temp.c";
259 string temp_o = "temp.o";
263 if (object_out != null)
267 List<string> c_bundle_names = new List<string> ();
268 List<string[]> config_names = new List<string[]> ();
269 byte [] buffer = new byte [8192];
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 MemoryStream ms = new MemoryStream ();
313 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
314 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){
315 deflate.Write (buffer, 0, n);
319 byte [] bytes = ms.GetBuffer ();
320 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
324 streams [url] = stream;
325 sizes [url] = real_size;
331 Parallel.ForEach (files, body);
333 foreach (var url in files)
337 // The non-parallel part
338 foreach (var url in files) {
339 string fname = new Uri (url).LocalPath;
340 string aname = Path.GetFileName (fname);
341 string encoded = aname.Replace ("-", "_").Replace (".", "_");
346 var stream = streams [url];
347 var real_size = sizes [url];
349 Console.WriteLine (" embedding: " + fname);
351 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
353 WriteBuffer (ts, stream, buffer);
356 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
357 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
358 " assembly_data_{0}, {2}}}, {3}}};",
359 encoded, aname, real_size, stream.Length);
360 double ratio = ((double) stream.Length * 100) / real_size;
361 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
363 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
364 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
365 encoded, aname, real_size);
369 c_bundle_names.Add ("assembly_bundle_" + encoded);
372 FileStream cf = File.OpenRead (fname + ".config");
373 Console.WriteLine (" config from: " + fname + ".config");
374 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
375 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
376 WriteBuffer (ts, cf, buffer);
378 config_names.Add (new string[] {aname, encoded});
379 } catch (FileNotFoundException) {
380 /* we ignore if the config file doesn't exist */
384 if (config_file != null){
387 conf = File.OpenRead (config_file);
389 Error (String.Format ("Failure to open {0}", config_file));
392 Console.WriteLine ("System config from: " + config_file);
393 tc.WriteLine ("extern const char system_config;");
394 WriteSymbol (ts, "system_config", config_file.Length);
396 WriteBuffer (ts, conf, buffer);
398 ts.Write ("\t.byte 0\n");
402 if (machine_config_file != null){
405 conf = File.OpenRead (machine_config_file);
407 Error (String.Format ("Failure to open {0}", machine_config_file));
410 Console.WriteLine ("Machine config from: " + machine_config_file);
411 tc.WriteLine ("extern const char machine_config;");
412 WriteSymbol (ts, "machine_config", machine_config_file.Length);
414 WriteBuffer (ts, conf, buffer);
415 ts.Write ("\t.byte 0\n");
420 Console.WriteLine ("Compiling:");
421 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
422 int ret = Execute (cmd);
429 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
431 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
433 foreach (string c in c_bundle_names){
434 tc.WriteLine ("\t&{0},", c);
436 tc.WriteLine ("\tNULL\n};\n");
437 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
439 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
440 foreach (string[] ass in config_names){
441 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
443 if (config_file != null)
444 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
445 if (machine_config_file != null)
446 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
447 tc.WriteLine ("}\n");
449 if (config_dir != null)
450 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
452 tc.WriteLine ("static const char *config_dir = NULL;");
454 Stream template_stream;
456 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
458 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
461 StreamReader s = new StreamReader (template_stream);
462 string template = s.ReadToEnd ();
466 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
467 StreamReader st = new StreamReader (template_main_stream);
468 string maintemplate = st.ReadToEnd ();
469 tc.Write (maintemplate);
477 string zlib = (compress ? "-lz" : "");
478 string debugging = "-g";
479 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc");
481 if (style == "linux")
486 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
488 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
489 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
490 "`pkg-config --libs-only-L mono-2` " + smonolib +
491 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
492 temp_c, temp_o, output, zlib, cc);
495 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
496 temp_c, temp_o, output, zlib, cc);
504 Console.WriteLine ("Done");
509 if (object_out == null){
510 File.Delete (temp_o);
513 File.Delete (temp_c);
515 File.Delete (temp_s);
520 static List<Assembly> LoadAssemblies (List<string> sources)
522 List<Assembly> assemblies = new List<Assembly> ();
525 foreach (string name in sources){
526 Assembly a = LoadAssembly (name);
537 Environment.Exit (1);
542 static readonly Universe universe = new Universe ();
544 static void QueueAssembly (List<string> files, string codebase)
546 if (files.Contains (codebase))
549 files.Add (codebase);
550 Assembly a = universe.LoadFile (new Uri(codebase).LocalPath);
555 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
556 a = universe.Load (an.Name);
557 QueueAssembly (files, a.CodeBase);
561 static Assembly LoadAssembly (string assembly)
566 char[] path_chars = { '/', '\\' };
568 if (assembly.IndexOfAny (path_chars) != -1) {
569 a = universe.LoadFile (assembly);
571 string ass = assembly;
572 if (ass.EndsWith (".dll"))
573 ass = assembly.Substring (0, assembly.Length - 4);
574 a = universe.Load (ass);
577 } catch (FileNotFoundException){
578 string total_log = "";
580 foreach (string dir in link_paths){
581 string full_path = Path.Combine (dir, assembly);
582 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
586 a = universe.LoadFile (full_path);
588 } catch (FileNotFoundException ff) {
589 total_log += ff.FusionLog;
593 Error ("Cannot find assembly `" + assembly + "'" );
594 Console.WriteLine ("Log: \n" + total_log);
595 } catch (IKVM.Reflection.BadImageFormatException f) {
596 Error ("Cannot load assembly (bad file format) " + f.Message);
597 } catch (FileLoadException f){
598 Error ("Cannot load assembly " + f.Message);
599 } catch (ArgumentNullException){
600 Error("Cannot load assembly (null argument)");
605 static void Error (string msg)
607 Console.Error.WriteLine (msg);
608 Environment.Exit (1);
613 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
615 " -c Produce stub only, do not compile\n" +
616 " -o out Specifies output filename\n" +
617 " -oo obj Specifies output filename for helper object file\n" +
618 " -L path Adds `path' to the search path for assemblies\n" +
619 " --nodeps Turns off automatic dependency embedding (default)\n" +
620 " --deps Turns on automatic dependency embedding\n" +
621 " --keeptemp Keeps the temporary files\n" +
622 " --config F Bundle system config file `F'\n" +
623 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
624 " --machine-config F Use the given file as the machine.config for the application.\n" +
625 " --static Statically link to mono libs\n" +
626 " --nomain Don't include a main() function, for libraries\n" +
627 " -z Compress the assemblies before embedding.\n" +
628 " You need zlib development headers and libraries.\n");
632 static extern int system (string s);
634 static extern int uname (IntPtr buf);
636 static void DetectOS ()
639 Console.WriteLine ("OS is: Windows");
644 IntPtr buf = Marshal.AllocHGlobal (8192);
645 if (uname (buf) != 0){
646 Console.WriteLine ("Warning: Unable to detect OS");
647 Marshal.FreeHGlobal (buf);
650 string os = Marshal.PtrToStringAnsi (buf);
651 Console.WriteLine ("OS is: " + os);
655 Marshal.FreeHGlobal (buf);
660 int p = (int) Environment.OSVersion.Platform;
661 return ((p == 4) || (p == 128) || (p == 6));
665 static int Execute (string cmdLine)
668 Console.WriteLine (cmdLine);
669 return system (cmdLine);
672 // on Windows, we have to pipe the output of a
673 // `cmd` interpolation to dos2unix, because the shell does not
674 // strip the CRLFs generated by the native pkg-config distributed
677 // But if it's *not* on cygwin, just skip it.
679 // check if dos2unix is applicable.
680 if (use_dos2unix == null) {
681 use_dos2unix = false;
683 var dos2unix = Process.Start ("dos2unix");
684 dos2unix.StandardInput.WriteLine ("aaa");
685 dos2unix.StandardInput.WriteLine ("\u0004");
686 dos2unix.WaitForExit ();
687 if (dos2unix.ExitCode == 0)
693 // and if there is no dos2unix, just run cmd /c.
694 if (use_dos2unix == false) {
695 Console.WriteLine (cmdLine);
696 ProcessStartInfo dos2unix = new ProcessStartInfo ();
697 dos2unix.UseShellExecute = false;
698 dos2unix.FileName = "cmd";
699 dos2unix.Arguments = String.Format ("/c \"{0}\"", cmdLine);
701 using (Process p = Process.Start (dos2unix)) {
707 StringBuilder b = new StringBuilder ();
709 for (int i = 0; i < cmdLine.Length; i++) {
710 if (cmdLine [i] == '`') {
711 if (count % 2 != 0) {
712 b.Append ("|dos2unix");
716 b.Append (cmdLine [i]);
718 cmdLine = b.ToString ();
719 Console.WriteLine (cmdLine);
721 ProcessStartInfo psi = new ProcessStartInfo ();
722 psi.UseShellExecute = false;
724 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
726 using (Process p = Process.Start (psi)) {
732 static string GetEnv (string name, string defaultValue)
734 string s = Environment.GetEnvironmentVariable (name);
735 return s != null ? s : defaultValue;