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 config_dir = null;
31 static string style = "linux";
34 static int Main (string [] args)
36 ArrayList sources = new ArrayList ();
37 int top = args.Length;
42 for (int i = 0; i < top; i++){
44 case "--help": case "-h": case "-?":
65 object_out = args [++i];
73 link_paths.Add (args [++i]);
88 if (style == "windows") {
89 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
93 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
94 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
102 config_file = args [++i];
110 config_dir = args [++i];
113 if (style == "windows") {
114 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
120 sources.Add (args [i]);
125 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
126 if (sources.Count == 0 || output == null) {
128 Environment.Exit (1);
131 ArrayList assemblies = LoadAssemblies (sources);
132 ArrayList files = new ArrayList ();
133 foreach (Assembly a in assemblies)
134 QueueAssembly (files, a.CodeBase);
136 GenerateBundles (files);
137 //GenerateJitWrapper ();
142 static void WriteSymbol (StreamWriter sw, string name, long size)
148 "\t.section .rodata\n" +
150 "\t.type {0}, @object\n" +
151 "\t.size {0}, {1}\n" +
157 "\t.section __TEXT,__text,regular,pure_instructions\n" +
158 "\t.section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n" +
168 "\t.section .rdata,\"dr\"\n" +
176 static void GenerateBundles (ArrayList files)
178 string temp_s = "temp.s"; // Path.GetTempFileName ();
179 string temp_c = "temp.c";
180 string temp_o = "temp.o";
184 if (object_out != null)
188 ArrayList c_bundle_names = new ArrayList ();
189 ArrayList config_names = new ArrayList ();
190 byte [] buffer = new byte [8192];
192 StreamWriter ts = new StreamWriter (File.Create (temp_s));
193 StreamWriter tc = new StreamWriter (File.Create (temp_c));
196 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
197 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
200 tc.WriteLine ("typedef struct _compressed_data {");
201 tc.WriteLine ("\tMonoBundledAssembly assembly;");
202 tc.WriteLine ("\tint compressed_size;");
203 tc.WriteLine ("} CompressedAssembly;\n");
206 foreach (string url in files){
207 string fname = new Uri (url).LocalPath;
208 string aname = Path.GetFileName (fname);
209 string encoded = aname.Replace ("-", "_").Replace (".", "_");
214 Console.WriteLine (" embedding: " + fname);
216 Stream stream = File.OpenRead (fname);
218 long real_size = stream.Length;
221 MemoryStream ms = new MemoryStream ();
222 DeflaterOutputStream deflate = new DeflaterOutputStream (ms);
223 while ((n = stream.Read (buffer, 0, 8192)) != 0){
224 deflate.Write (buffer, 0, n);
228 byte [] bytes = ms.GetBuffer ();
229 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
232 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
234 while ((n = stream.Read (buffer, 0, 8192)) != 0){
235 for (int i = 0; i < n; i++){
236 ts.Write ("\t.byte {0}\n", buffer [i]);
242 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
243 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
244 " assembly_data_{0}, {2}}}, {3}}};",
245 encoded, aname, real_size, stream.Length);
246 double ratio = ((double) stream.Length * 100) / real_size;
247 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
249 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
250 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
251 encoded, aname, real_size);
255 c_bundle_names.Add ("assembly_bundle_" + encoded);
258 FileStream cf = File.OpenRead (fname + ".config");
259 Console.WriteLine (" config from: " + fname + ".config");
260 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
261 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
262 while ((n = cf.Read (buffer, 0, 8192)) != 0){
263 for (int i = 0; i < n; i++){
264 ts.Write ("\t.byte {0}\n", buffer [i]);
268 config_names.Add (new string[] {aname, encoded});
269 } catch (FileNotFoundException) {
270 /* we ignore if the config file doesn't exist */
274 if (config_file != null){
277 conf = File.OpenRead (config_file);
279 Error (String.Format ("Failure to open {0}", config_file));
282 Console.WriteLine ("System config from: " + config_file);
283 tc.WriteLine ("extern const unsigned char system_config;");
284 WriteSymbol (ts, "system_config", config_file.Length);
287 while ((n = conf.Read (buffer, 0, 8192)) != 0){
288 for (int i = 0; i < n; i++){
289 ts.Write ("\t.byte {0}\n", buffer [i]);
293 ts.Write ("\t.byte 0\n");
298 Console.WriteLine ("Compiling:");
299 string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
300 int ret = Execute (cmd);
307 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
309 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
311 foreach (string c in c_bundle_names){
312 tc.WriteLine ("\t&{0},", c);
314 tc.WriteLine ("\tNULL\n};\n");
315 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
317 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
318 foreach (string[] ass in config_names){
319 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
321 if (config_file != null)
322 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
323 tc.WriteLine ("}\n");
325 if (config_dir != null)
326 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
328 tc.WriteLine ("static const char *config_dir = NULL;");
330 Stream template_stream;
332 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
334 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
337 StreamReader s = new StreamReader (template_stream);
338 string template = s.ReadToEnd ();
345 string zlib = (compress ? "-lz" : "");
346 string debugging = "-g";
347 string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
349 if (style == "linux")
354 smonolib = "`pkg-config --variable=libdir mono`/libmono.a ";
356 smonolib = "-Wl,-Bstatic -lmono -Wl,-Bdynamic ";
357 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono` {0} {3} " +
358 "`pkg-config --libs-only-L mono` " + smonolib +
359 "`pkg-config --libs-only-l mono | sed -e \"s/\\-lmono //\"` {1}",
360 temp_c, temp_o, output, zlib, cc);
363 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono` {3} {1}",
364 temp_c, temp_o, output, zlib, cc);
372 Console.WriteLine ("Done");
375 if (object_out == null){
376 File.Delete (temp_o);
379 File.Delete (temp_c);
381 File.Delete (temp_s);
386 static ArrayList LoadAssemblies (ArrayList sources)
388 ArrayList assemblies = new ArrayList ();
391 foreach (string name in sources){
392 Assembly a = LoadAssembly (name);
403 Environment.Exit (1);
408 static void QueueAssembly (ArrayList files, string codebase)
410 if (files.Contains (codebase))
413 files.Add (codebase);
414 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
419 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
420 a = Assembly.Load (an);
421 QueueAssembly (files, a.CodeBase);
425 static Assembly LoadAssembly (string assembly)
430 char[] path_chars = { '/', '\\' };
432 if (assembly.IndexOfAny (path_chars) != -1) {
433 a = Assembly.LoadFrom (assembly);
435 string ass = assembly;
436 if (ass.EndsWith (".dll"))
437 ass = assembly.Substring (0, assembly.Length - 4);
438 a = Assembly.Load (ass);
441 } catch (FileNotFoundException){
442 string total_log = "";
444 foreach (string dir in link_paths){
445 string full_path = Path.Combine (dir, assembly);
446 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
450 a = Assembly.LoadFrom (full_path);
452 } catch (FileNotFoundException ff) {
453 total_log += ff.FusionLog;
457 Error ("Cannot find assembly `" + assembly + "'" );
458 Console.WriteLine ("Log: \n" + total_log);
459 } catch (BadImageFormatException f) {
460 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
461 } catch (FileLoadException f){
462 Error ("Cannot load assembly " + f.FusionLog);
463 } catch (ArgumentNullException){
464 Error("Cannot load assembly (null argument)");
469 static void Error (string msg)
471 Console.Error.WriteLine (msg);
472 Environment.Exit (1);
477 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
479 " -c Produce stub only, do not compile\n" +
480 " -o out Specifies output filename\n" +
481 " -oo obj Specifies output filename for helper object file\n" +
482 " -L path Adds `path' to the search path for assemblies\n" +
483 " --nodeps Turns off automatic dependency embedding (default)\n" +
484 " --deps Turns on automatic dependency embedding\n" +
485 " --keeptemp Keeps the temporary files\n" +
486 " --config F Bundle system config file `F'\n" +
487 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
488 " --static Statically link to mono libs\n" +
489 " -z Compress the assemblies before embedding.\n");
493 static extern int system (string s);
495 static extern int uname (IntPtr buf);
497 static void DetectOS ()
500 Console.WriteLine ("OS is: Windows");
505 IntPtr buf = UnixMarshal.AllocHeap(8192);
506 if (uname (buf) != 0){
507 Console.WriteLine ("Warning: Unable to detect OS");
510 string os = Marshal.PtrToStringAnsi (buf);
511 Console.WriteLine ("OS is: " + os);
515 UnixMarshal.FreeHeap(buf);
520 int p = (int) Environment.OSVersion.Platform;
521 return ((p == 4) || (p == 128));
525 static int Execute (string cmdLine)
527 Console.WriteLine (cmdLine);
529 return system (cmdLine);
531 Process p = Process.Start ("sh", String.Format ("-c \"{0}\"", cmdLine));
537 static string GetEnv (string name, string defaultValue)
539 string s = Environment.GetEnvironmentVariable (name);
540 return s != null ? s : defaultValue;