protected MonoFundamentalType(MonoSymbolFile file, Cecil.TypeDefinition typedef,
					       string name, FundamentalKind kind, int size)
            : base(file.Language, name, kind, size)
        {
            this.file = file;
            this.typedef = typedef;
        }
示例#2
0
        public static int InjectHooks(Dictionary <string, List <AttributeData> > attributes, AssemblyDefinition assemblyDefinition)
        {
            if (!attributes.ContainsKey(nameof(AddMethodAttribute)))
            {
                return(0);
            }
            var injectedCorrectly = 0;

            ConsoleHelper.WriteNewline();
            foreach (var hook in attributes[nameof(AddMethodAttribute)])
            {
                // Improve: Add check for multiple args here
                var typeDefinition = Cecil.ConvertStringToClass(hook.Attribute.ConstructorArguments[0].Value.ToString(), assemblyDefinition);
                if (typeDefinition == null)
                {
                    continue;
                }
                var methodName = hook.Attribute.ConstructorArguments[1].Value.ToString();
                if (Cecil.MethodExists(typeDefinition, methodName))
                {
                    ConsoleHelper.WriteError($"Method \"{methodName}\" Already exists in type {typeDefinition.Name}.");
                    continue;
                }
                if (Cecil.InjectNewMethod(typeDefinition, assemblyDefinition, methodName, hook))
                {
                    ++injectedCorrectly;
                }
            }
            return(injectedCorrectly);
        }
示例#3
0
        public static int InjectHooks(Dictionary <string, List <HookData> > attributes, AssemblyDefinition assembly, Dictionary <string, TypeDefinition> typeDefinitions)
        {
            if (!attributes.ContainsKey(nameof(AddMethodHook)))
            {
                return(0);
            }

            int injectedCorrectly = 0;

            foreach (HookData hook in attributes[nameof(AddMethodHook)])
            {
                TypeDefinition typeDef = Cecil.ConvertStringToClass(hook.Attribute.ConstructorArguments[0].Value.ToString(), assembly, typeDefinitions);

                if (typeDef == null)
                {
                    continue;
                }

                string methodName = hook.Attribute.ConstructorArguments[1].Value.ToString();

                if (Cecil.MethodExists(typeDef, methodName))
                {
                    string desc = string.Format("Method {0} already exists in type {1}", methodName, typeDef.FullName);
                    Externs.MessageBox("Method already exists!", desc);
                }
                else if (Cecil.InjectNewMethod(typeDef, assembly, typeDefinitions, methodName, hook))
                {
                    ++injectedCorrectly;
                }
            }

            return(injectedCorrectly);
        }
        /// <summary>
        /// Writes the specified statement.
        /// </summary>
        /// <param name="statement">The statement.</param>
        void ILanguageWriter.Write(Cecil.Decompiler.Ast.Statement statement)
        {
            LanguageWriter.Write(statement);

            if (_formatter != null)
            {
                _formatter.CompleteDecompile(statement, this);
            }
        }
        /// <summary>
        /// Writes the specified expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        void ILanguageWriter.Write(Cecil.Decompiler.Ast.Expression expression)
        {
            LanguageWriter.Write(expression);

            if (_formatter != null)
            {
                _formatter.CompleteDecompile(expression, this);
            }
        }
示例#6
0
文件: Utils.cs 项目: baulig/debugger
        public static void DumpLineNumberTable(TextWriter writer, MonoSymbolFile file,
							Cecil.MethodDefinition mdef, C.MethodEntry entry)
        {
            try {
                DumpLineNumberTable_internal (writer, file, mdef, entry);
            } catch (Exception ex) {
                writer.WriteLine ("DUMP LNT EX: {0}", ex);
            }
        }
示例#7
0
        protected MonoClassInfo(MonoSymbolFile file, Cecil.TypeDefinition typedef,
					 TargetMemoryAccess target, TargetAddress klass)
        {
            this.SymbolFile = file;
            this.KlassAddress = klass;
            this.CecilType = typedef;

            parent_klass = MetadataHelper.MonoClassGetParent (target, klass);
            GenericClass = MetadataHelper.MonoClassGetGenericClass (target, klass);
            GenericContainer = MetadataHelper.MonoClassGetGenericContainer (target, klass);
        }
        /// <summary>
        /// Assigns the generic blueprint and the type arguments to the generic instance type.
        /// </summary>
        /// <param name="conversion"></param>
        /// <param name="converted"></param>
        /// <param name="convertedDeclaringType"></param>
        /// <returns></returns>
        public void Build(ILConversion conversion, ConvertedTypeDefinition_I converted, ConvertedTypeDefinition_I convertedDeclaringType)
        {
            //Done on purpose to find errors
            var typeDefinition = (TypeDefinition)converted.SourceTypeReference;

            System.Reflection.TypeAttributes attributes = Cecil.Metadata.Members.Types.GetTypeAttributes(typeDefinition);

            if (converted is ConvertedTypeDefinitionWithDeclaringType_I withDeclaringType)
            {
                var packingSize = Cecil.GetPackingSize(typeDefinition);

                if (convertedDeclaringType == null)                 // Can occur if passing in a single nested type or if a nested class gets processed before its parents gets
                // processed.
                {
                    if (!(converted.SourceTypeReference is TypeDefinition))
                    {
                        throw new Exception("Expected a type definition");
                    }

                    var semanticDeclaringType = Execution.Types.Ensuring.Ensure(conversion, converted.SourceTypeReference.DeclaringType, null, null);

                    if (!(semanticDeclaringType is ConvertedTypeDefinition_I producedDeclaringType))
                    {
                        throw new Exception($"Expected the declaring type of a nested class to be castable to {typeof(ConvertedTypeDefinition_I)}");
                    }

                    convertedDeclaringType = producedDeclaringType;
                }

                withDeclaringType.DeclaringType = convertedDeclaringType;

                // The plus sign and the parent class name before it needs to be dropped from the full name prior to calling define nested class
                // as the type builder will automatically add them back on based upon the name of the declaring type.
                var fullName = Types.Naming.GetTypeBuilderNestedClassFullName(converted.FullName);

                converted.TypeBuilder = convertedDeclaringType.TypeBuilder.DefineNestedType(fullName, attributes, null, packingSize);
            }
            else
            {
                if (converted.FullName == "<Module>")
                {
                    var x = converted.Module.ModuleBuilder.GetType("<Module>", true);
                }

                converted.TypeBuilder = converted.Module.ModuleBuilder.DefineType(converted.FullName, attributes);
            }

            converted.UnderlyingType = converted.TypeBuilder;

            this.Unified.Types.ExtendWithCrossReference(conversion.RuntimicSystem, converted, converted.UnderlyingType.AssemblyQualifiedName);

            Types.Building.UpdateBuildPhase(converted, BuildPhaseKind.TypeDefined);
        }
