示例#1
0
 internal void StoreExportedType(IMetadataScope scope, String fullName, TypeReference exportedTo)
 {
     if (scope != null)
     {
         exportMappings[GetTypeKey(scope, fullName)] = exportedTo;
     }
 }
示例#2
0
 /// <summary>
 /// Add the given message to the log.
 /// </summary>
 private void Log(MessageTypes type, string member, IMetadataScope scope, string msg)
 {
     if (IsDisposed) return;
     if (InvokeRequired)
     {
         Invoke(new Action<MessageTypes, string, IMetadataScope, string>(Log), type, member, scope, msg);
     }
     else
     {
         if ((type >= MessageTypes.MissingFirst) && (type <= MessageTypes.MissingLast))
         {
             MemberNode node;
             if (!nodes.TryGetValue(member, out node))
             {
                 node = new MemberNode(member, scope, type);
                 node.ImageIndex = (int) type;
                 nodes.Add(member, node);
                 tvList.Nodes.Add(node);
             }
             node.Messages.Add(msg);
             if (node == tvList.SelectedNode)
             {
                 tvUsedIn.Nodes.Add(new TreeNode(msg));
             }
         }
         else
         {
             tvLog.Nodes.Add(new TreeNode(msg) { ImageIndex = (int) type });
         }
         miCopy.Enabled = (tvList.Nodes.Count > 0);
     }
 }
 public ExportedType(string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
 {
     this.@namespace = @namespace;
     this.name = name;
     this.scope = scope;
     this.module = module;
 }
示例#4
0
 internal static string GetScopeName(IMetadataScope scope)
 {
     if (scope is AssemblyNameReference)
         return ((AssemblyNameReference)scope).Name;
     if (scope is ModuleDefinition)
         return ((ModuleDefinition) scope).Assembly.Name.Name;
     throw new Exception("Unsupported scope: " + scope);
 }
示例#5
0
        public static MModule getModule(IMetadataScope scope)
        {
            if (scope is ModuleDefinition)
                return getModule((ModuleDefinition)scope);
            else if (scope is AssemblyNameReference)
                return getModule((AssemblyNameReference)scope);

            return null;
        }
 public ProjectReference FindProjectReference(IMetadataScope scope)
 {
     if (scope == null)
         return null;
     string assemblyFullName = scope.AssemblyFullName();
     return References.FirstOrDefault(
         item => string.
             Equals(item.FullName, assemblyFullName, StringComparison.InvariantCultureIgnoreCase));
 }
 private static AssemblyNameReference GetReference(IMetadataScope scope)
 {
     ModuleDefinition definition = scope as ModuleDefinition;
     if (definition != null)
     {
         return definition.Assembly.Name;
     }
     return (AssemblyNameReference) scope;
 }
示例#8
0
 internal static string GetScopeName(IMetadataScope scope)
 {
     string scopeStr = null;
     if (scope is AssemblyNameReference)
         scopeStr = ((AssemblyNameReference) scope).Name;
     if (scope is ModuleDefinition)
         scopeStr = ((ModuleDefinition) scope).Assembly.Name.Name;
     return scopeStr;
 }
示例#9
0
        public APITests () {
            TestModule = ModuleDefinition.CreateModule("TestModule", ModuleKind.NetModule);
            MetadataScope = TestModule;

            T1 = new TypeReference("namespace", "Type1", TestModule, MetadataScope);
            T1_2 = new TypeReference("namespace", "Type1", TestModule, MetadataScope);
            T2 = new TypeReference("namespace", "Type2", TestModule, MetadataScope);
            T3 = new TypeReference("namespace2", "Type1", TestModule, MetadataScope);
        }
示例#10
0
 public static TypeReference FindType(this ModuleDefinition currentModule, string @namespace, string typeName, IMetadataScope scope = null, params string[] typeParameters)
 {
     var result = new TypeReference(@namespace, typeName, currentModule, scope);
     foreach (var typeParameter in typeParameters)
     {
         result.GenericParameters.Add(new GenericParameter(typeParameter, result));
     }
     return result;
 }
示例#11
0
 public static AssemblyNameReference GetAssemblyNameReference(IMetadataScope scope)
 {
     switch (scope.MetadataScopeType)
     {
         case MetadataScopeType.AssemblyNameReference:
             return (AssemblyNameReference)scope;
         case MetadataScopeType.ModuleDefinition:
             return ((ModuleDefinition)scope).Assembly.Name;
         default:
             return null;
     }
 }
 /// <summary>
 /// Returns the <see cref="AssemblyNameReference"/> associated with the <see cref="IMetadataScope"/>
 /// </summary>
 /// <param name="scope">A <see cref="IMetadataScope"/></param>
 /// <returns>The associated <see cref="AssemblyNameReference"/></returns>
 private static AssemblyNameReference GetAssemblyFromScope(IMetadataScope scope)
 {
     switch (scope.MetadataScopeType)
     {
         case MetadataScopeType.AssemblyNameReference:
             return (AssemblyNameReference)scope;
         case MetadataScopeType.ModuleDefinition:
             return ((ModuleDefinition) scope).Assembly.Name;
         default:
             throw new NotSupportedException();
     }
 }
示例#13
0
        static AssemblyNameReference GetAssemblyNameReference(IMetadataScope scope)
        {
            AssemblyNameReference reference;
            if (scope is ModuleDefinition)
            {
                AssemblyDefinition asm = ((ModuleDefinition)scope).Assembly;
                reference = asm.Name;
            }
            else
                reference = (AssemblyNameReference)scope;

            return reference;
        }
示例#14
0
        /// <summary>
        /// Are the given scopes the same?
        /// </summary>
        public static bool AreSame(this IMetadataScope x, IMetadataScope y)
        {
            // Both null?
            if ((x == null) && (y == null)) { return true; }

            // One null, other not null
            if ((x == null) || (y == null)) { return false; }

            var nx = GetName(x);
            var ny = GetName(y);

            return (nx == ny);
        }
示例#15
0
        IMetadataScope ImportScope(IMetadataScope scope)
        {
            switch (scope.MetadataScopeType)
            {
                case MetadataScopeType.AssemblyNameReference:
                    return ImportAssemblyName((AssemblyNameReference)scope);
                case MetadataScopeType.ModuleDefinition:
                    return ImportAssemblyName(((ModuleDefinition)scope).Assembly.Name);
                case MetadataScopeType.ModuleReference:
                    throw new NotImplementedException();
            }

            throw new NotSupportedException();
        }
示例#16
0
 public IMetadataScope GetLoggerAdapterMetadataScope()
 {
     if (_loggerScope == null)
     {
         //Check if reference to adapter assembly is present. If not, add it (we only look for the name, we assume that different versions are backward compatible)
         var loggerReference = _moduleDefinition.AssemblyReferences.FirstOrDefault(assRef => assRef.Name.Equals(_configuration.AssemblyNameReference.Name));
         if (loggerReference == null)
         {
             loggerReference = _configuration.AssemblyNameReference;
             _moduleDefinition.AssemblyReferences.Add(loggerReference);
         }
         _loggerScope = loggerReference;
     }
     return _loggerScope;
 }
        internal TypeReference Import(ModuleDefinition module, IMetadataScope scope, IInjector injector)
        {
            var reference = new TypeReference(
                ParentType == null ? Attr.Namespace : "",
                InjecteeType.Name,
                module,
                module.ImportScope(injector.MapMetadataScope(scope)),
                InjecteeType.IsValueType);

            MetadataSystem.TryProcessPrimitiveTypeReference(reference);

            if (ParentType != null)
            {
                var declDef = module.FindMatchingType(ParentType, true);
                reference.DeclaringType = CreateDeclRef(declDef, module, injector);
            }

            if (InjecteeType.ContainsGenericParameters)
                CecilHelpers.ImportGenericParameters(reference, InjecteeType);

            return reference;
        }
示例#18
0
        public ITypeContainer Resolve(IMetadataScope scope)
        {
            AssemblyNameReference assemblyName = scope as AssemblyNameReference;

            if (assemblyName != null)
            {
                var assembly = Assembly.Load(new AssemblyName(assemblyName.FullName));
                return new AssemblyTypeContainer(assembly);
            }

            ModuleDefinition moduleDefinition = scope as ModuleDefinition;

            if (moduleDefinition != null)
            {
                if (moduleDefinition.Assembly != null)
                {
                    var assembly = Assembly.Load(new AssemblyName(moduleDefinition.Assembly.FullName));
                    return new AssemblyTypeContainer(assembly);
                }
            }

            throw new NotImplementedException();
        }
示例#19
0
        /// <summary>
        /// Finds a type reference in the module.
        /// </summary>
        /// <param name="currentModule">The current module.</param>
        /// <param name="namespace">The namespace.</param>
        /// <param name="typeName">Name of the type.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="typeParameters">The type parameters.</param>
        /// <returns>The type reference.</returns>
        public static TypeReference FindType(this ModuleDefinition currentModule, string @namespace, string typeName, IMetadataScope scope = null, params string[] typeParameters)
        {
            var result = new TypeReference(@namespace, typeName, currentModule, scope);

            foreach (var typeParameter in typeParameters)
            {
                result.GenericParameters.Add(new GenericParameter(typeParameter, result));
            }

            return(result);
        }
示例#20
0
        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Usage("Not enough arguments");
                return(ERROR_BAD_COMMAND);
            }

            // control verbosity
            if (args[0] == "--quiet" || args[0] == "-q")
            {
                quiet        = true;
                logger.Level = Logger.LogLevel.WARNING;
                args         = args.Skip(1).ToArray();
            }
            else if (args[0] == "--debug")
            {
                logger.Level = Logger.LogLevel.DEBUG;
                args         = args.Skip(1).ToArray();
            }

            // again, check if we have enough arguments
            if (args.Length < 1)
            {
                Usage("Not enough arguments");
                return(ERROR_BAD_COMMAND);
            }

            // should we return an error code if pinvokes exist?

            bool treatPInvokeAsError = false;

            if (args[0] == "--treat-pinvoke-as-error")
            {
                treatPInvokeAsError = true;
                args = args.Skip(1).ToArray();
            }

            // again, check if we have enough arguments
            if (args.Length < 1)
            {
                Usage("Not enough arguments");
                return(ERROR_BAD_COMMAND);
            }

            // first arg is the path to the main assembly being processed
            string fileName = args[0];

            if (!File.Exists(fileName))
            {
                // if the file doesn't exist, it might be a directory
                // TODO: handle directories
                if (Directory.Exists(fileName))
                {
                    logger.Error("{0} appears to be a directory; .NET assemblies only, please.", fileName);
                    return(ERROR_NOT_DOTNET);
                }
                logger.Error("Couldn't find {0}. Are you sure it exists?", fileName);
                return(ERROR_NOT_THERE);
            }

            // check that the main file is a dot net assembly
            // this gives a clearer error message than the "one or more..." error
            try
            {
                System.Reflection.AssemblyName.GetAssemblyName(fileName);
            }
            catch (System.BadImageFormatException)
            {
                logger.Error("{0} is not a .NET assembly.", fileName);
                return(ERROR_NOT_DOTNET);
            }

            // load module and assembly resolver
            ModuleDefinition       module;
            CustomAssemblyResolver customResolver;

            try
            {
                // second arg and onwards should be paths to reference assemblies
                // instantiate custom assembly resolver that loads reference assemblies into cache
                // note: ONLY these assemblies will be available to the resolver
                customResolver = new CustomAssemblyResolver(args.Skip(1));

                // load the plugin module (with the custom assembly resolver)
                // TODO: perhaps we should load the plugin assembly then iterate through all modules
                module = ModuleDefinition.ReadModule(fileName, new ReaderParameters
                {
                    AssemblyResolver = customResolver
                });
            }
            catch (BadImageFormatException)
            {
                logger.Error("One (or more) of the files specified is not a .NET assembly");
                return(ERROR_NOT_DOTNET);
            }
            catch (FileNotFoundException e)
            {
                logger.Error("Couldn't find {0}. Are you sure it exists?", e.FileName);
                return(ERROR_NOT_THERE);
            }

            if (module.Assembly.Name.Name == "")
            {
                logger.Error("Assembly has no name. This is unexpected.");
                return(ERROR_UNHANDLED_EXCEPTION);
            }

            // extract cached reference assemblies from custom assembly resolver
            // we'll query these later to make sure we only attempt to resolve a reference when the
            // definition is defined in an assembly in this list
            cache = customResolver.Cache;

            // print assembly name
            logger.Info("{0}\n", module.Assembly.FullName);

            // print assembly references (buildtime)
            if (module.AssemblyReferences.Count > 0)
            {
                logger.Info("Assembly references:", module.Assembly.Name.Name);
                foreach (AssemblyNameReference reference in module.AssemblyReferences)
                {
                    logger.Info("  {0}", reference.FullName);
                }
            }
            logger.Info("");

            // print cached assembly names (i.e. runtime references)
            if (args.Length > 1)
            {
                logger.Info("Cached assemblies:");
                foreach (var assembly in args.Skip(1))
                {
                    logger.Info("  {0}", AssemblyDefinition.ReadAssembly(assembly).FullName);
                }
            }
            else // no reference assemblies. Grab the skipping rope
            {
                logger.Warning("Empty resolution cache (no reference assemblies specified)");
            }
            logger.Info("");

            // mixed-mode?
            bool isMixed = (module.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly;

            logger.Info("Mixed-mode? {0}\n", isMixed);

            // global failure/pinvoke trackers for setting return code
            bool failure = false;
            bool pinvoke = false;

            List <TypeDefinition> types = GetAllTypesAndNestedTypes(module.Types);

            // iterate over all the TYPES
            foreach (TypeDefinition type in types)
            {
                Pretty.Class("{0}", type.FullName);

                // iterate over all the METHODS that have a method body
                foreach (MethodDefinition method in type.Methods)
                {
                    Pretty.Method("{0}", method.FullName);
                    if (!method.HasBody) // skip if no body
                    {
                        continue;
                    }

                    // iterate over all the INSTRUCTIONS
                    foreach (var instruction in method.Body.Instructions)
                    {
                        // skip if no operand
                        if (instruction.Operand == null)
                        {
                            continue;
                        }

                        logger.Debug(
                            "Found instruction at {0} with code: {1}",
                            instruction.Offset,
                            instruction.OpCode.Code);

                        string instructionString = instruction.Operand.ToString()          // for sake of consistency
                                                   .Replace("{", "{{").Replace("}", "}}"); // escape curly brackets

                        // get the scope (the name of the assembly in which the operand is defined)
                        IMetadataScope scope = GetOperandScope(instruction.Operand);
                        if (scope != null)
                        {
                            // pinvoke?
                            ModuleReference nativeModule;
                            bool            isPInvoke = IsPInvoke(instruction.Operand, out nativeModule);
                            if (isPInvoke && nativeModule != null)
                            {
                                Pretty.Instruction(ResolutionStatus.PInvoke, nativeModule.Name, instructionString);
                                pinvoke = true;
                                continue;
                            }

                            // skip if scope is not in the list of cached reference assemblies
                            if (!cache.ContainsKey(scope.Name))
                            {
                                Pretty.Instruction(ResolutionStatus.Skipped, scope.Name, instructionString);
                                continue;
                            }
                            logger.Debug("{0} is on the list so let's try to resolve it", scope.Name);
                            logger.Debug(instruction.Operand.ToString());
                            // try to resolve operand
                            // this is the big question - does the field/method/class exist in one of
                            // the cached reference assemblies
                            bool success = TryResolve(instruction.Operand, type);
                            if (success || CheckMultidimensionalArray(instruction, method, type, scope))
                            {
                                Pretty.Instruction(ResolutionStatus.Success, scope.Name, instructionString);
                            }
                            else
                            {
                                Pretty.Instruction(ResolutionStatus.Failure, scope.Name, instructionString);
                                failure = true; // set global failure (non-zero exit code)
                            }
                        }
                    }
                }

                // check that all abstract methods in the base type (where appropriate) have been implemented
                // note: base type resolved against the referenced assemblies
                failure |= CheckAbstractMethods(type) == false;
            }

            // exit code
            if (failure)
            {
                return(ERROR_COMPAT);
            }
            if (pinvoke && treatPInvokeAsError)
            {
                return(ERROR_PINVOKE);
            }

            return(0); // a-ok
        }
