public static AssemblyDefinition TryResolve(this ModuleDefinition moduleDef, AssemblyNameReference assemblyNameRef)
 {
     try {
         return moduleDef.AssemblyResolver.Resolve(assemblyNameRef);
     } catch (AssemblyResolutionException) { }
     return null;
 }
 private Dictionary<IMemberDefinition, string> GetRenameMap(AssemblyNameReference assembly)
 {
     foreach (var map in Context.DefinitionsRenameMap)
         if (map.Key.FullName == assembly.FullName)
             return map.Value;
     return null;
 }
 public override void VisitAssemblyReference(AssemblyNameReference assemblyRef, AssemblyDefinition current)
 {
     if (string.Compare(assemblyRef.Name, this.myAssembly, true) == 0)
     {
         this.Aggregator.AddMatch(current);
     }
 }
Exemple #4
0
 AssemblyDefinition ResolveFailure(object sender, AssemblyNameReference reference)
 {
     string fpath = string.Empty;
     if (App.LocalDependencies.Keys.Contains(reference.FullName))
     {
         fpath = App.LocalDependencies[reference.FullName];
     }
     else
     {
         Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
         ofd.Filter = "Assembly|" + reference.Name + ".dll";
         if ((bool)ofd.ShowDialog()) fpath = ofd.FileName;
     }
     if (File.Exists(fpath))
     {
         AssemblyDefinition ad;
         try
         {
             ad = AssemblyDefinition.ReadAssembly(fpath);
             ResolvedReferences.Add(fpath);
             App.LocalDependencies.Add(reference.FullName, fpath);
             return ad;
         }
         catch (Exception)
         {
             MessageBox.Show("Unable to read assembly!");
             return ResolveFailure(sender, reference);
         }
     }
     return null;
 }
 IEnumerable<string> SearchDirForMatchingName(AssemblyNameReference assemblyNameReference)
 {
     var fileName = assemblyNameReference.Name + ".dll";
     return ReferenceDictionary.Values
         .Select(x => Path.Combine(Path.GetDirectoryName(x), fileName))
         .Where(File.Exists);
 }
        public AssemblyDefinition[] GetAssembliesByReference(AssemblyNameReference referencedAssemblyName)
        {
            ArgumentUtility.CheckNotNull ("referencedAssemblyName", referencedAssemblyName);

              var trackedAssembly = GetTrackedAssembliesByReference (referencedAssemblyName);
              return trackedAssembly != null ? trackedAssembly.Select(asm => asm.AssemblyDefinition).ToArray() : null;
        }
        /// <summary>
        /// Remove an assembly name reference
        /// </summary>
        /// <param name="anref">Assembly name reference</param>
        public static void Delete(AssemblyNameReference anref)
        {
            IPlugin plugin = PluginFactory.GetInstance();
            ModuleDefinition moddef = null;

            foreach (IAssemblyWrapper wrapper in plugin.GetAssemblies(true))
            {
                if (wrapper.IsValid)
                {
                    if (plugin.IsAssemblyContextLoaded(wrapper.Location))
                    {
                        IAssemblyContext context = plugin.GetAssemblyContext(wrapper.Location);
                        foreach (ModuleDefinition imoddef in context.AssemblyDefinition.Modules)
                        {
                            foreach (AssemblyNameReference ianref in imoddef.AssemblyReferences)
                            {
                                if (anref == ianref)
                                {
                                    moddef = imoddef;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (moddef != null)
            {
                moddef.AssemblyReferences.Remove(anref);
            }
        }
        private bool ShouldRemoveStrongName(AssemblyNameReference reference)
        {
            // Strong name is not present already
            if (reference.PublicKeyToken == null || reference.PublicKeyToken.Length == 0)
            {
                return false;
            }

            // Strong name must be kept
            if (Context.StrongNameReferences.Any(r => r == reference.Name))
            {
                return false;
            }

            AssemblyDefinition assembly;

            try
            {
                // Can't find target assembly
                assembly = Context.AssemblyResolver.Resolve(reference);
            }
            catch (AssemblyResolutionException)
            {
                return false;
            }

            // Don't remove strong name to framework references
            var assemblyDir = NormalizePath(Path.GetDirectoryName(assembly.MainModule.FullyQualifiedName));
            if (Context.FrameworkPaths.Any(path => NormalizePath(path) == assemblyDir))
            {
                return false;
            }

            return true;
        }
Exemple #9
0
		/// <summary>
		/// Determines if two assembly name references matches
		/// </summary>
		/// <param name="anref1">an assembly name reference</param>
		/// <param name="anref2">an assembly name reference to compare</param>
		/// <returns>true if matches</returns>
		public static bool ReferenceMatches(AssemblyNameReference anref1, AssemblyNameReference anref2)
		{
			// Skip Key
			return ((anref1.Name == anref2.Name) &&
			        (String.Compare(anref1.Version.ToString(2), anref2.Version.ToString(2), StringComparison.Ordinal) == 0) &&
			        (anref1.Culture == anref2.Culture));
		}
Exemple #10
0
    public void GetAssembly(string repository, AssemblyDefinition callingAssembly, AssemblyNameReference reference, Action<Stream> callback)
    {
      if (string.IsNullOrWhiteSpace(repository)) throw new ArgumentNullException("repository");
      if (callingAssembly == null) throw new ArgumentNullException("callingAssembly");
      if (reference == null) throw new ArgumentNullException("reference");
      if (callback == null) throw new ArgumentNullException("callback");

      repository = repository.TrimEnd('/');

      var uriString = GetRepositoryAddress(callingAssembly, reference);
      var uri = new Uri(repository + uriString, UriKind.RelativeOrAbsolute);
      var request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(uri);
      request.Method = "GET";
      request.BeginGetResponse(r =>
      {
        try
        {
          var rs = (HttpWebResponse)request.EndGetResponse(r);
          var stream = rs.GetResponseStream();

          Dispatcher.BeginInvoke(() => callback(stream));
        }
        catch (WebException ex)
        {
          Debug.WriteLine(ex.Message);
          Dispatcher.BeginInvoke(() => callback(null));
        }

      }, request);
    }
Exemple #11
0
        private Cecil.IMetadataScope ResolveScope(AnalysisNet.Types.IBasicType basicType)
        {
            if (basicType.ContainingAssembly.Name.Equals("mscorlib"))
            {
                return(Context.CurrentModule.TypeSystem.CoreLibrary);
            }

            if (basicType.ContainingAssembly.Name.Equals("System.Core"))
            {
                //var enumerable = Context.CurrentModule.ImportReference(typeof(Enumerable));
                //var r = enumerable.Module.AssemblyReferences.Where(assembly => assembly.Name.Equals("System.Core")).First();
                //return r;
                Cecil.AssemblyNameReference a = new Cecil.AssemblyNameReference(basicType.ContainingAssembly.Name, new Version(4, 0, 0, 0))
                {
                    PublicKeyToken = new byte[8] {
                        183, 122, 92, 86, 25, 52, 224, 137
                    }
                };
                return(a);
            }

            if (basicType.ContainingAssembly.Name.Equals("System"))
            {
                Cecil.AssemblyNameReference a = new Cecil.AssemblyNameReference(basicType.ContainingAssembly.Name, new Version(4, 0, 0, 0))
                {
                    PublicKeyToken = new byte[8] {
                        183, 122, 92, 86, 25, 52, 224, 137
                    }
                };
                return(a);
            }

            return(null);
        }
        public static FrameworkProfileInfo Parse(XDocument frameworkList)
        {
            var profileInfo = new FrameworkProfileInfo();
            var nameAttr = frameworkList.Root.Attribute("Name");
            profileInfo.Description = (nameAttr != null ? nameAttr.Value : null);
            profileInfo.Assemblies = new HashSet<AssemblyNameReference>(CecilEqualityComparer.Default);

            //frameworkList.Descendants("File").Select(file => AssemblyNameReference.Parse(string.Format("{0}, Version={1}, ",file.Attribute("AssemblyName").Value,)   ))
            foreach (var fileElement in frameworkList.Descendants("File")) {
                var assemblyName = fileElement.Attribute("AssemblyName").Value;

                var versionString = fileElement.Attribute("Version").Value;
                Version version = null;
                if (!Version.TryParse(versionString, out version)) {
                    Trace.WriteLine(string.Format("Warning: Couldn't parse version of the {0} assembly description.", fileElement.ToString()));
                }

                string culture = null;
                var attrib = fileElement.Attribute ("Culture");
                if (attrib != null && attrib.Value != "neutral") {
                    culture = attrib.Value;
                }

                var publicKeyTokenString = fileElement.Attribute("PublicKeyToken").Value;
                var publicKeyToken = new byte[publicKeyTokenString.Length / 2];
                for (int j = 0; j < publicKeyToken.Length; j++) {
                    publicKeyToken[j] = Byte.Parse(publicKeyTokenString.Substring(j * 2, 2), NumberStyles.HexNumber);
                }
                var assemblyNameRef = new AssemblyNameReference(assemblyName, version) { Culture = culture, PublicKeyToken = publicKeyToken };
                profileInfo.Assemblies.Add(assemblyNameRef);
            }

            return profileInfo;
        }
Exemple #13
0
        protected static MC.TypeReference TypeReferenceFromString(string fullname)
        {
            string[] split = fullname.Split(',');

            int lastTypeDot = split[0].LastIndexOf('.');

            System.Diagnostics.Debug.Assert(lastTypeDot > 0);
            System.Diagnostics.Debug.Assert(split.Length >= 2);

            string namespc = split[0].Substring(0, lastTypeDot).Trim();
            string type    = split[0].Substring(lastTypeDot + 1).Trim();
            string assem   = split[1].Trim();

            string  culture = string.Empty;
            Version version = new Version();

            for (int i = 2; i < split.Length; i++)
            {
                string val = split[i].Trim();
                if (val.StartsWith("Version="))
                {
                    version = new Version(val.Substring(8));
                }
                else if (val.StartsWith("Culture="))
                {
                    culture = val.Substring(8);
                }
                //PublicKeyToken=
            }

            MC.AssemblyNameReference itemAssem = new MC.AssemblyNameReference(assem, culture, version);
            return(new MC.TypeReference(type, namespc, itemAssem, false));
        }
        private void RewriteAssemblyReference(AssemblyNameReference reference)
        {
            try
            {
                if (ShouldRewriteToWinmdReference(reference))
                {
                    Context.RewriteTarget = true;
                    reference.Version = new Version(255, 255, 255, 255);
                    reference.IsWindowsRuntime = true;
                }

                var assembly = Context.AssemblyResolver.Resolve(reference);

                if ((reference.IsWindowsRuntime != assembly.Name.IsWindowsRuntime) || (IsFrameworkAssembly(assembly) && ShouldRewriteFrameworkReference(reference, assembly)))
                {
                    Context.RewriteTarget = true;
                    reference.Version = assembly.Name.Version;
                    reference.PublicKeyToken = Copy(assembly.Name.PublicKeyToken);
                    reference.IsWindowsRuntime = assembly.Name.IsWindowsRuntime;
                }

            }
            catch (AssemblyResolutionException)
            {
            }
        }
Exemple #15
0
        public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            return Cache.GetOrCreate(name.FullName, () => base.Resolve(name, parameters));
        }
 public WindowsRuntimeProjectionsComponent()
 {
     AssemblyNameReference reference = new AssemblyNameReference("Windows", new Version(0xff, 0xff, 0xff, 0xff)) {
         IsWindowsRuntime = true
     };
     this._windowsAssemblyReference = reference;
 }
        public virtual AssemblyDefinition Resolve(AssemblyNameReference name)
        {
            AssemblyDefinition assembly;
            string frameworkdir = Path.GetDirectoryName (typeof (object).Module.FullyQualifiedName);

            assembly = SearchDirectory (name, m_directories);
            if (assembly != null)
                return assembly;

            if (IsZero (name.Version)) {
                assembly = SearchDirectory (name, new string [] {frameworkdir});
                if (assembly != null)
                    return assembly;
            }

            #if !CF_1_0 && !CF_2_0
            if (name.Name == "mscorlib") {
                assembly = GetCorlib (name);
                if (assembly != null)
                    return assembly;
            }

            assembly = GetAssemblyInGac (name);
            if (assembly != null)
                return assembly;
            #endif

            assembly = SearchDirectory (name, new string [] {frameworkdir});
            if (assembly != null)
                return assembly;

            throw new FileNotFoundException ("Could not resolve: " + name);
        }
 public Tuple<TypeDefinition, AssemblyDefinition> this[TypeReference typ, AssemblyNameReference assembly]
 {
     get
       {
     return typ == null ? null : this[assembly.BuildAssemblyQualifiedName (typ)];
       }
 }
Exemple #19
0
 static string GetAssemblyFile(AssemblyNameReference reference, string prefix, string gac)
 {
     var gac_folder = new StringBuilder().Append(prefix).Append(reference.Version).Append("__");
     for (int i = 0; i < reference.PublicKeyToken.Length; i++)
         gac_folder.Append(reference.PublicKeyToken[i].ToString("x2"));
     return Path.Combine(Path.Combine(Path.Combine(gac, reference.Name), gac_folder.ToString()), reference.Name + ".dll");
 }
        /// <summary>
        /// Attempts to resolve the assembly by searching for it in the specified directories.
        /// </summary>
        /// <param name="name">The reference name of the assembly.</param>
        /// <returns>The definition of the assembly.</returns>
        /// <exception cref="AssemblyResolutionException">The assembly wasn't found in any of the listed directories.</exception>
        public override AssemblyDefinition Resolve(AssemblyNameReference name)
        {
            try
            {
                return base.Resolve(name);
            }
            catch (AssemblyResolutionException)
            {
                Trace.WriteLine("Second-chance attempt to resolve assembly " + name.FullName + "...");
                var definitions = from dirPath in this.paths
                                  let filePath = Path.Combine(dirPath, name.Name + ".dll")
                                  where File.Exists(filePath)
                                  let definition = AssemblyDefinition.ReadAssembly(filePath)
                                  where definition.FullName == name.FullName
                                  select definition;

                var match = definitions.SingleOrDefault();
                if (match != null)
                {
                    Trace.WriteLine("Assembly " + name.FullName + " was resolved.");
                    return match;
                }

                Trace.WriteLine("Failed to resolve assembly " + name.FullName + ".");
                throw;
            }
        }
Exemple #21
0
 /// <summary>
 /// Resolve an assembly by name.
 /// </summary>
 public AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return Resolve(name, new ReaderParameters(ReadingMode.Deferred) {
         AssemblyResolver = this,
         ReadSymbols = true,
     });
 }
Exemple #22
0
        public CLRHandler(XaeiOSCompiler compiler)
        {
            _compiler = compiler;

            // TODO: Initialize _mscorlib by CLR version and from path
            _mscorlib = CoreTypes.Corlib.Name;
        }
Exemple #23
0
		public void NoBuildOrMajor ()
		{
			var name = new AssemblyNameReference ("Foo", new Version (0, 0));
			Assert.AreEqual ("Foo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", name.FullName);

			name = new AssemblyNameReference ("Foo", new Version (0, 0, 0));
			Assert.AreEqual ("Foo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", name.FullName);
		}
Exemple #24
0
 public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
 {
     var assembly = ResolveInFolder(localFolder, name, parameters);
     if (assembly != null) return assembly;
     assembly = ResolveInFolder(frameworkFolder, name, parameters);
     if (assembly != null) return assembly;
     throw new AssemblyResolutionException(name);
 }
		AssemblyNameReference GetAssemblyReference (AssemblyNameReference refer)
		{
			foreach (AssemblyNameReference aref in Target.MainModule.AssemblyReferences) {
				if (aref.Name == refer.Name)
					return aref;
			}
			throw new ArgumentException ("Can't found AssemblyReference : " + refer.Name);
		}
		AssemblyNameReference GetAssemblyNameReference (AssemblyNameReference asm)
		{
			foreach (AssemblyNameReference reference in m_module.AssemblyReferences)
				if (reference.FullName == asm.FullName)
					return reference;

			return null;
		}
 public AssemblyDefinition Resolve(Mono.Cecil.AssemblyNameReference name)
 {
     if (!_cecilCache.TryGetValue(name.Name, out var assembly))
     {
         throw new Exception($"Assembly {name.Name} was not found in cache.");
     }
     return(assembly);
 }
 private static void RemoveStrongName(AssemblyNameReference name)
 {
     name.PublicKey = null;
     name.PublicKeyToken = new byte[0];
     name.HasPublicKey = false;
     name.Flags &= ~AssemblyFlags.PublicKey;
     name.HashAlgorithm = AssemblyHashAlgorithm.None;
 }
        public IMetadataScope Resolve(ModuleDefinition module, AssemblyNameReference assembly)
        {
            if (assembly.Name == module.Assembly.Name.Name)
            {
                return module;
            }

            return assembly;
        }
Exemple #30
0
 public Csvm(IDeobfuscatorContext deobfuscatorContext, ModuleDefinition module, Csvm oldOne)
 {
     this.deobfuscatorContext = deobfuscatorContext;
     this.module = module;
     if (oldOne.resource != null)
         this.resource = (EmbeddedResource)module.Resources[oldOne.module.Resources.IndexOf(oldOne.resource)];
     if (oldOne.vmAssemblyReference != null)
         this.vmAssemblyReference = module.AssemblyReferences[oldOne.module.AssemblyReferences.IndexOf(oldOne.vmAssemblyReference)];
 }
Exemple #31
0
		AssemblyNameReference GetAssemblyName (I18nAssemblies assembly)
		{
			AssemblyNameReference name = new AssemblyNameReference ("I18N", GetCorlibVersion ());
			if (assembly != I18nAssemblies.Base)
				name.Name += "." + assembly;

			name.PublicKeyToken = _pktoken;
			return name;
		}
        public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            if (!_loadedAssemblies.ContainsKey(name))
            {
                return base.Resolve(name, parameters);
            }

            return _loadedAssemblies[name];
        }
 public AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     var fileName = Path.Combine(Directory, name.Name) + ".dll";
     if (File.Exists(fileName))
     {
         return AssemblyDefinition.ReadAssembly(fileName);
     }
     var codeBase = Assembly.Load(name.FullName).CodeBase.Replace("file:///", "");
     return AssemblyDefinition.ReadAssembly(codeBase);
 }
        public static bool IsSystem(MethodReference rf)
        {
            if (IsExternalCall(rf))
            {
                Mono.Cecil.AssemblyNameReference assemRef = (Mono.Cecil.AssemblyNameReference)rf.DeclaringType.Scope;

                if (CodeProperties.IsSystemSigned(assemRef.PublicKeyToken))
                {
                    return true;
                }
            }
            return false;
        }
        public AssemblyDefinition Resolve(Mono.Cecil.AssemblyNameReference name, ReaderParameters parameters)
        {
            AssemblyNameReference n = AssemblyNameReference.Parse(name.FullName);

            string text = FindAssemblyFile(n);

            if (text == null)
            {
                if (throwOnError)
                {
                    throw new AssemblyResolutionException(n);
                }
                return(null);
            }
            return(GetAssembly(text, parameters));
        }
        public virtual AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (parameters == null)
            {
                parameters = new ReaderParameters();
            }

            var assembly = SearchDirectory(name, directories, parameters);

            if (assembly != null)
            {
                return(assembly);
            }

#if !SILVERLIGHT && !CF
            var framework_dir = Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName));

            if (IsZero(name.Version))
            {
                assembly = SearchDirectory(name, new [] { framework_dir }, parameters);
                if (assembly != null)
                {
                    return(assembly);
                }
            }

            if (name.Name == "mscorlib")
            {
                assembly = GetCorlib(name, parameters);
                if (assembly != null)
                {
                    return(assembly);
                }
            }

            assembly = GetAssemblyInGac(name, parameters);
            if (assembly != null)
            {
                return(assembly);
            }

            assembly = SearchDirectory(name, new [] { framework_dir }, parameters);
            if (assembly != null)
            {
                return(assembly);
            }