示例#9
0
        private void EnsureVariableTypes(ILConversion conversion, MethodDefinition method, TypeReference genericArgumentSource)
        {
            if (method.Body.HasVariables)
            {
                foreach (var variable in method.Body.Variables)
                {
                    var resolvedVariableTypeReference = Cecil.ResolveAnyTypeArguments(genericArgumentSource, variable.VariableType);

                    Types.Scanning.EnsureType(conversion, resolvedVariableTypeReference);
                }
            }
        }
示例#10
0
        private void EnsureReturnType(ILConversion conversion, MethodDefinition method, TypeReference genericArgumentSource)
        {
            var returnType = method.ReturnType;

            // If generic, go ahead and skip.  It will get resolved.
            if (returnType.IsGenericParameter)
            {
                return;
            }

            var resolvedReturnTypeReference = Cecil.ResolveAnyTypeArguments(genericArgumentSource, returnType);

            Types.Scanning.EnsureType(conversion, resolvedReturnTypeReference);
        }
示例#11
0
        private void EnsureTypes(ILConversion conversion, EventDefinition propertyDefinition, TypeReference genericArgumentSource)
        {
            var eventTypeReference = propertyDefinition.EventType;

            // If generic, go ahead and skip.  It will get resolved.
            if (eventTypeReference.IsGenericParameter)
            {
                return;
            }

            var resolvedEventTypeReference = Cecil.ResolveAnyTypeArguments(genericArgumentSource, propertyDefinition.EventType);

            var eventTypeDefinition = Models.Types.ResolveToTypeDefinition(conversion.RuntimicSystem, resolvedEventTypeReference);

            Execution.Types.Ensuring.Ensure(conversion, eventTypeDefinition, null, null);
        }
示例#12
0
        public void EnsureTypes(ILConversion conversion, FieldDefinition field, TypeReference genericArgumentSource)
        {
            var fieldTypeReference = field.FieldType;

            // If generic, go ahead and skip.  It will get resolved.
            if (fieldTypeReference.IsGenericParameter)
            {
                return;
            }

            var resolvedReturnTypeReference = Cecil.ResolveForTypeScan(genericArgumentSource, fieldTypeReference);

            var returnTypeDefinition = Models.Types.ResolveToTypeDefinition(conversion.RuntimicSystem, resolvedReturnTypeReference);

            Execution.Types.Ensuring.Ensure(conversion, returnTypeDefinition, null, null);
        }
示例#13
0
        private void EnsureTypes(ILConversion conversion, PropertyDefinition propertyDefinition, TypeReference genericArgumentSource)
        {
            var propertyTypeReference = propertyDefinition.PropertyType;

            // If generic, go ahead and skip.  It will get resolved.
            if (propertyTypeReference.IsGenericParameter)
            {
                return;
            }

            var resolvedPropertyTypeReference = Cecil.ResolveAnyTypeArguments(genericArgumentSource, propertyTypeReference);

            var propertyTypeDefinition = Models.Types.ResolveToTypeDefinition(conversion.RuntimicSystem, resolvedPropertyTypeReference);

            //Execution.Types.Ensuring.Ensure(conversion.Model, propertyTypeDefinition, null, null);

            throw new System.Exception("Fix");
        }
示例#14
0
        private void EnsureGenericParameters(ILConversion conversion, MethodDefinition method, TypeReference genericArgumentSource)
        {
            var genericParameters = method.GenericParameters;

            for (int i = 0; i < genericParameters.Count; i++)
            {
                var genericParameter = genericParameters[i];

                var genericParameterConstraints = genericParameter.Constraints;

                for (int j = 0; j < genericParameterConstraints.Count; j++)
                {
                    var resolvedConstraintTypeReference = Cecil.ResolveAnyTypeArguments(genericArgumentSource, genericParameterConstraints[j]);

                    Types.Scanning.EnsureType(conversion, resolvedConstraintTypeReference);
                }
            }
        }
