Ejemplo n.º 1
0
        public IAssemblyReference Map(IAssemblySymbol assembly)
        {
            Contract.Requires(assembly != null);
            Contract.Ensures(Contract.Result <IAssemblyReference>() != null);

            IAssemblyReference cciAssembly = null;

            if (!assemblySymbolCache.TryGetValue(assembly, out cciAssembly))
            {
                var an = assembly.Identity;
                IEnumerable <byte> pkt = an.PublicKeyToken.AsEnumerable();
                if (pkt == null)
                {
                    pkt = new byte[0];
                }
                var identity = new Microsoft.Cci.AssemblyIdentity(
                    this.nameTable.GetNameFor(an.Name),
                    an.CultureName == null ? "" : an.CultureName, // REVIEW: This can't be right
                    an.Version,
                    pkt,
                    "unknown://location" // BUGBUG an.Location == null ? "unknown://location" : an.Location
                    );
                cciAssembly = new Microsoft.Cci.Immutable.AssemblyReference(this.host, identity);
                assemblySymbolCache[assembly] = cciAssembly;
            }
            Contract.Assume(cciAssembly != null);
            return(cciAssembly);
        }
Ejemplo n.º 2
0
        public Assembly CompileProject(string projectFileName)
        {
            Assembly existing;
            if (Compilations.TryGetValue(Path.GetFullPath(projectFileName), out existing))
            {
                return existing;
            }

            var project = new Microsoft.Build.BuildEngine.Project();
            project.Load(projectFileName);

            var projectName = Environment.NameTable.GetNameFor(project.EvaluatedProperties["AssemblyName"].Value);
            var projectPath = project.FullFileName;
            var compilerOptions = new SpecSharpOptions();
            var assemblyReferences = new List<IAssemblyReference>();
            var moduleReferences = new List<IModuleReference>();
            var programSources = new List<SpecSharpSourceDocument>();
            var assembly = new SpecSharpAssembly(projectName, projectPath, Environment, compilerOptions, assemblyReferences, moduleReferences, programSources);
            var helper = new SpecSharpCompilationHelper(assembly.Compilation);

            Compilations[Path.GetFullPath(projectFileName)] = assembly;

            assemblyReferences.Add(Environment.LoadAssembly(Environment.CoreAssemblySymbolicIdentity));
            project.Build("ResolveAssemblyReferences");
            foreach (BuildItem item in project.GetEvaluatedItemsByName("ReferencePath"))
            {
                var assemblyName = new System.Reflection.AssemblyName(item.GetEvaluatedMetadata("FusionName"));
                var name = Environment.NameTable.GetNameFor(assemblyName.Name);
                var culture = assemblyName.CultureInfo != null ? assemblyName.CultureInfo.Name : "";
                var version = assemblyName.Version == null ? new Version(0, 0) : assemblyName.Version;
                var token = assemblyName.GetPublicKeyToken();
                if (token == null) token = new byte[0];
                var location = item.FinalItemSpec;
                var identity = new AssemblyIdentity(name, culture, version, token, location);
                var reference = Environment.LoadAssembly(identity);
                assemblyReferences.Add(reference);
            }

            foreach (BuildItem item in project.GetEvaluatedItemsByName("ProjectReference"))
            {
                var name = Environment.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(item.FinalItemSpec));
                var location = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(project.FullFileName), item.FinalItemSpec));
                var reference = CompileProject(location);
                assemblyReferences.Add(reference);
            }

            foreach (BuildItem item in project.GetEvaluatedItemsByName("Compile"))
            {
                var location = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(project.FullFileName), item.FinalItemSpec));
                var name = Environment.NameTable.GetNameFor(location);
                var programSource = new SpecSharpSourceDocument(helper, name, location, File.ReadAllText(location));
                programSources.Add(programSource);
            }

            return assembly;
        }
Ejemplo n.º 3
0
    /// <summary>
    /// Returns the original location of the corresponding assembly if available, otherwise returns the location of the shadow copy.
    /// If the corresponding assembly is not in the GAC, null is returned.
    /// </summary>
    public static string/*?*/ GetLocation(AssemblyIdentity assemblyIdentity, IMetadataHost metadataHost) {
      lock (GlobalLock.LockingObject) {
#if COMPACTFX
        var gacKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"\Software\Microsoft\.NETCompactFramework\Installer\Assemblies\Global");
        foreach (var gacName in gacKey.GetValueNames()) {
          if (IdentityMatchesString(assemblyIdentity, gacName)) {
            var values = gacKey.GetValue(gacName) as string[];
            if (values == null || values.Length == 0) continue;
            return values[0];
          }
        }
        return null;
#else
        if (!GlobalAssemblyCache.FusionLoaded) {
          GlobalAssemblyCache.FusionLoaded = true;
          System.Reflection.Assembly systemAssembly = typeof(object).Assembly;
          //^ assume systemAssembly != null;
          string/*?*/ systemAssemblyLocation = systemAssembly.Location;
          //^ assume systemAssemblyLocation != null;
          string dir = Path.GetDirectoryName(systemAssemblyLocation);
          //^ assume dir != null;
          GlobalAssemblyCache.LoadLibrary(Path.Combine(dir, "fusion.dll"));
        }
        IAssemblyEnum assemblyEnum;
        CreateAssemblyEnum(out assemblyEnum, null, null, ASM_CACHE.GAC, 0);
        if (assemblyEnum == null) return null;
        IApplicationContext applicationContext;
        IAssemblyName currentName;
        while (assemblyEnum.GetNextAssembly(out applicationContext, out currentName, 0) == 0) {
          //^ assume currentName != null;
          AssemblyName cn = new AssemblyName(currentName);
          if (assemblyIdentity.Equals(new AssemblyIdentity(metadataHost.NameTable.GetNameFor(cn.Name), cn.Culture, cn.Version, cn.PublicKeyToken, ""))) {
            string codeBase = cn.CodeBase;
            if (codeBase != null && codeBase.StartsWith("file://")) {
              Uri u = new Uri(codeBase, UriKind.Absolute);
              return u.LocalPath;
            }
            return cn.GetLocation();
          }
        }
        return null;
#endif
      }
    }
