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;
15 using System.Reflection;
17 using System.IO.Compression;
18 using System.Runtime.InteropServices;
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";
41 static int Main (string [] args)
43 List<string> sources = new List<string> ();
44 int top = args.Length;
49 for (int i = 0; i < top; i++){
51 case "--help": case "-h": case "-?":
72 object_out = args [++i];
80 link_paths.Add (args [++i]);
96 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
97 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
105 config_file = args [++i];
107 case "--machine-config":
113 machine_config_file = args [++i];
115 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
123 config_dir = args [++i];
143 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
149 sources.Add (args [i]);
153 if (static_link && style == "windows") {
154 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
159 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
160 if (sources.Count == 0 || output == null) {
162 Environment.Exit (1);
165 List<Assembly> assemblies = LoadAssemblies (sources);
166 List<string> files = new List<string> ();
167 foreach (Assembly a in assemblies)
168 QueueAssembly (files, a.CodeBase);
170 // Special casing mscorlib.dll: any specified mscorlib.dll cannot be loaded
171 // by Assembly.ReflectionFromLoadFrom(). Instead the fx assembly which runs
172 // mkbundle.exe is loaded, which is not what we want.
173 // So, replace it with whatever actually specified.
174 foreach (string srcfile in sources) {
175 if (Path.GetFileName (srcfile) == "mscorlib.dll") {
176 foreach (string file in files) {
177 if (Path.GetFileName (new Uri (file).LocalPath) == "mscorlib.dll") {
179 files.Add (new Uri (Path.GetFullPath (srcfile)).LocalPath);
187 GenerateBundles (files);
188 //GenerateJitWrapper ();
193 static void WriteSymbol (StreamWriter sw, string name, long size)
199 "\t.section .rodata\n" +
201 "\t.type {0}, \"object\"\n" +
202 "\t.size {0}, {1}\n" +
208 "\t.section __TEXT,__text,regular,pure_instructions\n" +
218 "\t.section .rdata,\"dr\"\n" +
226 static string [] chars = new string [256];
228 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
232 // Preallocate the strings we need.
233 if (chars [0] == null) {
234 for (int i = 0; i < chars.Length; i++)
235 chars [i] = string.Format ("{0}", i.ToString ());
238 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
240 for (int i = 0; i < n; i++) {
241 if (count % 32 == 0) {
242 ts.Write ("\n\t.byte ");
246 ts.Write (chars [buffer [i]]);
254 static void GenerateBundles (List<string> files)
256 string temp_s = "temp.s"; // Path.GetTempFileName ();
257 string temp_c = "temp.c";
258 string temp_o = "temp.o";
262 if (object_out != null)
266 List<string> c_bundle_names = new List<string> ();
267 List<string[]> config_names = new List<string[]> ();
268 byte [] buffer = new byte [8192];
270 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
271 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
274 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
275 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
276 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
279 tc.WriteLine ("typedef struct _compressed_data {");
280 tc.WriteLine ("\tMonoBundledAssembly assembly;");
281 tc.WriteLine ("\tint compressed_size;");
282 tc.WriteLine ("} CompressedAssembly;\n");
285 object monitor = new object ();
287 var streams = new Dictionary<string, Stream> ();
288 var sizes = new Dictionary<string, long> ();
290 // Do the file reading and compression in parallel
291 Action<string> body = delegate (string url) {
292 string fname = new Uri (url).LocalPath;
293 Stream stream = File.OpenRead (fname);
295 long real_size = stream.Length;
298 MemoryStream ms = new MemoryStream ();
299 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
300 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){
301 deflate.Write (buffer, 0, n);
305 byte [] bytes = ms.GetBuffer ();
306 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
310 streams [url] = stream;
311 sizes [url] = real_size;
316 Parallel.ForEach (files, body);
318 foreach (var url in files)
322 // The non-parallel part
323 foreach (var url in files) {
324 string fname = new Uri (url).LocalPath;
325 string aname = Path.GetFileName (fname);
326 string encoded = aname.Replace ("-", "_").Replace (".", "_");
331 var stream = streams [url];
332 var real_size = sizes [url];
334 Console.WriteLine (" embedding: " + fname);
336 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
338 WriteBuffer (ts, stream, buffer);
341 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
342 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
343 " assembly_data_{0}, {2}}}, {3}}};",
344 encoded, aname, real_size, stream.Length);
345 double ratio = ((double) stream.Length * 100) / real_size;
346 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
348 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
349 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
350 encoded, aname, real_size);
354 c_bundle_names.Add ("assembly_bundle_" + encoded);
357 FileStream cf = File.OpenRead (fname + ".config");
358 Console.WriteLine (" config from: " + fname + ".config");
359 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
360 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
361 WriteBuffer (ts, cf, buffer);
363 config_names.Add (new string[] {aname, encoded});
364 } catch (FileNotFoundException) {
365 /* we ignore if the config file doesn't exist */
369 if (config_file != null){
372 conf = File.OpenRead (config_file);
374 Error (String.Format ("Failure to open {0}", config_file));
377 Console.WriteLine ("System config from: " + config_file);
378 tc.WriteLine ("extern const char system_config;");
379 WriteSymbol (ts, "system_config", config_file.Length);
381 WriteBuffer (ts, conf, buffer);
383 ts.Write ("\t.byte 0\n");
387 if (machine_config_file != null){
390 conf = File.OpenRead (machine_config_file);
392 Error (String.Format ("Failure to open {0}", machine_config_file));
395 Console.WriteLine ("Machine config from: " + machine_config_file);
396 tc.WriteLine ("extern const char machine_config;");
397 WriteSymbol (ts, "machine_config", machine_config_file.Length);
399 WriteBuffer (ts, conf, buffer);
400 ts.Write ("\t.byte 0\n");
405 Console.WriteLine ("Compiling:");
406 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
407 int ret = Execute (cmd);
414 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
416 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
418 foreach (string c in c_bundle_names){
419 tc.WriteLine ("\t&{0},", c);
421 tc.WriteLine ("\tNULL\n};\n");
422 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
424 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
425 foreach (string[] ass in config_names){
426 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
428 if (config_file != null)
429 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
430 if (machine_config_file != null)
431 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
432 tc.WriteLine ("}\n");
434 if (config_dir != null)
435 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
437 tc.WriteLine ("static const char *config_dir = NULL;");
439 Stream template_stream;
441 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
443 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
446 StreamReader s = new StreamReader (template_stream);
447 string template = s.ReadToEnd ();
451 Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
452 StreamReader st = new StreamReader (template_main_stream);
453 string maintemplate = st.ReadToEnd ();
454 tc.Write (maintemplate);
462 string zlib = (compress ? "-lz" : "");
463 string debugging = "-g";
464 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
466 if (style == "linux")
471 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
473 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
474 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
475 "`pkg-config --libs-only-L mono-2` " + smonolib +
476 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
477 temp_c, temp_o, output, zlib, cc);
480 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
481 temp_c, temp_o, output, zlib, cc);
489 Console.WriteLine ("Done");
494 if (object_out == null){
495 File.Delete (temp_o);
498 File.Delete (temp_c);
500 File.Delete (temp_s);
505 static List<Assembly> LoadAssemblies (List<string> sources)
507 List<Assembly> assemblies = new List<Assembly> ();
510 foreach (string name in sources){
511 Assembly a = LoadAssembly (name);
522 Environment.Exit (1);
527 static void QueueAssembly (List<string> files, string codebase)
529 if (files.Contains (codebase))
532 files.Add (codebase);
533 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
538 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
539 a = Assembly.Load (an);
540 QueueAssembly (files, a.CodeBase);
544 static Assembly LoadAssembly (string assembly)
549 char[] path_chars = { '/', '\\' };
551 if (assembly.IndexOfAny (path_chars) != -1) {
552 a = Assembly.LoadFrom (assembly);
554 string ass = assembly;
555 if (ass.EndsWith (".dll"))
556 ass = assembly.Substring (0, assembly.Length - 4);
557 a = Assembly.Load (ass);
560 } catch (FileNotFoundException){
561 string total_log = "";
563 foreach (string dir in link_paths){
564 string full_path = Path.Combine (dir, assembly);
565 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
569 a = Assembly.LoadFrom (full_path);
571 } catch (FileNotFoundException ff) {
572 total_log += ff.FusionLog;
576 Error ("Cannot find assembly `" + assembly + "'" );
577 Console.WriteLine ("Log: \n" + total_log);
578 } catch (BadImageFormatException f) {
579 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
580 } catch (FileLoadException f){
581 Error ("Cannot load assembly " + f.FusionLog);
582 } catch (ArgumentNullException){
583 Error("Cannot load assembly (null argument)");
588 static void Error (string msg)
590 Console.Error.WriteLine (msg);
591 Environment.Exit (1);
596 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
598 " -c Produce stub only, do not compile\n" +
599 " -o out Specifies output filename\n" +
600 " -oo obj Specifies output filename for helper object file\n" +
601 " -L path Adds `path' to the search path for assemblies\n" +
602 " --nodeps Turns off automatic dependency embedding (default)\n" +
603 " --deps Turns on automatic dependency embedding\n" +
604 " --keeptemp Keeps the temporary files\n" +
605 " --config F Bundle system config file `F'\n" +
606 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
607 " --machine-config F Use the given file as the machine.config for the application.\n" +
608 " --static Statically link to mono libs\n" +
609 " --nomain Don't include a main() function, for libraries\n" +
610 " -z Compress the assemblies before embedding.\n" +
611 " You need zlib development headers and libraries.\n");
615 static extern int system (string s);
617 static extern int uname (IntPtr buf);
619 static void DetectOS ()
622 Console.WriteLine ("OS is: Windows");
627 IntPtr buf = Marshal.AllocHGlobal (8192);
628 if (uname (buf) != 0){
629 Console.WriteLine ("Warning: Unable to detect OS");
630 Marshal.FreeHGlobal (buf);
633 string os = Marshal.PtrToStringAnsi (buf);
634 Console.WriteLine ("OS is: " + os);
638 Marshal.FreeHGlobal (buf);
643 int p = (int) Environment.OSVersion.Platform;
644 return ((p == 4) || (p == 128) || (p == 6));
648 static int Execute (string cmdLine)
651 Console.WriteLine (cmdLine);
652 return system (cmdLine);
655 // on Windows, we have to pipe the output of a
656 // `cmd` interpolation to dos2unix, because the shell does not
657 // strip the CRLFs generated by the native pkg-config distributed
659 StringBuilder b = new StringBuilder ();
661 for (int i = 0; i < cmdLine.Length; i++) {
662 if (cmdLine [i] == '`') {
663 if (count % 2 != 0) {
664 b.Append ("|dos2unix");
668 b.Append (cmdLine [i]);
670 cmdLine = b.ToString ();
671 Console.WriteLine (cmdLine);
673 ProcessStartInfo psi = new ProcessStartInfo ();
674 psi.UseShellExecute = false;
676 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
678 using (Process p = Process.Start (psi)) {
684 static string GetEnv (string name, string defaultValue)
686 string s = Environment.GetEnvironmentVariable (name);
687 return s != null ? s : defaultValue;