#endif

            if (ResolveFailure != null)
            {
                assembly = ResolveFailure(this, name);
                if (assembly != null)
                {
                    return(assembly);
                }
            }

            //throw new AssemblyResolutionException (name);
            return(null);
        }
 public AssemblyResolveEventArgs(AssemblyNameReference reference)
 {
     this.reference = reference;
 }
Exemple #38
0
        static AssemblyDefinition GetCorlib(AssemblyNameReference reference)
        {
            SR.AssemblyName corlib = typeof(object).Assembly.GetName();
            if (corlib.Version == reference.Version || IsZero(reference.Version))
            {
                return(AssemblyFactory.GetAssembly(typeof(object).Module.FullyQualifiedName));
            }

            string path = Directory.GetParent(
                Directory.GetParent(
                    typeof(object).Module.FullyQualifiedName).FullName
                ).FullName;

            string runtime_path = null;

            if (OnMono())
            {
                if (reference.Version.Major == 1)
                {
                    runtime_path = "1.0";
                }
                else if (reference.Version.Major == 2)
                {
                    if (reference.Version.Minor == 1)
                    {
                        runtime_path = "2.1";
                    }
                    else
                    {
                        runtime_path = "2.0";
                    }
                }
                else if (reference.Version.Major == 4)
                {
                    runtime_path = "4.0";
                }
            }
            else
            {
                switch (reference.Version.ToString())
                {
                case "1.0.3300.0":
                    runtime_path = "v1.0.3705";
                    break;

                case "1.0.5000.0":
                    runtime_path = "v1.1.4322";
                    break;

                case "2.0.0.0":
                    runtime_path = "v2.0.50727";
                    break;

                case "4.0.0.0":
                    runtime_path = "v4.0.30319";
                    break;
                }
            }

            if (runtime_path == null)
            {
                throw new NotSupportedException("Version not supported: " + reference.Version);
            }

            path = Path.Combine(path, runtime_path);

            if (File.Exists(Path.Combine(path, "mscorlib.dll")))
            {
                return(AssemblyFactory.GetAssembly(Path.Combine(path, "mscorlib.dll")));
            }

            return(null);
        }