Ejemplo n.º 4
0
        public override AssemblyIdentity UnifyAssembly(AssemblyIdentity assemblyIdentity)
        {
            Dictionary<String, Byte[]> assembliesToUnify = new Dictionary<string, Byte[]>{
                {"System", new Byte[]{0xb7,0x7a,0x5c,0x56,0x19,0x34,0xe0,0x89}},
                {"System.Drawing", new Byte[]{0xb0,0x3f,0x5f,0x7f,0x11,0xd5,0x0a,0x3a}},
                {"System.Windows.Forms", new Byte[]{0xb7,0x7a,0x5c,0x56,0x19,0x34,0xe0,0x89}},
            };
            Byte[] publicKeyToken;

            if (assembliesToUnify.TryGetValue(assemblyIdentity.Name.Value, out publicKeyToken) && IteratorHelper.EnumerablesAreEqual<Byte>(publicKeyToken, assemblyIdentity.PublicKeyToken))
            {
                assemblyIdentity = new AssemblyIdentity(
                    assemblyIdentity.Name,
                    assemblyIdentity.Culture,
                    CoreAssemblySymbolicIdentity.Version, // roll forward to the version of mscorlib
                    assemblyIdentity.PublicKeyToken,
                    assemblyIdentity.Location);
            }

            return base.UnifyAssembly(assemblyIdentity);
        }
Ejemplo n.º 5
0
        // TODO: Something similar for ResolvingModuleReference?
        public override void ResolvingAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly)
        {
            List<String> paths = new List<string>();
            paths.Add(Path.GetDirectoryName(referringUnit.Location));
            paths.AddRange(_assemblyPaths);

            foreach (String assemblyFile in _referencedAssemblies)
            {
                if (Path.GetFileNameWithoutExtension(assemblyFile).Equals(referencedAssembly.Name.Value, StringComparison.OrdinalIgnoreCase))
                {
                    if (TryLoadAssembly(referringUnit, referencedAssembly, assemblyFile))
                    {
                        return;
                    }
                }
            }

            foreach (String path in paths)
            {
                String file = Path.Combine(path, referencedAssembly.Name.Value + ".dll");
                if (TryLoadAssembly(referringUnit, referencedAssembly, file))
                {
                    return;
                }

                file = Path.Combine(path, referencedAssembly.Name.Value + ".exe");
                if (TryLoadAssembly(referringUnit, referencedAssembly, file))
                {
                    return;
                }

                file = Path.Combine(path, referencedAssembly.Name.Value + ".winmd");
                if (TryLoadAssembly(referringUnit, referencedAssembly, file))
                {
                    return;
                }
            }

            throw new Exception(String.Format("Cannot find: {0}. Check assembly dependency paths.", referencedAssembly.ToString()));
        }
Ejemplo n.º 6
0
    public IAssemblyReference Map(R.IAssemblySymbol assembly) {
      Contract.Requires(assembly != null);
      Contract.Ensures(Contract.Result<IAssemblyReference>() != null);

      IAssemblyReference cciAssembly = null;
      if (!assemblySymbolCache.TryGetValue(assembly, out cciAssembly)) {
        var an = assembly.Identity;
        IEnumerable<byte> pkt = an.PublicKeyToken.AsEnumerable();
        if (pkt == null)
          pkt = new byte[0];
        var identity = new Microsoft.Cci.AssemblyIdentity(
          this.nameTable.GetNameFor(an.Name),
          an.CultureName == null ? "" : an.CultureName, // REVIEW: This can't be right
          an.Version,
          pkt,
          an.Location == null ? "unknown://location" : an.Location
          );
        cciAssembly = new Microsoft.Cci.Immutable.AssemblyReference(this.host, identity);
        assemblySymbolCache[assembly] = cciAssembly;
      }
      Contract.Assume(cciAssembly != null);
      return cciAssembly;
    }
Ejemplo n.º 7
0
 /// <summary>
 /// This method is called when the assembly reference is being resolved and its not already loaded by the host.
 /// </summary>
 /// <param name="referringUnit">The unit that is referencing the assembly.</param>
 /// <param name="referencedAssembly">Assembly identifier for the assembly being referenced.</param>
 public void ResolvingAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly) {
   Contract.Requires(referringUnit != null);
   Contract.Requires(referencedAssembly != null);
   throw new NotImplementedException();
 }
