Exemple #1
0
        private static AssemblyNode GetRuntimeAssembly()
        {
            AssemblyNode result = RuntimeAssemblyLocation.ParsedAssembly;

            if (result != null)
            {
                return(result);
            }
            if (RuntimeAssemblyLocation.Location == null)
            {
                //This happens when there was no call to SetToXXX. Use the location of the assembly linked into the compiler.
                RuntimeAssemblyLocation.Location = typeof(dummy).Module.Assembly.Location;
                result = AssemblyNode.GetAssembly((RuntimeAssemblyLocation.Location));
            }
            else
            {
                result = AssemblyNode.GetAssembly(RuntimeAssemblyLocation.Location);
                if (result == null)
                {
                    //This happens when the location was set by a call to SetToXXX, but the runtime assembly is not actually deployed
                    //in the directory containing the target platform assemblies. This is really an error, but as a convenience during
                    //development of the compiler, the assembly linked into the compiler is used instead.
                    RuntimeAssemblyLocation.Location = typeof(dummy).Module.Assembly.Location;
                    result = AssemblyNode.GetAssembly((RuntimeAssemblyLocation.Location));
                }
            }
            if (result == null)
            {
                result         = new AssemblyNode();
                result.Name    = "Microsoft.SpecSharp.Runtime";
                result.Version = Cci.TargetPlatform.TargetVersion;
            }
            Cci.TargetPlatform.AssemblyReferenceFor[Identifier.For(result.Name).UniqueIdKey] = new AssemblyReference(result);
            return(result);
        }
Exemple #2
0
        public static void init( )
        {
            // if ( allNamespaces != null ) return;
            allNamespaces = new NamespaceList();

            nsCached = new Dictionary <string, TypeNodeList>();

            // Scan all assemblies referenced in parameters
            // and take all namespaces from them.
            // Put all these namespaces into the common list.
            System.Collections.Specialized.StringCollection assemblies = CONTEXT.options.ReferencedAssemblies;
            foreach (string assName in assemblies)
            {
                AssemblyNode assembly = AssemblyNode.GetAssembly(assName, true, false, true);
                if (assembly == null && !CONTEXT.AnalysisOnly)
                {
                    ERROR.UnresolvedReference(assName);
                    continue;
                }
                NamespaceList nss = assembly.GetNamespaceList();
                for (int i = 0, n = nss.Length; i < n; i++)
                {
                    allNamespaces.Add(nss[i]);
                }
            }
        }
Exemple #3
0
        // Parsing logic

        public void LoadAssembly(string filePath)
        {
            //Console.WriteLine("loading {0}", filePath);
            //AssemblyNode assembly = AssemblyNode.GetAssembly(filePath);   // this causes mscorlib to be missing members
            //AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, cache); // this causes compact framework non-classes to register as classes
            //AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, cache, false, false, true, false); // this causes missing mscorlib members
            //AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, cache, false, false, false, false); // this causes non-classes to register as classes
            //AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, true, false); // this causes missing mscorlib members
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, false, false); // this causes non-classes to register as classes

            if (assembly != null)
            {
                if (assembly.Name == "mscorlib")
                {
                    ResetMscorlib(assembly);
                }

                // Console.WriteLine("assembly = {0}", assembly.Name);
                resolver.Add(assembly);
                //assembly.AssemblyReferenceResolutionAfterProbingFailed += unresolvedModuleHandler;
                assemblies.Add(assembly);
                //Console.WriteLine("{0} has {1} types", assembly.Name, assembly.ExportedTypes.Count);
                //StoreTypes(assembly.Types);
            }
        }
