Ejemplo n.º 1
0
        private static FieldDef GetOrCreateDataField(ModuleDef module, byte[] data)
        {
            var privateImplementationDetails = module.FindNormal("<PrivateImplementationDetails>");

            if (privateImplementationDetails is null)
            {
                privateImplementationDetails = new TypeDefUser(UTF8String.Empty, "<PrivateImplementationDetails>", module.CorLibTypes.Object.TypeRef)
                {
                    Attributes = TypeAttributes.NotPublic | TypeAttributes.Sealed
                };
                var compilerGeneratedAttribute = module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "CompilerGeneratedAttribute");
                var ca = new CustomAttribute(new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), compilerGeneratedAttribute));
                privateImplementationDetails.CustomAttributes.Add(ca);
                module.Types.Add(privateImplementationDetails);
            }
            string storageStructName = $"__StaticArrayInitTypeSize={data.Length}";
            var    storageStruct     = privateImplementationDetails.NestedTypes.FirstOrDefault(t => t.Name == storageStructName);

            if (storageStruct is null)
            {
                storageStruct = new TypeDefUser(string.Empty, storageStructName, module.CorLibTypes.GetTypeRef("System", "ValueType"))
                {
                    Attributes  = TypeAttributes.NestedPrivate | TypeAttributes.ExplicitLayout | TypeAttributes.Sealed,
                    ClassLayout = new ClassLayoutUser(1, (uint)data.Length)
                };
                privateImplementationDetails.NestedTypes.Add(storageStruct);
            }
            string dataFieldName;

            using (var sha256 = SHA256.Create())
                dataFieldName = BitConverter.ToString(sha256.ComputeHash(data)).Replace("-", string.Empty);
            var dataField = privateImplementationDetails.FindField(dataFieldName);

            if (!(dataField is null))
            {
                return(dataField);
            }
            dataField = new FieldDefUser(dataFieldName, new FieldSig(storageStruct.ToTypeSig()))
            {
                Attributes   = FieldAttributes.Assembly | FieldAttributes.Static | FieldAttributes.InitOnly | FieldAttributes.HasFieldRVA,
                InitialValue = data
            };
            privateImplementationDetails.Fields.Add(dataField);
            return(dataField);
        }