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")
295 var truntime = Path.Combine (targets_dir, cross_target, "mono");
296 if (!File.Exists (truntime)){
297 Console.Error.WriteLine ($"The runtime for the {cross_target} does not exist, use --fetch-target {cross_target} to download first");
301 GeneratePackage (files);
307 static string targets_dir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), ".mono", "targets");
309 static void CommandLocalTargets ()
313 Console.WriteLine ("Available targets:");
314 Console.WriteLine ("\tdefault\t- Current System Mono");
316 targets = Directory.GetDirectories (targets_dir);
320 foreach (var target in targets){
321 var p = Path.Combine (target, "mono");
323 Console.WriteLine ("\t{0}", Path.GetFileName (target));
327 static void WriteSymbol (StreamWriter sw, string name, long size)
333 "\t.section .rodata\n" +
335 "\t.type {0}, \"object\"\n" +
336 "\t.size {0}, {1}\n" +
342 "\t.section __TEXT,__text,regular,pure_instructions\n" +
352 "\t.section .rdata,\"dr\"\n" +
360 static string [] chars = new string [256];
362 static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
366 // Preallocate the strings we need.
367 if (chars [0] == null) {
368 for (int i = 0; i < chars.Length; i++)
369 chars [i] = string.Format ("{0}", i.ToString ());
372 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
374 for (int i = 0; i < n; i++) {
375 if (count % 32 == 0) {
376 ts.Write ("\n\t.byte ");
380 ts.Write (chars [buffer [i]]);
389 Dictionary<string, Tuple<long,int>> locations = new Dictionary<string, Tuple<long,int>> ();
390 const int align = 4096;
393 public PackageMaker (string output)
395 package = File.Create (output, 128*1024);
397 File.SetAttributes (output, unchecked ((FileAttributes) 0x80000000));
401 public int AddFile (string fname)
403 using (Stream fileStream = File.OpenRead (fname)){
404 var ret = fileStream.Length;
406 Console.WriteLine ("At {0:x} with input {1}", package.Position, fileStream.Length);
407 fileStream.CopyTo (package);
408 package.Position = package.Position + (align - (package.Position % align));
414 public void Add (string entry, string fname)
416 var p = package.Position;
417 var size = AddFile (fname);
419 locations [entry] = Tuple.Create(p, size);
422 public void AddString (string entry, string text)
424 var bytes = Encoding.UTF8.GetBytes (text);
425 locations [entry] = Tuple.Create (package.Position, bytes.Length);
426 package.Write (bytes, 0, bytes.Length);
427 package.Position = package.Position + (align - (package.Position % align));
432 foreach (var floc in locations.Keys){
433 Console.WriteLine ($"{floc} at {locations[floc]:x}");
437 public void WriteIndex ()
439 var indexStart = package.Position;
440 var binary = new BinaryWriter (package);
442 binary.Write (locations.Count);
443 foreach (var entry in from entry in locations orderby entry.Value.Item1 ascending select entry){
444 var bytes = Encoding.UTF8.GetBytes (entry.Key);
445 binary.Write (bytes.Length+1);
446 binary.Write (bytes);
447 binary.Write ((byte) 0);
448 binary.Write (entry.Value.Item1);
449 binary.Write (entry.Value.Item2);
451 binary.Write (indexStart);
452 binary.Write (Encoding.UTF8.GetBytes ("xmonkeysloveplay"));
464 static bool MaybeAddFile (PackageMaker maker, string code, string file)
469 if (!File.Exists (file)){
470 Console.Error.WriteLine ("The file {0} does not exist", file);
473 maker.Add (code, file);
477 static bool GeneratePackage (List<string> files)
479 if (runtime == null){
481 runtime = Process.GetCurrentProcess().MainModule.FileName;
483 Console.Error.WriteLine ("You must specify at least one runtime with --runtime or --cross");
484 Environment.Exit (1);
487 if (!File.Exists (runtime)){
488 Console.Error.WriteLine ($"The specified runtime at {runtime} does not exist");
489 Environment.Exit (1);
492 if (ctor_func != null){
493 Console.Error.WriteLine ("--static-ctor not supported with package bundling, you must use native compilation for this");
497 var maker = new PackageMaker (output);
498 maker.AddFile (runtime);
500 foreach (var url in files){
501 string fname = LocateFile (new Uri (url).LocalPath);
502 string aname = Path.GetFileName (fname);
504 maker.Add ("assembly:" + aname, fname);
505 if (File.Exists (fname + ".config"))
506 maker.Add ("config:" + aname, fname + ".config");
508 if (!MaybeAddFile (maker, "systemconfig:", config_file) || !MaybeAddFile (maker, "machineconfig:", machine_config_file))
511 if (config_dir != null)
512 maker.Add ("config_dir:", config_dir);
513 if (embedded_options != null)
514 maker.AddString ("options:", embedded_options);
520 static void GenerateBundles (List<string> files)
522 string temp_s = "temp.s"; // Path.GetTempFileName ();
523 string temp_c = "temp.c";
524 string temp_o = "temp.o";
528 if (object_out != null)
532 List<string> c_bundle_names = new List<string> ();
533 List<string[]> config_names = new List<string[]> ();
535 using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
536 using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
540 tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
541 tc.WriteLine ("\n#ifndef NULL\n#define NULL (void *)0\n#endif");
545 const unsigned char *data;
546 const unsigned int size;
547 } MonoBundledAssembly;
548 void mono_register_bundled_assemblies (const MonoBundledAssembly **assemblies);
549 void mono_register_config_for_assembly (const char* assembly_name, const char* config_xml);
552 tc.WriteLine ("#include <mono/metadata/mono-config.h>");
553 tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
557 tc.WriteLine ("typedef struct _compressed_data {");
558 tc.WriteLine ("\tMonoBundledAssembly assembly;");
559 tc.WriteLine ("\tint compressed_size;");
560 tc.WriteLine ("} CompressedAssembly;\n");
563 object monitor = new object ();
565 var streams = new Dictionary<string, Stream> ();
566 var sizes = new Dictionary<string, long> ();
568 // Do the file reading and compression in parallel
569 Action<string> body = delegate (string url) {
570 string fname = LocateFile (new Uri (url).LocalPath);
571 Stream stream = File.OpenRead (fname);
573 long real_size = stream.Length;
576 byte[] cbuffer = new byte [8192];
577 MemoryStream ms = new MemoryStream ();
578 GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
579 while ((n = stream.Read (cbuffer, 0, cbuffer.Length)) != 0){
580 deflate.Write (cbuffer, 0, n);
584 byte [] bytes = ms.GetBuffer ();
585 stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
589 streams [url] = stream;
590 sizes [url] = real_size;
596 Parallel.ForEach (files, body);
598 foreach (var url in files)
602 // The non-parallel part
603 byte [] buffer = new byte [8192];
604 // everything other than a-zA-Z0-9_ needs to be escaped in asm symbols.
605 var symbolEscapeRE = new System.Text.RegularExpressions.Regex ("[^\\w_]");
606 foreach (var url in files) {
607 string fname = LocateFile (new Uri (url).LocalPath);
608 string aname = Path.GetFileName (fname);
609 string encoded = symbolEscapeRE.Replace (aname, "_");
614 var stream = streams [url];
615 var real_size = sizes [url];
618 Console.WriteLine (" embedding: " + fname);
620 WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
622 WriteBuffer (ts, stream, buffer);
625 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
626 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
627 " assembly_data_{0}, {2}}}, {3}}};",
628 encoded, aname, real_size, stream.Length);
630 double ratio = ((double) stream.Length * 100) / real_size;
631 Console.WriteLine (" compression ratio: {0:.00}%", ratio);
634 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
635 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
636 encoded, aname, real_size);
640 c_bundle_names.Add ("assembly_bundle_" + encoded);
643 FileStream cf = File.OpenRead (fname + ".config");
645 Console.WriteLine (" config from: " + fname + ".config");
646 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
647 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
648 WriteBuffer (ts, cf, buffer);
650 config_names.Add (new string[] {aname, encoded});
651 } catch (FileNotFoundException) {
652 /* we ignore if the config file doesn't exist */
656 if (config_file != null){
659 conf = File.OpenRead (config_file);
661 Error (String.Format ("Failure to open {0}", config_file));
665 Console.WriteLine ("System config from: " + config_file);
666 tc.WriteLine ("extern const char system_config;");
667 WriteSymbol (ts, "system_config", config_file.Length);
669 WriteBuffer (ts, conf, buffer);
671 ts.Write ("\t.byte 0\n");
675 if (machine_config_file != null){
678 conf = File.OpenRead (machine_config_file);
680 Error (String.Format ("Failure to open {0}", machine_config_file));
684 Console.WriteLine ("Machine config from: " + machine_config_file);
685 tc.WriteLine ("extern const char machine_config;");
686 WriteSymbol (ts, "machine_config", machine_config_file.Length);
688 WriteBuffer (ts, conf, buffer);
689 ts.Write ("\t.byte 0\n");
695 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
697 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
699 foreach (string c in c_bundle_names){
700 tc.WriteLine ("\t&{0},", c);
702 tc.WriteLine ("\tNULL\n};\n");
703 tc.WriteLine ("static char *image_name = \"{0}\";", prog);
705 if (ctor_func != null) {
706 tc.WriteLine ("\nextern void {0} (void);", ctor_func);
707 tc.WriteLine ("\n__attribute__ ((constructor)) static void mono_mkbundle_ctor (void)");
708 tc.WriteLine ("{{\n\t{0} ();\n}}", ctor_func);
711 tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
712 foreach (string[] ass in config_names){
713 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
715 if (config_file != null)
716 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
717 if (machine_config_file != null)
718 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
719 tc.WriteLine ("}\n");
721 if (config_dir != null)
722 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
724 tc.WriteLine ("static const char *config_dir = NULL;");
726 Stream template_stream;
728 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
730 template_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
733 StreamReader s = new StreamReader (template_stream);
734 string template = s.ReadToEnd ();
737 if (!nomain && custom_main == null) {
738 Stream template_main_stream = System.Reflection.Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
739 StreamReader st = new StreamReader (template_main_stream);
740 string maintemplate = st.ReadToEnd ();
741 tc.Write (maintemplate);
746 string assembler = GetEnv("AS", "as");
747 string as_cmd = String.Format("{0} -o {1} {2} ", assembler, temp_o, temp_s);
754 Console.WriteLine("Compiling:");
756 if (style == "windows")
759 Func<string, string> quote = (pp) => { return "\"" + pp + "\""; };
761 string compiler = GetEnv("CC", "cl.exe");
762 string winsdkPath = GetEnv("WINSDK", @"C:\Program Files (x86)\Windows Kits\8.1");
763 string vsPath = GetEnv("VSINCLUDE", @"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC");
764 string monoPath = GetEnv("MONOPREFIX", @"C:\Program Files (x86)\Mono");
766 string[] includes = new string[] {winsdkPath + @"\Include\um", winsdkPath + @"\Include\shared", vsPath + @"\include", monoPath + @"\include\mono-2.0", "." };
767 string[] libs = new string[] { winsdkPath + @"\Lib\winv6.3\um\x86" , vsPath + @"\lib" };
768 var linkLibraries = new string[] { "kernel32.lib",
783 string glue_obj = "mkbundle_glue.obj";
787 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0-static.lib");
790 Console.WriteLine ("WARNING: Dynamically linking the Mono runtime on Windows is not a tested option.");
791 monoLib = LocateFile (monoPath + @"\lib\monosgen-2.0.lib");
792 LocateFile (monoPath + @"\lib\monosgen-2.0.dll"); // in this case, the .lib is just the import library, and the .dll is also needed
795 var compilerArgs = new List<string>();
796 compilerArgs.Add("/MT");
798 foreach (string include in includes)
799 compilerArgs.Add(String.Format ("/I {0}", quote (include)));
801 if (!nomain || custom_main != null) {
802 compilerArgs.Add(quote(temp_c));
803 compilerArgs.Add(quote(temp_o));
804 if (custom_main != null)
805 compilerArgs.Add(quote(custom_main));
806 compilerArgs.Add(quote(monoLib));
807 compilerArgs.Add("/link");
808 compilerArgs.Add("/NODEFAULTLIB");
809 compilerArgs.Add("/SUBSYSTEM:windows");
810 compilerArgs.Add("/ENTRY:mainCRTStartup");
811 compilerArgs.AddRange(linkLibraries);
812 compilerArgs.Add("/out:"+ output);
814 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
819 // we are just creating a .lib
820 compilerArgs.Add("/c"); // compile only
821 compilerArgs.Add(temp_c);
822 compilerArgs.Add(String.Format("/Fo" + glue_obj)); // .obj output name
824 string cl_cmd = String.Format("{0} {1}", compiler, String.Join(" ", compilerArgs.ToArray()));
827 string librarian = GetEnv ("LIB", "lib.exe");
828 var librarianArgs = new List<string> ();
829 librarianArgs.Add (String.Format ("/out:{0}.lib" + output));
830 librarianArgs.Add (temp_o);
831 librarianArgs.Add (glue_obj);
832 librarianArgs.Add (monoLib);
833 string lib_cmd = String.Format("{0} {1}", librarian, String.Join(" ", librarianArgs.ToArray()));
839 string zlib = (compress ? "-lz" : "");
840 string debugging = "-g";
841 string cc = GetEnv("CC", "cc");
844 if (style == "linux")
850 smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
852 smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
853 cmd = String.Format("{4} -o '{2}' -Wall `pkg-config --cflags mono-2` {0} {3} " +
854 "`pkg-config --libs-only-L mono-2` " + smonolib +
855 "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
856 temp_c, temp_o, output, zlib, cc);
861 cmd = String.Format("{4} " + debugging + " -o '{2}' -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
862 temp_c, temp_o, output, zlib, cc);
868 Console.WriteLine ("Done");
873 if (object_out == null){
874 File.Delete (temp_o);
877 File.Delete (temp_c);
879 File.Delete (temp_s);
884 static List<string> LoadAssemblies (List<string> sources)
886 List<string> assemblies = new List<string> ();
889 foreach (string name in sources){
891 Assembly a = LoadAssembly (name);
898 assemblies.Add (a.CodeBase);
899 } catch (Exception) {
902 Console.WriteLine ("File will not be scanned: {0}", name);
903 assemblies.Add (new Uri (new FileInfo (name).FullName).ToString ());
911 Environment.Exit (1);
916 static readonly Universe universe = new Universe ();
917 static readonly Dictionary<string, string> loaded_assemblies = new Dictionary<string, string> ();
919 static bool QueueAssembly (List<string> files, string codebase)
921 // Console.WriteLine ("CODE BASE IS {0}", codebase);
922 if (files.Contains (codebase))
925 var path = new Uri(codebase).LocalPath;
926 var name = Path.GetFileName (path);
928 if (loaded_assemblies.TryGetValue (name, out found)) {
929 Error (string.Format ("Duplicate assembly name `{0}'. Both `{1}' and `{2}' use same assembly name.", name, path, found));
933 loaded_assemblies.Add (name, path);
935 files.Add (codebase);
939 Assembly a = universe.LoadFile (path);
941 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
942 a = universe.Load (an.FullName);
943 if (!QueueAssembly (files, a.CodeBase))
946 } catch (Exception) {
954 static Assembly LoadAssembly (string assembly)
959 char[] path_chars = { '/', '\\' };
961 if (assembly.IndexOfAny (path_chars) != -1) {
962 a = universe.LoadFile (assembly);
964 string ass = assembly;
965 if (ass.EndsWith (".dll"))
966 ass = assembly.Substring (0, assembly.Length - 4);
967 a = universe.Load (ass);
970 } catch (FileNotFoundException){
971 string total_log = "";
973 foreach (string dir in link_paths){
974 string full_path = Path.Combine (dir, assembly);
975 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
979 a = universe.LoadFile (full_path);
981 } catch (FileNotFoundException ff) {
982 total_log += ff.FusionLog;
986 Error ("Cannot find assembly `" + assembly + "'" );
988 Console.WriteLine ("Log: \n" + total_log);
989 } catch (IKVM.Reflection.BadImageFormatException f) {
992 Error ("Cannot load assembly (bad file format) " + f.Message);
993 } catch (FileLoadException f){
994 Error ("Cannot load assembly " + f.Message);
995 } catch (ArgumentNullException){
996 Error("Cannot load assembly (null argument)");
1001 static void Error (string msg)
1003 Console.Error.WriteLine ("ERROR: " + msg);
1004 Environment.Exit (1);
1009 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
1011 " --config F Bundle system config file `F'\n" +
1012 " --config-dir D Set MONO_CFG_DIR to `D'\n" +
1013 " --deps Turns on automatic dependency embedding (default on simple)\n" +
1014 " -L path Adds `path' to the search path for assemblies\n" +
1015 " --machine-config F Use the given file as the machine.config for the application.\n" +
1016 " -o out Specifies output filename\n" +
1017 " --nodeps Turns off automatic dependency embedding (default on custom)\n" +
1018 " --skip-scan Skip scanning assemblies that could not be loaded (but still embed them).\n" +
1020 "--simple Simple mode does not require a C toolchain and can cross compile\n" +
1021 " --cross TARGET Generates a binary for the given TARGET\n"+
1022 " --local-targets Lists locally available targets\n" +
1023 " --list-targets Lists available targets on the remote server\n" +
1024 " --options OPTIONS Embed the specified Mono command line options on target\n" +
1025 " --runtime RUNTIME Manually specifies the Mono runtime to use\n" +
1026 " --target-server URL Specified a server to download targets from, default is " + target_server + "\n" +
1028 "--custom Builds a custom launcher, options for --custom\n" +
1029 " -c Produce stub only, do not compile\n" +
1030 " -oo obj Specifies output filename for helper object file\n" +
1031 " --dos2unix[=true|false]\n" +
1032 " When no value provided, or when `true` specified\n" +
1033 " `dos2unix` will be invoked to convert paths on Windows.\n" +
1034 " When `--dos2unix=false` used, dos2unix is NEVER used.\n" +
1035 " --keeptemp Keeps the temporary files\n" +
1036 " --static Statically link to mono libs\n" +
1037 " --nomain Don't include a main() function, for libraries\n" +
1038 " --custom-main C Link the specified compilation unit (.c or .obj) with entry point/init code\n" +
1039 " -z Compress the assemblies before embedding.\n" +
1040 " --static-ctor ctor Add a constructor call to the supplied function.\n" +
1041 " You need zlib development headers and libraries.\n");
1044 [DllImport ("libc")]
1045 static extern int system (string s);
1046 [DllImport ("libc")]
1047 static extern int uname (IntPtr buf);
1049 static void DetectOS ()
1052 os_message = "OS is: Windows";
1057 IntPtr buf = Marshal.AllocHGlobal (8192);
1058 if (uname (buf) != 0){
1059 os_message = "Warning: Unable to detect OS";
1060 Marshal.FreeHGlobal (buf);
1063 string os = Marshal.PtrToStringAnsi (buf);
1064 os_message = "OS is: " + os;
1068 Marshal.FreeHGlobal (buf);
1071 static bool IsUnix {
1073 int p = (int) Environment.OSVersion.Platform;
1074 return ((p == 4) || (p == 128) || (p == 6));
1078 static void Execute (string cmdLine)
1082 Console.WriteLine ("[execute cmd]: " + cmdLine);
1083 int ret = system (cmdLine);
1086 Error(String.Format("[Fail] {0}", ret));
1091 // on Windows, we have to pipe the output of a
1092 // `cmd` interpolation to dos2unix, because the shell does not
1093 // strip the CRLFs generated by the native pkg-config distributed
1096 // But if it's *not* on cygwin, just skip it.
1098 // check if dos2unix is applicable.
1099 if (use_dos2unix == true)
1101 var info = new ProcessStartInfo ("dos2unix");
1102 info.CreateNoWindow = true;
1103 info.RedirectStandardInput = true;
1104 info.UseShellExecute = false;
1105 var dos2unix = Process.Start (info);
1106 dos2unix.StandardInput.WriteLine ("aaa");
1107 dos2unix.StandardInput.WriteLine ("\u0004");
1108 dos2unix.StandardInput.Close ();
1109 dos2unix.WaitForExit ();
1110 if (dos2unix.ExitCode == 0)
1111 use_dos2unix = true;
1113 Console.WriteLine("Warning: dos2unix not found");
1114 use_dos2unix = false;
1117 if (use_dos2unix == null)
1118 use_dos2unix = false;
1120 ProcessStartInfo psi = new ProcessStartInfo();
1121 psi.UseShellExecute = false;
1123 // if there is no dos2unix, just run cmd /c.
1124 if (use_dos2unix == false)
1126 psi.FileName = "cmd";
1127 psi.Arguments = String.Format("/c \"{0}\"", cmdLine);
1131 psi.FileName = "sh";
1132 StringBuilder b = new StringBuilder();
1134 for (int i = 0; i < cmdLine.Length; i++)
1136 if (cmdLine[i] == '`')
1140 b.Append("|dos2unix");
1144 b.Append(cmdLine[i]);
1146 cmdLine = b.ToString();
1147 psi.Arguments = String.Format("-c \"{0}\"", cmdLine);
1151 Console.WriteLine(cmdLine);
1152 using (Process p = Process.Start (psi)) {
1154 int ret = p.ExitCode;
1156 Error (String.Format("[Fail] {0}", ret));
1161 static string GetEnv(string name, string defaultValue)
1163 string val = Environment.GetEnvironmentVariable(name);
1167 Console.WriteLine("{0} = {1}", name, val);
1173 Console.WriteLine("{0} = {1} (default)", name, val);
1178 static string LocateFile(string default_path)
1180 var override_path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(default_path));
1181 if (File.Exists(override_path))
1182 return override_path;
1183 else if (File.Exists(default_path))
1184 return default_path;
1186 throw new FileNotFoundException(default_path);