Exemple #39
0
 public int IndexOf(AssemblyNameReference value)
 {
     return(List.IndexOf(value));
 }
Exemple #40
0
 public void Add(AssemblyNameReference value)
 {
     List.Add(value);
 }
 public AssemblyResolutionException(AssemblyNameReference reference)
     : base(string.Format("Failed to resolve assembly: '{0}'", reference))
 {
     this.reference = reference;
 }
 public virtual void VisitAssemblyNameReference(AssemblyNameReference name)
 {
 }
Exemple #43
0
 public bool Contains(AssemblyNameReference value)
 {
     return(List.Contains(value));
 }
        public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
        {
            var references = module.AssemblyReferences;

            for (int i = 0; i < references.Count; i++)
            {
                var reference = references [i];
                if (!Equals(name_reference, reference))
                {
                    continue;
                }

                assembly_reference = reference;
                return(true);
            }

            assembly_reference = null;
            return(false);
        }
        public AssemblyResolveEventArgs(AssemblyNameReference reference, TargetArchitecture architecture)
        {
            this.reference = reference;

            this.architecture = architecture;
        }
        AssemblyDefinition GetCorlib(AssemblyNameReference reference, ReaderParameters parameters)
        {
            var version = reference.Version;
            var corlib  = typeof(object).Assembly.GetName();

            if (corlib.Version == version || IsZero(version))
            {
                return(GetAssembly(typeof(object).Module.FullyQualifiedName, parameters));
            }

            var path = Directory.GetParent(
                Directory.GetParent(
                    typeof(object).Module.FullyQualifiedName).FullName
                ).FullName;

            if (on_mono)
            {
                if (version.Major == 1)
                {
                    path = Path.Combine(path, "1.0");
                }
                else if (version.Major == 2)
                {
                    if (version.MajorRevision == 5)
                    {
                        path = Path.Combine(path, "2.1");
                    }
                    else
                    {
                        path = Path.Combine(path, "2.0");
                    }
                }
                else if (version.Major == 4)
                {
                    path = Path.Combine(path, "4.0");
                }
                else
                {
                    throw new NotSupportedException("Version not supported: " + version);
                }
            }
            else
            {
                switch (version.Major)
                {
                case 1:
                    if (version.MajorRevision == 3300)
                    {
                        path = Path.Combine(path, "v1.0.3705");
                    }
                    else
                    {
                        path = Path.Combine(path, "v1.0.5000.0");
                    }
                    break;

                case 2:
                    path = Path.Combine(path, "v2.0.50727");
                    break;

                case 4:
                    path = Path.Combine(path, "v4.0.30319");
                    break;

                default:
                    throw new NotSupportedException("Version not supported: " + version);
                }
            }

            var file = Path.Combine(path, "mscorlib.dll");

            if (File.Exists(file))
            {
                return(GetAssembly(file, parameters));
            }

            return(null);
        }
