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.Generic;
16 using System.IO.Compression;
17 using System.Runtime.InteropServices;
19 using IKVM.Reflection;
22 using System.Threading.Tasks;
25 static string output = "a.out";
26 static string object_out = null;
27 static List<string> link_paths = new List<string> ();
28 static bool autodeps = false;
29 static bool keeptemp = false;
30 static bool compile_only = false;
31 static bool static_link = false;
32 static string config_file = null;
33 static string machine_config_file = null;
34 static string config_dir = null;
35 static string style = "linux";
38 static bool? use_dos2unix = null;
39 static bool skip_scan;
40 static string ctor_func;
42 static int Main (string [] args)
44 List<string> sources = new List<string> ();
45 int top = args.Length;
50 for (int i = 0; i < top; i++){
52 case "--help": case "-h": case "-?":
73 object_out = args [++i];
81 link_paths.Add (args [++i]);
97 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
98 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
106 config_file = args [++i];
108 case "--machine-config":
114 machine_config_file = args [++i];
116 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
124 config_dir = args [++i];
144 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
152 case "--static-ctor":
157 ctor_func = args [++i];
160 case "--dos2unix=true":
163 case "--dos2unix=false":
164 use_dos2unix = false;
167 sources.Add (args [i]);
173 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
174 if (sources.Count == 0 || output == null) {
176 Environment.Exit (1);
179 List<string> assemblies = LoadAssemblies (sources);
180 List<string> files = new List<string> ();
181 foreach (string file in assemblies)
182 if (!QueueAssembly (files, file))
185 GenerateBundles (files);
186 //GenerateJitWrapper ();
191 static void WriteSymbol (StreamWriter sw, string name, long size)
197 "\t.section .rodata\n" +
199 "\t.type {0}, \"object\"\n" +
200 "\t.size {0}, {1}\n" +
206 "\t.section __TEXT,__text,regular,pure_instructions\n" +
216 "\t.section .rdata,\"dr\"\n" +
224 static string [] chars = new string [256];
226 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
230 // Preallocate the strings we need.
231 if (chars [0] == null) {
232 for (int i = 0; i < chars.Length; i++)
233 chars [i] = string.Format ("{0}", i.ToString ());
236 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
238 for (int i = 0; i < n; i++) {
239 if (count % 32 == 0) {
240 ts.Write ("\n\t.byte ");
244 ts.Write (chars [buffer [i]]);
252 static void GenerateBundles (List<string> files)
254 string temp_s = "temp.s"; // Path.GetTempFileName ();
255 string temp_c = "temp.c";
256 string temp_o = "temp.o";
260 if (object_out != null)
264 List<string> c_bundle_names = new List<string> ();
265 List<string[]> config_names = new List<string[]> ();
267 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
268 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
272 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
273 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
277 const unsigned char *data;
278 const unsigned int size;
279 } MonoBundledAssembly;
280 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
281 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
284 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
285 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
289 tc.WriteLine ("typedef struct _compressed_data {");
290 tc.WriteLine ("\tMonoBundledAssembly assembly;");
291 tc.WriteLine ("\tint compressed_size;");
292 tc.WriteLine ("} CompressedAssembly;\n");
295 object monitor = new object ();
297 var streams = new Dictionary<string, Stream> ();
298 var sizes = new Dictionary<string, long> ();
300 // Do the file reading and compression in parallel
301 Action<string> body = delegate (string url) {
302 string fname = LocateFile (new Uri (url).LocalPath);
303 Stream stream = File.OpenRead (fname);
305 long real_size = stream.Length;
308 byte[] cbuffer = new byte [8192];
309 MemoryStream ms = new MemoryStream ();
310 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
311 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
312 deflate.Write (cbuffer, 0, n);
316 byte [] bytes = ms.GetBuffer ();
317 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
321 streams [url] = stream;
322 sizes [url] = real_size;
328 Parallel.ForEach (files, body);
330 foreach (var url in files)
334 // The non-parallel part
335 byte [] buffer = new byte [8192];
336 foreach (var url in files) {
337 string fname = LocateFile (new Uri (url).LocalPath);
338 string aname = Path.GetFileName (fname);
339 string encoded = aname.Replace ("-", "_").Replace (".", "_");
344 var stream = streams [url];
345 var real_size = sizes [url];
347 Console.WriteLine (" embedding: " + fname);
349 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
351 WriteBuffer (ts, stream, buffer);
354 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
355 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
356 " assembly_data_{0}, {2}}}, {3}}};",
357 encoded, aname, real_size, stream.Length);
358 double ratio = ((double) stream.Length * 100) / real_size;
359 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
361 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
362 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
363 encoded, aname, real_size);
367 c_bundle_names.Add ("assembly_bundle_" + encoded);
370 FileStream cf = File.OpenRead (fname + ".config");
371 Console.WriteLine (" config from: " + fname + ".config");
372 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
373 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
374 WriteBuffer (ts, cf, buffer);
376 config_names.Add (new string[] {aname, encoded});
377 } catch (FileNotFoundException) {
378 /* we ignore if the config file doesn't exist */
382 if (config_file != null){
385 conf = File.OpenRead (config_file);
387 Error (String.Format ("Failure to open {0}", config_file));
390 Console.WriteLine ("System config from: " + config_file);
391 tc.WriteLine ("extern const char system_config;");
392 WriteSymbol (ts, "system_config", config_file.Length);
394 WriteBuffer (ts, conf, buffer);
396 ts.Write ("\t.byte 0\n");
400 if (machine_config_file != null){
403 conf = File.OpenRead (machine_config_file);
405 Error (String.Format ("Failure to open {0}", machine_config_file));
408 Console.WriteLine ("Machine config from: " + machine_config_file);
409 tc.WriteLine ("extern const char machine_config;");
410 WriteSymbol (ts, "machine_config", machine_config_file.Length);
412 WriteBuffer (ts, conf, buffer);
413 ts.Write ("\t.byte 0\n");
419 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
421 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
423 foreach (string c in c_bundle_names){
424 tc.WriteLine ("\t&{0},", c);
426 tc.WriteLine ("\tNULL\n};\n");
427 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
429 if (ctor_func != null) {
430 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
431 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
432 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
435 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
436 foreach (string[] ass in config_names){
437 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
439 if (config_file != null)
440 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
441 if (machine_config_file != null)
442 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
443 tc.WriteLine ("}\n");
445 if (config_dir != null)
446 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
448 tc.WriteLine ("static const char *config_dir = NULL;");
450 Stream template_stream;
452 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
454 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
457 StreamReader s = new StreamReader (template_stream);
458 string template = s.ReadToEnd ();
462 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
463 StreamReader st = new StreamReader (template_main_stream);
464 string maintemplate = st.ReadToEnd ();
465 tc.Write (maintemplate);
470 string assembler = GetEnv("AS", "as");
471 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
476 Console.WriteLine("Compiling:");
478 if (style == "windows")
481 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
483 string compiler = GetEnv("CC", "cl.exe");
484 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
485 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC");
486 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
488 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0"};
489 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
492 var compilerArgs = new List<string>();
493 foreach (string include in includes)
494 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
497 monoFile = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
499 monoFile = LocateFile (monoPath + @"\lib\monosgen-2.0.dll");
501 compilerArgs.Add("/MD");
502 compilerArgs.Add(temp_c);
503 compilerArgs.Add(temp_o);
504 compilerArgs.Add("/link");
507 compilerArgs.Add("/NOENTRY");
508 compilerArgs.Add("/DLL");
510 foreach (string lib in libs)
511 compilerArgs.Add(String.Format ("/LIBPATH:{0}", quote(lib)));
512 compilerArgs.Add (quote(monoFile));
514 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
519 string zlib = (compress ? "-lz" : "");
520 string debugging = "-g";
521 string cc = GetEnv("CC", "cc");
524 if (style == "linux")
530 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
532 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
533 cmd = String.Format("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
534 "`pkg-config --libs-only-L mono-2` " + smonolib +
535 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
536 temp_c, temp_o, output, zlib, cc);
541 cmd = String.Format("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
542 temp_c, temp_o, output, zlib, cc);
547 Console.WriteLine ("Done");
552 if (object_out == null){
553 File.Delete (temp_o);
556 File.Delete (temp_c);
558 File.Delete (temp_s);
563 static List<string> LoadAssemblies (List<string> sources)
565 List<string> assemblies = new List<string> ();
568 foreach (string name in sources){
570 Assembly a = LoadAssembly (name);
577 assemblies.Add (a.CodeBase);
578 } catch (Exception) {
580 Console.WriteLine ("File will not be scanned: {0}", name);
581 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
589 Environment.Exit (1);
594 static readonly Universe universe = new Universe ();
595 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
597 static bool QueueAssembly (List<string> files, string codebase)
599 // Console.WriteLine ("CODE BASE IS {0}", codebase);
600 if (files.Contains (codebase))
603 var path = new Uri(codebase).LocalPath;
604 var name = Path.GetFileName (path);
606 if (loaded_assemblies.TryGetValue (name, out found)) {
607 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
611 loaded_assemblies.Add (name, path);
613 files.Add (codebase);
617 Assembly a = universe.LoadFile (path);
619 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
620 a = universe.Load (an.FullName);
621 if (!QueueAssembly (files, a.CodeBase))
624 } catch (Exception) {
632 static Assembly LoadAssembly (string assembly)
637 char[] path_chars = { '/', '\\' };
639 if (assembly.IndexOfAny (path_chars) != -1) {
640 a = universe.LoadFile (assembly);
642 string ass = assembly;
643 if (ass.EndsWith (".dll"))
644 ass = assembly.Substring (0, assembly.Length - 4);
645 a = universe.Load (ass);
648 } catch (FileNotFoundException){
649 string total_log = "";
651 foreach (string dir in link_paths){
652 string full_path = Path.Combine (dir, assembly);
653 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
657 a = universe.LoadFile (full_path);
659 } catch (FileNotFoundException ff) {
660 total_log += ff.FusionLog;
664 Error ("Cannot find assembly `" + assembly + "'" );
665 Console.WriteLine ("Log: \n" + total_log);
666 } catch (IKVM.Reflection.BadImageFormatException f) {
669 Error ("Cannot load assembly (bad file format) " + f.Message);
670 } catch (FileLoadException f){
671 Error ("Cannot load assembly " + f.Message);
672 } catch (ArgumentNullException){
673 Error("Cannot load assembly (null argument)");
678 static void Error (string msg)
680 Console.Error.WriteLine ("ERROR: " + msg);
681 Environment.Exit (1);
686 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
688 " -c Produce stub only, do not compile\n" +
689 " -o out Specifies output filename\n" +
690 " -oo obj Specifies output filename for helper object file\n" +
691 " -L path Adds `path' to the search path for assemblies\n" +
692 " --nodeps Turns off automatic dependency embedding (default)\n" +
693 " --deps Turns on automatic dependency embedding\n" +
694 " --dos2unix[=true|false]\n" +
695 " When no value provided, or when `true` specified\n" +
696 " `dos2unix` will be invoked to convert paths on Windows.\n" +
697 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
698 " --keeptemp Keeps the temporary files\n" +
699 " --config F Bundle system config file `F'\n" +
700 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
701 " --machine-config F Use the given file as the machine.config for the application.\n" +
702 " --static Statically link to mono libs\n" +
703 " --nomain Don't include a main() function, for libraries\n" +
704 " -z Compress the assemblies before embedding.\n" +
705 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
706 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
707 " You need zlib development headers and libraries.\n");
711 static extern int system (string s);
713 static extern int uname (IntPtr buf);
715 static void DetectOS ()
718 Console.WriteLine ("OS is: Windows");
723 IntPtr buf = Marshal.AllocHGlobal (8192);
724 if (uname (buf) != 0){
725 Console.WriteLine ("Warning: Unable to detect OS");
726 Marshal.FreeHGlobal (buf);
729 string os = Marshal.PtrToStringAnsi (buf);
730 Console.WriteLine ("OS is: " + os);
734 Marshal.FreeHGlobal (buf);
739 int p = (int) Environment.OSVersion.Platform;
740 return ((p == 4) || (p == 128) || (p == 6));
744 static void Execute (string cmdLine)
747 Console.WriteLine ("[execute cmd]: " + cmdLine);
748 int ret = system (cmdLine);
751 Error(String.Format("[Fail] {0}", ret));
756 // on Windows, we have to pipe the output of a
757 // `cmd` interpolation to dos2unix, because the shell does not
758 // strip the CRLFs generated by the native pkg-config distributed
761 // But if it's *not* on cygwin, just skip it.
763 // check if dos2unix is applicable.
764 if (use_dos2unix == true)
766 var info = new ProcessStartInfo ("dos2unix");
767 info.CreateNoWindow = true;
768 info.RedirectStandardInput = true;
769 info.UseShellExecute = false;
770 var dos2unix = Process.Start (info);
771 dos2unix.StandardInput.WriteLine ("aaa");
772 dos2unix.StandardInput.WriteLine ("\u0004");
773 dos2unix.StandardInput.Close ();
774 dos2unix.WaitForExit ();
775 if (dos2unix.ExitCode == 0)
778 Console.WriteLine("Warning: dos2unix not found");
779 use_dos2unix = false;
782 if (use_dos2unix == null)
783 use_dos2unix = false;
785 ProcessStartInfo psi = new ProcessStartInfo();
786 psi.UseShellExecute = false;
788 // if there is no dos2unix, just run cmd /c.
789 if (use_dos2unix == false)
791 psi.FileName = "cmd";
792 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
797 StringBuilder b = new StringBuilder();
799 for (int i = 0; i < cmdLine.Length; i++)
801 if (cmdLine[i] == '`')
805 b.Append("|dos2unix");
809 b.Append(cmdLine[i]);
811 cmdLine = b.ToString();
812 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
815 Console.WriteLine(cmdLine);
816 using (Process p = Process.Start (psi)) {
818 int ret = p.ExitCode;
820 Error (String.Format("[Fail] {0}", ret));
825 static string GetEnv(string name, string defaultValue)
827 string val = Environment.GetEnvironmentVariable(name);
830 Console.WriteLine("{0} = {1}", name, val);
835 Console.WriteLine("{0} = {1} (default)", name, val);
840 static string LocateFile(string default_path)
842 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
843 if (File.Exists(override_path))
844 return override_path;
845 else if (File.Exists(default_path))
848 throw new FileNotFoundException(default_path);