示例#21
0
 public TypeReference(string name, string ns, IMetadataScope scope, bool valueType) :
     this(name, ns, scope)
 {
     m_isValueType = valueType;
 }
示例#22
0
        public TypeReference Retarget(TypeReference type, GenericContext context)
        {
            TypeReference reference;

            if (type == null)
            {
                return(type);
            }
            if ((type.IsFunctionPointer || type.IsOptionalModifier) || type.IsSentinel)
            {
                throw new NotImplementedException();
            }
            if (type.IsArray)
            {
                ArrayType type2 = (ArrayType)type;
                ArrayType type3 = new ArrayType(this.Retarget(type2.ElementType, context), type2.Rank);
                for (int i = 0; i < type2.Dimensions.Count; i++)
                {
                    ArrayDimension dimension = type2.Dimensions[i];
                    type3.Dimensions[i] = new ArrayDimension(dimension.LowerBound, dimension.UpperBound);
                }
                reference = type3;
            }
            else if (type.IsByReference)
            {
                ByReferenceType type4 = (ByReferenceType)type;
                reference = new ByReferenceType(this.Retarget(type4.ElementType, context));
            }
            else if (type.IsDefinition && Utility.SameScope(type.Scope, this.Module))
            {
                reference = type;
            }
            else if (type.IsGenericInstance)
            {
                GenericInstanceType type5 = (GenericInstanceType)type;
                GenericInstanceType type6 = new GenericInstanceType(this.Retarget(type5.ElementType, context));
                foreach (TypeReference reference2 in type5.GenericArguments)
                {
                    TypeReference item = this.Retarget(reference2, context);
                    type6.GenericArguments.Add(item);
                }
                reference = type6;
            }
            else
            {
                if (type.IsGenericParameter)
                {
                    GenericParameter parameter = (GenericParameter)type;
                    return(context.Retarget(parameter));
                }
                if (type.IsPinned)
                {
                    PinnedType type7 = (PinnedType)type;
                    reference = new PinnedType(this.Retarget(type7.ElementType, context));
                }
                else if (type.IsPointer)
                {
                    PointerType type8 = (PointerType)type;
                    reference = new PointerType(this.Retarget(type8.ElementType, context));
                }
                else if (type.IsRequiredModifier)
                {
                    RequiredModifierType type9 = (RequiredModifierType)type;
                    reference = new RequiredModifierType(this.Retarget(type9.ModifierType, context), this.Retarget(type9.ElementType, context));
                }
                else
                {
                    reference = type.Resolve();
                    if ((reference == null) && (this.OperationContext.Platform == Platform.UAP))
                    {
                        string fullName = null;
                        string str2     = type.FullName;
                        if ((!(str2 == "System.Collections.ArrayList") && !(str2 == "System.Collections.CollectionBase")) && (!(str2 == "System.Collections.Hashtable") && !(str2 == "System.Collections.Stack")))
                        {
                            if (str2 == "System.Reflection.BindingFlags")
                            {
                                fullName = "System.Reflection.TypeExtensions";
                            }
                        }
                        else
                        {
                            fullName = "System.Collections.NonGeneric";
                        }
                        if (fullName != null)
                        {
                            IMetadataScope scope = type.Scope;
                            type.Scope = AssemblyNameReference.Parse(fullName);
                            reference  = type.Resolve();
                            type.Scope = scope;
                        }
                    }
                }
            }
            return(this.Module.ImportReference(reference));
        }