Exemple #47
0
        /*Telerik Authorship*/
        private AssemblyDefinition Resolve(AssemblyNameReference name, string defaultPath, ReaderParameters parameters, TargetArchitecture architecture, SpecialTypeAssembly special, bool bubbleToUserIfFailed, bool addToFailedCache = true)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (parameters == null)
            {
                parameters = new ReaderParameters(this);
            }

            /*Telerik Authorship*/
            AssemblyStrongNameExtended assemblyKey = new AssemblyStrongNameExtended(name.FullName, architecture, special);

            if (assemblyPathResolver.IsFailedAssembly(assemblyKey))
            {
                return(null);
            }

            AssemblyDefinition assembly =
                GetFromResolvedAssemblies(new AssemblyName(name.Name, name.FullName, name.Version, name.PublicKey)
            {
                TargetArchitecture = architecture
            }, special);

            if (assembly != null)
            {
                return(assembly);
            }

            /*Telerik Authorship*/
            // This code has been added by Mono.Cecil 0.9.6. It has been commented, because retargetable references should be further
            // researched and handled appropriately across the application. TP item N. 323383
            //if (name.IsRetargetable)
            //{
            //	// if the reference is retargetable, zero it
            //	name = new AssemblyNameReference(name.Name, new Version(0, 0, 0, 0))
            //	{
            //		PublicKeyToken = Empty<byte>.Array,
            //	};
            //}

            assembly = SearchDirectory(name, parameters, architecture, defaultPath) ?? TryGetTargetAssembly(name, parameters, architecture, assemblyKey);

            if (assembly != null)
            {
                if (!filePathToAssemblyDefinitionCache.ContainsKey(assembly.MainModule.FilePath))
                {
                    AddToResolvedAssemblies(assembly);
                }
                return(assembly);
            }
            assembly = GetTargetAssembly(name, parameters, architecture);
            if (assembly != null)
            {
                if (!filePathToAssemblyDefinitionCache.ContainsKey(assembly.MainModule.FilePath))
                {
                    AddToResolvedAssemblies(assembly);
                }
                return(assembly);
            }
            if (bubbleToUserIfFailed)
            {
                return(UserSpecifiedAssembly(name, architecture, assemblyKey));
            }
            else if (addToFailedCache)
            {
                assemblyPathResolver.AddToUnresolvedCache(assemblyKey);
            }
            return(null);
        }
