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 ("\t.byte {0}\n", i.ToString ());
238 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
239 for (int i = 0; i < n; i++)
240 ts.Write (chars [buffer [i]]);
246 static void GenerateBundles (List<string> files)
248 string temp_s = "temp.s"; // Path.GetTempFileName ();
249 string temp_c = "temp.c";
250 string temp_o = "temp.o";
254 if (object_out != null)
258 List<string> c_bundle_names = new List<string> ();
259 List<string[]> config_names = new List<string[]> ();
260 byte [] buffer = new byte [8192];
262 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
263 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
266 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
267 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
268 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
271 tc.WriteLine ("typedef struct _compressed_data {");
272 tc.WriteLine ("\tMonoBundledAssembly assembly;");
273 tc.WriteLine ("\tint compressed_size;");
274 tc.WriteLine ("} CompressedAssembly;\n");
277 object monitor = new object ();
279 // Do the file reading and compression in parallel
280 Action<string> body = delegate (string url) {
281 string fname = new Uri (url).LocalPath;
282 string aname = Path.GetFileName (fname);
283 string encoded = aname.Replace ("-", "_").Replace (".", "_");
288 Stream stream = File.OpenRead (fname);
290 long real_size = stream.Length;
293 MemoryStream ms = new MemoryStream ();
294 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
295 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){
296 deflate.Write (buffer, 0, n);
300 byte [] bytes = ms.GetBuffer ();
301 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
304 // The non-parallel part
306 Console.WriteLine (" embedding: " + fname);
308 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
310 WriteBuffer (ts, stream, buffer);
313 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
314 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
315 " assembly_data_{0}, {2}}}, {3}}};",
316 encoded, aname, real_size, stream.Length);
317 double ratio = ((double) stream.Length * 100) / real_size;
318 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
320 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
321 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
322 encoded, aname, real_size);
326 c_bundle_names.Add ("assembly_bundle_" + encoded);
329 FileStream cf = File.OpenRead (fname + ".config");
330 Console.WriteLine (" config from: " + fname + ".config");
331 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
332 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
333 WriteBuffer (ts, cf, buffer);
335 config_names.Add (new string[] {aname, encoded});
336 } catch (FileNotFoundException) {
337 /* we ignore if the config file doesn't exist */
343 Parallel.ForEach (files, body);
345 foreach (var url in files)
349 if (config_file != null){
352 conf = File.OpenRead (config_file);
354 Error (String.Format ("Failure to open {0}", config_file));
357 Console.WriteLine ("System config from: " + config_file);
358 tc.WriteLine ("extern const char system_config;");
359 WriteSymbol (ts, "system_config", config_file.Length);
361 WriteBuffer (ts, conf, buffer);
363 ts.Write ("\t.byte 0\n");
367 if (machine_config_file != null){
370 conf = File.OpenRead (machine_config_file);
372 Error (String.Format ("Failure to open {0}", machine_config_file));
375 Console.WriteLine ("Machine config from: " + machine_config_file);
376 tc.WriteLine ("extern const char machine_config;");
377 WriteSymbol (ts, "machine_config", machine_config_file.Length);
379 WriteBuffer (ts, conf, buffer);
380 ts.Write ("\t.byte 0\n");
385 Console.WriteLine ("Compiling:");
386 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
387 int ret = Execute (cmd);
394 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
396 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
398 foreach (string c in c_bundle_names){
399 tc.WriteLine ("\t&{0},", c);
401 tc.WriteLine ("\tNULL\n};\n");
402 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
404 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
405 foreach (string[] ass in config_names){
406 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
408 if (config_file != null)
409 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
410 if (machine_config_file != null)
411 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
412 tc.WriteLine ("}\n");
414 if (config_dir != null)
415 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
417 tc.WriteLine ("static const char *config_dir = NULL;");
419 Stream template_stream;
421 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
423 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
426 StreamReader s = new StreamReader (template_stream);
427 string template = s.ReadToEnd ();
431 Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
432 StreamReader st = new StreamReader (template_main_stream);
433 string maintemplate = st.ReadToEnd ();
434 tc.Write (maintemplate);
442 string zlib = (compress ? "-lz" : "");
443 string debugging = "-g";
444 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
446 if (style == "linux")
451 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
453 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
454 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
455 "`pkg-config --libs-only-L mono-2` " + smonolib +
456 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
457 temp_c, temp_o, output, zlib, cc);
460 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
461 temp_c, temp_o, output, zlib, cc);
469 Console.WriteLine ("Done");
474 if (object_out == null){
475 File.Delete (temp_o);
478 File.Delete (temp_c);
480 File.Delete (temp_s);
485 static List<Assembly> LoadAssemblies (List<string> sources)
487 List<Assembly> assemblies = new List<Assembly> ();
490 foreach (string name in sources){
491 Assembly a = LoadAssembly (name);
502 Environment.Exit (1);
507 static void QueueAssembly (List<string> files, string codebase)
509 if (files.Contains (codebase))
512 files.Add (codebase);
513 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
518 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
519 a = Assembly.Load (an);
520 QueueAssembly (files, a.CodeBase);
524 static Assembly LoadAssembly (string assembly)
529 char[] path_chars = { '/', '\\' };
531 if (assembly.IndexOfAny (path_chars) != -1) {
532 a = Assembly.LoadFrom (assembly);
534 string ass = assembly;
535 if (ass.EndsWith (".dll"))
536 ass = assembly.Substring (0, assembly.Length - 4);
537 a = Assembly.Load (ass);
540 } catch (FileNotFoundException){
541 string total_log = "";
543 foreach (string dir in link_paths){
544 string full_path = Path.Combine (dir, assembly);
545 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
549 a = Assembly.LoadFrom (full_path);
551 } catch (FileNotFoundException ff) {
552 total_log += ff.FusionLog;
556 Error ("Cannot find assembly `" + assembly + "'" );
557 Console.WriteLine ("Log: \n" + total_log);
558 } catch (BadImageFormatException f) {
559 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
560 } catch (FileLoadException f){
561 Error ("Cannot load assembly " + f.FusionLog);
562 } catch (ArgumentNullException){
563 Error("Cannot load assembly (null argument)");
568 static void Error (string msg)
570 Console.Error.WriteLine (msg);
571 Environment.Exit (1);
576 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
578 " -c Produce stub only, do not compile\n" +
579 " -o out Specifies output filename\n" +
580 " -oo obj Specifies output filename for helper object file\n" +
581 " -L path Adds `path' to the search path for assemblies\n" +
582 " --nodeps Turns off automatic dependency embedding (default)\n" +
583 " --deps Turns on automatic dependency embedding\n" +
584 " --keeptemp Keeps the temporary files\n" +
585 " --config F Bundle system config file `F'\n" +
586 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
587 " --machine-config F Use the given file as the machine.config for the application.\n" +
588 " --static Statically link to mono libs\n" +
589 " --nomain Don't include a main() function, for libraries\n" +
590 " -z Compress the assemblies before embedding.\n" +
591 " You need zlib development headers and libraries.\n");
595 static extern int system (string s);
597 static extern int uname (IntPtr buf);
599 static void DetectOS ()
602 Console.WriteLine ("OS is: Windows");
607 IntPtr buf = Marshal.AllocHGlobal (8192);
608 if (uname (buf) != 0){
609 Console.WriteLine ("Warning: Unable to detect OS");
610 Marshal.FreeHGlobal (buf);
613 string os = Marshal.PtrToStringAnsi (buf);
614 Console.WriteLine ("OS is: " + os);
618 Marshal.FreeHGlobal (buf);
623 int p = (int) Environment.OSVersion.Platform;
624 return ((p == 4) || (p == 128) || (p == 6));
628 static int Execute (string cmdLine)
631 Console.WriteLine (cmdLine);
632 return system (cmdLine);
635 // on Windows, we have to pipe the output of a
636 // `cmd` interpolation to dos2unix, because the shell does not
637 // strip the CRLFs generated by the native pkg-config distributed
639 StringBuilder b = new StringBuilder ();
641 for (int i = 0; i < cmdLine.Length; i++) {
642 if (cmdLine [i] == '`') {
643 if (count % 2 != 0) {
644 b.Append ("|dos2unix");
648 b.Append (cmdLine [i]);
650 cmdLine = b.ToString ();
651 Console.WriteLine (cmdLine);
653 ProcessStartInfo psi = new ProcessStartInfo ();
654 psi.UseShellExecute = false;
656 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
658 using (Process p = Process.Start (psi)) {
664 static string GetEnv (string name, string defaultValue)
666 string s = Environment.GetEnvironmentVariable (name);
667 return s != null ? s : defaultValue;