示例#23
0
 bool isModuleAssembly(IMetadataScope scope)
 {
     return DotNetUtils.isReferenceToModule(module, scope);
 }
        static TypeReference CreateReference(Type type_info, ModuleDefinition module, IMetadataScope scope)
        {
            string @namespace, name;

            SplitFullName(type_info.type_fullname, out @namespace, out name);

            var type = new TypeReference(@namespace, name, module, scope);

            MetadataSystem.TryProcessPrimitiveType(type);

            AdjustGenericParameters(type);

            var nested_names = type_info.nested_names;

            if (nested_names.IsNullOrEmpty())
            {
                return(type);
            }

            for (int i = 0; i < nested_names.Length; i++)
            {
                type = new TypeReference(string.Empty, nested_names [i], module, null)
                {
                    DeclaringType = type,
                };

                AdjustGenericParameters(type);
            }

            return(type);
        }
示例#25
0
 internal void AttachToScope(IMetadataScope scope)
 {
     m_scope = scope;
 }
示例#26
0
        static Exception HandlePipelineProcessException(Exception e)
        {
            switch (e)
            {
            case AssemblyResolutionException are:
                return(new PlatformException(2002, true, are, are.Message));

            case AggregateException ae:
                return(ae);

            case PlatformException pe:
                return(pe);

            case MarkException me:
            {
                var re = me.InnerException as ResolutionException;
                if (re == null)
                {
                    if (me.InnerException != null)
                    {
                        return(ErrorHelper.CreateError(2102, me, Errors.MT2102, me.Method.FullName, me.Method.Module, me.InnerException.Message));
                    }
                    else
                    {
                        return(ErrorHelper.CreateError(2102, me, Errors.MT2102_A, me.Method.FullName, me.Method.Module));
                    }
                }
                else
                {
                    TypeReference  tr    = (re.Member as TypeReference);
                    IMetadataScope scope = tr == null ? re.Member.DeclaringType.Scope : tr.Scope;
                    return(ErrorHelper.CreateError(2101, me, Errors.MT2101, re.Member, me.Method.FullName, scope));
                }
            }

            case ResolutionException re:
            {
                TypeReference  tr    = (re.Member as TypeReference);
                IMetadataScope scope = tr == null ? re.Member.DeclaringType.Scope : tr.Scope;
                return(new PlatformException(2002, true, re, "Failed to resolve \"{0}\" reference from \"{1}\"", re.Member, scope));
            }

            case XmlResolutionException ex:
                return(new PlatformException(2017, true, ex, Errors.MX2017, ex?.InnerException?.Message ?? ex.Message));

            default:
                if (e.InnerException != null)
                {
                    return(HandlePipelineProcessException(e.InnerException));
                }

                var message = new StringBuilder();
                if (e.Data.Count > 0)
                {
                    message.AppendLine();
                    var m = e.Data ["MethodDefinition"] as string;
                    if (m != null)
                    {
                        message.AppendLine($"\tMethod: `{m}`");
                    }
                    var t = e.Data ["TypeReference"] as string;
                    if (t != null)
                    {
                        message.AppendLine($"\tType: `{t}`");
                    }
                    var a = e.Data ["AssemblyDefinition"] as string;
                    if (a != null)
                    {
                        message.AppendLine($"\tAssembly: `{a}`");
                    }
                }
                message.Append($"Reason: {e.Message}");
                return(new PlatformException(2001, true, e, Errors.MX2001, message));
            }
        }