Exemple #48
0
        public virtual AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
        {
            Mixin.CheckName(name);
            Mixin.CheckParameters(parameters);

            var assembly = SearchDirectory(name, directories, parameters);

            if (assembly != null)
            {
                return(assembly);
            }

            if (name.IsRetargetable)
            {
                // if the reference is retargetable, zero it
                name = new AssemblyNameReference(name.Name, Mixin.ZeroVersion)
                {
                    PublicKeyToken = Empty <byte> .Array,
                };
            }

            var framework_dir = Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName);

            if (IsZero(name.Version))
            {
                assembly = SearchDirectory(name, new [] { framework_dir }, parameters);
                if (assembly != null)
                {
                    return(assembly);
                }
            }

            if (name.Name == "mscorlib")
            {
                assembly = GetCorlib(name, parameters);
                if (assembly != null)
                {
                    return(assembly);
                }
            }

            assembly = GetAssemblyInGac(name, parameters);
            if (assembly != null)
            {
                return(assembly);
            }

            assembly = SearchDirectory(name, new [] { framework_dir }, parameters);
            if (assembly != null)
            {
                return(assembly);
            }

            if (ResolveFailure != null)
            {
                assembly = ResolveFailure(this, name);
                if (assembly != null)
                {
                    return(assembly);
                }
            }

            throw new AssemblyResolutionException(name);
        }
