[MSBuild] Fix minor assembly resolution issue
[mono.git] / mcs / class / Microsoft.Build.Tasks / Microsoft.Build.Tasks / AssemblyResolver.cs
1 //
2 // AssemblyResolver.cs
3 //
4 // Author:
5 //   Marek Sieradzki (marek.sieradzki@gmail.com)
6 //   Ankit Jain (jankit@novell.com)
7 // 
8 // (C) 2006 Marek Sieradzki
9 // Copyright 2009 Novell, Inc (http://www.novell.com)
10 //
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:
18 //
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 //
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.
29
30
31 using System;
32 using System.Collections.Generic;
33 using System.IO;
34 using System.Linq;
35 using System.Reflection;
36 using System.Security;
37 using Microsoft.Build.Framework;
38 using Microsoft.Build.Utilities;
39 using Mono.PkgConfig;
40
41 namespace Microsoft.Build.Tasks {
42         internal class AssemblyResolver {
43
44                 // name -> (version -> assemblypath)
45                 static Dictionary<string, TargetFrameworkAssemblies> target_framework_cache;
46                 static Dictionary<string, Dictionary<Version, string>> gac;
47                 TaskLoggingHelper log;
48                 List<string> search_log;
49
50                 static LibraryPcFileCache cache;
51
52                 public AssemblyResolver ()
53                 {
54                         if (gac == null) {
55                                 gac = new Dictionary<string, Dictionary<Version, string>> ();
56                                 target_framework_cache = new Dictionary <string, TargetFrameworkAssemblies> ();
57
58                                 GatherGacAssemblies ();
59                         }
60                 }
61
62                 public void ResetSearchLogger ()
63                 {
64                         if (search_log == null)
65                                 search_log = new List<string> ();
66                         else
67                                 search_log.Clear ();
68                 }
69
70                 string GetGacPath ()
71                 {
72                         // NOTE: code from mcs/tools/gacutil/driver.cs
73                         PropertyInfo gac = typeof (System.Environment).GetProperty ("GacPath", BindingFlags.Static | BindingFlags.NonPublic);
74
75                         if (gac == null)
76                                 return null;
77
78                         MethodInfo get_gac = gac.GetGetMethod (true);
79                         return (string) get_gac.Invoke (null, null);
80                 }
81
82                 void GatherGacAssemblies ()
83                 {
84                         string gac_path = GetGacPath ();
85                         if (gac_path == null)
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".
89
90                         Version version;
91                         DirectoryInfo version_info, assembly_info;
92
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]);
100
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);
105                                                 }
106
107                                                 string found_file;
108                                                 if (assembliesByVersion.TryGetValue (version, out found_file) &&
109                                                         File.GetLastWriteTime (file) <= File.GetLastWriteTime (found_file))
110                                                                 // Duplicate found, take the newer file
111                                                                 continue;
112
113                                                 assembliesByVersion [version] = file;
114                                         }
115                                 }
116                         }
117                 }
118
119                 public ResolvedReference FindInTargetFramework (ITaskItem reference, string framework_dir, bool specific_version)
120                 {
121                         if (!Directory.Exists (framework_dir))
122                                 return null;
123                         
124                         AssemblyName key_aname;
125                         if (!TryGetAssemblyNameFromFullName (reference.ItemSpec, out key_aname))
126                                 return null;
127
128                         TargetFrameworkAssemblies gac_asm;
129                         if (!target_framework_cache.TryGetValue (framework_dir, out gac_asm)) {
130                                 // fill gac_asm
131                                 gac_asm = target_framework_cache [framework_dir] = PopulateTargetFrameworkAssemblies (framework_dir);
132                         }
133
134                         KeyValuePair<AssemblyName, string> pair;
135                         if (gac_asm.NameToAssemblyNameCache.TryGetValue (key_aname.Name, out pair)) {
136                                 if (AssemblyNamesCompatible (key_aname, pair.Key, specific_version)) {
137                                         // gac and tgt frmwk refs are not copied private
138                                         return GetResolvedReference (reference, pair.Value, pair.Key, false,
139                                                         SearchPath.TargetFrameworkDirectory);
140                                 }
141
142                                 LogSearchMessage ("Considered target framework dir {0}, assembly name '{1}' did not " +
143                                                 "match the expected '{2}' (SpecificVersion={3})",
144                                                 framework_dir, pair.Key, key_aname, specific_version);
145                         } else {
146                                 LogSearchMessage ("Considered target framework dir {0}, assembly named '{1}' not found.",
147                                                 framework_dir, key_aname.Name);
148                         }
149                         return null;
150                 }
151
152                 // Look for %(Identity).{dll|exe|..}
153                 // if specific_version==true
154                 //      resolve if assembly names match
155                 // else
156                 //      resolve the valid assembly
157                 public ResolvedReference FindInDirectory (ITaskItem reference, string directory, string [] file_extensions, bool specific_version)
158                 {
159                         string filename = reference.ItemSpec;
160                         int comma_pos = filename.IndexOf (',');
161                         if (comma_pos >= 0)
162                                 filename = filename.Substring (0, comma_pos);
163
164                         // Try as a filename
165                         string path = Path.GetFullPath (Path.Combine (directory, filename));
166                         AssemblyName aname = null;
167                         if (specific_version && !TryGetAssemblyNameFromFullName (reference.ItemSpec, out aname))
168                                 return null;
169
170                         ResolvedReference resolved_ref = ResolveReferenceForPath (path, reference, aname, null, SearchPath.Directory, specific_version);
171                         if (resolved_ref != null)
172                                 return resolved_ref;
173
174                         // try path + Include + {.dll|.exe|..}
175                         foreach (string extn in file_extensions) {
176                                 resolved_ref = ResolveReferenceForPath (path + extn, reference, aname, null, SearchPath.Directory, specific_version);
177                                 if (resolved_ref != null)
178                                         return resolved_ref;
179                         }
180
181                         return null;
182                 }
183
184                 // tries to resolve reference from the given file path, and compares assembly names
185                 // if @specific_version == true, and logs accordingly
186                 ResolvedReference ResolveReferenceForPath (string filename, ITaskItem reference, AssemblyName aname,
187                                         string error_message, SearchPath spath, bool specific_version)
188                 {
189                         AssemblyName found_aname;
190                         if (!TryGetAssemblyNameFromFile (filename, out found_aname)) {
191                                 if (error_message != null)
192                                         log.LogMessage (MessageImportance.Low, error_message);
193                                 return null;
194                         }
195
196                         if (!specific_version || AssemblyNamesCompatible (aname, found_aname, specific_version)) {
197                                 // Check compatibility only if specific_version == true
198                                 return GetResolvedReference (reference, filename, found_aname, true, spath);
199                         } else {
200                                 LogSearchMessage ("Considered '{0}', but assembly name '{1}' did not match the " +
201                                                 "expected '{2}' (SpecificVersion={3})", filename, found_aname, aname, specific_version);
202                                 log.LogMessage (MessageImportance.Low, "Assembly names are not compatible.");
203                         }
204
205                         return null;
206                 }
207
208                 TargetFrameworkAssemblies PopulateTargetFrameworkAssemblies (string directory)
209                 {
210                         TargetFrameworkAssemblies gac_asm = new TargetFrameworkAssemblies (directory);
211                         foreach (string file in Directory.GetFiles (directory, "*.dll")) {
212                                 AssemblyName aname;
213                                 if (TryGetAssemblyNameFromFile (file, out aname))
214                                         gac_asm.NameToAssemblyNameCache [aname.Name] =
215                                                 new KeyValuePair<AssemblyName, string> (aname, file);
216                         }
217
218                         return gac_asm;
219                 }
220
221                 public ResolvedReference ResolveGacReference (ITaskItem reference, bool specific_version)
222                 {
223                         AssemblyName name;
224                         if (!TryGetAssemblyNameFromFullName (reference.ItemSpec, out name))
225                                 return null;
226
227                         if (!gac.ContainsKey (name.Name)) {
228                                 LogSearchMessage ("Considered {0}, but could not find in the GAC.",
229                                                 reference.ItemSpec);
230                                 return null;
231                         }
232
233                         if (name.Version != null) {
234                                 string ret;
235                                 if (gac [name.Name].TryGetValue (name.Version, out ret))
236                                         return GetResolvedReference (reference, ret, name, false, SearchPath.Gac);
237
238                                 // not found
239                                 if (specific_version) {
240                                         LogSearchMessage ("Considered '{0}', but an assembly with the specific version not found.",
241                                                         reference.ItemSpec);
242                                         return null;
243                                 }
244                         }
245
246                         Version [] versions = new Version [gac [name.Name].Keys.Count];
247                         gac [name.Name].Keys.CopyTo (versions, 0);
248                         Array.Sort (versions, (IComparer <Version>) null);
249                         Version highest = versions [versions.Length - 1];
250                         //FIXME: the aname being used here isn't correct, its version should
251                         //       actually match "highest"
252                         return GetResolvedReference (reference, gac [name.Name] [highest], name, false, SearchPath.Gac);
253                 }
254
255                 public ResolvedReference ResolvePkgConfigReference (ITaskItem reference, bool specific_version)
256                 {
257                         PackageAssemblyInfo pkg = null;
258
259                         pkg = PcCache.GetAssemblyLocation (reference.ItemSpec);
260                         if (pkg == null && !specific_version) {
261                                 // if not specific version, then just match simple name
262                                 string name = reference.ItemSpec;
263                                 if (name.IndexOf (',') > 0)
264                                         name = name.Substring (0, name.IndexOf (','));
265                                 pkg = PcCache.ResolveAssemblyName (name).FirstOrDefault ();
266                         }
267
268                         if (pkg == null) {
269                                 LogSearchMessage ("Considered {0}, but could not find in any pkg-config files.",
270                                                 reference.ItemSpec);
271                                 return null;
272                         }
273
274                         AssemblyName aname;
275                         if (!TryGetAssemblyNameFromFullName (pkg.FullName, out aname))
276                                 return null;
277
278                         ResolvedReference rr = GetResolvedReference (reference, pkg.File, aname,
279                                                 false, SearchPath.PkgConfig);
280                         rr.FoundInSearchPathAsString = String.Format ("{{PkgConfig}} provided by package named {0}",
281                                                         pkg.ParentPackage.Name);
282
283                         return rr;
284                 }
285
286                 // HintPath has a valid assembly
287                 // if specific_version==true
288                 //      resolve if assembly names match
289                 // else
290                 //      resolve the valid assembly
291                 public ResolvedReference ResolveHintPathReference (ITaskItem reference, bool specific_version)
292                 {
293                         string hintpath = reference.GetMetadata ("HintPath");
294                         if (String.IsNullOrEmpty (hintpath)) {
295                                 LogSearchMessage ("HintPath attribute not found");
296                                 return null;
297                         }
298
299                         if (!File.Exists (hintpath)) {
300                                 log.LogMessage (MessageImportance.Low, "HintPath {0} does not exist.", hintpath);
301                                 LogSearchMessage ("Considered {0}, but it does not exist.", hintpath);
302                                 return null;
303                         }
304
305                         AssemblyName aname;
306                         if (!TryGetAssemblyNameFromFullName (reference.ItemSpec, out aname))
307                                 return null;
308
309                         return ResolveReferenceForPath (hintpath, reference, aname,
310                                                 String.Format ("File at HintPath {0}, is either an invalid assembly or the file does not exist.", hintpath),
311                                                 SearchPath.HintPath, specific_version);
312                 }
313
314                 class CachedAssemblyName
315                 {
316                         public DateTime Time;
317                         public AssemblyName Name;
318                 }
319
320                 static Dictionary<string, CachedAssemblyName> assemblyNameCache = new Dictionary<string, CachedAssemblyName> ();
321                 public bool TryGetAssemblyNameFromFile (string filename, out AssemblyName aname)
322                 {
323                         FileInfo info = new FileInfo (filename);
324                         if (!info.Exists) {
325                                 aname = null;
326                                 LogSearchMessage ("Considered '{0}' as a file, but the file does not exist",
327                                                   filename);
328                                 return false;
329                         }
330                         filename = info.FullName;
331                         CachedAssemblyName cachedName;
332                         if (assemblyNameCache.TryGetValue (filename, out cachedName) && cachedName.Time == info.LastWriteTime) {
333                                 aname = cachedName.Name;
334                             return aname != null;
335                         }
336
337                         cachedName = new CachedAssemblyName ();
338                         cachedName.Time = info.LastWriteTime;
339                         aname = null;
340                         try {
341                                 cachedName.Name = aname = AssemblyName.GetAssemblyName (filename);
342                         } catch (FileNotFoundException) {
343                                 LogSearchMessage ("Considered '{0}' as a file, but the file does not exist",
344                                                 filename);
345                                 return false;
346                         } catch (BadImageFormatException) {
347                                 LogSearchMessage ("Considered '{0}' as a file, but it is an invalid assembly",
348                                                 filename);
349                         }
350
351                         assemblyNameCache [filename] = cachedName;
352                         return aname != null;
353                 }
354
355                 bool TryGetAssemblyNameFromFullName (string full_name, out AssemblyName aname)
356                 {
357                         aname = null;
358                         try {
359                                 aname = new AssemblyName (full_name);
360                         } catch (FileLoadException) {
361                                 LogSearchMessage ("Considered '{0}' as an assembly name, but it is invalid.", full_name);
362                         }
363
364                         return aname != null;
365                 }
366
367                 internal static bool AssemblyNamesCompatible (AssemblyName a, AssemblyName b, bool specificVersion)
368                 {
369                         return AssemblyNamesCompatible (a, b, specificVersion, true);
370                 }
371
372                 // if @specificVersion is true then match full name, else just the simple name
373                 internal static bool AssemblyNamesCompatible (AssemblyName a, AssemblyName b, bool specificVersion,
374                                 bool ignoreCase)
375                 {
376                         if (String.Compare (a.Name, b.Name, ignoreCase) != 0)
377                                 return false;
378
379                         if (!specificVersion)
380                                 // ..and simple names match
381                                 return true;
382
383                         if (a.CultureInfo != null && !a.CultureInfo.Equals (b.CultureInfo))
384                                 return false;
385
386                         if (a.Version != null && a.Version != b.Version)
387                                 return false;
388
389                         byte [] a_bytes = a.GetPublicKeyToken ();
390                         byte [] b_bytes = b.GetPublicKeyToken ();
391
392                         bool a_is_empty = (a_bytes == null || a_bytes.Length == 0);
393                         bool b_is_empty = (b_bytes == null || b_bytes.Length == 0);
394
395                         if (a_is_empty || b_is_empty)
396                                 return true;
397
398                         for (int i = 0; i < a_bytes.Length; i++)
399                                 if (a_bytes [i] != b_bytes [i])
400                                         return false;
401
402                         return true;
403                 }
404
405                 public bool IsStrongNamed (AssemblyName name)
406                 {
407                         return (name.Version != null &&
408                                         name.GetPublicKeyToken () != null &&
409                                         name.GetPublicKeyToken ().Length != 0);
410                 }
411
412                 // FIXME: to get default values of CopyLocal, compare with TargetFrameworkDirectories
413
414                 // If metadata 'Private' is present then use that or use @default_copy_local_value
415                 // as the value for CopyLocal
416                 internal ResolvedReference GetResolvedReference (ITaskItem reference, string filename,
417                                 AssemblyName aname, bool default_copy_local_value, SearchPath search_path)
418                 {
419                         string pvt = reference.GetMetadata ("Private");
420
421                         bool copy_local = default_copy_local_value;
422                         if (!String.IsNullOrEmpty (pvt))
423                                 //FIXME: log a warning for invalid value
424                                 Boolean.TryParse (pvt, out copy_local);
425
426                         ITaskItem new_item = new TaskItem (reference);
427                         new_item.ItemSpec = filename;
428                         return new ResolvedReference (new_item, aname, copy_local, search_path, reference.ItemSpec);
429                 }
430
431                 public void LogSearchMessage (string msg, params object [] args)
432                 {
433                         search_log.Add (String.Format (msg, args));
434                 }
435
436                 public void LogSearchLoggerMessages (MessageImportance importance)
437                 {
438                         foreach (string msg in search_log)
439                                 log.LogMessage (importance, msg);
440                 }
441
442                 public TaskLoggingHelper Log {
443                         set {
444                                 log = value;
445                                 PcFileCacheContext.Log = value;
446                         }
447                 }
448
449                 static LibraryPcFileCache PcCache  {
450                         get {
451                                 if (cache == null) {
452                                         var context = new PcFileCacheContext ();
453                                         cache = new LibraryPcFileCache (context);
454                                         cache.Update ();
455                                 }
456
457                                 return cache;
458                         }
459                 }
460         }
461
462         class TargetFrameworkAssemblies {
463                 public string Path;
464
465                 // assembly (simple) name -> (AssemblyName, file path)
466                 public Dictionary <string, KeyValuePair<AssemblyName, string>> NameToAssemblyNameCache;
467
468                 public TargetFrameworkAssemblies (string path)
469                 {
470                         this.Path = path;
471                         NameToAssemblyNameCache = new Dictionary<string, KeyValuePair<AssemblyName, string>> (
472                                         StringComparer.OrdinalIgnoreCase);
473                 }
474         }
475
476         class PcFileCacheContext : IPcFileCacheContext<LibraryPackageInfo>
477         {
478                 public static TaskLoggingHelper Log;
479
480                 // In the implementation of this method, the host application can extract
481                 // information from the pc file and store it in the PackageInfo object
482                 public void StoreCustomData (PcFile pcfile, LibraryPackageInfo pkg)
483                 {
484                 }
485
486                 // Should return false if the provided package does not have required
487                 // custom data
488                 public bool IsCustomDataComplete (string pcfile, LibraryPackageInfo pkg)
489                 {
490                         return true;
491                 }
492
493                 // Called to report errors
494                 public void ReportError (string message, Exception ex)
495                 {
496                         Log.LogMessage (MessageImportance.Low, "Error loading pkg-config files: {0} : {1}",
497                                         message, ex.ToString ());
498                 }
499         }
500
501         enum SearchPath
502         {
503                 Gac,
504                 TargetFrameworkDirectory,
505                 CandidateAssemblies,
506                 HintPath,
507                 Directory,
508                 RawFileName,
509                 PkgConfig
510         }
511 }
512
513
514