示例#15
0
        private void EnsureParameterTypes(ILConversion conversion, MethodDefinition method, TypeReference genericArgumentSource)
        {
            var parameters = method.Parameters;

            for (int i = 0; i < parameters.Count; i++)
            {
                var parameter = parameters[i];

                var parameterType = parameter.ParameterType;

                if (parameterType.IsGenericParameter)
                {
                    continue;
                }

                var resolvedParameterTypeReference = Cecil.ResolveAnyTypeArguments(genericArgumentSource, parameterType);

                Types.Scanning.EnsureType(conversion, resolvedParameterTypeReference);
            }
        }
示例#16
0
        public void EnsureTypes(ILConversion conversion, SemanticTypeMask_I boundTypeMask)
        {
            if (!boundTypeMask.IsDefinition())
            {
                return;
            }

            var typeDefinitionMask = (SemanticTypeDefinitionMask_I)boundTypeMask;

            var typeReference = typeDefinitionMask.SourceTypeReference;

            var typeDefinition = Cecil.GetFundamentalTypeDefinition(typeReference);

            var fields = typeDefinition.Fields;

            for (int i = 0; i < fields.Count; i++)
            {
                var field = fields[i];

                EnsureTypes(conversion, field, typeReference);
            }
        }
        public static int InjectHooks(Dictionary <string, List <AttributeData> > attributes, AssemblyDefinition assemblyDefinition)
        {
            if (!attributes.ContainsKey(nameof(HookAttributes)))
            {
                return(0);
            }
            var injectedCorrectly = 0;

            foreach (var hook in attributes[nameof(HookAttributes)])
            {
                hook.TargetData = Cecil.ConvertStringToClassAndMethod(hook.Attribute.ConstructorArguments[0].Value.ToString(), assemblyDefinition);
                if (hook.TargetData == null)
                {
                    continue;
                }
                if (Cecil.Inject(hook.TargetData, hook))
                {
                    ++injectedCorrectly;
                }
            }
            return(injectedCorrectly);
        }
示例#18
0
        /// <summary>
        /// Ensures that all of the types that the method uses have been created so that when the methods is actually converted,
        /// no types have to be created.
        /// </summary>
        /// <param name="conversion"></param>
        /// <param name="boundTypeMask"></param>
        public void EnsureTypes(ILConversion conversion, SemanticTypeMask_I boundTypeMask)
        {
            if (!boundTypeMask.IsDefinition())
            {
                return;
            }

            var typeDefinitionMask = (BoundTypeDefinitionMask_I)boundTypeMask;

            var typeReference = typeDefinitionMask.SourceTypeReference;

            // Done on purpose to find errors
            var typeDefinition = Cecil.GetFundamentalTypeDefinition(typeReference);

            var methods = typeDefinition.Methods;

            for (int i = 0; i < methods.Count; i++)
            {
                var method = methods[i];
                EnsureTypes(conversion, method, typeReference);
            }
        }
示例#19
0
        public static int InjectHooks(Dictionary <string, List <HookData> > attributes, AssemblyDefinition assembly, Dictionary <string, TypeDefinition> typeDefinitions)
        {
            if (!attributes.ContainsKey(nameof(AddCallHook)))
            {
                return(0);
            }

            int injectedCorrectly = 0;

            foreach (HookData hook in attributes[nameof(AddCallHook)])
            {
                if (hook.Attribute.ConstructorArguments.Count > 0)
                {
                    hook.TargetData = Cecil.ConvertStringToClassAndMethod(hook.Attribute.ConstructorArguments[0].Value.ToString(), assembly, typeDefinitions, hook);

                    if (hook.TargetData != null && Cecil.Inject(hook.TargetData, hook))
                    {
                        ++injectedCorrectly;
                    }
                }
            }

            return(injectedCorrectly);
        }
示例#20
0
        public System.Type GetUnderlyingType(RuntimicSystemModel model, TypeReference typeReference)
        {
            if (typeReference.IsGenericParameter)
            {
                var bound = ResolveToBound_GenericParameter(model, (GenericParameter)typeReference);

                return(bound.UnderlyingType);
            }

            if (typeReference.IsGenericInstance)
            {
                throw new Exception("Should never happen.");
                //var genericInstance = (GenericInstanceType)typeReference;

                //var genericTypeDefinitionType = GetUnderlyingType(model, genericInstance.ElementType);

                //System.Type[] genericArguments = new System.Type[genericInstance.GenericArguments.Count];

                //for (int i = 0; i < genericInstance.GenericArguments.Count; i++)
                //{
                // genericArguments[i] = GetUnderlyingType(model, genericInstance.GenericArguments[i]);

                // if (genericArguments[i] == null)
                // {
                //  throw new Exception("The underlying type was null.");
                // }

                //}

                //var result = XCommonAppPal.Api.Runtimic.Execution.Metadata.Assemblies.MakeGenericType(genericTypeDefinitionType, genericArguments);

                //return result;
            }

            return(Cecil.GetUnderlyingType(typeReference));
        }