Exemple #49
0
        public IList <ItemToolboxNode> Load(LoaderContext ctx, string filename)
        {
            MC.AssemblyDefinition        assem    = MC.AssemblyFactory.GetAssembly(filename);
            Mono.Linker.AssemblyResolver resolver = new Mono.Linker.AssemblyResolver();
            assem.Resolver = resolver;

            //Grab types that should be in System.dll
            Version runtimeVersion;

            switch (assem.Runtime)
            {
            case MC.TargetRuntime.NET_1_0:
            case MC.TargetRuntime.NET_1_1:
                runtimeVersion = new Version(1, 0, 5000, 0); break;

            case MC.TargetRuntime.NET_2_0:
                runtimeVersion = new Version(2, 0, 0, 0); break;

            default:
                throw new NotSupportedException("Runtime '" + assem.Runtime + "' is not supported.");
            }

            MC.AssemblyNameReference sysAssem = new MC.AssemblyNameReference("System", string.Empty, runtimeVersion);
            MC.TypeReference         toolboxItemType
                = new MC.TypeReference("ToolboxItemAttribute", "System.ComponentModel", sysAssem, false);
            MC.TypeReference categoryType
                = new MC.TypeReference("CategoryAttribute", "System.ComponentModel", sysAssem, false);

            if (resolver.Resolve(toolboxItemType) == null)
            {
                return(null);
            }

            List <ItemToolboxNode> list = new List <ItemToolboxNode> ();

            foreach (MC.ModuleDefinition module in assem.Modules)
            {
                foreach (MC.TypeDefinition typedef in module.Types)
                {
                    //only show visible concrete classes
                    if (typedef.IsAbstract || !typedef.IsClass || !typedef.IsPublic)
                    {
                        continue;
                    }

                    MC.TypeDefinition toolboxItem = null;
                    string            category    = null;

                    //find the ToolboxItem and Category attributes
                    foreach (MC.CustomAttribute att in AllCustomAttributes(resolver, typedef))
                    {
                        //find the value of the toolbox attribute
                        if (toolboxItem == null &&
                            IsEqualOrSubclass(resolver, att.Constructor.DeclaringType, toolboxItemType))
                        {
                            //check if it's ToolboxItemAttribute(false) (or null)
                            att.Resolve();
                            IList args = GetArgumentsToBaseConstructor(att, toolboxItemType);
                            if (args != null)
                            {
                                if (args.Count != 1)
                                {
                                    throw new InvalidOperationException("Malformed toolboxitem attribute");
                                }
                                object o = args[0];
                                if (o == null || (o is bool && ((bool)o) == false))
                                {
                                    break;
                                }
                                else
                                {
                                    //w have a type name for the toolbox item. try to resolve it
                                    string typeName = (string)o;
                                    toolboxItem = null;
                                    try {
                                        resolver.Resolve(TypeReferenceFromString(typeName));
                                    } catch (Exception ex) {
                                        System.Diagnostics.Debug.WriteLine(ex);
                                    }
                                    if (toolboxItem == null)
                                    {
                                        System.Diagnostics.Debug.WriteLine(
                                            "CecilToolboxItemScanner: Error resolving type "
                                            + typeName);
                                        break;
                                    }
                                }
                            }
                        }

                        //find the value of the category attribute
                        if (category == null &&
                            IsEqualOrSubclass(resolver, att.Constructor.DeclaringType, categoryType))
                        {
                            att.Resolve();
                            IList args = GetArgumentsToBaseConstructor(att, categoryType);
                            if (args != null && args.Count == 1)
                            {
                                category = (string)args[0];
                            }
                            else
                            {
                                throw new InvalidOperationException("Malformed category attribute");
                            }
                        }

                        if (toolboxItem != null && category != null)
                        {
                            break;
                        }
                    }

                    if (toolboxItem == null)
                    {
                        continue;
                    }

                    Load(assem, typedef, toolboxItem, category);
                }
            }

            return(list);
        }
