5 // Todd Berman <tberman@sevenl.net>
6 // Jackson Harper <jackson@ximian.com>
8 // Copyright 2003, 2004 Todd Berman
9 // Copyright 2004 Novell, Inc (http://www.novell.com)
16 using System.Reflection;
17 using System.Collections;
18 using System.Globalization;
19 using System.Runtime.InteropServices;
23 namespace Mono.Tools {
27 private enum Command {
38 private static bool silent;
40 public static int Main (string [] args)
45 Command command = Command.Unknown;
46 string command_str = null;
49 string name, package, gacdir, root;
50 name = package = root = gacdir = null;
51 bool check_refs = false;
53 // Check for silent arg first so we can supress
54 // warnings during command line parsing
55 if (Array.IndexOf (args, "/silent") > -1 || Array.IndexOf (args, "-silent") > -1)
58 for (int i=0; i<args.Length; i++) {
59 if (IsSwitch (args [i])) {
61 // for cmd line compatibility with other gacutils
62 // we always force it though
63 if (args [i] == "-f" || args [i] == "/f")
66 // Ignore this option for now, although we might implement it someday
67 if (args [i] == "/r") {
68 WriteLine ("WARNING: gacutil does not support traced references." +
69 "This option is being ignored.");
74 // This is already handled we just dont want to choke on it
75 if (args [i] == "-silent" || args [i] == "/silent")
78 if (args [i] == "-check_refs" || args [i] == "/check_refs") {
83 if (command == Command.Unknown) {
84 command = GetCommand (args [i]);
85 if (command != Command.Unknown) {
86 command_str = args [i];
91 if (i + 1 >= args.Length) {
92 Console.WriteLine ("Option " + args [i] + " takes 1 argument");
118 if (command == Command.Unknown && IsSwitch (args [0])) {
119 Console.WriteLine ("Unknown command: " + args [0]);
121 } else if (command == Command.Unknown) {
123 } else if (command == Command.Help) {
128 if (gacdir == null) {
129 gacdir = GetGacDir ();
130 libdir = GetLibDir ();
132 libdir = Path.Combine (gacdir, "mono");
133 gacdir = Path.Combine (libdir, "gac");
136 string link_gacdir = gacdir;
137 string link_libdir = libdir;
139 libdir = CombinePaths (root, libdir);
140 gacdir = CombinePaths (root, gacdir);
144 case Command.Install:
146 WriteLine ("Option " + command_str + " takes 1 argument");
149 if (!Install (check_refs, name, package, gacdir, link_gacdir, libdir, link_libdir))
152 case Command.InstallFromList:
154 WriteLine ("Option " + command_str + " takes 1 argument");
157 if (!InstallFromList (check_refs, name, package, gacdir, link_gacdir, libdir, link_libdir))
160 case Command.Uninstall:
162 WriteLine ("Option " + command_str + " takes 1 argument");
165 if (!Uninstall (name, package, gacdir, libdir))
166 Environment.Exit (1);
168 case Command.UninstallFromList:
170 WriteLine ("Option " + command_str + " takes 1 argument");
173 if (!UninstallFromList (name, package, gacdir, libdir))
176 case Command.UninstallSpecific:
178 WriteLine ("Opetion " + command_str + " takes 1 argument");
181 if (!UninstallSpecific (name, package, gacdir, libdir))
192 private static bool Install (bool check_refs, string name, string package,
193 string gacdir, string link_gacdir, string libdir, string link_libdir)
195 string failure_msg = "Failure adding assembly to the cache: ";
197 if (!File.Exists (name)) {
198 WriteLine (failure_msg + "The system cannot find the file specified.");
199 Environment.Exit (1);
202 AssemblyName an = null;
206 an = AssemblyName.GetAssemblyName (name);
208 WriteLine (failure_msg + "The file specified is not a valid assembly.");
212 pub_tok = an.GetPublicKeyToken ();
213 if (pub_tok == null || pub_tok.Length == 0) {
214 WriteLine (failure_msg + "Attempt to install an assembly without a strong name.");
218 if (check_refs && !CheckReferencedAssemblies (an)) {
219 WriteLine (failure_msg + "Attempt to install an assembly that references non " +
220 "strong named assemblies with -check_refs enabled.");
224 string conf_name = name + ".config";
225 string version_token = an.Version + "_" +
226 an.CultureInfo.Name.ToLower (CultureInfo.InvariantCulture) + "_" +
227 GetStringToken (pub_tok);
228 string full_path = Path.Combine (Path.Combine (gacdir, an.Name), version_token);
229 string asmb_file = Path.GetFileName (name);
230 string asmb_path = Path.Combine (full_path, asmb_file);
233 if (Directory.Exists (full_path)) {
234 // Wipe out the directory. This way we ensure old assemblies
235 // config files, and AOTd files are removed.
236 Directory.Delete (full_path, true);
238 Directory.CreateDirectory (full_path);
240 WriteLine (failure_msg + "gac directories could not be created, " +
241 "possibly permission issues.");
245 File.Copy (name, asmb_path, true);
246 if (File.Exists (conf_name))
247 File.Copy (conf_name, asmb_path + ".config", true);
249 if (package != null) {
250 string link_path = Path.Combine (Path.Combine (link_gacdir, an.Name), version_token);
251 string ref_dir = Path.Combine (libdir, package);
252 string ref_path = Path.Combine (ref_dir, asmb_file);
254 if (File.Exists (ref_path))
255 File.Delete (ref_path);
257 Directory.CreateDirectory (ref_dir);
259 WriteLine ("ERROR: Could not create package dir file.");
260 Environment.Exit (1);
262 Symlink (Path.Combine (link_path, asmb_file), ref_path);
264 WriteLine ("Package exported to: " + ref_path + " -> " +
265 Path.Combine (link_path, asmb_file));
269 WriteLine ("{0} installed into the gac ({1})", an.Name, gacdir);
273 private static bool Uninstall (string name, string package, string gacdir, string libdir)
275 string [] assembly_pieces = name.Split (new char[] { ',' });
276 Hashtable asm_info = new Hashtable ();
278 foreach (string item in assembly_pieces) {
279 string[] pieces = item.Trim ().Split (new char[] { '=' }, 2);
280 if(pieces.Length == 1)
281 asm_info ["assembly"] = pieces [0];
283 asm_info [pieces[0].Trim ().ToLower (CultureInfo.InvariantCulture)] = pieces [1];
286 string asmdir = Path.Combine (gacdir, (string) asm_info ["assembly"]);
287 if (!Directory.Exists (asmdir)) {
288 WriteLine ("No assemblies found that match: " + name);
292 string searchString = GetSearchString (asm_info);
293 string [] directories = Directory.GetDirectories (asmdir, searchString);
295 foreach (string dir in directories) {
296 Directory.Delete (dir, true);
297 if (package != null) {
298 string link_dir = Path.Combine (libdir, package);
299 string link = Path.Combine (link_dir, (string) asm_info ["assembly"] + ".dll");
301 if (Directory.GetFiles (link_dir).Length == 0) {
302 WriteLine ("Cleaning package directory, it is empty.");
303 Directory.Delete (link_dir);
306 WriteLine ("Assembly removed from the gac.");
309 if(Directory.GetDirectories (asmdir).Length == 0) {
310 WriteLine ("Cleaning assembly dir, its empty");
311 Directory.Delete (asmdir);
317 private static bool UninstallSpecific (string name, string package,
318 string gacdir, string libdir)
320 string failure_msg = "Failure to remove assembly from the cache: ";
322 if (!File.Exists (name)) {
323 WriteLine (failure_msg + "The system cannot find the file specified.");
327 AssemblyName an = null;
330 an = AssemblyName.GetAssemblyName (name);
332 WriteLine (failure_msg + "The file specified is not a valid assembly.");
336 return Uninstall (an.FullName.Replace (" ", String.Empty),
337 package, gacdir, libdir);
340 private static void List (string name, string gacdir)
342 WriteLine ("The following assemblies are installed into the GAC:");
345 FilteredList (name, gacdir);
350 DirectoryInfo gacinfo = new DirectoryInfo (gacdir);
351 foreach (DirectoryInfo parent in gacinfo.GetDirectories ()) {
352 foreach (DirectoryInfo dir in parent.GetDirectories ()) {
353 WriteLine (AsmbNameFromVersionString (parent.Name, dir.Name));
357 WriteLine ("Number of items = " + count);
360 private static void FilteredList (string name, string gacdir)
362 string [] assembly_pieces = name.Split (new char[] { ',' });
363 Hashtable asm_info = new Hashtable ();
365 foreach (string item in assembly_pieces) {
366 string[] pieces = item.Trim ().Split (new char[] { '=' }, 2);
367 if(pieces.Length == 1)
368 asm_info ["assembly"] = pieces [0];
370 asm_info [pieces[0].Trim ().ToLower (CultureInfo.InvariantCulture)] = pieces [1];
373 string asmdir = Path.Combine (gacdir, (string) asm_info ["assembly"]);
374 if (!Directory.Exists (asmdir)) {
375 WriteLine ("Number of items = 0");
378 string search = GetSearchString (asm_info);
379 string [] dir_list = Directory.GetDirectories (asmdir, search);
382 foreach (string dir in dir_list) {
383 WriteLine (AsmbNameFromVersionString ((string) asm_info ["assembly"],
384 new DirectoryInfo (dir).Name));
387 WriteLine ("Number of items = " + count);
390 private static bool InstallFromList (bool check_refs, string list_file, string package,
391 string gacdir, string link_gacdir, string libdir, string link_libdir)
393 StreamReader s = null;
394 int processed, failed;
396 processed = failed = 0;
399 s = new StreamReader (list_file);
402 while ((line = s.ReadLine ()) != null) {
403 if (!Install (check_refs, line, package, gacdir, link_gacdir,
404 libdir, link_libdir))
409 } catch (IOException ioe) {
410 WriteLine ("Failed to open assemblies list file " + list_file + ".");
420 private static bool UninstallFromList (string list_file, string package,
421 string gacdir, string libdir)
423 StreamReader s = null;
424 int processed, failed;
426 processed = failed = 0;
429 s = new StreamReader (list_file);
432 while ((line = s.ReadLine ()) != null) {
433 if (!Uninstall (line, package, gacdir, libdir))
437 } catch (IOException ioe) {
438 WriteLine ("Failed to open assemblies list file " + list_file + ".");
448 private static bool CheckReferencedAssemblies (AssemblyName an)
452 Assembly a = Assembly.LoadFrom (an.CodeBase);
453 AssemblyName corlib = typeof (object).Assembly.GetName ();
455 foreach (AssemblyName ref_an in a.GetReferencedAssemblies ()) {
456 if (ref_an.Name == corlib.Name) // Just do a string compare so we can install on diff versions
458 byte [] pt = ref_an.GetPublicKeyToken ();
459 if (pt == null || pt.Length == 0) {
460 WriteLine ("Assembly " + ref_an.Name + " is not strong named.");
464 } catch (Exception e) {
465 WriteLine (e.ToString ()); // This should be removed pre beta3
470 AppDomain.Unload (d);
478 private static string GetSearchString (Hashtable asm_info)
480 if (asm_info.Keys.Count == 1)
482 string version, culture, token;
484 version = asm_info ["version"] as string;
485 version = (version == null ? "*" : version);
486 culture = asm_info ["culture"] as string;
487 culture = (culture == null ? "*" : culture.ToLower (CultureInfo.InvariantCulture));
488 token = asm_info ["publickeytoken"] as string;
489 token = (token == null ? "*" : token.ToLower (CultureInfo.InvariantCulture));
491 return String.Format ("{0}_{1}_{2}", version, culture, token);
494 private static string AsmbNameFromVersionString (string name, string str)
496 string [] pieces = str.Split ('_');
497 return String.Format ("{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
498 name, pieces [0], (pieces [1] == String.Empty ? "neutral" : pieces [1]),
502 private static bool IsSwitch (string arg)
504 return (arg [0] == '-' || (arg [0] == '/' && !File.Exists (arg)));
507 private static Command GetCommand (string arg)
509 Command c = Command.Unknown;
519 case "--install-from-list":
520 c = Command.InstallFromList;
526 c = Command.Uninstall;
530 case "--uninstall-from-list":
531 c = Command.UninstallFromList;
535 case "--uninstall-specific":
536 c = Command.UninstallSpecific;
552 private static void Symlink (string oldpath, string newpath) {
553 if (Path.DirectorySeparatorChar == '/') {
554 symlink (oldpath, newpath);
556 File.Copy (oldpath, newpath);
560 [DllImport ("libc", SetLastError=true)]
561 public static extern int symlink (string oldpath, string newpath);
563 private static string GetGacDir () {
564 PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath",
565 BindingFlags.Static|BindingFlags.NonPublic);
567 WriteLine ("ERROR: Mono runtime not detected, please use " +
568 "the mono runtime for gacutil.exe");
569 Environment.Exit (1);
571 MethodInfo get_gac = gac.GetGetMethod (true);
572 return (string) get_gac.Invoke (null, null);
575 private static string GetLibDir () {
576 MethodInfo libdir = typeof (System.Environment).GetMethod ("internalGetGacPath",
577 BindingFlags.Static|BindingFlags.NonPublic);
578 if (libdir == null) {
579 WriteLine ("ERROR: Mono runtime not detected, please use " +
580 "the mono runtime for gacutil.exe");
581 Environment.Exit (1);
583 return Path.Combine ((string)libdir.Invoke (null, null), "mono");
586 private static string GetStringToken (byte[] tok)
588 StringBuilder sb = new StringBuilder ();
589 for (int i = 0; i < tok.Length ; i++)
590 sb.Append (tok[i].ToString ("x2"));
591 return sb.ToString ();
594 private static string CombinePaths (string a, string b)
596 string dsc = Path.DirectorySeparatorChar.ToString ();
597 string sep = (a.EndsWith (dsc) ? String.Empty : dsc);
598 string end = (b.StartsWith (dsc) ? b.Substring (1) : b);
599 return String.Concat (a, sep, end);
602 private static void WriteLine ()
606 Console.WriteLine ();
609 private static void WriteLine (string line)
613 Console.WriteLine (line);
616 private static void WriteLine (string line, params object [] p)
620 Console.WriteLine (line, p);
623 private static void Usage ()
626 Environment.Exit (1);
629 private static void ShowHelp (bool detailed)
631 WriteLine ("Usage: gacutil.exe <commands> [ <options> ]");
632 WriteLine ("Commands:");
634 WriteLine ("-i <assembly_path> [-check_refs] [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]");
635 WriteLine ("\tInstalls an assembly into the global assembly cache.");
637 WriteLine ("\t<assembly_path> is the name of the file that contains the " +
638 "\tassembly manifest\n" +
639 "\tExample: -i myDll.dll");
643 WriteLine ("-il <assembly_list_file> [-check_refs] [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]");
644 WriteLine ("\tInstalls one or more assemblies into the global assembly cache.");
646 WriteLine ("\t<assembly_list_file> is the path to a test file containing a list of\n" +
647 "\tassembly file paths on separate lines.\n" +
648 "\tExample -il assembly_list.txt\n" +
649 "\t\tassembly_list.txt contents:\n" +
650 "\t\tassembly1.dll\n" +
651 "\t\tassembly2.dll");
655 WriteLine ("-u <assembly_display_name> [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]");
656 WriteLine ("\tUninstalls an assembly from the global assembly cache.");
658 WriteLine ("\t<assembly_display_name> is the name of the assembly (partial or\n" +
659 "\tfully qualified) to remove from the global assembly cache. If a \n" +
660 "\tpartial name is specified all matching assemblies will be uninstalled.\n" +
661 "\tExample: -u myDll,Version=1.2.1.0");
665 WriteLine ("-ul <assembly_list_file> [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]");
666 WriteLine ("\tUninstalls one or more assemblies from the global assembly cache.");
668 WriteLine ("\t<assembly_list_file> is the path to a test file containing a list of\n" +
669 "\tassembly names on separate lines.\n" +
670 "\tExample -ul assembly_list.txt\n" +
671 "\t\tassembly_list.txt contents:\n" +
672 "\t\tassembly1,Version=1.0.0.0,Culture=en,PublicKeyToken=0123456789abcdef\n" +
673 "\t\tassembly2,Version=2.0.0.0,Culture=en,PublicKeyToken=0123456789abcdef");
677 WriteLine ("-us <assembly_path> [-package NAME] [-root ROOTDIR] [-gacdir GACDIR]");
678 WriteLine ("\tUninstalls an assembly using the specifed assemblies full name.");
680 WriteLine ("\t<assembly path> is the path to an assembly. The full assembly name\n" +
681 "\tis retrieved from the specified assembly if there is an assembly in\n" +
682 "\tthe GAC with a matching name, it is removed.\n" +
683 "\tExample: -us myDll.dll");
687 WriteLine ("-l [assembly_name] [-root ROOTDIR] [-gacdir GACDIR]");
688 WriteLine ("\tLists the contents of the global assembly cache.");
690 WriteLine ("\tWhen the <assembly_name> parameter is specified only matching\n" +
691 "\tassemblies are listed.");
696 WriteLine ("\tDisplays a detailed help screen");
702 WriteLine ("Options:");
703 WriteLine ("-package <NAME>");
704 WriteLine ("\tUsed to create a directory in prefix/lib/mono with the name NAME, and a\n" +
705 "\tsymlink is created from NAME/assembly_name to the assembly on the GAC.\n" +
706 "\tThis is used so developers can reference a set of libraries at once.");
709 WriteLine ("-gacdir <GACDIR>");
710 WriteLine ("\tUsed to specify the GACs base directory. Once an assembly has been installed\n" +
711 "\tto a non standard gacdir the MONO_GAC_PATH environment variable must be used\n" +
712 "\tto access the assembly.");
715 WriteLine ("-root <ROOTDIR>");
716 WriteLine ("\tUsed by developers integrating this with automake tools or packaging tools\n" +
717 "\tthat require a prefix directory to be specified. The root represents the\n" +
718 "\t\"libdir\" component of a prefix (typically prefix/lib).");
721 WriteLine ("-check_refs");
722 WriteLine ("\tUsed to ensure that the assembly being installed into the GAC does not\n" +
723 "\treference any non strong named assemblies. Assemblies being installed to\n" +
724 "\tthe GAC should not reference non strong named assemblies, however the is\n" +
725 "\tan optional check.");
728 WriteLine ("Ignored Options:");
730 WriteLine ("\tThe Mono gacutil ignores the -f option to maintian commandline compatibility with");
731 WriteLine ("\tother gacutils. gacutil will always force the installation of a new assembly.");
734 WriteLine ("-r <reference_scheme> <reference_id> <description>");
735 WriteLine ("\tThe Mono gacutil has not implemented traced references and will emit a warning");
736 WriteLine ("\twhen this option is used.");