2 // ResolveAssemblyReference.cs: Searches for assembly files.
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;
34 using System.Globalization;
37 using System.Reflection;
38 using System.Security;
39 using Microsoft.Build.Framework;
40 using Microsoft.Build.Utilities;
42 namespace Microsoft.Build.Tasks {
43 public class ResolveAssemblyReference : TaskExtension {
46 ITaskItem[] assemblyFiles;
47 ITaskItem[] assemblies;
49 string[] allowedAssemblyExtensions;
50 string[] allowedRelatedFileExtensions;
51 string[] candidateAssemblyFiles;
52 ITaskItem[] copyLocalFiles;
53 ITaskItem[] filesWritten;
54 bool findDependencies;
55 bool findRelatedFiles;
57 bool findSerializationAssemblies;
58 string[] installedAssemblyTables;
59 ITaskItem[] relatedFiles;
60 ITaskItem[] resolvedDependencyFiles;
61 ITaskItem[] resolvedFiles;
62 ITaskItem[] satelliteFiles;
63 ITaskItem[] scatterFiles;
65 ITaskItem[] serializationAssemblyFiles;
68 ITaskItem[] suggestedRedirects;
69 string[] targetFrameworkDirectories;
70 string targetProcessorArchitecture;
71 static string [] default_assembly_extensions;
73 AssemblyResolver assembly_resolver;
74 List<string> dependency_search_paths;
75 Dictionary<string, ResolvedReference> assemblyNameToResolvedRef;
76 Dictionary<string, ITaskItem> tempSatelliteFiles, tempRelatedFiles,
77 tempResolvedDepFiles, tempCopyLocalFiles;
78 List<ITaskItem> tempResolvedFiles;
79 List<PrimaryReference> primaryReferences;
80 Dictionary<string, string> alreadyScannedAssemblyNames;
81 Dictionary<string, string> conflictWarningsCache;
83 //FIXME: construct and use a graph of the dependencies, useful across projects
85 static ResolveAssemblyReference ()
87 default_assembly_extensions = new string [] { ".dll", ".exe" };
90 public ResolveAssemblyReference ()
92 assembly_resolver = new AssemblyResolver ();
95 //FIXME: make this reusable
96 public override bool Execute ()
98 if (assemblies == null && assemblyFiles == null)
102 assembly_resolver.Log = Log;
103 tempResolvedFiles = new List<ITaskItem> ();
104 tempCopyLocalFiles = new Dictionary<string, ITaskItem> ();
105 tempSatelliteFiles = new Dictionary<string, ITaskItem> ();
106 tempRelatedFiles = new Dictionary<string, ITaskItem> ();
107 tempResolvedDepFiles = new Dictionary<string, ITaskItem> ();
109 primaryReferences = new List<PrimaryReference> ();
110 assemblyNameToResolvedRef = new Dictionary<string, ResolvedReference> ();
111 conflictWarningsCache = new Dictionary<string, string> ();
113 ResolveAssemblies ();
114 ResolveAssemblyFiles ();
116 alreadyScannedAssemblyNames = new Dictionary<string, string> ();
118 // the first element is place holder for parent assembly's dir
119 dependency_search_paths = new List<string> () { String.Empty };
120 dependency_search_paths.AddRange (searchPaths);
122 // resolve dependencies
123 foreach (PrimaryReference pref in primaryReferences)
124 ResolveAssemblyFileDependencies (pref.TaskItem, pref.ParentCopyLocal);
126 resolvedFiles = tempResolvedFiles.ToArray ();
127 copyLocalFiles = tempCopyLocalFiles.Values.ToArray ();
128 satelliteFiles = tempSatelliteFiles.Values.ToArray ();
129 relatedFiles = tempRelatedFiles.Values.ToArray ();
130 resolvedDependencyFiles = tempResolvedDepFiles.Values.ToArray ();
132 tempResolvedFiles.Clear ();
133 tempCopyLocalFiles.Clear ();
134 tempSatelliteFiles.Clear ();
135 tempRelatedFiles.Clear ();
136 tempResolvedDepFiles.Clear ();
137 alreadyScannedAssemblyNames.Clear ();
138 primaryReferences.Clear ();
139 assemblyNameToResolvedRef.Clear ();
140 conflictWarningsCache.Clear ();
141 dependency_search_paths = null;
146 void ResolveAssemblies ()
148 if (assemblies == null || assemblies.Length == 0)
151 foreach (ITaskItem item in assemblies) {
152 if (!String.IsNullOrEmpty (item.GetMetadata ("SubType"))) {
153 Log.LogWarning ("Reference '{0}' has non-empty SubType. Ignoring.", item.ItemSpec);
157 LogWithPrecedingNewLine (MessageImportance.Low, "Primary Reference {0}", item.ItemSpec);
158 ResolvedReference resolved_ref = ResolveReference (item, searchPaths, true);
159 if (resolved_ref == null) {
160 Log.LogWarning ("Reference '{0}' not resolved", item.ItemSpec);
161 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
163 if (Environment.GetEnvironmentVariable ("XBUILD_LOG_REFERENCE_RESOLVER") != null)
164 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
166 Log.LogMessage (MessageImportance.Low,
167 "\tReference {0} resolved to {1}. CopyLocal = {2}",
168 item.ItemSpec, resolved_ref.TaskItem,
169 resolved_ref.TaskItem.GetMetadata ("CopyLocal"));
171 Log.LogMessage (MessageImportance.Low,
172 "\tReference found at search path {0}",
173 resolved_ref.FoundInSearchPathAsString);
175 if (TryAddNewReference (tempResolvedFiles, resolved_ref) &&
176 !IsFromGacOrTargetFramework (resolved_ref) &&
177 resolved_ref.FoundInSearchPath != SearchPath.PkgConfig) {
178 primaryReferences.Add (new PrimaryReference (
179 resolved_ref.TaskItem,
180 resolved_ref.TaskItem.GetMetadata ("CopyLocal")));
186 // Use @search_paths to resolve the reference
187 ResolvedReference ResolveReference (ITaskItem item, IEnumerable<string> search_paths, bool set_copy_local)
189 ResolvedReference resolved = null;
190 bool specific_version;
192 assembly_resolver.ResetSearchLogger ();
194 if (!TryGetSpecificVersionValue (item, out specific_version))
197 foreach (string spath in search_paths) {
198 assembly_resolver.LogSearchMessage ("For searchpath {0}", spath);
200 if (String.Compare (spath, "{HintPathFromItem}") == 0) {
201 resolved = assembly_resolver.ResolveHintPathReference (item, specific_version);
202 } else if (String.Compare (spath, "{TargetFrameworkDirectory}") == 0) {
203 if (targetFrameworkDirectories == null)
205 foreach (string fpath in targetFrameworkDirectories) {
206 resolved = assembly_resolver.FindInTargetFramework (item,
207 fpath, specific_version);
208 if (resolved != null)
211 } else if (String.Compare (spath, "{GAC}") == 0) {
212 resolved = assembly_resolver.ResolveGacReference (item, specific_version);
213 } else if (String.Compare (spath, "{RawFileName}") == 0) {
214 //FIXME: identify assembly names, as extract the name, and try with that?
216 if (assembly_resolver.TryGetAssemblyNameFromFile (item.ItemSpec, out aname))
217 resolved = assembly_resolver.GetResolvedReference (item, item.ItemSpec, aname, true,
218 SearchPath.RawFileName);
219 } else if (String.Compare (spath, "{CandidateAssemblyFiles}") == 0) {
220 assembly_resolver.LogSearchMessage (
221 "Warning: {{CandidateAssemblyFiles}} not supported currently");
222 } else if (String.Compare (spath, "{PkgConfig}") == 0) {
223 resolved = assembly_resolver.ResolvePkgConfigReference (item, specific_version);
225 resolved = assembly_resolver.FindInDirectory (
227 allowedAssemblyExtensions ?? default_assembly_extensions,
231 if (resolved != null)
235 if (resolved != null && set_copy_local)
236 SetCopyLocal (resolved.TaskItem, resolved.CopyLocal.ToString ());
241 bool TryGetSpecificVersionValue (ITaskItem item, out bool specific_version)
243 specific_version = true;
244 string value = item.GetMetadata ("SpecificVersion");
245 if (String.IsNullOrEmpty (value)) {
246 //AssemblyName name = new AssemblyName (item.ItemSpec);
247 // If SpecificVersion is not specified, then
248 // it is true if the Include is a strong name else false
249 //specific_version = assembly_resolver.IsStrongNamed (name);
251 // msbuild seems to just look for a ',' in the name :/
252 specific_version = item.ItemSpec.IndexOf (',') >= 0;
256 if (Boolean.TryParse (value, out specific_version))
259 Log.LogError ("Item '{0}' has attribute SpecificVersion with invalid value '{1}' " +
260 "which could not be converted to a boolean.", item.ItemSpec, value);
264 //FIXME: Consider CandidateAssemblyFiles also here
265 void ResolveAssemblyFiles ()
267 if (assemblyFiles == null)
270 foreach (ITaskItem item in assemblyFiles) {
271 assembly_resolver.ResetSearchLogger ();
273 if (!File.Exists (item.ItemSpec)) {
274 LogWithPrecedingNewLine (MessageImportance.Low,
275 "Primary Reference from AssemblyFiles {0}, file not found. Ignoring",
280 LogWithPrecedingNewLine (MessageImportance.Low, "Primary Reference from AssemblyFiles {0}", item.ItemSpec);
284 if (!assembly_resolver.TryGetAssemblyNameFromFile (item.ItemSpec, out aname)) {
285 Log.LogWarning ("Reference '{0}' not resolved", item.ItemSpec);
286 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
290 if (Environment.GetEnvironmentVariable ("XBUILD_LOG_REFERENCE_RESOLVER") != null)
291 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
293 ResolvedReference rr = assembly_resolver.GetResolvedReference (item, item.ItemSpec, aname, true,
294 SearchPath.RawFileName);
295 copy_local = rr.CopyLocal.ToString ();
297 if (!TryAddNewReference (tempResolvedFiles, rr))
301 SetCopyLocal (rr.TaskItem, copy_local);
303 FindAndAddRelatedFiles (item.ItemSpec, copy_local);
304 FindAndAddSatellites (item.ItemSpec, copy_local);
306 if (FindDependencies && !IsFromGacOrTargetFramework (rr) &&
307 rr.FoundInSearchPath != SearchPath.PkgConfig)
308 primaryReferences.Add (new PrimaryReference (item, copy_local));
312 // Tries to resolve assemblies referenced by @item
313 // Skips gac references
315 void ResolveAssemblyFileDependencies (ITaskItem item, string parent_copy_local)
317 Queue<string> dependencies = new Queue<string> ();
318 dependencies.Enqueue (item.ItemSpec);
320 while (dependencies.Count > 0) {
321 string filename = Path.GetFullPath (dependencies.Dequeue ());
322 Assembly asm = Assembly.ReflectionOnlyLoadFrom (filename);
323 if (alreadyScannedAssemblyNames.ContainsKey (asm.FullName))
326 // set the 1st search path to this ref's base path
327 // Will be used for resolving the dependencies
328 dependency_search_paths [0] = Path.GetDirectoryName (filename);
330 foreach (AssemblyName aname in asm.GetReferencedAssemblies ()) {
331 if (alreadyScannedAssemblyNames.ContainsKey (aname.FullName))
334 ResolvedReference resolved_ref = ResolveDependencyByAssemblyName (
335 aname, asm.FullName, parent_copy_local);
337 if (resolved_ref != null && !IsFromGacOrTargetFramework (resolved_ref)
338 && resolved_ref.FoundInSearchPath != SearchPath.PkgConfig)
339 dependencies.Enqueue (resolved_ref.TaskItem.ItemSpec);
341 alreadyScannedAssemblyNames.Add (asm.FullName, String.Empty);
345 // Resolves by looking dependency_search_paths
346 // which is dir of parent reference file, and
348 ResolvedReference ResolveDependencyByAssemblyName (AssemblyName aname, string parent_asm_name,
349 string parent_copy_local)
351 // This will check for compatible assembly name/version
352 ResolvedReference resolved_ref;
353 if (TryGetResolvedReferenceByAssemblyName (aname, false, out resolved_ref))
356 LogWithPrecedingNewLine (MessageImportance.Low, "Dependency {0}", aname);
357 Log.LogMessage (MessageImportance.Low, "\tRequired by {0}", parent_asm_name);
359 ITaskItem item = new TaskItem (aname.FullName);
360 item.SetMetadata ("SpecificVersion", "false");
361 resolved_ref = ResolveReference (item, dependency_search_paths, false);
363 if (resolved_ref != null) {
364 if (Environment.GetEnvironmentVariable ("XBUILD_LOG_REFERENCE_RESOLVER") != null)
365 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
367 Log.LogMessage (MessageImportance.Low, "\tReference {0} resolved to {1}.",
368 aname, resolved_ref.TaskItem.ItemSpec);
370 Log.LogMessage (MessageImportance.Low,
371 "\tReference found at search path {0}",
372 resolved_ref.FoundInSearchPathAsString);
374 if (resolved_ref.FoundInSearchPath == SearchPath.Directory) {
375 // override CopyLocal with parent's val
376 SetCopyLocal (resolved_ref.TaskItem, parent_copy_local);
378 Log.LogMessage (MessageImportance.Low,
379 "\tThis is CopyLocal {0} as parent item has this value",
382 if (TryAddNewReference (tempResolvedFiles, resolved_ref)) {
383 FindAndAddRelatedFiles (resolved_ref.TaskItem.ItemSpec, parent_copy_local);
384 FindAndAddSatellites (resolved_ref.TaskItem.ItemSpec, parent_copy_local);
388 Log.LogMessage (MessageImportance.Low,
389 "\tThis is CopyLocal false as it is in the gac," +
390 "target framework directory or provided by a package.");
392 TryAddNewReference (tempResolvedFiles, resolved_ref);
395 Log.LogWarning ("Reference '{0}' not resolved", aname);
396 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
402 void FindAndAddRelatedFiles (string filename, string parent_copy_local)
404 if (!findRelatedFiles || allowedRelatedFileExtensions == null)
407 foreach (string ext in allowedRelatedFileExtensions) {
408 string rfile = filename + ext;
409 if (File.Exists (rfile)) {
410 ITaskItem item = new TaskItem (rfile);
411 SetCopyLocal (item, parent_copy_local);
413 tempRelatedFiles.AddUniqueFile (item);
418 void FindAndAddSatellites (string filename, string parent_copy_local)
423 string basepath = Path.GetDirectoryName (filename);
424 string resource = String.Format ("{0}{1}{2}",
425 Path.GetFileNameWithoutExtension (filename),
427 Path.GetExtension (filename));
429 string dir_sep = Path.DirectorySeparatorChar.ToString ();
430 foreach (string dir in Directory.GetDirectories (basepath)) {
431 string culture = Path.GetFileName (dir);
432 if (!CultureNamesTable.ContainsKey (culture))
435 string res_path = Path.Combine (dir, resource);
436 if (File.Exists (res_path)) {
437 ITaskItem item = new TaskItem (res_path);
438 SetCopyLocal (item, parent_copy_local);
439 item.SetMetadata ("DestinationSubdirectory", culture + dir_sep);
440 tempSatelliteFiles.AddUniqueFile (item);
445 // returns true is it was new
446 bool TryAddNewReference (List<ITaskItem> file_list, ResolvedReference key_ref)
448 ResolvedReference found_ref;
449 if (!TryGetResolvedReferenceByAssemblyName (key_ref.AssemblyName, key_ref.IsPrimary, out found_ref)) {
450 assemblyNameToResolvedRef [key_ref.AssemblyName.Name] = key_ref;
451 file_list.Add (key_ref.TaskItem);
458 void SetCopyLocal (ITaskItem item, string copy_local)
460 item.SetMetadata ("CopyLocal", copy_local);
462 // Assumed to be valid value
463 if (Boolean.Parse (copy_local))
464 tempCopyLocalFiles.AddUniqueFile (item);
467 bool TryGetResolvedReferenceByAssemblyName (AssemblyName key_aname, bool is_primary, out ResolvedReference found_ref)
470 // Match by just name
471 if (!assemblyNameToResolvedRef.TryGetValue (key_aname.Name, out found_ref))
475 // match for full name
476 if (AssemblyResolver.AssemblyNamesCompatible (key_aname, found_ref.AssemblyName, true, false))
477 // exact match, so its already there, dont add anything
480 // we have a name match, but version mismatch!
481 assembly_resolver.LogSearchMessage ("A conflict was detected between '{0}' and '{1}'",
482 key_aname.FullName, found_ref.AssemblyName.FullName);
484 if (is_primary == found_ref.IsPrimary) {
485 assembly_resolver.LogSearchMessage ("Unable to choose between the two. " +
486 "Choosing '{0}' arbitrarily.", found_ref.AssemblyName.FullName);
490 // since all dependencies are processed after
491 // all primary refererences, the one in the cache
492 // has to be a primary
493 // Prefer a primary reference over a dependency
495 assembly_resolver.LogSearchMessage ("Choosing '{0}' as it is a primary reference.",
496 found_ref.AssemblyName.FullName);
498 LogConflictWarning (found_ref.AssemblyName.FullName, key_aname.FullName);
503 void LogWithPrecedingNewLine (MessageImportance importance, string format, params object [] args)
505 Log.LogMessage (importance, String.Empty);
506 Log.LogMessage (importance, format, args);
509 // conflict b/w @main and @conflicting, picking @main
510 void LogConflictWarning (string main, string conflicting)
512 string key = main + ":" + conflicting;
513 if (!conflictWarningsCache.ContainsKey (key)) {
514 Log.LogWarning ("Found a conflict between : '{0}' and '{1}'. Using '{0}' reference.",
516 conflictWarningsCache [key] = key;
520 bool IsFromGacOrTargetFramework (ResolvedReference rr)
522 return rr.FoundInSearchPath == SearchPath.Gac ||
523 rr.FoundInSearchPath == SearchPath.TargetFrameworkDirectory;
526 public bool AutoUnify {
527 get { return autoUnify; }
528 set { autoUnify = value; }
531 public ITaskItem[] AssemblyFiles {
532 get { return assemblyFiles; }
533 set { assemblyFiles = value; }
536 public ITaskItem[] Assemblies {
537 get { return assemblies; }
538 set { assemblies = value; }
541 public string AppConfigFile {
542 get { return appConfigFile; }
543 set { appConfigFile = value; }
546 public string[] AllowedAssemblyExtensions {
547 get { return allowedAssemblyExtensions; }
548 set { allowedAssemblyExtensions = value; }
551 public string[] AllowedRelatedFileExtensions {
552 get { return allowedRelatedFileExtensions; }
553 set { allowedRelatedFileExtensions = value; }
556 public string[] CandidateAssemblyFiles {
557 get { return candidateAssemblyFiles; }
558 set { candidateAssemblyFiles = value; }
562 public ITaskItem[] CopyLocalFiles {
563 get { return copyLocalFiles; }
567 public ITaskItem[] FilesWritten {
568 get { return filesWritten; }
569 set { filesWritten = value; }
572 public bool FindDependencies {
573 get { return findDependencies; }
574 set { findDependencies = value; }
577 public bool FindRelatedFiles {
578 get { return findRelatedFiles; }
579 set { findRelatedFiles = value; }
582 public bool FindSatellites {
583 get { return findSatellites; }
584 set { findSatellites = value; }
587 public bool FindSerializationAssemblies {
588 get { return findSerializationAssemblies; }
589 set { findSerializationAssemblies = value; }
592 public string[] InstalledAssemblyTables {
593 get { return installedAssemblyTables; }
594 set { installedAssemblyTables = value; }
598 public ITaskItem[] RelatedFiles {
599 get { return relatedFiles; }
603 public ITaskItem[] ResolvedDependencyFiles {
604 get { return resolvedDependencyFiles; }
608 public ITaskItem[] ResolvedFiles {
609 get { return resolvedFiles; }
613 public ITaskItem[] SatelliteFiles {
614 get { return satelliteFiles; }
618 public ITaskItem[] ScatterFiles {
619 get { return scatterFiles; }
623 public string[] SearchPaths {
624 get { return searchPaths; }
625 set { searchPaths = value; }
629 public ITaskItem[] SerializationAssemblyFiles {
630 get { return serializationAssemblyFiles; }
634 get { return silent; }
635 set { silent = value; }
638 public string StateFile {
639 get { return stateFile; }
640 set { stateFile = value; }
644 public ITaskItem[] SuggestedRedirects {
645 get { return suggestedRedirects; }
648 public string[] TargetFrameworkDirectories {
649 get { return targetFrameworkDirectories; }
650 set { targetFrameworkDirectories = value; }
653 public string TargetProcessorArchitecture {
654 get { return targetProcessorArchitecture; }
655 set { targetProcessorArchitecture = value; }
658 static Dictionary<string, string> cultureNamesTable;
659 static Dictionary<string, string> CultureNamesTable {
661 if (cultureNamesTable == null) {
662 cultureNamesTable = new Dictionary<string, string> ();
663 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures))
664 cultureNamesTable [ci.Name] = ci.Name;
667 return cultureNamesTable;
672 static class ResolveAssemblyReferenceHelper {
673 public static void AddUniqueFile (this Dictionary<string, ITaskItem> dic, ITaskItem item)
676 throw new ArgumentNullException ("dic");
678 throw new ArgumentNullException ("item");
680 string fullpath = Path.GetFullPath (item.ItemSpec);
681 if (!dic.ContainsKey (fullpath))
682 dic [fullpath] = item;
686 struct PrimaryReference {
687 public ITaskItem TaskItem;
688 public string ParentCopyLocal;
690 public PrimaryReference (ITaskItem item, string parent_copy_local)
693 ParentCopyLocal = parent_copy_local;