示例#27
0
        bool ResolveAllTypeReferences(AssemblyDefinition assembly)
        {
            if (resolvedTypeReferences == null)
            {
                resolvedTypeReferences = new HashSet <AssemblyDefinition> ();
            }
            if (resolvedTypeReferences.Contains(assembly))
            {
                return(false);
            }
            resolvedTypeReferences.Add(assembly);

            var  hash    = new Dictionary <TypeReference, IMetadataScope> ();
            bool changes = false;

            foreach (TypeReference tr in assembly.MainModule.GetTypeReferences())
            {
                if (hash.ContainsKey(tr))
                {
                    continue;
                }
                if (tr.IsWindowsRuntimeProjection)
                {
                    continue;
                }
                var            td    = tr.Resolve();
                IMetadataScope scope = tr.Scope;
                // at this stage reference might include things that can't be resolved
                // and if it is (resolved) it needs to be kept only if marked (#16213)
                if ((td != null) && Annotations.IsMarked(td))
                {
                    scope = assembly.MainModule.ImportReference(td).Scope;
                    if (tr.Scope != scope)
                    {
                        changes = true;
                    }
                    hash.Add(tr, scope);
                }
            }
            if (assembly.MainModule.HasExportedTypes)
            {
                foreach (var et in assembly.MainModule.ExportedTypes)
                {
                    var            td    = et.Resolve();
                    IMetadataScope scope = et.Scope;
                    if ((td != null) && Annotations.IsMarked(td))
                    {
                        scope = assembly.MainModule.ImportReference(td).Scope;
                        hash.Add(td, scope);
                        et.Scope = scope;
                    }
                }
            }

            // Resolve everything first before updating scopes.
            // If we set the scope to null, then calling Resolve() on any of its
            // nested types would crash.

            foreach (var e in hash)
            {
                e.Key.Scope = e.Value;
            }

            return(changes);
        }