Ejemplo n.º 8
0
    public virtual AssemblyIdentity ProbeAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly) {
      AssemblyIdentity result;

      if (!string.IsNullOrEmpty(referringUnit.Location)) {
        // probe for in the same directory as the referring unit
        var referringDir = Path.GetDirectoryName(Path.GetFullPath(referringUnit.Location));
        result = this.Probe(referringDir, referencedAssembly);
        if (result != null) return result;
      }

      // Probe in the libPaths directories
      foreach (string libPath in this.LibPaths) {
        Contract.Assume(libPath != null);
        result = this.Probe(libPath, referencedAssembly);
        if (result != null) return result;
      }

      // Check GAC
#if !COMPACTFX
      if (this.SearchInGAC) {
        string/*?*/ gacLocation = GlobalAssemblyCache.GetLocation(referencedAssembly, this);
        if (gacLocation != null) {
          return new AssemblyIdentity(referencedAssembly, gacLocation);
        }
      }
#endif

      // Check platform location
      var platformDir = Path.GetDirectoryName(Path.GetFullPath(GetLocalPath(typeof(object).Assembly.GetName())))??"";
      var coreVersion = this.CoreAssemblySymbolicIdentity.Version;
      if (coreVersion.Major == 1) {
        if (coreVersion.Minor == 0)
          platformDir = Path.Combine(Path.GetDirectoryName(platformDir)??"", "v1.0.3705");
        else if (coreVersion.Minor == 1)
          platformDir = Path.Combine(Path.GetDirectoryName(platformDir)??"", "v1.1.4322");
      } else if (coreVersion.Major == 2) {
        platformDir = Path.Combine(Path.GetDirectoryName(platformDir)??"", "v3.5");
        result = this.Probe(platformDir, referencedAssembly);
        if (result != null) return result;
        platformDir = Path.Combine(Path.GetDirectoryName(platformDir)??"", "v3.0");
        result = this.Probe(platformDir, referencedAssembly);
        if (result != null) return result;
        platformDir = Path.Combine(Path.GetDirectoryName(platformDir)??"", "v2.0.50727");
      } else if (coreVersion.Major == 4) {
        platformDir = Path.Combine(Path.GetDirectoryName(platformDir)??"", "v4.0.30319");
      }

      result = this.Probe(platformDir, referencedAssembly);
      if (result != null) return result;

      // Give up
      return new AssemblyIdentity(referencedAssembly, "unknown://location");
    }
Ejemplo n.º 9
0
 /// <summary>
 /// The assembly that matches the given reference, or a dummy assembly if no matching assembly can be found.
 /// </summary>
 public virtual IAssembly LoadAssembly(AssemblyIdentity assemblyIdentity) {
   IUnit/*?*/ unit;
   lock (GlobalLock.LockingObject) {
     this.unitCache.TryGetValue(assemblyIdentity, out unit);
   }
   IAssembly/*?*/ result;
   if (unit != null)
     result = unit as IAssembly;
   else {
     if (string.IsNullOrEmpty(assemblyIdentity.Location) || string.Equals(assemblyIdentity.Location, "unknown://location", StringComparison.OrdinalIgnoreCase)) {
       result = Dummy.Assembly;
       lock (GlobalLock.LockingObject) {
         this.unitCache.Add(assemblyIdentity, result);
       }
     } else {
       unit = this.LoadUnitFrom(assemblyIdentity.Location);
       result = unit as IAssembly;
       if (result != null && this.UnifyAssembly(result).Equals(assemblyIdentity))
         lock (GlobalLock.LockingObject) {
           this.unitCache[assemblyIdentity] = result;
           this.coreIdentities.Add(result.CoreAssemblySymbolicIdentity);
         }
     }
   }
   if (result == null) result = Dummy.Assembly;
   return result;
 }
Ejemplo n.º 10
0
    // Interning of module and assembly
    // enables fast comparision of the nominal types. The interned module id takes into account the unification policy applied by the host.
    // For example if mscorlib 1.0 and mscorlib 2.0 is unified by the host both of them will have same intered id, otherwise not.
    // Interned id is 32 bit integer. it is split into 22 bit part and 10 bit part. First part represents the assembly and other part represents module.
    // Simple module which are not part of any assembly is represented by 0 in assembly part and number in module part.
    // Main module of the assembly is represented with something in the assembly part and 0 in the module part.
    // Other modules of the multimodule assembly are represented with assembly part being containing assembly and module part distinct for each module.
    // Note that this places limit on number of modules that can be loaded to be 2^20 and number of modules loaded at 2^12

    uint IInternFactory.GetAssemblyInternedKey(AssemblyIdentity assemblyIdentity) {
      lock (GlobalLock.LockingObject) {
        AssemblyStore assemblyStore = this.GetAssemblyStore(assemblyIdentity);
        return assemblyStore.InternedId;
      }
    }
Ejemplo n.º 11
0
    AssemblyStore GetAssemblyStore(AssemblyIdentity assemblyIdentity) {
      Contract.Requires(assemblyIdentity != null);
      Contract.Ensures(Contract.Result<AssemblyStore>() != null);

      IName assemblyName = assemblyIdentity.Name;
      foreach (AssemblyStore aStore in this.AssemblyHashtable.GetValuesFor((uint)assemblyName.UniqueKey)) {
        if (assemblyIdentity.Equals(aStore.AssemblyIdentity)) return aStore;
      }
      uint value = this.CurrentAssemblyInternValue;
      this.CurrentAssemblyInternValue += 0x00001000;
      AssemblyStore aStore1 = new AssemblyStore(assemblyIdentity, value, this.CurrentNamespaceInternValue++);
      this.AssemblyHashtable.Add((uint)assemblyName.UniqueKey, aStore1);
      return aStore1;
    }
