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.
31 using System.Collections.Generic;
32 using System.Globalization;
35 using System.Reflection;
36 using System.Security;
37 using Microsoft.Build.Framework;
38 using Microsoft.Build.Utilities;
40 namespace Microsoft.Build.Tasks {
41 public class ResolveAssemblyReference : TaskExtension {
44 ITaskItem[] assemblyFiles;
45 ITaskItem[] assemblies;
47 string[] allowedAssemblyExtensions;
48 string[] allowedRelatedFileExtensions;
49 string[] candidateAssemblyFiles;
50 ITaskItem[] copyLocalFiles;
51 ITaskItem[] filesWritten;
52 bool findDependencies;
53 bool findRelatedFiles;
55 bool findSerializationAssemblies;
56 string[] installedAssemblyTables;
57 ITaskItem[] relatedFiles;
58 ITaskItem[] resolvedDependencyFiles;
59 ITaskItem[] resolvedFiles;
60 ITaskItem[] satelliteFiles;
61 ITaskItem[] scatterFiles;
63 ITaskItem[] serializationAssemblyFiles;
66 ITaskItem[] suggestedRedirects;
67 string[] targetFrameworkDirectories;
68 string targetProcessorArchitecture;
69 static string [] default_assembly_extensions;
71 AssemblyResolver assembly_resolver;
72 List<string> dependency_search_paths;
73 Dictionary<string, ResolvedReference> assemblyNameToResolvedRef;
74 Dictionary<string, ITaskItem> tempSatelliteFiles, tempRelatedFiles,
75 tempResolvedDepFiles, tempCopyLocalFiles;
76 List<ITaskItem> tempResolvedFiles;
77 List<PrimaryReference> primaryReferences;
78 Dictionary<string, string> alreadyScannedAssemblyNames;
79 Dictionary<string, string> conflictWarningsCache;
81 //FIXME: construct and use a graph of the dependencies, useful across projects
83 static ResolveAssemblyReference ()
85 default_assembly_extensions = new string [] { ".dll", ".exe" };
88 public ResolveAssemblyReference ()
90 assembly_resolver = new AssemblyResolver ();
93 //FIXME: make this reusable
94 public override bool Execute ()
96 if (assemblies == null && assemblyFiles == null)
100 LogTaskParameters ();
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 ();
115 resolvedFiles = tempResolvedFiles.ToArray ();
117 alreadyScannedAssemblyNames = new Dictionary<string, string> ();
119 // the first element is place holder for parent assembly's dir
120 dependency_search_paths = new List<string> () { String.Empty };
121 dependency_search_paths.AddRange (searchPaths);
123 // resolve dependencies
124 foreach (PrimaryReference pref in primaryReferences)
125 ResolveAssemblyFileDependencies (pref.TaskItem, pref.ParentCopyLocal);
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 Log.LogMessage (MessageImportance.Low,
164 "\tReference {0} resolved to {1}. CopyLocal = {2}",
165 item.ItemSpec, resolved_ref.TaskItem,
166 resolved_ref.TaskItem.GetMetadata ("CopyLocal"));
168 Log.LogMessage (MessageImportance.Low,
169 "\tReference found at search path {0}",
170 resolved_ref.FoundInSearchPathAsString);
172 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
174 if (TryAddNewReference (tempResolvedFiles, resolved_ref) &&
175 !IsFromGacOrTargetFramework (resolved_ref) &&
176 resolved_ref.FoundInSearchPath != SearchPath.PkgConfig) {
177 primaryReferences.Add (new PrimaryReference (
178 resolved_ref.TaskItem,
179 resolved_ref.TaskItem.GetMetadata ("CopyLocal")));
185 // Use @search_paths to resolve the reference
186 ResolvedReference ResolveReference (ITaskItem item, IEnumerable<string> search_paths, bool set_copy_local)
188 ResolvedReference resolved = null;
189 bool specific_version;
191 assembly_resolver.ResetSearchLogger ();
193 if (!TryGetSpecificVersionValue (item, out specific_version))
196 foreach (string spath in search_paths) {
197 assembly_resolver.LogSearchMessage ("For searchpath {0}", spath);
199 if (String.Compare (spath, "{HintPathFromItem}") == 0) {
200 resolved = assembly_resolver.ResolveHintPathReference (item, specific_version);
201 } else if (String.Compare (spath, "{TargetFrameworkDirectory}") == 0) {
202 if (targetFrameworkDirectories == null)
204 foreach (string fpath in targetFrameworkDirectories) {
205 resolved = assembly_resolver.FindInTargetFramework (item,
206 fpath, specific_version);
207 if (resolved != null)
210 } else if (String.Compare (spath, "{GAC}") == 0) {
211 resolved = assembly_resolver.ResolveGacReference (item, specific_version);
212 } else if (String.Compare (spath, "{RawFileName}") == 0) {
213 //FIXME: identify assembly names, as extract the name, and try with that?
215 if (assembly_resolver.TryGetAssemblyNameFromFile (item.ItemSpec, out aname))
216 resolved = assembly_resolver.GetResolvedReference (item, item.ItemSpec, aname, true,
217 SearchPath.RawFileName);
218 } else if (String.Compare (spath, "{CandidateAssemblyFiles}") == 0) {
219 assembly_resolver.LogSearchMessage (
220 "Warning: {{CandidateAssemblyFiles}} not supported currently");
221 } else if (String.Compare (spath, "{PkgConfig}") == 0) {
222 resolved = assembly_resolver.ResolvePkgConfigReference (item, specific_version);
224 resolved = assembly_resolver.FindInDirectory (
226 allowedAssemblyExtensions ?? default_assembly_extensions,
230 if (resolved != null)
234 if (resolved != null && set_copy_local)
235 SetCopyLocal (resolved.TaskItem, resolved.CopyLocal.ToString ());
240 bool TryGetSpecificVersionValue (ITaskItem item, out bool specific_version)
242 specific_version = true;
243 string value = item.GetMetadata ("SpecificVersion");
244 if (String.IsNullOrEmpty (value)) {
245 //AssemblyName name = new AssemblyName (item.ItemSpec);
246 // If SpecificVersion is not specified, then
247 // it is true if the Include is a strong name else false
248 //specific_version = assembly_resolver.IsStrongNamed (name);
250 // msbuild seems to just look for a ',' in the name :/
251 specific_version = item.ItemSpec.IndexOf (',') >= 0;
255 if (Boolean.TryParse (value, out specific_version))
258 Log.LogError ("Item '{0}' has attribute SpecificVersion with invalid value '{1}' " +
259 "which could not be converted to a boolean.", item.ItemSpec, value);
263 //FIXME: Consider CandidateAssemblyFiles also here
264 void ResolveAssemblyFiles ()
266 if (assemblyFiles == null)
269 foreach (ITaskItem item in assemblyFiles) {
270 assembly_resolver.ResetSearchLogger ();
272 if (!File.Exists (item.ItemSpec)) {
273 LogWithPrecedingNewLine (MessageImportance.Low,
274 "Primary Reference from AssemblyFiles {0}, file not found. Ignoring",
279 LogWithPrecedingNewLine (MessageImportance.Low, "Primary Reference from AssemblyFiles {0}", item.ItemSpec);
283 if (!assembly_resolver.TryGetAssemblyNameFromFile (item.ItemSpec, out aname)) {
284 Log.LogWarning ("Reference '{0}' not resolved", item.ItemSpec);
285 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Normal);
289 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
291 ResolvedReference rr = assembly_resolver.GetResolvedReference (item, item.ItemSpec, aname, true,
292 SearchPath.RawFileName);
293 copy_local = rr.CopyLocal.ToString ();
295 if (!TryAddNewReference (tempResolvedFiles, rr))
299 SetCopyLocal (rr.TaskItem, copy_local);
301 FindAndAddRelatedFiles (item.ItemSpec, copy_local);
302 FindAndAddSatellites (item.ItemSpec, copy_local);
304 if (FindDependencies && !IsFromGacOrTargetFramework (rr) &&
305 rr.FoundInSearchPath != SearchPath.PkgConfig)
306 primaryReferences.Add (new PrimaryReference (item, copy_local));
310 // Tries to resolve assemblies referenced by @item
311 // Skips gac references
313 void ResolveAssemblyFileDependencies (ITaskItem item, string parent_copy_local)
315 Queue<string> dependencies = new Queue<string> ();
316 dependencies.Enqueue (item.ItemSpec);
318 while (dependencies.Count > 0) {
319 string filename = Path.GetFullPath (dependencies.Dequeue ());
320 Assembly asm = Assembly.ReflectionOnlyLoadFrom (filename);
321 if (alreadyScannedAssemblyNames.ContainsKey (asm.FullName))
324 // set the 1st search path to this ref's base path
325 // Will be used for resolving the dependencies
326 dependency_search_paths [0] = Path.GetDirectoryName (filename);
328 foreach (AssemblyName aname in asm.GetReferencedAssemblies ()) {
329 if (alreadyScannedAssemblyNames.ContainsKey (aname.FullName))
332 ResolvedReference resolved_ref = ResolveDependencyByAssemblyName (
333 aname, asm.FullName, parent_copy_local);
335 if (IncludeDependencies (resolved_ref, aname.FullName)) {
336 tempResolvedDepFiles[resolved_ref.AssemblyName.FullName] = resolved_ref.TaskItem;
337 dependencies.Enqueue (resolved_ref.TaskItem.ItemSpec);
340 alreadyScannedAssemblyNames.Add (asm.FullName, String.Empty);
344 // Resolves by looking dependency_search_paths
345 // which is dir of parent reference file, and
347 ResolvedReference ResolveDependencyByAssemblyName (AssemblyName aname, string parent_asm_name,
348 string parent_copy_local)
350 // This will check for compatible assembly name/version
351 ResolvedReference resolved_ref;
352 if (TryGetResolvedReferenceByAssemblyName (aname, false, out resolved_ref))
355 LogWithPrecedingNewLine (MessageImportance.Low, "Dependency {0}", aname);
356 Log.LogMessage (MessageImportance.Low, "\tRequired by {0}", parent_asm_name);
358 ITaskItem item = new TaskItem (aname.FullName);
359 item.SetMetadata ("SpecificVersion", "false");
360 resolved_ref = ResolveReference (item, dependency_search_paths, false);
362 if (resolved_ref != null) {
363 Log.LogMessage (MessageImportance.Low, "\tReference {0} resolved to {1}.",
364 aname, resolved_ref.TaskItem.ItemSpec);
366 Log.LogMessage (MessageImportance.Low,
367 "\tReference found at search path {0}",
368 resolved_ref.FoundInSearchPathAsString);
370 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
372 if (resolved_ref.FoundInSearchPath == SearchPath.Directory) {
373 // override CopyLocal with parent's val
374 SetCopyLocal (resolved_ref.TaskItem, parent_copy_local);
376 Log.LogMessage (MessageImportance.Low,
377 "\tThis is CopyLocal {0} as parent item has this value",
380 if (TryAddNewReference (tempResolvedFiles, resolved_ref)) {
381 FindAndAddRelatedFiles (resolved_ref.TaskItem.ItemSpec, parent_copy_local);
382 FindAndAddSatellites (resolved_ref.TaskItem.ItemSpec, parent_copy_local);
386 Log.LogMessage (MessageImportance.Low,
387 "\tThis is CopyLocal false as it is in the GAC," +
388 "target framework directory or provided by a package.");
390 TryAddNewReference (tempResolvedFiles, resolved_ref);
393 Log.LogMessage (MessageImportance.Low, "Could not resolve the assembly \"{0}\".", aname);
394 assembly_resolver.LogSearchLoggerMessages (MessageImportance.Low);
400 void FindAndAddRelatedFiles (string filename, string parent_copy_local)
402 if (!findRelatedFiles || allowedRelatedFileExtensions == null)
405 foreach (string ext in allowedRelatedFileExtensions) {
406 string rfile = Path.ChangeExtension (filename, ext);
407 if (File.Exists (rfile)) {
408 ITaskItem item = new TaskItem (rfile);
409 SetCopyLocal (item, parent_copy_local);
411 tempRelatedFiles.AddUniqueFile (item);
416 void FindAndAddSatellites (string filename, string parent_copy_local)
421 string basepath = Path.GetDirectoryName (filename);
422 string resource = String.Format ("{0}{1}{2}",
423 Path.GetFileNameWithoutExtension (filename),
425 Path.GetExtension (filename));
427 string dir_sep = Path.DirectorySeparatorChar.ToString ();
428 foreach (string dir in Directory.GetDirectories (basepath)) {
429 string culture = Path.GetFileName (dir);
430 if (!CultureNamesTable.ContainsKey (culture))
433 string res_path = Path.Combine (dir, resource);
434 if (File.Exists (res_path)) {
435 ITaskItem item = new TaskItem (res_path);
436 SetCopyLocal (item, parent_copy_local);
437 item.SetMetadata ("DestinationSubdirectory", culture + dir_sep);
438 tempSatelliteFiles.AddUniqueFile (item);
443 // returns true is it was new
444 bool TryAddNewReference (List<ITaskItem> file_list, ResolvedReference key_ref)
446 ResolvedReference found_ref;
447 if (!TryGetResolvedReferenceByAssemblyName (key_ref.AssemblyName, key_ref.IsPrimary, out found_ref)) {
448 assemblyNameToResolvedRef [key_ref.AssemblyName.Name] = key_ref;
449 file_list.Add (key_ref.TaskItem);
456 void SetCopyLocal (ITaskItem item, string copy_local)
458 item.SetMetadata ("CopyLocal", copy_local);
460 // Assumed to be valid value
461 if (Boolean.Parse (copy_local))
462 tempCopyLocalFiles.AddUniqueFile (item);
465 bool TryGetResolvedReferenceByAssemblyName (AssemblyName key_aname, bool is_primary, out ResolvedReference found_ref)
468 // Match by just name
469 if (!assemblyNameToResolvedRef.TryGetValue (key_aname.Name, out found_ref))
473 // match for full name
474 if (AssemblyResolver.AssemblyNamesCompatible (key_aname, found_ref.AssemblyName, true, false))
475 // exact match, so its already there, dont add anything
478 // we have a name match, but version mismatch!
479 assembly_resolver.LogSearchMessage ("A conflict was detected between '{0}' and '{1}'",
480 key_aname.FullName, found_ref.AssemblyName.FullName);
482 if (is_primary == found_ref.IsPrimary) {
483 assembly_resolver.LogSearchMessage ("Unable to choose between the two. " +
484 "Choosing '{0}' arbitrarily.", found_ref.AssemblyName.FullName);
488 // since all dependencies are processed after
489 // all primary refererences, the one in the cache
490 // has to be a primary
491 // Prefer a primary reference over a dependency
493 assembly_resolver.LogSearchMessage ("Choosing '{0}' as it is a primary reference.",
494 found_ref.AssemblyName.FullName);
496 // If we can successfully use the primary reference, don't log a warning. It's too
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 bool IncludeDependencies (ResolvedReference rr, string aname)
530 if (aname.Equals ("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"))
532 return !IsFromGacOrTargetFramework (rr) && rr.FoundInSearchPath != SearchPath.PkgConfig;
535 void LogTaskParameters ()
537 Log.LogMessage (MessageImportance.Low, "TargetFrameworkDirectories:");
538 if (TargetFrameworkDirectories != null)
539 foreach (string dir in TargetFrameworkDirectories)
540 Log.LogMessage (MessageImportance.Low, "\t{0}", dir);
542 Log.LogMessage (MessageImportance.Low, "SearchPaths:");
543 if (SearchPaths != null)
544 foreach (string path in SearchPaths)
545 Log.LogMessage (MessageImportance.Low, "\t{0}", path);
548 public bool AutoUnify {
549 get { return autoUnify; }
550 set { autoUnify = value; }
553 public ITaskItem[] AssemblyFiles {
554 get { return assemblyFiles; }
555 set { assemblyFiles = value; }
558 public ITaskItem[] Assemblies {
559 get { return assemblies; }
560 set { assemblies = value; }
563 public string AppConfigFile {
564 get { return appConfigFile; }
565 set { appConfigFile = value; }
568 public string[] AllowedAssemblyExtensions {
569 get { return allowedAssemblyExtensions; }
570 set { allowedAssemblyExtensions = value; }
573 public string[] AllowedRelatedFileExtensions {
574 get { return allowedRelatedFileExtensions; }
575 set { allowedRelatedFileExtensions = value; }
578 public string[] CandidateAssemblyFiles {
579 get { return candidateAssemblyFiles; }
580 set { candidateAssemblyFiles = value; }
584 public ITaskItem[] CopyLocalFiles {
585 get { return copyLocalFiles; }
589 public ITaskItem[] FilesWritten {
590 get { return filesWritten; }
591 set { filesWritten = value; }
594 public bool FindDependencies {
595 get { return findDependencies; }
596 set { findDependencies = value; }
599 public bool FindRelatedFiles {
600 get { return findRelatedFiles; }
601 set { findRelatedFiles = value; }
604 public bool FindSatellites {
605 get { return findSatellites; }
606 set { findSatellites = value; }
609 public bool FindSerializationAssemblies {
610 get { return findSerializationAssemblies; }
611 set { findSerializationAssemblies = value; }
614 public string[] InstalledAssemblyTables {
615 get { return installedAssemblyTables; }
616 set { installedAssemblyTables = value; }
620 public ITaskItem[] RelatedFiles {
621 get { return relatedFiles; }
625 public ITaskItem[] ResolvedDependencyFiles {
626 get { return resolvedDependencyFiles; }
630 public ITaskItem[] ResolvedFiles {
631 get { return resolvedFiles; }
635 public ITaskItem[] SatelliteFiles {
636 get { return satelliteFiles; }
640 public ITaskItem[] ScatterFiles {
641 get { return scatterFiles; }
645 public string[] SearchPaths {
646 get { return searchPaths; }
647 set { searchPaths = value; }
651 public ITaskItem[] SerializationAssemblyFiles {
652 get { return serializationAssemblyFiles; }
656 get { return silent; }
657 set { silent = value; }
660 public string StateFile {
661 get { return stateFile; }
662 set { stateFile = value; }
666 public ITaskItem[] SuggestedRedirects {
667 get { return suggestedRedirects; }
671 public string TargetFrameworkMoniker { get; set; }
673 public string TargetFrameworkMonikerDisplayName { get; set; }
676 public string TargetFrameworkVersion { get; set; }
678 public string[] TargetFrameworkDirectories {
679 get { return targetFrameworkDirectories; }
680 set { targetFrameworkDirectories = value; }
683 public string TargetProcessorArchitecture {
684 get { return targetProcessorArchitecture; }
685 set { targetProcessorArchitecture = value; }
689 static Dictionary<string, string> cultureNamesTable;
690 static Dictionary<string, string> CultureNamesTable {
692 if (cultureNamesTable == null) {
693 cultureNamesTable = new Dictionary<string, string> ();
694 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures))
695 cultureNamesTable [ci.Name] = ci.Name;
698 return cultureNamesTable;
703 static class ResolveAssemblyReferenceHelper {
704 public static void AddUniqueFile (this Dictionary<string, ITaskItem> dic, ITaskItem item)
707 throw new ArgumentNullException ("dic");
709 throw new ArgumentNullException ("item");
711 string fullpath = Path.GetFullPath (item.ItemSpec);
712 if (!dic.ContainsKey (fullpath))
713 dic [fullpath] = item;
717 struct PrimaryReference {
718 public ITaskItem TaskItem;
719 public string ParentCopyLocal;
721 public PrimaryReference (ITaskItem item, string parent_copy_local)
724 ParentCopyLocal = parent_copy_local;