示例#28
0
        public AssemblyDefinition Resolve(IMetadataScope scope)
        {
            AssemblyNameReference reference = GetReference(scope);

            return(_resolver.Resolve(reference));
        }
示例#29
0
 public MessagePackReaderHelper(ModuleDefinition module, IMetadataScope messagePackScope)
 {
     this.typeSystem = module.TypeSystem;
     Nil             = new TypeReference("MessagePack", "Nil", module, messagePackScope, true);
     Reader          = new TypeReference("MessagePack", "MessagePackReader", module, messagePackScope, true);
 }
        private static TypeReference CreateReference(TypeParser.Type type_info, ModuleDefinition module, IMetadataScope scope)
        {
            string str;
            string str1;

            TypeParser.SplitFullName(type_info.type_fullname, out str, out str1);
            TypeReference typeReference = new TypeReference(str, str1, module, scope);

            MetadataSystem.TryProcessPrimitiveTypeReference(typeReference);
            TypeParser.AdjustGenericParameters(typeReference);
            string[] nestedNames = type_info.nested_names;
            if (nestedNames.IsNullOrEmpty <string>())
            {
                return(typeReference);
            }
            for (int i = 0; i < (int)nestedNames.Length; i++)
            {
                typeReference = new TypeReference(string.Empty, nestedNames[i], module, null)
                {
                    DeclaringType = typeReference
                };
                TypeParser.AdjustGenericParameters(typeReference);
            }
            return(typeReference);
        }