Ejemplo n.º 12
0
        private static bool IdentityMatchesString(AssemblyIdentity assemblyIdentity, string gacName)
        {
            int n = gacName.Length;
            var i = 0;

            if (!MatchIgnoringCase(assemblyIdentity.Name.Value, ',', gacName, ref i, n))
            {
                return(false);
            }
            while (i < n)
            {
                char ch = gacName[i];
                switch (ch)
                {
                case 'v':
                case 'V':
                    if (!MatchIgnoringCase("Version", '=', gacName, ref i, n))
                    {
                        return(false);
                    }
                    if (!MatchDecimal(assemblyIdentity.Version.Major, '.', gacName, ref i, n))
                    {
                        return(false);
                    }
                    if (!MatchDecimal(assemblyIdentity.Version.MajorRevision, '.', gacName, ref i, n))
                    {
                        return(false);
                    }
                    if (!MatchDecimal(assemblyIdentity.Version.Minor, '.', gacName, ref i, n))
                    {
                        return(false);
                    }
                    if (!MatchDecimal(assemblyIdentity.Version.MinorRevision, ',', gacName, ref i, n))
                    {
                        return(false);
                    }
                    break;

                case 'C':
                case 'c':
                    if (!MatchIgnoringCase("Culture", '=', gacName, ref i, n))
                    {
                        return(false);
                    }
                    var culture = assemblyIdentity.Culture;
                    if (culture.Length == 0)
                    {
                        culture = "neutral";
                    }
                    if (!MatchIgnoringCase(culture, ',', gacName, ref i, n))
                    {
                        return(false);
                    }
                    break;

                case 'P':
                case 'p':
                    if (!MatchIgnoringCase("PublicKeyToken", '=', gacName, ref i, n))
                    {
                        return(false);
                    }
                    if (!MatchHex(assemblyIdentity.PublicKeyToken, ',', gacName, ref i, n))
                    {
                        return(false);
                    }
                    break;

                default:
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 13
0
 public AssemblyIdentity ProbeAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly) {
   throw new NotImplementedException();
 }
Ejemplo n.º 14
0
 public override void ResolvingAssemblyReference(IUnit referringUnit, Microsoft.Cci.AssemblyIdentity referencedAssembly)
 {
     base.ResolvingAssemblyReference(referringUnit, referencedAssembly);
 }
Ejemplo n.º 15
0
 public override IAssembly LoadAssembly(Microsoft.Cci.AssemblyIdentity assemblyIdentity)
 {
     return(base.LoadAssembly(assemblyIdentity));
 }
Ejemplo n.º 16
0
        public bool TryGetAssemblyReference(IAssemblySymbol semanticAssembly, out IAssemblyReference cciAssembly)
        {
            Contract.Ensures(!Contract.Result <bool>() || Contract.ValueAtReturn(out cciAssembly) != null);

            cciAssembly = null;

            #region Check input
            if (semanticAssembly == null)
            {
                return(false);
            }
            #endregion
            #region Check cache
            if (ContractsPackageAccessor.Current.VSOptionsPage.Caching)
            {
                if (_semanticAssemblysToCCIAssemblys.TryGetValue(semanticAssembly, out cciAssembly))
                {
                    return(cciAssembly != Dummy.AssemblyReference && cciAssembly != null);
                }
            }
            #endregion
            // distinguish between the AssemblyName and the ProjectName

            var semanticAssemblyFileName = (semanticAssembly.Name == null) ? null : semanticAssembly.Name;
            if (string.IsNullOrWhiteSpace(semanticAssemblyFileName))
            {
                return(false);
            }
            var semanticAssemblyName = Path.GetFileName(semanticAssemblyFileName);
            if (semanticAssemblyName.EndsWith(".dll") || semanticAssemblyName.EndsWith(".exe"))
            {
                semanticAssemblyName = semanticAssemblyName.Remove(semanticAssemblyName.Length - 4, 4);
            }

            #region Try to get assembly from previously loaded assemblies from host
            foreach (var unit in Host.LoadedUnits)
            {
                if (unit == null)
                {
                    continue;
                }
                if (unit is Dummy)
                {
                    continue;
                }
                if (unit.Name.Value == semanticAssemblyName)
                {
                    cciAssembly = (IAssemblyReference)unit;
                    if (cciAssembly.ResolvedAssembly.Location == semanticAssemblyFileName)
                    {
                        goto ReturnTrue;
                    }
                }
            }
            #endregion
            #region Check if assembly is the same as the current project's output assembly
            if (_projectTracker.AssemblyIdentity != null && _projectTracker.AssemblyIdentity.Name != null)
            {
                if (semanticAssemblyName.Equals(_projectTracker.AssemblyIdentity.Name.Value, StringComparison.OrdinalIgnoreCase) || semanticAssemblyName.Equals(_projectTracker.ProjectName, StringComparison.OrdinalIgnoreCase))
                {
                    cciAssembly = new Microsoft.Cci.Immutable.AssemblyReference(this.Host, _projectTracker.AssemblyIdentity);
                    Host.AddLibPath(Path.Combine(Path.GetDirectoryName(semanticAssemblyFileName), "CodeContracts"));
                    Host.AddLibPath(Path.Combine(Path.GetDirectoryName(semanticAssemblyFileName), @"..\Debug\CodeContracts"));
                    goto ReturnTrue;
                }
            }
            else
            {
                ContractsPackageAccessor.Current.Logger.WriteToLog("Assembly identity for the project: " + _projectTracker.ProjectName + " was null.");
            }
            #endregion
            #region Build assembly reference
            if (semanticAssembly.Name == null || string.IsNullOrWhiteSpace(semanticAssembly.Name))
            {
                goto ReturnFalseNoOutput;                                                                              // because we have no name.
            }
            var projectName = Path.GetFileName(semanticAssembly.Name);
            if (projectName.EndsWith(".dll") || projectName.EndsWith(".exe"))
            {
                projectName = projectName.Remove(projectName.Length - 4, 4);
            }
            var references = _projectTracker.References;
            VSLangProj.Reference reference = null;
            for (int i = 1, refcount = references == null ? 0 : references.Count; i <= refcount; i++)
            {
                var tempRef = references.Item(i);
                if (tempRef == null)
                {
                    continue;
                }
                string refName = tempRef.Name;//Path.GetFileNameWithoutExtension(tempRef.Name);
                if (refName == null)
                {
                    continue;
                }
                if (refName.Equals(projectName, StringComparison.OrdinalIgnoreCase))
                {
                    reference = tempRef;
                    break;
                }
            }
            if (reference != null)
            {
                IName   iName    = Host.NameTable.GetNameFor(Path.GetFileNameWithoutExtension(reference.Path));
                string  culture  = reference.Culture ?? "en";
                Version version  = new Version(reference.MajorVersion, reference.MinorVersion, reference.BuildNumber, reference.RevisionNumber);
                string  location = reference.Path;
                if (!string.IsNullOrEmpty(location))
                {
                    Host.AddLibPath(Path.Combine(location.Substring(0, location.Length - Path.GetFileName(location).Length), "CodeContracts"));
                    var assemblyIdentity = new AssemblyIdentity(iName, culture, version, Enumerable <byte> .Empty, location);
                    cciAssembly = new Microsoft.Cci.Immutable.AssemblyReference(this.Host, assemblyIdentity);
                    goto ReturnTrue;
                }
            }
            goto ReturnFalse;
            #endregion
            #region ReturnTrue:
ReturnTrue:
            if (ContractsPackageAccessor.Current.VSOptionsPage.Caching)
            {
                _semanticAssemblysToCCIAssemblys[semanticAssembly] = cciAssembly;
            }
            EnsureAssemblyIsLoaded(semanticAssembly, ref cciAssembly);
            return(true);

            #endregion
            #region ReturnFalse:
ReturnFalse:
            ContractsPackageAccessor.Current.Logger.WriteToLog("Failed to build assembly reference for: " + semanticAssembly.Name);
ReturnFalseNoOutput:
            if (ContractsPackageAccessor.Current.VSOptionsPage.Caching)
            {
                _semanticAssemblysToCCIAssemblys[semanticAssembly] = Dummy.AssemblyReference;
            }
            return(false);

            #endregion
        }
Ejemplo n.º 17
0
 public AssemblyIdentity UnifyAssembly(AssemblyIdentity assemblyIdentity)
 {
     Contract.Requires(assemblyIdentity != null);
     Contract.Ensures(Contract.Result <AssemblyIdentity>() != null);
     throw new NotImplementedException();
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Looks in the specified <paramref name="probeDir"/> to see if a file
 /// exists, first with the extension "dll" and then with the extension "exe".
 /// Returns null if not found, otherwise constructs a new AssemblyIdentity
 /// </summary>
 private AssemblyIdentity/*?*/ Probe(string probeDir, AssemblyIdentity referencedAssembly) {
   string path = Path.Combine(probeDir, referencedAssembly.Name.Value + ".dll");
   if (File.Exists(path)) return new AssemblyIdentity(referencedAssembly, path);
   path = Path.Combine(probeDir, referencedAssembly.Name.Value + ".exe");
   if (File.Exists(path)) return new AssemblyIdentity(referencedAssembly, path);
   return null;
 }
Ejemplo n.º 19
0
 /// <summary>
 /// This method is called when the assembly reference is being resolved and its not already loaded by the Read/Write host.
 /// </summary>
 /// <param name="referringUnit">The unit that is referencing the assembly.</param>
 /// <param name="referencedAssembly">Assembly identity for the assembly being referenced.</param>
 public virtual void ResolvingAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly) {
   if (!string.IsNullOrEmpty(referencedAssembly.Location)) {
     this.LoadUnit(referencedAssembly);
   } else {
     AssemblyIdentity ai = this.ProbeAssemblyReference(referringUnit, referencedAssembly);
     if (ai != null && !String.IsNullOrEmpty(ai.Location)) {
       this.LoadUnit(ai);
     }
   }
 }
Ejemplo n.º 20
0
    /// <summary>
    /// Given the identity of a referenced assembly (but not its location), apply host specific policies for finding the location
    /// of the referenced assembly.
    /// Returns an assembly identity that matches the given referenced assembly identity, but which includes a location.
    /// If the probe failed to find the location of the referenced assembly, the location will be "unknown://location".
    /// </summary>
    /// <param name="referringUnit">The unit that is referencing the assembly. It will have been loaded from somewhere and thus
    /// has a known location, which will typically be probed for the referenced assembly.</param>
    /// <param name="referencedAssembly">The assembly being referenced. This will not have a location since there is no point in probing
    /// for the location of an assembly when you already know its location.</param>
    /// <returns>
    /// An assembly identity that matches the given referenced assembly identity, but which includes a location.
    /// If the probe failed to find the location of the referenced assembly, the location will be "unknown://location".
    /// </returns>
    /// <remarks>
    /// Looks for the referenced assembly first in the same directory as the referring unit, then
    /// in any search paths provided to the constructor, then finally the GAC.
    /// </remarks>
    //^ [Pure]
    public override AssemblyIdentity ProbeAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly) {
      // probe for in the same directory as the referring unit
      var referringDir = Path.GetDirectoryName(Path.GetFullPath(referringUnit.Location));
      AssemblyIdentity result = this.Probe(referringDir, referencedAssembly);
      if (result != null) return result;

      // Probe in the libPaths directories
      foreach (string libPath in this.LibPaths) {
        result = this.Probe(libPath, referencedAssembly);
        if (result != null) return result;
      }

      // Check GAC
#if !COMPACTFX
      if (this.SearchInGAC) {
        string/*?*/ gacLocation = GlobalAssemblyCache.GetLocation(referencedAssembly, this);
        if (gacLocation != null) {
          return new AssemblyIdentity(referencedAssembly, gacLocation);
        }
      }
#endif

      // Check platform location
      var platformDir = Path.GetDirectoryName(Path.GetFullPath(GetLocalPath(typeof(object).Assembly.GetName())));
      result = this.Probe(platformDir, referencedAssembly);
      if (result != null) return result;

      // Give up
      return new AssemblyIdentity(referencedAssembly, "unknown://location");
    }
Ejemplo n.º 21
0
 protected override Microsoft.Cci.AssemblyIdentity Probe(string probeDir, Microsoft.Cci.AssemblyIdentity referencedAssembly)
 {
     return(base.Probe(probeDir, referencedAssembly));
 }
Ejemplo n.º 22
0
        public bool CanIncludeAssembly(AssemblyIdentity assemblyIdentity)
        {
            // If no filter set, we include all assemblies
            if (Options.IncludedAssemblies == null)
            {
                return true;
            }

            // Look through the list
            foreach (AssemblyIdentity assemblyId in Options.IncludedAssemblies)
            {
                if (assemblyId.Equals(assemblyIdentity))
                {
                    return true;
                }
            }

            // Assembly was not found in the list.
            return false;
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Returns the assembly corresponding to passed assemblyIdentifier if it was loaded.
 /// </summary>
 /// <param name="unifiedAssemblyIdentity">THe assembly Identifier that is unified with respect to the compilation host.</param>
 /// <returns></returns>
 public IAssembly/*?*/ FindAssembly(AssemblyIdentity unifiedAssemblyIdentity) {
   lock (GlobalLock.LockingObject) {
     uint internedModuleId = (uint)this.metadataReaderHost.InternFactory.GetAssemblyInternedKey(unifiedAssemblyIdentity);
     Module/*?*/ module = this.InternedIdToModuleMap.Find(internedModuleId);
     return module as IAssembly;
   }
 }
Ejemplo n.º 24
0
 public AssemblyIdentity UnifyAssembly(AssemblyIdentity assemblyIdentity) {
   throw new NotImplementedException();
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Allocates an object that identifies a .NET assembly, using its name, culture, version, public key token, and location.
 /// </summary>
 /// <param name="template">An assembly identity to use a template for the new identity.</param>
 /// <param name="location">A location that should replace the location from the template.</param>
 public AssemblyIdentity(AssemblyIdentity template, string location)
   : base(template.Name, location) {
   Contract.Requires(template != null);
   Contract.Requires(location != null);
   this.culture = template.Culture;
   this.version = template.Version;
   this.publicKeyToken = template.PublicKeyToken;
 }
Ejemplo n.º 26
0
 internal AssemblyStore(
   AssemblyIdentity assemblyIdentity,
   uint internedId,
   uint rootNamespaceInternedId
 ) {
   this.AssemblyIdentity = assemblyIdentity;
   this.InternedIdWithCount = internedId;
   this.RootNamespaceInternedId = rootNamespaceInternedId;
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Allocates an object that identifies a .NET module that forms part of an assembly.
 /// Can be just the name of the module along with the identifier of the assembly, but can also include the location where the module is stored.
 /// </summary>
 /// <param name="name">The name of the identified module.</param>
 /// <param name="location">The location where the module is stored. Can be the empty string if the location is not known. The location need not be a file path.</param>
 /// <param name="containingAssembly">The identifier of the assembly to which the identified module belongs. May be null.</param>
 public ModuleIdentity(IName name, string location, AssemblyIdentity/*?*/ containingAssembly)
   : base(name, location) {
   Contract.Requires(name != null);
   Contract.Requires(location != null);
   this.containingAssembly = containingAssembly;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Returns the identity of the assembly containing the core system types such as System.Object, by asking
 /// each of the loaded units for its opinion on the matter and returning the opinion with the highest version number.
 /// If none of the loaded units have an opinion, the identity of the runtime executing the compiler itself is returned.
 /// </summary>
 protected virtual AssemblyIdentity GetCoreAssemblySymbolicIdentity() {
   Contract.Ensures(Contract.Result<AssemblyIdentity>() != null);
   AssemblyIdentity/*?*/ result = null;
   IUnit referringUnit = Dummy.Unit;
   if (this.unitCache.Count > 0) {
     var dummyVersion = new Version(255, 255, 255, 255);
     lock (GlobalLock.LockingObject) {
       foreach (IUnit unit in this.unitCache.Values) {
         Contract.Assume(unit != null);
         AssemblyIdentity coreId = unit.CoreAssemblySymbolicIdentity;
         if (coreId.Name.Value.Length == 0) continue;
         this.coreIdentities.Add(coreId);
         if (result == null || result.Version == dummyVersion ||
            (result.Version < coreId.Version && coreId.Version != dummyVersion) ||
             result.Version == coreId.Version && unit.UnitIdentity.Equals(coreId)) {
           result = coreId;
           referringUnit = unit;
         }
       }
     }
   }
   if (result == null) {
     //If we get here, none of the assemblies in the unit cache has an opinion on the identity of the core assembly.
     //Usually this will be because this method was called before any assemblies have been loaded.
     //In this case, we have little option but to choose the identity of the core assembly of the platform we are running on.
     var coreAssemblyName = typeof(object).Assembly.GetName();
     var version = coreAssemblyName.Version;
     Contract.Assume(version != null);
     var publicKeyToken = coreAssemblyName.GetPublicKeyToken();
     Contract.Assume(publicKeyToken != null);
     result = new AssemblyIdentity(this.NameTable.GetNameFor(coreAssemblyName.Name), "", version, publicKeyToken, "");
   }
   if (result.Location.Length == 0) {
     //We either found a plausible identity by polling the assemblies in the unit cache, or we used the identity of our own core assembly.
     //However, we defer to ProbeAssemblyReference to find an actual location for the assembly.
     //(Note that if result.Location.Length > 0, then the core assembly has already been loaded and we thus know the location and don't have to probe.)
     this.coreAssemblySymbolicIdentity = result; //in case ProbeAssemblyReference wants to know the core identity
     result = this.ProbeAssemblyReference(referringUnit, result);
   }
   return this.coreAssemblySymbolicIdentity = result;
 }
Ejemplo n.º 29
0
    public static AssemblyIdentity GetAssemblyIdentity(EnvDTE.Project project, MetadataReaderHost host) {
      Contract.Requires(project != null);
      Contract.Requires(host != null);

      if (!ProjectIsAvailable(project))
        return null;

      VSServiceProvider.Current.Logger.WriteToLog("Getting the assembly identity for project: " + project.Name);

      string location_RootDir = null;
      string location_RelativeAssemblyDir = null;
      string location_FileName = null;
      string location = null;
      IName iName = null;
      string culture = "";//TODO: Find out where to get culture information.
      Version version = new Version();
      AssemblyIdentity result = null;
      try {
        var activePropCount = 
          project.ConfigurationManager != null && project.ConfigurationManager.ActiveConfiguration != null && project.ConfigurationManager.ActiveConfiguration.Properties != null ?
          project.ConfigurationManager.ActiveConfiguration.Properties.Count : 0;
        for (int i = activePropCount; 1 <= i; i--) {
          var prop = project.ConfigurationManager.ActiveConfiguration.Properties.Item(i);
          if (prop == null) continue;
          if (prop.Name == "OutputPath") {
            location_RelativeAssemblyDir = prop.Value as string;
            break;
          }
        }
        var propCount = project.Properties != null ? project.Properties.Count : 0;
        for (int i = propCount; 1 <= i; i--) {
          var prop = project.Properties.Item(i);
          if (prop == null) continue;
          switch (prop.Name) {
            case "AssemblyName":
              iName = host.NameTable.GetNameFor(prop.Value as string);
              break;
            case "AssemblyVersion":
              var stringVersion = prop.Value as string;
              if (!Version.TryParse(stringVersion, out version))
              {
                  version = new Version();
              }
              Contract.Assume(version != null);
              break;
            case "FullPath":
              location_RootDir = prop.Value as string;
              break;
            case "OutputFileName":
              location_FileName = prop.Value as string;
              break;
            default:
              break;
          }
        }
      } catch (COMException comEx) {
        VSServiceProvider.Current.Logger.WriteToLog("COM Exception while trying to access project's properties.");
        VSServiceProvider.Current.Logger.WriteToLog("Message: " + comEx.Message);
        if (comEx.Message.Contains(COMExceptionMessage_ProjectUnavailable)) {
          VSServiceProvider.Current.Logger.WriteToLog("Returning null.");
          return null;
        } else if (((uint)comEx.ErrorCode) == 0x80020009) {
          VSServiceProvider.Current.Logger.WriteToLog("Returning null.");
          return null;
        } else {
          throw comEx;
        }
      }

      //Check if we got enough information from VS to build the location
      if (location_FileName == null
        || location_RelativeAssemblyDir == null
        || location_RootDir == null) {
        VSServiceProvider.Current.Logger.WriteToLog("Couldn't find path to the project's output assembly.");
        return null;
      }

      //Set the location of the output assembly
      location = Path.Combine(location_RootDir, location_RelativeAssemblyDir, location_FileName);

      //Check that the output assembly exists
      if (!File.Exists(location)) {
        VSServiceProvider.Current.Logger.WriteToLog("Project output assembly could not be found at the location given by Visual Studio: " + location);
      }

      //Check our other information from VS
      if (iName == null
        || string.IsNullOrEmpty(location)) {
        VSServiceProvider.Current.Logger.WriteToLog("Couldn't gather sufficient information from the project to construct an assembly identity.");
        return null;
      }

      //Success
      Contract.Assert(version != null);
      Contract.Assert(culture != null);
      result = new AssemblyIdentity(iName, culture, version, Enumerable<byte>.Empty, location);
      host.AddLibPath(Path.Combine(location_RootDir, location_RelativeAssemblyDir, "CodeContracts"));
      host.AddLibPath(Path.Combine(location_RootDir, location_RelativeAssemblyDir, @"..\Debug\CodeContracts"));

      return result;
    }
Ejemplo n.º 30
0
 /// <summary>
 /// Finds the assembly that matches the given identifier among the already loaded set of assemblies,
 /// or a dummy assembly if no matching assembly can be found.
 /// </summary>
 public IAssembly FindAssembly(AssemblyIdentity assemblyIdentity) {
   IUnit/*?*/ unit;
   lock (GlobalLock.LockingObject) {
     this.unitCache.TryGetValue(assemblyIdentity, out unit);
   }
   IAssembly/*?*/ result = unit as IAssembly;
   if (result != null)
     return result;
   return Dummy.Assembly;
 }
Ejemplo n.º 31
0
 AssemblyStore GetAssemblyStore(AssemblyIdentity assemblyIdentity) {
   IName assemblyName = assemblyIdentity.Name;
   foreach (AssemblyStore aStore in this.AssemblyHashtable.GetValuesFor((uint)assemblyName.UniqueKey)) {
     if (assemblyIdentity.Equals(aStore.AssemblyIdentity)) {
       return aStore;
     }
   }
   uint value = this.CurrentAssemblyInternValue;
   this.CurrentAssemblyInternValue += 0x00001000;
   AssemblyStore aStore1 = new AssemblyStore(assemblyIdentity, value, this.CurrentNamespaceInternValue++);
   this.AssemblyHashtable.Add((uint)assemblyName.UniqueKey, aStore1);
   return aStore1;
 }
Ejemplo n.º 32
0
    /// <summary>
    /// Looks in the specified <paramref name="probeDir"/> to see if a file
    /// exists, first with the extension "dll" and then with the extensions "winmd" and "exe".
    /// Returns null if not found, otherwise constructs a new AssemblyIdentity
    /// </summary>
    protected virtual AssemblyIdentity/*?*/ Probe(string probeDir, AssemblyIdentity referencedAssembly) {
      Contract.Requires(probeDir != null);
      Contract.Requires(referencedAssembly != null);

      string path = Path.Combine(probeDir, referencedAssembly.Name.Value + ".dll");
      if (!File.Exists(path)) path = Path.Combine(probeDir, referencedAssembly.Name.Value + ".winmd");
      if (!File.Exists(path)) path = Path.Combine(probeDir, referencedAssembly.Name.Value + ".exe");
      if (!File.Exists(path)) return null;
      var assembly = this.LoadUnitFrom(path) as IAssembly;
      if (assembly == null) return null;
      if (!assembly.AssemblyIdentity.Equals(referencedAssembly)) return null;
      return assembly.AssemblyIdentity;
    }
Ejemplo n.º 33
0
 /// <summary>
 /// Returns the identity of the assembly containing the core system types such as System.Object, by asking
 /// each of the loaded units for its opinion on the matter and returning the opinion with the highest version number.
 /// If none of the loaded units have an opinion, the identity of the runtime executing the compiler itself is returned.
 /// </summary>
 protected virtual AssemblyIdentity GetCoreAssemblySymbolicIdentity() {
   var coreAssemblyName = typeof(object).Assembly.GetName();
   string loc = GetLocalPath(coreAssemblyName);
   if (this.unitCache.Count > 0) {
     AssemblyIdentity/*?*/ result = null;
     foreach (IUnit unit in this.unitCache.Values) {
       AssemblyIdentity coreId = unit.CoreAssemblySymbolicIdentity;
       if (coreId.Name.Value.Length == 0) continue;
       if (result == null || result.Version < coreId.Version) result = coreId;
     }
     if (result != null) {
       //The loaded assemblies have an opinion on the identity of the core assembly. By default, we are going to respect that opinion.
       if (result.Location.Length == 0) {
         //However, they do not know where to find it. (This will only be non empty if one of the loaded assemblies itself is the core assembly.)
         if (loc.Length > 0) {
           //We don't know where to find the core assembly that the loaded assemblies want, but we do know where to find the core assembly
           //that we are running on. Perhaps it is the same assembly as the one we've identified. In that case we know where it can be found.
           var myCore = new AssemblyIdentity(this.NameTable.GetNameFor(coreAssemblyName.Name), "", coreAssemblyName.Version, coreAssemblyName.GetPublicKeyToken(), loc);
           if (myCore.Equals(result)) return myCore; //myCore is the same as result, but also has a non null location.
         }
         //TODO: if the core assembly being referenced is not the same as the one running the host, probe in the standard places to find its location.
         //put this probing logic in a separate, overridable method and use it in LoadAssembly and LoadModule.
         //Hook it up with the GAC.
       }
       return result;
     }
   }
   //If we get here, none of the assemblies in the unit cache has an opinion on the identity of the core assembly.
   //Usually this will be because this method was called before any assemblies have been loaded.
   //In this case, we have little option but to choose the identity of the core assembly of the platform we are running on.
   return new AssemblyIdentity(this.NameTable.GetNameFor(coreAssemblyName.Name), "", coreAssemblyName.Version, coreAssemblyName.GetPublicKeyToken(), loc);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Default implementation of UnifyAssembly. Override this method to change the behavior.
 /// </summary>
 public virtual AssemblyIdentity UnifyAssembly(AssemblyIdentity assemblyIdentity) {
   if (assemblyIdentity.Name.UniqueKeyIgnoringCase == this.CoreAssemblySymbolicIdentity.Name.UniqueKeyIgnoringCase &&
     assemblyIdentity.Culture == this.CoreAssemblySymbolicIdentity.Culture && 
     IteratorHelper.EnumerablesAreEqual(assemblyIdentity.PublicKeyToken, this.CoreAssemblySymbolicIdentity.PublicKeyToken))
     return this.CoreAssemblySymbolicIdentity;
   if (this.CoreIdentities.Contains(assemblyIdentity)) return this.CoreAssemblySymbolicIdentity;
   return assemblyIdentity;
 }
Ejemplo n.º 35
0
 /// <summary>
 /// The assembly that matches the given reference, or a dummy assembly if no matching assembly can be found.
 /// </summary>
 public virtual IAssembly LoadAssembly(AssemblyIdentity assemblyIdentity) {
   IUnit/*?*/ unit;
   lock (GlobalLock.LockingObject) {
     this.unitCache.TryGetValue(assemblyIdentity, out unit);
   }
   if (unit == null) {
     if (assemblyIdentity.Location == "" || assemblyIdentity.Location == "unknown://location") {
       unit = Dummy.Assembly;
       this.unitCache.Add(assemblyIdentity, unit);
     } else {
       unit = this.LoadUnitFrom(assemblyIdentity.Location);
       var assembly = unit as IAssembly;
       if (assembly != null && this.UnifyAssembly(assembly.AssemblyIdentity).Equals(assemblyIdentity))
         this.unitCache[assemblyIdentity] = unit;
     }
   }
   IAssembly/*?*/ result = unit as IAssembly;
   if (result == null) result = Dummy.Assembly;
   return result;
 }
Ejemplo n.º 36
0
 public IAssembly LoadAssembly(AssemblyIdentity assemblyIdentity) {
   throw new NotImplementedException();
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Given the identity of a referenced assembly (but not its location), apply host specific policies for finding the location
 /// of the referenced assembly.
 /// </summary>
 /// <param name="referringUnit">The unit that is referencing the assembly. It will have been loaded from somewhere and thus
 /// has a known location, which will typically be probed for the referenced assembly.</param>
 /// <param name="referencedAssembly">The assembly being referenced. This will not have a location since there is no point in probing
 /// for the location of an assembly when you already know its location.</param>
 /// <returns>
 /// An assembly identity that matches the given referenced assembly identity, but which includes a location.
 /// If the probe failed to find the location of the referenced assembly, the location will be "unknown://location".
 /// </returns>
 /// <remarks>
 /// Default implementation of ProbeAssemblyReference. Override this method to change its behavior.
 /// </remarks>
 //^ [Pure]
 public virtual AssemblyIdentity ProbeAssemblyReference(IUnit referringUnit, AssemblyIdentity referencedAssembly) {
   return new AssemblyIdentity(referencedAssembly, "unknown://location");
 }