示例#21
0
        public ExecutionTypeNode_I Ensure(ExecutionEnsureContext context)
        {
            if (!context.IsConverted.HasValue)
            {
                throw new Exception("Expected conversion to be figured out.");
            }

            if (context.StructuralInputTypeNode.CecilTypeReference.IsNested && context.DeclaringType == null)
            {
                context.DeclaringType = Execution.Types.Ensuring.EnsureBound(context,
                                                                             context.StructuralInputTypeNode.CecilTypeReference.DeclaringType, cloneContext: true);
            }

            if (context.IsConverted.Value)
            {
                var conversion = context.Conversion;

                var structuralInputTypeNode = context.StructuralInputTypeNode;

                var metadataToken = structuralInputTypeNode.MetadataToken;

                var structuralAssembly = Conversion.Metadata.Assemblies.EnsureNode(context.Conversion, structuralInputTypeNode.Module.Assembly);

                var convertedModuleNode = Conversion.Metadata.Modules.Ensure(context.Conversion, structuralAssembly, structuralInputTypeNode.Module);

                var tableId = (int)(metadataToken & 0xFF000000);

                if (!convertedModuleNode.Tables.TryGetValue(tableId, out ConvertedTypeTable table))
                {
                    table = new ConvertedTypeTable();

                    convertedModuleNode.Tables.Add(tableId, table);
                }

                if (table.ByRow.TryGetValue((uint)context.RowId, out ConversionTypeNode conversionTypeNode))
                {
                    return(conversionTypeNode);
                }



                var converted = Conversion.Metadata.Members.Types.Creation.Create(conversion.RuntimicSystem, structuralInputTypeNode.CecilTypeReference);

                converted.Module = convertedModuleNode.ConvertedModule;

                conversionTypeNode = new ConversionTypeNode()
                {
                    Assembly        = structuralAssembly,
                    ByReferenceType = null,
                    Id = 0,
                    InputStructuralNode = structuralInputTypeNode,
                    IsByReferenceType   = false,
                    IsDerived           = false,
                    IsPointerType       = false,
                    MetadataToken       = metadataToken,
                    Module      = convertedModuleNode,
                    PointerType = null,
                    Type        = converted
                };

                table.ByRow.Add((uint)context.RowId, conversionTypeNode);

                var convertedDeclaringType = context.ConvertedDeclaringType;

                Converted_BuildPhase1(conversion, structuralInputTypeNode, converted, convertedDeclaringType);

                Conversion.Metadata.Members.Types.Building.IfPossibleBuildPhase2(conversion, converted);

                return(conversionTypeNode);
            }
            else
            {
                var structuralInputTypeNode = context.StructuralInputTypeNode;

                if (structuralInputTypeNode.FullName == "Root.Code.Containers.E01D.Sorting.SortingContainer_I`1")
                {
                }

                var metadataToken = structuralInputTypeNode.MetadataToken;

                var boundAssembly = Bound.Metadata.Assemblies.EnsureNode(context.RuntimicSystem, structuralInputTypeNode.Module.Assembly);

                var boundModuleNode = Bound.Metadata.Modules.Ensuring.EnsureNode(context.RuntimicSystem, boundAssembly, structuralInputTypeNode.Module);

                var tableId = (int)(metadataToken & 0xFF000000);

                if (!boundModuleNode.Tables.TryGetValue(tableId, out BoundTypeTable table))
                {
                    table = new BoundTypeTable();

                    boundModuleNode.Tables.Add(tableId, table);
                }

                if (table.ByRow.TryGetValue((uint)context.RowId, out BoundTypeNode boundTypeNode))
                {
                    return(boundTypeNode);
                }
                //---------------------------------
                // Conversion is going to occur.
                //---------------------------------

                if (context.UnderlyingType == null)
                {
                    context.UnderlyingType = Cecil.GetUnderlyingType(structuralInputTypeNode.CecilTypeReference);

                    if (context.UnderlyingType == null)
                    {
                        throw new Exception("Null type");
                    }
                }

                var bound = Bound.Metadata.Members.Types.Creation.Create(context.RuntimicSystem, context.StructuralInputTypeNode.CecilTypeReference, context.UnderlyingType);

                boundTypeNode = new BoundTypeNode()
                {
                    Assembly        = boundAssembly,
                    ByReferenceType = null,
                    Id = 0,
                    InputStructuralNode = structuralInputTypeNode,
                    IsByReferenceType   = false,
                    IsDerived           = false,
                    IsPointerType       = false,
                    MetadataToken       = metadataToken,
                    Module      = boundModuleNode,
                    PointerType = null,
                    Type        = bound
                };


                bound.Module = boundModuleNode.BoundModule;

                //// Add the type instance to the model.  Do not do any recursive calls till this methods is called.
                table.ByRow.Add((uint)context.RowId, boundTypeNode);



                //Types.Addition.Add(semanticModel, boundModule, bound);

                Bound.Metadata.Members.Types.Building.NonGenericInstances.Phase1Initial.Build(context.RuntimicSystem, bound, context.UnderlyingType, context.DeclaringType);

                return(boundTypeNode);
            }
        }
示例#22
0
        public TargetType LookupMonoType(Cecil.TypeReference type)
        {
            TargetType result = (TargetType) type_hash [type];
            if (result != null)
                return result;

            if (type is Cecil.ArrayType) {
                Cecil.ArrayType atype = (Cecil.ArrayType) type;
                TargetType element_type = LookupMonoType (atype.ElementType);
                result = new MonoArrayType (element_type, atype.Rank);
            } else if (type is Cecil.TypeDefinition) {
                Cecil.TypeDefinition tdef = (Cecil.TypeDefinition) type;
                if (tdef.IsEnum)
                    result = new MonoEnumType (this, tdef);
                else
                    result = new MonoClassType (this, tdef);
            } else {
                Console.WriteLine ("UNKNOWN TYPE: {0} {1}", type, type.GetType ());
                return null;
            }

            if (!type_hash.Contains (type))
                type_hash.Add (type, result);
            return result;
        }
示例#23
0
        internal void AddCoreType(Cecil.TypeDefinition typedef, TargetType type,
					   TargetClassType klass, TargetAddress klass_address)
        {
            corlib.AddType (typedef, type);
            if (!class_hash.Contains (klass_address))
                class_hash.Add (klass_address, type);
        }
