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