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;
19 using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
22 static string output = "a.out";
23 static string object_out = null;
24 static ArrayList link_paths = new ArrayList ();
25 static bool autodeps = false;
26 static bool keeptemp = false;
27 static bool compile_only = false;
28 static bool static_link = false;
29 static string config_file = null;
30 static string machine_config_file = null;
31 static string config_dir = null;
32 static string style = "linux";
36 static int Main (string [] args)
38 ArrayList sources = new ArrayList ();
39 int top = args.Length;
44 for (int i = 0; i < top; i++){
46 case "--help": case "-h": case "-?":
67 object_out = args [++i];
75 link_paths.Add (args [++i]);
90 if (style == "windows") {
91 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
95 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
96 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
104 config_file = args [++i];
106 case "--machine-config":
112 machine_config_file = args [++i];
114 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
122 config_dir = args [++i];
131 sources.Add (args [i]);
136 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
137 if (sources.Count == 0 || output == null) {
139 Environment.Exit (1);
142 ArrayList assemblies = LoadAssemblies (sources);
143 ArrayList files = new ArrayList ();
144 foreach (Assembly a in assemblies)
145 QueueAssembly (files, a.CodeBase);
147 GenerateBundles (files);
148 //GenerateJitWrapper ();
153 static void WriteSymbol (StreamWriter sw, string name, long size)
159 "\t.section .rodata\n" +
161 "\t.type {0}, @object\n" +
162 "\t.size {0}, {1}\n" +
168 "\t.section __TEXT,__text,regular,pure_instructions\n" +
169 "\t.section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n" +
179 "\t.section .rdata,\"dr\"\n" +
187 static void GenerateBundles (ArrayList files)
189 string temp_s = "temp.s"; // Path.GetTempFileName ();
190 string temp_c = "temp.c";
191 string temp_o = "temp.o";
195 if (object_out != null)
199 ArrayList c_bundle_names = new ArrayList ();
200 ArrayList config_names = new ArrayList ();
201 byte [] buffer = new byte [8192];
203 StreamWriter ts = new StreamWriter (File.Create (temp_s));
204 StreamWriter tc = new StreamWriter (File.Create (temp_c));
207 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
208 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
211 tc.WriteLine ("typedef struct _compressed_data {");
212 tc.WriteLine ("\tMonoBundledAssembly assembly;");
213 tc.WriteLine ("\tint compressed_size;");
214 tc.WriteLine ("} CompressedAssembly;\n");
217 foreach (string url in files){
218 string fname = new Uri (url).LocalPath;
219 string aname = Path.GetFileName (fname);
220 string encoded = aname.Replace ("-", "_").Replace (".", "_");
225 Console.WriteLine (" embedding: " + fname);
227 Stream stream = File.OpenRead (fname);
229 long real_size = stream.Length;
232 MemoryStream ms = new MemoryStream ();
233 DeflaterOutputStream deflate = new DeflaterOutputStream (ms);
234 while ((n = stream.Read (buffer, 0, 8192)) != 0){
235 deflate.Write (buffer, 0, n);
239 byte [] bytes = ms.GetBuffer ();
240 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
243 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
245 while ((n = stream.Read (buffer, 0, 8192)) != 0){
246 for (int i = 0; i < n; i++){
247 ts.Write ("\t.byte {0}\n", buffer [i]);
253 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
254 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
255 " assembly_data_{0}, {2}}}, {3}}};",
256 encoded, aname, real_size, stream.Length);
257 double ratio = ((double) stream.Length * 100) / real_size;
258 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
260 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
261 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
262 encoded, aname, real_size);
266 c_bundle_names.Add ("assembly_bundle_" + encoded);
269 FileStream cf = File.OpenRead (fname + ".config");
270 Console.WriteLine (" config from: " + fname + ".config");
271 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
272 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
273 while ((n = cf.Read (buffer, 0, 8192)) != 0){
274 for (int i = 0; i < n; i++){
275 ts.Write ("\t.byte {0}\n", buffer [i]);
279 config_names.Add (new string[] {aname, encoded});
280 } catch (FileNotFoundException) {
281 /* we ignore if the config file doesn't exist */
285 if (config_file != null){
288 conf = File.OpenRead (config_file);
290 Error (String.Format ("Failure to open {0}", config_file));
293 Console.WriteLine ("System config from: " + config_file);
294 tc.WriteLine ("extern const unsigned char system_config;");
295 WriteSymbol (ts, "system_config", config_file.Length);
298 while ((n = conf.Read (buffer, 0, 8192)) != 0){
299 for (int i = 0; i < n; i++){
300 ts.Write ("\t.byte {0}\n", buffer [i]);
304 ts.Write ("\t.byte 0\n");
308 if (machine_config_file != null){
311 conf = File.OpenRead (machine_config_file);
313 Error (String.Format ("Failure to open {0}", machine_config_file));
316 Console.WriteLine ("Machine config from: " + machine_config_file);
317 tc.WriteLine ("extern const unsigned char machine_config;");
318 WriteSymbol (ts, "machine_config", machine_config_file.Length);
321 while ((n = conf.Read (buffer, 0, 8192)) != 0){
322 for (int i = 0; i < n; i++){
323 ts.Write ("\t.byte {0}\n", buffer [i]);
327 ts.Write ("\t.byte 0\n");
332 Console.WriteLine ("Compiling:");
333 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
334 int ret = Execute (cmd);
341 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
343 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
345 foreach (string c in c_bundle_names){
346 tc.WriteLine ("\t&{0},", c);
348 tc.WriteLine ("\tNULL\n};\n");
349 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
351 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
352 foreach (string[] ass in config_names){
353 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
355 if (config_file != null)
356 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
357 if (machine_config_file != null)
358 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
359 tc.WriteLine ("}\n");
361 if (config_dir != null)
362 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
364 tc.WriteLine ("static const char *config_dir = NULL;");
366 Stream template_stream;
368 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
370 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
373 StreamReader s = new StreamReader (template_stream);
374 string template = s.ReadToEnd ();
378 Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
379 StreamReader st = new StreamReader (template_main_stream);
380 string maintemplate = st.ReadToEnd ();
381 tc.Write (maintemplate);
389 string zlib = (compress ? "-lz" : "");
390 string debugging = "-g";
391 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
393 if (style == "linux")
398 smonolib = "`pkg-config --variable=libdir mono`/libmono.a ";
400 smonolib = "-Wl,-Bstatic -lmono -Wl,-Bdynamic ";
401 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono` {0} {3} " +
402 "`pkg-config --libs-only-L mono` " + smonolib +
403 "`pkg-config --libs-only-l mono | sed -e \"s/\\-lmono //\"` {1}",
404 temp_c, temp_o, output, zlib, cc);
407 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono` {3} {1}",
408 temp_c, temp_o, output, zlib, cc);
416 Console.WriteLine ("Done");
419 if (object_out == null){
420 File.Delete (temp_o);
423 File.Delete (temp_c);
425 File.Delete (temp_s);
430 static ArrayList LoadAssemblies (ArrayList sources)
432 ArrayList assemblies = new ArrayList ();
435 foreach (string name in sources){
436 Assembly a = LoadAssembly (name);
447 Environment.Exit (1);
452 static void QueueAssembly (ArrayList files, string codebase)
454 if (files.Contains (codebase))
457 files.Add (codebase);
458 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
463 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
464 a = Assembly.Load (an);
465 QueueAssembly (files, a.CodeBase);
469 static Assembly LoadAssembly (string assembly)
474 char[] path_chars = { '/', '\\' };
476 if (assembly.IndexOfAny (path_chars) != -1) {
477 a = Assembly.LoadFrom (assembly);
479 string ass = assembly;
480 if (ass.EndsWith (".dll"))
481 ass = assembly.Substring (0, assembly.Length - 4);
482 a = Assembly.Load (ass);
485 } catch (FileNotFoundException){
486 string total_log = "";
488 foreach (string dir in link_paths){
489 string full_path = Path.Combine (dir, assembly);
490 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
494 a = Assembly.LoadFrom (full_path);
496 } catch (FileNotFoundException ff) {
497 total_log += ff.FusionLog;
501 Error ("Cannot find assembly `" + assembly + "'" );
502 Console.WriteLine ("Log: \n" + total_log);
503 } catch (BadImageFormatException f) {
504 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
505 } catch (FileLoadException f){
506 Error ("Cannot load assembly " + f.FusionLog);
507 } catch (ArgumentNullException){
508 Error("Cannot load assembly (null argument)");
513 static void Error (string msg)
515 Console.Error.WriteLine (msg);
516 Environment.Exit (1);
521 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
523 " -c Produce stub only, do not compile\n" +
524 " -o out Specifies output filename\n" +
525 " -oo obj Specifies output filename for helper object file\n" +
526 " -L path Adds `path' to the search path for assemblies\n" +
527 " --nodeps Turns off automatic dependency embedding (default)\n" +
528 " --deps Turns on automatic dependency embedding\n" +
529 " --keeptemp Keeps the temporary files\n" +
530 " --config F Bundle system config file `F'\n" +
531 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
532 " --static Statically link to mono libs\n" +
533 " --nomain Don't include a main() function, for libraries\n" +
534 " -z Compress the assemblies before embedding.\n");
538 static extern int system (string s);
540 static extern int uname (IntPtr buf);
542 static void DetectOS ()
545 Console.WriteLine ("OS is: Windows");
550 IntPtr buf = UnixMarshal.AllocHeap(8192);
551 if (uname (buf) != 0){
552 Console.WriteLine ("Warning: Unable to detect OS");
555 string os = Marshal.PtrToStringAnsi (buf);
556 Console.WriteLine ("OS is: " + os);
560 UnixMarshal.FreeHeap(buf);
565 int p = (int) Environment.OSVersion.Platform;
566 return ((p == 4) || (p == 128));
570 static int Execute (string cmdLine)
572 Console.WriteLine (cmdLine);
574 return system (cmdLine);
576 Process p = Process.Start ("sh", String.Format ("-c \"{0}\"", cmdLine));
582 static string GetEnv (string name, string defaultValue)
584 string s = Environment.GetEnvironmentVariable (name);
585 return s != null ? s : defaultValue;