示例#24
0
        Cecil.TypeDefinition resolve_cecil_type_ref(Cecil.TypeReference type)
        {
            type = type.GetElementType ();

            if (type is Cecil.TypeDefinition)
                return (Cecil.TypeDefinition) type;

            Cecil.AssemblyNameReference reference = type.Scope as Cecil.AssemblyNameReference;
            if (reference != null) {
                Cecil.AssemblyDefinition assembly = resolve_cecil_asm_name (reference);
                if (assembly == null)
                    return null;

                return assembly.MainModule.GetType (type.FullName);
            }

            Cecil.ModuleDefinition module = type.Scope as Cecil.ModuleDefinition;
            if (module != null)
                return module.GetType (type.FullName);

            throw new NotImplementedException ();
        }
示例#25
0
		Ast.Expression Convert(Ast.Expression expr, Cecil.TypeReference actualType, Cecil.TypeReference reqType)
		{
			if (reqType == null || actualType == reqType) {
				return expr;
			} else {
				bool actualIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(actualType);
				bool requiredIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(reqType);
				
				if (TypeAnalysis.IsBoolean(reqType)) {
					if (TypeAnalysis.IsBoolean(actualType))
						return expr;
					if (actualIsIntegerOrEnum) {
						return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, AstBuilder.MakePrimitive(0, actualType));
					} else {
						return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, new NullReferenceExpression());
					}
				}
				if (TypeAnalysis.IsBoolean(actualType) && requiredIsIntegerOrEnum) {
					return new ConditionalExpression {
						Condition = expr,
						TrueExpression = AstBuilder.MakePrimitive(1, reqType),
						FalseExpression = AstBuilder.MakePrimitive(0, reqType)
					};
				}

				if (expr is PrimitiveExpression && !requiredIsIntegerOrEnum && TypeAnalysis.IsEnum(actualType))
				{
					return expr.CastTo(AstBuilder.ConvertType(actualType));
				}

				if (actualIsIntegerOrEnum && requiredIsIntegerOrEnum) {
					return expr.CastTo(AstBuilder.ConvertType(reqType));
				}
				return expr;
			}
		}
示例#26
0
            public MonoMethod(MonoSymbolFile file, MethodSource source, int domain,
					   C.MethodEntry method, Cecil.MethodDefinition mdef)
                : base(source.Name, file.ImageFile, file.Module)
            {
                this.file = file;
                this.source = source;
                this.domain = domain;
                this.method = method;
                this.mdef = mdef;

                foreach (Cecil.CustomAttribute cattr in mdef.CustomAttributes) {
                    string cname = cattr.Constructor.DeclaringType.FullName;
                    if ((cname == "System.Diagnostics.DebuggerHiddenAttribute") ||
                        (cname == "System.Runtime.CompilerServices.CompilerGeneratedAttribute"))
                        is_compiler_generated = true;
                }
            }
示例#27
0
            public MonoMethodSource(MonoSymbolFile file, SourceFile source_file,
						 C.MethodEntry method, Cecil.MethodDefinition mdef,
						 MonoClassType klass, MonoFunctionType function)
            {
                this.file = file;
                this.source_file = source_file;
                this.method = method;
                this.mdef = mdef;
                this.function = function;
                this.klass = klass;

                full_name = method.GetRealName ();
                if (full_name == null)
                    full_name = MonoSymbolFile.GetMethodName (mdef);

                C.LineNumberEntry start, end;
                C.LineNumberTable lnt = method.GetLineNumberTable ();
                if (lnt.GetMethodBounds (out start, out end))
                    start_row = start.Row; end_row = end.Row;
            }
示例#28
0
 internal static string GetMethodSignature(Cecil.MethodDefinition mdef)
 {
     StringBuilder sb = new StringBuilder ("(");
     bool first = true;
     foreach (Cecil.ParameterDefinition p in mdef.Parameters) {
         if (first)
             first = false;
         else
             sb.Append (", ");
         sb.Append (GetTypeSignature (p.ParameterType).Replace ('+','/'));
     }
     sb.Append (")");
     return sb.ToString ();
 }
示例#29
0
 internal static string GetMethodName(Cecil.MethodDefinition mdef)
 {
     StringBuilder sb = new StringBuilder (GetTypeSignature (mdef.DeclaringType));
     if (mdef.DeclaringType.GenericParameters.Count > 0) {
         sb.Append ('<');
         bool first = true;
         foreach (Cecil.GenericParameter p in mdef.DeclaringType.GenericParameters) {
             if (first)
                 first = false;
             else
                 sb.Append (',');
             sb.Append (p.Name);
         }
         sb.Append ('>');
     }
     sb.Append ('.');
     sb.Append (mdef.Name);
     if (mdef.GenericParameters.Count > 0) {
         sb.Append ('<');
         bool first = true;
         foreach (Cecil.GenericParameter p in mdef.GenericParameters) {
             if (first)
                 first = false;
             else
                 sb.Append (',');
             sb.Append (p.Name);
         }
         sb.Append ('>');
     }
     sb.Append (GetMethodSignature (mdef));
     return sb.ToString ();
 }