Exemple #4
0
        /// <summary>
        /// This is used to load an assembly that will be parsed and documented
        /// </summary>
        /// <param name="filePath">The path of the documented assembly to load</param>
        public void LoadAssembly(string filePath)
        {
            // This causes non-classes to register as classes
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false,
                                                             (this.SourceCodeBasePath != null), false, false);

            if (assembly != null)
            {
                // If generating reflection data for a framework, reset the core library if seen
                if (assembly.Name == CoreSystemTypes.SystemAssembly.Name)
                {
                    ResetMscorlib(assembly);
                }

                resolver.Add(assembly);
                assemblies.Add(assembly);

                if (this.SourceCodeBasePath != null)
                {
                    if (!assembly.reader.PdbExists)
                    {
                        this.MessageLogger(LogLevel.Warn, "The program database (PDB) file associated with " +
                                           $"'{filePath}' does not exist or could not be loaded.  Source context information " +
                                           "is unavailable.");
                    }
                    else
                    {
                        this.MessageLogger(LogLevel.Info, $"Found a current program database (PDB) file for '{filePath}'.");
                    }
                }
            }
        }
 public static AssemblyNode GetAssembly()
 {
     if (_assemblyNode == null)
     {
         _assemblyNode = AssemblyNode.GetAssembly(Assembly.GetExecutingAssembly().Location, true, true, true);
     }
     return(_assemblyNode);
 }
Exemple #6
0
        public static TypeNode TypeNodeFactory <T> ()
        {
            Type         targetType      = typeof(T);
            string       targetLocation  = targetType.Assembly.Location;
            AssemblyNode targetAssembly  = AssemblyNode.GetAssembly(targetLocation);
            Identifier   targetNamespace = Identifier.For(targetType.Namespace);
            Identifier   targetName      = Identifier.For(targetType.Name);

            return(targetAssembly.GetType(targetNamespace, targetName));
        }
Exemple #7
0
        public static TypeNode TypeNodeFactory(Type targetType)
        {
            ArgumentUtility.CheckNotNull("targetType", targetType);
            string       targetLocation  = targetType.Assembly.Location;
            AssemblyNode targetAssembly  = AssemblyNode.GetAssembly(targetLocation);
            Identifier   targetNamespace = Identifier.For(targetType.Namespace);
            Identifier   targetName      = Identifier.For(targetType.Name);

            return(targetAssembly.GetType(targetNamespace, targetName));
        }
        private AssemblyNode ProbeForAssemblyWithExtensionAtomic(string directory, string assemblyName, string[] exts)
        {
            foreach (string ext in exts)
            {
                bool   tempDebugInfo = this.usePDB;
                string fullName      = Path.Combine(directory, assemblyName + ext);

                if (this.trace)
                {
                    LoadTracing(String.Format("Attempting load from {0}", fullName));
                }

                if (File.Exists(fullName))
                {
                    if (tempDebugInfo)
                    {
                        // Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
                        string pdbFullName;
                        if (String.IsNullOrEmpty(ext))
                        {
                            pdbFullName = Path.Combine(directory, Path.GetFileNameWithoutExtension(assemblyName) + ".pdb");
                        }
                        else
                        {
                            pdbFullName = Path.Combine(directory, assemblyName + ".pdb");
                        }

                        if (!File.Exists(pdbFullName))
                        {
                            tempDebugInfo = false;
                        }
                    }

                    if (this.trace)
                    {
                        LoadTracing(string.Format("Resolved assembly reference '{0}' to '{1}'. (Using directory {2})",
                                                  assemblyName, fullName, directory));
                    }

                    var result = AssemblyNode.GetAssembly(
                        fullName,                           // path to assembly
                        TargetPlatform.StaticAssemblyCache, // global cache to use for assemblies
                        true,                               // doNotLockFile
                        tempDebugInfo,                      // getDebugInfo
                        true,                               // useGlobalCache
                        this.preserveShortBranches,         // preserveShortBranches
                        this.PostLoadHook
                        );

                    return(result);
                }
            }

            return(null);
        }
Exemple #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="reference"></param>
        /// <param name="module"></param>
        /// <returns></returns>
        public override AssemblyNode ResolveReference(
            AssemblyReference reference, Module module)
        {
            AssemblyNode assembly = base.ResolveReference(reference, module);

            if (assembly == null)
            {
                string strongName = reference.StrongName;

                if (_redirects != null && _redirects.Count != 0 &&
                    _redirects.ContainsKey(strongName))
                {
                    assembly = _redirects[strongName];

                    ConsoleApplication.WriteMessage(LogLevel.Info,
                                                    "Redirecting, '{0}' version, from '{1}' to '{2}'",
                                                    reference.Name, reference.Version, assembly.Version);
                }
                else if (_sourcePaths != null && _sourcePaths.Count != 0)
                {
                    string assemblyName     = reference.Name + ".dll";
                    string assemblyLocation = null;
                    foreach (string sourcePath in _sourcePaths)
                    {
                        string tempLocation = Path.Combine(sourcePath, assemblyName);
                        if (File.Exists(tempLocation))
                        {
                            assemblyLocation = tempLocation;
                            break;
                        }
                    }

                    if (assemblyLocation != null)
                    {
                        assembly = AssemblyNode.GetAssembly(assemblyLocation,
                                                            null, false, false, false, false);
                        if (assembly != null)
                        {
                            if (_redirects != null)
                            {
                                _redirects[strongName] = assembly;
                            }
                            else
                            {
                                base.Add(assembly);
                            }
                        }
                    }
                }
            }

            return(assembly);
        }
