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;
15 using System.Reflection;
17 using System.IO.Compression;
18 using System.Runtime.InteropServices;
23 static string output = "a.out";
24 static string object_out = null;
25 static ArrayList link_paths = new ArrayList ();
26 static bool autodeps = false;
27 static bool keeptemp = false;
28 static bool compile_only = false;
29 static bool static_link = false;
30 static string config_file = null;
31 static string machine_config_file = null;
32 static string config_dir = null;
33 static string style = "linux";
37 static int Main (string [] args)
39 ArrayList sources = new ArrayList ();
40 int top = args.Length;
45 for (int i = 0; i < top; i++){
47 case "--help": case "-h": case "-?":
68 object_out = args [++i];
76 link_paths.Add (args [++i]);
92 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
93 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
101 config_file = args [++i];
103 case "--machine-config":
109 machine_config_file = args [++i];
111 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
119 config_dir = args [++i];
139 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
145 sources.Add (args [i]);
149 if (static_link && style == "windows") {
150 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
155 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
156 if (sources.Count == 0 || output == null) {
158 Environment.Exit (1);
161 ArrayList assemblies = LoadAssemblies (sources);
162 ArrayList files = new ArrayList ();
163 foreach (Assembly a in assemblies)
164 QueueAssembly (files, a.CodeBase);
166 // Special casing mscorlib.dll: any specified mscorlib.dll cannot be loaded
167 // by Assembly.ReflectionFromLoadFrom(). Instead the fx assembly which runs
168 // mkbundle.exe is loaded, which is not what we want.
169 // So, replace it with whatever actually specified.
170 foreach (string srcfile in sources) {
171 if (Path.GetFileName (srcfile) == "mscorlib.dll") {
172 foreach (string file in files) {
173 if (Path.GetFileName (new Uri (file).LocalPath) == "mscorlib.dll") {
175 files.Add (new Uri (Path.GetFullPath (srcfile)).LocalPath);
183 GenerateBundles (files);
184 //GenerateJitWrapper ();
189 static void WriteSymbol (StreamWriter sw, string name, long size)
195 "\t.section .rodata\n" +
197 "\t.type {0}, \"object\"\n" +
198 "\t.size {0}, {1}\n" +
204 "\t.section __TEXT,__text,regular,pure_instructions\n" +
214 "\t.section .rdata,\"dr\"\n" +
222 static string [] chars = new string [256];
224 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
228 // Preallocate the strings we need.
229 if (chars [0] == null) {
230 for (int i = 0; i < chars.Length; i++)
231 chars [i] = string.Format ("\t.byte {0}\n", i.ToString ());
234 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
235 for (int i = 0; i < n; i++)
236 ts.Write (chars [buffer [i]]);
242 static void GenerateBundles (ArrayList files)
244 string temp_s = "temp.s"; // Path.GetTempFileName ();
245 string temp_c = "temp.c";
246 string temp_o = "temp.o";
250 if (object_out != null)
254 ArrayList c_bundle_names = new ArrayList ();
255 ArrayList config_names = new ArrayList ();
256 byte [] buffer = new byte [8192];
258 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
259 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
262 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
263 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
264 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
267 tc.WriteLine ("typedef struct _compressed_data {");
268 tc.WriteLine ("\tMonoBundledAssembly assembly;");
269 tc.WriteLine ("\tint compressed_size;");
270 tc.WriteLine ("} CompressedAssembly;\n");
273 foreach (string url in files){
274 string fname = new Uri (url).LocalPath;
275 string aname = Path.GetFileName (fname);
276 string encoded = aname.Replace ("-", "_").Replace (".", "_");
281 Console.WriteLine (" embedding: " + fname);
283 Stream stream = File.OpenRead (fname);
285 // Compression can be parallelized
286 long real_size = stream.Length;
289 MemoryStream ms = new MemoryStream ();
290 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
291 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){
292 deflate.Write (buffer, 0, n);
296 byte [] bytes = ms.GetBuffer ();
297 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
300 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
302 WriteBuffer (ts, stream, buffer);
305 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
306 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
307 " assembly_data_{0}, {2}}}, {3}}};",
308 encoded, aname, real_size, stream.Length);
309 double ratio = ((double) stream.Length * 100) / real_size;
310 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
312 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
313 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
314 encoded, aname, real_size);
318 c_bundle_names.Add ("assembly_bundle_" + encoded);
321 FileStream cf = File.OpenRead (fname + ".config");
322 Console.WriteLine (" config from: " + fname + ".config");
323 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
324 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
325 WriteBuffer (ts, cf, buffer);
327 config_names.Add (new string[] {aname, encoded});
328 } catch (FileNotFoundException) {
329 /* we ignore if the config file doesn't exist */
333 if (config_file != null){
336 conf = File.OpenRead (config_file);
338 Error (String.Format ("Failure to open {0}", config_file));
341 Console.WriteLine ("System config from: " + config_file);
342 tc.WriteLine ("extern const char system_config;");
343 WriteSymbol (ts, "system_config", config_file.Length);
345 WriteBuffer (ts, conf, buffer);
347 ts.Write ("\t.byte 0\n");
351 if (machine_config_file != null){
354 conf = File.OpenRead (machine_config_file);
356 Error (String.Format ("Failure to open {0}", machine_config_file));
359 Console.WriteLine ("Machine config from: " + machine_config_file);
360 tc.WriteLine ("extern const char machine_config;");
361 WriteSymbol (ts, "machine_config", machine_config_file.Length);
363 WriteBuffer (ts, conf, buffer);
364 ts.Write ("\t.byte 0\n");
369 Console.WriteLine ("Compiling:");
370 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
371 int ret = Execute (cmd);
378 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
380 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
382 foreach (string c in c_bundle_names){
383 tc.WriteLine ("\t&{0},", c);
385 tc.WriteLine ("\tNULL\n};\n");
386 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
388 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
389 foreach (string[] ass in config_names){
390 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
392 if (config_file != null)
393 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
394 if (machine_config_file != null)
395 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
396 tc.WriteLine ("}\n");
398 if (config_dir != null)
399 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
401 tc.WriteLine ("static const char *config_dir = NULL;");
403 Stream template_stream;
405 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
407 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
410 StreamReader s = new StreamReader (template_stream);
411 string template = s.ReadToEnd ();
415 Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
416 StreamReader st = new StreamReader (template_main_stream);
417 string maintemplate = st.ReadToEnd ();
418 tc.Write (maintemplate);
426 string zlib = (compress ? "-lz" : "");
427 string debugging = "-g";
428 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
430 if (style == "linux")
435 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
437 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
438 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
439 "`pkg-config --libs-only-L mono-2` " + smonolib +
440 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
441 temp_c, temp_o, output, zlib, cc);
444 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
445 temp_c, temp_o, output, zlib, cc);
453 Console.WriteLine ("Done");
458 if (object_out == null){
459 File.Delete (temp_o);
462 File.Delete (temp_c);
464 File.Delete (temp_s);
469 static ArrayList LoadAssemblies (ArrayList sources)
471 ArrayList assemblies = new ArrayList ();
474 foreach (string name in sources){
475 Assembly a = LoadAssembly (name);
486 Environment.Exit (1);
491 static void QueueAssembly (ArrayList files, string codebase)
493 if (files.Contains (codebase))
496 files.Add (codebase);
497 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
502 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
503 a = Assembly.Load (an);
504 QueueAssembly (files, a.CodeBase);
508 static Assembly LoadAssembly (string assembly)
513 char[] path_chars = { '/', '\\' };
515 if (assembly.IndexOfAny (path_chars) != -1) {
516 a = Assembly.LoadFrom (assembly);
518 string ass = assembly;
519 if (ass.EndsWith (".dll"))
520 ass = assembly.Substring (0, assembly.Length - 4);
521 a = Assembly.Load (ass);
524 } catch (FileNotFoundException){
525 string total_log = "";
527 foreach (string dir in link_paths){
528 string full_path = Path.Combine (dir, assembly);
529 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
533 a = Assembly.LoadFrom (full_path);
535 } catch (FileNotFoundException ff) {
536 total_log += ff.FusionLog;
540 Error ("Cannot find assembly `" + assembly + "'" );
541 Console.WriteLine ("Log: \n" + total_log);
542 } catch (BadImageFormatException f) {
543 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
544 } catch (FileLoadException f){
545 Error ("Cannot load assembly " + f.FusionLog);
546 } catch (ArgumentNullException){
547 Error("Cannot load assembly (null argument)");
552 static void Error (string msg)
554 Console.Error.WriteLine (msg);
555 Environment.Exit (1);
560 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
562 " -c Produce stub only, do not compile\n" +
563 " -o out Specifies output filename\n" +
564 " -oo obj Specifies output filename for helper object file\n" +
565 " -L path Adds `path' to the search path for assemblies\n" +
566 " --nodeps Turns off automatic dependency embedding (default)\n" +
567 " --deps Turns on automatic dependency embedding\n" +
568 " --keeptemp Keeps the temporary files\n" +
569 " --config F Bundle system config file `F'\n" +
570 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
571 " --machine-config F Use the given file as the machine.config for the application.\n" +
572 " --static Statically link to mono libs\n" +
573 " --nomain Don't include a main() function, for libraries\n" +
574 " -z Compress the assemblies before embedding.\n" +
575 " You need zlib development headers and libraries.\n");
579 static extern int system (string s);
581 static extern int uname (IntPtr buf);
583 static void DetectOS ()
586 Console.WriteLine ("OS is: Windows");
591 IntPtr buf = Marshal.AllocHGlobal (8192);
592 if (uname (buf) != 0){
593 Console.WriteLine ("Warning: Unable to detect OS");
594 Marshal.FreeHGlobal (buf);
597 string os = Marshal.PtrToStringAnsi (buf);
598 Console.WriteLine ("OS is: " + os);
602 Marshal.FreeHGlobal (buf);
607 int p = (int) Environment.OSVersion.Platform;
608 return ((p == 4) || (p == 128) || (p == 6));
612 static int Execute (string cmdLine)
615 Console.WriteLine (cmdLine);
616 return system (cmdLine);
619 // on Windows, we have to pipe the output of a
620 // `cmd` interpolation to dos2unix, because the shell does not
621 // strip the CRLFs generated by the native pkg-config distributed
623 StringBuilder b = new StringBuilder ();
625 for (int i = 0; i < cmdLine.Length; i++) {
626 if (cmdLine [i] == '`') {
627 if (count % 2 != 0) {
628 b.Append ("|dos2unix");
632 b.Append (cmdLine [i]);
634 cmdLine = b.ToString ();
635 Console.WriteLine (cmdLine);
637 ProcessStartInfo psi = new ProcessStartInfo ();
638 psi.UseShellExecute = false;
640 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
642 using (Process p = Process.Start (psi)) {
648 static string GetEnv (string name, string defaultValue)
650 string s = Environment.GetEnvironmentVariable (name);
651 return s != null ? s : defaultValue;