示例#30
0
        internal static void CheckCustomAttributes(Cecil.ICustomAttributeProvider type,
							    out DebuggerBrowsableState? browsable_state,
							    out DebuggerDisplayAttribute debugger_display,
							    out DebuggerTypeProxyAttribute type_proxy,
							    out bool is_compiler_generated)
        {
            browsable_state = null;
            debugger_display = null;
            type_proxy = null;
            is_compiler_generated = false;

            foreach (Cecil.CustomAttribute cattr in type.CustomAttributes) {
                string cname = cattr.Constructor.DeclaringType.FullName;
                if (cname == cgen_attr) {
                    is_compiler_generated = true;
                } else if (cname == debugger_display_attr) {
                    string text = (string) cattr.ConstructorArguments [0].Value;
                    debugger_display = new DebuggerDisplayAttribute (text);
                    foreach (var named_arg in cattr.Properties) {
                        string key = named_arg.Name;
                        if (key == "Name")
                            debugger_display.Name = (string) named_arg.Argument.Value;
                        else if (key == "Type")
                            debugger_display.Type = (string) named_arg.Argument.Value;
                        else {
                            debugger_display = null;
                            break;
                        }
                    }
                } else if (cname == browsable_attr) {
                    browsable_state = (DebuggerBrowsableState) cattr.GetBlob () [2];
                } else if (cname == type_proxy_attr) {
                    string text = (string) cattr.ConstructorArguments [0].Value;
                    type_proxy = new DebuggerTypeProxyAttribute (text);
                }
            }
        }
示例#31
0
        private void Converted_BuildPhase1(ILConversion conversion, StructuralTypeNode structuralInputTypeNode, ConvertedTypeDefinition converted,
                                           ConvertedTypeDefinition_I convertedDeclaringType)
        {
            var typeDefinition = (TypeDefinition)structuralInputTypeNode.CecilTypeReference;

            System.Reflection.TypeAttributes attributes = Cecil.Metadata.Members.Types.GetTypeAttributes(typeDefinition);

            var packingSize = Cecil.GetPackingSize(typeDefinition);

            if (converted is ConvertedTypeDefinitionWithDeclaringType_I withDeclaringType)
            {
                if (convertedDeclaringType == null
                    )                     // Can occur if passing in a single nested type or if a nested class gets processed before its parents gets
                                          // processed.
                {
                    if (!(converted.SourceTypeReference is TypeDefinition))
                    {
                        throw new Exception("Expected a type definition");
                    }

                    var semanticDeclaringType =
                        Execution.Types.Ensuring.Ensure(conversion, converted.SourceTypeReference.DeclaringType, null,
                                                        null);

                    if (!(semanticDeclaringType is ConvertedTypeDefinition_I producedDeclaringType))
                    {
                        throw new Exception(
                                  $"Expected the declaring type of a nested class to be castable to {typeof(ConvertedTypeDefinition_I)}");
                    }

                    convertedDeclaringType = producedDeclaringType;
                }

                withDeclaringType.DeclaringType = convertedDeclaringType;

                // The plus sign and the parent class name before it needs to be dropped from the full name prior to calling define nested class
                // as the type builder will automatically add them back on based upon the name of the declaring type.
                var fullName = Conversion.Metadata.Members.Types.Naming.GetTypeBuilderNestedClassFullName(converted.FullName);

                // The !IsEnum check prevents: [MD]: Error: ClassLayout has parent TypeDef token=0x02000036 marked AutoLayout. [token:0x00000001]
                // The Class or ValueType indexed by Parent shall be SequentialLayout or ExplicitLayout (§II.23.1.15).
                // That is, AutoLayout types shall not own any rows in the ClassLayout table. [ERROR]
                if (typeDefinition.IsValueType && !typeDefinition.IsEnum)
                {
                    converted.TypeBuilder = convertedDeclaringType.TypeBuilder.DefineNestedType(converted.FullName, attributes, null, (PackingSize)typeDefinition.PackingSize, typeDefinition.ClassSize);
                }
                else
                {
                    converted.TypeBuilder = convertedDeclaringType.TypeBuilder.DefineNestedType(fullName, attributes, null, packingSize);
                }
            }
            else
            {
                if (converted.FullName == "Root.Testing.Resources.Models.E01D.Runtimic.Execution.Emitting.Conversion.Inputs.Types.SimpleValueType")
                {
                }

                if (converted.FullName == "<Module>")
                {
                    var x = converted.Module.ModuleBuilder.GetType("<Module>", true);
                }

                // The !IsEnum check prevents: [MD]: Error: ClassLayout has parent TypeDef token=0x02000036 marked AutoLayout. [token:0x00000001]
                // The Class or ValueType indexed by Parent shall be SequentialLayout or ExplicitLayout (§II.23.1.15).
                // That is, AutoLayout types shall not own any rows in the ClassLayout table. [ERROR]
                if (typeDefinition.IsValueType && !typeDefinition.IsEnum)
                {
                    converted.TypeBuilder = converted.Module.ModuleBuilder.DefineType(converted.FullName, attributes, null, (PackingSize)typeDefinition.PackingSize, typeDefinition.ClassSize);
                }
                else
                {
                    converted.TypeBuilder = converted.Module.ModuleBuilder.DefineType(converted.FullName, attributes, null, packingSize);
                }
            }

            converted.UnderlyingType = converted.TypeBuilder;

            //this.Unified.Types.ExtendWithCrossReference(conversion.Model, converted,
            //	converted.UnderlyingType.AssemblyQualifiedName);

            Conversion.Metadata.Members.Types.Building.UpdateBuildPhase(converted, BuildPhaseKind.TypeDefined);
        }