Exemple #10
0
        /// <summary>
        /// This is used to try and resolve an assembly reference
        /// </summary>
        /// <param name="reference">The assembly reference</param>
        /// <param name="referrer">The module requiring the reference</param>
        /// <returns>The assembly node if resolved or null if not resolved</returns>
        public virtual AssemblyNode ResolveReference(AssemblyReference reference, Module referrer)
        {
            AssemblyNode assembly;

            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            // Try to get it from the cache
            string name = reference.StrongName;

            if (cache.ContainsKey(name))
            {
                return(cache[name]);
            }

            // Try to get it from the GAC if so indicated
            if (this.UseGac)
            {
                string location = GlobalAssemblyCache.GetLocation(reference);

                if (location != null)
                {
                    assembly = AssemblyNode.GetAssembly(location, null, false, false, false, false);

                    if (assembly != null)
                    {
                        this.Add(assembly);
                        return(assembly);
                    }
                }
            }

            // Try the redirects if not found
            foreach (BindingRedirectSettings brs in redirects)
            {
                if (brs.IsRedirectFor(name) && cache.ContainsKey(brs.StrongName))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Using redirect '{0}' in place of '{1}'",
                                                    brs.StrongName, name);

                    assembly = cache[brs.StrongName];

                    // Add the same assembly under the current name
                    cache.Add(name, assembly);
                    return(assembly);
                }
            }

            // Couldn't find it; return null
            return(null);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="reference"></param>
        /// <param name="module"></param>
        /// <returns></returns>
        public override AssemblyNode ResolveReference(
            AssemblyReference reference, Module module)
        {
            AssemblyNode assembly = base.ResolveReference(reference, module);

            if (assembly == null)
            {
                string strongName = reference.StrongName;

                if (_redirects != null && _redirects.Count != 0 &&
                    _redirects.ContainsKey(strongName))
                {
                    assembly = _redirects[strongName];
                }
                else if (_sourcePaths != null && _sourcePaths.Count != 0)
                {
                    string assemblyName     = reference.Name + ".dll";
                    string assemblyLocation = null;
                    foreach (string sourcePath in _sourcePaths)
                    {
                        string tempLocation = Path.Combine(sourcePath, assemblyName);
                        if (File.Exists(tempLocation))
                        {
                            assemblyLocation = tempLocation;
                            break;
                        }
                    }

                    if (assemblyLocation != null)
                    {
                        assembly = AssemblyNode.GetAssembly(assemblyLocation,
                                                            null, false, false, false, false);
                        if (assembly != null)
                        {
                            if (_redirects != null)
                            {
                                _redirects[strongName] = assembly;
                            }
                            else
                            {
                                base.Add(assembly);
                            }
                        }
                    }
                }
            }

            return(assembly);
        }
Exemple #12
0
        /// <summary>
        /// This is used to load an assembly that will be parsed and documented
        /// </summary>
        /// <param name="filePath">The path of the documented assembly to load</param>
        public void LoadAssembly(string filePath)
        {
            // This causes non-classes to register as classes
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, false, false);

            if (assembly != null)
            {
                if (assembly.Name == "mscorlib")
                {
                    ResetMscorlib(assembly);
                }

                resolver.Add(assembly);
                assemblies.Add(assembly);
            }
        }
