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.Runtime.InteropServices;
20 using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
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]);
91 if (style == "windows") {
92 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", 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];
132 sources.Add (args [i]);
137 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
138 if (sources.Count == 0 || output == null) {
140 Environment.Exit (1);
143 ArrayList assemblies = LoadAssemblies (sources);
144 ArrayList files = new ArrayList ();
145 foreach (Assembly a in assemblies)
146 QueueAssembly (files, a.CodeBase);
148 GenerateBundles (files);
149 //GenerateJitWrapper ();
154 static void WriteSymbol (StreamWriter sw, string name, long size)
160 "\t.section .rodata\n" +
162 "\t.type {0}, @object\n" +
163 "\t.size {0}, {1}\n" +
169 "\t.section __TEXT,__text,regular,pure_instructions\n" +
170 "\t.section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n" +
180 "\t.section .rdata,\"dr\"\n" +
188 static void GenerateBundles (ArrayList files)
190 string temp_s = "temp.s"; // Path.GetTempFileName ();
191 string temp_c = "temp.c";
192 string temp_o = "temp.o";
196 if (object_out != null)
200 ArrayList c_bundle_names = new ArrayList ();
201 ArrayList config_names = new ArrayList ();
202 byte [] buffer = new byte [8192];
204 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
205 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
208 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
209 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
210 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
213 tc.WriteLine ("typedef struct _compressed_data {");
214 tc.WriteLine ("\tMonoBundledAssembly assembly;");
215 tc.WriteLine ("\tint compressed_size;");
216 tc.WriteLine ("} CompressedAssembly;\n");
219 foreach (string url in files){
220 string fname = new Uri (url).LocalPath;
221 string aname = Path.GetFileName (fname);
222 string encoded = aname.Replace ("-", "_").Replace (".", "_");
227 Console.WriteLine (" embedding: " + fname);
229 Stream stream = File.OpenRead (fname);
231 long real_size = stream.Length;
234 MemoryStream ms = new MemoryStream ();
235 DeflaterOutputStream deflate = new DeflaterOutputStream (ms);
236 while ((n = stream.Read (buffer, 0, 8192)) != 0){
237 deflate.Write (buffer, 0, n);
241 byte [] bytes = ms.GetBuffer ();
242 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
245 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
247 while ((n = stream.Read (buffer, 0, 8192)) != 0){
248 for (int i = 0; i < n; i++){
249 ts.Write ("\t.byte {0}\n", buffer [i]);
255 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
256 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
257 " assembly_data_{0}, {2}}}, {3}}};",
258 encoded, aname, real_size, stream.Length);
259 double ratio = ((double) stream.Length * 100) / real_size;
260 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
262 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
263 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
264 encoded, aname, real_size);
268 c_bundle_names.Add ("assembly_bundle_" + encoded);
271 FileStream cf = File.OpenRead (fname + ".config");
272 Console.WriteLine (" config from: " + fname + ".config");
273 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
274 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
275 while ((n = cf.Read (buffer, 0, 8192)) != 0){
276 for (int i = 0; i < n; i++){
277 ts.Write ("\t.byte {0}\n", buffer [i]);
281 config_names.Add (new string[] {aname, encoded});
282 } catch (FileNotFoundException) {
283 /* we ignore if the config file doesn't exist */
287 if (config_file != null){
290 conf = File.OpenRead (config_file);
292 Error (String.Format ("Failure to open {0}", config_file));
295 Console.WriteLine ("System config from: " + config_file);
296 tc.WriteLine ("extern const unsigned char system_config;");
297 WriteSymbol (ts, "system_config", config_file.Length);
300 while ((n = conf.Read (buffer, 0, 8192)) != 0){
301 for (int i = 0; i < n; i++){
302 ts.Write ("\t.byte {0}\n", buffer [i]);
306 ts.Write ("\t.byte 0\n");
310 if (machine_config_file != null){
313 conf = File.OpenRead (machine_config_file);
315 Error (String.Format ("Failure to open {0}", machine_config_file));
318 Console.WriteLine ("Machine config from: " + machine_config_file);
319 tc.WriteLine ("extern const unsigned char machine_config;");
320 WriteSymbol (ts, "machine_config", machine_config_file.Length);
323 while ((n = conf.Read (buffer, 0, 8192)) != 0){
324 for (int i = 0; i < n; i++){
325 ts.Write ("\t.byte {0}\n", buffer [i]);
329 ts.Write ("\t.byte 0\n");
334 Console.WriteLine ("Compiling:");
335 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
336 int ret = Execute (cmd);
343 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
345 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
347 foreach (string c in c_bundle_names){
348 tc.WriteLine ("\t&{0},", c);
350 tc.WriteLine ("\tNULL\n};\n");
351 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
353 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
354 foreach (string[] ass in config_names){
355 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
357 if (config_file != null)
358 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
359 if (machine_config_file != null)
360 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
361 tc.WriteLine ("}\n");
363 if (config_dir != null)
364 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
366 tc.WriteLine ("static const char *config_dir = NULL;");
368 Stream template_stream;
370 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
372 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
375 StreamReader s = new StreamReader (template_stream);
376 string template = s.ReadToEnd ();
380 Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
381 StreamReader st = new StreamReader (template_main_stream);
382 string maintemplate = st.ReadToEnd ();
383 tc.Write (maintemplate);
391 string zlib = (compress ? "-lz" : "");
392 string debugging = "-g";
393 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
395 if (style == "linux")
400 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
402 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
403 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
404 "`pkg-config --libs-only-L mono-2` " + smonolib +
405 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
406 temp_c, temp_o, output, zlib, cc);
409 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
410 temp_c, temp_o, output, zlib, cc);
418 Console.WriteLine ("Done");
423 if (object_out == null){
424 File.Delete (temp_o);
427 File.Delete (temp_c);
429 File.Delete (temp_s);
434 static ArrayList LoadAssemblies (ArrayList sources)
436 ArrayList assemblies = new ArrayList ();
439 foreach (string name in sources){
440 Assembly a = LoadAssembly (name);
451 Environment.Exit (1);
456 static void QueueAssembly (ArrayList files, string codebase)
458 if (files.Contains (codebase))
461 files.Add (codebase);
462 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
467 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
468 a = Assembly.Load (an);
469 QueueAssembly (files, a.CodeBase);
473 static Assembly LoadAssembly (string assembly)
478 char[] path_chars = { '/', '\\' };
480 if (assembly.IndexOfAny (path_chars) != -1) {
481 a = Assembly.LoadFrom (assembly);
483 string ass = assembly;
484 if (ass.EndsWith (".dll"))
485 ass = assembly.Substring (0, assembly.Length - 4);
486 a = Assembly.Load (ass);
489 } catch (FileNotFoundException){
490 string total_log = "";
492 foreach (string dir in link_paths){
493 string full_path = Path.Combine (dir, assembly);
494 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
498 a = Assembly.LoadFrom (full_path);
500 } catch (FileNotFoundException ff) {
501 total_log += ff.FusionLog;
505 Error ("Cannot find assembly `" + assembly + "'" );
506 Console.WriteLine ("Log: \n" + total_log);
507 } catch (BadImageFormatException f) {
508 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
509 } catch (FileLoadException f){
510 Error ("Cannot load assembly " + f.FusionLog);
511 } catch (ArgumentNullException){
512 Error("Cannot load assembly (null argument)");
517 static void Error (string msg)
519 Console.Error.WriteLine (msg);
520 Environment.Exit (1);
525 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
527 " -c Produce stub only, do not compile\n" +
528 " -o out Specifies output filename\n" +
529 " -oo obj Specifies output filename for helper object file\n" +
530 " -L path Adds `path' to the search path for assemblies\n" +
531 " --nodeps Turns off automatic dependency embedding (default)\n" +
532 " --deps Turns on automatic dependency embedding\n" +
533 " --keeptemp Keeps the temporary files\n" +
534 " --config F Bundle system config file `F'\n" +
535 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
536 " --machine-config F Use the given file as the machine.config for the application.\n" +
537 " --static Statically link to mono libs\n" +
538 " --nomain Don't include a main() function, for libraries\n" +
539 " -z Compress the assemblies before embedding.\n" +
540 " You need zlib development headers and libraries.\n");
544 static extern int system (string s);
546 static extern int uname (IntPtr buf);
548 static void DetectOS ()
551 Console.WriteLine ("OS is: Windows");
556 IntPtr buf = UnixMarshal.AllocHeap(8192);
557 if (uname (buf) != 0){
558 Console.WriteLine ("Warning: Unable to detect OS");
559 UnixMarshal.FreeHeap(buf);
562 string os = Marshal.PtrToStringAnsi (buf);
563 Console.WriteLine ("OS is: " + os);
567 UnixMarshal.FreeHeap(buf);
572 int p = (int) Environment.OSVersion.Platform;
573 return ((p == 4) || (p == 128) || (p == 6));
577 static int Execute (string cmdLine)
580 Console.WriteLine (cmdLine);
581 return system (cmdLine);
584 // on Windows, we have to pipe the output of a
585 // `cmd` interpolation to dos2unix, because the shell does not
586 // strip the CRLFs generated by the native pkg-config distributed
588 StringBuilder b = new StringBuilder ();
590 for (int i = 0; i < cmdLine.Length; i++) {
591 if (cmdLine [i] == '`') {
592 if (count % 2 != 0) {
593 b.Append ("|dos2unix");
597 b.Append (cmdLine [i]);
599 cmdLine = b.ToString ();
600 Console.WriteLine (cmdLine);
602 ProcessStartInfo psi = new ProcessStartInfo ();
603 psi.UseShellExecute = false;
605 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
607 using (Process p = Process.Start (psi)) {
613 static string GetEnv (string name, string defaultValue)
615 string s = Environment.GetEnvironmentVariable (name);
616 return s != null ? s : defaultValue;