public virtual DialogResult ShowDialog(CustomAttribute attribute, CustomAttributeNamedArgument? argument, bool usefields) { m_selectedargument = argument; m_selectedattribute = attribute; m_usefields = usefields; return base.ShowDialog(); }
private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set) { set = null; if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1) { return(false); } Mono.Cecil.SecurityAttribute item = declaration.SecurityAttributes[0]; if (!item.AttributeType.IsTypeOf("System.Security.Permissions", "PermissionSetAttribute")) { return(false); } PermissionSetAttribute permissionSetAttribute = new PermissionSetAttribute((System.Security.Permissions.SecurityAction)declaration.Action); Mono.Cecil.CustomAttributeNamedArgument customAttributeNamedArgument = item.Properties[0]; string value = (string)customAttributeNamedArgument.Argument.Value; string name = customAttributeNamedArgument.Name; if (name == "XML") { permissionSetAttribute.XML = value; } else { if (name != "Name") { throw new NotImplementedException(customAttributeNamedArgument.Name); } permissionSetAttribute.Name = value; } set = permissionSetAttribute.CreatePermissionSet(); return(true); }
public virtual DialogResult ShowDialog(CustomAttribute attribute, CustomAttributeNamedArgument? argument, bool usefields) { SelectedArgument = argument; SelectedAttribute = attribute; _useFields = usefields; return ShowDialog(); }
private void MapCustomAttributes(SR.ICustomAttributeProvider provider, MC.ICustomAttributeProvider targetProvider) { var type = provider.GetType(); // System.Reflection.Module.GetCustomAttributesData() not implemented in mono <= 3.4.0 if (_is_running_mono && typeof(System.Reflection.Module).IsAssignableFrom(type)) { return; } var method = type.GetMethod("GetCustomAttributesData"); if (method == null) { throw new NotSupportedException("No method GetCustomAttributesData for type " + provider.GetType().FullName); } var custom_attributes_data = (IList <CustomAttributeData>)method.Invoke(provider, new object[0]); foreach (var custom_attribute_data in custom_attributes_data) { var custom_attribute = new CustomAttribute(CreateReference(custom_attribute_data.Constructor, null)); foreach (var argument in custom_attribute_data.ConstructorArguments) { custom_attribute.ConstructorArguments.Add(CustomAttributeArgumentFor(argument)); } foreach (var named_argument in custom_attribute_data.NamedArguments) { var argument = new MC.CustomAttributeNamedArgument(named_argument.MemberInfo.Name, CustomAttributeArgumentFor(named_argument.TypedValue)); if (named_argument.MemberInfo is PropertyInfo) { custom_attribute.Properties.Add(argument); } else if (named_argument.MemberInfo is FieldInfo) { custom_attribute.Fields.Add(argument); } else { throw new NotSupportedException(); } } targetProvider.CustomAttributes.Add(custom_attribute); } }
private static void CreateAndAddCharSetFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { System.Runtime.InteropServices.CharSet charSet = System.Runtime.InteropServices.CharSet.None; if (method.PInvokeInfo.IsCharSetAnsi) { charSet = System.Runtime.InteropServices.CharSet.Ansi; } if (method.PInvokeInfo.IsCharSetUnicode) { charSet = System.Runtime.InteropServices.CharSet.Unicode; } if (method.PInvokeInfo.IsCharSetAuto) { charSet = System.Runtime.InteropServices.CharSet.Auto; } TypeReference charSetArgumentType = Utilities.GetCorlibTypeReference(typeof(System.Runtime.InteropServices.CharSet), method.DeclaringType.Module); //Casted to int, so that it can be resolved to enum member by EnumValueToFieldCombinationMatcher.GetEnumFieldDefinitionByValue //invokd in WeiteAttributeNamedArgs CustomAttributeArgument charSetArgument = new CustomAttributeArgument(charSetArgumentType, (int)(charSet)); CustomAttributeNamedArgument namedCharSetArgument = new CustomAttributeNamedArgument("CharSet", charSetArgument); dllImportAttr.Fields.Add(namedCharSetArgument); }
private CustomAttributeNamedArgument Fix(CustomAttributeNamedArgument namedArg, IGenericParameterProvider context) { CustomAttributeNamedArgument ret = new CustomAttributeNamedArgument(namedArg.Name, Fix(namedArg.Argument, context)); return ret; }
private void WriteSecurityDeclarationArgument(CustomAttributeNamedArgument na) { TypeReference type = na.Argument.Type; if (type.MetadataType == MetadataType.Class || type.MetadataType == MetadataType.ValueType) { WriteKeyWordPostSpace("enum"); if (type.Scope != type.Module) { WriteKeyWordPostSpace("class"); Write(ILHelpers.Escape(GetAssemblyQualifiedName(type))); } else { WriteTypeReference(type, ILNameSyntax.TypeName); } } else { WriteTypeReference(type); } WriteSpace(); WriteReference(ILHelpers.Escape(na.Name), type); WriteSpace(); WriteToken("="); WriteSpace(); if (na.Argument.Value is string) { Write(string.Format("string('{0}')", ConvertString((string)na.Argument.Value).Replace("'", "\'"))); } else { WriteConstant(na.Argument.Value); } }
private static void CreateAndAddCallingConventionFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { /// this StdCall is the default calling conventon (according to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.callingconvention.aspx) if (!method.PInvokeInfo.IsCallConvWinapi) { TypeReference callingConventionArgumentType = Utilities.GetCorlibTypeReference(typeof(System.Runtime.InteropServices.CallingConvention), method.DeclaringType.Module); /// set the integer value of the field, so that RenameEnumValues can pick it up and fix it accordinly. int callingConventionValue = 0; if (method.PInvokeInfo.IsCallConvFastcall) { callingConventionValue = 5; } else if (method.PInvokeInfo.IsCallConvThiscall) { callingConventionValue = 4; } else if (method.PInvokeInfo.IsCallConvStdCall) { callingConventionValue = 3; } else if (method.PInvokeInfo.IsCallConvCdecl) { callingConventionValue = 2; } else { //default case, shouldn't be reached callingConventionValue = 1; } CustomAttributeArgument callingConventionArgument = new CustomAttributeArgument(callingConventionArgumentType, callingConventionValue); CustomAttributeNamedArgument namedCallingConventionArgument = new CustomAttributeNamedArgument("CallingConvention", callingConventionArgument); dllImportAttr.Fields.Add(namedCallingConventionArgument); } }
protected void FixCustomAttributeNamedArguments(ModuleDefinition module, Collection<CustomAttributeNamedArgument> narguments) { for (var i = 0; i < narguments.Count; i++) narguments[i] = new CustomAttributeNamedArgument(narguments[i].Name, FixCustomAttributeArgument(module, narguments[i].Argument)); }
void addCustomAttributeNamedArgument(CustomAttributeNamedArgument field) { addCustomAttributeArgument(field.Argument); }
private static void AssertEquality( CustomAttributeNamedArgument expected, CustomAttributeNamedArgument actual, string attributeTargetName) { Assert.AreEqual( expected.Name, actual.Name, string.Format("Looking for custom attribute named argument with name {0} but found {1} for target {2} of mixed assembly", expected.Name, actual.Name, attributeTargetName)); AssertEquality(expected.Argument.Type.Resolve(), actual.Argument.Type.Resolve()); if (expected.Argument.Value != null && actual.Argument.Value != null) { AssertEquality(expected.Argument.Value as dynamic, actual.Argument.Value as dynamic); } else { if (expected.Argument.Value == null && actual.Argument.Value != null) { string.Format( "Looking for custom attribute named argument [{0}] with null value but found [{1}][{2}] for target {3} of mixed assembly", expected.Name, actual.Name, actual.Argument.Value.ToString()); } if (expected.Argument.Value != null && actual.Argument.Value == null) { string.Format( "Looking for custom attribute named argument [{0}][{1}] value but found [{2}] with null value for target {3} of mixed assembly", expected.Name, expected.Argument.Value.ToString(), actual.Name); } } }
internal void FixReferences(Collection<SecurityDeclaration> securitydeclarations) { if (securitydeclarations.Count > 0) { foreach (SecurityDeclaration sd in securitydeclarations) { foreach (SecurityAttribute sa in sd.SecurityAttributes) { sa.AttributeType = Fix(sa.AttributeType); FixReferences(sa.Fields); if (sa.HasFields) throw new NotSupportedException(); FixReferences(sa.Properties); if (sa.HasProperties) { foreach (var prop in sa.Properties.ToArray()) { if (prop.Name == "PublicKeyBlob") { if (repack.TargetAssemblyDefinition.Name.HasPublicKey) { if (targetAssemblyPublicKeyBlobString == null) foreach (byte b in repack.TargetAssemblyDefinition.Name.PublicKey) targetAssemblyPublicKeyBlobString += b.ToString("X").PadLeft(2, '0'); if (prop.Argument.Type.FullName != "System.String") throw new NotSupportedException("Invalid type of argument, expected string"); CustomAttributeNamedArgument newProp = new CustomAttributeNamedArgument(prop.Name, new CustomAttributeArgument(prop.Argument.Type, targetAssemblyPublicKeyBlobString)); sa.Properties.Remove(prop); sa.Properties.Add(newProp); } else { repack.WARN("SecurityPermission with PublicKeyBlob found but target has no strong name!"); } } } } } } if ((repack.TargetAssemblyMainModule.Runtime == TargetRuntime.Net_1_0) || (repack.TargetAssemblyMainModule.Runtime == TargetRuntime.Net_1_1)) { SecurityDeclaration[] sdArray = securitydeclarations.ToArray(); securitydeclarations.Clear(); foreach (SecurityDeclaration sd in sdArray) securitydeclarations.Add(PermissionsetHelper.Permission2XmlSet(sd, repack.TargetAssemblyMainModule)); } } }
/// <summary> /// Creates a reference to a property used in a custom attribute. /// </summary> /// <param name="emitter">The emitter.</param> /// <param name="attribute">The attribute.</param> /// <param name="field">The attribute variable.</param> /// <param name="property">The property.</param> public void CreateAttributeProperty(MethodEmitter emitter, CustomAttribute attribute, Variable field, Mono.Cecil.CustomAttributeNamedArgument property) { var il = emitter.GetIL(); var member = field.Type.Resolve().Properties.FirstOrDefault(p => p.Name == property.Name)?.SetMethod; if (member == null) { throw new MissingMemberException($"Cannot resolve property {property.Name} of {attribute.AttributeType.Name} as there is no setter"); } il.Emit(Codes.ThisIf(field)); il.Emit(Codes.Load(field)); CreateAttributeParameter(emitter, attribute, property.Argument); il.Emit(Codes.Invoke(member.Import())); }
protected void MarkCustomAttributeProperty (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute) { PropertyDefinition property = GetProperty (attribute, namedArgument.Name); if (property != null) MarkMethod (property.SetMethod); MarkIfType (namedArgument.Argument); }
private static List <CppMethodData> ProcessTypeContents(Il2CppMetadata metadata, PE cppAssembly, Il2CppTypeDefinition cppTypeDefinition, TypeDefinition ilTypeDefinition, Il2CppAssemblyDefinition imageDef) { var imageName = metadata.GetStringFromIndex(imageDef.nameIndex); var typeMetaText = new StringBuilder(); typeMetaText.Append($"Type: {ilTypeDefinition.FullName}:") .Append($"\n\tBase Class: \n\t\t{ilTypeDefinition.BaseType}\n") .Append("\n\tInterfaces:\n"); foreach (var iface in ilTypeDefinition.Interfaces) { typeMetaText.Append($"\t\t{iface.InterfaceType.FullName}\n"); } if (ilTypeDefinition.NestedTypes.Count > 0) { typeMetaText.Append("\n\tNested Types:\n"); foreach (var nestedType in ilTypeDefinition.NestedTypes) { typeMetaText.Append($"\t\t{nestedType.FullName}\n"); } } var addressAttribute = ilTypeDefinition.Module.Types.First(x => x.Name == "AddressAttribute").Methods[0]; var fieldOffsetAttribute = ilTypeDefinition.Module.Types.First(x => x.FullName == "Cpp2IlInjected.FieldOffsetAttribute").Methods[0]; var attributeAttribute = ilTypeDefinition.Module.Types.First(x => x.Name == "AttributeAttribute").Methods[0]; var metadataOffsetAttribute = ilTypeDefinition.Module.Types.First(x => x.Name == "MetadataOffsetAttribute").Methods[0]; var tokenAttribute = ilTypeDefinition.Module.Types.First(x => x.Name == "TokenAttribute").Methods[0]; var stringType = ilTypeDefinition.Module.ImportReference(Utils.TryLookupTypeDefByName("System.String").Item1); //Token attribute var customTokenAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(tokenAttribute)); customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{cppTypeDefinition.token:X}"))); ilTypeDefinition.CustomAttributes.Add(customTokenAttribute); //field var fields = new List <FieldInType>(); var baseFields = new List <FieldDefinition>(); var current = ilTypeDefinition; while (current.BaseType != null) { var targetName = current.BaseType.FullName; if (targetName.Contains("<")) // types with generic parameters (Type'1<T>) are stored as Type'1, so I just removed the part that causes trouble and called it a day { targetName = targetName.Substring(0, targetName.IndexOf("<")); } current = SharedState.AllTypeDefinitions.Find(t => t.FullName == targetName); if (current == null) { typeMetaText.Append("WARN: Type " + targetName + " is not defined yet\n"); break; } baseFields.InsertRange(0, current.Fields.Where(f => !f.IsStatic)); // each loop we go one inheritage level deeper, so these "new" fields should be inserted before the previous ones } //Handle base fields var fieldOffset = baseFields.Aggregate((ulong)(ilTypeDefinition.MetadataType == MetadataType.Class ? 0x10 : 0x0), (currentOffset, baseField) => HandleField(baseField.FieldType, currentOffset, baseField.Name, baseField, ref fields, typeMetaText)); var lastFieldIdx = cppTypeDefinition.firstFieldIdx + cppTypeDefinition.field_count; for (var fieldIdx = cppTypeDefinition.firstFieldIdx; fieldIdx < lastFieldIdx; ++fieldIdx) { var fieldDef = metadata.fieldDefs[fieldIdx]; var fieldType = cppAssembly.types[fieldDef.typeIndex]; var fieldName = metadata.GetStringFromIndex(fieldDef.nameIndex); var fieldTypeRef = Utils.ImportTypeInto(ilTypeDefinition, fieldType, cppAssembly, metadata); var fieldDefinition = new FieldDefinition(fieldName, (FieldAttributes)fieldType.attrs, fieldTypeRef); ilTypeDefinition.Fields.Add(fieldDefinition); //Field default values if (fieldDefinition.HasDefault) { var fieldDefault = metadata.GetFieldDefaultValueFromIndex(fieldIdx); if (fieldDefault != null && fieldDefault.dataIndex != -1) { fieldDefinition.Constant = LibCpp2ILUtils.GetDefaultValue(fieldDefault.dataIndex, fieldDefault.typeIndex, metadata, cppAssembly); } } customTokenAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(tokenAttribute)); customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{fieldDef.token:X}"))); fieldDefinition.CustomAttributes.Add(customTokenAttribute); if (!fieldDefinition.IsStatic) { fieldOffset = HandleField(fieldTypeRef, fieldOffset, fieldName, fieldDefinition, ref fields, typeMetaText); } var customAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(metadataOffsetAttribute)); var offset = new CustomAttributeNamedArgument("Offset", new CustomAttributeArgument(stringType, $"0x{fieldOffset:X}")); customAttribute.Fields.Add(offset); fieldDefinition.CustomAttributes.Add(customAttribute); } fields.Sort(); //By offset SharedState.FieldsByType[ilTypeDefinition] = fields; //Methods var lastMethodId = cppTypeDefinition.firstMethodIdx + cppTypeDefinition.method_count; var typeMethods = new List <CppMethodData>(); Il2CppGenericContainer genericContainer; for (var methodId = cppTypeDefinition.firstMethodIdx; methodId < lastMethodId; ++methodId) { var methodDef = metadata.methodDefs[methodId]; var methodReturnType = cppAssembly.types[methodDef.returnTypeIdx]; var methodName = metadata.GetStringFromIndex(methodDef.nameIndex); var methodDefinition = new MethodDefinition(methodName, (MethodAttributes)methodDef.flags, ilTypeDefinition.Module.ImportReference(Utils.TryLookupTypeDefByName("System.Void").Item1)); SharedState.UnmanagedToManagedMethods[methodDef] = methodDefinition; var offsetInRam = cppAssembly.GetMethodPointer(methodDef.methodIndex, methodId, imageDef.assemblyIndex, methodDef.token); var offsetInFile = offsetInRam == 0 ? 0 : cppAssembly.MapVirtualAddressToRaw(offsetInRam); typeMetaText.Append($"\n\tMethod: {methodName}:\n") .Append($"\t\tFile Offset 0x{offsetInFile:X8}\n") .Append($"\t\tRam Offset 0x{offsetInRam:x8}\n") .Append($"\t\tVirtual Method Slot: {methodDef.slot}\n"); var bytes = new List <byte>(); var offset = offsetInFile; while (true) { var b = cppAssembly.raw[offset]; if (b == 0xC3 && cppAssembly.raw[offset + 1] == 0xCC) { break; } if (b == 0xCC && bytes.Count > 0 && (bytes.Last() == 0xcc || bytes.Last() == 0xc3)) { break; } bytes.Add(b); offset++; } typeMetaText.Append($"\t\tMethod Length: {bytes.Count} bytes\n"); typeMethods.Add(new CppMethodData { MethodName = methodName, MethodId = methodId, MethodBytes = bytes.ToArray(), MethodOffsetRam = offsetInRam }); ilTypeDefinition.Methods.Add(methodDefinition); methodDefinition.ReturnType = Utils.ImportTypeInto(methodDefinition, methodReturnType, cppAssembly, metadata); customTokenAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(tokenAttribute)); customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{methodDef.token:X}"))); methodDefinition.CustomAttributes.Add(customTokenAttribute); if (methodDefinition.HasBody && ilTypeDefinition.BaseType?.FullName != "System.MulticastDelegate") { var ilprocessor = methodDefinition.Body.GetILProcessor(); if (methodDefinition.ReturnType.FullName == "System.Void") { ilprocessor.Append(ilprocessor.Create(OpCodes.Ret)); } else if (methodDefinition.ReturnType.IsValueType) { var variable = new VariableDefinition(methodDefinition.ReturnType); methodDefinition.Body.Variables.Add(variable); ilprocessor.Append(ilprocessor.Create(OpCodes.Ldloca_S, variable)); ilprocessor.Append(ilprocessor.Create(OpCodes.Initobj, methodDefinition.ReturnType)); ilprocessor.Append(ilprocessor.Create(OpCodes.Ldloc_0)); ilprocessor.Append(ilprocessor.Create(OpCodes.Ret)); } else { ilprocessor.Append(ilprocessor.Create(OpCodes.Ldnull)); ilprocessor.Append(ilprocessor.Create(OpCodes.Ret)); } } SharedState.MethodsByIndex.Add(methodId, methodDefinition); //Method Params for (var paramIdx = 0; paramIdx < methodDef.parameterCount; ++paramIdx) { var parameterDef = metadata.parameterDefs[methodDef.parameterStart + paramIdx]; var parameterName = metadata.GetStringFromIndex(parameterDef.nameIndex); var parameterType = cppAssembly.types[parameterDef.typeIndex]; var parameterTypeRef = Utils.ImportTypeInto(methodDefinition, parameterType, cppAssembly, metadata); var parameterDefinition = new ParameterDefinition(parameterName, (ParameterAttributes)parameterType.attrs, parameterTypeRef); methodDefinition.Parameters.Add(parameterDefinition); //Default values for params if (parameterDefinition.HasDefault) { var parameterDefault = metadata.GetParameterDefaultValueFromIndex(methodDef.parameterStart + paramIdx); if (parameterDefault != null && parameterDefault.dataIndex != -1) { parameterDefinition.Constant = LibCpp2ILUtils.GetDefaultValue(parameterDefault.dataIndex, parameterDefault.typeIndex, metadata, cppAssembly); } } typeMetaText.Append($"\n\t\tParameter {paramIdx}:\n") .Append($"\t\t\tName: {parameterName}\n") .Append($"\t\t\tType: {(parameterTypeRef.Namespace == "" ? "<None>" : parameterTypeRef.Namespace)}.{parameterTypeRef.Name}\n") .Append($"\t\t\tDefault Value: {parameterDefinition.Constant}"); } //Address attribute var methodPointer = LibCpp2IlMain.ThePe.GetMethodPointer(methodDef.methodIndex, methodId, imageDef.assemblyIndex, methodDef.token); if (methodPointer > 0) { var customAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(addressAttribute)); var fixedMethodPointer = LibCpp2IlMain.ThePe.GetRVA(methodPointer); var rva = new CustomAttributeNamedArgument("RVA", new CustomAttributeArgument(stringType, $"0x{fixedMethodPointer:X}")); var offsetArg = new CustomAttributeNamedArgument("Offset", new CustomAttributeArgument(stringType, $"0x{LibCpp2IlMain.ThePe.MapVirtualAddressToRaw(methodPointer):X}")); var va = new CustomAttributeNamedArgument("VA", new CustomAttributeArgument(stringType, $"0x{methodPointer:X}")); customAttribute.Fields.Add(rva); customAttribute.Fields.Add(offsetArg); customAttribute.Fields.Add(va); if (methodDef.slot != ushort.MaxValue) { var slot = new CustomAttributeNamedArgument("Slot", new CustomAttributeArgument(stringType, methodDef.slot.ToString())); customAttribute.Fields.Add(slot); } methodDefinition.CustomAttributes.Add(customAttribute); } if (methodDef.genericContainerIndex >= 0) { genericContainer = metadata.genericContainers[methodDef.genericContainerIndex]; if (genericContainer.type_argc > methodDefinition.GenericParameters.Count) { for (var j = 0; j < genericContainer.type_argc; j++) { var genericParameterIndex = genericContainer.genericParameterStart + j; var param = metadata.genericParameters[genericParameterIndex]; var genericName = metadata.GetStringFromIndex(param.nameIndex); if (!SharedState.GenericParamsByIndex.TryGetValue(genericParameterIndex, out var genericParameter)) { genericParameter = new GenericParameter(genericName, methodDefinition); methodDefinition.GenericParameters.Add(genericParameter); SharedState.GenericParamsByIndex.Add(genericParameterIndex, genericParameter); } else { if (!methodDefinition.GenericParameters.Contains(genericParameter)) { methodDefinition.GenericParameters.Add(genericParameter); } } } } } if (methodDef.slot < ushort.MaxValue) { SharedState.VirtualMethodsBySlot[methodDef.slot] = methodDefinition; } SharedState.MethodsByAddress[offsetInRam] = methodDefinition; } //Properties var lastPropertyId = cppTypeDefinition.firstPropertyId + cppTypeDefinition.propertyCount; for (var propertyId = cppTypeDefinition.firstPropertyId; propertyId < lastPropertyId; ++propertyId) { var propertyDef = metadata.propertyDefs[propertyId]; var propertyName = metadata.GetStringFromIndex(propertyDef.nameIndex); TypeReference propertyType = null; MethodDefinition getter = null; MethodDefinition setter = null; if (propertyDef.get >= 0) { getter = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodIdx + propertyDef.get]; propertyType = getter.ReturnType; } if (propertyDef.set >= 0) { setter = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodIdx + propertyDef.set]; if (propertyType == null) { propertyType = setter.Parameters[0].ParameterType; } } var propertyDefinition = new PropertyDefinition(propertyName, (PropertyAttributes)propertyDef.attrs, propertyType) { GetMethod = getter, SetMethod = setter }; customTokenAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(tokenAttribute)); customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{propertyDef.token:X}"))); propertyDefinition.CustomAttributes.Add(customTokenAttribute); ilTypeDefinition.Properties.Add(propertyDefinition); } //Events var lastEventId = cppTypeDefinition.firstEventId + cppTypeDefinition.eventCount; for (var eventId = cppTypeDefinition.firstEventId; eventId < lastEventId; ++eventId) { var eventDef = metadata.eventDefs[eventId]; var eventName = metadata.GetStringFromIndex(eventDef.nameIndex); var eventType = cppAssembly.types[eventDef.typeIndex]; var eventTypeRef = Utils.ImportTypeInto(ilTypeDefinition, eventType, cppAssembly, metadata); var eventDefinition = new EventDefinition(eventName, (EventAttributes)eventType.attrs, eventTypeRef); if (eventDef.add >= 0) { eventDefinition.AddMethod = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodIdx + eventDef.add]; } if (eventDef.remove >= 0) { eventDefinition.RemoveMethod = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodIdx + eventDef.remove]; } if (eventDef.raise >= 0) { eventDefinition.InvokeMethod = SharedState.MethodsByIndex[cppTypeDefinition.firstMethodIdx + eventDef.raise]; } customTokenAttribute = new CustomAttribute(ilTypeDefinition.Module.ImportReference(tokenAttribute)); customTokenAttribute.Fields.Add(new CustomAttributeNamedArgument("Token", new CustomAttributeArgument(stringType, $"0x{eventDef.token:X}"))); eventDefinition.CustomAttributes.Add(customTokenAttribute); ilTypeDefinition.Events.Add(eventDefinition); } if (!Program.CommandLineOptions.SkipMetadataTextFiles) { File.WriteAllText(Path.Combine(Path.GetFullPath("cpp2il_out"), "types", ilTypeDefinition.Module.Assembly.Name.Name, ilTypeDefinition.Name.Replace("<", "_").Replace(">", "_").Replace("|", "_") + "_metadata.txt"), typeMetaText.ToString()); } if (cppTypeDefinition.genericContainerIndex < 0) { return(typeMethods); //Finished processing if not generic } genericContainer = metadata.genericContainers[cppTypeDefinition.genericContainerIndex]; if (genericContainer.type_argc <= ilTypeDefinition.GenericParameters.Count) { return(typeMethods); //Finished processing } for (var i = 0; i < genericContainer.type_argc; i++) { var genericParameterIndex = genericContainer.genericParameterStart + i; var param = metadata.genericParameters[genericParameterIndex]; var genericName = metadata.GetStringFromIndex(param.nameIndex); if (!SharedState.GenericParamsByIndex.TryGetValue(genericParameterIndex, out var genericParameter)) { genericParameter = new GenericParameter(genericName, ilTypeDefinition); ilTypeDefinition.GenericParameters.Add(genericParameter); SharedState.GenericParamsByIndex.Add(genericParameterIndex, genericParameter); } else { if (ilTypeDefinition.GenericParameters.Contains(genericParameter)) { continue; } ilTypeDefinition.GenericParameters.Add(genericParameter); } } return(typeMethods); }
private void MapType(TypeReference typeReference) { var scope = string.Empty; switch (typeReference.Scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: scope = FromCILToTypeName(typeReference.FullName) + ", " + typeReference.Scope; break; case MetadataScopeType.ModuleReference: break; case MetadataScopeType.ModuleDefinition: var moduleDefinition = typeReference.Scope as ModuleDefinition; if (moduleDefinition != null) scope = FromCILToTypeName(typeReference.FullName) + ", " + moduleDefinition.Assembly; break; default: throw new Exception(string.Format("Assembly Scope Null. Check assembly {0}", typeReference.FullName)); } var customAttribute = new CustomAttribute(_debuggerVisualizerAssembly.MainModule.Import(_debuggerVisualizerAttributeCtor)); var targetType = new CustomAttributeArgument(_debuggerVisualizerAssembly.MainModule.TypeSystem.String, scope); var descriptionType = new CustomAttributeArgument(_debuggerVisualizerAssembly.MainModule.TypeSystem.String, _assemblyDescriptionAttributeValue); var targetTypeProperty = new CustomAttributeNamedArgument("TargetTypeName", targetType); var descriptionTypeProperty = new CustomAttributeNamedArgument("Description", descriptionType); customAttribute.ConstructorArguments.Add(_customDebuggerVisualizerAttributeArgument); customAttribute.ConstructorArguments.Add(_visualizerObjectSourceCustomAttributeArgument); customAttribute.Properties.Add(targetTypeProperty); customAttribute.Properties.Add(descriptionTypeProperty); _debuggerVisualizerAssembly.CustomAttributes.Add(customAttribute); }
private void MapCustomAttributes(SR.ICustomAttributeProvider provider, MC.ICustomAttributeProvider targetProvider) { var type = provider.GetType(); // System.Reflection.Module.GetCustomAttributesData() not implemented in mono <= 3.4.0 if (_is_running_mono && typeof(System.Reflection.Module).IsAssignableFrom(type)) return; var method = type.GetMethod("GetCustomAttributesData"); if (method == null) throw new NotSupportedException("No method GetCustomAttributesData for type " + provider.GetType().FullName); var custom_attributes_data = (IList<CustomAttributeData>)method.Invoke(provider, new object[0]); foreach (var custom_attribute_data in custom_attributes_data) { var custom_attribute = new CustomAttribute(CreateReference(custom_attribute_data.Constructor, null)); foreach (var argument in custom_attribute_data.ConstructorArguments) { custom_attribute.ConstructorArguments.Add(CustomAttributeArgumentFor(argument)); } foreach (var named_argument in custom_attribute_data.NamedArguments) { var argument = new MC.CustomAttributeNamedArgument(named_argument.MemberInfo.Name, CustomAttributeArgumentFor(named_argument.TypedValue)); if (named_argument.MemberInfo is PropertyInfo) custom_attribute.Properties.Add(argument); else if (named_argument.MemberInfo is FieldInfo) custom_attribute.Fields.Add(argument); else throw new NotSupportedException(); } targetProvider.CustomAttributes.Add(custom_attribute); } }
/// <summary> /// Clone all arguments from source to target. /// </summary> private static void CloneCANamedArguments(IList<CustomAttributeNamedArgument> target, IList<CustomAttributeNamedArgument> source) { foreach (var x in source) { var clone = new CustomAttributeNamedArgument( x.Name, CloneCAArgument(x.Argument)); target.Add(clone); } }
/// <summary> /// Are argument a and b the same? /// </summary> public static bool AreSame(this CustomAttributeNamedArgument a, CustomAttributeNamedArgument b, Func<GenericParameter, TypeReference> genericParamResolver) { return (a.Name == b.Name) && a.Argument.AreSame(b.Argument, genericParamResolver); }
private static void CreateAndAddThrowOnUnmappableCharFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { // ThrowOnUnmappableChar is false by default if (method.PInvokeInfo.IsThrowOnUnmappableCharEnabled) { TypeReference throwOnUnmappableCharArgumentType = method.DeclaringType.Module.TypeSystem.Boolean; CustomAttributeArgument throwOnUnmappableCharArgument = new CustomAttributeArgument(throwOnUnmappableCharArgumentType, true); CustomAttributeNamedArgument namedThrowOnUnmappableCharArgument = new CustomAttributeNamedArgument("ThrowOnUnmappableChar", throwOnUnmappableCharArgument); dllImportAttr.Fields.Add(namedThrowOnUnmappableCharArgument); } }
private static void CreateAndAddSetLastErrorFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { //SetLastError is false by default if (method.PInvokeInfo.SupportsLastError) { TypeReference setLastErrorArgumentType = method.DeclaringType.Module.TypeSystem.Boolean; CustomAttributeArgument setLastErrorArgument = new CustomAttributeArgument(setLastErrorArgumentType, true); CustomAttributeNamedArgument namedSetLastErrorArgument = new CustomAttributeNamedArgument("SetLastError", setLastErrorArgument); dllImportAttr.Fields.Add(namedSetLastErrorArgument); } }
protected void MarkCustomAttributeField (CustomAttributeNamedArgument namedArgument, TypeDefinition attribute) { FieldDefinition field = GetField (attribute, namedArgument.Name); if (field != null) MarkField (field); MarkIfType (namedArgument.Argument); }
private static void CreateAndAddPreserveSigFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { /// PreserveSig is true by default if (!method.IsPreserveSig) { TypeReference preserveSigArgumentType = method.DeclaringType.Module.TypeSystem.Boolean; CustomAttributeArgument preserveSigArgument = new CustomAttributeArgument(preserveSigArgumentType, false); CustomAttributeNamedArgument namedPreserveSigArgument = new CustomAttributeNamedArgument("PreserveSig", preserveSigArgument); dllImportAttr.Fields.Add(namedPreserveSigArgument); } }
private CustomAttributeNamedArgument FixPlatformVersion(CustomAttributeNamedArgument cana) { return new CustomAttributeNamedArgument(cana.Name, FixPlatformVersion(cana.Argument)); }
private static void CreateAndAddExactSpellingFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { TypeReference exactSpellingArgumentType = method.DeclaringType.Module.TypeSystem.Boolean; CustomAttributeArgument exactSpellingArgument = new CustomAttributeArgument(exactSpellingArgumentType, method.PInvokeInfo.IsNoMangle); CustomAttributeNamedArgument namedExactSpellingArgument = new CustomAttributeNamedArgument("ExactSpelling", exactSpellingArgument); dllImportAttr.Fields.Add(namedExactSpellingArgument); }
private CustomAttributeNamedArgument Fix(CustomAttributeNamedArgument namedArg) { CustomAttributeNamedArgument ret = new CustomAttributeNamedArgument(namedArg.Name, Fix(namedArg.Argument)); return ret; }
private static void CreateAndAddBestFitMappingFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { // BestFitMapping is true by default if (method.PInvokeInfo.IsBestFitDisabled) { TypeReference bestFitMappingArgumentType = method.DeclaringType.Module.TypeSystem.Boolean; CustomAttributeArgument bestFitMappingArgument = new CustomAttributeArgument(bestFitMappingArgumentType, false); CustomAttributeNamedArgument namedBestFitMappingArgument = new CustomAttributeNamedArgument("BestFitMapping", bestFitMappingArgument); dllImportAttr.Fields.Add(namedBestFitMappingArgument); } }
protected virtual void Visit(Mono.Cecil.CustomAttributeNamedArgument customAttributeNamedArgument, Context context) { this.Visit(customAttributeNamedArgument.Argument, context); }
private static void CreateAndAddEntryPointFieldArgument(MethodDefinition method, CustomAttribute dllImportAttr) { // EntryPoint is the name of the method by default if (method.PInvokeInfo.EntryPoint != method.Name) { TypeReference entryPointArgumentType = method.DeclaringType.Module.TypeSystem.String; CustomAttributeArgument entryPointArgument = new CustomAttributeArgument(entryPointArgumentType, method.PInvokeInfo.EntryPoint); CustomAttributeNamedArgument namedEntryPointArgument = new CustomAttributeNamedArgument("EntryPoint", entryPointArgument); dllImportAttr.Fields.Add(namedEntryPointArgument); } }
/// <summary> /// CopyMethod copies a method definition into a new copy which can be added /// to another module. /// </summary> /// <param name="method">The MethodDefinition to copy</param> /// <returns>A copy of the MethodDefinition</returns> public static MethodDefinition CopyMethod(MethodDefinition method) { MethodDefinition newMethod = new MethodDefinition(method.Name, method.Attributes, method.ReturnType); foreach (ParameterDefinition param in method.Parameters) { ParameterDefinition newParam = new ParameterDefinition(param.Name, param.Attributes, param.ParameterType); newMethod.Parameters.Add(newParam); } foreach (CustomAttribute attr in method.CustomAttributes) { CustomAttribute newAttr = new CustomAttribute(attr.Constructor); foreach (CustomAttributeArgument arg in attr.ConstructorArguments) { CustomAttributeArgument newArg = new CustomAttributeArgument(arg.Type, arg.Value); newAttr.ConstructorArguments.Add(newArg); } foreach (CustomAttributeNamedArgument arg in attr.Fields) { CustomAttributeNamedArgument newArg = new CustomAttributeNamedArgument(arg.Name, new CustomAttributeArgument(arg.Argument.Type, arg.Argument.Value)); newAttr.Fields.Add(newArg); } newMethod.CustomAttributes.Add(newAttr); } if (method.Body != null) { if (newMethod.Body == null) newMethod.Body = new MethodBody(newMethod); foreach (Instruction inst in method.Body.Instructions) { newMethod.Body.Instructions.Add(inst); } foreach (VariableDefinition var in method.Body.Variables) { VariableDefinition newVar = new VariableDefinition(var.Name, var.VariableType); newMethod.Body.Variables.Add(newVar); } foreach (ExceptionHandler handler in method.Body.ExceptionHandlers) { ExceptionHandler newHandler = new ExceptionHandler(handler.HandlerType); newHandler.HandlerStart = handler.HandlerStart; newHandler.HandlerEnd = handler.HandlerEnd; newHandler.TryStart = handler.TryStart; newHandler.TryEnd = handler.TryEnd; newHandler.FilterStart = handler.FilterStart; newHandler.CatchType = handler.CatchType; newMethod.Body.ExceptionHandlers.Add(newHandler); } newMethod.Body.InitLocals = method.Body.InitLocals; } return newMethod; }
private void FixPlatformVersion(CustomAttributeNamedArgument cana) { FixPlatformVersion(cana.Argument); }