Exemple #13
0
        // Accessory modules

        //private IDictionary cache = new Hashtable();

        public void LoadAccessoryAssembly(string filePath)
        {
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, false, false); // this causes non-classes to register as classes

            if (assembly != null)
            {
                if (assembly.Name == "mscorlib")
                {
                    ResetMscorlib(assembly);
                }

                resolver.Add(assembly);
                //assembly.AssemblyReferenceResolutionAfterProbingFailed += unresolvedModuleHandler;
                accessoryAssemblies.Add(assembly);
            }
        }
Exemple #14
0
        /// <summary>
        /// Example use of the CodePrinter class: prints the code of all the methods
        /// from an application rooted in a specific assembly file.
        /// </summary>
        /// <param name="args">Root assembly of the analyzed program.</param>
        public static void TestMain(string[] args)
        {
            AssemblyNode an = AssemblyNode.GetAssembly(args[0]);

            if (an == null)
            {
                Console.WriteLine("assembly \"{0}\" not found", args[0]);
                Environment.Exit(1);
            }

            ClassHierarchy ch = new ClassHierarchy(args[0]); //DataStructUtil.singleton(an));

            foreach (Method method in ch.AllMethods())
            {
                CodePrinter.PrintMethod(Console.Out, method);
            }
        }
Exemple #15
0
        /// <summary>
        /// This is used to load an accessory assembly
        /// </summary>
        /// <param name="filePath">The path of the accessory assembly to load</param>
        public void LoadAccessoryAssembly(string filePath)
        {
            // This causes non-classes to register as classes
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, false, false);

            if (assembly != null)
            {
                // Ignore these.  We've identified the system types assembly already and the other two won't
                // contain any usable types.
                if (assembly.Name == "mscorlib" || assembly.Name == "netstandard" || assembly.Name == "System.Runtime")
                {
                    return;
                }

                resolver.Add(assembly);
                accessoryAssemblies.Add(assembly);
            }
        }
Exemple #16
0
        /// <summary>
        /// This is used to load an accessory assembly
        /// </summary>
        /// <param name="filePath">The path of the accessory assembly to load</param>
        public void LoadAccessoryAssembly(string filePath)
        {
            // This causes non-classes to register as classes
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, false, false);

            if (assembly != null)
            {
                // Do not reset for frameworks that redirect all mscorlib types to other assemblies or it results
                // in a stack overflow.
                if ((assembly.Name == "mscorlib" && !TargetPlatform.AllSystemTypesRedirected) || assembly.Name == "netstandard")
                {
                    ResetMscorlib(assembly);
                }

                resolver.Add(assembly);
                accessoryAssemblies.Add(assembly);
            }
        }
Exemple #17
0
        /// <summary>
        /// This is used to load an assembly that will be parsed and documented
        /// </summary>
        /// <param name="filePath">The path of the documented assembly to load</param>
        public void LoadAssembly(string filePath)
        {
            // This causes non-classes to register as classes
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false, false, false, false);

            if (assembly != null)
            {
                // Do not reset for frameworks that redirect all mscorlib types to other assemblies or it results
                // in a stack overflow.
                if (assembly.Name == "mscorlib" && TargetPlatform.Platform != ".NETCore" &&
                    TargetPlatform.Platform != ".NETPortable" && TargetPlatform.Platform != "WindowsPhoneApp")
                {
                    ResetMscorlib(assembly);
                }

                resolver.Add(assembly);
                assemblies.Add(assembly);
            }
        }