示例#31
0
    string StringifyTypeRef(TypeReference t)
    {
        switch (t.MetadataType)
        {
        case MetadataType.Void:
            return("void");

        case MetadataType.Boolean:
            return("bool");

        case MetadataType.Char:
            return("char");

        case MetadataType.SByte:
            return("int8");

        case MetadataType.Byte:
            return("unsigned int8");

        case MetadataType.Int16:
            return("int16");

        case MetadataType.UInt16:
            return("unsigned int16");

        case MetadataType.Int32:
            return("int32");

        case MetadataType.UInt32:
            return("unsigned int32");

        case MetadataType.Int64:
            return("int64");

        case MetadataType.UInt64:
            return("unsigned int64");

        case MetadataType.Single:
            return("float32");

        case MetadataType.Double:
            return("float64");

        case MetadataType.String:
            return("string");

        case MetadataType.IntPtr:
            return("native int");

        case MetadataType.UIntPtr:
            //return "unsigned native int";
            return("[mscorlib]System.UIntPtr");

        case MetadataType.TypedByReference:
            return("typedref");

        case MetadataType.Class:
        case MetadataType.Object:
        case MetadataType.ValueType: {
            var            sb = new StringBuilder();
            IMetadataScope s  = t.Scope;
            if (t.MetadataType == MetadataType.ValueType)
            {
                sb.Append("valuetype ");
            }
            else
            {
                sb.Append("class ");
            }
            EmitScope(s, sb);
            sb.Append(EscapeName(t.FullName));
            return(sb.ToString());
        }

        case MetadataType.Array: {
            ArrayType at = (t as ArrayType);

            if (at.IsVector)
            {
                return(StringifyTypeRef(at.ElementType) + "[]");
            }

            var suffix = new StringBuilder();
            suffix.Append("[");
            for (int i = 0; i < at.Dimensions.Count; i++)
            {
                if (i > 0)
                {
                    suffix.Append(",");
                }

                suffix.Append(at.Dimensions [i].ToString());
            }
            suffix.Append("]");

            return(StringifyTypeRef(at.ElementType) + suffix);
        }

        case MetadataType.Pointer:
            return(StringifyTypeRef((t as TypeSpecification).ElementType) + "*");

        case MetadataType.ByReference:
            return(StringifyTypeRef((t as TypeSpecification).ElementType) + "&");

        case MetadataType.Pinned:
            return(StringifyTypeRef((t as TypeSpecification).ElementType) + " pinned");

        case MetadataType.GenericInstance: {
            var sb   = new StringBuilder();
            var inst = (t as GenericInstanceType);
            sb.Append(StringifyTypeRef(inst.ElementType));
            sb.Append("<");
            int aindex = 0;
            foreach (TypeReference arg in inst.GenericArguments)
            {
                if (aindex > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(StringifyTypeRef(arg));
                aindex++;
            }
            sb.Append(">");
            return(sb.ToString());
        }

        case MetadataType.Var:
            return("!" + (t as GenericParameter).Position);

        case MetadataType.MVar:
            return("!!" + (t as GenericParameter).Position);

        case MetadataType.Sentinel:
            return("..., " + StringifyTypeRef((t as SentinelType).ElementType));

        case MetadataType.RequiredModifier: {
            var mod = (t as RequiredModifierType);
            if (mod.ModifierType.MetadataType != MetadataType.Class)
            {
                throw new NotImplementedException();
            }
            var sb = new StringBuilder();
            sb.Append(StringifyTypeRef(mod.ElementType));
            sb.Append(" modreq (");
            EmitScope(mod.ModifierType.Scope, sb);
            sb.Append(EscapeName(mod.ModifierType.FullName));
            sb.Append(")");
            return(sb.ToString());
        }

        default:
            throw new NotImplementedException("" + t.MetadataType + " " + t.ToString());
        }
    }
示例#32
0
        public static void Process(LinkerOptions options, out MonoTouchLinkContext context, out List <AssemblyDefinition> assemblies)
        {
            var pipeline = CreatePipeline(options);

            foreach (var ad in options.MainAssemblies)
            {
                pipeline.PrependStep(new MobileResolveMainAssemblyStep(ad, options.Application.Embeddinator));
            }

            context = CreateLinkContext(options, pipeline);
            context.Resolver.AddSearchDirectory(options.OutputDirectory);

            if (options.DumpDependencies)
            {
                var prepareDependenciesDump = context.Annotations.GetType().GetMethod("PrepareDependenciesDump", new Type[1] {
                    typeof(string)
                });
                if (prepareDependenciesDump != null)
                {
                    prepareDependenciesDump.Invoke(context.Annotations, new object[1] {
                        string.Format("{0}{1}linker-dependencies.xml.gz", options.OutputDirectory, Path.DirectorySeparatorChar)
                    });
                }
            }

            try {
                pipeline.Process(context);
            } catch (FileNotFoundException fnfe) {
                // Cecil throw this if the assembly is not found
                throw new MonoTouchException(2002, true, fnfe, fnfe.Message);
            } catch (AggregateException) {
                throw;
            } catch (MonoTouchException) {
                throw;
            } catch (MarkException me) {
                var re = me.InnerException as ResolutionException;
                if (re == null)
                {
                    if (me.InnerException != null)
                    {
                        throw ErrorHelper.CreateError(2102, me, "Error processing the method '{0}' in the assembly '{1}': {2}", me.Method.FullName, me.Method.Module, me.InnerException.Message);
                    }
                    else
                    {
                        throw ErrorHelper.CreateError(2102, me, "Error processing the method '{0}' in the assembly '{1}'", me.Method.FullName, me.Method.Module);
                    }
                }
                else
                {
                    TypeReference  tr    = (re.Member as TypeReference);
                    IMetadataScope scope = tr == null ? re.Member.DeclaringType.Scope : tr.Scope;
                    throw ErrorHelper.CreateError(2101, me, "Can't resolve the reference '{0}', referenced from the method '{1}' in '{2}'.", re.Member, me.Method.FullName, scope);
                }
            } catch (ResolutionException re) {
                TypeReference  tr    = (re.Member as TypeReference);
                IMetadataScope scope = tr == null ? re.Member.DeclaringType.Scope : tr.Scope;
                throw new MonoTouchException(2002, true, re, "Failed to resolve \"{0}\" reference from \"{1}\"", re.Member, scope);
            } catch (XmlResolutionException ex) {
                throw new MonoTouchException(2017, true, ex, "Could not process XML description: {0}", ex?.InnerException?.Message ?? ex.Message);
            } catch (Exception e) {
                var message = new StringBuilder();
                if (e.Data.Count > 0)
                {
                    message.AppendLine();
                    var m = e.Data ["MethodDefinition"] as string;
                    if (m != null)
                    {
                        message.AppendLine($"\tMethod: `{m}`");
                    }
                    var t = e.Data ["TypeReference"] as string;
                    if (t != null)
                    {
                        message.AppendLine($"\tType: `{t}`");
                    }
                    var a = e.Data ["AssemblyDefinition"] as string;
                    if (a != null)
                    {
                        message.AppendLine($"\tAssembly: `{a}`");
                    }
                }
                message.Append($"Reason: {e.Message}");
                throw new MonoTouchException(2001, true, e, "Could not link assemblies. {0}", message);
            }

            assemblies = ListAssemblies(context);
        }
示例#33
0
 public MessagePackSecurityHelper(ModuleDefinition module, IMetadataScope messagePackScope, MessagePackReaderHelper readerHelper)
 {
     this.module           = module;
     this.messagePackScope = messagePackScope;
     this.readerHelper     = readerHelper;
 }
示例#34
0
 protected override bool IgnoreScope(IMetadataScope scope)
 {
     return(false);
 }
        private void InitializeRealm(IMetadataScope realmAssembly)
        {
            Realm       = new TypeReference("Realms", "Realm", Module, realmAssembly);
            RealmObject = new TypeReference("Realms", "RealmObject", Module, realmAssembly);

            {
                RealmIntegerOfT = new TypeReference("Realms", "RealmInteger`1", Module, realmAssembly)
                {
                    IsValueType = true
                };
                var T = GetRealmIntegerGenericParameter(RealmIntegerOfT);
                RealmIntegerOfT.GenericParameters.Add(T);
                var instance = new GenericInstanceType(RealmIntegerOfT)
                {
                    GenericArguments = { T }
                };

                RealmIntegerOfT_ConvertToT = new MethodReference("op_Implicit", T, RealmIntegerOfT)
                {
                    Parameters = { new ParameterDefinition(instance) },
                    HasThis    = false
                };

                RealmIntegerOfT_ConvertFromT = new MethodReference("op_Implicit", instance, RealmIntegerOfT)
                {
                    Parameters = { new ParameterDefinition(T) },
                    HasThis    = false
                };
            }

            {
                Realm_Add = new MethodReference("Add", Types.VoidReference, Realm)
                {
                    HasThis = true
                };
                var T = new GenericParameter(Realm_Add)
                {
                    Constraints = { new GenericParameterConstraint(RealmObject) }
                };
                Realm_Add.ReturnType = T;
                Realm_Add.GenericParameters.Add(T);
                Realm_Add.Parameters.Add(new ParameterDefinition(T));
                Realm_Add.Parameters.Add(new ParameterDefinition(Types.BooleanReference));
            }

            RealmObject_get_IsManaged = new MethodReference("get_IsManaged", Types.BooleanReference, RealmObject)
            {
                HasThis = true
            };
            RealmObject_get_Realm = new MethodReference("get_Realm", Realm, RealmObject)
            {
                HasThis = true
            };
            RealmObject_RaisePropertyChanged = new MethodReference("RaisePropertyChanged", Types.VoidReference, RealmObject)
            {
                HasThis    = true,
                Parameters = { new ParameterDefinition(Types.StringReference) }
            };

            {
                RealmObject_GetObjectValue = new MethodReference("GetObjectValue", Types.VoidReference, RealmObject)
                {
                    HasThis = true
                };
                var T = new GenericParameter(RealmObject_GetObjectValue)
                {
                    Constraints = { new GenericParameterConstraint(RealmObject) }
                };
                RealmObject_GetObjectValue.ReturnType = T;
                RealmObject_GetObjectValue.GenericParameters.Add(T);
                RealmObject_GetObjectValue.Parameters.Add(new ParameterDefinition(Types.StringReference));
            }

            {
                RealmObject_SetObjectValue = new MethodReference("SetObjectValue", Types.VoidReference, RealmObject)
                {
                    HasThis = true
                };
                var T = new GenericParameter(RealmObject_SetObjectValue)
                {
                    Constraints = { new GenericParameterConstraint(RealmObject) }
                };
                RealmObject_SetObjectValue.GenericParameters.Add(T);
                RealmObject_SetObjectValue.Parameters.Add(new ParameterDefinition(Types.StringReference));
                RealmObject_SetObjectValue.Parameters.Add(new ParameterDefinition(T));
            }

            {
                RealmObject_GetListValue = new MethodReference("GetListValue", new GenericInstanceType(IListOfT), RealmObject)
                {
                    HasThis = true
                };
                var T = new GenericParameter(RealmObject_GetListValue);
                (RealmObject_GetListValue.ReturnType as GenericInstanceType).GenericArguments.Add(T);
                RealmObject_GetListValue.GenericParameters.Add(T);
                RealmObject_GetListValue.Parameters.Add(new ParameterDefinition(Types.StringReference));
            }

            {
                RealmObject_GetBacklinks = new MethodReference("GetBacklinks", new GenericInstanceType(IQueryableOfT), RealmObject)
                {
                    HasThis = true
                };
                var T = new GenericParameter(RealmObject_GetBacklinks)
                {
                    Constraints = { new GenericParameterConstraint(RealmObject) }
                };
                (RealmObject_GetBacklinks.ReturnType as GenericInstanceType).GenericArguments.Add(T);
                RealmObject_GetBacklinks.GenericParameters.Add(T);
                RealmObject_GetBacklinks.Parameters.Add(new ParameterDefinition(Types.StringReference));
            }

            IRealmObjectHelper = new TypeReference("Realms.Weaving", "IRealmObjectHelper", Module, realmAssembly);

            PreserveAttribute             = new TypeReference("Realms", "PreserveAttribute", Module, realmAssembly);
            PreserveAttribute_Constructor = new MethodReference(".ctor", Types.VoidReference, PreserveAttribute)
            {
                HasThis = true
            };
            PreserveAttribute_ConstructorWithParams = new MethodReference(".ctor", Types.VoidReference, PreserveAttribute)
            {
                HasThis    = true,
                Parameters = { new ParameterDefinition(Types.BooleanReference), new ParameterDefinition(Types.BooleanReference) }
            };

            WovenAttribute             = new TypeReference("Realms", "WovenAttribute", Module, realmAssembly);
            WovenAttribute_Constructor = new MethodReference(".ctor", Types.VoidReference, WovenAttribute)
            {
                HasThis    = true,
                Parameters = { new ParameterDefinition(System_Type) }
            };

            WovenAssemblyAttribute             = new TypeReference("Realms", "WovenAssemblyAttribute", Module, realmAssembly);
            WovenAssemblyAttribute_Constructor = new MethodReference(".ctor", Types.VoidReference, WovenAssemblyAttribute)
            {
                HasThis = true
            };

            WovenPropertyAttribute             = new TypeReference("Realms", "WovenPropertyAttribute", Module, realmAssembly);
            WovenPropertyAttribute_Constructor = new MethodReference(".ctor", Types.VoidReference, WovenPropertyAttribute)
            {
                HasThis = true
            };

            ExplicitAttribute = new TypeReference("Realms", "ExplicitAttribute", Module, realmAssembly);

            var realmSchema = new TypeReference("Realms.Schema", "RealmSchema", Module, realmAssembly);

            RealmSchema_AddDefaultTypes = new MethodReference("AddDefaultTypes", Types.VoidReference, realmSchema)
            {
                HasThis = false
            };
            {
                var ienumerableOfType = new GenericInstanceType(IEnumerableOfT)
                {
                    GenericArguments = { System_Type }
                };

                RealmSchema_AddDefaultTypes.Parameters.Add(new ParameterDefinition(ienumerableOfType));
            }
        }
示例#36
0
 public Pair(string scope, string name, IMetadataScope metadataScope)
 {
     this.scope    = scope;
     this.name     = name;
     MetadataScope = metadataScope;
 }
示例#37
0
        /// <summary>
        /// Checks to see if the instruction includes a multidimensional array and
        /// if so attempts to reconstruct the instruction as a normal (1d) array
        /// operation (.ctor, getter or setter) and resolve that instead.
        /// </summary>
        /// <returns><c>true</c>, if multidimensional array was successfully
        /// reconstructed as a 1d array instruction and successfully resolved,
        /// <c>false</c> otherwise.</returns>
        /// <param name="instruction">An instruction.</param>
        /// <param name="method">The method which contains the instruction.</param>
        /// <param name="type">The type which contains the method and instruction.</param>
        /// <param name="scope">The scope of the instruction (name of assembly).</param>
        /// <remarks>
        /// Multidimensional array instructions won't resolve because "there's
        /// nothing in the metadata to resolve to: those methods are created on the
        /// fly by the runtime".
        /// See https://www.mail-archive.com/[email protected]/msg03876.html.
        /// </remarks>
        static bool CheckMultidimensionalArray(Mono.Cecil.Cil.Instruction instruction, MethodDefinition method, TypeDefinition type, IMetadataScope scope)
        {
            var processor = method.Body.GetILProcessor();

            foreach (var pattern in Patterns)
            {
                var m = pattern.Key.Match(instruction.Operand.ToString());
                if (m.Success)
                {
                    string full_name = m.Groups[1].Value;
                    logger.Debug("Attemping to reconstruct multidimensional array instruction as '{0}' with opcode '{1}'", full_name, pattern.Value.Code);
                    var asm      = cache[scope.Name];
                    var tmp_type = asm.MainModule.GetType(full_name);
                    if (tmp_type == null)
                    {
                        logger.Debug("{0} not found in {1}", full_name, scope.Name);
                        return(false);
                    }
                    var new_instr = processor.Create(pattern.Value, tmp_type);
                    return(TryResolve(new_instr.Operand, type));
                }
            }

            return(false);
        }
示例#38
0
		public TypeReference (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
			: this (@namespace, name)
		{
			this.module = module;
			this.scope = scope;
		}
示例#39
0
 public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
     : this(@namespace, name)
 {
     this.module = module;
     this.scope  = scope;
 }
示例#40
0
 private static Pair GetTypeKey(IMetadataScope scope, String fullName)
 {
     return(new Pair(GetScopeName(scope), fullName, scope));
 }
示例#41
0
 public TypeReference(string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) :
     this(@namespace, name, module, scope)
 {
     value_type = valueType;
 }
		internal TypeReference (string name, string ns, IMetadataScope scope) : this (name, ns)
		{
			m_scope = scope;
		}
示例#43
0
文件: LinkContext.cs 项目: GirlD/mono
		public AssemblyDefinition Resolve (IMetadataScope scope)
		{
			AssemblyNameReference reference = GetReference (scope);
			try {
				AssemblyDefinition assembly = _resolver.Resolve (reference, _readerParameters);

				if (SeenFirstTime (assembly)) {
					SafeReadSymbols (assembly);
					SetAction (assembly);
				}

				return assembly;
			}
			catch {
				throw new AssemblyResolutionException (reference);
			}
		}
		internal void AttachToScope (IMetadataScope scope)
		{
			m_scope = scope;
		}
示例#45
0
		public TypeReference (string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) :
			this (@namespace, name, module, scope)
		{
			value_type = valueType;
		}
示例#46
0
 public ExportedType(string @namespace, string name, IMetadataScope scope)
 {
     this.@namespace = @namespace;
     this.name       = name;
     this.scope      = scope;
 }
		protected override bool IgnoreScope (IMetadataScope scope)
		{
			return false;
		}
示例#48
0
文件: MarkStep.cs 项目: nuxleus/mono
		void MarkScope (IMetadataScope scope)
		{
			var provider = scope as IMetadataTokenProvider;
			if (provider == null)
				return;

			Annotations.Mark (provider);
		}
示例#49
0
        public StructuralAssemblyNode Ensure(RuntimicSystemModel semanticModel, IMetadataScope scope)
        {
            string fullName = Assemblies.Naming.GetAssemblyName(scope);

            return(Ensure(semanticModel, fullName));
        }
示例#50
0
 internal TypeReference(string name, string ns, IMetadataScope scope) : this(name, ns)
 {
     m_scope = scope;
 }
		public TypeReference (string name, string ns, IMetadataScope scope, bool valueType) :
			this (name, ns, scope)
		{
			m_isValueType = valueType;
		}
示例#52
0
文件: MarkStep.cs 项目: zgramana/mono
        protected virtual bool IgnoreScope(IMetadataScope scope)
        {
            AssemblyDefinition assembly = ResolveAssembly(scope);

            return(Annotations.GetAction(assembly) != AssemblyAction.Link);
        }
示例#53
0
 public MemberNode(string member, IMetadataScope scope, MessageTypes type)
 {
     this.member = member;
     this.scope = scope;
     this.type = type;
     Text = member;
     // Cells.Add(new Cell((scope != null) ? scope.ToString() : ""));
 }
示例#54
0
 string GetAssemblyName(IMetadataScope scope)
 {
     return(scope is AssemblyNameReference ? ((AssemblyNameReference)scope).FullName : null);
 }
示例#55
0
文件: MarkStep.cs 项目: nuxleus/mono
		protected virtual bool IgnoreScope (IMetadataScope scope)
		{
			AssemblyDefinition assembly = ResolveAssembly (scope);
			return Annotations.GetAction (assembly) != AssemblyAction.Link;
		}
示例#56
0
 private static bool IsAssemblyCSharp(this IMetadataScope scope)
 {
     return(scope.Name != "Assembly-CSharp.dll");
 }
示例#57
0
文件: MarkStep.cs 项目: nuxleus/mono
		AssemblyDefinition ResolveAssembly (IMetadataScope scope)
		{
			AssemblyDefinition assembly = _context.Resolve (scope);
			MarkAssembly (assembly);
			return assembly;
		}
示例#58
0
        /*Telerik Authorship*/
        internal TypeDefinition Resolve(TypeReference type, ICollection <string> visitedDlls)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            // TODO: The following code must be uncommented when bug 284860 (the one with the Resolver) is fixed.
            //if (type is ArrayType)
            //{
            //    type = type.Module.TypeSystem.LookupType("System", "Array");
            //}
            //else
            //{
            type = type.GetElementType();
            //}

            IMetadataScope scope = type.Scope;

            if (scope == null)
            {
                return(null);
            }
            switch (scope.MetadataScopeType)
            {
            case MetadataScopeType.AssemblyNameReference:
                /*Telerik Authorship*/
                TargetArchitecture architecture = type.Module.GetModuleArchitecture();
                var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope, type.Module.ModuleDirectoryPath, architecture);
                if (assembly == null)
                {
                    return(null);
                }

                /*Telerik Authorship*/
                if (visitedDlls.Contains(assembly.MainModule.FilePath))
                {
                    return(null);
                }
                visitedDlls.Add(assembly.MainModule.FilePath);

                return(GetType(assembly.MainModule, type, visitedDlls));

            case MetadataScopeType.ModuleDefinition:

                ModuleDefinition theModule = (ModuleDefinition)scope;
                /*Telerik Authorship*/
                if (visitedDlls.Contains(theModule.FilePath))
                {
                    return(null);
                }
                visitedDlls.Add(theModule.FilePath);

                return(GetType(theModule, type, visitedDlls));

            case MetadataScopeType.ModuleReference:
                var modules    = type.Module.Assembly.Modules;
                var module_ref = (ModuleReference)scope;
                for (int i = 0; i < modules.Count; i++)
                {
                    var netmodule = modules[i];
                    if (netmodule.Name == module_ref.Name)
                    {
                        /*Telerik Authorship*/
                        if (visitedDlls.Contains(netmodule.FilePath))
                        {
                            return(null);
                        }
                        visitedDlls.Add(netmodule.FilePath);
                        return(GetType(netmodule, type, visitedDlls));
                    }
                }
                break;
            }

            throw new NotSupportedException();
        }