public void FileField_IsNotSearchable() { // VRN-1679 - file fields should not be searchable. var field = new FieldDefinition("Test", ColumnTypes.File, null, string.Empty); Assert.IsFalse(field.IsSearchable); }
public void Execute() { LogInfo("enter execute"); var configurableTypes = ModuleDefinition.Types.Where(t => t.CustomAttributes .Any(c => c.AttributeType.Name == typeof(ConfigurableAttribute).Name)); foreach(var type in configurableTypes) { if (type.IsSealed && type.IsAbstract) { LogInfo(string.Format("Type {0} is static and cannot be configurable. Skipping type", type)); continue; } var isConfiguredField = new FieldDefinition("<>__isConfigured", Mono.Cecil.FieldAttributes.Private, ModuleDefinition.TypeSystem.Boolean); type.Fields.Add(isConfiguredField); var ensureConfigurationMethod = GenerateEnsureConfigurationMethod(isConfiguredField, type); type.Methods.Add(ensureConfigurationMethod); foreach (var ctor in type.GetConstructors().Where(ctor => !ctor.IsStatic)) { var baseCtorCall = ctor.Body.Instructions.Single(i => IsCallToCtor(i)); var baseCtorCallIndex = ctor.Body.Instructions.IndexOf(baseCtorCall); ctor.Body.Instructions.Insert(baseCtorCallIndex + 1, Instruction.Create(OpCodes.Ldarg_0)); ctor.Body.Instructions.Insert(baseCtorCallIndex + 2, Instruction.Create(OpCodes.Callvirt, ensureConfigurationMethod)); } } }
public void Read(ClrModuleReader reader) { this.FieldDefinition = new FieldDefinition(); this.FieldDefinition.Attributes = (FieldAttributes)reader.Binary.ReadUInt16(); this.FieldDefinition.Name = reader.ReadString(); this.Signature = reader.ReadFieldSignature(); }
void InjectField(TypeDefinition type, FieldDefinition fieldDefinition) { var staticConstructor = type.GetStaticConstructor(); staticConstructor.Body.SimplifyMacros(); var genericInstanceMethod = new GenericInstanceMethod(forContextDefinition); if (type.IsCompilerGenerated() && type.IsNested) { genericInstanceMethod.GenericArguments.Add(type.DeclaringType.GetGeneric()); } else { genericInstanceMethod.GenericArguments.Add(type.GetGeneric()); } var instructions = staticConstructor.Body.Instructions; type.Fields.Add(fieldDefinition); var returns = instructions.Where(_ => _.OpCode == OpCodes.Ret) .ToList(); var ilProcessor = staticConstructor.Body.GetILProcessor(); foreach (var returnInstruction in returns) { var newReturn = Instruction.Create(OpCodes.Ret); ilProcessor.InsertAfter(returnInstruction, newReturn); ilProcessor.InsertBefore(newReturn, Instruction.Create(OpCodes.Call, genericInstanceMethod)); ilProcessor.InsertBefore(newReturn, Instruction.Create(OpCodes.Stsfld, fieldDefinition.GetGeneric())); returnInstruction.OpCode = OpCodes.Nop; } staticConstructor.Body.OptimizeMacros(); }
public void CreateArrayField() { // set up temp assembly. var assembly = Utilities.CreateTempNetAssembly(); var typeSystem = assembly.NetDirectory.MetadataHeader.TypeSystem; var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>(); var fieldTable = tableStream.GetTable<FieldDefinition>(); var importer = new ReferenceImporter(tableStream); // create field. var arraySignature = new ArrayTypeSignature(typeSystem.Int32); arraySignature.Dimensions.Add(new ArrayDimension(2, 1)); arraySignature.Dimensions.Add(new ArrayDimension(2)); arraySignature.Dimensions.Add(new ArrayDimension()); var field = new FieldDefinition(FieldName, FieldAttributes.Public | FieldAttributes.Static, new FieldSignature(importer.ImportTypeSignature(arraySignature))); fieldTable.Add(field); // build and validate. assembly = Utilities.RebuildNetAssembly(assembly); fieldTable = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>().GetTable<FieldDefinition>(); field = fieldTable.First(x => x.Name == FieldName); Assert.IsInstanceOfType(field.Signature.FieldType, typeof(ArrayTypeSignature)); Utilities.ValidateType(arraySignature, field.Signature.FieldType); }
void ProcessField(TypeNode node, FieldDefinition field) { var name = field.Name; if (!field.IsPublic || field.IsStatic || !char.IsUpper(name, 0)) { return; } if (node.TypeDefinition.HasGenericParameters) { var message = string.Format("Skipped converting public field '{0}.{1}' to a property because generic types are not currently supported. You should make this a public property instead.", node.TypeDefinition.Name, field.Name); logger.LogWarning(message); return; } field.Name = string.Format("<{0}>k__BackingField", name); field.IsPublic = false; field.IsPrivate = true; var get = GetGet(field, name); node.TypeDefinition.Methods.Add(get); var set = GetSet(field, name); node.TypeDefinition.Methods.Add(set); var propertyDefinition = new PropertyDefinition(name, PropertyAttributes.None, field.FieldType) { GetMethod = get, SetMethod = set }; foreach (var customAttribute in field.CustomAttributes) { propertyDefinition.CustomAttributes.Add(customAttribute); } node.TypeDefinition.Properties.Add(propertyDefinition); ForwardedFields.Add(field, propertyDefinition); }
void InjectField(TypeDefinition type, FieldDefinition fieldDefinition) { var staticConstructor = type.GetStaticConstructor(); var instructions = staticConstructor.Body.Instructions; if (type.HasGenericParameters) { instructions.Insert(0, Instruction.Create(OpCodes.Call, buildLoggerGenericMethod)); instructions.Insert(1, Instruction.Create(OpCodes.Stsfld, fieldDefinition.GetGeneric())); } else { var logName = type.FullName; if (type.IsCompilerGenerated() && type.IsNested) { logName = type.DeclaringType.FullName; } instructions.Insert(0, Instruction.Create(OpCodes.Ldstr, logName)); instructions.Insert(1, Instruction.Create(OpCodes.Call, buildLoggerMethod)); instructions.Insert(2, Instruction.Create(OpCodes.Stsfld, fieldDefinition)); } type.Fields.Add(fieldDefinition); }
public override List<IFieldDefinition> Rewrite(List<IFieldDefinition> fields) { if (fields != null) { var addedFields = new List<IFieldDefinition>(); foreach (var field in fields) { if (field.IsStatic == false && field.ContainingType.IsEnum == false) { // private long fieldname$$storeCount; var storeField = new FieldDefinition() { Name = this.host.NameTable.GetNameFor(MemberHelper.GetMemberSignature(field, NameFormattingOptions.None) + "$$storeCount"), Type = this.host.PlatformType.SystemInt64, InternFactory = base.host.InternFactory, ContainingTypeDefinition = field.ContainingTypeDefinition, Visibility = field.Visibility, IsStatic = false }; var loadField = new FieldDefinition() { Name = this.host.NameTable.GetNameFor(MemberHelper.GetMemberSignature(field, NameFormattingOptions.None) + "$$loadCount"), Type = this.host.PlatformType.SystemInt64, InternFactory = base.host.InternFactory, ContainingTypeDefinition = field.ContainingTypeDefinition, Visibility = field.Visibility, IsStatic = false }; addedFields.Add(storeField); addedFields.Add(loadField); Console.WriteLine("Added shadow field to : " + MemberHelper.GetMemberSignature(field, NameFormattingOptions.None)); } } foreach (var field in addedFields) fields.Add(field); } return fields; }
void ProcessField(FieldDefinition field) { if (IsCompilerGenerated(field.CustomAttributes)) { return; } if (field.IsPublic) { return; } var requiresPublicize = false; if (field.IsAssembly) { field.IsAssembly = false; requiresPublicize = true; } if (field.IsPrivate) { field.IsPrivate = false; requiresPublicize = true; } if (requiresPublicize) { field.IsPublic = true; AddEditorBrowsableAttribute(field.CustomAttributes); } }
void CreateFields(TypeDefinition targetTypeDefinition) { TargetField = new FieldDefinition("target", FieldAttributes.Public, targetTypeDefinition); TypeDefinition.Fields.Add(TargetField); PropertyNameField = new FieldDefinition("propertyName", FieldAttributes.Public, ModuleWeaver.ModuleDefinition.TypeSystem.String); TypeDefinition.Fields.Add(PropertyNameField); }
public static string GetQuotedColumnName(this IOrmLiteDialectProvider dialect, ModelDefinition modelDef, FieldDefinition fieldDef) { return dialect.GetQuotedTableName(modelDef.ModelName) + "." + dialect.GetQuotedColumnName(fieldDef.FieldName); }
//Also support coercing 0 != int as Bool public override object FromDbValue(FieldDefinition fieldDef, object value) { if (value is bool) return value; return 0 != (long)this.ConvertNumber(typeof(long), value); }
void InjectAsStreamReader(TypeDefinition targetType, FieldDefinition fieldDefinition) { AsStreamReaderMethod = new MethodDefinition("AsStreamReader", staticMethodAttributes, StreamReaderTypeReference); var streamVariable = new VariableDefinition(StreamTypeReference); AsStreamReaderMethod.Body.Variables.Add(streamVariable); var pathParam = new ParameterDefinition(ModuleDefinition.TypeSystem.String); AsStreamReaderMethod.Parameters.Add(pathParam); AsStreamReaderMethod.Body.InitLocals = true; var inst = AsStreamReaderMethod.Body.Instructions; var skipReturn = Instruction.Create(OpCodes.Nop); inst.Add(Instruction.Create(OpCodes.Ldsfld, fieldDefinition)); inst.Add(Instruction.Create(OpCodes.Ldarg, pathParam)); inst.Add(Instruction.Create(OpCodes.Callvirt, GetManifestResourceStreamMethod)); inst.Add(Instruction.Create(OpCodes.Stloc, streamVariable)); inst.Add(Instruction.Create(OpCodes.Ldloc, streamVariable)); inst.Add(Instruction.Create(OpCodes.Brtrue_S, skipReturn)); inst.Add(Instruction.Create(OpCodes.Ldnull)); inst.Add(Instruction.Create(OpCodes.Ret)); inst.Add(skipReturn); inst.Add(Instruction.Create(OpCodes.Ldloc, streamVariable)); inst.Add(Instruction.Create(OpCodes.Newobj, StreamReaderConstructorReference)); inst.Add(Instruction.Create(OpCodes.Ret)); targetType.Methods.Add(AsStreamReaderMethod); }
public QueryResultsTotalizerModel(IVisualStudioAdapter visualStudioAdapter) { this.visualStudioAdapter = visualStudioAdapter; CurrentWorkItems = new WorkItem[0]; NumericFieldDefinitions = new FieldDefinition[0]; }
void CreateFields(TypeDefinition targetTypeDefinition) { Target = new FieldDefinition("target", FieldAttributes.Public, targetTypeDefinition); TypeDefinition.Fields.Add(Target); PropertyName = new FieldDefinition("propertyName", FieldAttributes.Public, msCoreReferenceFinder.StringTypeReference); TypeDefinition.Fields.Add(PropertyName); }
public override object FromDbValue(FieldDefinition fieldDef, object value) { var dateTime = (DateTime)value; if (DateStyle == DateTimeKind.Unspecified) dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local); return base.FromDbValue(dateTime); }
public void CustomFields_IsSearchable() { var fieldName = new FieldDefinition("Full Name", ColumnTypes.String, null, null); var fieldDate = new FieldDefinition("Date field", ColumnTypes.DateTime, null, null); Assert.IsTrue(fieldName.IsSearchable); Assert.IsTrue(fieldDate.IsSearchable); }
void AddToList(FieldDefinition field, string name) { var retIndex = loaderCctor.Body.Instructions.Count - 1; loaderCctor.Body.Instructions.InsertBefore(retIndex, new Instruction[] { Instruction.Create(OpCodes.Ldsfld, field), Instruction.Create(OpCodes.Ldstr, name), Instruction.Create(OpCodes.Callvirt, listOfStringAdd), }); }
public override object FromDbValue(FieldDefinition fieldDef, object value) { //BitConverter.IsLittleEndian // TODO: check big endian byte[] raw = ((Guid)value).ToByteArray(); return new Guid(System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(raw, 0)), System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 4)), System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(raw, 6)), raw[8], raw[9], raw[10], raw[11], raw[12], raw[13], raw[14], raw[15]); }
internal static CilField Create(FieldDefinition fieldDefinition, int token, ref CilReaders readers, CilTypeDefinition typeDefinition) { CilField field = new CilField(); field._fieldDefinition = fieldDefinition; field._token = token; field._readers = readers; field._typeDefinition = typeDefinition; field._isDefaultInitialized = false; return field; }
public override object FromDbValue(FieldDefinition fieldDef, object value) { var bytes = value as byte[]; if (bytes != null) { var ulongValue = OrmLiteUtils.ConvertToULong(bytes); return ulongValue; } return null; }
void InjectField(TypeDefinition type, FieldDefinition fieldDefinition) { var staticConstructor = type.GetStaticConstructor(); var instructions = staticConstructor.Body.Instructions; instructions.Insert(0, Instruction.Create(OpCodes.Ldstr, type.FullName)); instructions.Insert(1, Instruction.Create(OpCodes.Call, buildLoggerMethod)); instructions.Insert(2, Instruction.Create(OpCodes.Stsfld, fieldDefinition.GetGeneric())); type.Fields.Add(fieldDefinition); }
public override object FromDbValue(FieldDefinition fieldDef, object value) { var strValue = value as string; if (strValue != null) { value = DateTimeSerializer.ParseShortestXsdDateTime(strValue); } return FromDbValue(value); }
public override object FromDbValue(FieldDefinition fieldDef, object value) { var strValue = value as string; if (strValue != null) { if (OrmLiteConfig.StringFilter != null) return OrmLiteConfig.StringFilter(strValue); } return value.ToString(); }
public override object FromDbValue(FieldDefinition fieldDef, object value) { if (value is char[]) return value; var strValue = value as string; if (strValue != null) return strValue.ToCharArray(); return (char[])value; }
/// <summary> /// Inject a hook call into this method. /// </summary> /// <param name="method">This method that is used as a target.</param> /// <param name="injectionMethod">The method the call of which to inject.</param> /// <param name="codeOffset"> /// The index of the instruction from which to start injecting. If positive, will count from the /// beginning of the method. If negative, will count from the end. For instance, -1 is the method's last instruction /// and 0 is the first. /// </param> /// <param name="tag"> /// If <see cref="InjectFlags.PassTag" /> is specified, the value of this parameter will be passed as a /// parameter to the injection method. /// </param> /// <param name="flags">Injection flags that specify what values to pass to the injection method and how to inject it.</param> /// <param name="dir">The direction in which to insert the call: either above the start code or below it.</param> /// <param name="localsID"> /// An array of indicies of local variables to pass to the injection method. Used only if /// <see cref="InjectFlags.PassLocals" /> is specified, otherwise ignored. /// </param> /// <param name="typeFields"> /// An array of class fields from the type the target lies in to pass to the injection method. /// Used only if <see cref="InjectFlags.PassFields" /> is specified, otherwise ignored. /// </param> public static void InjectWith(this MethodDefinition method, MethodDefinition injectionMethod, int codeOffset = 0, int tag = 0, InjectFlags flags = InjectFlags.None, InjectDirection dir = InjectDirection.Before, int[] localsID = null, FieldDefinition[] typeFields = null) { InjectionDefinition id = new InjectionDefinition(method, injectionMethod, flags, localsID, typeFields); id.Inject(codeOffset, tag, dir); }
void InjectField(TypeDefinition type, FieldDefinition fieldDefinition) { var logName = type.GetNonCompilerGeneratedType().FullName; var staticConstructor = type.GetStaticConstructor(); var instructions = staticConstructor.Body.Instructions; instructions.Insert(0, Instruction.Create(OpCodes.Call, GetDefaultLogManager)); instructions.Insert(1, Instruction.Create(OpCodes.Ldstr, logName)); instructions.Insert(2, Instruction.Create(OpCodes.Ldnull)); instructions.Insert(3, Instruction.Create(OpCodes.Callvirt, constructLoggerMethod)); instructions.Insert(4, Instruction.Create(OpCodes.Stsfld, fieldDefinition.GetGeneric())); type.Fields.Add(fieldDefinition); }
MethodDefinition GetSet(FieldDefinition field, string name) { var set = new MethodDefinition("set_" + name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, msCoreReferenceFinder.VoidTypeReference); var instructions = set.Body.Instructions; instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); instructions.Add(Instruction.Create(OpCodes.Ldarg_1)); instructions.Add(Instruction.Create(OpCodes.Stfld, field)); instructions.Add(Instruction.Create(OpCodes.Ret)); set.Parameters.Add(new ParameterDefinition(field.FieldType)); set.SemanticsAttributes = MethodSemanticsAttributes.Setter; return set; }
void InjectAsStream(TypeDefinition targetType, FieldDefinition fieldDefinition) { AsStreamMethod = new MethodDefinition("AsStream", staticMethodAttributes, StreamTypeReference); var pathParam = new ParameterDefinition(ModuleDefinition.TypeSystem.String); AsStreamMethod.Parameters.Add(pathParam); AsStreamMethod.Body.InitLocals = true; var inst = AsStreamMethod.Body.Instructions; inst.Add(Instruction.Create(OpCodes.Ldsfld, fieldDefinition)); inst.Add(Instruction.Create(OpCodes.Ldarg, pathParam)); inst.Add(Instruction.Create(OpCodes.Callvirt, GetManifestResourceStreamMethod)); inst.Add(Instruction.Create(OpCodes.Ret)); targetType.Methods.Add(AsStreamMethod); }
void ProcessField( FieldDefinition field) { if (field.IsStatic) { return; } if (field.Attributes != FieldAttributes.InitOnly) { field.Attributes = field.Attributes | FieldAttributes.InitOnly; ImmutableFields.Add(field); } }
public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) { new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).DisassembleField(field); }
public FieldInfo(FieldDefinition field, FieldDefinition arrayInitField) { this.field = field; this.arrayInitField = arrayInitField; this.array = (byte[])arrayInitField.InitialValue.Clone(); }
protected override void ProcessFieldProperties(SPField field, FieldDefinition fieldModel) { // let base setting be setup base.ProcessFieldProperties(field, fieldModel); }
public ActionResult <FieldDefinitionDto> GetFieldDefinition([FromRoute] int fieldDefinitionTypeID) { var fieldDefinitionDto = FieldDefinition.GetByFieldDefinitionTypeID(_dbContext, fieldDefinitionTypeID); return(RequireNotNullThrowNotFound(fieldDefinitionDto, "FieldDefinition", fieldDefinitionTypeID)); }
protected override Type GetTargetFieldType(FieldDefinition model) { return(typeof(SPBusinessDataField)); }
protected override Type GetTargetFieldType(FieldDefinition model) { return(typeof(FieldMultiLineText)); }
public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options) { var dis = CreateDisassembler(output, options); dis.DisassembleField(field); }
/// <summary> /// Defines the <see cref="IMicroContainer.GetInstance"/> method implementation for the container type. /// </summary> /// <param name="containerType">The container type.</param> /// <param name="module">The target module.</param> /// <param name="getServiceHash">The GetServiceHash method.</param> /// <param name="jumpTargetField">The field that will store the jump target indexes.</param> /// <param name="serviceMap">The service map that contains the list of existing services.</param> public void DefineGetInstanceMethod(TypeDefinition containerType, ModuleDefinition module, MethodDefinition getServiceHash, FieldDefinition jumpTargetField, IDictionary <IDependency, IImplementation> serviceMap) { var targetMethods = new List <MethodDefinition>(); foreach (MethodDefinition method in containerType.Methods) { if (method.Name != "GetInstance") { continue; } targetMethods.Add(method); } MethodDefinition getInstanceMethod = targetMethods[0]; var body = getInstanceMethod.Body; body.InitLocals = true; var il = body.GetILProcessor(); body.Instructions.Clear(); DefineServices(serviceMap, getInstanceMethod, jumpTargetField, getServiceHash, il); il.Emit(OpCodes.Ret); }
private void WriteGetterFixedSizeArray(TypeDefinition type, ManagedUnrealTypeInfo typeInfo, ManagedUnrealPropertyInfo propertyInfo, MethodDefinition getter, FieldDefinition isValidField, FieldDefinition offsetField, FieldDefinition nativePropertyField, FieldDefinition fixedSizeArrayField) { ILProcessor processor = BeginGetter(getter); processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Ldfld, fixedSizeArrayField); // Save the position of the branch instruction for later, when we have a reference to its target. // (will insert Brtrue_S before this instruction as a null check on the wrapper field) processor.Emit(OpCodes.Ldarg_0); Instruction branchPosition = processor.Body.Instructions[processor.Body.Instructions.Count - 1]; MethodReference constructor = null; foreach (MethodDefinition ctor in fixedSizeArrayField.FieldType.Resolve().GetConstructors()) { if (ctor.Parameters.Count == 3) { constructor = ctor; break; } } VerifyNonNull(constructor, type, "constructor for " + fixedSizeArrayField.FieldType.FullName); constructor = GetConstrainedGenericTypeCtor(fixedSizeArrayField.FieldType, constructor); // new TFixedSizeArray<XXXX>(IntPtr.Add(Address, XXXX_Offset), XXXX_PropertyAddress, this); // IntPtr.Add(this.Address, XXXX_Offset) processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Call, uobjectAddressGetter); processor.Emit(OpCodes.Ldsfld, offsetField); processor.Emit(OpCodes.Call, intPtrAddMethod); // XXXX_PropertyAddress processor.Emit(OpCodes.Ldsfld, nativePropertyField); // this processor.Emit(OpCodes.Ldarg_0); // Create an instance of the array and store in the member field processor.Emit(OpCodes.Newobj, constructor); processor.Emit(OpCodes.Stfld, fixedSizeArrayField); // return XXXX; processor.Emit(OpCodes.Ldarg_0); Instruction branchTarget = processor.Body.Instructions[processor.Body.Instructions.Count - 1]; processor.Emit(OpCodes.Ldfld, fixedSizeArrayField); // Insert the branch (before the return statement) Instruction branchInstruction = processor.Create(OpCodes.Brtrue_S, branchTarget); processor.InsertBefore(branchPosition, branchInstruction); EndGetter(typeInfo, propertyInfo, getter, isValidField, processor); }
/// <summary> /// Defines the instructions that create each service type in the <paramref name="serviceMap"/>. /// </summary> /// <param name="serviceMap">The service map that contains the list of application dependencies.</param> /// <param name="getInstanceMethod">The method that will be used to instantiate the service types.</param> /// <param name="jumpTargetField">The field that holds the dictionary with the switch table target instructions.</param> /// <param name="getServiceHash">The method that calculates the service hash code.</param> /// <param name="il">The <see cref="ILProcessor"/> that points to the body of the factory method.</param> private void DefineServices(IDictionary <IDependency, IImplementation> serviceMap, MethodDefinition getInstanceMethod, FieldDefinition jumpTargetField, MethodDefinition getServiceHash, ILProcessor il) { var endLabel = Instruction.Create(OpCodes.Nop); il.Append(endLabel); var body = il.Body; body.InitLocals = true; var method = body.Method; var returnValue = method.AddLocal <object>(); var declaringType = method.DeclaringType; var module = declaringType.Module; var jumpTargets = new Dictionary <IDependency, Instruction>(); foreach (var dependency in serviceMap.Keys) { jumpTargets[dependency] = il.Create(OpCodes.Nop); } var getItemMethod = module.ImportMethod <Dictionary <int, int> >("get_Item"); var serviceHash = method.AddLocal <int>(); var skipCreate = il.Create(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, jumpTargetField); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Call, getServiceHash); il.Emit(OpCodes.Stloc, serviceHash); var contains = module.ImportMethod <Dictionary <int, int> >("ContainsKey"); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, jumpTargetField); il.Emit(OpCodes.Ldloc, serviceHash); il.Emit(OpCodes.Callvirt, contains); il.Emit(OpCodes.Brfalse, skipCreate); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, jumpTargetField); il.Emit(OpCodes.Ldloc, serviceHash); il.Emit(OpCodes.Callvirt, getItemMethod); var switchLabels = new List <Instruction>(jumpTargets.Values); var labels = switchLabels.ToArray(); il.Emit(OpCodes.Switch, labels); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Stloc, returnValue); il.Emit(OpCodes.Br, skipCreate); foreach (var dependency in serviceMap.Keys) { // Set the jump target var currentLabel = jumpTargets[dependency]; il.Append(currentLabel); var serviceType = module.ImportType(dependency.ServiceType); // Emit the implementation var implementation = serviceMap[dependency]; EmitService(getInstanceMethod, dependency, implementation, serviceMap); il.Emit(OpCodes.Stloc, returnValue); var serviceInstance = returnValue; // Call IInitialize.Initialize(this) on the current type if (_initializer != null) { _initializer.Initialize(il, module, serviceInstance); } //il.Emit(OpCodes.Ldloc, returnValue); //il.Emit(OpCodes.Unbox_Any, serviceType); il.Emit(OpCodes.Br, endLabel); } il.Append(skipCreate); var getNextContainer = module.ImportMethod <IMicroContainer>("get_NextContainer"); var otherContainer = method.AddLocal <IMicroContainer>(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Callvirt, getNextContainer); il.Emit(OpCodes.Stloc, otherContainer); // if (otherContainer != null ) { var skipOtherContainerCall = il.Create(OpCodes.Nop); il.Emit(OpCodes.Ldloc, otherContainer); il.Emit(OpCodes.Brfalse, skipOtherContainerCall); // Prevent the container from calling itself il.Emit(OpCodes.Ldloc, otherContainer); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Brtrue, skipOtherContainerCall); var otherGetInstanceMethod = module.ImportMethod <IMicroContainer>("GetInstance"); // return otherContainer.GetInstance(type, key); il.Emit(OpCodes.Ldloc, otherContainer); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Callvirt, otherGetInstanceMethod); il.Emit(OpCodes.Stloc, returnValue); il.Emit(OpCodes.Br, endLabel); // } il.Append(skipOtherContainerCall); il.Append(endLabel); il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ldloc, returnValue); }
private void WriteSetter(ManagedUnrealTypeInfo typeInfo, ManagedUnrealPropertyInfo propertyInfo, MethodDefinition setter, FieldDefinition isValidField, FieldDefinition offsetField, FieldDefinition nativePropertyField) { ILProcessor processor = BeginSetter(setter); Instruction loadValue = processor.Create(OpCodes.Ldarg_1); Instruction[] loadBufferInstructions = GetLoadNativeBufferInstructions(typeInfo, processor, null, offsetField); MethodReference marshaler = GetToNativeMarshaler(ManagedUnrealMarshalerType.Default, propertyInfo); WriteMarshalToNative(processor, nativePropertyField, loadBufferInstructions, null, loadValue, marshaler); EndSetter(typeInfo, propertyInfo, setter, isValidField, processor); }
public static bool IsCompilerGenerated(this FieldDefinition field, MetadataReader metadata) { return(field.GetCustomAttributes().HasKnownAttribute(metadata, KnownAttribute.CompilerGenerated)); }
public static InnerInvoker Create(ModuleDefinition moduleDefinition, TypeDefinition parent, MethodDefinition targetMethod) { var innerInvoker = new TypeDefinition(parent.Namespace, $"{targetMethod.Name}Invoker", TypeAttributes.NotPublic | TypeAttributes.NestedPrivate); var result = new InnerInvoker(innerInvoker); var invocationType = moduleDefinition.ImportReference(typeof(Invocation)); innerInvoker.BaseType = invocationType; // Constructor var methodAttributes = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; var constructor = new MethodDefinition(".ctor", methodAttributes, moduleDefinition.TypeSystem.Void); constructor.Parameters.Add(new ParameterDefinition("interceptorTypes", ParameterAttributes.None, moduleDefinition.ImportReference(typeof(Type).MakeArrayType()))); constructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); constructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_1)); var baseConstructor = invocationType.Resolve().GetConstructors().Single(); constructor.Body.Instructions.Add(Instruction.Create(OpCodes.Call, moduleDefinition.ImportReference(baseConstructor))); constructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); // Fields var parentField = new FieldDefinition(parent.Name, FieldAttributes.Assembly, parent); innerInvoker.Fields.Add(parentField); result.ParentTypeFieldDefinition = parentField; for (int i = 0; i < targetMethod.Parameters.Count; i++) { var parameter = targetMethod.Parameters[i]; var parameterFieldDefinition = new FieldDefinition($"Value{i + 1}", FieldAttributes.Assembly, parameter.ParameterType); innerInvoker.Fields.Add(parameterFieldDefinition); result.ParameterFieldDefinisions.Add(parameterFieldDefinition); } // Properties var arguments = new PropertyDefinition("Arguments", PropertyAttributes.None, moduleDefinition.ImportReference(typeof(object).MakeArrayType())) { HasThis = true }; var getArgumentsAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Virtual; var getArguments = new MethodDefinition("get_Arguments", getArgumentsAttributes, moduleDefinition.ImportReference(typeof(object).MakeArrayType())) { HasThis = true }; getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, targetMethod.Parameters.Count)); getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Newarr, moduleDefinition.TypeSystem.Object)); for (int i = 0; i < result.ParameterFieldDefinisions.Count; i++) { var fieldDefinition = result.ParameterFieldDefinisions[i]; getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Dup)); getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, i)); getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Ldfld, fieldDefinition)); if (fieldDefinition.FieldType.IsPrimitive) { getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Box, fieldDefinition.FieldType)); } getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Stelem_Ref)); } getArguments.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); innerInvoker.Methods.Add(getArguments); arguments.GetMethod = getArguments; innerInvoker.Properties.Add(arguments); // InvokeEndpoint var invokeEndpointAttribute = MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.Virtual; var invokeEndpoint = new MethodDefinition("InvokeEndpoint", invokeEndpointAttribute, moduleDefinition.TypeSystem.Object); invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Ldfld, parentField)); foreach (var valueFieldDefinition in result.ParameterFieldDefinisions) { invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Ldfld, valueFieldDefinition)); } invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Callvirt, targetMethod)); if (targetMethod.ReturnType.IsPrimitive) { invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Box, targetMethod.ReturnType)); } invokeEndpoint.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); innerInvoker.Methods.Add(invokeEndpoint); innerInvoker.Methods.Add(constructor); return(result); }
public static MethodDefinition ProcessSyncVarGet(FieldDefinition fd, string originalName, FieldDefinition netFieldId) { //Create the get method MethodDefinition get = new MethodDefinition( "get_Network" + originalName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, fd.FieldType); ILProcessor getWorker = get.Body.GetILProcessor(); // [SyncVar] GameObject? if (fd.FieldType.FullName == Weaver.gameObjectType.FullName) { // return this.GetSyncVarGameObject(ref field, uint netId); // this. getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldfld, netFieldId)); getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldflda, fd)); getWorker.Append(getWorker.Create(OpCodes.Call, Weaver.getSyncVarGameObjectReference)); getWorker.Append(getWorker.Create(OpCodes.Ret)); } // [SyncVar] NetworkIdentity? else if (fd.FieldType.FullName == Weaver.NetworkIdentityType.FullName) { // return this.GetSyncVarNetworkIdentity(ref field, uint netId); // this. getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldfld, netFieldId)); getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldflda, fd)); getWorker.Append(getWorker.Create(OpCodes.Call, Weaver.getSyncVarNetworkIdentityReference)); getWorker.Append(getWorker.Create(OpCodes.Ret)); } // [SyncVar] int, string, etc. else { getWorker.Append(getWorker.Create(OpCodes.Ldarg_0)); getWorker.Append(getWorker.Create(OpCodes.Ldfld, fd)); getWorker.Append(getWorker.Create(OpCodes.Ret)); } get.Body.Variables.Add(new VariableDefinition(fd.FieldType)); get.Body.InitLocals = true; get.SemanticsAttributes = MethodSemanticsAttributes.Getter; return(get); }
protected void ValidateField(AssertPair <FieldDefinition, Field> assert, Field spObject, FieldDefinition definition) { assert .ShouldNotBeNull(spObject) .ShouldBeEqual(m => m.Title, o => o.Title) //.ShouldBeEqual(m => m.InternalName, o => o.InternalName) .ShouldBeEqual(m => m.Id, o => o.Id); //.ShouldBeEqual(m => m.FieldType, o => o.TypeAsString) //.ShouldBeEqual(m => m.Group, o => o.Group); if (!string.IsNullOrEmpty(definition.Group)) { assert.ShouldBeEqual(m => m.Group, o => o.Group); } else { assert.SkipProperty(m => m.Group); } CustomFieldTypeValidation(assert, spObject, definition); if (!string.IsNullOrEmpty(definition.StaticName)) { assert.ShouldBeEqual(m => m.StaticName, o => o.StaticName); } else { assert.SkipProperty(m => m.StaticName); } if (definition.AddFieldOptions.HasFlag(BuiltInAddFieldOptions.DefaultValue)) { assert.SkipProperty(m => m.AddFieldOptions, "BuiltInAddFieldOptions.DefaultValue. Skipping."); } else { // TODO } if (definition.AddToDefaultView) { if (IsListScopedField) { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(m => m.AddToDefaultView); var context = HostList.Context; var field = HostList.Fields.GetById(definition.Id); var defaultView = HostList.DefaultView; context.Load(defaultView); context.Load(defaultView, v => v.ViewFields); context.Load(field); context.ExecuteQueryWithTrace(); var isValid = HostList.DefaultView .ViewFields .Contains(field.InternalName); return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } else { assert.SkipProperty(m => m.AddToDefaultView, "IsListScopedField = true. AddToDefaultView is ignored. Skipping."); } } else { assert.SkipProperty(m => m.AddToDefaultView, "AddToDefaultView is false. Skipping."); } if (definition.AdditionalAttributes.Count == 0) { assert.SkipProperty(m => m.AdditionalAttributes, "AdditionalAttributes count is 0. Skipping."); } else { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.AdditionalAttributes); var isValid = true; var dstXmlNode = XDocument.Parse(d.SchemaXml).Root; foreach (var attr in s.AdditionalAttributes) { var sourceAttrName = attr.Name; var sourceAttrValue = attr.Value; var destAttrValue = dstXmlNode.GetAttributeValue(sourceAttrName); isValid = sourceAttrValue == destAttrValue; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } if (string.IsNullOrEmpty(definition.RawXml)) { assert.SkipProperty(m => m.RawXml, "RawXml is NULL or empty. Skipping."); } else { assert.ShouldBeEqual((p, s, d) => { var srcProp = s.GetExpressionValue(def => def.RawXml); var isValid = true; var srcXmlNode = XDocument.Parse(s.RawXml).Root; var dstXmlNode = XDocument.Parse(d.SchemaXml).Root; foreach (var attr in srcXmlNode.Attributes()) { var sourceAttrName = attr.Name.LocalName; var sourceAttrValue = attr.Value; var destAttrValue = dstXmlNode.GetAttributeValue(sourceAttrName); isValid = sourceAttrValue == destAttrValue; if (!isValid) { break; } } return(new PropertyValidationResult { Tag = p.Tag, Src = srcProp, Dst = null, IsValid = isValid }); }); } // TODO, R&D to check InternalName changes in list-scoped fields if (spObject.InternalName == definition.InternalName) { assert.ShouldBeEqual(m => m.InternalName, o => o.InternalName); } else { assert.SkipProperty(m => m.InternalName, "Target InternalName is different to source InternalName. Could be an error if this is not a list scoped field"); } if (!string.IsNullOrEmpty(definition.ValidationFormula)) { assert.ShouldBeEqual(m => m.ValidationFormula, o => o.ValidationFormula); } else { assert.SkipProperty(m => m.ValidationFormula, string.Format("ValidationFormula value is not set. Skippping.")); } if (!string.IsNullOrEmpty(definition.ValidationMessage)) { assert.ShouldBeEqual(m => m.ValidationMessage, o => o.ValidationMessage); } else { assert.SkipProperty(m => m.ValidationMessage, string.Format("ValidationFormula value is not set. Skippping.")); } // taxonomy field seems to prodice issues w/ Required/Description validation if (!SkipRequredPropValidation) { assert.ShouldBeEqual(m => m.Required, o => o.Required); } else { assert.SkipProperty(m => m.Required, "Skipping Required prop validation."); } if (!string.IsNullOrEmpty(definition.Description)) { assert.ShouldBeEqual(m => m.Description, o => o.Description); } else { assert.SkipProperty(m => m.Description, "Skipping Description prop validation."); } assert.ShouldBeEqual(m => m.Hidden, o => o.Hidden); if (!string.IsNullOrEmpty(definition.DefaultValue)) { assert.ShouldBePartOf(m => m.DefaultValue, o => o.DefaultValue); } else { assert.SkipProperty(m => m.DefaultValue, string.Format("Default value is not set. Skippping.")); } if (!string.IsNullOrEmpty(spObject.JSLink) && (spObject.JSLink == "SP.UI.Taxonomy.js|SP.UI.Rte.js(d)|SP.Taxonomy.js(d)|ScriptForWebTaggingUI.js(d)" || spObject.JSLink == "choicebuttonfieldtemplate.js" || spObject.JSLink == "clienttemplates.js")) { assert.SkipProperty(m => m.JSLink, string.Format("OOTB read-ony JSLink value:[{0}]", spObject.JSLink)); } else { assert.ShouldBePartOf(m => m.JSLink, o => o.JSLink); } if (definition.EnforceUniqueValues.HasValue) { assert.ShouldBeEqual(m => m.EnforceUniqueValues, o => o.EnforceUniqueValues); } else { assert.SkipProperty(m => m.EnforceUniqueValues, "EnforceUniqueValues is NULL"); } if (definition.ShowInDisplayForm.HasValue) { assert.ShouldBeEqual(m => m.ShowInDisplayForm, o => o.GetShowInDisplayForm()); } else { assert.SkipProperty(m => m.ShowInDisplayForm, "ShowInDisplayForm is NULL"); } if (definition.ShowInEditForm.HasValue) { assert.ShouldBeEqual(m => m.ShowInEditForm, o => o.GetShowInEditForm()); } else { assert.SkipProperty(m => m.ShowInEditForm, "ShowInEditForm is NULL"); } if (definition.ShowInListSettings.HasValue) { assert.ShouldBeEqual(m => m.ShowInListSettings, o => o.GetShowInListSettings()); } else { assert.SkipProperty(m => m.ShowInListSettings, "ShowInListSettings is NULL"); } if (definition.ShowInNewForm.HasValue) { assert.ShouldBeEqual(m => m.ShowInNewForm, o => o.GetShowInNewForm()); } else { assert.SkipProperty(m => m.ShowInNewForm, "ShowInNewForm is NULL"); } if (definition.ShowInVersionHistory.HasValue) { assert.ShouldBeEqual(m => m.ShowInVersionHistory, o => o.GetShowInVersionHistory()); } else { assert.SkipProperty(m => m.ShowInVersionHistory, "ShowInVersionHistory is NULL"); } if (definition.ShowInViewForms.HasValue) { assert.ShouldBeEqual(m => m.ShowInViewForms, o => o.GetShowInViewForms()); } else { assert.SkipProperty(m => m.ShowInViewForms, "ShowInViewForms is NULL"); } assert .ShouldBeEqual(m => m.Indexed, o => o.Indexed); if (definition.AllowDeletion.HasValue) { assert.ShouldBeEqual(m => m.AllowDeletion, o => o.GetAllowDeletion()); } else { assert.SkipProperty(m => m.AllowDeletion, "AllowDeletion is NULL"); } }
public ActionResult <List <FieldDefinitionDto> > ListAllFieldDefinitions() { var fieldDefinitionDtos = FieldDefinition.List(_dbContext); return(fieldDefinitionDtos); }
protected virtual void CustomFieldTypeValidation(AssertPair <FieldDefinition, Field> assert, Field spObject, FieldDefinition definition) { assert.ShouldBeEqual(m => m.FieldType, o => o.TypeAsString); }
private void WriteGetterDelegate(ManagedUnrealTypeInfo typeInfo, ManagedUnrealPropertyInfo propertyInfo, MethodDefinition getter, FieldDefinition isValidField, FieldDefinition offsetField, FieldDefinition delegateWrapperField) { ILProcessor processor = BeginGetter(getter); processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Ldfld, delegateWrapperField); // Save the position of the branch instruction for later, when we have a reference to its target. // (will insert Brtrue_S before this instruction as a null check on the wrapper field) processor.Emit(OpCodes.Ldarg_0); Instruction branchPosition = processor.Body.Instructions[processor.Body.Instructions.Count - 1]; Type delegateType = ManagedUnrealTypeInfo.GetTypeFromPropertyInfo(propertyInfo); // Find the default constructor / SetAddress method for the delegate System.Reflection.ConstructorInfo delegateCtor = delegateType.GetConstructor(Type.EmptyTypes); System.Reflection.MethodInfo setAddressMethod = delegateType.GetMethod("SetAddress"); // Create an instance of the delegate and store in the member field processor.Emit(OpCodes.Newobj, assembly.MainModule.ImportEx(delegateCtor)); processor.Emit(OpCodes.Stfld, delegateWrapperField); processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Ldfld, delegateWrapperField); processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Call, uobjectAddressGetter); processor.Emit(OpCodes.Ldsfld, offsetField); processor.Emit(OpCodes.Call, intPtrAddMethod); processor.Emit(OpCodes.Callvirt, assembly.MainModule.ImportEx(setAddressMethod)); processor.Emit(OpCodes.Ldarg_0); Instruction branchTarget = processor.Body.Instructions[processor.Body.Instructions.Count - 1]; processor.Emit(OpCodes.Ldfld, delegateWrapperField); // Insert the branch Instruction branchInstruction = processor.Create(OpCodes.Brtrue_S, branchTarget); processor.InsertBefore(branchPosition, branchInstruction); EndGetter(typeInfo, propertyInfo, getter, isValidField, processor); }
public void VisitFieldDefinition(FieldDefinition field) { VisitTypeReference(field.FieldType); }
private void WriteGetterCollection(ManagedUnrealTypeInfo typeInfo, ManagedUnrealPropertyInfo propertyInfo, MethodDefinition getter, FieldDefinition isValidField, FieldDefinition offsetField, FieldDefinition nativePropertyField, FieldDefinition collectionWrapperField) { ILProcessor processor = BeginGetter(getter); processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Ldfld, collectionWrapperField); // Save the position of the branch instruction for later, when we have a reference to its target. // (will insert Brtrue_S before this instruction as a null check on the wrapper field) processor.Emit(OpCodes.Ldarg_0); Instruction branchPosition = processor.Body.Instructions[processor.Body.Instructions.Count - 1]; processor.Emit(OpCodes.Ldc_I4_1); processor.Emit(OpCodes.Ldsfld, nativePropertyField); // New delegate marshaling code, this will use a cached delegate EmitCachedMarshalingDelegates(processor, propertyInfo, ManagedUnrealMarshalerType.Default); System.Reflection.ConstructorInfo collectionCtor; System.Reflection.MethodInfo fromNativeMethod; System.Reflection.MethodInfo toNativeMethod; GetInstancedMarshalerMethods(propertyInfo, ManagedUnrealMarshalerType.Default, out collectionCtor, out fromNativeMethod, out toNativeMethod); int numFromNativeParams = fromNativeMethod.GetParameters().Length; // Create an instance of the collection marshaler and store in the member field processor.Emit(OpCodes.Newobj, assembly.MainModule.ImportEx(collectionCtor)); processor.Emit(OpCodes.Stfld, collectionWrapperField); // Store the branch destination processor.Emit(OpCodes.Ldarg_0); Instruction branchTarget = processor.Body.Instructions[processor.Body.Instructions.Count - 1]; processor.Emit(OpCodes.Ldfld, collectionWrapperField); processor.Emit(OpCodes.Ldarg_0); processor.Emit(OpCodes.Call, uobjectAddressGetter); processor.Emit(OpCodes.Ldsfld, offsetField); processor.Emit(OpCodes.Call, intPtrAddMethod); if (numFromNativeParams == marshalerFromNativeParamCount) { // arrayIndex, prop (IntPtr.Zero as prop is already known by the collection marshaler), this processor.Emit(OpCodes.Ldc_I4_0); processor.Emit(OpCodes.Ldnull); processor.Emit(OpCodes.Ldarg_0); } else { System.Diagnostics.Debug.Assert(numFromNativeParams == marshalerFromNativeParamCountMin); } processor.Emit(OpCodes.Callvirt, assembly.MainModule.ImportEx(fromNativeMethod)); // Now insert the branch Instruction branchInstruction = processor.Create(OpCodes.Brtrue_S, branchTarget); processor.InsertBefore(branchPosition, branchInstruction); EndGetter(typeInfo, propertyInfo, getter, isValidField, processor); }
public static bool IsDynamicType(this FieldDefinition field) { return(field.CustomAttributes.Any(a => a.AttributeType.EqualsType(typeof(DynamicAttribute)))); }
private void WriteGetter(ManagedUnrealTypeInfo typeInfo, ManagedUnrealPropertyInfo propertyInfo, MethodDefinition getter, FieldDefinition isValidField, FieldDefinition offsetField, FieldDefinition nativePropertyField) { ILProcessor processor = BeginGetter(getter); Instruction[] loadBufferInstructions = GetLoadNativeBufferInstructions(typeInfo, processor, null, offsetField); MethodReference marshaler = GetFromNativeMarshaler(ManagedUnrealMarshalerType.Default, propertyInfo); WriteMarshalFromNative(processor, nativePropertyField, loadBufferInstructions, null, marshaler); EndGetter(typeInfo, propertyInfo, getter, isValidField, processor); }
private DecompiledType GetDecompiledType(IMemberDefinition member, ILanguage language) { TypeDefinition declaringType = Utilities.GetDeclaringTypeOrSelf(member); DecompiledType decompiledType = new DecompiledType(declaringType); Queue <IMemberDefinition> decompilationQueue = new Queue <IMemberDefinition>(); decompilationQueue.Enqueue(member); while (decompilationQueue.Count > 0) { IMemberDefinition currentMember = decompilationQueue.Dequeue(); if (currentMember is TypeDefinition && currentMember == member) { TypeDefinition currentType = (currentMember as TypeDefinition); List <IMemberDefinition> members = Utilities.GetTypeMembers(currentType); foreach (IMemberDefinition typeMember in members) { decompilationQueue.Enqueue(typeMember); } } if (currentMember is MethodDefinition) { DecompileMember(currentMember as MethodDefinition, language, decompiledType); } if (currentMember is EventDefinition) { EventDefinition eventDefinition = (currentMember as EventDefinition); AutoImplementedEventMatcher matcher = new AutoImplementedEventMatcher(eventDefinition); bool isAutoImplemented = matcher.IsAutoImplemented(); if (isAutoImplemented) { decompiledType.TypeContext.AutoImplementedEvents.Add(eventDefinition); } if (eventDefinition.AddMethod != null) { DecompileMember(eventDefinition.AddMethod, language, decompiledType); } if (eventDefinition.RemoveMethod != null) { DecompileMember(eventDefinition.RemoveMethod, language, decompiledType); } if (eventDefinition.InvokeMethod != null) { DecompileMember(eventDefinition.InvokeMethod, language, decompiledType); } } if (currentMember is PropertyDefinition) { PropertyDefinition propertyDefinition = (currentMember as PropertyDefinition); AutoImplementedPropertyMatcher matcher = new AutoImplementedPropertyMatcher(propertyDefinition); bool isAutoImplemented = matcher.IsAutoImplemented(); if (isAutoImplemented) { decompiledType.TypeContext.AutoImplementedProperties.Add(propertyDefinition); } if (propertyDefinition.GetMethod != null) { DecompileMember(propertyDefinition.GetMethod, language, decompiledType); } if (propertyDefinition.SetMethod != null) { DecompileMember(propertyDefinition.SetMethod, language, decompiledType); } } if (currentMember is FieldDefinition) { FieldDefinition currentField = currentMember as FieldDefinition; /// Decompile all the constructors, that can set default values to the field. /// For instance fields decompile only instance constructors. /// For static fields decompile only static constructors. foreach (MethodDefinition method in currentMember.DeclaringType.Methods) { if (method.IsConstructor && currentField.IsStatic == method.IsStatic) { DecompileConstructorChain(method, language, decompiledType); break; } } } } decompiledType.TypeContext.ExplicitlyImplementedMembers = GetExplicitlyImplementedInterfaceMethods(declaringType, language); return(decompiledType); }
public override void ProcessField(FieldDefinition field) { ProcessAttributeProvider(field); }
protected override Type GetTargetFieldType(FieldDefinition model) { return(typeof(SPFieldMultiChoice)); }
private void RewriteClass(TypeDefinition type, ManagedUnrealTypeInfo classInfo) { InjectedMembers injectedMembers = new InjectedMembers(classInfo); if (classInfo.IsStructAsClass) { FieldDefinition structAddressField = new FieldDefinition(classInfo.Name + codeSettings.VarNames.StructAddress, FieldAttributes.Public | FieldAttributes.Static, intPtrTypeRef); type.Fields.Add(structAddressField); injectedMembers.ClassAddress = structAddressField; FieldDefinition structIsValidField = new FieldDefinition(classInfo.Name + codeSettings.VarNames.IsValid, FieldAttributes.Private | FieldAttributes.Static, int32TypeRef); type.Fields.Add(structIsValidField); injectedMembers.StructIsValid = structIsValidField; OverrideStructAsClassGetStructAddress(type, structAddressField); } foreach (ManagedUnrealPropertyInfo propertyInfo in classInfo.Properties) { PropertyDefinition propertyDefinition = FindPropertyByName(type, propertyInfo.Name); if (!propertyInfo.IsField && !propertyInfo.IsBackingFieldPreStripped) { StripBackingField(type, propertyInfo); } // Add offset field FieldDefinition isValidField = AddIsValidField(type, propertyInfo); FieldDefinition offsetField = AddOffsetField(type, propertyInfo); FieldDefinition nativePropertyField = AddNativePropertyField(type, propertyInfo); injectedMembers.SetPropertyIsValid(propertyInfo, isValidField); injectedMembers.SetPropertyOffset(propertyInfo, offsetField); injectedMembers.SetPropertyAddress(propertyInfo, nativePropertyField); FieldDefinition fixedSizeArrayField = null; if (propertyInfo.IsFixedSizeArray) { // Add a field to store the fixed size array for the getter...technically we already had one of these which was // the backing field that was stripped. Maybe just not strip the backing field rather than adding a new field // of what should already exist. fixedSizeArrayField = new FieldDefinition( propertyInfo.Name + codeSettings.VarNames.FixedSizeArrayCached, FieldAttributes.Private, propertyDefinition.PropertyType); type.Fields.Add(fixedSizeArrayField); } FieldDefinition collectionWrapperField = null; if (propertyInfo.IsCollection) { // Add a field to store the collection wrapper for the getter collectionWrapperField = new FieldDefinition( propertyInfo.Name + codeSettings.VarNames.CollectionMarshaler, FieldAttributes.Private, assembly.MainModule.ImportEx(ManagedUnrealTypeInfo.GetCollectionType(propertyInfo, ManagedUnrealMarshalerType.Default))); type.Fields.Add(collectionWrapperField); } FieldDefinition delegateWrapperField = null; if (propertyInfo.IsDelegate) { // Add a field to store the delegate wrapper for the getter delegateWrapperField = new FieldDefinition( propertyInfo.Name + codeSettings.VarNames.DelegateCached, FieldAttributes.Private, assembly.MainModule.ImportEx(ManagedUnrealTypeInfo.GetTypeFromPropertyInfo(propertyInfo))); type.Fields.Add(delegateWrapperField); } if (propertyDefinition.GetMethod != null) { if (propertyInfo.IsFixedSizeArray) { WriteGetterFixedSizeArray(type, classInfo, propertyInfo, propertyDefinition.GetMethod, isValidField, offsetField, nativePropertyField, fixedSizeArrayField); } else if (propertyInfo.IsCollection) { // NOTE: To support type downgrading we would need to update any references - this likely wouldn't work well // Downgrade the collection from List to IList, Dictionarty to IDictionary, HashSet to ISet //Type downgradedCollection = GetDowngradedCollectionType(propertyInfo, ManagedUnrealMarshalerType.Default); //propertyDefinition.PropertyType = assembly.MainModule.ImportEx(downgradedCollection); WriteGetterCollection(classInfo, propertyInfo, propertyDefinition.GetMethod, isValidField, offsetField, nativePropertyField, collectionWrapperField); } else if (propertyInfo.IsDelegate) { WriteGetterDelegate(classInfo, propertyInfo, propertyDefinition.GetMethod, isValidField, offsetField, delegateWrapperField); } else { WriteGetter(classInfo, propertyInfo, propertyDefinition.GetMethod, isValidField, offsetField, nativePropertyField); } } if (propertyDefinition.SetMethod != null) { if (propertyInfo.IsFixedSizeArray) { // Setter for fixed sized arrays isn't currently supported (use the indexer / SetValues method) type.Methods.Remove(propertyDefinition.SetMethod); propertyDefinition.SetMethod = null; } else if (propertyInfo.IsCollection) { // Setter for collections isn't currently supported. Use Clear/AddRange instead (this is what the // setter would need to be recoded to if we ever add this support) type.Methods.Remove(propertyDefinition.SetMethod); propertyDefinition.SetMethod = null; } else if (propertyInfo.IsDelegate) { // Setter for delegates isn't currently supported. type.Methods.Remove(propertyDefinition.SetMethod); propertyDefinition.SetMethod = null; } else { WriteSetter(classInfo, propertyInfo, propertyDefinition.SetMethod, isValidField, offsetField, nativePropertyField); } } AddPathAttribute(propertyDefinition, propertyInfo); } if (!classInfo.IsStructAsClass) { Dictionary <string, List <MethodDefinition> > methodsByName = new Dictionary <string, List <MethodDefinition> >(); foreach (MethodDefinition method in type.Methods) { List <MethodDefinition> methods; if (!methodsByName.TryGetValue(method.Name, out methods)) { methodsByName.Add(method.Name, methods = new List <MethodDefinition>()); } methods.Add(method); } foreach (ManagedUnrealFunctionInfo functionInfo in classInfo.Functions) { string functionName = functionInfo.Name; if (codeSettings.UseExplicitImplementationMethods && functionInfo.IsBlueprintEvent && functionInfo.IsOverride) { functionName = functionInfo.Name + codeSettings.VarNames.ImplementationMethod; } List <MethodDefinition> methods; methodsByName.TryGetValue(functionName, out methods); VerifySingleResult(methods, type, "Function " + functionName + " (the reflection system doesn't support overloads"); FieldDefinition functionIsValid = AddIsValidField(type, functionInfo); FieldDefinition functionAddressField = AddNativeFunctionField(type, functionInfo); FieldDefinition paramsSizeField = AddParamsSizeField(type, functionInfo); injectedMembers.SetFunctionIsValid(functionInfo, functionIsValid); injectedMembers.SetFunctionAddress(functionInfo, functionAddressField); injectedMembers.SetFunctionParamsSize(functionInfo, paramsSizeField); // Validate the parameters and add the fields for the parameter offsets / addresses GetParamsFromMethod(type, functionInfo, methods[0], injectedMembers, true); if (functionInfo.IsBlueprintEvent || functionInfo.IsRPC) { bool perInstanceFunctionAddress = functionInfo.IsBlueprintEvent; RewriteMethodAsUFunctionInvoke(type, classInfo, functionInfo, methods[0], injectedMembers, perInstanceFunctionAddress); } else { WriteFunctionInvoker(type, classInfo, functionInfo, methods[0], injectedMembers, false); } AddPathAttribute(methods[0], functionInfo); } } AddPathAttribute(type, classInfo); CreateLoadNativeTypeMethod(type, classInfo, injectedMembers); }
public static FieldSignature GetSignature(this MetadataReader metadataReader, FieldDefinition fieldDefinition) { return(new FieldSignature(metadataReader.GetBlobReader(fieldDefinition.Signature))); }
public bool Process(AssemblyProcessorContext context) { var assembly = context.Assembly; var mscorlibAssembly = CecilExtensions.FindCorlibAssembly(assembly); if (mscorlibAssembly == null) { throw new InvalidOperationException("Missing mscorlib.dll from assembly"); } // For now, use import, but this can cause mixed framework versions when processing an assembly with a different framework version. voidType = assembly.MainModule.TypeSystem.Void; stringType = assembly.MainModule.TypeSystem.String; objectType = assembly.MainModule.TypeSystem.Object; var propertyInfoType = assembly.MainModule.ImportReference(mscorlibAssembly.MainModule.GetTypeResolved(typeof(PropertyInfo).FullName)); var typeType = mscorlibAssembly.MainModule.GetTypeResolved(typeof(Type).FullName); TypeDefinition propertyChangedExtendedEventArgsType; ModuleDefinition strideCoreModule; try { strideCoreModule = assembly.GetStrideCoreModule(); } catch (Exception) { return(true); } propertyChangedExtendedEventArgsType = strideCoreModule.GetTypes().First(x => x.Name == "PropertyChangedExtendedEventArgs").Resolve(); var typeTokenInfoEx = mscorlibAssembly.MainModule.GetTypeResolved("System.Reflection.TypeInfo").Resolve(); var getPropertyMethod = typeTokenInfoEx.Methods.First(x => x.Name == "GetDeclaredProperty" && x.Parameters.Count == 1); var getTypeFromHandleMethod = typeType.Methods.First(x => x.Name == "GetTypeFromHandle"); var getTokenInfoExMethod = CecilExtensions.FindReflectionAssembly(assembly).MainModule.GetTypeResolved("System.Reflection.IntrospectionExtensions").Resolve().Methods.First(x => x.Name == "GetTypeInfo"); var propertyChangedExtendedEventArgsConstructor = assembly.MainModule.ImportReference(propertyChangedExtendedEventArgsType.Methods.First(x => x.IsConstructor)); bool modified = false; foreach (var type in assembly.MainModule.GetTypes()) { MethodReference getPropertyChangedMethod; getPropertyChangedMethod = GetGetPropertyChangedMethod(assembly, type); //var propertyChangedField = GetPropertyChangedField(type); //if (propertyChangedField == null) // continue; var propertyChangedField = GetPropertyChangedField(type); if (getPropertyChangedMethod == null && propertyChangedField == null) { continue; } TypeReference propertyChangedFieldType; if (getPropertyChangedMethod == null) { modified = true; getPropertyChangedMethod = GetOrCreateGetPropertyChangedMethod(assembly, type, propertyChangedField); } if (propertyChangedField != null) { propertyChangedField = assembly.MainModule.ImportReference(propertyChangedField); propertyChangedFieldType = propertyChangedField.FieldType; } else { propertyChangedFieldType = getPropertyChangedMethod.ReturnType; } // Add generic to declaring type if (getPropertyChangedMethod.DeclaringType.HasGenericParameters) { getPropertyChangedMethod = getPropertyChangedMethod.MakeGeneric(getPropertyChangedMethod.DeclaringType.GenericParameters.ToArray()); } var propertyChangedInvoke = assembly.MainModule.ImportReference(propertyChangedFieldType.Resolve().Methods.First(x => x.Name == "Invoke")); foreach (var property in type.Properties) { if (property.SetMethod == null || !property.HasThis) { continue; } MethodReference propertyGetMethod = property.GetMethod; // Only patch properties that have a public Getter var methodDefinition = propertyGetMethod.Resolve(); if ((methodDefinition.Attributes & MethodAttributes.Public) != MethodAttributes.Public) { continue; } // Add generic to declaring type if (propertyGetMethod.DeclaringType.HasGenericParameters) { propertyGetMethod = propertyGetMethod.MakeGeneric(propertyGetMethod.DeclaringType.GenericParameters.ToArray()); } //var versionableAttribute = property.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName == typeof(VersionableAttribute).FullName); //if (versionableAttribute == null) // continue; modified = true; FieldReference staticField = new FieldDefinition(property.Name + "PropertyInfo", FieldAttributes.Static | FieldAttributes.Private | FieldAttributes.InitOnly, propertyInfoType); type.Fields.Add((FieldDefinition)staticField); // Add generic to declaring type if (staticField.DeclaringType.HasGenericParameters) { staticField = staticField.MakeGeneric(staticField.DeclaringType.GenericParameters.ToArray()); } // In static constructor, find PropertyInfo and store it in static field { var staticConstructor = type.GetStaticConstructor(); if (staticConstructor == null) { staticConstructor = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, voidType); staticConstructor.Body.GetILProcessor().Append(Instruction.Create(OpCodes.Ret)); type.Methods.Add(staticConstructor); } VariableReference localTokenEx = null; int localTokenExIndex = 0; for (int i = 0; i < staticConstructor.Body.Variables.Count; i++) { var localVar = staticConstructor.Body.Variables[i]; if (localVar.VariableType.FullName == typeTokenInfoEx.FullName) { localTokenEx = localVar; localTokenExIndex = i; break; } } if (localTokenEx == null) { localTokenEx = new VariableDefinition(assembly.MainModule.ImportReference(typeTokenInfoEx)); staticConstructor.Body.Variables.Add((VariableDefinition)localTokenEx); localTokenExIndex = staticConstructor.Body.Variables.Count - 1; } var ilProcessor = staticConstructor.Body.GetILProcessor(); var returnInstruction = staticConstructor.Body.Instructions.Last(); var newReturnInstruction = Instruction.Create(returnInstruction.OpCode); newReturnInstruction.Operand = returnInstruction.Operand; returnInstruction.OpCode = OpCodes.Nop; returnInstruction.Operand = null; // Find PropertyInfo and store it in static field ilProcessor.Append(Instruction.Create(OpCodes.Ldtoken, type)); ilProcessor.Append(Instruction.Create(OpCodes.Call, assembly.MainModule.ImportReference(getTypeFromHandleMethod))); ilProcessor.Append(Instruction.Create(OpCodes.Call, assembly.MainModule.ImportReference(getTokenInfoExMethod))); ilProcessor.Append(LocationToStloc(ilProcessor, localTokenExIndex)); ilProcessor.Append(ilProcessor.Create(OpCodes.Ldloca_S, (byte)localTokenExIndex)); ilProcessor.Append(Instruction.Create(OpCodes.Ldstr, property.Name)); ilProcessor.Append(Instruction.Create(OpCodes.Call, assembly.MainModule.ImportReference(getPropertyMethod))); ilProcessor.Append(Instruction.Create(OpCodes.Stsfld, staticField)); ilProcessor.Append(newReturnInstruction); } { var ilProcessor = property.SetMethod.Body.GetILProcessor(); var returnInstruction = property.SetMethod.Body.Instructions.Last(); var firstInstruction = property.SetMethod.Body.Instructions[0]; if (property.SetMethod.Body.Instructions[0].OpCode != OpCodes.Nop) { ilProcessor.InsertBefore(property.SetMethod.Body.Instructions[0], Instruction.Create(OpCodes.Nop)); } var newReturnInstruction = Instruction.Create(returnInstruction.OpCode); newReturnInstruction.Operand = returnInstruction.Operand; returnInstruction.OpCode = OpCodes.Nop; returnInstruction.Operand = null; var propertyChangedVariable = new VariableDefinition(assembly.MainModule.ImportReference(propertyChangedFieldType)); property.SetMethod.Body.Variables.Add(propertyChangedVariable); var oldValueVariable = new VariableDefinition(objectType); property.SetMethod.Body.Variables.Add(oldValueVariable); Instruction jump1, jump2; // Prepend: // var propertyChanged = GetPropertyChanged(); // var oldValue = propertyChanged != null ? (object)Property : null; property.SetMethod.Body.SimplifyMacros(); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Ldarg_0)); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Call, getPropertyChangedMethod)); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Stloc, propertyChangedVariable)); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Ldloc, propertyChangedVariable)); ilProcessor.InsertBefore(firstInstruction, jump1 = Instruction.Create(OpCodes.Brtrue, Instruction.Create(OpCodes.Nop))); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Ldnull)); ilProcessor.InsertBefore(firstInstruction, jump2 = Instruction.Create(OpCodes.Br, Instruction.Create(OpCodes.Nop))); ilProcessor.InsertBefore(firstInstruction, (Instruction)(jump1.Operand = Instruction.Create(OpCodes.Ldarg_0))); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Call, propertyGetMethod)); if (property.PropertyType.IsValueType) { ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Box, property.PropertyType)); } ilProcessor.InsertBefore(firstInstruction, (Instruction)(jump2.Operand = Instruction.Create(OpCodes.Nop))); ilProcessor.InsertBefore(firstInstruction, Instruction.Create(OpCodes.Stloc, oldValueVariable)); // Append: // if (propertyChanged != null) // propertyChanged(this, new PropertyChangedExtendedEventArgs("Property", oldValue, Property)); ilProcessor.Append(Instruction.Create(OpCodes.Ldloc, propertyChangedVariable)); ilProcessor.Append(Instruction.Create(OpCodes.Ldnull)); ilProcessor.Append(Instruction.Create(OpCodes.Ceq)); ilProcessor.Append(Instruction.Create(OpCodes.Brtrue, newReturnInstruction)); ilProcessor.Append(Instruction.Create(OpCodes.Ldloc, propertyChangedVariable)); ilProcessor.Append(Instruction.Create(OpCodes.Ldarg_0)); ilProcessor.Append(Instruction.Create(OpCodes.Ldsfld, staticField)); ilProcessor.Append(Instruction.Create(OpCodes.Ldloc, oldValueVariable)); ilProcessor.Append(Instruction.Create(OpCodes.Ldarg_0)); ilProcessor.Append(Instruction.Create(OpCodes.Call, propertyGetMethod)); if (property.PropertyType.IsValueType) { ilProcessor.Append(Instruction.Create(OpCodes.Box, property.PropertyType)); } ilProcessor.Append(Instruction.Create(OpCodes.Newobj, propertyChangedExtendedEventArgsConstructor)); ilProcessor.Append(Instruction.Create(OpCodes.Callvirt, propertyChangedInvoke)); ilProcessor.Append(Instruction.Create(OpCodes.Nop)); ilProcessor.Append(newReturnInstruction); property.SetMethod.Body.OptimizeMacros(); } } } return(modified); }
public static bool HasFlag(this FieldDefinition fieldDefinition, FieldAttributes attribute) => (fieldDefinition.Attributes & attribute) == attribute;
private FieldData(FieldDefinition fieldDefinition, MemberAccessibility accessibility, DeclaringTypeData declaringType) : base(fieldDefinition, accessibility, fieldDefinition.FieldType, fieldDefinition.IsDynamicType(), fieldDefinition.IsStatic ? MemberFlags.Static : MemberFlags.None, declaringType) { this.IsReadOnly = fieldDefinition.IsInitOnly; }