Exemple #18
0
        /// <summary>
        /// This is used to load an assembly that will be parsed and documented
        /// </summary>
        /// <param name="filePath">The path of the documented assembly to load</param>
        public void LoadAssembly(string filePath)
        {
            // This causes non-classes to register as classes
            AssemblyNode assembly = AssemblyNode.GetAssembly(filePath, null, false,
                                                             (this.SourceCodeBasePath != null), false, false);

            if (assembly != null)
            {
                // Do not reset for frameworks that redirect all mscorlib types to other assemblies or it results
                // in a stack overflow.
                if ((assembly.Name == "mscorlib" && !TargetPlatform.AllSystemTypesRedirected) || assembly.Name == "netstandard")
                {
                    ResetMscorlib(assembly);
                }

                resolver.Add(assembly);
                assemblies.Add(assembly);

                if (this.SourceCodeBasePath != null)
                {
                    if (assembly.reader.PdbOutOfDate)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, "The program database (PDB) file " +
                                                        "associated with '{0}' is out of date.  Source context information is unavailable.",
                                                        filePath);
                    }
                    else
                    if (!assembly.reader.PdbExists)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, "The program database (PDB) file " +
                                                        "associated with '{0}' does not exist or could not be loaded.  Source context " +
                                                        "information is unavailable.", filePath);
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Info, "Found a current program database " +
                                                        "(PDB) file for '{0}'.", filePath);
                    }
                }
            }
        }
        public virtual AssemblyNode ResolveReference(AssemblyReference reference, Module module)
        {
            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            //Console.WriteLine("resolving {0}", reference.StrongName);

            // try to get it from the cache
            string name = reference.StrongName;

            if (cache.ContainsKey(name))
            {
                return(cache[name]);
            }

            // try to get it from the gac
            if (useGac)
            {
                string location = GlobalAssemblyCache.GetLocation(reference);
                if (location != null)
                {
                    AssemblyNode assembly = AssemblyNode.GetAssembly(location, null, false, false, false, false);
                    if (assembly != null)
                    {
                        Add(assembly);
                        return(assembly);
                    }
                }
            }

            // couldn't find it; return null
            // Console.WriteLine("returning null on request for {0}", reference.StrongName);
            //OnUnresolvedAssemblyReference(reference, module);
            return(null);
        }
Exemple #20
0
 private static AssemblyNode OnAssemblyReferenceResolutionAfterProbingFailed(
     AssemblyReference assemblyReference, ModuleNode referencingModule)
 {
     return(AssemblyNode.GetAssembly(Assembly.Load(assemblyReference.GetAssemblyName().FullName).Location, true, false, true));
 }
Exemple #21
0
 public AssemblyNode GetAssemblyNode()
 {
     CompileSourceCode();
     return(AssemblyNode.GetAssembly(outputAssemblyFileName, true, false, true));
 }