Exemple #50
0
 public virtual AssemblyDefinition Resolve(AssemblyNameReference name)
 {
     return(Resolve(name, new ReaderParameters()));
 }
Exemple #51
0
        private bool TryGetAssemblyNameReference(AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
        {
            Collection <AssemblyNameReference> assemblyReferences = this.module.AssemblyReferences;

            for (int i = 0; i < assemblyReferences.Count; i++)
            {
                AssemblyNameReference item = assemblyReferences[i];
                if (name_reference.FullName == item.FullName)
                {
                    assembly_reference = item;
                    return(true);
                }
            }
            assembly_reference = null;
            return(false);
        }
 public AssemblyDefinition Resolve(Mono.Cecil.AssemblyNameReference name, ReaderParameters parameters)
 {
     throw new NotSupportedException();
 }
 public Mono.Cecil.AssemblyDefinition Resolve(Mono.Cecil.AssemblyNameReference name)
 {
     return(Resolve(name, new Mono.Cecil.ReaderParameters(Mono.Cecil.ReadingMode.Deferred)));
 }
 public Mono.Cecil.AssemblyDefinition Resolve(Mono.Cecil.AssemblyNameReference reference, Mono.Cecil.ReaderParameters parameters)
 {
     return(ResolveAssemblyByLocation(GetReferenceLocation(reference.Name), parameters));
 }
 int IEqualityComparer <AssemblyNameReference> .GetHashCode(AssemblyNameReference obj)
 {
     return(obj != null?obj.Name.GetHashCode() : 0);
 }
Exemple #56
0
    public static int Main(string[] args)
    {
        string coreclr_dir          = ".";
        string input_assembly_name  = null;
        string output_assembly_name = null;
        bool   force = false;

        for (int i = 0; i < args.Length; i++)
        {
            switch (args [i])
            {
            case "--coreclr":
            case "-c":
                coreclr_dir = args [++i];
                break;

            case "-v":
                Verbose = true;
                break;

            case "-f":
                force = true;
                break;

            case "--":
                i++;
                goto default;

            default:
                input_assembly_name  = args [i++];
                output_assembly_name = args [i];
                if (i != args.Length - 1)
                {
                    return(Usage());
                }
                break;
            }
        }


        Log("Converting {0} => {1}", input_assembly_name, output_assembly_name);

        if (input_assembly_name == null || output_assembly_name == null)
        {
            return(Usage());
        }

        // Step 1.
        // Process all CoreCLR assemblies, build a type=>assembly mapping.


        Log("Scanning the CoreCLR libraries at {0}...", coreclr_dir);

        var coreclr_dlls = Directory.GetFiles(coreclr_dir, "System.*.dll");

        var type2as            = new Dictionary <string, string> ();
        var netcore_assemblies = new Dictionary <string, AssemblyNameReference> ();

        foreach (var netcore_dll_path in coreclr_dlls)
        {
//			if (coreclr_dll.IndexOf (".Private.") != -1)
//				continue;

            var netcore_dll_name = Path.GetFileName(netcore_dll_path);
            netcore_dll_name = netcore_dll_name.Substring(0, netcore_dll_name.Length - 4);

            Log("  A {0}", netcore_dll_name);

            var assembly = Mono.Cecil.AssemblyDefinition.ReadAssembly(netcore_dll_path);

            var assembly_reference = new Mono.Cecil.AssemblyNameReference(netcore_dll_name, assembly.Name.Version);

            var token = assembly.Name.PublicKeyToken;
            Log("    publickeytoken = {0}", String.Join(" ", token.Select(b => b.ToString("X2")).ToArray()));
            assembly_reference.PublicKeyToken = assembly.Name.PublicKeyToken;

            netcore_assemblies [netcore_dll_name] = assembly_reference;

            foreach (var module in assembly.Modules)
            {
                Log("    M {0}", module.Name);

                foreach (var type in module.ExportedTypes.Select(et => et.FullName).Concat(module.Types.Select(t => t.FullName)))
                {
                    Log("      T {0}", type);

                    if (type2as.ContainsKey(type))
                    {
                        Log("      Warning: Type {0} already exists in another assembly {1}", type, type2as [type]);
                        // Seems like a fairly common thing for whatever reason. Intentional or not?
                        // threw new Exception ();
                    }
                    type2as [type] = netcore_dll_name;
                }
            }
        }

        // Step 2.
        // Scan the input assembly, replace all references to the appropriate .NET Core libs.

        Log("\n\nA {0}", input_assembly_name);

        var input_assembly = Mono.Cecil.AssemblyDefinition.ReadAssembly(input_assembly_name);

        Log("Processing the modules...");

        foreach (var module in input_assembly.Modules)
        {
            {
                Log("  M {0}", module.Name);
                Log("  Replacing assembly references in types...");
            }

            foreach (var type in module.GetTypeReferences())
            {
                if (Verbose)
                {
                    Console.Write("    T {0} S {1} => ", type.FullName, type.Scope.Name);
                }

                if (type.Scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)
                {
                    Log("[unexpected scope, skipping]");
                    continue;
                }

                if (type.FullName.IndexOf("System.") == -1)
                {
                    Log("[not in mscorlib, skipping]");
                    continue;
                }

                // Replace the reference & update scope.
                string clean_name = type.FullName;
                try {
                    var generic_pos = clean_name.IndexOf('/');
                    if (generic_pos != -1)
                    {
                        clean_name = clean_name.Substring(0, generic_pos);
                    }

                    var netcore_assembly = netcore_assemblies [type2as [clean_name]];

                    if (!module.AssemblyReferences.Contains(netcore_assembly))
                    {
                        module.AssemblyReferences.Add(netcore_assembly);
                    }
                    type.Scope = netcore_assembly;

                    Log("A {0}", type2as [clean_name] + ".dll");
                }
                catch (KeyNotFoundException) {
                    Console.Error.WriteLine("Error: Type {0}(https://dotnet.github.io/api/{0}.html) not found in any assembly provided.", clean_name);
                    Console.Error.WriteLine("       Perhaps you forgot to get the correct NuGet package or it's not supported by .NET Core?");
                    if (!force)
                    {
                        return(3);
                    }
                }
            }

            // Remove default mscorlib
            try {
                module.AssemblyReferences.Remove(module.AssemblyReferences.SingleOrDefault(a => a.Name == "mscorlib"));
            } catch (System.InvalidOperationException) {
                // Not present
            }
        }

        input_assembly.Write(output_assembly_name);

        Log("Success.");

        return(0);
    }
Exemple #57
0
 public virtual AssemblyDefinition Resolve(string fullName)
 {
     return(Resolve(AssemblyNameReference.Parse(fullName)));
 }
Exemple #58
0
 public void Insert(int index, AssemblyNameReference value)
 {
     List.Insert(index, value);
 }
Exemple #59
0
 public void Remove(AssemblyNameReference value)
 {
     List.Remove(value);
 }
 public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference)
     : base(name, flags)
 {
     this.reference = reference;
 }