示例#32
0
        Cecil.AssemblyDefinition resolve_cecil_asm_name(Cecil.AssemblyNameReference name)
        {
            foreach (MonoSymbolFile symfile in symfile_hash.Values) {
                if (name.FullName == symfile.Assembly.Name.FullName)
                    return symfile.Assembly;
            }

            return null;
        }
示例#33
0
        public static MonoClassInfo ReadCoreType(MonoSymbolFile file,
							  Cecil.TypeDefinition typedef,
							  TargetMemoryAccess target,
							  TargetAddress klass,
							  out MonoClassType type)
        {
            MonoClassInfo info = new MonoClassInfo (file, typedef, target, klass);
            type = new MonoClassType (file, typedef, info);
            ((IMonoStructType) type).ClassInfo = info;
            info.struct_type = type;
            info.type = type;
            return info;
        }
示例#34
0
        public TargetType LookupMonoType(Cecil.TypeReference type)
        {
            MonoSymbolFile file;

            Cecil.TypeDefinition typedef = type as Cecil.TypeDefinition;
            if (typedef != null) {
                file = (MonoSymbolFile) assembly_hash [type.Module.Assembly];
                if (file == null) {
                    Console.WriteLine ("Type `{0}' from unknown assembly `{1}'",
                               type, type.Module.Assembly);
                    return null;
                }

                return file.LookupMonoType (typedef);
            }

            Cecil.ArrayType array = type as Cecil.ArrayType;
            if (array != null) {
                TargetType element_type = LookupMonoType (array.ElementType);
                if (element_type == null)
                    return null;

                return new MonoArrayType (element_type, array.Rank);
            }

            Cecil.ByReferenceType reftype = type as Cecil.ByReferenceType;
            if (reftype != null) {
                TargetType element_type = LookupMonoType (reftype.ElementType);
                if (element_type == null)
                    return null;

                return new MonoPointerType (element_type);
            }

            Cecil.GenericParameter gen_param = type as Cecil.GenericParameter;
            if (gen_param != null)
                return new MonoGenericParameterType (this, gen_param.Name);

            Cecil.GenericInstanceType gen_inst = type as Cecil.GenericInstanceType;
            if (gen_inst != null) {
                TargetType[] args = new TargetType [gen_inst.GenericArguments.Count];
                for (int i = 0; i < args.Length; i++) {
                    args [i] = LookupMonoType (gen_inst.GenericArguments [i]);
                    if (args [i] == null)
                        return null;
                }

                MonoClassType container = LookupMonoType (gen_inst.ElementType)
                    as MonoClassType;
                if (container == null)
                    return null;

                return new MonoGenericInstanceType (container, args, TargetAddress.Null);
            }

            int rank = 0;

            string full_name = type.FullName;
            int pos = full_name.IndexOf ('[');
            if (pos > 0) {
                string dim = full_name.Substring (pos);
                full_name = full_name.Substring (0, pos);

                if ((dim.Length < 2) || (dim [dim.Length - 1] != ']'))
                    throw new ArgumentException ();
                for (int i = 1; i < dim.Length - 1; i++)
                    if (dim [i] != ',')
                        throw new ArgumentException ();

                rank = dim.Length - 1;
            }

            TargetType mono_type = LookupType (full_name);
            if (mono_type == null)
                return null;

            if (rank > 0)
                return new MonoArrayType (mono_type, rank);
            else
                return mono_type;
        }
示例#35
0
 public static int GetMethodToken(Cecil.MethodDefinition method)
 {
     return (int) (method.MetadataToken.TokenType + method.MetadataToken.RID);
 }
示例#36
0
        internal MonoClassType CreateCoreType(MonoSymbolFile file, Cecil.TypeDefinition typedef,
						       TargetMemoryAccess memory, TargetAddress klass)
        {
            MonoClassType type;
            MonoClassInfo info = MonoClassInfo.ReadCoreType (
                file, typedef, memory, klass, out type);
            class_info_by_addr.Add (klass, info);

            return type;
        }
示例#37
0
 public static Cecil.MethodDefinition GetMethod(Cecil.ModuleDefinition module, int token)
 {
     return (Cecil.MethodDefinition) module.LookupByToken (
         Cecil.Metadata.TokenType.Method, token & 0xffffff);
 }
示例#38
0
文件: Utils.cs 项目: baulig/debugger
        static void DumpLineNumberTable_internal(TextWriter writer, MonoSymbolFile file,
							  Cecil.MethodDefinition mdef, C.MethodEntry entry)
        {
            string full_name = MonoSymbolFile.GetMethodName (mdef);
            if (mdef.MetadataToken.TokenType != Cecil.Metadata.TokenType.Method) {
                writer.WriteLine ("UNKNOWN METHOD: {0}", full_name);
                return;
            }

            writer.WriteLine ();
            writer.WriteLine ("Symfile Line Numbers (file / row / offset):");
            writer.WriteLine ("-------------------------------------------");

            C.LineNumberEntry[] lnt;
            lnt = entry.GetLineNumberTable ().LineNumbers;
            for (int i = 0; i < lnt.Length; i++) {
                C.LineNumberEntry lne = lnt [i];

                writer.WriteLine ("{0,4} {1,4} {2,4} {3,4:x}{4}", i,
                          lne.File, lne.Row, lne.Offset,
                          lne.IsHidden ? " (hidden)" : "");
            }

            writer.WriteLine ("-------------------------------------------");
            writer.WriteLine ();

            List<string> lines;
            Dictionary<int,int> offsets;

            if (!DisassembleMethod_internal (file.ImageFile, (int) mdef.MetadataToken.RID, out lines, out offsets)) {
                writer.WriteLine ("Cannot disassemble method: {0}", full_name);
                return;
            }

            writer.WriteLine ("Disassembling {0}:\n\n{1}\n", full_name, String.Join ("\n", lines.ToArray ()));
        }
