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
13 using System.Collections;
14 using System.Reflection;
16 using System.Runtime.InteropServices;
18 using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
21 static string output = "a.out";
22 static string object_out = null;
23 static ArrayList link_paths = new ArrayList ();
24 static bool autodeps = false;
25 static bool keeptemp = false;
26 static bool compile_only = false;
27 static bool static_link = false;
28 static string config_file = null;
29 static string config_dir = null;
30 static string style = "linux";
33 static int Main (string [] args)
35 ArrayList sources = new ArrayList ();
36 int top = args.Length;
39 for (int i = 0; i < top; i++){
41 case "--help": case "-h": case "-?":
62 object_out = args [++i];
70 link_paths.Add (args [++i]);
86 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
87 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
95 config_file = args [++i];
103 config_dir = args [++i];
109 sources.Add (args [i]);
116 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
117 if (sources.Count == 0 || output == null) {
119 Environment.Exit (1);
122 ArrayList assemblies = LoadAssemblies (sources);
123 ArrayList files = new ArrayList ();
124 foreach (Assembly a in assemblies)
125 QueueAssembly (files, a.CodeBase);
127 GenerateBundles (files);
128 //GenerateJitWrapper ();
133 static void WriteSymbol (StreamWriter sw, string name, long size)
139 "\t.section .rodata\n" +
141 "\t.type {0}, @object\n" +
142 "\t.size {0}, {1}\n" +
148 "\t.section __TEXT,__text,regular,pure_instructions\n" +
149 "\t.section __TEXT,__picsymbolstub1,symbol_stubs,pure_instructions,32\n" +
159 static void GenerateBundles (ArrayList files)
161 string temp_s = "temp.s"; // Path.GetTempFileName ();
162 string temp_c = "temp.c";
163 string temp_o = Path.GetTempFileName () + ".o";
167 if (object_out != null)
171 ArrayList c_bundle_names = new ArrayList ();
172 ArrayList config_names = new ArrayList ();
173 byte [] buffer = new byte [8192];
175 StreamWriter ts = new StreamWriter (File.Create (temp_s));
176 StreamWriter tc = new StreamWriter (File.Create (temp_c));
179 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
180 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
183 tc.WriteLine ("typedef struct _compressed_data {");
184 tc.WriteLine ("\tMonoBundledAssembly assembly;");
185 tc.WriteLine ("\tint compressed_size;");
186 tc.WriteLine ("} CompressedAssembly;\n");
189 foreach (string url in files){
190 string fname = url.Substring (7);
191 string aname = fname.Substring (fname.LastIndexOf ("/") + 1);
192 string encoded = aname.Replace ("-", "_").Replace (".", "_");
197 Console.WriteLine (" embedding: " + fname);
199 Stream stream = File.OpenRead (fname);
201 long real_size = stream.Length;
204 MemoryStream ms = new MemoryStream ();
205 DeflaterOutputStream deflate = new DeflaterOutputStream (ms);
206 while ((n = stream.Read (buffer, 0, 8192)) != 0){
207 deflate.Write (buffer, 0, n);
211 byte [] bytes = ms.GetBuffer ();
212 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
215 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
217 while ((n = stream.Read (buffer, 0, 8192)) != 0){
218 for (int i = 0; i < n; i++){
219 ts.Write ("\t.byte {0}\n", buffer [i]);
225 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
226 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
227 " assembly_data_{0}, {2}}}, {3}}};",
228 encoded, aname, real_size, stream.Length);
229 double ratio = ((double) stream.Length * 100) / real_size;
230 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
232 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
233 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
234 encoded, aname, real_size);
238 c_bundle_names.Add ("assembly_bundle_" + encoded);
241 FileStream cf = File.OpenRead (fname + ".config");
242 Console.WriteLine (" config from: " + fname + ".config");
243 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
244 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
245 while ((n = cf.Read (buffer, 0, 8192)) != 0){
246 for (int i = 0; i < n; i++){
247 ts.Write ("\t.byte {0}\n", buffer [i]);
251 config_names.Add (new string[] {aname, encoded});
252 } catch (FileNotFoundException) {
253 /* we ignore if the config file doesn't exist */
257 if (config_file != null){
260 conf = File.OpenRead (config_file);
262 Error (String.Format ("Failure to open {0}", config_file));
265 Console.WriteLine ("System config from: " + config_file);
266 tc.WriteLine ("extern const unsigned char system_config;");
267 WriteSymbol (ts, "system_config", config_file.Length);
270 while ((n = conf.Read (buffer, 0, 8192)) != 0){
271 for (int i = 0; i < n; i++){
272 ts.Write ("\t.byte {0}\n", buffer [i]);
276 ts.Write ("\t.byte 0\n");
281 Console.WriteLine ("Compiling:");
282 string cmd = String.Format ("as -o {0} {1} ", temp_o, temp_s);
283 Console.WriteLine (cmd);
284 int ret = system (cmd);
291 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
293 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
295 foreach (string c in c_bundle_names){
296 tc.WriteLine ("\t&{0},", c);
298 tc.WriteLine ("\tNULL\n};\n");
299 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
301 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
302 foreach (string[] ass in config_names){
303 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
305 if (config_file != null)
306 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
307 tc.WriteLine ("}\n");
309 if (config_dir != null)
310 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
312 tc.WriteLine ("static const char *config_dir = NULL;");
314 Stream template_stream;
316 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
318 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
321 StreamReader s = new StreamReader (template_stream);
322 string template = s.ReadToEnd ();
329 string zlib = (compress ? "-lz" : "");
330 string debugging = "-g";
332 if (style == "linux")
337 smonolib = "`pkg-config --variable=libdir mono`/libmono.a ";
339 smonolib = "-Wl,-Bstatic -lmono -Wl,-Bdynamic ";
340 cmd = String.Format ("cc -o {2} -Wall `pkg-config --cflags mono` {0} {3}" +
341 "`pkg-config --libs-only-L mono` " + smonolib +
342 "`pkg-config --libs-only-l mono | sed -e \"s/\\-lmono //\"` {1}",
343 temp_c, temp_o, output, zlib);
346 cmd = String.Format ("cc " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono` {3} {1}",
347 temp_c, temp_o, output, zlib);
350 Console.WriteLine (cmd);
356 Console.WriteLine ("Done");
359 if (object_out == null){
360 File.Delete (temp_o);
363 File.Delete (temp_c);
365 File.Delete (temp_s);
370 static ArrayList LoadAssemblies (ArrayList sources)
372 ArrayList assemblies = new ArrayList ();
375 foreach (string name in sources){
376 Assembly a = LoadAssembly (name);
387 Environment.Exit (1);
392 static void QueueAssembly (ArrayList files, string codebase)
394 if (files.Contains (codebase))
397 files.Add (codebase);
398 Assembly a = Assembly.LoadFrom (codebase);
403 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
404 a = Assembly.Load (an);
405 QueueAssembly (files, a.CodeBase);
409 static Assembly LoadAssembly (string assembly)
414 char[] path_chars = { '/', '\\' };
416 if (assembly.IndexOfAny (path_chars) != -1) {
417 a = Assembly.LoadFrom (assembly);
419 string ass = assembly;
420 if (ass.EndsWith (".dll"))
421 ass = assembly.Substring (0, assembly.Length - 4);
422 a = Assembly.Load (ass);
425 } catch (FileNotFoundException){
426 string total_log = "";
428 foreach (string dir in link_paths){
429 string full_path = Path.Combine (dir, assembly);
430 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
434 a = Assembly.LoadFrom (full_path);
436 } catch (FileNotFoundException ff) {
437 total_log += ff.FusionLog;
441 Error ("Cannot find assembly `" + assembly + "'" );
442 Console.WriteLine ("Log: \n" + total_log);
443 } catch (BadImageFormatException f) {
444 Error ("Cannot load assembly (bad file format)" + f.FusionLog);
445 } catch (FileLoadException f){
446 Error ("Cannot load assembly " + f.FusionLog);
447 } catch (ArgumentNullException){
448 Error("Cannot load assembly (null argument)");
453 static void Error (string msg)
455 Console.Error.WriteLine (msg);
456 Environment.Exit (1);
461 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
463 " -c Produce stub only, do not compile\n" +
464 " -o out Specifies output filename\n" +
465 " -oo obj Specifies output filename for helper object file\n" +
466 " -L path Adds `path' to the search path for assemblies\n" +
467 " --nodeps Turns off automatic dependency embedding (default)\n" +
468 " --deps Turns on automatic dependency embedding\n" +
469 " --keeptemp Keeps the temporary files\n" +
470 " --config F Bundle system config file `F'\n" +
471 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
472 " --static Statically link to mono libs\n" +
473 " -z Compress the assemblies before embedding.\n");
477 static extern int system (string s);
479 static extern int uname (IntPtr buf);
481 static void DetectOS ()
483 IntPtr buf = UnixMarshal.AllocHeap(8192);
484 if (uname (buf) != 0){
485 Console.WriteLine ("Warning: Unable to detect OS");
488 string os = Marshal.PtrToStringAnsi (buf);
489 Console.WriteLine ("OS is: " + os);
493 UnixMarshal.FreeHeap(buf);