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 static Dictionary<string, TargetFrameworkAssemblies> target_framework_cache;
47 static Dictionary<string, Dictionary<Version, string>> gac;
48 TaskLoggingHelper log;
49 List<string> search_log;
51 static LibraryPcFileCache cache;
53 public AssemblyResolver ()
56 gac = new Dictionary<string, Dictionary<Version, string>> ();
57 target_framework_cache = new Dictionary <string, TargetFrameworkAssemblies> ();
59 GatherGacAssemblies ();
63 public void ResetSearchLogger ()
65 if (search_log == null)
66 search_log = new List<string> ();
73 // NOTE: code from mcs/tools/gacutil/driver.cs
74 PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
79 MethodInfo get_gac = gac.GetGetMethod (true);
80 return (string) get_gac.Invoke (null, null);
83 void GatherGacAssemblies ()
85 string gac_path = GetGacPath ();
87 throw new InvalidOperationException ("XBuild must be run on Mono runtime");
88 if (!Directory.Exists (gac_path))
89 return; // in case mono isn't "installed".
92 DirectoryInfo version_info, assembly_info;
94 foreach (string assembly_name in Directory.GetDirectories (gac_path)) {
95 assembly_info = new DirectoryInfo (assembly_name);
96 foreach (string version_token in Directory.GetDirectories (assembly_name)) {
97 foreach (string file in Directory.GetFiles (version_token, "*.dll")) {
98 version_info = new DirectoryInfo (version_token);
99 version = new Version (version_info.Name.Split (
100 new char [] {'_'}, StringSplitOptions.RemoveEmptyEntries) [0]);
102 Dictionary<Version, string> assembliesByVersion = new Dictionary <Version, string> ();
103 if (!gac.TryGetValue (assembly_info.Name, out assembliesByVersion)) {
104 assembliesByVersion = new Dictionary <Version, string> ();
105 gac.Add (assembly_info.Name, assembliesByVersion);
109 if (assembliesByVersion.TryGetValue (version, out found_file) &&
110 File.GetLastWriteTime (file) <= File.GetLastWriteTime (found_file))
111 // Duplicate found, take the newer file
114 assembliesByVersion [version] = file;
120 public ResolvedReference FindInTargetFramework (ITaskItem reference, string framework_dir, bool specific_version)
122 if (!Directory.Exists (framework_dir))
125 AssemblyName key_aname;
126 if (!TryGetAssemblyNameFromFullName (reference.ItemSpec, out key_aname))
129 TargetFrameworkAssemblies gac_asm;
130 if (!target_framework_cache.TryGetValue (framework_dir, out gac_asm)) {
132 gac_asm = target_framework_cache [framework_dir] = PopulateTargetFrameworkAssemblies (framework_dir);
135 KeyValuePair<AssemblyName, string> pair;
136 if (gac_asm.NameToAssemblyNameCache.TryGetValue (key_aname.Name, out pair)) {
137 if (AssemblyNamesCompatible (key_aname, pair.Key, specific_version)) {
138 // gac and tgt frmwk refs are not copied private
139 return GetResolvedReference (reference, pair.Value, pair.Key, false,
140 SearchPath.TargetFrameworkDirectory);
143 LogSearchMessage ("Considered target framework dir {0}, assembly name '{1}' did not " +
144 "match the expected '{2}' (SpecificVersion={3})",
145 framework_dir, pair.Key, key_aname, specific_version);
147 LogSearchMessage ("Considered target framework dir {0}, assembly named '{1}' not found.",
148 framework_dir, key_aname.Name);
153 // Look for %(Identity).{dll|exe|..}
154 // if specific_version==true
155 // resolve if assembly names match
157 // resolve the valid assembly
158 public ResolvedReference FindInDirectory (ITaskItem reference, string directory, string [] file_extensions, bool specific_version)
160 string filename = reference.ItemSpec;
161 int comma_pos = filename.IndexOf (',');
163 filename = filename.Substring (0, comma_pos);
166 string path = Path.GetFullPath (Path.Combine (directory, filename));
167 AssemblyName aname = null;
168 if (specific_version && !TryGetAssemblyNameFromFullName (reference.ItemSpec, out aname))
171 ResolvedReference resolved_ref = ResolveReferenceForPath (path, reference, aname, null, SearchPath.Directory, specific_version);
172 if (resolved_ref != null)
175 // try path + Include + {.dll|.exe|..}
176 foreach (string extn in file_extensions) {
177 resolved_ref = ResolveReferenceForPath (path + extn, reference, aname, null, SearchPath.Directory, specific_version);
178 if (resolved_ref != null)
185 // tries to resolve reference from the given file path, and compares assembly names
186 // if @specific_version == true, and logs accordingly
187 ResolvedReference ResolveReferenceForPath (string filename, ITaskItem reference, AssemblyName aname,
188 string error_message, SearchPath spath, bool specific_version)
190 AssemblyName found_aname;
191 if (!TryGetAssemblyNameFromFile (filename, out found_aname)) {
192 if (error_message != null)
193 log.LogMessage (MessageImportance.Low, error_message);
197 if (!specific_version || AssemblyNamesCompatible (aname, found_aname, specific_version)) {
198 // Check compatibility only if specific_version == true
199 return GetResolvedReference (reference, filename, found_aname, true, spath);
201 LogSearchMessage ("Considered '{0}', but assembly name '{1}' did not match the " +
202 "expected '{2}' (SpecificVersion={3})", filename, found_aname, aname, specific_version);
203 log.LogMessage (MessageImportance.Low, "Assembly names are not compatible.");
209 TargetFrameworkAssemblies PopulateTargetFrameworkAssemblies (string directory)
211 TargetFrameworkAssemblies gac_asm = new TargetFrameworkAssemblies (directory);
212 foreach (string file in Directory.GetFiles (directory, "*.dll")) {
214 if (TryGetAssemblyNameFromFile (file, out aname))
215 gac_asm.NameToAssemblyNameCache [aname.Name] =
216 new KeyValuePair<AssemblyName, string> (aname, file);
222 public ResolvedReference ResolveGacReference (ITaskItem reference, bool specific_version)
225 if (!TryGetAssemblyNameFromFullName (reference.ItemSpec, out name))
228 if (!gac.ContainsKey (name.Name)) {
229 LogSearchMessage ("Considered {0}, but could not find in the GAC.",
234 if (name.Version != null) {
236 if (gac [name.Name].TryGetValue (name.Version, out ret))
237 return GetResolvedReference (reference, ret, name, false, SearchPath.Gac);
240 if (specific_version) {
241 LogSearchMessage ("Considered '{0}', but an assembly with the specific version not found.",
247 Version [] versions = new Version [gac [name.Name].Keys.Count];
248 gac [name.Name].Keys.CopyTo (versions, 0);
249 Array.Sort (versions, (IComparer <Version>) null);
250 Version highest = versions [versions.Length - 1];
251 //FIXME: the aname being used here isn't correct, its version should
252 // actually match "highest"
253 return GetResolvedReference (reference, gac [name.Name] [highest], name, false, SearchPath.Gac);
256 public ResolvedReference ResolvePkgConfigReference (ITaskItem reference, bool specific_version)
258 PackageAssemblyInfo pkg = null;
260 if (specific_version) {
261 pkg = PcCache.GetAssemblyLocation (reference.ItemSpec);
263 // if not specific version, then just match simple name
264 string name = reference.ItemSpec;
265 if (name.IndexOf (',') > 0)
266 name = name.Substring (0, name.IndexOf (','));
267 pkg = PcCache.ResolveAssemblyName (name).FirstOrDefault ();
271 LogSearchMessage ("Considered {0}, but could not find in any pkg-config files.",
277 if (!TryGetAssemblyNameFromFullName (pkg.FullName, out aname))
280 ResolvedReference rr = GetResolvedReference (reference, pkg.File, aname,
281 false, SearchPath.PkgConfig);
282 rr.FoundInSearchPathAsString = String.Format ("{{PkgConfig}} provided by package named {0}",
283 pkg.ParentPackage.Name);
288 // HintPath has a valid assembly
289 // if specific_version==true
290 // resolve if assembly names match
292 // resolve the valid assembly
293 public ResolvedReference ResolveHintPathReference (ITaskItem reference, bool specific_version)
295 string hintpath = reference.GetMetadata ("HintPath");
296 if (String.IsNullOrEmpty (hintpath)) {
297 LogSearchMessage ("HintPath attribute not found");
301 if (!File.Exists (hintpath)) {
302 log.LogMessage (MessageImportance.Low, "HintPath {0} does not exist.", hintpath);
303 LogSearchMessage ("Considered {0}, but it does not exist.", hintpath);
308 if (!TryGetAssemblyNameFromFullName (reference.ItemSpec, out aname))
311 return ResolveReferenceForPath (hintpath, reference, aname,
312 String.Format ("File at HintPath {0}, is either an invalid assembly or the file does not exist.", hintpath),
313 SearchPath.HintPath, specific_version);
316 static Dictionary<string, AssemblyName> assemblyNameCache = new Dictionary<string, AssemblyName> ();
317 public bool TryGetAssemblyNameFromFile (string filename, out AssemblyName aname)
319 filename = Path.GetFullPath (filename);
320 if (assemblyNameCache.TryGetValue (filename, out aname))
321 return aname != null;
325 aname = AssemblyName.GetAssemblyName (filename);
326 } catch (FileNotFoundException) {
327 LogSearchMessage ("Considered '{0}' as a file, but the file does not exist",
329 } catch (BadImageFormatException) {
330 LogSearchMessage ("Considered '{0}' as a file, but it is an invalid assembly",
334 assemblyNameCache [filename] = aname;
335 return aname != null;
338 bool TryGetAssemblyNameFromFullName (string full_name, out AssemblyName aname)
342 aname = new AssemblyName (full_name);
343 } catch (FileLoadException) {
344 LogSearchMessage ("Considered '{0}' as an assembly name, but it is invalid.", full_name);
347 return aname != null;
350 internal static bool AssemblyNamesCompatible (AssemblyName a, AssemblyName b, bool specificVersion)
352 return AssemblyNamesCompatible (a, b, specificVersion, true);
355 // if @specificVersion is true then match full name, else just the simple name
356 internal static bool AssemblyNamesCompatible (AssemblyName a, AssemblyName b, bool specificVersion,
359 if (String.Compare (a.Name, b.Name, ignoreCase) != 0)
362 if (!specificVersion)
363 // ..and simple names match
366 if (a.CultureInfo != null && !a.CultureInfo.Equals (b.CultureInfo))
369 if (a.Version != null && a.Version != b.Version)
372 byte [] a_bytes = a.GetPublicKeyToken ();
373 byte [] b_bytes = b.GetPublicKeyToken ();
375 bool a_is_empty = (a_bytes == null || a_bytes.Length == 0);
376 bool b_is_empty = (b_bytes == null || b_bytes.Length == 0);
378 if (a_is_empty || b_is_empty)
381 for (int i = 0; i < a_bytes.Length; i++)
382 if (a_bytes [i] != b_bytes [i])
388 public bool IsStrongNamed (AssemblyName name)
390 return (name.Version != null &&
391 name.GetPublicKeyToken () != null &&
392 name.GetPublicKeyToken ().Length != 0);
395 // FIXME: to get default values of CopyLocal, compare with TargetFrameworkDirectories
397 // If metadata 'Private' is present then use that or use @default_copy_local_value
398 // as the value for CopyLocal
399 internal ResolvedReference GetResolvedReference (ITaskItem reference, string filename,
400 AssemblyName aname, bool default_copy_local_value, SearchPath search_path)
402 string pvt = reference.GetMetadata ("Private");
404 bool copy_local = default_copy_local_value;
405 if (!String.IsNullOrEmpty (pvt))
406 //FIXME: log a warning for invalid value
407 Boolean.TryParse (pvt, out copy_local);
409 ITaskItem new_item = new TaskItem (reference);
410 new_item.ItemSpec = filename;
411 return new ResolvedReference (new_item, aname, copy_local, search_path, reference.ItemSpec);
414 public void LogSearchMessage (string msg, params object [] args)
416 search_log.Add (String.Format (msg, args));
419 public void LogSearchLoggerMessages (MessageImportance importance)
421 foreach (string msg in search_log)
422 log.LogMessage (importance, msg);
425 public TaskLoggingHelper Log {
428 PcFileCacheContext.Log = value;
432 static LibraryPcFileCache PcCache {
435 var context = new PcFileCacheContext ();
436 cache = new LibraryPcFileCache (context);
445 class TargetFrameworkAssemblies {
448 // assembly (simple) name -> (AssemblyName, file path)
449 public Dictionary <string, KeyValuePair<AssemblyName, string>> NameToAssemblyNameCache;
451 public TargetFrameworkAssemblies (string path)
454 NameToAssemblyNameCache = new Dictionary<string, KeyValuePair<AssemblyName, string>> (
455 StringComparer.OrdinalIgnoreCase);
459 class PcFileCacheContext : IPcFileCacheContext<LibraryPackageInfo>
461 public static TaskLoggingHelper Log;
463 // In the implementation of this method, the host application can extract
464 // information from the pc file and store it in the PackageInfo object
465 public void StoreCustomData (PcFile pcfile, LibraryPackageInfo pkg)
469 // Should return false if the provided package does not have required
471 public bool IsCustomDataComplete (string pcfile, LibraryPackageInfo pkg)
476 // Called to report errors
477 public void ReportError (string message, Exception ex)
479 Log.LogMessage (MessageImportance.Low, "Error loading pkg-config files: {0} : {1}",
480 message, ex.ToString ());
487 TargetFrameworkDirectory,