private static void SwapParameterTypes(MethodDefinition method, TypeDefinition targetDependency, TypeReference interfaceType, HashSet<MethodReference> modifiedMethods) { if (method.IsAbstract || !method.HasBody) return; bool modified = false; var parameters = method.Parameters.Cast<ParameterDefinition>(); foreach (var parameter in parameters) { var parameterType = parameter.ParameterType; if (parameterType != targetDependency) continue; parameter.ParameterType = interfaceType; modified = true; } if (!modified) return; modifiedMethods.Add(method); }
private void ExtractLayoutInformation(AnalysisNet.Types.TypeDefinition type, Cecil.TypeDefinition typeDefinition) { AnalysisNet.Types.LayoutKind kind; if (typeDefinition.IsAutoLayout) { kind = AnalysisNet.Types.LayoutKind.AutoLayout; } else if (typeDefinition.IsExplicitLayout) { kind = AnalysisNet.Types.LayoutKind.ExplicitLayout; } else if (typeDefinition.IsSequentialLayout) { kind = AnalysisNet.Types.LayoutKind.SequentialLayout; } else { throw new NotImplementedException(); } Model.Types.LayoutInformation layoutInformation = new AnalysisNet.Types.LayoutInformation(kind) { ClassSize = typeDefinition.ClassSize, PackingSize = typeDefinition.PackingSize }; type.LayoutInformation = layoutInformation; }
private AnalysisNet.Types.TypeDefinition ExtractClass(Cecil.TypeDefinition cecilType, AnalysisNet.Types.TypeKind typeKind, AnalysisNet.Types.TypeDefinitionKind typeDefinitionKind) { string name = UnmangleName(cecilType); AnalysisNet.Types.TypeDefinition type = new AnalysisNet.Types.TypeDefinition(name, typeKind, typeDefinitionKind); Cecil.TypeReference basedef = cecilType.BaseType; type.IsAbstract = cecilType.IsAbstract; type.IsSealed = cecilType.IsSealed; if (basedef != null) { type.Base = ExtractType(basedef) as AnalysisNet.Types.IBasicType; } ExtractCustomAttributes(type.Attributes, cecilType.CustomAttributes); ExtractGenericTypeParameters(type, cecilType); ExtractInterfaces(type.Interfaces, cecilType.Interfaces); ExtractFields(type, type.Fields, cecilType.Fields); ExtractMethods(type, type.Methods, cecilType.Methods); ExtractPropertyDefinitions(type, cecilType); ExtractExplicitMethodOverrides(type, cecilType); ExtractLayoutInformation(type, cecilType); return(type); }
public AnalysisNet.Types.TypeDefinition ExtractTypeDefinition(Cecil.TypeDefinition cecilType) { AnalysisNet.Types.TypeDefinition result; // the order matters // an enum can be a value type if (cecilType.IsEnum) { result = ExtractEnum(cecilType); } else if (cecilType.IsValueType) { result = ExtractClass(cecilType, AnalysisNet.Types.TypeKind.ValueType, AnalysisNet.Types.TypeDefinitionKind.Struct); } else if (cecilType.IsClass) { // includes delegates! AnalysisNet.Types.TypeDefinitionKind kind = IsDelegate(cecilType) ? AnalysisNet.Types.TypeDefinitionKind.Delegate : AnalysisNet.Types.TypeDefinitionKind.Class; result = ExtractClass(cecilType, AnalysisNet.Types.TypeKind.ReferenceType, kind); } else if (cecilType.IsInterface) { result = ExtractInterface(cecilType); } else { throw new NotImplementedException(); } return(result); }
// the extracted type is added to the expected namespace // if cecilType is a nested type, we guarantee that we have already visited its declaring type private void ExtractTypeDefinition(Cecil.TypeDefinition cecilType, AnalysisNet.Assembly assembly, TypeExtractor typeExtractor) { // afaik it is not necessary to generate this class // for instance cci does not even load it although cecil does if (cecilType.Name.Equals("<Module>") && cecilType.BaseType == null) { return; } AnalysisNet.Types.TypeDefinition extractedType = typeExtractor.ExtractTypeDefinition(cecilType); typeDefinitions[cecilType] = extractedType; extractedType.ContainingAssembly = assembly; // analysis-net does not follow ecma standard for nested types // analysis-net expects to have nested types in their ContainingType.Types and share the same namespace that its enclosing type. // However, nested types should not be added to the ContainingNamespace.Types // If the type is not nested then the processed type is added to its namespace directly if (cecilType.DeclaringType != null) { AnalysisNet.Types.TypeDefinition containingType = typeDefinitions[cecilType.DeclaringType]; extractedType.ContainingType = containingType; containingType.Types.Add(extractedType); extractedType.ContainingNamespace = containingType.ContainingNamespace; } else { AnalysisNet.Namespace ns = GetOrCreateNamespace(cecilType.Namespace); extractedType.ContainingNamespace = ns; ns.Types.Add(extractedType); } }
public TypeDefinition addType(String sTypeNameSpace, String sTypeName, TypeAttributes taTypeAttributes, TypeReference trTypeReference) { var tdNewType = new TypeDefinition(sTypeName, sTypeNameSpace, taTypeAttributes, trTypeReference); mainModule.Types.Add(tdNewType); return tdNewType; }
private MonoStringType(MonoSymbolFile file, Cecil.TypeDefinition typedef, int object_size, int size) : base(file, typedef, "string", FundamentalKind.String, size) { this.ObjectSize = object_size; this.CreateString = file.MonoLanguage.MonoDebuggerInfo.CreateString; }
public RuleResult CheckType (TypeDefinition type) { //type does not apply if not an interface or is an empty interface if (!type.IsInterface || !type.HasMethods) return RuleResult.DoesNotApply; //TODO: take into account [InternalsVisibleTo] on iface's assembly AssemblyDefinition current_assembly = type.Module.Assembly; if (type.IsVisible ()) { // We should not, by default, promote the implementation of interfaces in assemblies that // do not, already, refer to the current one because: // (a) we could be suggesting circular references (solvable, or not, by refactoring) // (b) it has a very HIGH performance cost, with verry LITTLE value (in # of defects) string current_assembly_name = current_assembly.Name.Name; foreach (AssemblyDefinition assembly in Runner.Assemblies) { // by default only process assemblies (from the set) that refers to the current one // or the current one itself if (!ReferencesOnly || (current_assembly_name == assembly.Name.Name) || assembly.References (current_assembly_name)) { CheckAssemblyTypes (assembly, type); } } } else { // if the interface is not visible then we only check this assembly CheckAssemblyTypes (current_assembly, type); } return Runner.CurrentRuleResult; }
private void AddMaskingProperty(Cecil.TypeDefinition type, Cecil.PropertyDefinition property) { var maskedPropety = new Cecil.PropertyDefinition(property.Name + "Mask", Cecil.PropertyAttributes.None, ModuleDefinition.TypeSystem.String); //maskedPropety.GetMethod = type.Properties.Add(maskedPropety); }
public RuleResult CheckType(TypeDefinition type) { if (!type.IsClass || type.IsAbstract || !type.HasMethods) return RuleResult.DoesNotApply; // check if TestFixture is applied to any type in the hierarchy TypeDefinition testingType = type; while (testingType != null) { if (testingType.HasAttribute ("NUnit.Framework", "TestFixtureAttribute")) return RuleResult.Success; if (testingType.BaseType != null) testingType = testingType.BaseType.Resolve (); else break; } foreach (MethodDefinition method in type.Methods) { if (method.IsTest ()) { Severity severity = (NUnitVersion == null || NUnitVersion < Version25) ? Severity.High : Severity.Low; Runner.Report (method, severity, Confidence.High); return RuleResult.Failure; } } return Runner.CurrentRuleResult; }
/// <summary> /// Create the Ctor /// </summary> private static void CreateDefaultCtor(ReachableContext reachableContext, TypeDefinition type) { var typeSystem = type.Module.TypeSystem; var ctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, typeSystem.Void); ctor.DeclaringType = type; var body = new MethodBody(ctor); body.InitLocals = true; ctor.Body = body; // Prepare code var seq = new ILSequence(); seq.Emit(OpCodes.Nop); seq.Emit(OpCodes.Ret); // Append ret sequence seq.AppendTo(body); // Update offsets body.ComputeOffsets(); // Add ctor type.Methods.Add(ctor); ctor.SetReachable(reachableContext); }
public void Init() { CurrentAssembly = CecilExtensions.CurrentAssembly; ThisType = CurrentAssembly.FindRuntimeType(GetType()); Recompiler = new ILDynaRec.Recompiler(); }
private void GetValues (TypeDefinition type) { values.Clear (); Type ftype = null; foreach (FieldDefinition field in type.Fields) { if (field.IsStatic) { if (ftype == null) ftype = field.Constant.GetType (); ulong value; if (ftype == typeof (ulong)) { value = (ulong) field.Constant; if (value != 0 && !values.Contains (value)) values.Add (value); } else { long v = Convert.ToInt64 (field.Constant); if (v > 0) { value = (ulong) v; if (!values.Contains (value)) values.Add (value); } else if (v < 0) { values.Clear (); break; } } } } }
public static System.Reflection.MethodBase ToSystemMethodInfo(this Mono.Cecil.MethodDefinition md) { System.Reflection.MethodInfo result = null; String md_name = Campy.Utils.Utility.NormalizeMonoCecilName(md.FullName); // Get owning type. Mono.Cecil.TypeDefinition td = md.DeclaringType; Type t = td.ToSystemType(); foreach (System.Reflection.MethodInfo mi in t.GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.Default)) { String full_name = string.Format("{0} {1}.{2}({3})", mi.ReturnType.FullName, Campy.Utils.Utility.RemoveGenericParameters(mi.ReflectedType), mi.Name, string.Join(",", mi.GetParameters().Select(o => string.Format("{0}", o.ParameterType)).ToArray())); full_name = Campy.Utils.Utility.NormalizeSystemReflectionName(full_name); if (md_name.Contains(full_name)) { return(mi); } } foreach (System.Reflection.ConstructorInfo mi in t.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.Default)) { String full_name = string.Format("{0}.{1}({2})", Campy.Utils.Utility.RemoveGenericParameters(mi.ReflectedType), mi.Name, string.Join(",", mi.GetParameters().Select(o => string.Format("{0}", o.ParameterType)).ToArray())); full_name = Campy.Utils.Utility.NormalizeSystemReflectionName(full_name); if (md_name.Contains(full_name)) { return(mi); } } Debug.Assert(result != null); return(result); }
public IEnumerable<TypeReference> OfType(TypeDefinition definition) { if (definition == null) throw new ArgumentNullException("definition"); return definition.Methods.SelectMany(m => OfMethod(m)); }
public RuleResult CheckType (TypeDefinition type) { // rule only apply to (non generated) delegates if (!type.IsDelegate () || type.IsGeneratedCode ()) return RuleResult.DoesNotApply; MethodDefinition invoke = type.GetMethod ("Invoke"); // this happens for System.MulticastDelegate if (invoke == null) return RuleResult.DoesNotApply; if (!invoke.ReturnType.IsNamed ("System", "Void")) return RuleResult.Success; if (!invoke.HasParameters) return RuleResult.Success; IList<ParameterDefinition> pdc = invoke.Parameters; if (pdc.Count != 2) return RuleResult.Success; if (!pdc [0].ParameterType.IsNamed ("System", "Object")) return RuleResult.Success; if (!pdc [1].ParameterType.Inherits ("System", "EventArgs")) return RuleResult.Success; Runner.Report (type, Severity.Medium, Confidence.High); return RuleResult.Failure; }
private MethodDefinition FindOldMethodBody(TypeDefinition oldType, MethodDefinition methodDefinition) { MethodDefinition oldMethodBody = null; if (oldType != null) oldMethodBody = oldType.Methods.SingleOrDefault(m => m.Name == methodDefinition.Name); return oldMethodBody; }
public DerivedTypesTreeNode(AssemblyList list, TypeDefinition type) { this.list = list; this.type = type; this.LazyLoading = true; this.threading = new ThreadingSupport(); }
public BaseTypeWalker(IType type, ComponentCache componentCache = null) : this(componentCache) { Contract.Requires<ArgumentNullException>(type != null); this.type = type.TypeDefinition; }
public void Collect(Mono.Cecil.TypeDefinition td, TypeCollection typeCollection, ConfigBase config) { if (td.ShouldIgnoreType()) { return; } // don't duplicate types if (typeCollection.Contains(td.FullName)) { return; } StringBuilder sb = new StringBuilder(); var indentCount = 0; ITypeWriter typeWriter = typeSelector.PickTypeWriter(td, indentCount, typeCollection, config); td.Interfaces.Each(item => { var foundType = typeCollection.LookupType(item); if (foundType == null) { //TODO: This reporting a missing type is too early in the process. // typeNotFoundErrorHandler.Handle(item); return; } var itemWriter = typeSelector.PickTypeWriter(foundType, indentCount, typeCollection, config); typeCollection.Add(foundType.Namespace, foundType.Name, itemWriter); }); typeCollection.Add(td.Namespace, td.Name, typeWriter); }
public void VisitType(TypeDefinition type) { Log.DebugLine(this, "-----------------------------------"); Log.DebugLine(this, "{0}", type); string names = string.Empty; foreach (PropertyDefinition prop in type.Properties) { string name = prop.Name; MethodDefinition[] methods1 = type.Methods.GetMethod("Get" + name); MethodDefinition[] methods2 = type.Methods.GetMethod("Set" + name); if (methods1.Length > 0 && methods1[0].IsPublic) names += name + " "; else if (methods2.Length > 0 && methods2[0].IsPublic) names += name + " "; } if (names.Length > 0) { Log.DebugLine(this, "names: {0}", names); Reporter.TypeFailed(type, CheckID, "Properties: " + names); } }
public RuleResult CheckType (TypeDefinition type) { // Only check for value types and types with fields. // But also for types with attributes, since FXCop only issues a warning if ComVisible is explicitly defined. if (!type.IsValueType || !type.HasCustomAttributes || !type.HasFields) return RuleResult.DoesNotApply; // Ensure the defining assembly is not null, then perform the same check for attributes on the assembly. AssemblyDefinition assembly = type.GetAssembly (); if (assembly != null && !assembly.HasCustomAttributes) return RuleResult.DoesNotApply; // Iterate through attributes on the type and assembly to ensure that ComVisible is false on the assembly, // and true on the type. bool exp; if (assembly != null) { if (assembly.IsComVisible (out exp) && exp) return RuleResult.Success; } if (!type.IsComVisible (out exp) && exp) return RuleResult.Success; // If we find any, low severity as the code works, but it's bad practice. foreach (FieldDefinition field in type.Fields) if (!field.IsPublic) Runner.Report (field, Severity.Low, Confidence.Total); return Runner.CurrentRuleResult; }
public TypeWriterBase(TypeDefinition typeDefinition, int indentCount, TypeCollection typeCollection, ConfigBase config) { this.TypeDefinition = typeDefinition; this.IndentCount = indentCount; this.TypeCollection = typeCollection; this.Config = config; }
private void SetAttributes(AnalysisNet.Types.TypeDefinition typeDefinition, Cecil.TypeDefinition cecilDef) { cecilDef.IsAbstract = typeDefinition.IsAbstract; cecilDef.IsSealed = typeDefinition.IsSealed; if (typeDefinition.ContainingType != null) { cecilDef.IsNestedPublic = true; } else { cecilDef.IsPublic = true; } if (typeDefinition.LayoutInformation is AnalysisNet.Types.LayoutInformation layoutInfo) { if (layoutInfo.Kind == AnalysisNet.Types.LayoutKind.AutoLayout) { cecilDef.IsAutoLayout = true; } else if (layoutInfo.Kind == AnalysisNet.Types.LayoutKind.ExplicitLayout) { cecilDef.IsExplicitLayout = true; } else if (layoutInfo.Kind == AnalysisNet.Types.LayoutKind.SequentialLayout) { cecilDef.IsSequentialLayout = true; } cecilDef.PackingSize = layoutInfo.PackingSize; cecilDef.ClassSize = layoutInfo.ClassSize; } }
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type) { if (!type.HasInterfaces) yield break; TypeReference implementedInterfaceRef = type.Interfaces.FirstOrDefault(i => i.Resolve() == analyzedMethod.DeclaringType); if (implementedInterfaceRef == null) yield break; foreach (MethodDefinition method in type.Methods.Where(m => m.Name == analyzedMethod.Name)) { if (TypesHierarchyHelpers.MatchInterfaceMethod(method, analyzedMethod, implementedInterfaceRef)) { var node = new AnalyzedMethodTreeNode(method); node.Language = this.Language; yield return node; } yield break; } foreach (MethodDefinition method in type.Methods) { if (method.HasOverrides && method.Overrides.Any(m => m.Resolve() == analyzedMethod)) { var node = new AnalyzedMethodTreeNode(method); node.Language = this.Language; yield return node; } } }
public Cecil.MethodDefinition MethodDefinition(AnalysisNet.Types.MethodDefinition methodDefinition) { Cecil.MethodDefinition cecilMethodDefinition = new Cecil.MethodDefinition(methodDefinition.Name, 0, Context.CurrentModule.TypeSystem.Void); GenerateMethodAttributes(methodDefinition, cecilMethodDefinition); cecilMethodDefinition.CreateGenericParameters(methodDefinition.GenericParameters.Count); Cecil.TypeReference returnType = ReferenceGenerator.TypeReference(methodDefinition.ReturnType); cecilMethodDefinition.ReturnType = returnType; AddConstraintsToGenericParameters(methodDefinition, cecilMethodDefinition); Cecil.TypeReference typeRef = ReferenceGenerator.TypeReference(methodDefinition.ContainingType); Cecil.TypeDefinition containingType = typeRef.Resolve(); cecilMethodDefinition.DeclaringType = containingType as Cecil.TypeDefinition; SetOverrides(methodDefinition, cecilMethodDefinition); SetCustomAttributes(methodDefinition.Attributes, cecilMethodDefinition.CustomAttributes); IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.ParameterDefinition> parameterDefinitions = CreateParameters(methodDefinition, cecilMethodDefinition); if (methodDefinition.HasBody) { cecilMethodDefinition.Body.MaxStackSize = methodDefinition.Body.MaxStack; cecilMethodDefinition.Body.InitLocals = methodDefinition.Body.LocalVariables.Count > 0; IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.Cil.VariableDefinition> variableDefinitions = CreateLocalVariables(methodDefinition, cecilMethodDefinition); InstructionGenerator instructionGenerator = new InstructionGenerator(ReferenceGenerator); // analysis-net instruction -> [cecil instruction] IDictionary <AnalysisNet.Bytecode.Instruction, IList <Cecil.Cil.Instruction> > mapInstructions = instructionGenerator.CreateInstructions(methodDefinition, cecilMethodDefinition, variableDefinitions, parameterDefinitions); CreateExceptionHandlers(mapInstructions, methodDefinition.Body, cecilMethodDefinition.Body); } return(cecilMethodDefinition); }
public static void EmitInsideNamespace(this JavascriptFormatter formatter, TypeDefinition typedef, bool isTopLevel, Action <bool> inner) { var fullNamespace = DefinitelyTypedUtilities.GetFullNamespace(typedef); foreach (var part in fullNamespace) { if (isTopLevel) { formatter.WriteRaw("export"); formatter.Space(); formatter.WriteRaw("declare"); formatter.Space(); isTopLevel = false; } formatter.WriteRaw("namespace"); formatter.Space(); formatter.Identifier(part); formatter.Space(); formatter.OpenBrace(); } inner(isTopLevel); foreach (var part in fullNamespace) { formatter.CloseBrace(); } }
public static void WriteSelfReference(this JavascriptFormatter formatter, TypeDefinition typeDefinition, Facade facade) { switch (facade) { case Facade.Instance: formatter.Identifier("Instance"); formatter.WriteGenericArgumentsIfNeed(typeDefinition.GenericParameters, null); break; case Facade.TIn: formatter.Identifier("TIn"); formatter.WriteGenericArgumentsIfNeed(typeDefinition.GenericParameters, null); break; case Facade.TOut: formatter.Identifier("TOut"); formatter.WriteGenericArgumentsIfNeed(typeDefinition.GenericParameters, null); break; case Facade.Static: formatter.Identifier("Static"); formatter.WriteGenericArgumentsIfNeed(typeDefinition.GenericParameters, null); break; case Facade.Factory: formatter.Identifier("Factory"); break; default: throw new ArgumentOutOfRangeException("facade", facade, null); } }
public RuleResult CheckType (TypeDefinition type) { //does rule apply? if (type.IsEnum || type.IsInterface || type.IsAbstract || type.IsDelegate () || type.IsGeneratedCode ()) return RuleResult.DoesNotApply; if (!type.HasFields || (type.Fields.Count < MinimumFieldCount)) return RuleResult.DoesNotApply; if (!type.HasMethods || (type.Methods.Count < MinimumMethodCount)) return RuleResult.DoesNotApply; //yay! rule do apply! double coh = GetCohesivenessForType (type); if (coh >= SuccessLowerLimit) return RuleResult.Success; if (0 == coh) return RuleResult.DoesNotApply; //how's severity? Severity sev = GetCohesivenessSeverity(coh); string msg = String.Format (CultureInfo.CurrentCulture, "Type cohesiveness : {0}%", (int) (coh * 100)); Runner.Report (type, sev, Confidence.Normal, msg); return RuleResult.Failure; }
public void Init() { CurrentAssembly = Cecil.AssemblyDefinition.ReadAssembly(Reflection.Assembly.GetExecutingAssembly().Location); ThisType = CurrentAssembly.FindRuntimeType(GetType()); Recompiler = new ILDynaRec.Recompiler(); }
private IEnumerable<SharpTreeNode> FindReferencesInType(TypeDefinition type) { if (analyzedType.IsEnum && type == analyzedType) yield break; if (!this.Language.ShowMember(type)) yield break; foreach (FieldDefinition field in type.Fields) { if (TypeIsExposedBy(field)) yield return new AnalyzedFieldTreeNode(field); } foreach (PropertyDefinition property in type.Properties) { if (TypeIsExposedBy(property)) yield return new AnalyzedPropertyTreeNode(property); } foreach (EventDefinition eventDef in type.Events) { if (TypeIsExposedBy(eventDef)) yield return new AnalyzedEventTreeNode(eventDef); } foreach (MethodDefinition method in type.Methods) { if (TypeIsExposedBy(method)) yield return new AnalyzedMethodTreeNode(method); } }
private bool GetFieldOrProperty(ILWeaver weaver, MethodDefinition originalMethod, TypeDefinition currentArg, string[] target, Patching.Patcher patcher) { if (currentArg == null || target == null || target.Length == 0) { return(false); } int i; TypeDefinition arg = currentArg; for (i = 0; i < target.Length; i++) { if (GetFieldOrProperty(weaver, originalMethod, ref arg, target[i], patcher)) { continue; } ShowMsg($"Could not find the field or property `{target[i]}` in any of the base classes or interfaces of `{currentArg.Name}`.", "Invalid field or property", patcher); return(false); } if (arg.IsValueType || arg.IsByReference) { weaver.Add(arg.Module == originalMethod.Module ? Instruction.Create(OpCodes.Box, arg.Resolve()) : Instruction.Create(OpCodes.Box, originalMethod.Module.Import(arg.Resolve()))); } return(i >= 1); }
private void EmitClassFactory(TypeDefinition typedef) { if (typedef.GenericParameters.Count > 0) { Formatter.WriteRaw("interface"); Formatter.Space(); Formatter.WriteSelfReference(typedef, Facade.Factory); Formatter.Space(); Formatter.OpenBrace(); Formatter.Identifier("Of"); Formatter.WriteGenericMethodSignatureWithoutResultType(typedef.GenericParameters, null); Formatter.Space(); Formatter.WriteRaw(":"); Formatter.Space(); Formatter.WriteSelfReference(typedef, Facade.Static); Formatter.CloseBrace(); } else { Formatter.WriteRaw("type"); Formatter.Space(); Formatter.WriteSelfReference(typedef, Facade.Factory); Formatter.Space(); Formatter.WriteRaw("="); Formatter.Space(); Formatter.WriteSelfReference(typedef, Facade.Static); Formatter.Semicolon(); } }
private void ProcessType(bool? assemblyConfigureAwaitValue, TypeDefinition type) { if (type.IsCompilerGenerated() && type.IsIAsyncStateMachine()) { return; } var configureAwaitValue = (bool?)type.GetConfigureAwaitAttribute()?.ConstructorArguments[0].Value; configureAwaitValue = configureAwaitValue ?? assemblyConfigureAwaitValue; foreach (var method in type.Methods) { var localConfigureAwaitValue = (bool?)method.GetConfigureAwaitAttribute()?.ConstructorArguments[0].Value; var localConfigWasSet = localConfigureAwaitValue.HasValue; localConfigureAwaitValue = localConfigureAwaitValue ?? configureAwaitValue; if (localConfigureAwaitValue == null) continue; var asyncStateMachineType = method.GetAsyncStateMachineType(); if (asyncStateMachineType != null) { AddAwaitConfigToAsyncMethod(asyncStateMachineType, localConfigureAwaitValue.Value); } else if (localConfigWasSet) { LogWarning($"ConfigureAwaitAttribue applied to non-async method '{method.FullName}'."); continue; } } }
public MessageCollection CheckType(TypeDefinition type, Runner runner) { MessageCollection messageCollection = new MessageCollection(); foreach (MethodDefinition method in type.Methods) { if (!method.IsStatic) { return null; } } foreach (FieldDefinition field in type.Fields) { if (!field.IsStatic) { return null; } } foreach (MethodDefinition ctor in type.Constructors) { if (!ctor.IsStatic && (ctor.Attributes & MethodAttributes.Public) == MethodAttributes.Public) { Location location = new Location(type.Name, ctor.Name, 0); Message message = new Message(MessageString, location, MessageType.Error); messageCollection.Add(message); } } return messageCollection.Count > 0 ? messageCollection : null; }
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type) { foreach (MethodDefinition method in type.Methods) { bool found = false; if (!method.HasBody) continue; // ignore chained constructors // (since object is the root of everything, we can short circuit the test in this case) if (method.Name == ".ctor" && (isSystemObject || analyzedType == type || TypesHierarchyHelpers.IsBaseType(analyzedType, type, false))) continue; foreach (Instruction instr in method.Body.Instructions) { MethodReference mr = instr.Operand as MethodReference; if (mr != null && mr.Name == ".ctor") { if (Helpers.IsReferencedBy(analyzedType, mr.DeclaringType)) { found = true; break; } } } method.Body = null; if (found) { var node = new AnalyzedMethodTreeNode(method); node.Language = this.Language; yield return node; } } }
private MethodUsage CreateUsage(MemberReference operand, ModuleDefinition assembly, TypeDefinition type, MethodDefinition method, string testAssemblyPath) { if (operand == null) return null; Test test = new Test { PathToAssembly = Path.GetDirectoryName(testAssemblyPath), AssemblyName = assembly.Assembly.Name.Name, NamespaceName = type.Namespace, ClassName = type.Name, MethodName = method.Name }; var instructionCall = new MethodUsage { AssemblyName = operand.DeclaringType.Scope.Name + ".dll", NamespaceName = operand.DeclaringType.Namespace, ClassName = operand.DeclaringType.Name, MethodName = operand.Name, TestCoverage = new List<Test> {test} }; return instructionCall; }
private static bool IsInstantiationOf(TypeDefinition definition, Instruction candidate) { if (candidate.OpCode != OpCodes.Newobj) return false; MethodReference ctor = (MethodReference) candidate.Operand; return ctor.DeclaringType.Resolve() == definition; }
private IEnumerable<AnalyzerTreeNode> FindReferencesInType(TypeDefinition type) { string name = analyzedMethod.Name; foreach (MethodDefinition method in type.Methods) { bool found = false; if (!method.HasBody) continue; foreach (Instruction instr in method.Body.Instructions) { MethodReference mr = instr.Operand as MethodReference; if (mr != null && mr.Name == name && Helpers.IsReferencedBy(analyzedMethod.DeclaringType, mr.DeclaringType) && mr.Resolve() == analyzedMethod) { found = true; break; } } method.Body = null; if (found) { MethodDefinition codeLocation = this.Language.GetOriginalCodeLocation(method) as MethodDefinition; if (codeLocation != null && !HasAlreadyBeenFound(codeLocation)) { var node= new AnalyzedMethodTreeNode(codeLocation); node.Language = this.Language; yield return node; } } } }
private static bool IsCastTo(TypeDefinition castTarget, Instruction instruction) { if (instruction.OpCode != OpCodes.Castclass) return false; TypeReference typeReference = (TypeReference)instruction.Operand; return typeReference.Resolve() == castTarget; }
private static void CompileType(Mono.Cecil.TypeDefinition sourceType, WasmModuleBuilder wasmBuilder) { foreach (var sourceMethod in sourceType.Methods) { CompileMethod(sourceMethod, wasmBuilder); } }
internal virtual TypeDefinition GetInjecteeCecilType(ModuleDefinition module) { if (_injecteeCecilDef == null) _injecteeCecilDef = module.FindMatchingType(InjecteeType, true); return _injecteeCecilDef; }
private static AssemblyDefinition CreateTestAssembly() { var name = new AssemblyNameDefinition("TestArithmeticOperatorTurtleAdd", new Version(1, 0)); var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll); var type = new TypeDefinition("TestArithmeticOperatorTurtleAdd", "TestClass", TypeAttributes.Class | TypeAttributes.Public); var intType = assembly.MainModule.Import(typeof(int)); var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType); var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType); var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType); method.Parameters.Add(leftParam); method.Parameters.Add(rightParam); var resultVariable = new VariableDefinition(intType); method.Body.Variables.Add(resultVariable); var processor = method.Body.GetILProcessor(); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_1)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_2)); method.Body.Instructions.Add(processor.Create(OpCodes.Add)); method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Ldloc, resultVariable)); method.Body.Instructions.Add(processor.Create(OpCodes.Ret)); type.Methods.Add(method); assembly.MainModule.Types.Add(type); return assembly; }
public void DecompileOnDemand(TypeDefinition type) { if (type == null) return; if (CheckMappings(type.MetadataToken.ToInt32())) return; try { DecompilerContext context = new DecompilerContext(type.Module); AstBuilder astBuilder = new AstBuilder(context); astBuilder.AddType(type); astBuilder.GenerateCode(new PlainTextOutput()); int token = type.MetadataToken.ToInt32(); var info = new DecompileInformation { CodeMappings = astBuilder.CodeMappings, LocalVariables = astBuilder.LocalVariables, DecompiledMemberReferences = astBuilder.DecompiledMemberReferences }; // save the data DebugInformation.AddOrUpdate(token, info, (k, v) => info); } catch { return; } }
/// <summary> /// Adds a GetServiceHashCode method to a target type. /// </summary> /// <param name="targetType">The target type.</param> /// <param name="shouldBeVisible">A boolean flag that indicates whether or not the method should be public.</param> /// <returns>The GetServiceHashCode method.</returns> public MethodDefinition AddGetServiceHashMethodTo(TypeDefinition targetType, bool shouldBeVisible) { var options = new MethodBuilderOptions(); DefineOptions(targetType, shouldBeVisible, options); var module = targetType.Module; var methodBuilder = new MethodBuilder(); var method = methodBuilder.CreateMethod(options); var body = method.Body; var il = body.GetILProcessor (); var getHashCodeMethod = module.ImportMethod<object>("GetHashCode"); var hashVariable = EmitGetServiceTypeHashCode(module, body, il, getHashCodeMethod); // Calculate the hash code for the service name // if it isn't null il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Ceq); var skipNameHash = il.Create(OpCodes.Nop); il.Emit(OpCodes.Brtrue, skipNameHash); EmitGetServiceNameHashCode(il, getHashCodeMethod, hashVariable); il.Append(skipNameHash); il.Emit(OpCodes.Ldloc, hashVariable); il.Emit(OpCodes.Ret); return method; }
public MethodDefinition addMainMethod(TypeDefinition tdTargetType) { MethodDefinition mainMethod = createMethod_StaticVoid("Main"); tdTargetType.Methods.Add(mainMethod); assemblyDefinition.EntryPoint = mainMethod; return mainMethod; }
public RuleResult CheckType (TypeDefinition type) { // rule applies only to types, interfaces and structures (value types) if (type.IsEnum || type.IsDelegate () || type.IsGeneratedCode ()) return RuleResult.DoesNotApply; // rule onyly applies to type that implements IDisposable if (!type.Implements ("System.IDisposable")) return RuleResult.DoesNotApply; // no problem is a finalizer is found if (type.HasMethod (MethodSignatures.Finalize)) return RuleResult.Success; // otherwise check for native types foreach (FieldDefinition field in type.Fields) { // we can't dispose static fields in IDisposable if (field.IsStatic) continue; if (!field.FieldType.GetElementType ().IsNative ()) continue; Runner.Report (field, Severity.High, Confidence.High); } // special case: a struct cannot define a finalizer so it's a // bad candidate to hold references to unmanaged resources if (type.IsValueType && (Runner.CurrentRuleResult == RuleResult.Failure)) Runner.Report (type, Severity.High, Confidence.High, Struct); return Runner.CurrentRuleResult; }
public ILType(ILModule module, Mono.Cecil.TypeDefinition type, ILogger logger) { if (type.HasCustomAttributes && type.IsClass) { attributes.AddRange(type.CustomAttributes); } foreach (Mono.Cecil.FieldDefinition f in type.Fields) { this.fields.Add(f.Name, new ILField(this, f)); } foreach (Mono.Cecil.MethodDefinition m in type.Methods) { if (m.IsStatic == false) { var method = new ILMethod(this, null, logger); method.fail = "only export static method"; methods[m.FullName] = method; } else { var method = new ILMethod(this, m, logger); if (methods.ContainsKey(m.FullName)) { throw new Exception("already have a func named:" + type.FullName + "::" + m.Name); } methods[m.FullName] = method; } } }
public MonoEnumType(MonoSymbolFile file, Cecil.TypeDefinition type) : base(file.MonoLanguage) { this.type = type; this.file = file; class_type = new MonoClassType(file, type); }
private Cecil.TypeDefinition CreateInterfaceDefinition(AnalysisNet.Types.TypeDefinition typeDefinition) { Cecil.TypeDefinition cecilDefinition = CreateClassDefinition(typeDefinition); cecilDefinition.Attributes |= Cecil.TypeAttributes.Interface; cecilDefinition.Attributes |= Cecil.TypeAttributes.Abstract; // todo: not sure about this cecilDefinition.Attributes &= ~Cecil.TypeAttributes.Class; return(cecilDefinition); }
private void EmitClassStatic(TypeDefinition typedef) { Formatter.WriteRaw("interface"); Formatter.Space(); Formatter.WriteSelfReference(typedef, Facade.Static); Formatter.Space(); Formatter.WriteRaw("extends"); Formatter.Space(); Formatter.WriteRaw(typedef.IsAbstract && typedef.IsSealed ? "$StaticType" : "$Type"); Formatter.WriteRaw("<"); Formatter.WriteSelfReference(typedef, Facade.Instance); Formatter.Comma(); Formatter.WriteSelfReference(typedef, Facade.TIn); Formatter.Comma(); Formatter.WriteSelfReference(typedef, Facade.TOut); Formatter.WriteRaw(">"); Formatter.Space(); Formatter.OpenBrace(); var staticFields = typedef.Fields.Where(it => it.IsPublic && it.IsStatic && !Translator.ShouldSkipMember(it)).OrderBy(md => md.Name); foreach (var staticField in staticFields) { EmitField(staticField); } // TODO: We need filter them to not hide fields var staticProperties = typedef.Properties .Where(it => !Translator.ShouldSkipMember(it) && !it.HasParameters && ( (it.GetMethod != null && it.GetMethod.IsPublic && it.GetMethod.IsStatic && !Translator.ShouldSkipMember(it.GetMethod)) || (it.SetMethod != null && it.SetMethod.IsPublic && it.SetMethod.IsStatic && !Translator.ShouldSkipMember(it.SetMethod)))) .OrderBy(md => md.Name); foreach (var staticProperty in staticProperties) { EmitProperty(staticProperty); } var constructors = typedef.Methods.Where(it => it.IsPublic && !it.IsStatic && it.IsConstructor && !Translator.ShouldSkipMember(it)); var staticMethods = typedef.Methods.Where(it => it.IsPublic && it.IsStatic && !it.IsConstructor && !Translator.ShouldSkipMember(it)).OrderBy(it => it.Name); foreach (var method in constructors.Concat(staticMethods)) { EmitMethod(method); } if (typedef.IsInterface) { var instanceMethods = typedef.Methods.Where(it => it.IsPublic && !Translator.ShouldSkipMember(it)).GroupBy(method => method.Name).OrderBy(group => group.Key); foreach (var instanceMethodGroup in instanceMethods) { EmitInterfaceMethodGroup(instanceMethodGroup.Key, instanceMethodGroup); } } Formatter.CloseBrace(); }
public static bool ShouldIgnoreType(this Mono.Cecil.TypeDefinition name) { if (!name.IsPublic) { return(true); } return(false); }
public void Add(Mono.Cecil.TypeReference type) { // Add all methods of type. Mono.Cecil.TypeDefinition type_defintion = type.Resolve(); foreach (Mono.Cecil.MethodDefinition definition in type_defintion.Methods) { Add(definition); } }
public OutParameterReturnTypeWriter(ConfigBase config, int indentCount, Mono.Cecil.TypeDefinition TypeDefinition, string methodName, TypeReference retrunTypeReference, List <ParameterDefinition> outTypes) { this.config = config; this.IndentCount = indentCount; this.TypeDefinition = TypeDefinition; this.MethodName = methodName; this.ReturnTypeReference = retrunTypeReference; this.OutTypes = outTypes; }
public string CrefFromHref(string href) { var m = typeInHref.Match(href); if (!m.Success) { return(string.Format("!:BadHref:{0}", href)); } string jniTypeName = m.Groups ["type"].Value.Replace('.', '$'); if (jniTypeName.EndsWith("package-summary")) { return(CreateNamespaceCref(jniTypeName)); } Type type = GetAvailableTypes() .FirstOrDefault(t => { var r = (RegisterAttribute [])t.GetCustomAttributes <RegisterAttribute> (false); if (r.Length == 0) { return(false); } return(r [0].Name == jniTypeName); }); if (type == null) { return(string.Format("!:NoType:{0};Href={1}", jniTypeName, href)); } string member = m.Groups ["member"].Value; if (string.IsNullOrEmpty(member)) { return("T:" + type.FullName.Replace('/', '+')); } member = TypeUtilities.StripGenericArgument(member); var tregister = ((RegisterAttribute [])type.GetCustomAttributes <RegisterAttribute> (false)) [0]; MemberInfo mi = type.Fields.Cast <MemberInfo> ().Concat(type.Properties).Concat(type.Methods) .FirstOrDefault(x => { var ras = (RegisterAttribute [])x.GetCustomAttributes <RegisterAttribute> (false); return(ras.Any(ra => Application.GetAnchor(tregister, ra) == member)); }); if (mi != null) { return(CreateCref(mi)); } string enumRef; if (Application.EnumMappings != null && Application.EnumMappings.TryGetValue(jniTypeName + "." + member, out enumRef)) { return(enumRef); } return("!:" + type.FullName + "." + member); }
private void SetDeclaringType(AnalysisNet.Types.TypeDefinition typeDefinition, Cecil.TypeDefinition cecilDef) { Cecil.TypeReference declaringTypeRef = typeDefinition.ContainingType == null ? null : ReferenceGenerator.TypeReference(typeDefinition.ContainingType); if (declaringTypeRef != null) { Cecil.TypeDefinition declaringType = declaringTypeRef.Resolve(); declaringType.NestedTypes.Add(cecilDef); cecilDef.DeclaringType = declaringType; } }
private static IEnumerable <ClrMethodDefinition> GetAllMethods( Mono.Cecil.TypeDefinition typeDefinition, ClrAssembly parentAssembly) { return(typeDefinition.Methods .Select(parentAssembly.Resolve) .Cast <ClrMethodDefinition>() .Concat( typeDefinition.NestedTypes.SelectMany( type => GetAllMethods(type, parentAssembly)))); }
private void DefineMember(TypeDefinition type, IAstDefinition memberAst, DefinitionBuildingContext context) { var builder = this.builders.SingleOrDefault(c => c.CanBuild(memberAst, type)); if (builder == null) { throw new NotImplementedException("LightCompiler: No DefinitionBuilder for " + memberAst + " under " + type + "."); } builder.Build(memberAst, type, context); }
private MethodDefinition FindEntryToInstantiator(Mono.Cecil.TypeDefinition typedef) { foreach (var metdef in typedef.Methods) { if (metdef.Name == "GetNewStaticPrefabByStaticPrefabType") { return(metdef);//No need to go check further(no parameters overload expected) } } throw new InstrumentationFailureException("SP Registry Instantiator method is unavailable!"); }
public static IEnumerable <Cecil.TypeDefinition> IterateNestedTypes( this Cecil.TypeDefinition type) { foreach (var nestedType in type.NestedTypes) { yield return(nestedType); foreach (var nested in IterateNestedTypes(nestedType)) { yield return(nestedType); } } }