Exemple #22
0
        public AssemblyNode Resolve(AssemblyReference assemblyReference, Module referencingModule)
        {
            WriteToLog("AssemblyResolver: Assembly '{0}' is referencing assembly '{1}'.",
                       referencingModule.Name, assemblyReference.Name);
            AssemblyNode a = null;

            try
            {
                // Location Priority (in decreasing order):
                // 1. referencing Module's directory
                // 2. directory original assembly was in
                // 3. list of directories specified by client
                // 4. Framework directory
                //
                // Extension Priority (in decreasing order):
                // dll, exe, (any others?)
                #region Check referencing module's directory
                WriteToLog("\tAssemblyResolver: Attempting referencing assembly's directory.");
                if (referencingModule.Directory != null)
                {
                    foreach (string ext in exts)
                    {
                        bool   tempDebugInfo = debugInfo;
                        string fullName      = Path.Combine(referencingModule.Directory, assemblyReference.Name + "." + ext);
                        if (File.Exists(fullName))
                        {
                            if (tempDebugInfo)
                            {
                                // Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
                                string pdbFullName = Path.Combine(referencingModule.Directory, assemblyReference.Name + ".pdb");
                                if (!File.Exists(pdbFullName))
                                {
                                    WriteToLog("Can not find PDB file. Debug info will not be available for assembly '{0}'.",
                                               assemblyReference.Name);
                                    tempDebugInfo = false;
                                }
                            }
                            WriteToLog("Resolved assembly reference '{0}' to '{1}'. (Used referencing Module's directory.)",
                                       assemblyReference.Name,
                                       fullName);
                            a = AssemblyNode.GetAssembly(
                                fullName,                           // path to assembly
                                h,                                  // global cache to use for assemblies
                                true,                               // doNotLockFile
                                tempDebugInfo,                      // getDebugInfo
                                useGlobalCache,                     // useGlobalCache
                                shortB                              // preserveShortBranches
                                );
                            break;
                        }
                    }
                }
                else
                {
                    WriteToLog("\t\tAssemblyResolver: Referencing assembly's directory is null.");
                }
                if (a == null)
                {
                    if (referencingModule.Directory != null)
                    {
                        WriteToLog("\tAssemblyResolver: Did not find assembly in referencing assembly's directory.");
                    }
                }
                else
                {
                    goto End;
                }
                #endregion
                #region Check input directory
                WriteToLog("\tAssemblyResolver: Attempting input directory.");
                foreach (string ext in exts)
                {
                    bool   tempDebugInfo = debugInfo;
                    string fullName      = Path.Combine(inputDirectory, assemblyReference.Name + "." + ext);
                    if (File.Exists(fullName))
                    {
                        WriteToLog("Resolved assembly reference '{0}' to '{1}'. (Used the original input directory.)",
                                   assemblyReference.Name,
                                   fullName);
                        if (tempDebugInfo)
                        {
                            // Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
                            string pdbFullName = Path.Combine(referencingModule.Directory, assemblyReference.Name + ".pdb");
                            if (!File.Exists(pdbFullName))
                            {
                                WriteToLog("Can not find PDB file. Debug info will not be available for assembly '{0}'.",
                                           assemblyReference.Name);
                                tempDebugInfo = false;
                            }
                        }
                        a = AssemblyNode.GetAssembly(
                            fullName,                       // path to assembly
                            h,                              // global cache to use for assemblies
                            true,                           // doNotLockFile
                            tempDebugInfo,                  // getDebugInfo
                            useGlobalCache,                 // useGlobalCache
                            shortB                          // preserveShortBranches
                            );
                        break;
                    }
                }
                if (a == null)
                {
                    WriteToLog("\tAssemblyResolver: Did not find assembly in input directory.");
                }
                else
                {
                    goto End;
                }
                #endregion
                #region Check user-supplied search directories
                WriteToLog("\tAssemblyResolver: Attempting user-supplied directories.");
                if (directories != null)
                {
                    foreach (string dir in directories)
                    {
                        foreach (string ext in exts)
                        {
                            string fullName = dir + "\\" + assemblyReference.Name + "." + ext;
                            if (File.Exists(fullName))
                            {
                                bool tempDebugInfo = debugInfo;
                                WriteToLog("Resolved assembly reference '{0}' to '{1}'. (Used a client-supplied directory.)",
                                           assemblyReference.Name,
                                           fullName);
                                if (tempDebugInfo)
                                {
                                    // Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
                                    string pdbFullName = Path.Combine(referencingModule.Directory, assemblyReference.Name + ".pdb");
                                    if (!File.Exists(pdbFullName))
                                    {
                                        WriteToLog("Can not find PDB file. Debug info will not be available for assembly '{0}'.",
                                                   assemblyReference.Name);
                                        tempDebugInfo = false;
                                    }
                                }
                                a = AssemblyNode.GetAssembly(               //(fullName,h, true, false, true);
                                    fullName,                               // path to assembly
                                    h,                                      // global cache to use for assemblies
                                    true,                                   // doNotLockFile
                                    tempDebugInfo,                          // getDebugInfo
                                    useGlobalCache,                         // useGlobalCache
                                    shortB                                  // preserveShortBranches
                                    );
                                break;
                            }
                        }
                        if (a != null)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    WriteToLog("\tAssemblyResolver: No user-supplied directories.");
                }
                if (a == null)
                {
                    if (directories != null)
                    {
                        WriteToLog("\tAssemblyResolver: Did not find assembly in user-supplied directories.");
                    }
                }
                else
                {
                    goto End;
                }
                #endregion
                #region Check framework directory
                WriteToLog("\tAssemblyResolver: Attempting framework directory.");
                if (TargetPlatform.PlatformAssembliesLocation != null)
                {
                    var directory = TargetPlatform.PlatformAssembliesLocation;
                    foreach (string ext in exts)
                    {
                        bool   tempDebugInfo = debugInfo;
                        string fullName      = Path.Combine(directory, assemblyReference.Name + "." + ext);
                        if (File.Exists(fullName))
                        {
                            if (tempDebugInfo)
                            {
                                // Don't pass the debugInfo flag to GetAssembly unless the PDB file exists.
                                string pdbFullName = Path.Combine(directory, assemblyReference.Name + ".pdb");
                                if (!File.Exists(pdbFullName))
                                {
                                    WriteToLog("Can not find PDB file. Debug info will not be available for assembly '{0}'.",
                                               assemblyReference.Name);
                                    tempDebugInfo = false;
                                }
                            }
                            WriteToLog("Resolved assembly reference '{0}' to '{1}'. (Used framework directory.)",
                                       assemblyReference.Name,
                                       fullName);
                            a = AssemblyNode.GetAssembly(
                                fullName,       // path to assembly
                                h,              // global cache to use for assemblies
                                true,           // doNotLockFile
                                tempDebugInfo,  // getDebugInfo
                                useGlobalCache, // useGlobalCache
                                shortB          // preserveShortBranches
                                );
                            break;
                        }
                    }
                }
                else
                {
                    WriteToLog("\t\tAssemblyResolver: Platform assemblies location is null.");
                }
                if (a == null)
                {
                    if (referencingModule.Directory != null)
                    {
                        WriteToLog("\tAssemblyResolver: Did not find assembly in framework directory.");
                    }
                }
                else
                {
                    goto End;
                }
                #endregion
End:
                if (a == null)
                {
                    WriteToLog("AssemblyResolver: Unable to resolve reference. (It still might be found, e.g., in the GAC.)");
                }
            }
            catch (Exception e)
            {
                WriteToLog("AssemblyResolver: Exception occurred. Unable to resolve reference.");
                WriteToLog("Inner exception: " + e.ToString());
            }
            return(a);
        }
Exemple #23
0
        /// <summary>
        /// This is used to try and resolve an assembly reference
        /// </summary>
        /// <param name="reference">The assembly reference</param>
        /// <param name="referrer">The module requiring the reference</param>
        /// <returns>The assembly node if resolved or null if not resolved</returns>
        public virtual AssemblyNode ResolveReference(AssemblyReference reference, Module referrer)
        {
            AssemblyNode assembly;

            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            // Try to get it from the cache
            string name = reference.StrongName;

            if (cache.ContainsKey(name))
            {
                return(cache[name]);
            }

            // Try to get it from the GAC if so indicated
            if (this.UseGac)
            {
                string location = GlobalAssemblyCache.GetLocation(reference);

                if (location != null)
                {
                    assembly = AssemblyNode.GetAssembly(location, null, false, false, false, false);

                    if (assembly != null)
                    {
                        this.Add(assembly);
                        return(assembly);
                    }
                }
            }

            // Try the redirects if not found
            foreach (BindingRedirectSettings brs in redirects)
            {
                if (brs.IsRedirectFor(name) && cache.ContainsKey(brs.StrongName))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Using redirect '{0}' in place of '{1}'",
                                                    brs.StrongName, name);

                    assembly = cache[brs.StrongName];

                    // Add the same assembly under the current name
                    cache.Add(name, assembly);
                    return(assembly);
                }
            }

            // For mscorlib v255.255.255.255, redirect to System.Runtime.  This is typically one like a .NETCore
            // framework which redirects all of the system types there.
            if (reference.Name == "mscorlib" && reference.Version.Major == 255)
            {
                // The system assembly should be set.  If so, it'll point to the one we need.
                if (SystemTypes.SystemAssembly != null)
                {
                    assembly = SystemTypes.SystemAssembly;
                    cache.Add(name, assembly);
                    return(assembly);
                }

                // If not, look for it in the cache
                string key = cache.Keys.FirstOrDefault(k => k.StartsWith("System.Runtime,", StringComparison.Ordinal));

                if (key != null)
                {
                    assembly = cache[key];
                    cache.Add(name, assembly);
                    return(assembly);
                }
            }

            if (reference.Name != "mscorlib")
            {
                // Try for a framework assembly in the target platform
                var assemblyRef = (AssemblyReference)TargetPlatform.AssemblyReferenceFor[Identifier.For(reference.Name).UniqueIdKey];

                if (assemblyRef != null && System.IO.File.Exists(assemblyRef.Location))
                {
                    assembly = AssemblyNode.GetAssembly(assemblyRef.Location, null, false, false, false, false);

                    ConsoleApplication.WriteMessage(LogLevel.Info, "Using framework redirect '{0}' in place of '{1}'",
                                                    assembly.StrongName, name);

                    cache.Add(name, assembly);
                    return(assembly);
                }
            }

            // Couldn't find it; return null
            return(null);
        }