5 // Marek Sieradzki (marek.sieradzki@gmail.com)
6 // Ankit Jain (jankit@novell.com)
8 // (C) 2006 Marek Sieradzki
9 // Copyright 2009 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections.Generic;
36 using System.Reflection;
37 using System.Security;
38 using Microsoft.Build.Framework;
39 using Microsoft.Build.Utilities;
42 namespace Microsoft.Build.Tasks {
43 internal class AssemblyResolver {
45 // name -> (version -> assemblypath)
46 Dictionary<string, TargetFrameworkAssemblies> target_framework_cache;
47 Dictionary<string, Dictionary<Version, string>> gac;
48 TaskLoggingHelper log;
50 List<string> search_log;
52 static LibraryPcFileCache cache;
54 public AssemblyResolver ()
56 gac = new Dictionary<string, Dictionary<Version, string>> ();
57 target_framework_cache = new Dictionary <string, TargetFrameworkAssemblies> ();
59 GatherGacAssemblies ();
62 public void ResetSearchLogger ()
64 if (search_log == null)
65 search_log = new List<string> ();
72 // NOTE: code from mcs/tools/gacutil/driver.cs
73 PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
78 MethodInfo get_gac = gac.GetGetMethod (true);
79 return (string) get_gac.Invoke (null, null);
82 void GatherGacAssemblies ()
84 string gac_path = GetGacPath ();
86 throw new InvalidOperationException ("XBuild must be run on Mono runtime");
87 if (!Directory.Exists (gac_path))
88 return; // in case mono isn't "installed".
91 DirectoryInfo version_info, assembly_info;
93 foreach (string assembly_name in Directory.GetDirectories (gac_path)) {
94 assembly_info = new DirectoryInfo (assembly_name);
95 foreach (string version_token in Directory.GetDirectories (assembly_name)) {
96 foreach (string file in Directory.GetFiles (version_token, "*.dll")) {
97 version_info = new DirectoryInfo (version_token);
98 version = new Version (version_info.Name.Split (
99 new char [] {'_'}, StringSplitOptions.RemoveEmptyEntries) [0]);
101 Dictionary<Version, string> assembliesByVersion = new Dictionary <Version, string> ();
102 if (!gac.TryGetValue (assembly_info.Name, out assembliesByVersion)) {
103 assembliesByVersion = new Dictionary <Version, string> ();
104 gac.Add (assembly_info.Name, assembliesByVersion);
108 if (assembliesByVersion.TryGetValue (version, out found_file) &&
109 File.GetLastWriteTime (file) <= File.GetLastWriteTime (found_file))
110 // Duplicate found, take the newer file
113 assembliesByVersion [version] = file;
119 public ResolvedReference FindInTargetFramework (ITaskItem reference, string framework_dir, bool specific_version)
121 if (!Directory.Exists (framework_dir))
124 AssemblyName key_aname = new AssemblyName (reference.ItemSpec);
125 TargetFrameworkAssemblies gac_asm;
126 if (!target_framework_cache.TryGetValue (framework_dir, out gac_asm)) {
128 gac_asm = target_framework_cache [framework_dir] = PopulateTargetFrameworkAssemblies (framework_dir);
131 KeyValuePair<AssemblyName, string> pair;
132 if (gac_asm.NameToAssemblyNameCache.TryGetValue (key_aname.Name, out pair)) {
133 if (AssemblyNamesCompatible (key_aname, pair.Key, specific_version, true)) {
134 // gac and tgt frmwk refs are not copied private
135 return GetResolvedReference (reference, pair.Value, pair.Key, false,
136 SearchPath.TargetFrameworkDirectory);
139 LogSearchMessage ("Considered target framework dir {0}, assembly name '{1}' did not " +
140 "match the expected '{2}' (SpecificVersion={3})",
141 framework_dir, pair.Key, key_aname, specific_version);
143 LogSearchMessage ("Considered target framework dir {0}, assembly named '{1}' not found.",
144 framework_dir, key_aname.Name);
149 public ResolvedReference FindInDirectory (ITaskItem reference, string directory, string [] file_extensions)
151 if (reference.ItemSpec.IndexOf (',') < 0) {
153 string path = Path.Combine (directory, reference.ItemSpec);
154 AssemblyName aname = GetAssemblyNameFromFile (path);
156 return GetResolvedReference (reference, path, aname, true, SearchPath.Directory);
158 foreach (string extn in file_extensions) {
159 string path_with_extn = path + extn;
160 aname = GetAssemblyNameFromFile (path_with_extn);
162 return GetResolvedReference (reference, path_with_extn, aname, true,
163 SearchPath.Directory);
167 // Probably an assembly name
168 AssemblyName key_aname = new AssemblyName (reference.ItemSpec);
169 foreach (string extn in file_extensions) {
170 foreach (string file in Directory.GetFiles (directory, "*" + extn)) {
171 AssemblyName found_aname = GetAssemblyNameFromFile (file);
172 if (found_aname == null)
173 // error already logged
176 //FIXME: Extract 'name' and look only for name.dll name.exe ?
177 if (AssemblyNamesCompatible (key_aname, found_aname, false))
178 return GetResolvedReference (reference, file, found_aname, true,
179 SearchPath.Directory);
181 LogSearchMessage ("Considered {0}, but assembly name wasn't compatible.", file);
188 TargetFrameworkAssemblies PopulateTargetFrameworkAssemblies (string directory)
190 TargetFrameworkAssemblies gac_asm = new TargetFrameworkAssemblies (directory);
191 foreach (string file in Directory.GetFiles (directory, "*.dll")) {
192 AssemblyName aname = GetAssemblyNameFromFile (file);
193 gac_asm.NameToAssemblyNameCache [aname.Name] =
194 new KeyValuePair<AssemblyName, string> (aname, file);
200 public ResolvedReference ResolveGacReference (ITaskItem reference, bool specific_version)
202 AssemblyName name = new AssemblyName (reference.ItemSpec);
203 if (!gac.ContainsKey (name.Name)) {
204 LogSearchMessage ("Considered {0}, but could not find in the GAC.",
209 if (name.Version != null) {
211 if (gac [name.Name].TryGetValue (name.Version, out ret))
212 return GetResolvedReference (reference, ret, name, false, SearchPath.Gac);
215 if (specific_version) {
216 LogSearchMessage ("Considered '{0}', but an assembly with the specific version not found.",
222 Version [] versions = new Version [gac [name.Name].Keys.Count];
223 gac [name.Name].Keys.CopyTo (versions, 0);
224 Array.Sort (versions, (IComparer <Version>) null);
225 Version highest = versions [versions.Length - 1];
226 //FIXME: the aname being used here isn't correct, its version should
227 // actually match "highest"
228 return GetResolvedReference (reference, gac [name.Name] [highest], name, false, SearchPath.Gac);
231 public ResolvedReference ResolvePkgConfigReference (ITaskItem reference, bool specific_version)
233 PackageAssemblyInfo pkg = null;
235 if (specific_version) {
236 pkg = PcCache.GetAssemblyLocation (reference.ItemSpec);
238 // if not specific version, then just match simple name
239 string name = reference.ItemSpec;
240 if (name.IndexOf (',') > 0)
241 name = name.Substring (0, name.IndexOf (','));
242 pkg = PcCache.ResolveAssemblyName (name).FirstOrDefault ();
246 LogSearchMessage ("Considered {0}, but could not find in any pkg-config files.",
251 ResolvedReference rr = GetResolvedReference (reference, pkg.File, new AssemblyName (pkg.FullName),
252 false, SearchPath.PkgConfig);
253 rr.FoundInSearchPathAsString = String.Format ("{{PkgConfig}} provided by package named {0}",
254 pkg.ParentPackage.Name);
259 public ResolvedReference ResolveHintPathReference (ITaskItem reference, bool specific_version)
261 AssemblyName name = new AssemblyName (reference.ItemSpec);
262 ResolvedReference resolved = null;
264 string hintpath = reference.GetMetadata ("HintPath");
265 if (String.IsNullOrEmpty (hintpath)) {
266 LogSearchMessage ("HintPath attribute not found");
270 if (!File.Exists (hintpath)) {
271 log.LogMessage (MessageImportance.Low, "HintPath {0} does not exist.", hintpath);
272 LogSearchMessage ("Considered {0}, but it does not exist.", hintpath);
276 AssemblyName found = GetAssemblyNameFromFile (hintpath);
278 log.LogMessage (MessageImportance.Low, "File at HintPath {0}, is either an invalid assembly or the file does not exist.", hintpath);
282 if (AssemblyNamesCompatible (name, found, specific_version)) {
283 resolved = GetResolvedReference (reference, hintpath, found, true, SearchPath.HintPath);
285 LogSearchMessage ("Considered {0}, but assembly name '{1}' did not match the " +
286 "expected '{2}' (SpecificVersion={3})", hintpath, found, name, specific_version);
287 log.LogMessage (MessageImportance.Low, "Assembly names are not compatible.");
293 public AssemblyName GetAssemblyNameFromFile (string filename)
295 AssemblyName aname = null;
296 filename = Path.GetFullPath (filename);
298 aname = AssemblyName.GetAssemblyName (filename);
299 } catch (FileNotFoundException) {
300 LogSearchMessage ("Considered '{0}' as a file, but the file does not exist",
302 } catch (BadImageFormatException) {
303 LogSearchMessage ("Considered '{0}' as a file, but it is an invalid assembly",
310 internal static bool AssemblyNamesCompatible (AssemblyName a, AssemblyName b, bool specificVersion)
312 return AssemblyNamesCompatible (a, b, specificVersion, false);
315 // if @specificVersion is true then match full name, else just the simple name
316 internal static bool AssemblyNamesCompatible (AssemblyName a, AssemblyName b, bool specificVersion,
319 if (String.Compare (a.Name, b.Name, ignoreCase) != 0)
322 if (!specificVersion)
323 // ..and simple names match
326 if (a.CultureInfo != null && !a.CultureInfo.Equals (b.CultureInfo))
329 if (a.Version != null && a.Version != b.Version)
332 byte [] a_bytes = a.GetPublicKeyToken ();
333 byte [] b_bytes = b.GetPublicKeyToken ();
335 bool a_is_empty = (a_bytes == null || a_bytes.Length == 0);
336 bool b_is_empty = (b_bytes == null || b_bytes.Length == 0);
338 if (a_is_empty && b_is_empty)
341 if (a_is_empty || b_is_empty)
344 for (int i = 0; i < a_bytes.Length; i++)
345 if (a_bytes [i] != b_bytes [i])
351 public bool IsStrongNamed (AssemblyName name)
353 return (name.Version != null &&
354 name.GetPublicKeyToken () != null &&
355 name.GetPublicKeyToken ().Length != 0);
358 // FIXME: to get default values of CopyLocal, compare with TargetFrameworkDirectories
360 // If metadata 'Private' is present then use that or use @default_copy_local_value
361 // as the value for CopyLocal
362 internal ResolvedReference GetResolvedReference (ITaskItem reference, string filename,
363 AssemblyName aname, bool default_copy_local_value, SearchPath search_path)
365 string pvt = reference.GetMetadata ("Private");
367 bool copy_local = default_copy_local_value;
368 if (!String.IsNullOrEmpty (pvt))
369 //FIXME: log a warning for invalid value
370 Boolean.TryParse (pvt, out copy_local);
372 ITaskItem new_item = new TaskItem (reference);
373 new_item.ItemSpec = filename;
374 return new ResolvedReference (new_item, aname, copy_local, search_path, reference.ItemSpec);
377 public void LogSearchMessage (string msg, params object [] args)
379 search_log.Add (String.Format (msg, args));
382 public void LogSearchLoggerMessages ()
384 foreach (string msg in search_log)
385 log.LogMessage (msg);
388 public TaskLoggingHelper Log {
391 PcFileCacheContext.Log = value;
395 static LibraryPcFileCache PcCache {
398 var context = new PcFileCacheContext ();
399 cache = new LibraryPcFileCache (context);
408 class TargetFrameworkAssemblies {
411 // assembly (simple) name -> (AssemblyName, file path)
412 public Dictionary <string, KeyValuePair<AssemblyName, string>> NameToAssemblyNameCache;
414 public TargetFrameworkAssemblies (string path)
417 NameToAssemblyNameCache = new Dictionary<string, KeyValuePair<AssemblyName, string>> (
418 StringComparer.InvariantCultureIgnoreCase);
422 class PcFileCacheContext : IPcFileCacheContext<LibraryPackageInfo>
424 public static TaskLoggingHelper Log;
426 // In the implementation of this method, the host application can extract
427 // information from the pc file and store it in the PackageInfo object
428 public void StoreCustomData (PcFile pcfile, LibraryPackageInfo pkg)
432 // Should return false if the provided package does not have required
434 public bool IsCustomDataComplete (string pcfile, LibraryPackageInfo pkg)
439 // Called to report errors
440 public void ReportError (string message, Exception ex)
442 Log.LogMessage (MessageImportance.Low, "Error loading pkg-config files: {0} : {1}",
443 message, ex.ToString ());
450 TargetFrameworkDirectory,