示例#39
0
 public static int GetMethodToken(Cecil.MethodDefinition method)
 {
     return method.MetadataToken.ToInt32 ();
 }
示例#40
0
        // This must match mono_type_get_desc() in mono/metadata/debug-helpers.c.
        protected static string GetTypeSignature(Cecil.TypeReference t)
        {
            Cecil.ByReferenceType rtype = t as Cecil.ByReferenceType;
            if (rtype != null)
                return GetTypeSignature (rtype.ElementType) + "&";

            Cecil.ArrayType atype = t as Cecil.ArrayType;
            if (atype != null) {
                string etype = GetTypeSignature (atype.ElementType);
                if (atype.Rank > 1)
                    return String.Format ("{0}[{1}]", etype, atype.Rank);
                else
                    return etype + "[]";
            }

            switch (t.FullName) {
            case "System.Char":	return "char";
            case "System.Boolean":	return "bool";
            case "System.Byte":	return "byte";
            case "System.SByte":	return "sbyte";
            case "System.Int16":	return "int16";
            case "System.UInt16":	return "uint16";
            case "System.Int32":	return "int";
            case "System.UInt32":	return "uint";
            case "System.Int64":	return "long";
            case "System.UInt64":	return "ulong";
            case "System.Single":	return "single";
            case "System.Double":	return "double";
            case "System.String":	return "string";
            case "System.Object":	return "object";
            case "System.Decimal":  return "decimal";
            default:		return RemoveGenericArity (t.FullName);
            }
        }
示例#41
0
 public void AddType(Cecil.TypeDefinition typedef, TargetType type)
 {
     if (!type_hash.Contains (typedef))
         type_hash.Add (typedef, type);
 }
示例#42
0
        protected MonoClassType LookupMonoClass(Cecil.TypeReference typeref)
        {
            TargetType type = LookupMonoType (typeref);
            if (type == null)
                return null;

            MonoClassType class_type = type as MonoClassType;
            if (class_type != null)
                return class_type;

            if (type.HasClassType)
                return (MonoClassType) type.ClassType;

            throw new InternalError ("UNKNOWN TYPE: {0}", type);
        }
示例#43
0
 public TypeHashEntry(Cecil.TypeDefinition type)
 {
     Token = (int) (type.MetadataToken.TokenType + type.MetadataToken.RID);
 }
示例#44
0
		Ast.Expression Convert(Ast.Expression expr, Cecil.TypeReference actualType, Cecil.TypeReference reqType)
		{
			if (actualType == null || reqType == null || TypeAnalysis.IsSameType(actualType, reqType)) {
				return expr;
			} else if (actualType is ByReferenceType && reqType is PointerType && expr is DirectionExpression) {
				return Convert(
					new UnaryOperatorExpression(UnaryOperatorType.AddressOf, ((DirectionExpression)expr).Expression.Detach()),
					new PointerType(((ByReferenceType)actualType).ElementType),
					reqType);
			} else if (actualType is PointerType && reqType is ByReferenceType) {
				expr = Convert(expr, actualType, new PointerType(((ByReferenceType)reqType).ElementType));
				return new DirectionExpression {
					FieldDirection = FieldDirection.Ref,
					Expression = new UnaryOperatorExpression(UnaryOperatorType.Dereference, expr)
				};
			} else if (actualType is PointerType && reqType is PointerType) {
				if (actualType.FullName != reqType.FullName)
					return expr.CastTo(AstBuilder.ConvertType(reqType));
				else
					return expr;
			} else {
				bool actualIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(actualType);
				bool requiredIsIntegerOrEnum = TypeAnalysis.IsIntegerOrEnum(reqType);
				
				if (TypeAnalysis.IsBoolean(reqType)) {
					if (TypeAnalysis.IsBoolean(actualType))
						return expr;
					if (actualIsIntegerOrEnum) {
						return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, AstBuilder.MakePrimitive(0, actualType));
					} else {
						return new BinaryOperatorExpression(expr, BinaryOperatorType.InEquality, new NullReferenceExpression());
					}
				}
				if (TypeAnalysis.IsBoolean(actualType) && requiredIsIntegerOrEnum) {
					return new ConditionalExpression {
						Condition = expr,
						TrueExpression = AstBuilder.MakePrimitive(1, reqType),
						FalseExpression = AstBuilder.MakePrimitive(0, reqType)
					};
				}

				if (expr is PrimitiveExpression && !requiredIsIntegerOrEnum && TypeAnalysis.IsEnum(actualType))
				{
					return expr.CastTo(AstBuilder.ConvertType(actualType));
				}
				
				bool actualIsPrimitiveType = actualIsIntegerOrEnum
					|| actualType.MetadataType == MetadataType.Single || actualType.MetadataType == MetadataType.Double;
				bool requiredIsPrimitiveType = requiredIsIntegerOrEnum
					|| reqType.MetadataType == MetadataType.Single || reqType.MetadataType == MetadataType.Double;
				if (actualIsPrimitiveType && requiredIsPrimitiveType) {
					return expr.CastTo(AstBuilder.ConvertType(reqType));
				}
				return expr;
			}
		}
示例#45
0
 public MdbSymbolReader(Cecil.AssemblyDefinition asm, MonoSymbolFile file)
 {
     this.Assembly = asm;
     this.File = file;
 }