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 LogTaskParameters ();
104 assembly_resolver.Log = Log;
105 tempResolvedFiles = new List<ITaskItem> ();
106 tempCopyLocalFiles = new Dictionary<string, ITaskItem> ();
107 tempSatelliteFiles = new Dictionary<string, ITaskItem> ();
108 tempRelatedFiles = new Dictionary<string, ITaskItem> ();
109 tempResolvedDepFiles = new Dictionary<string, ITaskItem> ();
111 primaryReferences = new List<PrimaryReference> ();
112 assemblyNameToResolvedRef = new Dictionary<string, ResolvedReference> ();
113 conflictWarningsCache = new Dictionary<string, string> ();
115 ResolveAssemblies ();
116 ResolveAssemblyFiles ();
118 alreadyScannedAssemblyNames = new Dictionary<string, string> ();
120 // the first element is place holder for parent assembly's dir
121 dependency_search_paths = new List<string> () { String.Empty };
122 dependency_search_paths.AddRange (searchPaths);
124 // resolve dependencies
125 foreach (PrimaryReference pref in primaryReferences)
126 ResolveAssemblyFileDependencies (pref.TaskItem, pref.ParentCopyLocal);
128 resolvedFiles = tempResolvedFiles.ToArray ();
129 copyLocalFiles = tempCopyLocalFiles.Values.ToArray ();
130 satelliteFiles = tempSatelliteFiles.Values.ToArray ();
131 relatedFiles = tempRelatedFiles.Values.ToArray ();
132 resolvedDependencyFiles = tempResolvedDepFiles.Values.ToArray ();
134 tempResolvedFiles.Clear ();
135 tempCopyLocalFiles.Clear ();
136 tempSatelliteFiles.Clear ();
137 tempRelatedFiles.Clear ();
138 tempResolvedDepFiles.Clear ();
139 alreadyScannedAssemblyNames.Clear ();
140 primaryReferences.Clear ();
141 assemblyNameToResolvedRef.Clear ();
142 conflictWarningsCache.Clear ();
143 dependency_search_paths = null;
148 void ResolveAssemblies ()
150 if (assemblies == null || assemblies.Length == 0)
153 foreach (ITaskItem item in assemblies) {
154 if (!String.IsNullOrEmpty (item.GetMetadata ("SubType"))) {
155 Log.LogWarning ("Reference '{0}' has non-empty SubType. Ignoring.", item.ItemSpec);
159 LogWithPrecedingNewLine (MessageImportance.Low, "Primary Reference {0}", item.ItemSpec);
160 ResolvedReference resolved_ref = ResolveReference (item, searchPaths, true);
161 if (resolved_ref == null) {
162 Log.LogWarning ("Reference '{0}' not resolved", item.ItemSpec);
163 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
165 if (Environment.GetEnvironmentVariable ("XBUILD_LOG_REFERENCE_RESOLVER") != null)
166 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
168 Log.LogMessage (MessageImportance.Low,
169 "\tReference {0} resolved to {1}. CopyLocal = {2}",
170 item.ItemSpec, resolved_ref.TaskItem,
171 resolved_ref.TaskItem.GetMetadata ("CopyLocal"));
173 Log.LogMessage (MessageImportance.Low,
174 "\tReference found at search path {0}",
175 resolved_ref.FoundInSearchPathAsString);
177 if (TryAddNewReference (tempResolvedFiles, resolved_ref) &&
178 !IsFromGacOrTargetFramework (resolved_ref) &&
179 resolved_ref.FoundInSearchPath != SearchPath.PkgConfig) {
180 primaryReferences.Add (new PrimaryReference (
181 resolved_ref.TaskItem,
182 resolved_ref.TaskItem.GetMetadata ("CopyLocal")));
188 // Use @search_paths to resolve the reference
189 ResolvedReference ResolveReference (ITaskItem item, IEnumerable<string> search_paths, bool set_copy_local)
191 ResolvedReference resolved = null;
192 bool specific_version;
194 assembly_resolver.ResetSearchLogger ();
196 if (!TryGetSpecificVersionValue (item, out specific_version))
199 foreach (string spath in search_paths) {
200 assembly_resolver.LogSearchMessage ("For searchpath {0}", spath);
202 if (String.Compare (spath, "{HintPathFromItem}") == 0) {
203 resolved = assembly_resolver.ResolveHintPathReference (item, specific_version);
204 } else if (String.Compare (spath, "{TargetFrameworkDirectory}") == 0) {
205 if (targetFrameworkDirectories == null)
207 foreach (string fpath in targetFrameworkDirectories) {
208 resolved = assembly_resolver.FindInTargetFramework (item,
209 fpath, specific_version);
210 if (resolved != null)
213 } else if (String.Compare (spath, "{GAC}") == 0) {
214 resolved = assembly_resolver.ResolveGacReference (item, specific_version);
215 } else if (String.Compare (spath, "{RawFileName}") == 0) {
216 //FIXME: identify assembly names, as extract the name, and try with that?
218 if (assembly_resolver.TryGetAssemblyNameFromFile (item.ItemSpec, out aname))
219 resolved = assembly_resolver.GetResolvedReference (item, item.ItemSpec, aname, true,
220 SearchPath.RawFileName);
221 } else if (String.Compare (spath, "{CandidateAssemblyFiles}") == 0) {
222 assembly_resolver.LogSearchMessage (
223 "Warning: {{CandidateAssemblyFiles}} not supported currently");
224 } else if (String.Compare (spath, "{PkgConfig}") == 0) {
225 resolved = assembly_resolver.ResolvePkgConfigReference (item, specific_version);
227 resolved = assembly_resolver.FindInDirectory (
229 allowedAssemblyExtensions ?? default_assembly_extensions,
233 if (resolved != null)
237 if (resolved != null && set_copy_local)
238 SetCopyLocal (resolved.TaskItem, resolved.CopyLocal.ToString ());
243 bool TryGetSpecificVersionValue (ITaskItem item, out bool specific_version)
245 specific_version = true;
246 string value = item.GetMetadata ("SpecificVersion");
247 if (String.IsNullOrEmpty (value)) {
248 //AssemblyName name = new AssemblyName (item.ItemSpec);
249 // If SpecificVersion is not specified, then
250 // it is true if the Include is a strong name else false
251 //specific_version = assembly_resolver.IsStrongNamed (name);
253 // msbuild seems to just look for a ',' in the name :/
254 specific_version = item.ItemSpec.IndexOf (',') >= 0;
258 if (Boolean.TryParse (value, out specific_version))
261 Log.LogError ("Item '{0}' has attribute SpecificVersion with invalid value '{1}' " +
262 "which could not be converted to a boolean.", item.ItemSpec, value);
266 //FIXME: Consider CandidateAssemblyFiles also here
267 void ResolveAssemblyFiles ()
269 if (assemblyFiles == null)
272 foreach (ITaskItem item in assemblyFiles) {
273 assembly_resolver.ResetSearchLogger ();
275 if (!File.Exists (item.ItemSpec)) {
276 LogWithPrecedingNewLine (MessageImportance.Low,
277 "Primary Reference from AssemblyFiles {0}, file not found. Ignoring",
282 LogWithPrecedingNewLine (MessageImportance.Low, "Primary Reference from AssemblyFiles {0}", item.ItemSpec);
286 if (!assembly_resolver.TryGetAssemblyNameFromFile (item.ItemSpec, out aname)) {
287 Log.LogWarning ("Reference '{0}' not resolved", item.ItemSpec);
288 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
292 if (Environment.GetEnvironmentVariable ("XBUILD_LOG_REFERENCE_RESOLVER") != null)
293 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
295 ResolvedReference rr = assembly_resolver.GetResolvedReference (item, item.ItemSpec, aname, true,
296 SearchPath.RawFileName);
297 copy_local = rr.CopyLocal.ToString ();
299 if (!TryAddNewReference (tempResolvedFiles, rr))
303 SetCopyLocal (rr.TaskItem, copy_local);
305 FindAndAddRelatedFiles (item.ItemSpec, copy_local);
306 FindAndAddSatellites (item.ItemSpec, copy_local);
308 if (FindDependencies && !IsFromGacOrTargetFramework (rr) &&
309 rr.FoundInSearchPath != SearchPath.PkgConfig)
310 primaryReferences.Add (new PrimaryReference (item, copy_local));
314 // Tries to resolve assemblies referenced by @item
315 // Skips gac references
317 void ResolveAssemblyFileDependencies (ITaskItem item, string parent_copy_local)
319 Queue<string> dependencies = new Queue<string> ();
320 dependencies.Enqueue (item.ItemSpec);
322 while (dependencies.Count > 0) {
323 string filename = Path.GetFullPath (dependencies.Dequeue ());
324 Assembly asm = Assembly.ReflectionOnlyLoadFrom (filename);
325 if (alreadyScannedAssemblyNames.ContainsKey (asm.FullName))
328 // set the 1st search path to this ref's base path
329 // Will be used for resolving the dependencies
330 dependency_search_paths [0] = Path.GetDirectoryName (filename);
332 foreach (AssemblyName aname in asm.GetReferencedAssemblies ()) {
333 if (alreadyScannedAssemblyNames.ContainsKey (aname.FullName))
336 ResolvedReference resolved_ref = ResolveDependencyByAssemblyName (
337 aname, asm.FullName, parent_copy_local);
339 if (resolved_ref != null && !IsFromGacOrTargetFramework (resolved_ref)
340 && resolved_ref.FoundInSearchPath != SearchPath.PkgConfig)
341 dependencies.Enqueue (resolved_ref.TaskItem.ItemSpec);
343 alreadyScannedAssemblyNames.Add (asm.FullName, String.Empty);
347 // Resolves by looking dependency_search_paths
348 // which is dir of parent reference file, and
350 ResolvedReference ResolveDependencyByAssemblyName (AssemblyName aname, string parent_asm_name,
351 string parent_copy_local)
353 // This will check for compatible assembly name/version
354 ResolvedReference resolved_ref;
355 if (TryGetResolvedReferenceByAssemblyName (aname, false, out resolved_ref))
358 LogWithPrecedingNewLine (MessageImportance.Low, "Dependency {0}", aname);
359 Log.LogMessage (MessageImportance.Low, "\tRequired by {0}", parent_asm_name);
361 ITaskItem item = new TaskItem (aname.FullName);
362 item.SetMetadata ("SpecificVersion", "false");
363 resolved_ref = ResolveReference (item, dependency_search_paths, false);
365 if (resolved_ref != null) {
366 if (Environment.GetEnvironmentVariable ("XBUILD_LOG_REFERENCE_RESOLVER") != null)
367 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
369 Log.LogMessage (MessageImportance.Low, "\tReference {0} resolved to {1}.",
370 aname, resolved_ref.TaskItem.ItemSpec);
372 Log.LogMessage (MessageImportance.Low,
373 "\tReference found at search path {0}",
374 resolved_ref.FoundInSearchPathAsString);
376 if (resolved_ref.FoundInSearchPath == SearchPath.Directory) {
377 // override CopyLocal with parent's val
378 SetCopyLocal (resolved_ref.TaskItem, parent_copy_local);
380 Log.LogMessage (MessageImportance.Low,
381 "\tThis is CopyLocal {0} as parent item has this value",
384 if (TryAddNewReference (tempResolvedFiles, resolved_ref)) {
385 FindAndAddRelatedFiles (resolved_ref.TaskItem.ItemSpec, parent_copy_local);
386 FindAndAddSatellites (resolved_ref.TaskItem.ItemSpec, parent_copy_local);
390 Log.LogMessage (MessageImportance.Low,
391 "\tThis is CopyLocal false as it is in the gac," +
392 "target framework directory or provided by a package.");
394 TryAddNewReference (tempResolvedFiles, resolved_ref);
397 Log.LogWarning ("Reference '{0}' not resolved", aname);
398 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
404 void FindAndAddRelatedFiles (string filename, string parent_copy_local)
406 if (!findRelatedFiles || allowedRelatedFileExtensions == null)
409 foreach (string ext in allowedRelatedFileExtensions) {
410 string rfile = filename + ext;
411 if (File.Exists (rfile)) {
412 ITaskItem item = new TaskItem (rfile);
413 SetCopyLocal (item, parent_copy_local);
415 tempRelatedFiles.AddUniqueFile (item);
420 void FindAndAddSatellites (string filename, string parent_copy_local)
425 string basepath = Path.GetDirectoryName (filename);
426 string resource = String.Format ("{0}{1}{2}",
427 Path.GetFileNameWithoutExtension (filename),
429 Path.GetExtension (filename));
431 string dir_sep = Path.DirectorySeparatorChar.ToString ();
432 foreach (string dir in Directory.GetDirectories (basepath)) {
433 string culture = Path.GetFileName (dir);
434 if (!CultureNamesTable.ContainsKey (culture))
437 string res_path = Path.Combine (dir, resource);
438 if (File.Exists (res_path)) {
439 ITaskItem item = new TaskItem (res_path);
440 SetCopyLocal (item, parent_copy_local);
441 item.SetMetadata ("DestinationSubdirectory", culture + dir_sep);
442 tempSatelliteFiles.AddUniqueFile (item);
447 // returns true is it was new
448 bool TryAddNewReference (List<ITaskItem> file_list, ResolvedReference key_ref)
450 ResolvedReference found_ref;
451 if (!TryGetResolvedReferenceByAssemblyName (key_ref.AssemblyName, key_ref.IsPrimary, out found_ref)) {
452 assemblyNameToResolvedRef [key_ref.AssemblyName.Name] = key_ref;
453 file_list.Add (key_ref.TaskItem);
460 void SetCopyLocal (ITaskItem item, string copy_local)
462 item.SetMetadata ("CopyLocal", copy_local);
464 // Assumed to be valid value
465 if (Boolean.Parse (copy_local))
466 tempCopyLocalFiles.AddUniqueFile (item);
469 bool TryGetResolvedReferenceByAssemblyName (AssemblyName key_aname, bool is_primary, out ResolvedReference found_ref)
472 // Match by just name
473 if (!assemblyNameToResolvedRef.TryGetValue (key_aname.Name, out found_ref))
477 // match for full name
478 if (AssemblyResolver.AssemblyNamesCompatible (key_aname, found_ref.AssemblyName, true, false))
479 // exact match, so its already there, dont add anything
482 // we have a name match, but version mismatch!
483 assembly_resolver.LogSearchMessage ("A conflict was detected between '{0}' and '{1}'",
484 key_aname.FullName, found_ref.AssemblyName.FullName);
486 if (is_primary == found_ref.IsPrimary) {
487 assembly_resolver.LogSearchMessage ("Unable to choose between the two. " +
488 "Choosing '{0}' arbitrarily.", found_ref.AssemblyName.FullName);
492 // since all dependencies are processed after
493 // all primary refererences, the one in the cache
494 // has to be a primary
495 // Prefer a primary reference over a dependency
497 assembly_resolver.LogSearchMessage ("Choosing '{0}' as it is a primary reference.",
498 found_ref.AssemblyName.FullName);
500 LogConflictWarning (found_ref.AssemblyName.FullName, key_aname.FullName);
505 void LogWithPrecedingNewLine (MessageImportance importance, string format, params object [] args)
507 Log.LogMessage (importance, String.Empty);
508 Log.LogMessage (importance, format, args);
511 // conflict b/w @main and @conflicting, picking @main
512 void LogConflictWarning (string main, string conflicting)
514 string key = main + ":" + conflicting;
515 if (!conflictWarningsCache.ContainsKey (key)) {
516 Log.LogWarning ("Found a conflict between : '{0}' and '{1}'. Using '{0}' reference.",
518 conflictWarningsCache [key] = key;
522 bool IsFromGacOrTargetFramework (ResolvedReference rr)
524 return rr.FoundInSearchPath == SearchPath.Gac ||
525 rr.FoundInSearchPath == SearchPath.TargetFrameworkDirectory;
528 void LogTaskParameters ()
530 Log.LogMessage (MessageImportance.Low, "TargetFrameworkDirectories:");
531 if (TargetFrameworkDirectories != null)
532 foreach (string dir in TargetFrameworkDirectories)
533 Log.LogMessage (MessageImportance.Low, "\t{0}", dir);
535 Log.LogMessage (MessageImportance.Low, "SearchPaths:");
536 if (SearchPaths != null)
537 foreach (string path in SearchPaths)
538 Log.LogMessage (MessageImportance.Low, "\t{0}", path);
541 public bool AutoUnify {
542 get { return autoUnify; }
543 set { autoUnify = value; }
546 public ITaskItem[] AssemblyFiles {
547 get { return assemblyFiles; }
548 set { assemblyFiles = value; }
551 public ITaskItem[] Assemblies {
552 get { return assemblies; }
553 set { assemblies = value; }
556 public string AppConfigFile {
557 get { return appConfigFile; }
558 set { appConfigFile = value; }
561 public string[] AllowedAssemblyExtensions {
562 get { return allowedAssemblyExtensions; }
563 set { allowedAssemblyExtensions = value; }
566 public string[] AllowedRelatedFileExtensions {
567 get { return allowedRelatedFileExtensions; }
568 set { allowedRelatedFileExtensions = value; }
571 public string[] CandidateAssemblyFiles {
572 get { return candidateAssemblyFiles; }
573 set { candidateAssemblyFiles = value; }
577 public ITaskItem[] CopyLocalFiles {
578 get { return copyLocalFiles; }
582 public ITaskItem[] FilesWritten {
583 get { return filesWritten; }
584 set { filesWritten = value; }
587 public bool FindDependencies {
588 get { return findDependencies; }
589 set { findDependencies = value; }
592 public bool FindRelatedFiles {
593 get { return findRelatedFiles; }
594 set { findRelatedFiles = value; }
597 public bool FindSatellites {
598 get { return findSatellites; }
599 set { findSatellites = value; }
602 public bool FindSerializationAssemblies {
603 get { return findSerializationAssemblies; }
604 set { findSerializationAssemblies = value; }
607 public string[] InstalledAssemblyTables {
608 get { return installedAssemblyTables; }
609 set { installedAssemblyTables = value; }
613 public ITaskItem[] RelatedFiles {
614 get { return relatedFiles; }
618 public ITaskItem[] ResolvedDependencyFiles {
619 get { return resolvedDependencyFiles; }
623 public ITaskItem[] ResolvedFiles {
624 get { return resolvedFiles; }
628 public ITaskItem[] SatelliteFiles {
629 get { return satelliteFiles; }
633 public ITaskItem[] ScatterFiles {
634 get { return scatterFiles; }
638 public string[] SearchPaths {
639 get { return searchPaths; }
640 set { searchPaths = value; }
644 public ITaskItem[] SerializationAssemblyFiles {
645 get { return serializationAssemblyFiles; }
649 get { return silent; }
650 set { silent = value; }
653 public string StateFile {
654 get { return stateFile; }
655 set { stateFile = value; }
659 public ITaskItem[] SuggestedRedirects {
660 get { return suggestedRedirects; }
664 public string TargetFrameworkMoniker { get; set; }
666 public string TargetFrameworkMonikerDisplayName { get; set; }
669 public string TargetFrameworkVersion { get; set; }
671 public string[] TargetFrameworkDirectories {
672 get { return targetFrameworkDirectories; }
673 set { targetFrameworkDirectories = value; }
676 public string TargetProcessorArchitecture {
677 get { return targetProcessorArchitecture; }
678 set { targetProcessorArchitecture = value; }
682 static Dictionary<string, string> cultureNamesTable;
683 static Dictionary<string, string> CultureNamesTable {
685 if (cultureNamesTable == null) {
686 cultureNamesTable = new Dictionary<string, string> ();
687 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures))
688 cultureNamesTable [ci.Name] = ci.Name;
691 return cultureNamesTable;
696 static class ResolveAssemblyReferenceHelper {
697 public static void AddUniqueFile (this Dictionary<string, ITaskItem> dic, ITaskItem item)
700 throw new ArgumentNullException ("dic");
702 throw new ArgumentNullException ("item");
704 string fullpath = Path.GetFullPath (item.ItemSpec);
705 if (!dic.ContainsKey (fullpath))
706 dic [fullpath] = item;
710 struct PrimaryReference {
711 public ITaskItem TaskItem;
712 public string ParentCopyLocal;
714 public PrimaryReference (ITaskItem item, string parent_copy_local)
717 ParentCopyLocal = parent_copy_local;