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
10 // (C) 2016 Xamarin Inc
13 // * Add support for packaging native libraries, extracting at runtime and setting the library path.
14 // * Implement --list-targets lists all the available remote targets
17 using System.Diagnostics;
19 using System.Collections.Generic;
21 using System.IO.Compression;
22 using System.Runtime.InteropServices;
24 using IKVM.Reflection;
26 using System.Diagnostics;
28 using System.Threading.Tasks;
31 static string output = "a.out";
32 static string object_out = null;
33 static List<string> link_paths = new List<string> ();
34 static bool autodeps = false;
35 static bool keeptemp = false;
36 static bool compile_only = false;
37 static bool static_link = false;
38 static string config_file = null;
39 static string machine_config_file = null;
40 static string config_dir = null;
41 static string style = "linux";
42 static string os_message = "";
45 static string custom_main = null;
46 static bool? use_dos2unix = null;
47 static bool skip_scan;
48 static string ctor_func;
50 static string cross_target = null;
51 static string fetch_target = null;
52 static bool custom_mode = true;
53 static string embedded_options = null;
54 static string runtime = null;
55 static string target_server = "https://download.mono-project.com/runtimes/raw/";
57 static int Main (string [] args)
59 List<string> sources = new List<string> ();
60 int top = args.Length;
65 for (int i = 0; i < top; i++){
67 case "--help": case "-h": case "-?":
84 case "--local-targets":
85 CommandLocalTargets ();
95 cross_target = args [++i];
98 case "--fetch-target":
103 fetch_target = args [++i];
106 case "--list-targets":
107 var wc = new WebClient ();
108 var s = wc.DownloadString (new Uri (target_server + "target-list.txt"));
109 Console.WriteLine ("Cross-compilation targets available:\n" + s);
113 case "--target-server":
118 target_server = args [++i];
134 embedded_options = args [++i];
141 runtime = args [++i];
148 object_out = args [++i];
156 link_paths.Add (args [++i]);
180 config_file = args [++i];
182 case "--machine-config":
188 machine_config_file = args [++i];
191 Console.WriteLine ("WARNING:\n Check that the machine.config file you are bundling\n doesn't contain sensitive information specific to this machine.");
199 config_dir = args [++i];
207 case "--custom-main":
212 custom_main = args [++i];
226 Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
234 case "--static-ctor":
239 ctor_func = args [++i];
242 case "--dos2unix=true":
245 case "--dos2unix=false":
246 use_dos2unix = false;
253 sources.Add (args [i]);
260 Console.WriteLine (os_message);
261 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
263 if (sources.Count == 0 || output == null) {
265 Environment.Exit (1);
268 List<string> assemblies = LoadAssemblies (sources);
269 List<string> files = new List<string> ();
270 foreach (string file in assemblies)
271 if (!QueueAssembly (files, file))
274 if (fetch_target != null){
275 var truntime = Path.Combine (targets_dir, fetch_target, "mono");
276 Directory.CreateDirectory (Path.GetDirectoryName (truntime));
277 var wc = new WebClient ();
278 var uri = new Uri ($"{target_server}{fetch_target}");
280 wc.DownloadFile (uri, truntime);
282 Console.Error.WriteLine ($"Failure to download the specified runtime from {uri}");
283 File.Delete (truntime);
290 GenerateBundles (files);
292 if (cross_target == "default")
299 if (cross_target == null){
300 Console.Error.WriteLine ("you should specify either a --runtime or a --cross compilation target");
301 Environment.Exit (1);
303 truntime = Path.Combine (targets_dir, cross_target, "mono");
305 if (!File.Exists (truntime)){
306 Console.Error.WriteLine ($"The runtime for the {cross_target} does not exist, use --fetch-target {cross_target} to download first");
310 GeneratePackage (files);
316 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
318 static void CommandLocalTargets ()
322 Console.WriteLine ("Available targets:");
323 Console.WriteLine ("\tdefault\t- Current System Mono");
325 targets = Directory.GetDirectories (targets_dir);
329 foreach (var target in targets){
330 var p = Path.Combine (target, "mono");
332 Console.WriteLine ("\t{0}", Path.GetFileName (target));
336 static void WriteSymbol (StreamWriter sw, string name, long size)
342 "\t.section .rodata\n" +
344 "\t.type {0}, \"object\"\n" +
345 "\t.size {0}, {1}\n" +
351 "\t.section __TEXT,__text,regular,pure_instructions\n" +
361 "\t.section .rdata,\"dr\"\n" +
369 static string [] chars = new string [256];
371 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
375 // Preallocate the strings we need.
376 if (chars [0] == null) {
377 for (int i = 0; i < chars.Length; i++)
378 chars [i] = string.Format ("{0}", i.ToString ());
381 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
383 for (int i = 0; i < n; i++) {
384 if (count % 32 == 0) {
385 ts.Write ("\n\t.byte ");
389 ts.Write (chars [buffer [i]]);
398 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
399 const int align = 4096;
402 public PackageMaker (string output)
404 package = File.Create (output, 128*1024);
406 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
410 public int AddFile (string fname)
412 using (Stream fileStream = File.OpenRead (fname)){
413 var ret = fileStream.Length;
415 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
416 fileStream.CopyTo (package);
417 package.Position = package.Position + (align - (package.Position % align));
423 public void Add (string entry, string fname)
425 var p = package.Position;
426 var size = AddFile (fname);
428 locations [entry] = Tuple.Create(p, size);
431 public void AddString (string entry, string text)
433 var bytes = Encoding.UTF8.GetBytes (text);
434 locations [entry] = Tuple.Create (package.Position, bytes.Length);
435 package.Write (bytes, 0, bytes.Length);
436 package.Position = package.Position + (align - (package.Position % align));
441 foreach (var floc in locations.Keys){
442 Console.WriteLine ($"{floc} at {locations[floc]:x}");
446 public void WriteIndex ()
448 var indexStart = package.Position;
449 var binary = new BinaryWriter (package);
451 binary.Write (locations.Count);
452 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
453 var bytes = Encoding.UTF8.GetBytes (entry.Key);
454 binary.Write (bytes.Length+1);
455 binary.Write (bytes);
456 binary.Write ((byte) 0);
457 binary.Write (entry.Value.Item1);
458 binary.Write (entry.Value.Item2);
460 binary.Write (indexStart);
461 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
473 static bool MaybeAddFile (PackageMaker maker, string code, string file)
478 if (!File.Exists (file)){
479 Console.Error.WriteLine ("The file {0} does not exist", file);
482 maker.Add (code, file);
486 static bool GeneratePackage (List<string> files)
488 if (runtime == null){
490 runtime = Process.GetCurrentProcess().MainModule.FileName;
492 Console.Error.WriteLine ("You must specify at least one runtime with --runtime or --cross");
493 Environment.Exit (1);
496 if (!File.Exists (runtime)){
497 Console.Error.WriteLine ($"The specified runtime at {runtime} does not exist");
498 Environment.Exit (1);
501 if (ctor_func != null){
502 Console.Error.WriteLine ("--static-ctor not supported with package bundling, you must use native compilation for this");
506 var maker = new PackageMaker (output);
507 maker.AddFile (runtime);
509 foreach (var url in files){
510 string fname = LocateFile (new Uri (url).LocalPath);
511 string aname = Path.GetFileName (fname);
513 maker.Add ("assembly:" + aname, fname);
514 if (File.Exists (fname + ".config"))
515 maker.Add ("config:" + aname, fname + ".config");
517 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
520 if (config_dir != null)
521 maker.Add ("config_dir:", config_dir);
522 if (embedded_options != null)
523 maker.AddString ("options:", embedded_options);
529 static void GenerateBundles (List<string> files)
531 string temp_s = "temp.s"; // Path.GetTempFileName ();
532 string temp_c = "temp.c";
533 string temp_o = "temp.o";
537 if (object_out != null)
541 List<string> c_bundle_names = new List<string> ();
542 List<string[]> config_names = new List<string[]> ();
544 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
545 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
549 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
550 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
554 const unsigned char *data;
555 const unsigned int size;
556 } MonoBundledAssembly;
557 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
558 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
561 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
562 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
566 tc.WriteLine ("typedef struct _compressed_data {");
567 tc.WriteLine ("\tMonoBundledAssembly assembly;");
568 tc.WriteLine ("\tint compressed_size;");
569 tc.WriteLine ("} CompressedAssembly;\n");
572 object monitor = new object ();
574 var streams = new Dictionary<string, Stream> ();
575 var sizes = new Dictionary<string, long> ();
577 // Do the file reading and compression in parallel
578 Action<string> body = delegate (string url) {
579 string fname = LocateFile (new Uri (url).LocalPath);
580 Stream stream = File.OpenRead (fname);
582 long real_size = stream.Length;
585 byte[] cbuffer = new byte [8192];
586 MemoryStream ms = new MemoryStream ();
587 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
588 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
589 deflate.Write (cbuffer, 0, n);
593 byte [] bytes = ms.GetBuffer ();
594 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
598 streams [url] = stream;
599 sizes [url] = real_size;
605 Parallel.ForEach (files, body);
607 foreach (var url in files)
611 // The non-parallel part
612 byte [] buffer = new byte [8192];
613 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
614 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
615 foreach (var url in files) {
616 string fname = LocateFile (new Uri (url).LocalPath);
617 string aname = Path.GetFileName (fname);
618 string encoded = symbolEscapeRE.Replace (aname, "_");
623 var stream = streams [url];
624 var real_size = sizes [url];
627 Console.WriteLine (" embedding: " + fname);
629 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
631 WriteBuffer (ts, stream, buffer);
634 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
635 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
636 " assembly_data_{0}, {2}}}, {3}}};",
637 encoded, aname, real_size, stream.Length);
639 double ratio = ((double) stream.Length * 100) / real_size;
640 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
643 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
644 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
645 encoded, aname, real_size);
649 c_bundle_names.Add ("assembly_bundle_" + encoded);
652 FileStream cf = File.OpenRead (fname + ".config");
654 Console.WriteLine (" config from: " + fname + ".config");
655 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
656 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
657 WriteBuffer (ts, cf, buffer);
659 config_names.Add (new string[] {aname, encoded});
660 } catch (FileNotFoundException) {
661 /* we ignore if the config file doesn't exist */
665 if (config_file != null){
668 conf = File.OpenRead (config_file);
670 Error (String.Format ("Failure to open {0}", config_file));
674 Console.WriteLine ("System config from: " + config_file);
675 tc.WriteLine ("extern const char system_config;");
676 WriteSymbol (ts, "system_config", config_file.Length);
678 WriteBuffer (ts, conf, buffer);
680 ts.Write ("\t.byte 0\n");
684 if (machine_config_file != null){
687 conf = File.OpenRead (machine_config_file);
689 Error (String.Format ("Failure to open {0}", machine_config_file));
693 Console.WriteLine ("Machine config from: " + machine_config_file);
694 tc.WriteLine ("extern const char machine_config;");
695 WriteSymbol (ts, "machine_config", machine_config_file.Length);
697 WriteBuffer (ts, conf, buffer);
698 ts.Write ("\t.byte 0\n");
704 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
706 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
708 foreach (string c in c_bundle_names){
709 tc.WriteLine ("\t&{0},", c);
711 tc.WriteLine ("\tNULL\n};\n");
712 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
714 if (ctor_func != null) {
715 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
716 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
717 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
720 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
721 foreach (string[] ass in config_names){
722 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
724 if (config_file != null)
725 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
726 if (machine_config_file != null)
727 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
728 tc.WriteLine ("}\n");
730 if (config_dir != null)
731 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
733 tc.WriteLine ("static const char *config_dir = NULL;");
735 Stream template_stream;
737 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
739 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
742 StreamReader s = new StreamReader (template_stream);
743 string template = s.ReadToEnd ();
746 if (!nomain && custom_main == null) {
747 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
748 StreamReader st = new StreamReader (template_main_stream);
749 string maintemplate = st.ReadToEnd ();
750 tc.Write (maintemplate);
755 string assembler = GetEnv("AS", "as");
756 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
763 Console.WriteLine("Compiling:");
765 if (style == "windows")
768 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
770 string compiler = GetEnv("CC", "cl.exe");
771 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
772 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
773 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
775 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
776 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
777 var linkLibraries = new string[] { "kernel32.lib",
792 string glue_obj = "mkbundle_glue.obj";
796 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
799 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
800 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
801 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
804 var compilerArgs = new List<string>();
805 compilerArgs.Add("/MT");
807 foreach (string include in includes)
808 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
810 if (!nomain || custom_main != null) {
811 compilerArgs.Add(quote(temp_c));
812 compilerArgs.Add(quote(temp_o));
813 if (custom_main != null)
814 compilerArgs.Add(quote(custom_main));
815 compilerArgs.Add(quote(monoLib));
816 compilerArgs.Add("/link");
817 compilerArgs.Add("/NODEFAULTLIB");
818 compilerArgs.Add("/SUBSYSTEM:windows");
819 compilerArgs.Add("/ENTRY:mainCRTStartup");
820 compilerArgs.AddRange(linkLibraries);
821 compilerArgs.Add("/out:"+ output);
823 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
828 // we are just creating a .lib
829 compilerArgs.Add("/c"); // compile only
830 compilerArgs.Add(temp_c);
831 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
833 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
836 string librarian = GetEnv ("LIB", "lib.exe");
837 var librarianArgs = new List<string> ();
838 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
839 librarianArgs.Add (temp_o);
840 librarianArgs.Add (glue_obj);
841 librarianArgs.Add (monoLib);
842 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
848 string zlib = (compress ? "-lz" : "");
849 string debugging = "-g";
850 string cc = GetEnv("CC", "cc");
853 if (style == "linux")
859 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
861 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
862 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
863 "`pkg-config --libs-only-L mono-2` " + smonolib +
864 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
865 temp_c, temp_o, output, zlib, cc);
870 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
871 temp_c, temp_o, output, zlib, cc);
877 Console.WriteLine ("Done");
882 if (object_out == null){
883 File.Delete (temp_o);
886 File.Delete (temp_c);
888 File.Delete (temp_s);
893 static List<string> LoadAssemblies (List<string> sources)
895 List<string> assemblies = new List<string> ();
898 foreach (string name in sources){
900 Assembly a = LoadAssembly (name);
907 assemblies.Add (a.CodeBase);
908 } catch (Exception) {
911 Console.WriteLine ("File will not be scanned: {0}", name);
912 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
920 Environment.Exit (1);
925 static readonly Universe universe = new Universe ();
926 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
928 static bool QueueAssembly (List<string> files, string codebase)
930 // Console.WriteLine ("CODE BASE IS {0}", codebase);
931 if (files.Contains (codebase))
934 var path = new Uri(codebase).LocalPath;
935 var name = Path.GetFileName (path);
937 if (loaded_assemblies.TryGetValue (name, out found)) {
938 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
942 loaded_assemblies.Add (name, path);
944 files.Add (codebase);
948 Assembly a = universe.LoadFile (path);
950 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
951 a = universe.Load (an.FullName);
952 if (!QueueAssembly (files, a.CodeBase))
955 } catch (Exception) {
963 static Assembly LoadAssembly (string assembly)
968 char[] path_chars = { '/', '\\' };
970 if (assembly.IndexOfAny (path_chars) != -1) {
971 a = universe.LoadFile (assembly);
973 string ass = assembly;
974 if (ass.EndsWith (".dll"))
975 ass = assembly.Substring (0, assembly.Length - 4);
976 a = universe.Load (ass);
979 } catch (FileNotFoundException){
980 string total_log = "";
982 foreach (string dir in link_paths){
983 string full_path = Path.Combine (dir, assembly);
984 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
988 a = universe.LoadFile (full_path);
990 } catch (FileNotFoundException ff) {
991 total_log += ff.FusionLog;
995 Error ("Cannot find assembly `" + assembly + "'" );
997 Console.WriteLine ("Log: \n" + total_log);
998 } catch (IKVM.Reflection.BadImageFormatException f) {
1001 Error ("Cannot load assembly (bad file format) " + f.Message);
1002 } catch (FileLoadException f){
1003 Error ("Cannot load assembly " + f.Message);
1004 } catch (ArgumentNullException){
1005 Error("Cannot load assembly (null argument)");
1010 static void Error (string msg)
1012 Console.Error.WriteLine ("ERROR: " + msg);
1013 Environment.Exit (1);
1018 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1020 " --config F Bundle system config file `F'\n" +
1021 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1022 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1023 " -L path Adds `path' to the search path for assemblies\n" +
1024 " --machine-config F Use the given file as the machine.config for the application.\n" +
1025 " -o out Specifies output filename\n" +
1026 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1027 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1029 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1030 " --cross TARGET Generates a binary for the given TARGET\n"+
1031 " --local-targets Lists locally available targets\n" +
1032 " --list-targets Lists available targets on the remote server\n" +
1033 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1034 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1035 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1037 "--custom Builds a custom launcher, options for --custom\n" +
1038 " -c Produce stub only, do not compile\n" +
1039 " -oo obj Specifies output filename for helper object file\n" +
1040 " --dos2unix[=true|false]\n" +
1041 " When no value provided, or when `true` specified\n" +
1042 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1043 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1044 " --keeptemp Keeps the temporary files\n" +
1045 " --static Statically link to mono libs\n" +
1046 " --nomain Don't include a main() function, for libraries\n" +
1047 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1048 " -z Compress the assemblies before embedding.\n" +
1049 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1050 " You need zlib development headers and libraries.\n");
1053 [DllImport ("libc")]
1054 static extern int system (string s);
1055 [DllImport ("libc")]
1056 static extern int uname (IntPtr buf);
1058 static void DetectOS ()
1061 os_message = "OS is: Windows";
1066 IntPtr buf = Marshal.AllocHGlobal (8192);
1067 if (uname (buf) != 0){
1068 os_message = "Warning: Unable to detect OS";
1069 Marshal.FreeHGlobal (buf);
1072 string os = Marshal.PtrToStringAnsi (buf);
1073 os_message = "OS is: " + os;
1077 Marshal.FreeHGlobal (buf);
1080 static bool IsUnix {
1082 int p = (int) Environment.OSVersion.Platform;
1083 return ((p == 4) || (p == 128) || (p == 6));
1087 static void Execute (string cmdLine)
1091 Console.WriteLine ("[execute cmd]: " + cmdLine);
1092 int ret = system (cmdLine);
1095 Error(String.Format("[Fail] {0}", ret));
1100 // on Windows, we have to pipe the output of a
1101 // `cmd` interpolation to dos2unix, because the shell does not
1102 // strip the CRLFs generated by the native pkg-config distributed
1105 // But if it's *not* on cygwin, just skip it.
1107 // check if dos2unix is applicable.
1108 if (use_dos2unix == true)
1110 var info = new ProcessStartInfo ("dos2unix");
1111 info.CreateNoWindow = true;
1112 info.RedirectStandardInput = true;
1113 info.UseShellExecute = false;
1114 var dos2unix = Process.Start (info);
1115 dos2unix.StandardInput.WriteLine ("aaa");
1116 dos2unix.StandardInput.WriteLine ("\u0004");
1117 dos2unix.StandardInput.Close ();
1118 dos2unix.WaitForExit ();
1119 if (dos2unix.ExitCode == 0)
1120 use_dos2unix = true;
1122 Console.WriteLine("Warning: dos2unix not found");
1123 use_dos2unix = false;
1126 if (use_dos2unix == null)
1127 use_dos2unix = false;
1129 ProcessStartInfo psi = new ProcessStartInfo();
1130 psi.UseShellExecute = false;
1132 // if there is no dos2unix, just run cmd /c.
1133 if (use_dos2unix == false)
1135 psi.FileName = "cmd";
1136 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1140 psi.FileName = "sh";
1141 StringBuilder b = new StringBuilder();
1143 for (int i = 0; i < cmdLine.Length; i++)
1145 if (cmdLine[i] == '`')
1149 b.Append("|dos2unix");
1153 b.Append(cmdLine[i]);
1155 cmdLine = b.ToString();
1156 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1160 Console.WriteLine(cmdLine);
1161 using (Process p = Process.Start (psi)) {
1163 int ret = p.ExitCode;
1165 Error (String.Format("[Fail] {0}", ret));
1170 static string GetEnv(string name, string defaultValue)
1172 string val = Environment.GetEnvironmentVariable(name);
1176 Console.WriteLine("{0} = {1}", name, val);
1182 Console.WriteLine("{0} = {1} (default)", name, val);
1187 static string LocateFile(string default_path)
1189 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1190 if (File.Exists(override_path))
1191 return override_path;
1192 else if (File.Exists(default_path))
1193 return default_path;
1195 throw new FileNotFoundException(default_path);