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 sources.Add (args [i]);
164 if (static_link && style == "windows") {
165 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
170 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
171 if (sources.Count == 0 || output == null) {
173 Environment.Exit (1);
176 List<string> assemblies = LoadAssemblies (sources);
177 List<string> files = new List<string> ();
178 foreach (string file in assemblies)
179 if (!QueueAssembly (files, file))
182 GenerateBundles (files);
183 //GenerateJitWrapper ();
188 static void WriteSymbol (StreamWriter sw, string name, long size)
194 "\t.section .rodata\n" +
196 "\t.type {0}, \"object\"\n" +
197 "\t.size {0}, {1}\n" +
203 "\t.section __TEXT,__text,regular,pure_instructions\n" +
213 "\t.section .rdata,\"dr\"\n" +
221 static string [] chars = new string [256];
223 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
227 // Preallocate the strings we need.
228 if (chars [0] == null) {
229 for (int i = 0; i < chars.Length; i++)
230 chars [i] = string.Format ("{0}", i.ToString ());
233 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
235 for (int i = 0; i < n; i++) {
236 if (count % 32 == 0) {
237 ts.Write ("\n\t.byte ");
241 ts.Write (chars [buffer [i]]);
249 static void GenerateBundles (List<string> files)
251 string temp_s = "temp.s"; // Path.GetTempFileName ();
252 string temp_c = "temp.c";
253 string temp_o = "temp.o";
257 if (object_out != null)
261 List<string> c_bundle_names = new List<string> ();
262 List<string[]> config_names = new List<string[]> ();
264 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
265 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
269 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
270 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
274 const unsigned char *data;
275 const unsigned int size;
276 } MonoBundledAssembly;
277 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
278 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
281 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
282 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
286 tc.WriteLine ("typedef struct _compressed_data {");
287 tc.WriteLine ("\tMonoBundledAssembly assembly;");
288 tc.WriteLine ("\tint compressed_size;");
289 tc.WriteLine ("} CompressedAssembly;\n");
292 object monitor = new object ();
294 var streams = new Dictionary<string, Stream> ();
295 var sizes = new Dictionary<string, long> ();
297 // Do the file reading and compression in parallel
298 Action<string> body = delegate (string url) {
299 string fname = new Uri (url).LocalPath;
300 Stream stream = File.OpenRead (fname);
302 long real_size = stream.Length;
305 byte[] cbuffer = new byte [8192];
306 MemoryStream ms = new MemoryStream ();
307 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
308 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
309 deflate.Write (cbuffer, 0, n);
313 byte [] bytes = ms.GetBuffer ();
314 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
318 streams [url] = stream;
319 sizes [url] = real_size;
325 Parallel.ForEach (files, body);
327 foreach (var url in files)
331 // The non-parallel part
332 byte [] buffer = new byte [8192];
333 foreach (var url in files) {
334 string fname = new Uri (url).LocalPath;
335 string aname = Path.GetFileName (fname);
336 string encoded = aname.Replace ("-", "_").Replace (".", "_");
341 var stream = streams [url];
342 var real_size = sizes [url];
344 Console.WriteLine (" embedding: " + fname);
346 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
348 WriteBuffer (ts, stream, buffer);
351 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
352 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
353 " assembly_data_{0}, {2}}}, {3}}};",
354 encoded, aname, real_size, stream.Length);
355 double ratio = ((double) stream.Length * 100) / real_size;
356 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
358 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
359 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
360 encoded, aname, real_size);
364 c_bundle_names.Add ("assembly_bundle_" + encoded);
367 FileStream cf = File.OpenRead (fname + ".config");
368 Console.WriteLine (" config from: " + fname + ".config");
369 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
370 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
371 WriteBuffer (ts, cf, buffer);
373 config_names.Add (new string[] {aname, encoded});
374 } catch (FileNotFoundException) {
375 /* we ignore if the config file doesn't exist */
379 if (config_file != null){
382 conf = File.OpenRead (config_file);
384 Error (String.Format ("Failure to open {0}", config_file));
387 Console.WriteLine ("System config from: " + config_file);
388 tc.WriteLine ("extern const char system_config;");
389 WriteSymbol (ts, "system_config", config_file.Length);
391 WriteBuffer (ts, conf, buffer);
393 ts.Write ("\t.byte 0\n");
397 if (machine_config_file != null){
400 conf = File.OpenRead (machine_config_file);
402 Error (String.Format ("Failure to open {0}", machine_config_file));
405 Console.WriteLine ("Machine config from: " + machine_config_file);
406 tc.WriteLine ("extern const char machine_config;");
407 WriteSymbol (ts, "machine_config", machine_config_file.Length);
409 WriteBuffer (ts, conf, buffer);
410 ts.Write ("\t.byte 0\n");
415 string assembler = GetEnv ("AS", IsUnix ? "as" : "i686-pc-mingw32-as");
417 Console.WriteLine ("Compiling:");
418 string cmd = String.Format ("{0} -o {1} {2} ", assembler, temp_o, temp_s);
419 int ret = Execute (cmd);
426 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
428 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
430 foreach (string c in c_bundle_names){
431 tc.WriteLine ("\t&{0},", c);
433 tc.WriteLine ("\tNULL\n};\n");
434 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
436 if (ctor_func != null) {
437 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
438 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
439 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
442 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
443 foreach (string[] ass in config_names){
444 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
446 if (config_file != null)
447 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
448 if (machine_config_file != null)
449 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
450 tc.WriteLine ("}\n");
452 if (config_dir != null)
453 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
455 tc.WriteLine ("static const char *config_dir = NULL;");
457 Stream template_stream;
459 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
461 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
464 StreamReader s = new StreamReader (template_stream);
465 string template = s.ReadToEnd ();
469 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
470 StreamReader st = new StreamReader (template_main_stream);
471 string maintemplate = st.ReadToEnd ();
472 tc.Write (maintemplate);
480 string zlib = (compress ? "-lz" : "");
481 string debugging = "-g";
482 string cc = GetEnv ("CC", IsUnix ? "cc" : "i686-pc-mingw32-gcc");
484 if (style == "linux")
489 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
491 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
492 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
493 "`pkg-config --libs-only-L mono-2` " + smonolib +
494 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
495 temp_c, temp_o, output, zlib, cc);
498 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
499 temp_c, temp_o, output, zlib, cc);
507 Console.WriteLine ("Done");
512 if (object_out == null){
513 File.Delete (temp_o);
516 File.Delete (temp_c);
518 File.Delete (temp_s);
523 static List<string> LoadAssemblies (List<string> sources)
525 List<string> assemblies = new List<string> ();
528 foreach (string name in sources){
530 Assembly a = LoadAssembly (name);
537 assemblies.Add (a.CodeBase);
538 } catch (Exception e) {
540 Console.WriteLine ("File will not be scanned: {0}", name);
541 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
549 Environment.Exit (1);
554 static readonly Universe universe = new Universe ();
555 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
557 static bool QueueAssembly (List<string> files, string codebase)
559 // Console.WriteLine ("CODE BASE IS {0}", codebase);
560 if (files.Contains (codebase))
563 var path = new Uri(codebase).LocalPath;
564 var name = Path.GetFileName (path);
566 if (loaded_assemblies.TryGetValue (name, out found)) {
567 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
571 loaded_assemblies.Add (name, path);
573 files.Add (codebase);
577 Assembly a = universe.LoadFile (path);
579 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
580 a = universe.Load (an.FullName);
581 if (!QueueAssembly (files, a.CodeBase))
584 } catch (Exception e) {
592 static Assembly LoadAssembly (string assembly)
597 char[] path_chars = { '/', '\\' };
599 if (assembly.IndexOfAny (path_chars) != -1) {
600 a = universe.LoadFile (assembly);
602 string ass = assembly;
603 if (ass.EndsWith (".dll"))
604 ass = assembly.Substring (0, assembly.Length - 4);
605 a = universe.Load (ass);
608 } catch (FileNotFoundException){
609 string total_log = "";
611 foreach (string dir in link_paths){
612 string full_path = Path.Combine (dir, assembly);
613 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
617 a = universe.LoadFile (full_path);
619 } catch (FileNotFoundException ff) {
620 total_log += ff.FusionLog;
624 Error ("Cannot find assembly `" + assembly + "'" );
625 Console.WriteLine ("Log: \n" + total_log);
626 } catch (IKVM.Reflection.BadImageFormatException f) {
629 Error ("Cannot load assembly (bad file format) " + f.Message);
630 } catch (FileLoadException f){
631 Error ("Cannot load assembly " + f.Message);
632 } catch (ArgumentNullException){
633 Error("Cannot load assembly (null argument)");
638 static void Error (string msg)
640 Console.Error.WriteLine ("ERROR: " + msg);
641 Environment.Exit (1);
646 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
648 " -c Produce stub only, do not compile\n" +
649 " -o out Specifies output filename\n" +
650 " -oo obj Specifies output filename for helper object file\n" +
651 " -L path Adds `path' to the search path for assemblies\n" +
652 " --nodeps Turns off automatic dependency embedding (default)\n" +
653 " --deps Turns on automatic dependency embedding\n" +
654 " --keeptemp Keeps the temporary files\n" +
655 " --config F Bundle system config file `F'\n" +
656 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
657 " --machine-config F Use the given file as the machine.config for the application.\n" +
658 " --static Statically link to mono libs\n" +
659 " --nomain Don't include a main() function, for libraries\n" +
660 " -z Compress the assemblies before embedding.\n" +
661 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
662 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
663 " You need zlib development headers and libraries.\n");
667 static extern int system (string s);
669 static extern int uname (IntPtr buf);
671 static void DetectOS ()
674 Console.WriteLine ("OS is: Windows");
679 IntPtr buf = Marshal.AllocHGlobal (8192);
680 if (uname (buf) != 0){
681 Console.WriteLine ("Warning: Unable to detect OS");
682 Marshal.FreeHGlobal (buf);
685 string os = Marshal.PtrToStringAnsi (buf);
686 Console.WriteLine ("OS is: " + os);
690 Marshal.FreeHGlobal (buf);
695 int p = (int) Environment.OSVersion.Platform;
696 return ((p == 4) || (p == 128) || (p == 6));
700 static int Execute (string cmdLine)
703 Console.WriteLine (cmdLine);
704 return system (cmdLine);
708 // on Windows, we have to pipe the output of a
709 // `cmd` interpolation to dos2unix, because the shell does not
710 // strip the CRLFs generated by the native pkg-config distributed
713 // But if it's *not* on cygwin, just skip it.
715 // check if dos2unix is applicable.
716 if (use_dos2unix == null) {
717 use_dos2unix = false;
719 var info = new ProcessStartInfo ("dos2unix");
720 info.CreateNoWindow = true;
721 info.RedirectStandardInput = true;
722 info.UseShellExecute = false;
723 var dos2unix = Process.Start (info);
724 dos2unix.StandardInput.WriteLine ("aaa");
725 dos2unix.StandardInput.WriteLine ("\u0004");
726 dos2unix.StandardInput.Close ();
727 dos2unix.WaitForExit ();
728 if (dos2unix.ExitCode == 0)
734 // and if there is no dos2unix, just run cmd /c.
735 if (use_dos2unix == false) {
737 Console.WriteLine (cmdLine);
738 ProcessStartInfo dos2unix = new ProcessStartInfo ();
739 dos2unix.UseShellExecute = false;
740 dos2unix.FileName = "cmd";
741 dos2unix.Arguments = String.Format ("/c \"{0}\"", cmdLine);
743 using (Process p = Process.Start (dos2unix)) {
751 StringBuilder b = new StringBuilder ();
753 for (int i = 0; i < cmdLine.Length; i++) {
754 if (cmdLine [i] == '`') {
756 if (count % 2 != 0) {
757 b.Append ("|dos2unix");
762 b.Append (cmdLine [i]);
764 cmdLine = b.ToString ();
765 Console.WriteLine (cmdLine);
767 ProcessStartInfo psi = new ProcessStartInfo ();
768 psi.UseShellExecute = false;
770 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
772 using (Process p = Process.Start (psi)) {
778 static string GetEnv (string name, string defaultValue)
780 string s = Environment.GetEnvironmentVariable (name);
781 return s != null ? s : defaultValue;