Merge pull request #601 from knocte/sock_improvements
[mono.git] / mcs / tools / mkbundle / mkbundle.cs
1 //
2 // mkbundle: tool to create bundles.
3 //
4 // Based on the `make-bundle' Perl script written by Paolo Molaro (lupus@debian.org)
5 //
6 // Author:
7 //   Miguel de Icaza
8 //
9 // (C) Novell, Inc 2004
10 //
11 using System;
12 using System.Diagnostics;
13 using System.Xml;
14 using System.Collections.Generic;
15 using System.Reflection;
16 using System.IO;
17 using System.IO.Compression;
18 using System.Runtime.InteropServices;
19 using System.Text;
20
21
22 #if NET_4_5
23 using System.Threading.Tasks;
24 #endif
25
26 class MakeBundle {
27         static string output = "a.out";
28         static string object_out = null;
29         static List<string> link_paths = new List<string> ();
30         static bool autodeps = false;
31         static bool keeptemp = false;
32         static bool compile_only = false;
33         static bool static_link = false;
34         static string config_file = null;
35         static string machine_config_file = null;
36         static string config_dir = null;
37         static string style = "linux";
38         static bool compress;
39         static bool nomain;
40         
41         static int Main (string [] args)
42         {
43                 List<string> sources = new List<string> ();
44                 int top = args.Length;
45                 link_paths.Add (".");
46
47                 DetectOS ();
48                 
49                 for (int i = 0; i < top; i++){
50                         switch (args [i]){
51                         case "--help": case "-h": case "-?":
52                                 Help ();
53                                 return 1;
54
55                         case "-c":
56                                 compile_only = true;
57                                 break;
58                                 
59                         case "-o": 
60                                 if (i+1 == top){
61                                         Help (); 
62                                         return 1;
63                                 }
64                                 output = args [++i];
65                                 break;
66
67                         case "-oo":
68                                 if (i+1 == top){
69                                         Help (); 
70                                         return 1;
71                                 }
72                                 object_out = args [++i];
73                                 break;
74
75                         case "-L":
76                                 if (i+1 == top){
77                                         Help (); 
78                                         return 1;
79                                 }
80                                 link_paths.Add (args [++i]);
81                                 break;
82
83                         case "--nodeps":
84                                 autodeps = false;
85                                 break;
86
87                         case "--deps":
88                                 autodeps = true;
89                                 break;
90
91                         case "--keeptemp":
92                                 keeptemp = true;
93                                 break;
94                         case "--static":
95                                 static_link = true;
96                                 Console.WriteLine ("Note that statically linking the LGPL Mono runtime has more licensing restrictions than dynamically linking.");
97                                 Console.WriteLine ("See http://www.mono-project.com/Licensing for details on licensing.");
98                                 break;
99                         case "--config":
100                                 if (i+1 == top) {
101                                         Help ();
102                                         return 1;
103                                 }
104
105                                 config_file = args [++i];
106                                 break;
107                         case "--machine-config":
108                                 if (i+1 == top) {
109                                         Help ();
110                                         return 1;
111                                 }
112
113                                 machine_config_file = args [++i];
114
115                                 Console.WriteLine ("WARNING:\n  Check that the machine.config file you are bundling\n  doesn't contain sensitive information specific to this machine.");
116                                 break;
117                         case "--config-dir":
118                                 if (i+1 == top) {
119                                         Help ();
120                                         return 1;
121                                 }
122
123                                 config_dir = args [++i];
124                                 break;
125                         case "-z":
126                                 compress = true;
127                                 break;
128                         case "--nomain":
129                                 nomain = true;
130                                 break;
131                         case "--style":
132                                 if (i+1 == top) {
133                                         Help ();
134                                         return 1;
135                                 }
136                                 style = args [++i];
137                                 switch (style) {
138                                 case "windows":
139                                 case "mac":
140                                 case "linux":
141                                         break;
142                                 default:
143                                         Console.Error.WriteLine ("Invalid style '{0}' - only 'windows', 'mac' and 'linux' are supported for --style argument", style);
144                                         return 1;
145                                 }
146                                         
147                                 break;
148                         default:
149                                 sources.Add (args [i]);
150                                 break;
151                         }
152                         
153                         if (static_link && style == "windows") {
154                                 Console.Error.WriteLine ("The option `{0}' is not supported on this platform.", args [i]);
155                                 return 1;
156                         }
157                 }
158
159                 Console.WriteLine ("Sources: {0} Auto-dependencies: {1}", sources.Count, autodeps);
160                 if (sources.Count == 0 || output == null) {
161                         Help ();
162                         Environment.Exit (1);
163                 }
164
165                 List<Assembly> assemblies = LoadAssemblies (sources);
166                 List<string> files = new List<string> ();
167                 foreach (Assembly a in assemblies)
168                         QueueAssembly (files, a.CodeBase);
169                         
170                 // Special casing mscorlib.dll: any specified mscorlib.dll cannot be loaded
171                 // by Assembly.ReflectionFromLoadFrom(). Instead the fx assembly which runs
172                 // mkbundle.exe is loaded, which is not what we want.
173                 // So, replace it with whatever actually specified.
174                 foreach (string srcfile in sources) {
175                         if (Path.GetFileName (srcfile) == "mscorlib.dll") {
176                                 foreach (string file in files) {
177                                         if (Path.GetFileName (new Uri (file).LocalPath) == "mscorlib.dll") {
178                                                 files.Remove (file);
179                                                 files.Add (new Uri (Path.GetFullPath (srcfile)).LocalPath);
180                                                 break;
181                                         }
182                                 }
183                                 break;
184                         }
185                 }
186
187                 GenerateBundles (files);
188                 //GenerateJitWrapper ();
189                 
190                 return 0;
191         }
192
193         static void WriteSymbol (StreamWriter sw, string name, long size)
194         {
195                 switch (style){
196                 case "linux":
197                         sw.WriteLine (
198                                 ".globl {0}\n" +
199                                 "\t.section .rodata\n" +
200                                 "\t.p2align 5\n" +
201                                 "\t.type {0}, \"object\"\n" +
202                                 "\t.size {0}, {1}\n" +
203                                 "{0}:\n",
204                                 name, size);
205                         break;
206                 case "osx":
207                         sw.WriteLine (
208                                 "\t.section __TEXT,__text,regular,pure_instructions\n" + 
209                                 "\t.globl _{0}\n" +
210                                 "\t.data\n" +
211                                 "\t.align 4\n" +
212                                 "_{0}:\n",
213                                 name, size);
214                         break;
215                 case "windows":
216                         sw.WriteLine (
217                                 ".globl _{0}\n" +
218                                 "\t.section .rdata,\"dr\"\n" +
219                                 "\t.align 32\n" +
220                                 "_{0}:\n",
221                                 name, size);
222                         break;
223                 }
224         }
225         
226         static string [] chars = new string [256];
227         
228         static void WriteBuffer (StreamWriter ts, Stream stream, byte[] buffer)
229         {
230                 int n;
231                 
232                 // Preallocate the strings we need.
233                 if (chars [0] == null) {
234                         for (int i = 0; i < chars.Length; i++)
235                                 chars [i] = string.Format ("\t.byte {0}\n", i.ToString ());
236                 }
237
238                 while ((n = stream.Read (buffer, 0, buffer.Length)) != 0) {
239                         for (int i = 0; i < n; i++)
240                                 ts.Write (chars [buffer [i]]);
241                 }
242
243                 ts.WriteLine ();
244         }
245         
246         static void GenerateBundles (List<string> files)
247         {
248                 string temp_s = "temp.s"; // Path.GetTempFileName ();
249                 string temp_c = "temp.c";
250                 string temp_o = "temp.o";
251
252                 if (compile_only)
253                         temp_c = output;
254                 if (object_out != null)
255                         temp_o = object_out;
256                 
257                 try {
258                         List<string> c_bundle_names = new List<string> ();
259                         List<string[]> config_names = new List<string[]> ();
260                         byte [] buffer = new byte [8192];
261
262                         using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
263                         using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
264                         string prog = null;
265
266                         tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
267                         tc.WriteLine ("#include <mono/metadata/mono-config.h>");
268                         tc.WriteLine ("#include <mono/metadata/assembly.h>\n");
269
270                         if (compress) {
271                                 tc.WriteLine ("typedef struct _compressed_data {");
272                                 tc.WriteLine ("\tMonoBundledAssembly assembly;");
273                                 tc.WriteLine ("\tint compressed_size;");
274                                 tc.WriteLine ("} CompressedAssembly;\n");
275                         }
276
277                         object monitor = new object ();
278
279                         // Do the file reading and compression in parallel
280                         Action<string> body = delegate (string url) {
281                                 string fname = new Uri (url).LocalPath;
282                                 string aname = Path.GetFileName (fname);
283                                 string encoded = aname.Replace ("-", "_").Replace (".", "_");
284
285                                 if (prog == null)
286                                         prog = aname;
287                                                                 
288                                 Stream stream = File.OpenRead (fname);
289
290                                 long real_size = stream.Length;
291                                 int n;
292                                 if (compress) {
293                                         MemoryStream ms = new MemoryStream ();
294                                         GZipStream deflate = new GZipStream (ms, CompressionMode.Compress, leaveOpen:true);
295                                         while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){
296                                                 deflate.Write (buffer, 0, n);
297                                         }
298                                         stream.Close ();
299                                         deflate.Close ();
300                                         byte [] bytes = ms.GetBuffer ();
301                                         stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
302                                 }
303
304                                 // The non-parallel part
305                                 lock (monitor) {
306                                         Console.WriteLine ("   embedding: " + fname);
307
308                                         WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);
309                         
310                                         WriteBuffer (ts, stream, buffer);
311
312                                         if (compress) {
313                                                 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
314                                                 tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
315                                                                           " assembly_data_{0}, {2}}}, {3}}};",
316                                                                           encoded, aname, real_size, stream.Length);
317                                                 double ratio = ((double) stream.Length * 100) / real_size;
318                                                 Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
319                                         } else {
320                                                 tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
321                                                 tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
322                                                                           encoded, aname, real_size);
323                                         }
324                                         stream.Close ();
325
326                                         c_bundle_names.Add ("assembly_bundle_" + encoded);
327
328                                         try {
329                                                 FileStream cf = File.OpenRead (fname + ".config");
330                                                 Console.WriteLine (" config from: " + fname + ".config");
331                                                 tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
332                                                 WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
333                                                 WriteBuffer (ts, cf, buffer);
334                                                 ts.WriteLine ();
335                                                 config_names.Add (new string[] {aname, encoded});
336                                         } catch (FileNotFoundException) {
337                                                 /* we ignore if the config file doesn't exist */
338                                         }
339                                 }
340                         };
341
342 #if NET_4_5
343                         Parallel.ForEach (files, body);
344 #else
345                         foreach (var url in files)
346                                 body (url);
347 #endif
348
349                         if (config_file != null){
350                                 FileStream conf;
351                                 try {
352                                         conf = File.OpenRead (config_file);
353                                 } catch {
354                                         Error (String.Format ("Failure to open {0}", config_file));
355                                         return;
356                                 }
357                                 Console.WriteLine ("System config from: " + config_file);
358                                 tc.WriteLine ("extern const char system_config;");
359                                 WriteSymbol (ts, "system_config", config_file.Length);
360
361                                 WriteBuffer (ts, conf, buffer);
362                                 // null terminator
363                                 ts.Write ("\t.byte 0\n");
364                                 ts.WriteLine ();
365                         }
366
367                         if (machine_config_file != null){
368                                 FileStream conf;
369                                 try {
370                                         conf = File.OpenRead (machine_config_file);
371                                 } catch {
372                                         Error (String.Format ("Failure to open {0}", machine_config_file));
373                                         return;
374                                 }
375                                 Console.WriteLine ("Machine config from: " + machine_config_file);
376                                 tc.WriteLine ("extern const char machine_config;");
377                                 WriteSymbol (ts, "machine_config", machine_config_file.Length);
378
379                                 WriteBuffer (ts, conf, buffer);
380                                 ts.Write ("\t.byte 0\n");
381                                 ts.WriteLine ();
382                         }
383                         ts.Close ();
384                         
385                         Console.WriteLine ("Compiling:");
386                         string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
387                         int ret = Execute (cmd);
388                         if (ret != 0){
389                                 Error ("[Fail]");
390                                 return;
391                         }
392
393                         if (compress)
394                                 tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
395                         else
396                                 tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");
397
398                         foreach (string c in c_bundle_names){
399                                 tc.WriteLine ("\t&{0},", c);
400                         }
401                         tc.WriteLine ("\tNULL\n};\n");
402                         tc.WriteLine ("static char *image_name = \"{0}\";", prog);
403
404                         tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
405                         foreach (string[] ass in config_names){
406                                 tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
407                         }
408                         if (config_file != null)
409                                 tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
410                         if (machine_config_file != null)
411                                 tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
412                         tc.WriteLine ("}\n");
413
414                         if (config_dir != null)
415                                 tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
416                         else
417                                 tc.WriteLine ("static const char *config_dir = NULL;");
418
419                         Stream template_stream;
420                         if (compress) {
421                                 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
422                         } else {
423                                 template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
424                         }
425
426                         StreamReader s = new StreamReader (template_stream);
427                         string template = s.ReadToEnd ();
428                         tc.Write (template);
429
430                         if (!nomain) {
431                                 Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
432                                 StreamReader st = new StreamReader (template_main_stream);
433                                 string maintemplate = st.ReadToEnd ();
434                                 tc.Write (maintemplate);
435                         }
436                         
437                         tc.Close ();
438
439                         if (compile_only)
440                                 return;
441
442                         string zlib = (compress ? "-lz" : "");
443                         string debugging = "-g";
444                         string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");
445
446                         if (style == "linux")
447                                 debugging = "-ggdb";
448                         if (static_link) {
449                                 string smonolib;
450                                 if (style == "osx")
451                                         smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
452                                 else
453                                         smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
454                                 cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
455                                                      "`pkg-config --libs-only-L mono-2` " + smonolib +
456                                                      "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
457                                                      temp_c, temp_o, output, zlib, cc);
458                         } else {
459                                 
460                                 cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
461                                                      temp_c, temp_o, output, zlib, cc);
462                         }
463                             
464                         ret = Execute (cmd);
465                         if (ret != 0){
466                                 Error ("[Fail]");
467                                 return;
468                         }
469                         Console.WriteLine ("Done");
470                         }
471                         }
472                 } finally {
473                         if (!keeptemp){
474                                 if (object_out == null){
475                                         File.Delete (temp_o);
476                                 }
477                                 if (!compile_only){
478                                         File.Delete (temp_c);
479                                 }
480                                 File.Delete (temp_s);
481                         }
482                 }
483         }
484         
485         static List<Assembly> LoadAssemblies (List<string> sources)
486         {
487                 List<Assembly> assemblies = new List<Assembly> ();
488                 bool error = false;
489                 
490                 foreach (string name in sources){
491                         Assembly a = LoadAssembly (name);
492
493                         if (a == null){
494                                 error = true;
495                                 continue;
496                         }
497                         
498                         assemblies.Add (a);
499                 }
500
501                 if (error)
502                         Environment.Exit (1);
503
504                 return assemblies;
505         }
506         
507         static void QueueAssembly (List<string> files, string codebase)
508         {
509                 if (files.Contains (codebase))
510                         return;
511
512                 files.Add (codebase);
513                 Assembly a = Assembly.LoadFrom (new Uri(codebase).LocalPath);
514
515                 if (!autodeps)
516                         return;
517                 
518                 foreach (AssemblyName an in a.GetReferencedAssemblies ()) {
519                         a = Assembly.Load (an);
520                         QueueAssembly (files, a.CodeBase);
521                 }
522         }
523
524         static Assembly LoadAssembly (string assembly)
525         {
526                 Assembly a;
527                 
528                 try {
529                         char[] path_chars = { '/', '\\' };
530                         
531                         if (assembly.IndexOfAny (path_chars) != -1) {
532                                 a = Assembly.LoadFrom (assembly);
533                         } else {
534                                 string ass = assembly;
535                                 if (ass.EndsWith (".dll"))
536                                         ass = assembly.Substring (0, assembly.Length - 4);
537                                 a = Assembly.Load (ass);
538                         }
539                         return a;
540                 } catch (FileNotFoundException){
541                         string total_log = "";
542                         
543                         foreach (string dir in link_paths){
544                                 string full_path = Path.Combine (dir, assembly);
545                                 if (!assembly.EndsWith (".dll") && !assembly.EndsWith (".exe"))
546                                         full_path += ".dll";
547                                 
548                                 try {
549                                         a = Assembly.LoadFrom (full_path);
550                                         return a;
551                                 } catch (FileNotFoundException ff) {
552                                         total_log += ff.FusionLog;
553                                         continue;
554                                 }
555                         }
556                         Error ("Cannot find assembly `" + assembly + "'" );
557                         Console.WriteLine ("Log: \n" + total_log);
558                 } catch (BadImageFormatException f) {
559                         Error ("Cannot load assembly (bad file format)" + f.FusionLog);
560                 } catch (FileLoadException f){
561                         Error ("Cannot load assembly " + f.FusionLog);
562                 } catch (ArgumentNullException){
563                         Error("Cannot load assembly (null argument)");
564                 }
565                 return null;
566         }
567
568         static void Error (string msg)
569         {
570                 Console.Error.WriteLine (msg);
571                 Environment.Exit (1);
572         }
573
574         static void Help ()
575         {
576                 Console.WriteLine ("Usage is: mkbundle [options] assembly1 [assembly2...]\n\n" +
577                                    "Options:\n" +
578                                    "    -c                  Produce stub only, do not compile\n" +
579                                    "    -o out              Specifies output filename\n" +
580                                    "    -oo obj             Specifies output filename for helper object file\n" +
581                                    "    -L path             Adds `path' to the search path for assemblies\n" +
582                                    "    --nodeps            Turns off automatic dependency embedding (default)\n" +
583                                    "    --deps              Turns on automatic dependency embedding\n" +
584                                    "    --keeptemp          Keeps the temporary files\n" +
585                                    "    --config F          Bundle system config file `F'\n" +
586                                    "    --config-dir D      Set MONO_CFG_DIR to `D'\n" +
587                                    "    --machine-config F  Use the given file as the machine.config for the application.\n" +
588                                    "    --static            Statically link to mono libs\n" +
589                                    "    --nomain            Don't include a main() function, for libraries\n" +
590                                    "    -z                  Compress the assemblies before embedding.\n" +
591                                    "                        You need zlib development headers and libraries.\n");
592         }
593
594         [DllImport ("libc")]
595         static extern int system (string s);
596         [DllImport ("libc")]
597         static extern int uname (IntPtr buf);
598                 
599         static void DetectOS ()
600         {
601                 if (!IsUnix) {
602                         Console.WriteLine ("OS is: Windows");
603                         style = "windows";
604                         return;
605                 }
606
607                 IntPtr buf = Marshal.AllocHGlobal (8192);
608                 if (uname (buf) != 0){
609                         Console.WriteLine ("Warning: Unable to detect OS");
610                         Marshal.FreeHGlobal (buf);
611                         return;
612                 }
613                 string os = Marshal.PtrToStringAnsi (buf);
614                 Console.WriteLine ("OS is: " + os);
615                 if (os == "Darwin")
616                         style = "osx";
617                 
618                 Marshal.FreeHGlobal (buf);
619         }
620
621         static bool IsUnix {
622                 get {
623                         int p = (int) Environment.OSVersion.Platform;
624                         return ((p == 4) || (p == 128) || (p == 6));
625                 }
626         }
627
628         static int Execute (string cmdLine)
629         {
630                 if (IsUnix) {
631                         Console.WriteLine (cmdLine);
632                         return system (cmdLine);
633                 }
634
635                 // on Windows, we have to pipe the output of a
636                 // `cmd` interpolation to dos2unix, because the shell does not
637                 // strip the CRLFs generated by the native pkg-config distributed
638                 // with Mono.
639                 StringBuilder b = new StringBuilder ();
640                 int count = 0;
641                 for (int i = 0; i < cmdLine.Length; i++) {
642                         if (cmdLine [i] == '`') {
643                                 if (count % 2 != 0) {
644                                         b.Append ("|dos2unix");
645                                 }
646                                 count++;
647                         }
648                         b.Append (cmdLine [i]);
649                 }
650                 cmdLine = b.ToString ();
651                 Console.WriteLine (cmdLine);
652                         
653                 ProcessStartInfo psi = new ProcessStartInfo ();
654                 psi.UseShellExecute = false;
655                 psi.FileName = "sh";
656                 psi.Arguments = String.Format ("-c \"{0}\"", cmdLine);
657
658                 using (Process p = Process.Start (psi)) {
659                         p.WaitForExit ();
660                         return p.ExitCode;
661                 }
662         }
663
664         static string GetEnv (string name, string defaultValue) 
665         {
666                 string s = Environment.GetEnvironmentVariable (name);
667                 return s != null ? s : defaultValue;
668         }
669 }