using System; using System.Buffers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.CodeAnalysis; using ProtoBuf; using ProtoBuf.Compiler; using ProtoBuf.Extensions; using ProtoBuf.Internal; using ProtoBuf.Internal.Serializers; using ProtoBuf.Meta; using ProtoBuf.Serializers; using ProtoBuf.WellKnownTypes; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyFileVersion("3.2.56.57311")] [assembly: AssemblyInformationalVersion("3.2.56+dfdfce61a7")] [assembly: InternalsVisibleTo("protobuf-net.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Marc Gravell")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("See https://github.com/protobuf-net/protobuf-net")] [assembly: AssemblyDescription("Provides simple access to fast and efficient \"Protocol Buffers\" serialization from .NET applications")] [assembly: AssemblyProduct("protobuf-net (netstandard2.1)")] [assembly: AssemblyTitle("protobuf-net")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/protobuf-net/protobuf-net")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("3.0.0.0")] [assembly: TypeForwardedTo(typeof(BclHelpers))] [assembly: TypeForwardedTo(typeof(BufferExtension))] [assembly: TypeForwardedTo(typeof(CompatibilityLevel))] [assembly: TypeForwardedTo(typeof(CompatibilityLevelAttribute))] [assembly: TypeForwardedTo(typeof(DataFormat))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion128))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion128Object))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion32))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion32Object))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion64))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnion64Object))] [assembly: TypeForwardedTo(typeof(DiscriminatedUnionObject))] [assembly: TypeForwardedTo(typeof(Extensible))] [assembly: TypeForwardedTo(typeof(IExtensible))] [assembly: TypeForwardedTo(typeof(IExtension))] [assembly: TypeForwardedTo(typeof(IExtensionResettable))] [assembly: TypeForwardedTo(typeof(IMeasuredProtoOutput<>))] [assembly: TypeForwardedTo(typeof(ImplicitFields))] [assembly: TypeForwardedTo(typeof(IProtoInput<>))] [assembly: TypeForwardedTo(typeof(IProtoOutput<>))] [assembly: TypeForwardedTo(typeof(MeasureState<>))] [assembly: TypeForwardedTo(typeof(MemberSerializationOptions))] [assembly: TypeForwardedTo(typeof(ProtoSyntax))] [assembly: TypeForwardedTo(typeof(TypeFormatEventArgs))] [assembly: TypeForwardedTo(typeof(TypeFormatEventHandler))] [assembly: TypeForwardedTo(typeof(TypeModel))] [assembly: TypeForwardedTo(typeof(PrefixStyle))] [assembly: TypeForwardedTo(typeof(ProtoAfterDeserializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoAfterSerializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoBeforeDeserializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoBeforeSerializationAttribute))] [assembly: TypeForwardedTo(typeof(ProtoContractAttribute))] [assembly: TypeForwardedTo(typeof(ProtoConverterAttribute))] [assembly: TypeForwardedTo(typeof(ProtoEnumAttribute))] [assembly: TypeForwardedTo(typeof(ProtoException))] [assembly: TypeForwardedTo(typeof(ProtoIgnoreAttribute))] [assembly: TypeForwardedTo(typeof(ProtoIncludeAttribute))] [assembly: TypeForwardedTo(typeof(ProtoMapAttribute))] [assembly: TypeForwardedTo(typeof(ProtoMemberAttribute))] [assembly: TypeForwardedTo(typeof(ProtoPartialIgnoreAttribute))] [assembly: TypeForwardedTo(typeof(ProtoPartialMemberAttribute))] [assembly: TypeForwardedTo(typeof(ProtoReader))] [assembly: TypeForwardedTo(typeof(ProtoTypeCode))] [assembly: TypeForwardedTo(typeof(ProtoWriter))] [assembly: TypeForwardedTo(typeof(SerializationContext))] [assembly: TypeForwardedTo(typeof(SubItemToken))] [assembly: TypeForwardedTo(typeof(TimeSpanScale))] [assembly: TypeForwardedTo(typeof(WireType))] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.7.115.8147")] [ExcludeFromCodeCoverage] internal static class ThisAssembly { internal const string AssemblyConfiguration = "Release"; internal const string AssemblyFileVersion = "3.2.56.57311"; internal const string AssemblyInformationalVersion = "3.2.56+dfdfce61a7"; internal const string AssemblyName = "protobuf-net"; internal const string AssemblyTitle = "protobuf-net"; internal const string AssemblyVersion = "3.0.0.0"; internal static readonly DateTime GitCommitAuthorDate = new DateTime(638895502940000000L, DateTimeKind.Utc); internal static readonly DateTime GitCommitDate = new DateTime(638895502940000000L, DateTimeKind.Utc); internal const string GitCommitId = "dfdfce61a739cfd76f05fcdacf8a4b3b9e94e684"; internal const bool IsPrerelease = false; internal const bool IsPublicRelease = true; internal const string PublicKey = "002400000480000094000000060200000024000052534131000400000100010009ed9caa457bfc205716c3d4e8b255a63ddf71c9e53b1b5f574ab6ffdba11e80ab4b50be9c46d43b75206280070ddba67bd4c830f93f0317504a76ba6a48243c36d2590695991164592767a7bbc4453b34694e31e20815a096e4483605139a32a76ec2fef196507487329c12047bf6a68bca8ee9354155f4d01daf6eec5ff6bc"; internal const string PublicKeyToken = "257b51d87d2e4d67"; internal const string RootNamespace = "ProtoBuf"; } namespace ProtoBuf { public static class Serializer { public static class NonGeneric { public static object DeepClone(object instance) { if (instance != null) { return ((TypeModel)RuntimeTypeModel.Default).DeepClone(instance); } return null; } public static void Serialize(Stream dest, object instance) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (instance != null) { State val = State.Create(dest, (TypeModel)(object)RuntimeTypeModel.Default, (object)null); try { ((State)(ref val)).Model.SerializeRootFallback(ref val, instance); } finally { ((State)(ref val)).Dispose(); } } } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, Stream source) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, (object)null, (object)null, -1L); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, Stream source, object instance = null, object userState = null, long length = -1L) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState, length); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, ReadOnlyMemory source, object instance = null, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, ReadOnlySequence source, object instance = null, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState); } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, ReadOnlySpan source, object instance = null, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(type, source, instance, userState); } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public static object Merge(Stream source, object instance) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (instance == null) { throw new ArgumentNullException("instance"); } State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootFallback(instance, instance.GetType()); } finally { ((State)(ref val)).Dispose(); } } public static void SerializeWithLengthPrefix(Stream destination, object instance, PrefixStyle style, int fieldNumber) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (instance == null) { throw new ArgumentNullException("instance"); } ((TypeModel)RuntimeTypeModel.Default).SerializeWithLengthPrefix(destination, instance, instance.GetType(), style, fieldNumber); } public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) value = ((TypeModel)RuntimeTypeModel.Default).DeserializeWithLengthPrefix(source, (object)null, (Type)null, style, 0, resolver); return value != null; } public static bool CanSerialize(Type type) { return ((TypeModel)RuntimeTypeModel.Default).IsDefined(type); } public static void PrepareSerializer([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type) { RuntimeTypeModel.Default[type].CompileInPlace(); } } public static class GlobalOptions { private static ProtoSyntax _defaultSyntax = (ProtoSyntax)1; [Obsolete("Please use RuntimeTypeModel.Default.InferTagFromNameDefault instead (or on a per-model basis)", false)] public static bool InferTagFromName { get { return RuntimeTypeModel.Default.InferTagFromNameDefault; } set { RuntimeTypeModel.Default.InferTagFromNameDefault = value; } } public static ProtoSyntax DefaultSyntax { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return _defaultSyntax; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) if ((int)value <= 1) { _defaultSyntax = value; } else { ThrowHelper.ThrowArgumentOutOfRangeException("DefaultSyntax"); } } } internal static ProtoSyntax Normalize(ProtoSyntax syntax) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if ((int)syntax != 0) { if ((int)syntax == 1) { return syntax; } return DefaultSyntax; } return syntax; } } [Obsolete("Please use ProtoBuf.TypeResolver", true)] public delegate Type TypeResolver(int fieldNumber); private const string ProtoBinaryField = "proto"; public const int ListItemTag = 1; public static string GetProto() { return ((TypeModel)RuntimeTypeModel.Default).GetSchema(typeof(T), (ProtoSyntax)(-1)); } public static string GetProto(ProtoSyntax syntax) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) return ((TypeModel)RuntimeTypeModel.Default).GetSchema(typeof(T), syntax); } public static string GetProto(SchemaGenerationOptions options) { return ((TypeModel)RuntimeTypeModel.Default).GetSchema(options); } public static T DeepClone<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T instance, SerializationContext context) { return ((TypeModel)RuntimeTypeModel.Default).DeepClone(instance, (object)context); } public static T DeepClone<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T instance, object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).DeepClone(instance, userState); } public static MeasureState Measure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(T value, object userState = null, long abortAfter = -1L) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) return ((TypeModel)RuntimeTypeModel.Default).Measure(value, userState, abortAfter); } public static T Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T instance) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootImpl(instance); } finally { ((State)(ref val)).Dispose(); } } public static TTo ChangeType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TFrom, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] TTo>(TFrom instance) { using MemoryStream memoryStream = new MemoryStream(); Serialize(memoryStream, instance); memoryStream.Position = 0L; return Deserialize(memoryStream); } public static void Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(XmlReader reader, T instance) where T : IXmlSerializable { if (reader == null) { throw new ArgumentNullException("reader"); } if (instance == null) { throw new ArgumentNullException("instance"); } byte[] buffer = new byte[4096]; using MemoryStream memoryStream = new MemoryStream(); int depth = reader.Depth; while (reader.Read() && reader.Depth > depth) { if (reader.NodeType == XmlNodeType.Text) { int count; while ((count = reader.ReadContentAsBase64(buffer, 0, 4096)) > 0) { memoryStream.Write(buffer, 0, count); } if (reader.Depth <= depth) { break; } } } memoryStream.Position = 0L; Merge(memoryStream, instance); } public static void Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, T instance) where T : class, ISerializable { Merge(info, new StreamingContext(StreamingContextStates.Persistence), instance); } public static void Merge<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, StreamingContext context, T instance) where T : class, ISerializable { //IL_0096: Unknown result type (might be due to invalid IL or missing references) if (info == null) { throw new ArgumentNullException("info"); } if (instance == null) { throw new ArgumentNullException("instance"); } if (instance.GetType() != typeof(T)) { throw new ArgumentException("Incorrect type", "instance"); } byte[] buffer = (byte[])info.GetValue("proto", typeof(byte[])); using MemoryStream memoryStream = new MemoryStream(buffer); T val = ((TypeModel)RuntimeTypeModel.Default).Deserialize((Stream)memoryStream, instance, context.Context); if (val != instance) { throw new ProtoException("Deserialization changed the instance; cannot succeed."); } } public static void PrepareSerializer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>() { RuntimeTypeModel.Default[typeof(T)].CompileInPlace(); } public static IFormatter CreateFormatter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>() { return ((TypeModel)RuntimeTypeModel.Default).CreateFormatter(typeof(T)); } public static IEnumerable DeserializeItems<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, PrefixStyle style, int fieldNumber) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((TypeModel)RuntimeTypeModel.Default).DeserializeItems(source, style, fieldNumber); } public static T DeserializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, PrefixStyle style) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return DeserializeWithLengthPrefix(source, style, 0); } public static T DeserializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, PrefixStyle style, int fieldNumber) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return (T)((TypeModel)RuntimeTypeModel.Default).DeserializeWithLengthPrefix(source, (object)null, typeof(T), style, fieldNumber); } public static T MergeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T instance, PrefixStyle style) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) return (T)((TypeModel)RuntimeTypeModel.Default).DeserializeWithLengthPrefix(source, (object)instance, typeof(T), style, 0); } public static bool TryReadLengthPrefix(Stream source, PrefixStyle style, out int length) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) int num = default(int); int num2 = default(int); length = ProtoReader.ReadLengthPrefix(source, false, style, ref num, ref num2); return num2 > 0; } public static bool TryReadLengthPrefix(byte[] buffer, int index, int count, PrefixStyle style, out int length) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) using Stream source = new MemoryStream(buffer, index, count); return TryReadLengthPrefix(source, style, out length); } [Obsolete("This API is no longer required and may be removed in a future release")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public static void FlushPool() { } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootImpl(default(T)); } finally { ((State)(ref val)).Dispose(); } } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T value, SerializationContext context, long length = -1L) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)context, length); try { return ((State)(ref val)).DeserializeRootImpl(value); } finally { ((State)(ref val)).Dispose(); } } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream source, T value = default(T), object userState = null, long length = -1L) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, userState, length); try { return ((State)(ref val)).DeserializeRootImpl(value); } finally { ((State)(ref val)).Dispose(); } } public static object Deserialize([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] Type type, Stream source) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(source, (TypeModel)(object)RuntimeTypeModel.Default, (object)null, -1L); try { return ((State)(ref val)).DeserializeRootFallback((object)null, type); } finally { ((State)(ref val)).Dispose(); } } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(ReadOnlyMemory source, T value = default(T), object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(source, value, userState); } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(ReadOnlySequence source, T value = default(T), object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(source, value, userState); } public static T Deserialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(ReadOnlySpan source, T value = default(T), object userState = null) { return ((TypeModel)RuntimeTypeModel.Default).Deserialize(source, value, userState); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance) { Serialize(destination, instance, null); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance, object userState) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(destination, (TypeModel)(object)RuntimeTypeModel.Default, userState); try { TypeModel.SerializeImpl(ref val, instance); } finally { ((State)(ref val)).Dispose(); } } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(IBufferWriter destination, T instance, object userState = null) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) State val = State.Create(destination, (TypeModel)(object)RuntimeTypeModel.Default, userState); try { TypeModel.SerializeImpl(ref val, instance); } finally { ((State)(ref val)).Dispose(); } } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, T instance) where T : class, ISerializable { Serialize(info, new StreamingContext(StreamingContextStates.Persistence), instance); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(SerializationInfo info, StreamingContext context, T instance) where T : class, ISerializable { if (info == null) { throw new ArgumentNullException("info"); } if (instance == null) { throw new ArgumentNullException("instance"); } if (instance.GetType() != typeof(T)) { throw new ArgumentException("Incorrect type", "instance"); } using MemoryStream memoryStream = new MemoryStream(); ((TypeModel)RuntimeTypeModel.Default).Serialize((Stream)memoryStream, instance, context.Context); info.AddValue("proto", memoryStream.ToArray()); } public static void Serialize<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(XmlWriter writer, T instance) where T : IXmlSerializable { if (writer == null) { throw new ArgumentNullException("writer"); } if (instance == null) { throw new ArgumentNullException("instance"); } using MemoryStream memoryStream = new MemoryStream(); Serialize(memoryStream, instance); ArraySegment arraySegment = default(ArraySegment); Helpers.GetBuffer(memoryStream, ref arraySegment); writer.WriteBase64(arraySegment.Array, arraySegment.Offset, arraySegment.Count); } public static void SerializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance, PrefixStyle style) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) SerializeWithLengthPrefix(destination, instance, style, 0); } public static void SerializeWithLengthPrefix<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] T>(Stream destination, T instance, PrefixStyle style, int fieldNumber) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) ((TypeModel)RuntimeTypeModel.Default).SerializeWithLengthPrefix(destination, (object)instance, typeof(T), style, fieldNumber); } } } namespace ProtoBuf.Serializers { internal static class EnumSerializers { internal static object GetSerializer(Type type) { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(GetProvider(type), type); if (!(underlyingProvider is FieldInfo fieldInfo)) { if (underlyingProvider is MethodInfo methodInfo) { return methodInfo.Invoke(null, null); } return null; } return fieldInfo.GetValue(null); } internal static MemberInfo GetProvider(Type type) { if ((object)type == null) { return null; } type = Nullable.GetUnderlyingType(type) ?? type; if (!type.IsEnum) { return null; } string text = Type.GetTypeCode(type) switch { TypeCode.SByte => "CreateSByte", TypeCode.Int16 => "CreateInt16", TypeCode.Int32 => "CreateInt32", TypeCode.Int64 => "CreateInt64", TypeCode.Byte => "CreateByte", TypeCode.UInt16 => "CreateUInt16", TypeCode.UInt32 => "CreateUInt32", TypeCode.UInt64 => "CreateUInt64", _ => null, }; if (text == null) { return null; } return typeof(EnumSerializer).GetMethod(text, BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(type); } } internal static class RepeatedSerializers { [StructLayout(LayoutKind.Auto)] private readonly struct MethodTuple { public string Name => Method.Name; private MethodInfo Method { get; } public int GenericArgCount { get; } public MethodInfo Construct(Type[] targs) { if (GenericArgCount != 0) { return Method.MakeGenericMethod(targs); } return Method; } public MethodTuple(MethodInfo method) { Method = method; GenericArgCount = (method.IsGenericMethodDefinition ? method.GetGenericArguments().Length : 0); } } private sealed class Registration { public bool ExactOnly { get; } public int Priority { get; } private Func Implementation { get; } public MemberInfo Resolve(Type root, Type current) { Type[] arg = (current.IsGenericType ? current.GetGenericArguments() : ((!current.IsArray) ? Type.EmptyTypes : new Type[1] { current.GetElementType() })); return Implementation?.Invoke(root, current, arg); } public Registration(int priority, Func implementation, bool exactOnly) { Priority = priority; Implementation = implementation; ExactOnly = exactOnly; } } private static readonly Hashtable s_providers; private static readonly Hashtable s_methodsPerDeclaringType; private static readonly Hashtable s_knownTypes; private static readonly Registration s_Array; private static readonly Type[] NotSupportedFlavors; private static readonly MethodInfo s_NestedNotSupported; private static readonly MethodInfo s_GeneralNotSupported; internal static MemberInfo Resolve(Type declaringType, string methodName, Type[] targs) { if (targs == null) { targs = Type.EmptyTypes; } MethodTuple[] array = (MethodTuple[])s_methodsPerDeclaringType[declaringType]; if (array == null) { MethodInfo[] methods = declaringType.GetMethods(BindingFlags.Static | BindingFlags.Public); array = Array.ConvertAll(methods, (MethodInfo m) => new MethodTuple(m)); lock (s_methodsPerDeclaringType) { s_methodsPerDeclaringType[declaringType] = array; } } MethodTuple[] array2 = array; for (int num = 0; num < array2.Length; num++) { MethodTuple methodTuple = array2[num]; if (methodTuple.Name == methodName && targs.Length == methodTuple.GenericArgCount) { return methodTuple.Construct(targs); } } return null; } static RepeatedSerializers() { s_methodsPerDeclaringType = new Hashtable(); s_knownTypes = new Hashtable(); s_Array = new Registration(0, (Type root, Type current, Type[] targs) => (!(root == current)) ? null : Resolve(typeof(RepeatedSerializer), "CreateVector", targs), exactOnly: true); NotSupportedFlavors = new Type[7] { typeof(Span<>), typeof(ReadOnlySpan<>), typeof(ReadOnlySequence<>), typeof(ReadOnlyMemory<>), typeof(Memory<>), typeof(ArraySegment<>), typeof(IMemoryOwner<>) }; s_NestedNotSupported = typeof(RepeatedSerializer).GetMethod("CreateNestedDataNotSupported"); s_GeneralNotSupported = typeof(RepeatedSerializer).GetMethod("CreateNotSupported"); s_providers = new Hashtable(); Add(typeof(List<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateList", (root == current) ? targs : new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(ImmutableArray<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableArray", targs)); Add(typeof(ImmutableDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateImmutableDictionary", targs)); Add(typeof(ImmutableSortedDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateImmutableSortedDictionary", targs)); Add(typeof(IImmutableDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateIImmutableDictionary", targs)); Add(typeof(ImmutableList<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableList", targs)); Add(typeof(IImmutableList<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableIList", targs)); Add(typeof(ImmutableHashSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableHashSet", targs)); Add(typeof(ImmutableSortedSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableSortedSet", targs)); Add(typeof(IImmutableSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableISet", targs)); Add(typeof(ImmutableQueue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableQueue", targs)); Add(typeof(IImmutableQueue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableIQueue", targs)); Add(typeof(ImmutableStack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableStack", targs)); Add(typeof(IImmutableStack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateImmutableIStack", targs)); Add(typeof(ConcurrentDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateConcurrentDictionary", new Type[3] { root, targs[0], targs[1] }), exactOnly: false); Add(typeof(ConcurrentBag<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateConcurrentBag", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(ConcurrentQueue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateConcurrentQueue", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(ConcurrentStack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateConcurrentStack", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(IProducerConsumerCollection<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateIProducerConsumerCollection", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(Dictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateDictionary", (root == current) ? targs : new Type[3] { root, targs[0], targs[1] }), exactOnly: false); Add(typeof(IDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateDictionary", new Type[3] { root, targs[0], targs[1] }), exactOnly: false); Add(typeof(IReadOnlyDictionary<, >), (Type root, Type current, Type[] targs) => Resolve(typeof(MapSerializer), "CreateIReadOnlyDictionary", targs)); Add(typeof(Queue<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateQueue", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(Stack<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateStack", new Type[2] { root, targs[0] }), exactOnly: false); Add(typeof(HashSet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateSet", new Type[2] { root, targs[0] })); Add(typeof(ISet<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateSet", new Type[2] { root, targs[0] })); Add(typeof(IEnumerable<>), (Type root, Type current, Type[] targs) => Resolve(typeof(RepeatedSerializer), "CreateEnumerable", new Type[2] { root, targs[0] }), exactOnly: false); } public static void Add(Type type, Func implementation, bool exactOnly = true, Hashtable externalProviders = null) { Hashtable hashtable = ((externalProviders == null) ? s_providers : externalProviders); if ((object)type == null) { ThrowHelper.ThrowArgumentNullException("type"); } lock (hashtable) { Registration value = new Registration(s_providers.Count * ((externalProviders == null) ? 1 : (-1)) + 1, implementation, exactOnly); hashtable.Add(type, value); } lock (s_knownTypes) { s_knownTypes.Clear(); } } internal static RepeatedSerializerStub TryGetRepeatedProvider(Type type, Hashtable externalProvders = null) { if ((object)type == null || type == typeof(string)) { return null; } RepeatedSerializerStub repeatedSerializerStub = (RepeatedSerializerStub)s_knownTypes[type]; if (repeatedSerializerStub == null) { Type genericTypeDefinition; if (!TypeHelper.IsBytesLike(type) && type.IsGenericType && Array.IndexOf(NotSupportedFlavors, genericTypeDefinition = type.GetGenericTypeDefinition()) >= 0) { if (genericTypeDefinition == typeof(Span<>) || genericTypeDefinition == typeof(ReadOnlySpan<>)) { throw new NotSupportedException("Serialization cannot work with [ReadOnly]Span; [ReadOnly]Memory may be enabled later"); } repeatedSerializerStub = NotSupported(s_GeneralNotSupported, type, type.GetGenericArguments()[0]); } else { MemberInfo providerForType = GetProviderForType(type, externalProvders); if ((object)providerForType == null) { repeatedSerializerStub = ((!type.IsArray || !(type != typeof(byte[]))) ? RepeatedSerializerStub.Empty : NotSupported(s_GeneralNotSupported, type, type.GetElementType())); } else { repeatedSerializerStub = RepeatedSerializerStub.Create(type, providerForType); if (TestIfNestedNotSupported(repeatedSerializerStub)) { repeatedSerializerStub = NotSupported(s_NestedNotSupported, repeatedSerializerStub.ForType, repeatedSerializerStub.ItemType); } } } lock (s_knownTypes) { s_knownTypes[type] = repeatedSerializerStub; } } if (!repeatedSerializerStub.IsEmpty) { return repeatedSerializerStub; } return null; } [MethodImpl(MethodImplOptions.NoInlining)] internal static RepeatedSerializerStub NotSupported(MethodInfo kind, Type collectionType, Type itemType) { return RepeatedSerializerStub.Create(collectionType, kind.MakeGenericMethod(collectionType, itemType)); } private static bool TestIfNestedNotSupported(RepeatedSerializerStub repeated) { if ((object)repeated?.ItemType == null) { return false; } if (!repeated.IsMap && (repeated.ItemType == repeated.ForType || TryGetRepeatedProvider(repeated.ItemType) != null)) { return true; } return false; } private static MemberInfo GetProviderForType(Type type, Hashtable externalProviders) { if ((object)type == null) { return null; } if (TypeHelper.IsBytesLike(type)) { return null; } if (type.IsArray) { Type type2 = type.GetElementType().MakeArrayType(); if (!(type2 == type)) { return null; } return s_Array.Resolve(type, type2); } MemberInfo bestMatch = null; int bestMatchPriority = int.MaxValue; bool bestIsAmbiguous = false; Type type3 = type; if (externalProviders != null) { while ((object)type3 != null && type3 != typeof(object)) { if (TryGetExternalProvider(type, type3, bestMatchPriority, out var member, out var priority, externalProviders)) { Consider(member, priority); } type3 = type3.BaseType; } Type[] interfaces = type.GetInterfaces(); foreach (Type current in interfaces) { if (TryGetExternalProvider(type, current, bestMatchPriority, out var member2, out var priority2, externalProviders)) { Consider(member2, priority2); } } } type3 = type; while ((object)type3 != null && type3 != typeof(object)) { if (TryGetProvider(type, type3, bestMatchPriority, out var member3, out var priority3)) { Consider(member3, priority3); } type3 = type3.BaseType; } Type[] interfaces2 = type.GetInterfaces(); foreach (Type current2 in interfaces2) { if (TryGetProvider(type, current2, bestMatchPriority, out var member4, out var priority4)) { Consider(member4, priority4); } } if (!bestIsAmbiguous) { return bestMatch; } return null; void Consider(MemberInfo memberInfo, int num) { if (num < bestMatchPriority) { bestMatch = memberInfo; bestMatchPriority = num; bestIsAmbiguous = false; } else if (num == bestMatchPriority && !object.Equals(bestMatch, memberInfo)) { bestIsAmbiguous = true; } } } private static bool TryGetProvider(Type root, Type current, int bestMatchPriority, out MemberInfo member, out int priority) { Registration registration = (Registration)s_providers[current]; if (registration == null && current.IsGenericType) { registration = (Registration)s_providers[current.GetGenericTypeDefinition()]; } if (registration == null || registration.Priority > bestMatchPriority || (registration.ExactOnly && root != current)) { member = null; priority = 0; return false; } member = registration.Resolve(root, current); priority = registration.Priority; return true; } private static bool TryGetExternalProvider(Type root, Type current, int bestMatchPriority, out MemberInfo member, out int priority, Hashtable externalProviders) { Registration registration = (Registration)externalProviders[current]; if (registration == null && current.IsGenericType) { registration = (Registration)externalProviders[current.GetGenericTypeDefinition()]; } if (registration == null || registration.Priority > bestMatchPriority || (registration.ExactOnly && root != current)) { member = null; priority = 0; return false; } member = registration.Resolve(root, current); priority = registration.Priority; return true; } } internal sealed class RepeatedSerializerStub { internal static readonly RepeatedSerializerStub Empty = new RepeatedSerializerStub(null, null); private object _serializer; public MemberInfo Provider { get; } public bool IsMap { get; } public bool IsEmpty => (object)Provider == null; public object Serializer => _serializer ?? CreateSerializer(); public Type ForType { get; } public Type ItemType { get; } internal bool IsValidProtobufMap(RuntimeTypeModel model, CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!IsMap) { return false; } ResolveMapTypes(out var keyType, out var valueType); if (!IsValidKey(keyType, compatibilityLevel, dataFormat)) { return false; } RepeatedSerializerStub repeatedSerializerStub = ((model == null) ? RepeatedSerializers.TryGetRepeatedProvider(valueType) : model.TryGetRepeatedProvider(valueType, (CompatibilityLevel)0)); if (repeatedSerializerStub != null) { return false; } return true; static bool IsValidKey(Type type, CompatibilityLevel val, DataFormat val2) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Invalid comparison between Unknown and I4 if ((object)type == null) { return false; } if (type.IsEnum) { return true; } if (type == typeof(string)) { return true; } if (!type.IsValueType) { return false; } if ((object)Nullable.GetUnderlyingType(type) != null) { return false; } TypeCode typeCode = Type.GetTypeCode(type); if ((uint)(typeCode - 5) <= 7u) { return true; } if ((int)val >= 300 && type == typeof(Guid) && (int)val2 != 3) { return true; } return false; } } [MethodImpl(MethodImplOptions.NoInlining)] private object CreateSerializer() { try { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(Provider, ForType); object serializer; if (!(underlyingProvider is FieldInfo fieldInfo)) { if (!(underlyingProvider is MethodInfo { IsStatic: not false } methodInfo)) { goto IL_004d; } serializer = methodInfo.Invoke(null, null); } else { if (!fieldInfo.IsStatic) { goto IL_004d; } serializer = fieldInfo.GetValue(null); } goto IL_004f; IL_004d: serializer = null; goto IL_004f; IL_004f: _serializer = serializer; return _serializer; } catch (TargetInvocationException ex) when (ex.InnerException != null) { throw ex.InnerException; } } internal void EmitProvider(CompilerContext ctx) { EmitProvider(ctx.IL); } private void EmitProvider(ILGenerator il) { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(Provider, ForType); RuntimeTypeModel.EmitProvider(underlyingProvider, il); } public static RepeatedSerializerStub Create(Type forType, MemberInfo provider) { if ((object)provider != null) { return new RepeatedSerializerStub(forType, provider); } return Empty; } private RepeatedSerializerStub(Type forType, MemberInfo provider) { ForType = forType; Provider = provider; IsMap = CheckIsMap(provider, out var itemType); ItemType = itemType; } private static bool CheckIsMap(MemberInfo provider, out Type itemType) { Type type = ((provider is MethodInfo methodInfo) ? methodInfo.ReturnType : ((provider is FieldInfo fieldInfo) ? fieldInfo.FieldType : ((provider is PropertyInfo propertyInfo) ? propertyInfo.PropertyType : ((!(provider is Type type2)) ? null : type2)))); Type type3 = type; while ((object)type3 != null && type3 != typeof(object)) { if (type3.IsGenericType) { Type genericTypeDefinition = type3.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(MapSerializer<, , >)) { Type[] genericArguments = type3.GetGenericArguments(); itemType = typeof(KeyValuePair<, >).MakeGenericType(genericArguments[1], genericArguments[2]); return true; } if (genericTypeDefinition == typeof(RepeatedSerializer<, >)) { Type[] genericArguments2 = type3.GetGenericArguments(); itemType = genericArguments2[1]; return false; } } type3 = type3.BaseType; } itemType = null; return false; } internal void ResolveMapTypes(out Type keyType, out Type valueType) { keyType = (valueType = null); if (IsMap) { Type[] genericArguments = ItemType.GetGenericArguments(); keyType = genericArguments[0]; valueType = genericArguments[1]; } } } } namespace ProtoBuf.Meta { internal abstract class AttributeMap { private sealed class ReflectionAttributeMap : AttributeMap { private readonly Attribute attribute; public override object Target => attribute; public override Type AttributeType => attribute.GetType(); public ReflectionAttributeMap(Attribute attribute) { this.attribute = attribute; } public override bool TryGet(string key, bool publicOnly, out object value) { MemberInfo[] instanceFieldsAndProperties = Helpers.GetInstanceFieldsAndProperties(attribute.GetType(), publicOnly); MemberInfo[] array = instanceFieldsAndProperties; foreach (MemberInfo memberInfo in array) { if (string.Equals(memberInfo.Name, key, StringComparison.OrdinalIgnoreCase)) { if (memberInfo is PropertyInfo propertyInfo) { value = propertyInfo.GetValue(attribute, null); return true; } if (memberInfo is FieldInfo fieldInfo) { value = fieldInfo.GetValue(attribute); return true; } throw new NotSupportedException(memberInfo.GetType().Name); } } value = null; return false; } } public abstract Type AttributeType { get; } public abstract object Target { get; } [Obsolete("Please use AttributeType instead")] public new Type GetType() { return AttributeType; } public override string ToString() { return AttributeType?.FullName ?? ""; } public abstract bool TryGet(string key, bool publicOnly, out object value); public bool TryGet(string key, out object value) { return TryGet(key, publicOnly: true, out value); } public static AttributeMap[] Create(Type type, bool inherit) { object[] customAttributes = type.GetCustomAttributes(inherit); AttributeMap[] array = new AttributeMap[customAttributes.Length]; for (int i = 0; i < customAttributes.Length; i++) { array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); } return array; } public static AttributeMap[] Create(MemberInfo member, bool inherit) { object[] customAttributes = member.GetCustomAttributes(inherit); AttributeMap[] array = new AttributeMap[customAttributes.Length]; for (int i = 0; i < customAttributes.Length; i++) { array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); } return array; } public static AttributeMap[] Create(Assembly assembly) { object[] customAttributes = assembly.GetCustomAttributes(inherit: false); AttributeMap[] array = new AttributeMap[customAttributes.Length]; for (int i = 0; i < customAttributes.Length; i++) { array[i] = new ReflectionAttributeMap((Attribute)customAttributes[i]); } return array; } } public sealed class AutoCompileTypeModel : TypeModel { private static readonly Hashtable s_assemblyModels = new Hashtable(); public static TypeModel Instance { get; } = (TypeModel)(object)new AutoCompileTypeModel(); public static TypeModel CreateForAssembly() { return CreateForAssembly(typeof(T).Assembly, null); } public static TypeModel CreateForAssembly(Type type) { if ((object)type == null) { ThrowHelper.ThrowArgumentNullException("type"); } return CreateForAssembly(type.Assembly, null); } public static TypeModel CreateForAssembly(Assembly assembly) { return CreateForAssembly(assembly, null); } public static TypeModel CreateForAssembly(Assembly assembly, RuntimeTypeModel.CompilerOptions options) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown if ((object)assembly == null) { ThrowHelper.ThrowArgumentNullException("assembly"); } if (options == null) { TypeModel val = (TypeModel)s_assemblyModels[assembly]; if (val != null) { return val; } } return CreateForAssemblyImpl(assembly, options); } private AutoCompileTypeModel() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static TypeModel ForAssembly(Type type) { if ((object)type != null) { return CreateForAssembly(type.Assembly, null); } return NullModel.Singleton; } public override string GetSchema(SchemaGenerationOptions options) { return ForAssembly(options.HasTypes ? options.Types.First() : null).GetSchema(options); } protected override ISerializer GetSerializer() { return ForAssembly(typeof(T)).GetSerializerCore((CompatibilityLevel)0); } internal override bool IsKnownType(CompatibilityLevel ambient) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) return ForAssembly(typeof(T)).IsKnownType(ambient); } private static TypeModel CreateForAssemblyImpl(Assembly assembly, RuntimeTypeModel.CompilerOptions options) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if ((object)assembly == null) { throw new ArgumentNullException("assembly"); } lock (assembly) { TypeModel val = (TypeModel)s_assemblyModels[assembly]; if (val != null) { return val; } RuntimeTypeModel runtimeTypeModel = null; Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (!type.IsGenericTypeDefinition && RuntimeTypeModel.IsFullyPublic(type) && type.IsDefined(typeof(ProtoContractAttribute), inherit: true) && (options == null || options.OnIncludeType(type))) { (runtimeTypeModel ?? (runtimeTypeModel = RuntimeTypeModel.Create("CreateForAssemblyImpl"))).Add(type, applyDefaultBehaviour: true); } } if (runtimeTypeModel == null) { throw new InvalidOperationException("No types marked [ProtoContract] found in assembly '" + assembly.GetName().Name + "'"); } TypeModel val2 = runtimeTypeModel.Compile(options); s_assemblyModels[assembly] = val2; return val2; } } } public class CallbackSet { private readonly MetaType metaType; private MethodInfo beforeSerialize; private MethodInfo afterSerialize; private MethodInfo beforeDeserialize; private MethodInfo afterDeserialize; internal unsafe MethodInfo this[CallbackType callbackType] => (int)callbackType switch { 0 => beforeSerialize, 1 => afterSerialize, 2 => beforeDeserialize, 3 => afterDeserialize, _ => throw new ArgumentException("Callback type not supported: " + ((object)(*(CallbackType*)(&callbackType))/*cast due to .constrained prefix*/).ToString(), "callbackType"), }; public MethodInfo BeforeSerialize { get { return beforeSerialize; } set { beforeSerialize = SanityCheckCallback(value); } } public MethodInfo BeforeDeserialize { get { return beforeDeserialize; } set { beforeDeserialize = SanityCheckCallback(value); } } public MethodInfo AfterSerialize { get { return afterSerialize; } set { afterSerialize = SanityCheckCallback(value); } } public MethodInfo AfterDeserialize { get { return afterDeserialize; } set { afterDeserialize = SanityCheckCallback(value); } } public bool NonTrivial { get { if ((object)beforeSerialize == null && (object)beforeDeserialize == null && (object)afterSerialize == null) { return (object)afterDeserialize != null; } return true; } } internal CallbackSet(MetaType metaType) { this.metaType = metaType ?? throw new ArgumentNullException("metaType"); } internal static bool CheckCallbackParameters(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { Type parameterType = parameters[i].ParameterType; if (!(parameterType == typeof(SerializationContext)) && !(parameterType == typeof(Type)) && !(parameterType == typeof(StreamingContext))) { return false; } } return true; } private MethodInfo SanityCheckCallback(MethodInfo callback) { metaType.ThrowIfFrozen(); if ((object)callback == null) { return callback; } if (callback.IsStatic) { throw new ArgumentException("Callbacks cannot be static", "callback"); } if (callback.ReturnType != typeof(void) || !CheckCallbackParameters(callback)) { throw CreateInvalidCallbackSignature(callback); } return callback; } internal static Exception CreateInvalidCallbackSignature(MethodInfo method) { return new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." + method.Name); } } [StructLayout(LayoutKind.Auto)] public readonly struct EnumMember : IEquatable, IComparable { public string Name { get; } public object Value { get; } internal bool HasValue { get { if (Value != null) { return !string.IsNullOrWhiteSpace(Name); } return false; } } public EnumMember(object value, string name) { Name = name; Value = value; } internal int? TryGetInt32() { return TryGetInt32(Value); } internal static int? TryGetInt32(object value) { if (value != null) { Type type = value.GetType(); if (type.IsEnum) { type = Enum.GetUnderlyingType(type); } switch (Type.GetTypeCode(type)) { case TypeCode.SByte: return (sbyte)value; case TypeCode.Int16: return (short)value; case TypeCode.Int32: return (int)value; case TypeCode.Byte: return (byte)value; case TypeCode.UInt16: return (ushort)value; case TypeCode.UInt32: { uint num3 = (uint)value; if (num3 <= int.MaxValue) { return (int)num3; } break; } case TypeCode.UInt64: { ulong num2 = (ulong)value; if (num2 <= int.MaxValue) { return (int)num2; } break; } case TypeCode.Int64: { long num = (long)value; if (num >= int.MinValue && num <= int.MaxValue) { return (int)num; } break; } } } return null; } public EnumMember WithName(string name) { return new EnumMember(Value, name); } public EnumMember WithValue(object value) { return new EnumMember(value, Name); } public EnumMember Normalize(Type type) { return WithValue(Normalize(Value, type)); } public bool Equals(T value) where T : unmanaged { return object.Equals(Normalize(Value, typeof(T)), Normalize(value, typeof(T))); } public override string ToString() { return $"{Name}={Value}"; } public override int GetHashCode() { return (Name?.GetHashCode() ?? 0) ^ (Value?.GetHashCode() ?? 0); } public override bool Equals(object obj) { if (obj is EnumMember other) { return Equals(other); } return false; } public bool Equals(EnumMember other) { if (string.Equals(Name, other.Name)) { return object.Equals(Value, other.Value); } return false; } public static bool operator ==(EnumMember x, EnumMember y) { return x.Equals(y); } public static bool operator !=(EnumMember x, EnumMember y) { return !x.Equals(y); } private static object Normalize(object value, Type type) { return Convert.ChangeType(value, type.IsEnum ? Enum.GetUnderlyingType(type) : type); } public static EnumMember Create(T value) where T : unmanaged { return new EnumMember(value, value.ToString()).Normalize(typeof(T)); } internal void Validate() { if (string.IsNullOrWhiteSpace(Name)) { ThrowHelper.ThrowInvalidOperationException("All enum declarations must have valid names", (Exception)null); } } public int CompareTo(EnumMember other) { int? num = TryGetInt32(); int? num2 = other.TryGetInt32(); if (!num.HasValue && !num2.HasValue) { return 0; } if (!num.HasValue) { return 1; } if (!num2.HasValue) { return -1; } if (num.Value < 0 && num2.Value >= 0) { return 1; } if (num2.Value < 0 && num.Value >= 0) { return -1; } return num.Value.CompareTo(num2.Value); } } public sealed class MetaType : ISerializerProxy { internal sealed class Comparer : IComparer, IComparer { private readonly HashSet _callstack; internal Comparer(HashSet callstack) { _callstack = callstack; } public int Compare(object x, object y) { return Compare(x as MetaType, y as MetaType); } public int Compare(MetaType x, MetaType y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } return string.Compare(x.GetSchemaTypeName(_callstack), y.GetSchemaTypeName(_callstack), StringComparison.Ordinal); } } [Flags] internal enum AttributeFamily { None = 0, ProtoBuf = 1, DataContractSerializer = 2, XmlSerializer = 4, AutoTuple = 8 } private enum TypeOptions : ushort { None = 0, Pending = 1, Frozen = 4, PrivateOnApi = 8, SkipConstructor = 0x10, AutoTuple = 0x40, IgnoreListHandling = 0x80, IsGroup = 0x100, IgnoreUnknownSubTypes = 0x200 } private class ExtraLayerValueMembers : IEnumerable, IEnumerable { private readonly Dictionary _schemaMemberTypeMap = new Dictionary(); private readonly Dictionary _wrappedSchemaMembers = new Dictionary(); public bool IsEmpty() { return _wrappedSchemaMembers.Count == 0; } public NullWrappedValueMemberData Add(string schemaTypeName, ValueMember valueMember) { if (!_schemaMemberTypeMap.ContainsKey(schemaTypeName)) { NullWrappedValueMemberData nullWrappedValueMemberData = new NullWrappedValueMemberData(valueMember, schemaTypeName); _schemaMemberTypeMap[schemaTypeName] = nullWrappedValueMemberData.ItemType; _wrappedSchemaMembers[nullWrappedValueMemberData.WrappedSchemaTypeName] = nullWrappedValueMemberData; return nullWrappedValueMemberData; } Type type = _schemaMemberTypeMap[schemaTypeName]; if (type == valueMember.ItemType) { NullWrappedValueMemberData nullWrappedValueMemberData2 = new NullWrappedValueMemberData(valueMember, schemaTypeName); _wrappedSchemaMembers[nullWrappedValueMemberData2.WrappedSchemaTypeName] = nullWrappedValueMemberData2; return nullWrappedValueMemberData2; } if (string.IsNullOrEmpty(valueMember.Name) || valueMember.Member?.Name == valueMember.Name) { NullWrappedValueMemberData nullWrappedValueMemberData3 = new NullWrappedValueMemberData(valueMember, schemaTypeName, null, hasSchemaTypeNameCollision: true); _wrappedSchemaMembers[nullWrappedValueMemberData3.WrappedSchemaTypeName] = nullWrappedValueMemberData3; return nullWrappedValueMemberData3; } string name = valueMember.Name; if (_schemaMemberTypeMap.ContainsKey(name)) { NullWrappedValueMemberData nullWrappedValueMemberData4 = new NullWrappedValueMemberData(valueMember, schemaTypeName, name, hasSchemaTypeNameCollision: true); _wrappedSchemaMembers[nullWrappedValueMemberData4.WrappedSchemaTypeName] = nullWrappedValueMemberData4; return nullWrappedValueMemberData4; } NullWrappedValueMemberData nullWrappedValueMemberData5 = new NullWrappedValueMemberData(valueMember, schemaTypeName, name); _schemaMemberTypeMap[name] = nullWrappedValueMemberData5.ItemType; _wrappedSchemaMembers[nullWrappedValueMemberData5.WrappedSchemaTypeName] = nullWrappedValueMemberData5; return nullWrappedValueMemberData5; } public IEnumerator GetEnumerator() { return _wrappedSchemaMembers.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private MetaType baseType; private CompatibilityLevel _compatibilityLevel; private List _subTypes; private CallbackSet callbacks; private string name; private string origin; private MethodInfo factory; private readonly RuntimeTypeModel model; private IProtoTypeSerializer _serializer; private Type constructType; internal Type surrogateType; internal DataFormat surrogateDataFormat; private MethodInfo underlyingToSurrogate; private MethodInfo surrogateToUnderlying; private List _fields; private List _enums = new List(); private volatile TypeOptions flags; private Type _serializerType; private List _reservations; IRuntimeProtoSerializerNode ISerializerProxy.Serializer => Serializer; public MetaType BaseType => baseType; internal RuntimeTypeModel Model => model; public CompatibilityLevel CompatibilityLevel { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _compatibilityLevel; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (value != _compatibilityLevel) { if (HasFields) { ThrowHelper.ThrowInvalidOperationException($"{CompatibilityLevel} cannot be set once fields have been defined", (Exception)null); } CompatibilityLevelAttribute.AssertValid(value); _compatibilityLevel = value; } } } public bool IncludeSerializerMethod { get { return !HasFlag(TypeOptions.PrivateOnApi); } set { SetFlag(TypeOptions.PrivateOnApi, !value, throwIfFrozen: true); } } public bool AsReferenceDefault { get { return false; } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] set { if (value != AsReferenceDefault) { ThrowHelper.ThrowNotSupportedException(); } } } public bool HasCallbacks { get { if (callbacks != null) { return callbacks.NonTrivial; } return false; } } public bool HasSubtypes { get { if (_subTypes != null) { return _subTypes.Count != 0; } return false; } } public int SubtypesCount => _subTypes?.Count ?? 0; public CallbackSet Callbacks => callbacks ?? (callbacks = new CallbackSet(this)); private bool IsValueType => Type.IsValueType; public string Name { get { return name; } set { ThrowIfFrozen(); name = value; } } public string Origin { get { return origin; } set { ThrowIfFrozen(); origin = value; } } public Type Type { get; } internal IProtoTypeSerializer Serializer { get { if (_serializer == null) { int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); if (_serializer == null) { SetFlag(TypeOptions.Frozen, value: true, throwIfFrozen: false); _serializer = BuildSerializer(); if (model.AutoCompile) { CompileInPlace(); } } } finally { model.ReleaseLock(opaqueToken); } } return _serializer; } } public bool UseConstructor { get { return !HasFlag(TypeOptions.SkipConstructor); } set { SetFlag(TypeOptions.SkipConstructor, !value, throwIfFrozen: true); } } public Type ConstructType { get { return constructType; } set { ThrowIfFrozen(); constructType = value; } } internal bool HasSurrogate => (object)surrogateType != null; public ValueMember this[int fieldNumber] { get { if (HasFields) { foreach (ValueMember field in Fields) { if (field.FieldNumber == fieldNumber) { return field; } } } return null; } } public ValueMember this[MemberInfo member] { get { if ((object)member == null || !HasFields) { return null; } foreach (ValueMember field in Fields) { if (field.Member == member || field.BackingMember == member) { return field; } } return null; } } internal bool HasFields { get { if (_fields != null) { return _fields.Count != 0; } return false; } } internal List Fields => _fields ?? (_fields = new List()); internal List Enums => _enums ?? (_enums = new List()); internal bool HasEnums { get { if (_enums != null) { return _enums.Count != 0; } return false; } } public bool EnumPassthru { [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", false)] get { return Type.IsEnum; } [Obsolete("Enum value maps have been deprecated and are no longer supported; all enums are now effectively pass-thru; custom maps should be applied via shadow properties; in C#, lambda-based 'switch expressions' make for very convenient shadow properties", true)] set { if (value != EnumPassthru) { ThrowHelper.ThrowNotSupportedException(); } } } public bool IgnoreListHandling { get { return HasFlag(TypeOptions.IgnoreListHandling); } set { SetFlag(TypeOptions.IgnoreListHandling, value, throwIfFrozen: true); model.ResetServiceCache(Type); } } public bool IgnoreUnknownSubTypes { get { return HasFlag(TypeOptions.IgnoreUnknownSubTypes); } set { SetFlag(TypeOptions.IgnoreUnknownSubTypes, value, throwIfFrozen: true); } } internal bool Pending { get { return HasFlag(TypeOptions.Pending); } set { SetFlag(TypeOptions.Pending, value, throwIfFrozen: false); } } public Type SerializerType { get { return _serializerType; } set { if (value != _serializerType) { if (!value.IsClass) { ThrowHelper.ThrowArgumentException("Custom serializer providers must be classes", "SerializerType"); } ThrowIfFrozen(); _serializerType = value; } } } internal bool IsAutoTuple => HasFlag(TypeOptions.AutoTuple); public bool IsGroup { get { return HasFlag(TypeOptions.IsGroup); } set { SetFlag(TypeOptions.IsGroup, value, throwIfFrozen: true); } } internal bool HasReservations => (_reservations?.Count ?? 0) != 0; public override string ToString() { return Type.ToString(); } private bool IsValidSubType(Type subType) { if ((object)subType != null && !subType.IsValueType) { return Type.IsAssignableFrom(subType); } return false; } public MetaType AddSubType(int fieldNumber, Type derivedType) { return AddSubType(fieldNumber, derivedType, (DataFormat)0); } private static void ThrowSubTypeWithSurrogate(Type type) { ThrowHelper.ThrowInvalidOperationException("Types with surrogates cannot be used in inheritance hierarchies: " + TypeHelper.NormalizeName(type), (Exception)null); } public MetaType AddSubType(int fieldNumber, Type derivedType, DataFormat dataFormat) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) if ((object)derivedType == null) { throw new ArgumentNullException("derivedType"); } if (fieldNumber < 1) { throw new ArgumentOutOfRangeException("fieldNumber"); } if ((!Type.IsClass && !Type.IsInterface) || Type.IsSealed) { throw new InvalidOperationException("Sub-types can only be added to non-sealed classes: " + TypeHelper.NormalizeName(Type)); } if (!IsValidSubType(derivedType)) { throw new ArgumentException(TypeHelper.NormalizeName(derivedType) + " is not a valid sub-type of " + TypeHelper.NormalizeName(Type), "derivedType"); } int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); MetaType metaType = model[derivedType]; ThrowIfFrozen(); metaType.ThrowIfFrozen(); if (IsAutoTuple || metaType.IsAutoTuple) { ThrowTupleTypeWithInheritance(derivedType); } if ((object)surrogateType != null) { ThrowSubTypeWithSurrogate(Type); } if ((object)metaType.surrogateType != null) { ThrowSubTypeWithSurrogate(derivedType); } SubType item = new SubType(fieldNumber, metaType, dataFormat); ThrowIfFrozen(); metaType.SetBaseType(this); (_subTypes ?? (_subTypes = new List())).Add(item); return this; } finally { model.ReleaseLock(opaqueToken); } } private static void ThrowTupleTypeWithInheritance(Type type) { ThrowHelper.ThrowInvalidOperationException("Tuple-based types cannot be used in inheritance hierarchies: " + TypeHelper.NormalizeName(type), (Exception)null); } private void SetBaseType(MetaType baseType) { if (baseType == null) { throw new ArgumentNullException("baseType"); } if (this.baseType == baseType) { return; } if (this.baseType != null) { throw new InvalidOperationException("Type '" + this.baseType.Type.FullName + "' can only participate in one inheritance hierarchy"); } for (MetaType metaType = baseType; metaType != null; metaType = metaType.baseType) { if (metaType == this) { throw new InvalidOperationException("Cyclic inheritance of '" + this.baseType.Type.FullName + "' is not allowed"); } } this.baseType = baseType; } public MetaType SetCallbacks(MethodInfo beforeSerialize, MethodInfo afterSerialize, MethodInfo beforeDeserialize, MethodInfo afterDeserialize) { CheckSetCallbacks(); CallbackSet callbackSet = Callbacks; callbackSet.BeforeSerialize = beforeSerialize; callbackSet.AfterSerialize = afterSerialize; callbackSet.BeforeDeserialize = beforeDeserialize; callbackSet.AfterDeserialize = afterDeserialize; return this; } private void CheckSetCallbacks() { ThrowIfFrozen(); ThrowIfAutoTuple(); } public MetaType SetCallbacks(string beforeSerialize, string afterSerialize, string beforeDeserialize, string afterDeserialize) { CheckSetCallbacks(); CallbackSet callbackSet = Callbacks; callbackSet.BeforeSerialize = ResolveMethod(beforeSerialize, instance: true); callbackSet.AfterSerialize = ResolveMethod(afterSerialize, instance: true); callbackSet.BeforeDeserialize = ResolveMethod(beforeDeserialize, instance: true); callbackSet.AfterDeserialize = ResolveMethod(afterDeserialize, instance: true); return this; } public string GetSchemaTypeName() { return GetSchemaTypeName(null); } internal string GetSchemaTypeName(HashSet callstack) { if (callstack == null) { callstack = new HashSet(); } if (!callstack.Add(Type)) { return Type.Name; } try { if ((object)surrogateType != null && !callstack.Contains(surrogateType)) { return model[surrogateType].GetSchemaTypeName(callstack); } if (!string.IsNullOrEmpty(name)) { return name; } string text = Type.Name; if (Type.IsArray) { return GetArrayName(Type.GetElementType()); } if (Type.IsGenericType) { StringBuilder stringBuilder = new StringBuilder(text); int num = text.IndexOf('`'); if (num >= 0) { stringBuilder.Length = num; } Type[] genericArguments = Type.GetGenericArguments(); foreach (Type type in genericArguments) { stringBuilder.Append('_'); Type type2 = type; MetaType metaType; if (((TypeModel)model).IsDefined(type2) && (metaType = model[type2]) != null) { stringBuilder.Append(LastPart(metaType.GetSchemaTypeName(callstack))); continue; } if (type2.IsArray) { stringBuilder.Append(GetArrayName(type2.GetElementType())); continue; } metaType = null; try { metaType = model.Add(type2, applyDefaultBehaviour: true, (CompatibilityLevel)0); } catch { } if (metaType != null) { stringBuilder.Append(metaType.GetSchemaTypeName(callstack)); } else { stringBuilder.Append(type2.Name); } } return stringBuilder.ToString(); } return text; } finally { callstack.Remove(Type); } string GetArrayName(Type elementType) { MetaType metaType2; string text2 = ((((TypeModel)model).IsDefined(elementType) && (metaType2 = model[elementType]) != null) ? metaType2.GetSchemaTypeName(callstack) : elementType.Name); return "Array_" + text2; } static string LastPart(string value) { if (string.IsNullOrWhiteSpace(value)) { return value; } int num2 = value.LastIndexOf('.'); if (num2 >= 0) { return value.Substring(num2 + 1); } return value; } } internal string GuessPackage() { string text = Name; if (string.IsNullOrWhiteSpace(text)) { return null; } if (text[0] != '.') { return null; } return text[..text.LastIndexOf('.')].Trim('.').Trim(); } public MetaType SetFactory(MethodInfo factory) { RuntimeTypeModel.VerifyFactory(factory, Type); ThrowIfFrozen(); ThrowIfAutoTuple(); this.factory = factory; return this; } public MetaType SetFactory(string factory) { return SetFactory(ResolveMethod(factory, instance: false)); } private MethodInfo ResolveMethod(string name, bool instance) { if (string.IsNullOrEmpty(name)) { return null; } if (!instance) { return Helpers.GetStaticMethod(Type, name); } return Helpers.GetInstanceMethod(Type, name); } internal static Exception InbuiltType(Type type, Exception innerException = null) { string message = "Data of this type has inbuilt behaviour, and cannot be added to a model in this way: " + type.FullName; if (innerException != null) { return new ArgumentException(message, innerException); } return new ArgumentException(message); } internal MetaType(RuntimeTypeModel model, Type type, MethodInfo factory) { this.factory = factory; if (model == null) { throw new ArgumentNullException("model"); } if ((object)type == null) { throw new ArgumentNullException("type"); } IRuntimeProtoSerializerNode runtimeProtoSerializerNode = model.TryGetBasicTypeSerializer(type); if (runtimeProtoSerializerNode != null) { throw InbuiltType(type); } Type = type; if (type.IsArray) { SetFlag(TypeOptions.Frozen, value: true, throwIfFrozen: false); } this.model = model; } internal void ThrowIfFrozen() { if ((flags & TypeOptions.Frozen) != TypeOptions.None) { throw new InvalidOperationException("The type cannot be changed once a serializer has been generated for " + Type.FullName); } } internal Type GetInheritanceRoot() { if (Type.IsValueType) { return null; } MetaType rootType = GetRootType(this); if (rootType != this) { return rootType.Type; } if (_subTypes != null && _subTypes.Count != 0) { return rootType.Type; } return null; } private SerializerFeatures GetFeatures() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (Type.IsEnum) { return (SerializerFeatures)48; } if (!Type.IsValueType) { MetaType rootType = GetRootType(this); if (rootType != this) { return rootType.GetFeatures(); } } SerializerFeatures val = (SerializerFeatures)64; return (SerializerFeatures)(val | (IsGroup ? 19 : 18)); } private bool HasRealInheritance() { if (baseType == null || baseType == this) { return (_subTypes?.Count ?? 0) > 0; } return true; } private IProtoTypeSerializer BuildSerializer() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Unknown result type (might be due to invalid IL or missing references) if ((object)SerializerType != null) { return ExternalSerializer.Create(Type, SerializerType); } Validate(); RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(Type, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { if ((object)surrogateType != null) { throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot use a surrogate"); } if (_subTypes != null && _subTypes.Count != 0) { throw new ArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be subclassed"); } ValueMember valueMember = new ValueMember(model, 1, Type, repeatedSerializerStub.ItemType, null, (DataFormat)0) { CompatibilityLevel = CompatibilityLevel }; return TypeSerializer.Create(Type, new int[1] { 1 }, new IRuntimeProtoSerializerNode[1] { valueMember.Serializer }, null, isRootType: true, useConstructor: true, !IgnoreUnknownSubTypes, null, constructType, factory, GetInheritanceRoot(), GetFeatures()); } bool flag = HasRealInheritance(); if ((object)surrogateType != null) { if (flag) { ThrowSubTypeWithSurrogate(Type); } WireType defaultWireType; IRuntimeProtoSerializerNode runtimeProtoSerializerNode = ValueMember.TryGetCoreSerializer(Model, surrogateDataFormat, CompatibilityLevel, surrogateType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); SerializerFeatures features; if (runtimeProtoSerializerNode != null) { try { features = ExternalSerializer.Create(surrogateType, typeof(PrimaryTypeProvider)).Features; } catch (Exception innerException) { throw InbuiltType(surrogateType, innerException); } } else { MetaType metaType = model[surrogateType]; MetaType metaType2; while ((metaType2 = metaType.baseType) != null) { if (metaType.HasRealInheritance()) { ThrowSubTypeWithSurrogate(metaType.Type); } metaType = metaType2; } IProtoTypeSerializer serializer = metaType.Serializer; features = serializer.Features; runtimeProtoSerializerNode = serializer; } return (IProtoTypeSerializer)Activator.CreateInstance(typeof(SurrogateSerializer<>).MakeGenericType(Type), surrogateType, underlyingToSurrogate, surrogateToUnderlying, runtimeProtoSerializerNode, features); } if (IsAutoTuple) { if (flag) { ThrowTupleTypeWithInheritance(Type); } MemberInfo[] mappedMembers; ConstructorInfo constructorInfo = ResolveTupleConstructor(Type, out mappedMembers) ?? throw new InvalidOperationException(); return (IProtoTypeSerializer)Activator.CreateInstance(typeof(TupleSerializer<>).MakeGenericType(Type), model, constructorInfo, mappedMembers, GetFeatures(), CompatibilityLevel); } if (HasFields) { Fields.TrimExcess(); } if (HasEnums) { Enums.TrimExcess(); } int num = _fields?.Count ?? 0; int num2 = _subTypes?.Count ?? 0; int[] array = new int[num + num2]; IRuntimeProtoSerializerNode[] array2 = new IRuntimeProtoSerializerNode[num + num2]; int num3 = 0; if (num2 != 0) { foreach (SubType subType in _subTypes) { if (!subType.DerivedType.IgnoreListHandling && model.TryGetRepeatedProvider(subType.DerivedType.Type, (CompatibilityLevel)0) != null) { ThrowHelper.ThrowArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a subclass"); } array[num3] = subType.FieldNumber; array2[num3++] = subType.GetSerializer(Type); } } if (num != 0) { foreach (ValueMember field in _fields) { array[num3] = field.FieldNumber; array2[num3++] = field.Serializer; } } List list = null; for (MetaType metaType3 = BaseType; metaType3 != null; metaType3 = metaType3.BaseType) { MethodInfo methodInfo = (metaType3.HasCallbacks ? metaType3.Callbacks.BeforeDeserialize : null); if ((object)methodInfo != null) { (list ?? (list = new List())).Add(methodInfo); } } MethodInfo[] array3 = null; if (list != null) { array3 = new MethodInfo[list.Count]; list.CopyTo(array3, 0); Array.Reverse(array3); } return TypeSerializer.Create(Type, array, array2, array3, baseType == null, UseConstructor, !IgnoreUnknownSubTypes, callbacks, constructType, factory, GetInheritanceRoot(), GetFeatures()); } private static Type GetBaseType(MetaType type) { return type.Type.BaseType; } internal static bool GetAsReferenceDefault(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (type.IsEnum) { return false; } AttributeMap[] array = AttributeMap.Create(type, inherit: false); for (int i = 0; i < array.Length; i++) { if (array[i].AttributeType.FullName == "ProtoBuf.ProtoContractAttribute" && array[i].TryGet("AsReferenceDefault", out var value)) { return (bool)value; } } return false; } internal void ApplyDefaultBehaviour(CompatibilityLevel ambient) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) TypeAddedEventArgs args = null; RuntimeTypeModel.OnBeforeApplyDefaultBehaviour(this, ref args); if (args == null || args.ApplyDefaultBehaviour) { ApplyDefaultBehaviourImpl(ambient); } RuntimeTypeModel.OnAfterApplyDefaultBehaviour(this, ref args); } private void ApplyDefaultBehaviourImpl(CompatibilityLevel ambient) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_047d: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_06e5: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_05fd: Unknown result type (might be due to invalid IL or missing references) //IL_05a6: Unknown result type (might be due to invalid IL or missing references) Type type = GetBaseType(this); if ((object)type != null && model.FindWithoutAdd(type) == null && GetContractFamily(model, type, null) != AttributeFamily.None) { model.FindOrAddAuto(type, demand: true, addWithContractOnly: false, addEvenIfAutoDisabled: false, ambient); } AttributeMap[] array = AttributeMap.Create(Type, inherit: false); AttributeFamily attributeFamily = GetContractFamily(model, Type, array); if (attributeFamily == AttributeFamily.AutoTuple) { SetFlag(TypeOptions.AutoTuple, value: true, throwIfFrozen: true); } CompatibilityLevel val = CompatibilityLevel; if ((int)val <= 0) { if (IsAutoTuple) { val = ambient; } if ((int)val <= 0) { val = Model.DefaultCompatibilityLevel; } CompatibilityLevel = TypeCompatibilityHelper.GetTypeCompatibilityLevel(Type, val); } bool isEnum = Type.IsEnum; if (attributeFamily == AttributeFamily.None && !isEnum) { return; } List list = null; List list2 = null; int dataMemberOffset = 0; int num = 1; bool flag = model.InferTagFromNameDefault; ImplicitFields val2 = (ImplicitFields)0; string text = null; string text2 = null; foreach (AttributeMap attributeMap in array) { string fullName = attributeMap.AttributeType.FullName; object value; if (!isEnum && fullName == "ProtoBuf.ProtoIncludeAttribute") { int fieldNumber = 0; if (attributeMap.TryGet("tag", out value)) { fieldNumber = (int)value; } DataFormat dataFormat = (DataFormat)0; if (attributeMap.TryGet("DataFormat", out value)) { dataFormat = (DataFormat)(int)value; } Type type2 = null; try { if (attributeMap.TryGet("knownTypeName", out value)) { type2 = TypeModel.ResolveKnownType((string)value, Type.Assembly); } else if (attributeMap.TryGet("knownType", out value)) { type2 = (Type)value; } } catch (Exception innerException) { throw new InvalidOperationException("Unable to resolve sub-type of: " + Type.FullName, innerException); } if ((object)type2 == null) { throw new InvalidOperationException("Unable to resolve sub-type of: " + Type.FullName); } if (IsValidSubType(type2)) { AddSubType(fieldNumber, type2, dataFormat); } } if (fullName == "ProtoBuf.ProtoPartialIgnoreAttribute" && attributeMap.TryGet("MemberName", out value) && value != null) { (list ?? (list = new List())).Add((string)value); } if (!isEnum && fullName == "ProtoBuf.ProtoPartialMemberAttribute") { (list2 ?? (list2 = new List())).Add(attributeMap); } if (fullName == "ProtoBuf.ProtoContractAttribute") { if (attributeMap.TryGet("Name", out value)) { text = (string)value; } if (attributeMap.TryGet("Origin", out value)) { text2 = (string)value; } if (!Type.IsEnum) { if (attributeMap.TryGet("DataMemberOffset", out value)) { dataMemberOffset = (int)value; } if (attributeMap.TryGet("InferTagFromNameHasValue", publicOnly: false, out value) && (bool)value && attributeMap.TryGet("InferTagFromName", out value)) { flag = (bool)value; } if (attributeMap.TryGet("ImplicitFields", out value) && value != null) { val2 = (ImplicitFields)(int)value; } if (attributeMap.TryGet("SkipConstructor", out value)) { UseConstructor = !(bool)value; } if (attributeMap.TryGet("IgnoreListHandling", out value)) { IgnoreListHandling = (bool)value; } if (attributeMap.TryGet("ImplicitFirstTag", out value) && (int)value > 0) { num = (int)value; } if (attributeMap.TryGet("IsGroup", out value)) { IsGroup = (bool)value; } if (attributeMap.TryGet("IgnoreUnknownSubTypes", out value)) { IgnoreUnknownSubTypes = (bool)value; } if (attributeMap.TryGet("Surrogate", out value)) { SetSurrogate((Type)value); } if (attributeMap.TryGet("Serializer", out value)) { SerializerType = (Type)value; } } } if (fullName == "System.Runtime.Serialization.DataContractAttribute" && text == null && attributeMap.TryGet("Name", out value)) { text = (string)value; } if (fullName == "System.Xml.Serialization.XmlTypeAttribute" && text == null && attributeMap.TryGet("TypeName", out value)) { text = (string)value; } if (fullName == "ProtoBuf.ProtoReservedAttribute") { object target = attributeMap.Target; ProtoReservedAttribute val3 = (ProtoReservedAttribute)((target is ProtoReservedAttribute) ? target : null); if (val3 != null) { AddReservation(val3); } } } if (!string.IsNullOrEmpty(text)) { Name = text; } if (text2 != null) { Origin = text2; } if ((int)val2 != 0) { attributeFamily &= AttributeFamily.ProtoBuf; } MethodInfo[] array2 = null; List list3 = new List(); List list4 = new List(); MemberInfo[] members = Type.GetMembers(isEnum ? (BindingFlags.Static | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); MemberInfo[] array3 = members; foreach (MemberInfo memberInfo in array3) { if (memberInfo.DeclaringType != Type || memberInfo.IsDefined(typeof(ProtoIgnoreAttribute), inherit: true) || (list != null && list.Contains(memberInfo.Name))) { continue; } bool forced = false; if (memberInfo is PropertyInfo propertyInfo) { if (isEnum) { continue; } MemberInfo backingMember = null; if (!propertyInfo.CanWrite) { string text3 = "<" + propertyInfo.Name + ">k__BackingField"; MemberInfo[] array4 = members; foreach (MemberInfo memberInfo2 in array4) { if (memberInfo2 is FieldInfo && memberInfo2.Name == text3) { backingMember = memberInfo2; break; } } } Type effectiveType = propertyInfo.PropertyType; bool isPublic = (object)Helpers.GetGetMethod(propertyInfo, false, false) != null; bool isField = false; ApplyDefaultBehaviour_AddMembers(attributeFamily, isEnum, list2, dataMemberOffset, flag, val2, list3, memberInfo, ref forced, isPublic, isField, ref effectiveType, list4, backingMember); } else if (memberInfo is FieldInfo fieldInfo) { Type effectiveType = fieldInfo.FieldType; bool isPublic = fieldInfo.IsPublic; bool isField = true; if (!isEnum || fieldInfo.IsStatic) { ApplyDefaultBehaviour_AddMembers(attributeFamily, isEnum, list2, dataMemberOffset, flag, val2, list3, memberInfo, ref forced, isPublic, isField, ref effectiveType, list4); } } else if (memberInfo is MethodInfo methodInfo && !isEnum) { AttributeMap[] array5 = AttributeMap.Create(methodInfo, inherit: false); if (array5 != null && array5.Length != 0) { CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoBeforeSerializationAttribute", ref array2, 0); CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoAfterSerializationAttribute", ref array2, 1); CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoBeforeDeserializationAttribute", ref array2, 2); CheckForCallback(methodInfo, array5, "ProtoBuf.ProtoAfterDeserializationAttribute", ref array2, 3); CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnSerializingAttribute", ref array2, 4); CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnSerializedAttribute", ref array2, 5); CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnDeserializingAttribute", ref array2, 6); CheckForCallback(methodInfo, array5, "System.Runtime.Serialization.OnDeserializedAttribute", ref array2, 7); } } } if (flag || (int)val2 != 0) { list3.Sort(); int num2 = num; foreach (ProtoMemberAttribute item in list3) { if (!item.TagIsPinned) { item.Rebase(num2++); } } } foreach (ProtoMemberAttribute item2 in list3) { ValueMember valueMember = ApplyDefaultBehaviour(isEnum, item2); if (valueMember != null) { Add(valueMember); } } foreach (EnumMember item3 in list4) { Enums.Add(item3); } if (array2 != null) { SetCallbacks(Coalesce(array2, 0, 4), Coalesce(array2, 1, 5), Coalesce(array2, 2, 6), Coalesce(array2, 3, 7)); } } internal void Assert(CompatibilityLevel expected) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) CompatibilityLevel compatibilityLevel = CompatibilityLevel; if (compatibilityLevel != expected) { ThrowHelper.ThrowInvalidOperationException($"The expected ('{expected}') and actual ('{compatibilityLevel}') compatibility level of '{TypeHelper.NormalizeName(Type)}' did not match; the same type cannot be used with different compatibility levels in the same model; this is most commonly an issue with tuple-like types in different contexts", (Exception)null); } } private static void ApplyDefaultBehaviour_AddMembers(AttributeFamily family, bool isEnum, List partialMembers, int dataMemberOffset, bool inferTagByName, ImplicitFields implicitMode, List members, MemberInfo member, ref bool forced, bool isPublic, bool isField, ref Type effectiveType, List enumMembers, MemberInfo backingMember = null) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)implicitMode != 1) { if ((int)implicitMode == 2 && isField) { forced = true; } } else if (isPublic) { forced = true; } if (effectiveType.IsSubclassOf(typeof(Delegate))) { effectiveType = null; } if ((object)effectiveType != null) { EnumMember enumMember; ProtoMemberAttribute val = NormalizeProtoMember(member, family, forced, isEnum, partialMembers, dataMemberOffset, inferTagByName, out enumMember, backingMember); if (val != null) { members.Add(val); } if (enumMember.HasValue) { enumMembers.Add(enumMember); } } } private static MethodInfo Coalesce(MethodInfo[] arr, int x, int y) { return arr[x] ?? arr[y]; } internal static AttributeFamily GetContractFamily(RuntimeTypeModel model, Type type, AttributeMap[] attributes) { AttributeFamily attributeFamily = AttributeFamily.None; if (attributes == null) { attributes = AttributeMap.Create(type, inherit: false); } for (int i = 0; i < attributes.Length; i++) { switch (attributes[i].AttributeType.FullName) { case "ProtoBuf.ProtoContractAttribute": { bool value = false; GetFieldBoolean(ref value, attributes[i], "UseProtoMembersOnly"); if (value) { return AttributeFamily.ProtoBuf; } attributeFamily |= AttributeFamily.ProtoBuf; break; } case "System.Xml.Serialization.XmlTypeAttribute": if (!model.AutoAddProtoContractTypesOnly) { attributeFamily |= AttributeFamily.XmlSerializer; } break; case "System.Runtime.Serialization.DataContractAttribute": if (!model.AutoAddProtoContractTypesOnly) { attributeFamily |= AttributeFamily.DataContractSerializer; } break; } } if (attributeFamily == AttributeFamily.None && (object)ResolveTupleConstructor(type, out var _) != null) { attributeFamily |= AttributeFamily.AutoTuple; } return attributeFamily; } internal static ConstructorInfo ResolveTupleConstructor(Type type, out MemberInfo[] mappedMembers) { mappedMembers = null; if ((object)type == null) { throw new ArgumentNullException("type"); } if (type.IsAbstract) { return null; } ConstructorInfo[] constructors = Helpers.GetConstructors(type, false); if (constructors.Length == 0 || (constructors.Length == 1 && constructors[0].GetParameters().Length == 0)) { return null; } MemberInfo[] instanceFieldsAndProperties = Helpers.GetInstanceFieldsAndProperties(type, true); List list = new List(); bool flag = type.Name.IndexOf("Tuple", StringComparison.OrdinalIgnoreCase) < 0; for (int i = 0; i < instanceFieldsAndProperties.Length; i++) { if (instanceFieldsAndProperties[i] is PropertyInfo propertyInfo) { if (!propertyInfo.CanRead) { return null; } if (flag && propertyInfo.CanWrite && IsPublicSetter(Helpers.GetSetMethod(propertyInfo, false, false))) { return null; } list.Add(propertyInfo); } else if (instanceFieldsAndProperties[i] is FieldInfo fieldInfo) { if (flag && !fieldInfo.IsInitOnly) { return null; } list.Add(fieldInfo); } } if (list.Count == 0) { return null; } MemberInfo[] array = new MemberInfo[list.Count]; list.CopyTo(array, 0); int[] array2 = new int[array.Length]; int num = 0; ConstructorInfo result = null; mappedMembers = new MemberInfo[array2.Length]; for (int j = 0; j < constructors.Length; j++) { ParameterInfo[] parameters = constructors[j].GetParameters(); if (parameters.Length != array.Length) { continue; } for (int k = 0; k < array2.Length; k++) { array2[k] = -1; } for (int l = 0; l < parameters.Length; l++) { for (int m = 0; m < array.Length; m++) { if (string.Compare(parameters[l].Name, array[m].Name, StringComparison.OrdinalIgnoreCase) == 0) { Type memberType = Helpers.GetMemberType(array[m]); if (!(memberType != parameters[l].ParameterType)) { array2[l] = m; } } } } bool flag2 = false; for (int n = 0; n < array2.Length; n++) { if (array2[n] < 0) { flag2 = true; break; } mappedMembers[n] = array[array2[n]]; } if (!flag2) { num++; result = constructors[j]; } } if (num != 1) { return null; } return result; static bool IsPublicSetter(MethodInfo method) { if ((object)method == null) { return false; } Type[] array3 = method.ReturnParameter?.GetRequiredCustomModifiers() ?? Type.EmptyTypes; for (int num2 = 0; num2 < array3.Length; num2++) { if (array3[num2]?.FullName == "System.Runtime.CompilerServices.IsExternalInit") { return false; } } return true; } } private static void CheckForCallback(MethodInfo method, AttributeMap[] attributes, string callbackTypeName, ref MethodInfo[] callbacks, int index) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < attributes.Length; i++) { if (attributes[i].AttributeType.FullName == callbackTypeName) { if (callbacks == null) { callbacks = new MethodInfo[8]; } else if ((object)callbacks[index] != null) { Type reflectedType = method.ReflectedType; throw new ProtoException("Duplicate " + callbackTypeName + " callbacks on " + reflectedType.FullName); } callbacks[index] = method; } } } private static bool HasFamily(AttributeFamily value, AttributeFamily required) { return (value & required) == required; } private static ProtoMemberAttribute NormalizeProtoMember(MemberInfo member, AttributeFamily family, bool forced, bool isEnum, List partialMembers, int dataMemberOffset, bool inferByTagName, out EnumMember enumMember, MemberInfo backingMember = null) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_036e: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_037b: Unknown result type (might be due to invalid IL or missing references) //IL_0382: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_03a9: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_03b8: Unknown result type (might be due to invalid IL or missing references) //IL_03c2: Expected O, but got Unknown enumMember = default(EnumMember); if ((object)member == null || (family == AttributeFamily.None && !isEnum)) { return null; } int value = int.MinValue; int num = ((!inferByTagName) ? 1 : (-1)); string text = null; bool value2 = false; bool ignore = false; bool flag = false; bool value3 = false; bool value4 = false; bool value5 = false; bool value6 = false; bool tagIsPinned = false; bool value7 = false; DataFormat value8 = (DataFormat)0; if (isEnum) { forced = true; } AttributeMap[] attribs = AttributeMap.Create(member, inherit: true); if (isEnum) { if (GetAttribute(attribs, "ProtoBuf.ProtoIgnoreAttribute") == null) { AttributeMap attribute = GetAttribute(attribs, "ProtoBuf.ProtoEnumAttribute"); object rawConstantValue = ((FieldInfo)member).GetRawConstantValue(); if (attribute != null) { GetFieldName(ref text, attribute, "Name"); } if (string.IsNullOrWhiteSpace(text)) { text = member.Name; } enumMember = new EnumMember(rawConstantValue, text); } return null; } if (!ignore && !flag) { AttributeMap attribute = GetAttribute(attribs, "ProtoBuf.ProtoMemberAttribute"); GetIgnore(ref ignore, attribute, attribs, "ProtoBuf.ProtoIgnoreAttribute"); if (!ignore && attribute != null) { GetFieldNumber(ref value, attribute, "Tag"); GetFieldName(ref text, attribute, "Name"); GetFieldBoolean(ref value3, attribute, "IsRequired"); GetFieldBoolean(ref value2, attribute, "IsPacked"); GetFieldBoolean(ref value7, attribute, "OverwriteList"); GetDataFormat(ref value8, attribute, "DataFormat"); GetFieldBoolean(ref value5, attribute, "AsReferenceHasValue", publicOnly: false); if (value5) { value5 = GetFieldBoolean(ref value4, attribute, "AsReference", publicOnly: true); } GetFieldBoolean(ref value6, attribute, "DynamicType"); flag = (tagIsPinned = value > 0); } if (!flag && partialMembers != null) { foreach (AttributeMap partialMember in partialMembers) { if (partialMember.TryGet("MemberName", out var value9) && (string)value9 == member.Name) { GetFieldNumber(ref value, partialMember, "Tag"); GetFieldName(ref text, partialMember, "Name"); GetFieldBoolean(ref value3, partialMember, "IsRequired"); GetFieldBoolean(ref value2, partialMember, "IsPacked"); GetFieldBoolean(ref value7, attribute, "OverwriteList"); GetDataFormat(ref value8, partialMember, "DataFormat"); GetFieldBoolean(ref value5, attribute, "AsReferenceHasValue", publicOnly: false); if (value5) { value5 = GetFieldBoolean(ref value4, partialMember, "AsReference", publicOnly: true); } GetFieldBoolean(ref value6, partialMember, "DynamicType"); if (flag = (tagIsPinned = value > 0)) { break; } } } } } if (!ignore && !flag && HasFamily(family, AttributeFamily.DataContractSerializer)) { AttributeMap attribute = GetAttribute(attribs, "System.Runtime.Serialization.DataMemberAttribute"); if (attribute != null) { GetFieldNumber(ref value, attribute, "Order"); GetFieldName(ref text, attribute, "Name"); GetFieldBoolean(ref value3, attribute, "IsRequired"); flag = value >= num; if (flag) { value += dataMemberOffset; } } } if (!ignore && !flag && HasFamily(family, AttributeFamily.XmlSerializer)) { AttributeMap attribute = GetAttribute(attribs, "System.Xml.Serialization.XmlElementAttribute") ?? GetAttribute(attribs, "System.Xml.Serialization.XmlArrayAttribute"); GetIgnore(ref ignore, attribute, attribs, "System.Xml.Serialization.XmlIgnoreAttribute"); if (attribute != null && !ignore) { GetFieldNumber(ref value, attribute, "Order"); GetFieldName(ref text, attribute, "ElementName"); flag = value >= num; } } if (!ignore && !flag && GetAttribute(attribs, "System.NonSerializedAttribute") != null) { ignore = true; } if (ignore || (value < num && !forced)) { return null; } return new ProtoMemberAttribute(value, forced || inferByTagName) { DataFormat = value8, IsPacked = value2, OverwriteList = value7, IsRequired = value3, Name = (string.IsNullOrEmpty(text) ? member.Name : text), Member = member, BackingMember = backingMember, TagIsPinned = tagIsPinned }; } private ValueMember ApplyDefaultBehaviour(bool isEnum, ProtoMemberAttribute normalizedAttribute) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Invalid comparison between Unknown and I4 //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected I4, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Invalid comparison between Unknown and I4 //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Invalid comparison between Unknown and I4 //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Invalid comparison between Unknown and I4 //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_0376: Unknown result type (might be due to invalid IL or missing references) //IL_037b: Unknown result type (might be due to invalid IL or missing references) //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_038f: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_0367: Unknown result type (might be due to invalid IL or missing references) MemberInfo member; if (normalizedAttribute == null || (object)(member = normalizedAttribute.Member) == null) { return null; } Type memberType = Helpers.GetMemberType(member); CompatibilityLevel memberCompatibilityLevel = TypeCompatibilityHelper.GetMemberCompatibilityLevel(member, CompatibilityLevel); RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(memberType, memberCompatibilityLevel); AttributeMap[] attribs = AttributeMap.Create(member, inherit: true); object defaultValue = null; if (model.UseImplicitZeroDefaults) { ProtoTypeCode typeCode = Helpers.GetTypeCode(memberType); if ((int)typeCode <= 100) { switch (typeCode - 3) { default: if ((int)typeCode == 100) { defaultValue = TimeSpan.Zero; } break; case 0: defaultValue = false; break; case 12: defaultValue = 0m; break; case 10: defaultValue = 0f; break; case 11: defaultValue = 0.0; break; case 3: defaultValue = (byte)0; break; case 1: defaultValue = '\0'; break; case 4: defaultValue = (short)0; break; case 6: defaultValue = 0; break; case 8: defaultValue = 0L; break; case 2: defaultValue = (sbyte)0; break; case 5: defaultValue = (ushort)0; break; case 7: defaultValue = 0u; break; case 9: defaultValue = 0uL; break; } } else if ((int)typeCode != 102) { if ((int)typeCode != 108) { if ((int)typeCode == 109) { defaultValue = UIntPtr.Zero; } } else { defaultValue = IntPtr.Zero; } } else { defaultValue = Guid.Empty; } } AttributeMap attribute; if ((attribute = GetAttribute(attribs, "System.ComponentModel.DefaultValueAttribute")) != null && attribute.TryGet("Value", out var value)) { defaultValue = value; } ValueMember valueMember = ((isEnum || normalizedAttribute.Tag > 0) ? new ValueMember(model, Type, normalizedAttribute.Tag, member, memberType, repeatedSerializerStub?.ItemType, null, normalizedAttribute.DataFormat, defaultValue) : null); if (valueMember != null) { valueMember.CompatibilityLevel = memberCompatibilityLevel; valueMember.BackingMember = normalizedAttribute.BackingMember; Type type = Type; PropertyInfo propertyInfo = Helpers.GetProperty(type, member.Name + "Specified", true); MethodInfo getMethod = Helpers.GetGetMethod(propertyInfo, true, true); if ((object)getMethod == null || getMethod.IsStatic) { propertyInfo = null; } if ((object)propertyInfo != null) { valueMember.SetSpecified(getMethod, Helpers.GetSetMethod(propertyInfo, true, true)); } else { MethodInfo instanceMethod = Helpers.GetInstanceMethod(type, "ShouldSerialize" + member.Name, Type.EmptyTypes); if ((object)instanceMethod != null && instanceMethod.ReturnType == typeof(bool)) { valueMember.SetSpecified(instanceMethod, null); } } if (!string.IsNullOrEmpty(normalizedAttribute.Name)) { valueMember.SetName(normalizedAttribute.Name); } valueMember.IsPacked = normalizedAttribute.IsPacked; valueMember.IsRequired = normalizedAttribute.IsRequired; valueMember.OverwriteList = normalizedAttribute.OverwriteList; if (repeatedSerializerStub != null) { DataFormat val = (DataFormat)0; DataFormat mapValueFormat = (DataFormat)0; bool flag = true; if ((attribute = GetAttribute(attribs, "ProtoBuf.ProtoMapAttribute")) != null) { if (attribute.TryGet("DisableMap", out var value2) && (bool)value2) { flag = false; } else { if (attribute.TryGet("KeyFormat", out value2)) { val = (DataFormat)value2; } if (attribute.TryGet("ValueFormat", out value2)) { mapValueFormat = (DataFormat)value2; } } } if (flag && repeatedSerializerStub.IsValidProtobufMap(model, valueMember.CompatibilityLevel, val)) { valueMember.MapKeyFormat = val; valueMember.MapValueFormat = mapValueFormat; valueMember.IsMap = true; } } if ((attribute = GetAttribute(attribs, typeof(NullWrappedValueAttribute).FullName)) != null) { valueMember.NullWrappedValue = true; if (attribute.TryGet("AsGroup", out var value3) && value3 is bool nullWrappedValueGroup) { valueMember.NullWrappedValueGroup = nullWrappedValueGroup; } } if ((attribute = GetAttribute(attribs, typeof(NullWrappedCollectionAttribute).FullName)) != null) { valueMember.NullWrappedCollection = true; if (attribute.TryGet("AsGroup", out var value4) && value4 is bool nullWrappedCollectionGroup) { valueMember.NullWrappedCollectionGroup = nullWrappedCollectionGroup; } } } return valueMember; } private static void GetDataFormat(ref DataFormat value, AttributeMap attrib, string memberName) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown if (attrib != null && (int)value == 0 && attrib.TryGet(memberName, out var value2) && value2 != null) { value = (DataFormat)(int)(DataFormat)value2; } } private static void GetIgnore(ref bool ignore, AttributeMap attrib, AttributeMap[] attribs, string fullName) { if (!ignore && attrib != null) { ignore = GetAttribute(attribs, fullName) != null; } } private static void GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName) { GetFieldBoolean(ref value, attrib, memberName, publicOnly: true); } private static bool GetFieldBoolean(ref bool value, AttributeMap attrib, string memberName, bool publicOnly) { if (attrib == null) { return false; } if (value) { return true; } if (attrib.TryGet(memberName, publicOnly, out var value2) && value2 != null) { value = (bool)value2; return true; } return false; } private static void GetFieldNumber(ref int value, AttributeMap attrib, string memberName) { if (attrib != null && value <= 0 && attrib.TryGet(memberName, out var value2) && value2 != null) { value = (int)value2; } } private static void GetFieldName(ref string name, AttributeMap attrib, string memberName) { if (attrib != null && string.IsNullOrEmpty(name) && attrib.TryGet(memberName, out var value) && value != null) { name = (string)value; } } private static AttributeMap GetAttribute(AttributeMap[] attribs, string fullName) { foreach (AttributeMap attributeMap in attribs) { if (attributeMap != null && attributeMap.AttributeType.FullName == fullName) { return attributeMap; } } return null; } public MetaType Add(int fieldNumber, string memberName) { AddField(fieldNumber, memberName, null, null, null); return this; } public ValueMember AddField(int fieldNumber, string memberName) { return AddField(fieldNumber, memberName, null, null, null); } public MetaType Add(string memberName) { Add(GetNextFieldNumber(), memberName); return this; } public void SetSurrogate(Type surrogateType) { SetSurrogate(surrogateType, null, null, (DataFormat)0); } internal void SetSurrogate(Type surrogateType, MethodInfo underlyingToSurrogate, MethodInfo surrogateToUnderlying, DataFormat dataFormat) { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) if (surrogateType == Type) { surrogateType = null; } if ((object)surrogateType != null) { if (surrogateType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(surrogateType)) { ThrowHelper.ThrowArgumentException("Repeated data (a list, collection, etc) has inbuilt behaviour and cannot be used as a surrogate"); } if ((BaseType != null && BaseType != this) || (_subTypes?.Count ?? 0) > 0) { ThrowSubTypeWithSurrogate(Type); } if (surrogateType.IsGenericTypeDefinition) { if (!Type.IsGenericType) { ThrowHelper.ThrowArgumentException("Cannot use an open generic type as a surrogate for a non generic type"); } Type[] genericArguments = Type.GetGenericArguments(); if (genericArguments.Length != surrogateType.GetGenericArguments().Length) { ThrowHelper.ThrowArgumentException("The generic type parameters of the surrogate must match the generic arguments of the target type"); } surrogateType = surrogateType.MakeGenericType(genericArguments); } } int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); ThrowIfFrozen(); this.surrogateType = surrogateType; this.underlyingToSurrogate = underlyingToSurrogate; this.surrogateToUnderlying = surrogateToUnderlying; surrogateDataFormat = dataFormat; SetFlag(TypeOptions.AutoTuple, value: false, throwIfFrozen: false); } finally { model.ReleaseLock(opaqueToken); } } internal MetaType GetSurrogateOrSelf() { if ((object)surrogateType != null) { return model[surrogateType]; } return this; } internal MetaType GetSurrogateOrBaseOrSelf(bool deep) { if ((object)surrogateType != null) { return model[surrogateType]; } MetaType metaType = baseType; if (metaType != null) { if (deep) { MetaType result; do { result = metaType; metaType = metaType.baseType; } while (metaType != null); return result; } return metaType; } return this; } private int GetNextFieldNumber() { int num = 0; if (HasFields) { foreach (ValueMember field in Fields) { if (field.FieldNumber > num) { num = field.FieldNumber; } } } if (_subTypes != null) { foreach (SubType subType in _subTypes) { if (subType.FieldNumber > num) { num = subType.FieldNumber; } } } return num + 1; } public MetaType Add(params string[] memberNames) { if (memberNames == null) { throw new ArgumentNullException("memberNames"); } int nextFieldNumber = GetNextFieldNumber(); for (int i = 0; i < memberNames.Length; i++) { Add(nextFieldNumber++, memberNames[i]); } return this; } public MetaType Add(int fieldNumber, string memberName, object defaultValue) { AddField(fieldNumber, memberName, null, null, defaultValue); return this; } public MetaType Add(int fieldNumber, string memberName, Type itemType, Type defaultType) { AddField(fieldNumber, memberName, itemType, defaultType, null); return this; } public ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType) { return AddField(fieldNumber, memberName, itemType, defaultType, null); } private void ThrowIfAutoTuple() { if (IsAutoTuple) { Throw(); } static void Throw() { throw new InvalidOperationException("This operation is not supported for tuple-like types; to disable tuple-like type discovery, use applyDefaultBehaviour: false when first adding the type to the model."); } } private ValueMember AddField(int fieldNumber, string memberName, Type itemType, Type defaultType, object defaultValue) { //IL_01ab: Unknown result type (might be due to invalid IL or missing references) MemberInfo memberInfo = null; MemberInfo[] member = Type.GetMember(memberName, Type.IsEnum ? (BindingFlags.Static | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); if (member != null && member.Length == 1) { memberInfo = member[0]; } if ((object)memberInfo == null) { throw new ArgumentException("Unable to determine member: " + memberName, "memberName"); } ThrowIfAutoTuple(); PropertyInfo propertyInfo = null; Type type; switch (memberInfo.MemberType) { case MemberTypes.Field: { FieldInfo fieldInfo = (FieldInfo)memberInfo; type = fieldInfo.FieldType; break; } case MemberTypes.Property: propertyInfo = (PropertyInfo)memberInfo; type = propertyInfo.PropertyType; break; default: throw new NotSupportedException(memberInfo.MemberType.ToString()); } RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(type, (CompatibilityLevel)0); if ((object)itemType != null && repeatedSerializerStub?.ItemType != itemType) { ThrowHelper.ThrowInvalidOperationException("Expected item type of " + ((repeatedSerializerStub != null) ? TypeHelper.NormalizeName(repeatedSerializerStub.ItemType) : null), (Exception)null); } MemberInfo memberInfo2 = null; if ((object)propertyInfo != null && !propertyInfo.CanWrite) { MemberInfo[] member2 = Type.GetMember("<" + ((PropertyInfo)memberInfo).Name + ">k__BackingField", Type.IsEnum ? (BindingFlags.Static | BindingFlags.Public) : (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); if (member2 != null && member2.Length == 1 && member2[0] is FieldInfo) { memberInfo2 = member2[0]; } } if (repeatedSerializerStub != null) { if ((object)defaultType != null && defaultType != repeatedSerializerStub.ForType) { ThrowHelper.ThrowNotSupportedException("Default types for collections are not currently supported; recommendation: initialize the colleciton in the type"); } defaultType = repeatedSerializerStub.ForType; } ValueMember valueMember = new ValueMember(model, Type, fieldNumber, memberInfo2 ?? memberInfo, type, repeatedSerializerStub?.ItemType, defaultType, (DataFormat)0, defaultValue) { CompatibilityLevel = CompatibilityLevel }; if ((object)memberInfo2 != null) { valueMember.SetName(memberInfo.Name); } Add(valueMember); return valueMember; } private void Add(ValueMember member) { if (Type.IsEnum) { ThrowHelper.ThrowInvalidOperationException("Enums should use SetEnumValues to customize the enum definitions", (Exception)null); } int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); ThrowIfFrozen(); Fields.Add(member); } finally { model.ReleaseLock(opaqueToken); } } public ValueMember[] GetFields() { if (!HasFields) { return Array.Empty(); } ValueMember[] array = Fields.ToArray(); Array.Sort(array, ValueMember.Comparer.Default); return array; } public EnumMember[] GetEnumValues() { if (!HasEnums) { return Array.Empty(); } EnumMember[] array = Enums.ToArray(); Array.Sort(array); return array; } public void SetEnumValues(EnumMember[] values) { if (!Type.IsEnum) { ThrowHelper.ThrowInvalidOperationException("Only enums should use SetEnumValues", (Exception)null); } if (values == null) { ThrowHelper.ThrowArgumentNullException("values"); } EnumMember[] collection = Array.ConvertAll(values, (EnumMember val) => val.Normalize(Type)); foreach (EnumMember enumMember in values) { enumMember.Validate(); } int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); ThrowIfFrozen(); Enums.Clear(); Enums.AddRange(collection); } finally { model.ReleaseLock(opaqueToken); } } internal bool IsValidEnum() { return IsValidEnum(_enums); } internal static bool IsValidEnum(IList values) { if (values == null || values.Count == 0) { return false; } foreach (EnumMember value in values) { if (!value.TryGetInt32().HasValue) { return false; } } return true; } public SubType[] GetSubtypes() { if (_subTypes == null || _subTypes.Count == 0) { return Array.Empty(); } SubType[] array = _subTypes.ToArray(); Array.Sort(array, SubType.Comparer.Default); return array; } internal IEnumerable GetAllGenericArguments() { return GetAllGenericArguments(Type); } private static IEnumerable GetAllGenericArguments(Type type) { Type[] genericArguments = type.GetGenericArguments(); Type[] array = genericArguments; foreach (Type arg in array) { yield return arg; foreach (Type allGenericArgument in GetAllGenericArguments(arg)) { yield return allGenericArgument; } } } public void CompileInPlace() { IProtoTypeSerializer serializer = Serializer; if (!(serializer is ICompiledSerializer) && !serializer.ExpectedType.IsEnum && model.TryGetRepeatedProvider(Type, (CompatibilityLevel)0) == null) { ICompiledSerializer compiledSerializer = CompiledSerializer.Wrap(serializer, model); if (serializer != compiledSerializer) { _serializer = (IProtoTypeSerializer)compiledSerializer; Model.ResetServiceCache(Type); } } } internal bool IsDefined(int fieldNumber) { if (HasFields) { foreach (ValueMember field in Fields) { if (field.FieldNumber == fieldNumber) { return true; } } } return false; } private bool HasFlag(TypeOptions flag) { return (flags & flag) == flag; } private void SetFlag(TypeOptions flag, bool value, bool throwIfFrozen) { if (throwIfFrozen && HasFlag(flag) != value) { ThrowIfFrozen(); } if (value) { flags |= flag; } else { flags &= (TypeOptions)(ushort)(~(int)flag); } } internal static MetaType GetRootType(MetaType source) { while (source._serializer != null) { MetaType metaType = source.baseType; if (metaType == null) { return source; } source = metaType; } RuntimeTypeModel runtimeTypeModel = source.model; int opaqueToken = 0; try { runtimeTypeModel.TakeLock(ref opaqueToken); MetaType metaType2; while ((metaType2 = source.baseType) != null) { source = metaType2; } return source; } finally { runtimeTypeModel.ReleaseLock(opaqueToken); } } internal bool IsPrepared() { return _serializer is CompiledSerializer; } internal static StringBuilder NewLine(StringBuilder builder, int indent) { return builder.AppendLine().Append(' ', indent * 3); } internal void WriteSchema(HashSet callstack, StringBuilder builder, int indent, HashSet imports, ProtoSyntax syntax, string package, SchemaGenerationFlags flags) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_071d: Unknown result type (might be due to invalid IL or missing references) //IL_0723: Unknown result type (might be due to invalid IL or missing references) //IL_0747: Unknown result type (might be due to invalid IL or missing references) //IL_074d: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_09ae: Unknown result type (might be due to invalid IL or missing references) //IL_09b1: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_04c6: Invalid comparison between Unknown and I4 if ((object)surrogateType != null) { return; } bool multipleNamespaceSupport = (flags & 1) > 0; bool flag = (flags & 4) > 0; RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(Type, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName(callstack)).Append(" {"); if (repeatedSerializerStub.IsValidProtobufMap(model, CompatibilityLevel, (DataFormat)0)) { repeatedSerializerStub.ResolveMapTypes(out var keyType, out var valueType); NewLine(builder, indent + 1).Append("map<").Append(model.GetSchemaTypeName(callstack, keyType, (DataFormat)0, CompatibilityLevel, asReference: false, dynamicType: false, imports)).Append(", ") .Append(model.GetSchemaTypeName(callstack, valueType, (DataFormat)0, CompatibilityLevel, asReference: false, dynamicType: false, imports)) .Append("> items = 1;"); } else { NewLine(builder, indent + 1).Append("repeated ").Append(model.GetSchemaTypeName(callstack, repeatedSerializerStub.ItemType, (DataFormat)0, CompatibilityLevel, asReference: false, dynamicType: false, imports)).Append(" items = 1;"); } NewLine(builder, indent).Append('}'); return; } if (IsAutoTuple) { if ((object)ResolveTupleConstructor(Type, out var mappedMembers) == null) { return; } NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName(callstack)).Append(" {"); AddNamespace(imports); for (int i = 0; i < mappedMembers.Length; i++) { Type effectiveType; if (mappedMembers[i] is PropertyInfo propertyInfo) { effectiveType = propertyInfo.PropertyType; } else { if (!(mappedMembers[i] is FieldInfo fieldInfo)) { throw new NotSupportedException("Unknown member type: " + mappedMembers[i].GetType().Name); } effectiveType = fieldInfo.FieldType; } NewLine(builder, indent + 1).Append(((int)syntax == 0) ? "optional " : "").Append(model.GetSchemaTypeName(callstack, effectiveType, (DataFormat)0, CompatibilityLevel, asReference: false, dynamicType: false, imports)).Append(' ') .Append(mappedMembers[i].Name) .Append(" = ") .Append(i + 1) .Append(';'); } NewLine(builder, indent).Append('}'); return; } if (Type.IsEnum) { EnumMember[] enumValues = GetEnumValues(); string value = (flag ? (GetSchemaTypeName(callstack) + "_") : ""); bool flag2 = IsValidEnum(enumValues); if (!flag2) { NewLine(builder, indent).Append("/* for context only"); } NewLine(builder, indent).Append("enum ").Append(GetSchemaTypeName(callstack)).Append(" {"); AddNamespace(imports); if (Type.IsDefined(typeof(FlagsAttribute), inherit: true)) { NewLine(builder, indent + 1).Append("// this is a composite/flags enumeration"); } bool flag3 = false; HashSet hashSet = new HashSet(); EnumMember[] array = enumValues; foreach (EnumMember enumMember in array) { int? num = enumMember.TryGetInt32(); if (num.HasValue && !hashSet.Add(num.Value)) { flag3 = true; break; } } if (flag3) { NewLine(builder, indent + 1).Append("option allow_alias = true;"); } bool flag4 = false; EnumMember[] array2 = enumValues; for (int k = 0; k < array2.Length; k++) { EnumMember enumMember2 = array2[k]; int? num2 = enumMember2.TryGetInt32(); if (num2.HasValue && num2.Value == 0) { NewLine(builder, indent + 1).Append(value).Append(enumMember2.Name).Append(" = 0;"); flag4 = true; } } if ((int)syntax == 1 && !flag4) { NewLine(builder, indent + 1).Append(value).Append("ZERO").Append(" = 0;") .Append(" // proto3 requires a zero value as the first item (it can be named anything)"); } EnumMember[] array3 = enumValues; for (int l = 0; l < array3.Length; l++) { EnumMember enumMember3 = array3[l]; int? num3 = enumMember3.TryGetInt32(); if (num3.HasValue) { if (num3.Value != 0) { NewLine(builder, indent + 1).Append(value).Append(enumMember3.Name).Append(" = ") .Append(num3.Value) .Append(';'); } } else { NewLine(builder, indent + 1).Append("// ").Append(value).Append(enumMember3.Name) .Append(" = ") .Append(enumMember3.Value) .Append(';') .Append(" // note: enums should be valid 32-bit integers"); } } if (HasReservations) { AppendReservations(); } NewLine(builder, indent).Append('}'); if (!flag2) { NewLine(builder, indent).Append("*/"); } return; } ExtraLayerValueMembers extraLayerValueMembers = new ExtraLayerValueMembers(); ValueMember[] fields = GetFields(); int length = builder.Length; NewLine(builder, indent).Append("message ").Append(GetSchemaTypeName(callstack)).Append(" {"); AddNamespace(imports); ValueMember[] array4 = fields; foreach (ValueMember member in array4) { bool hasOption = false; string schemaTypeName2; string altName; if (member.IsMap) { if (member.NullWrappedCollection || member.NullWrappedValue) { throw new NotSupportedException("Schema generation for null-wrapped maps and maps with null-wrapped values is not currently implemented; poke @mgravell with a big stick if you need this!"); } repeatedSerializerStub = model.TryGetRepeatedProvider(member.MemberType, (CompatibilityLevel)0); repeatedSerializerStub.ResolveMapTypes(out var keyType2, out var valueType2); string schemaTypeName = model.GetSchemaTypeName(callstack, keyType2, member.MapKeyFormat, CompatibilityLevel, asReference: false, dynamicType: false, imports); schemaTypeName2 = model.GetSchemaTypeName(callstack, valueType2, member.MapValueFormat, CompatibilityLevel, member.AsReference, member.DynamicType, imports); NewLine(builder, indent + 1).Append("map<").Append(schemaTypeName).Append(',') .Append(schemaTypeName2) .Append("> ") .Append(member.Name) .Append(" = ") .Append(member.FieldNumber) .Append(';'); } else if (member.RequiresExtraLayerInSchema()) { schemaTypeName2 = member.GetSchemaTypeName(callstack, applyNetObjectProxy: true, imports, out altName); NullWrappedValueMemberData nullWrappedValueMemberData = extraLayerValueMembers.Add(schemaTypeName2, member); WriteValueMember(nullWrappedValueMemberData.WrappedSchemaTypeName, nullWrappedValueMemberData.HasGroupModifier); } else { bool considerWrappersProtoTypes = member.HasExtendedNullSupport(); schemaTypeName2 = member.GetSchemaTypeName(callstack, applyNetObjectProxy: true, imports, out altName, considerWrappersProtoTypes); WriteValueMember(schemaTypeName2, member.RequiresGroupModifier); } if (schemaTypeName2 == ".bcl.NetObjectProxy" && member.AsReference && !member.DynamicType) { builder.Append(" // reference-tracked ").Append(member.GetSchemaTypeName(callstack, applyNetObjectProxy: false, imports, out var _)); } void WriteValueMember(string schemaModelTypeName, bool hasGroupModifier = false) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Invalid comparison between Unknown and I4 //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_03bf: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) if (member.NullWrappedCollection) { throw new NotSupportedException("Schema generation for null-wrapped collections is not currently implemented; poke @mgravell with a big stick if you need this!"); } string value3 = (((object)member.ItemType != null) ? "repeated " : (((int)syntax != 0) ? "" : (member.IsRequired ? "required " : "optional "))); NewLine(builder, indent + 1).Append(value3); if (hasGroupModifier) { builder.Append("group "); } else if ((int)member.DataFormat == 4) { builder.Append("group "); } builder.Append(schemaModelTypeName).Append(' ').Append(member.Name) .Append(" = ") .Append(member.FieldNumber); if ((int)syntax == 0 && member.DefaultValue != null && !member.IsRequired) { if (member.DefaultValue is string) { AddOption(builder, ref hasOption).Append("default = \"").Append(member.DefaultValue).Append('"'); } else if (!(member.DefaultValue is TimeSpan)) { if (member.DefaultValue is bool flag5) { AddOption(builder, ref hasOption).Append(flag5 ? "default = true" : "default = false"); } else { object defaultValue = member.DefaultValue; if (defaultValue is Enum && defaultValue.GetType() == member.MemberType && ((TypeModel)model).IsDefined(member.MemberType, member.CompatibilityLevel)) { MetaType metaType = model[member.MemberType]; foreach (EnumMember @enum in metaType.Enums) { if (!string.IsNullOrWhiteSpace(@enum.Name) && defaultValue.Equals(@enum.Value)) { defaultValue = @enum.Name; break; } } } AddOption(builder, ref hasOption).Append("default = ").Append(member.DefaultValue); } } } if (CanPack(member.ItemType)) { if ((int)syntax == 0) { if (member.IsPacked) { AddOption(builder, ref hasOption).Append("packed = true"); } } else if (!member.IsPacked) { AddOption(builder, ref hasOption).Append("packed = false"); } } if (member.AsReference) { imports.Add("protobuf-net/protogen.proto"); AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).asRef = true"); } if (member.DynamicType) { imports.Add("protobuf-net/protogen.proto"); AddOption(builder, ref hasOption).Append("(.protobuf_net.fieldopt).dynamicType = true"); } CloseOption(builder, ref hasOption).Append(';'); if ((int)syntax != 0 && member.DefaultValue != null && !member.IsRequired && !IsImplicitDefault(member.DefaultValue)) { builder.Append(" // default value could not be applied: ").Append(member.DefaultValue); } if (!string.IsNullOrWhiteSpace(altName)) { builder.Append(" // declared as invalid enum: ").Append(altName); } } } if (_subTypes != null && _subTypes.Count != 0) { SubType[] array5 = _subTypes.ToArray(); Array.Sort(array5, SubType.Comparer.Default); string[] array6 = new string[array5.Length]; for (int n = 0; n < array5.Length; n++) { array6[n] = array5[n].DerivedType.GetSchemaTypeName(callstack); } string text = "subtype"; while (Array.IndexOf(array6, text) >= 0) { text = "_" + text; } NewLine(builder, indent + 1).Append("oneof ").Append(text).Append(" {"); if ((flags & 2) != 0) { imports.Add("protobuf-net/protogen.proto"); NewLine(builder, indent + 2).Append("option (.protobuf_net.oneofopt).isSubType = true;"); } for (int num4 = 0; num4 < array5.Length; num4++) { string value2 = array6[num4]; NewLine(builder, indent + 2).Append(value2).Append(' ').Append(value2) .Append(" = ") .Append(array5[num4].FieldNumber) .Append(';'); } NewLine(builder, indent + 1).Append('}'); } if (HasReservations) { AppendReservations(); } NewLine(builder, indent).Append('}'); AddExtraLayerSchemaModels(extraLayerValueMembers, length); void AddExtraLayerSchemaModels(ExtraLayerValueMembers extraLayerValueMembers2, int pos) { if (extraLayerValueMembers2.IsEmpty()) { return; } foreach (NullWrappedValueMemberData item in extraLayerValueMembers2) { NullWrappedValueMemberData wrappedValueMember = item; if (wrappedValueMember.HasSchemaTypeNameCollision) { builder.NewLine(ref pos, indent).Insert("// warning: duplicate message name; you can use [ProtoContract(Name = \"...\")] to supply an alternative schema name", ref pos); } builder.NewLine(ref pos, indent).Insert("message ", ref pos).Insert(wrappedValueMember.WrappedSchemaTypeName, ref pos) .Insert(" {", ref pos); builder.NewLine(ref pos, indent + 1); WriteWrappedFieldPayload(); builder.Insert(";", ref pos); builder.NewLine(ref pos, indent).Insert("}", ref pos); void WriteWrappedFieldPayload() { builder.Insert("optional ", ref pos).Insert(wrappedValueMember.SchemaTypeName, ref pos).Insert(" value = 1", ref pos); } } } void AddNamespace(HashSet hashSet2) { if (multipleNamespaceSupport && !IsAutoTuple && !string.IsNullOrWhiteSpace(Type.Namespace) && !(Type.Namespace == package)) { hashSet2.Add("protobuf-net/protogen.proto"); NewLine(builder, indent + 1).Append("option (.protobuf_net."); if (Type.IsEnum) { builder.Append("enumopt"); } else { builder.Append("msgopt"); } builder.Append(").namespace = \"" + Type.Namespace + "\";"); } } void AppendReservations() { foreach (ProtoReservedAttribute reservation in _reservations) { NewLine(builder, indent + 1).Append("reserved "); if (reservation.From != 0) { builder.Append(reservation.From); if (reservation.To != reservation.From) { builder.Append(" to ").Append(reservation.To); } } else { builder.Append('"').Append(reservation.Name).Append('"'); } builder.Append(';'); if (!string.IsNullOrWhiteSpace(reservation.Comment)) { builder.Append(" /* ").Append(reservation.Comment).Append(" */"); } } } } private static StringBuilder AddOption(StringBuilder builder, ref bool hasOption) { if (hasOption) { return builder.Append(", "); } hasOption = true; return builder.Append(" ["); } private static StringBuilder CloseOption(StringBuilder builder, ref bool hasOption) { if (hasOption) { hasOption = false; return builder.Append(']'); } return builder; } private static bool IsImplicitDefault(object value) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected I4, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Invalid comparison between Unknown and I4 //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Invalid comparison between Unknown and I4 try { if (value == null) { return false; } ProtoTypeCode typeCode = Helpers.GetTypeCode(value.GetType()); if ((int)typeCode <= 100) { switch (typeCode - 3) { default: if ((int)typeCode != 100) { break; } return (TimeSpan)value == TimeSpan.Zero; case 0: return !(bool)value; case 3: return (byte)value == 0; case 1: return (char)value == '\0'; case 13: return (DateTime)value == default(DateTime); case 12: return (decimal)value == 0m; case 11: return (double)value == 0.0; case 4: return (short)value == 0; case 6: return (int)value == 0; case 8: return (long)value == 0; case 2: return (sbyte)value == 0; case 10: return (float)value == 0f; case 15: return value != null && ((string)value).Length == 0; case 5: return (ushort)value == 0; case 7: return (uint)value == 0; case 9: return (ulong)value == 0; case 14: break; } } else { if ((int)typeCode == 108) { return (IntPtr)value == IntPtr.Zero; } if ((int)typeCode == 109) { return (UIntPtr)value == UIntPtr.Zero; } } } catch { } return false; } private static bool CanPack(Type type) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 if ((object)type == null) { return false; } ProtoTypeCode typeCode = Helpers.GetTypeCode(type); if (typeCode - 3 <= 11) { return true; } return false; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] public void ApplyFieldOffset(int offset) { if (Type.IsEnum) { throw new InvalidOperationException("Cannot apply field-offset to an enum"); } if (offset == 0) { return; } int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); ThrowIfFrozen(); List fields = _fields; List subTypes = _subTypes; if (fields != null) { foreach (ValueMember item in fields) { AssertValidFieldNumber(item.FieldNumber + offset); } } if (subTypes != null) { foreach (SubType item2 in subTypes) { AssertValidFieldNumber(item2.FieldNumber + offset); } } if (fields != null) { foreach (ValueMember item3 in fields) { item3.FieldNumber += offset; } } if (subTypes == null) { return; } foreach (SubType item4 in subTypes) { item4.FieldNumber += offset; } } finally { model.ReleaseLock(opaqueToken); } } internal static void AssertValidFieldNumber(int fieldNumber) { if (fieldNumber < 1) { throw new ArgumentOutOfRangeException("fieldNumber"); } } public MetaType AddReservation(int field, string comment = null) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown return AddReservation(new ProtoReservedAttribute(field, comment)); } public MetaType AddReservation(int from, int to, string comment = null) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown return AddReservation(new ProtoReservedAttribute(from, to, comment)); } public MetaType AddReservation(string field, string comment = null) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown return AddReservation(new ProtoReservedAttribute(field, comment)); } private MetaType AddReservation(ProtoReservedAttribute reservation) { reservation.Verify(); int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); ThrowIfFrozen(); if (_reservations == null) { _reservations = new List(); } _reservations.Add(reservation); } finally { model.ReleaseLock(opaqueToken); } return this; } internal void Validate() { ValidateReservations(); } internal void ValidateReservations() { if (!HasReservations || (!HasFields && !HasSubtypes && !HasEnums)) { return; } foreach (ProtoReservedAttribute reservation in _reservations) { if (reservation.From != 0) { if (_fields != null) { foreach (ValueMember field in _fields) { if (field.FieldNumber >= reservation.From && field.FieldNumber <= reservation.To) { throw new InvalidOperationException($"Field {field.FieldNumber} is reserved and cannot be used for data member '{field.Name}'{CommentSuffix(reservation)}."); } } } if (_enums != null) { foreach (EnumMember @enum in _enums) { int? num = @enum.TryGetInt32(); if (num.HasValue && num.Value >= reservation.From && num.Value <= reservation.To) { throw new InvalidOperationException($"Field {num.Value} is reserved and cannot be used for enum value '{@enum.Name}'{CommentSuffix(reservation)}."); } } } if (_subTypes == null) { continue; } foreach (SubType subType in _subTypes) { if (subType.FieldNumber >= reservation.From && subType.FieldNumber <= reservation.To) { throw new InvalidOperationException($"Field {subType.FieldNumber} is reserved and cannot be used for sub-type '{TypeHelper.NormalizeName(subType.DerivedType.Type)}'{CommentSuffix(reservation)}."); } } continue; } if (_fields != null) { foreach (ValueMember field2 in _fields) { if (field2.Name == reservation.Name) { throw new InvalidOperationException($"Field '{field2.Name}' is reserved and cannot be used for data member {field2.FieldNumber}{CommentSuffix(reservation)}."); } } } if (_enums != null) { foreach (EnumMember enum2 in _enums) { if (enum2.Name == reservation.Name) { throw new InvalidOperationException($"Field '{enum2.Name}' is reserved and cannot be used for enum value {enum2.Value}{CommentSuffix(reservation)}."); } } } if (_subTypes == null) { continue; } foreach (SubType subType2 in _subTypes) { string text = subType2.DerivedType.Name; if (string.IsNullOrWhiteSpace(text)) { text = subType2.DerivedType.Type.Name; } if (text == reservation.Name) { throw new InvalidOperationException($"Field '{text}' is reserved and cannot be used for sub-type {subType2.FieldNumber}{CommentSuffix(reservation)}."); } } } static string CommentSuffix(ProtoReservedAttribute reservation) { string comment = reservation.Comment; if (string.IsNullOrWhiteSpace(comment)) { return ""; } return " (" + comment.Trim() + ")"; } } } internal class NullWrappedValueMemberData { private readonly string _originalSchemaTypeName; private readonly string _alternativeTypeName; private readonly bool _hasSchemaTypeNameCollision; private readonly ValueMember _valueMember; public string SchemaTypeName => _originalSchemaTypeName; public string WrappedSchemaTypeName { get { string text = ((!string.IsNullOrEmpty(_alternativeTypeName)) ? _alternativeTypeName : _originalSchemaTypeName); if (_valueMember.SupportNull) { return "WrappedAsSupportNull" + text; } if (_valueMember.NullWrappedValueGroup) { return "WrappedAsGroup" + text; } return "Wrapped" + text; } } public bool HasSchemaTypeNameCollision { get { if (_hasSchemaTypeNameCollision) { return !HasKnownTypeSchema(); } return false; } } public Type ItemType => _valueMember.ItemType; public bool HasGroupModifier => _valueMember.RequiresGroupModifier; public NullWrappedValueMemberData(ValueMember valueMember, string originalSchemaTypeName, string alternativeTypeName = null, bool hasSchemaTypeNameCollision = false) { _originalSchemaTypeName = originalSchemaTypeName; _alternativeTypeName = alternativeTypeName; _hasSchemaTypeNameCollision = hasSchemaTypeNameCollision; _valueMember = valueMember; } private bool HasKnownTypeSchema() { switch (_originalSchemaTypeName) { case "int32": case "int64": case "double": case "string": case "uint32": case "uint64": case "bool": return true; default: return false; } } } public sealed class RuntimeTypeModel : TypeModel { private enum RuntimeTypeModelOptions { None = 0, InternStrings = 1, IncludeDateTimeKind = 2, SkipZeroLengthPackedArrays = 4, AllowPackedEncodingAtRoot = 8, TypeModelMask = 15, InferTagFromNameDefault = 1024, IsDefaultModel = 2048, Frozen = 4096, AutoAddMissingTypes = 8192, AutoCompile = 16384, UseImplicitZeroDefaults = 32768, AllowParseableTypes = 65536, AutoAddProtoContractTypesOnly = 131072 } internal static class CommonImports { public const string Bcl = "protobuf-net/bcl.proto"; public const string WrappersProto = "google/protobuf/wrappers.proto"; public const string Timestamp = "google/protobuf/timestamp.proto"; public const string Duration = "google/protobuf/duration.proto"; public const string Protogen = "protobuf-net/protogen.proto"; public const string Empty = "google/protobuf/empty.proto"; } private sealed class BasicType { public Type Type { get; } public IRuntimeProtoSerializerNode Serializer { get; } public BasicType(Type type, IRuntimeProtoSerializerNode serializer) { Type = type; Serializer = serializer; } } internal sealed class SerializerPair : IComparable { public readonly int MetaKey; public readonly int BaseKey; public readonly MetaType Type; public readonly MethodBuilder Serialize; public readonly MethodBuilder Deserialize; public readonly ILGenerator SerializeBody; public readonly ILGenerator DeserializeBody; int IComparable.CompareTo(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } SerializerPair serializerPair = (SerializerPair)obj; if (BaseKey == MetaKey) { if (serializerPair.BaseKey == serializerPair.MetaKey) { return MetaKey.CompareTo(serializerPair.MetaKey); } return 1; } if (serializerPair.BaseKey == serializerPair.MetaKey) { return -1; } int num = BaseKey.CompareTo(serializerPair.BaseKey); if (num == 0) { num = MetaKey.CompareTo(serializerPair.MetaKey); } return num; } public SerializerPair(int metaKey, int baseKey, MetaType type, MethodBuilder serialize, MethodBuilder deserialize, ILGenerator serializeBody, ILGenerator deserializeBody) { MetaKey = metaKey; BaseKey = baseKey; Serialize = serialize; Deserialize = deserialize; SerializeBody = serializeBody; DeserializeBody = deserializeBody; Type = type; } } public sealed class CompilerOptions { internal const string NoPersistence = "Assembly persistence not supported on this runtime"; public string TargetFrameworkName { get; set; } public string TargetFrameworkDisplayName { get; set; } public string TypeName { get; set; } [Obsolete("Assembly persistence not supported on this runtime")] public string OutputPath { get; set; } public string ImageRuntimeVersion { get; set; } public int MetaDataVersion { get; set; } public string AssemblyCompanyName { get; set; } public string AssemblyCopyright { get; set; } public string AssemblyDescription { get; set; } public string AssemblyProductName { get; set; } public string AssemblyTitle { get; set; } public string AssemblyTrademark { get; set; } public Version AssemblyVersion { get; set; } public Version AssemblyProductVersion { get; set; } public Accessibility Accessibility { get; set; } public event Func IncludeType; public void SetFrameworkOptions(MetaType from) { if (from == null) { throw new ArgumentNullException("from"); } AttributeMap[] array = AttributeMap.Create(from.Type.Assembly); AttributeMap[] array2 = array; foreach (AttributeMap attributeMap in array2) { if (attributeMap.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute") { if (attributeMap.TryGet("FrameworkName", out var value)) { TargetFrameworkName = (string)value; } if (attributeMap.TryGet("FrameworkDisplayName", out value)) { TargetFrameworkDisplayName = (string)value; } break; } } } internal bool OnIncludeType(Type type) { return this.IncludeType?.Invoke(type) ?? true; } } public enum Accessibility { Public, Internal } private RuntimeTypeModelOptions _options; private CompatibilityLevel _defaultCompatibilityLevel = (CompatibilityLevel)200; private static readonly BasicList.MatchPredicate BasicTypeFinder = (object value, object ctx) => ((BasicType)value).Type == (Type)ctx; private static readonly BasicList.MatchPredicate MetaTypeFinder = (object value, object ctx) => ((MetaType)value).Type == (Type)ctx; private readonly BasicList types = new BasicList(); private readonly BasicList basicTypes = new BasicList(); private readonly Hashtable _serviceCache = new Hashtable(); private int metadataTimeoutMilliseconds = 5000; private int contentionCounter = 1; private MethodInfo defaultFactory; private readonly string _name; private static readonly object s_ModelSyncLock = new object(); private Hashtable _externalProviders; public override TypeModelOptions Options => (TypeModelOptions)(_options & RuntimeTypeModelOptions.TypeModelMask); internal CompilerContextScope Scope { get; } = CompilerContextScope.CreateInProcess(); public bool InferTagFromNameDefault { get { return GetOption(RuntimeTypeModelOptions.InferTagFromNameDefault); } set { SetOption(RuntimeTypeModelOptions.InferTagFromNameDefault, value); } } public bool AutoAddProtoContractTypesOnly { get { return GetOption(RuntimeTypeModelOptions.AutoAddProtoContractTypesOnly); } set { SetOption(RuntimeTypeModelOptions.AutoAddProtoContractTypesOnly, value); } } public bool UseImplicitZeroDefaults { get { return GetOption(RuntimeTypeModelOptions.UseImplicitZeroDefaults); } set { if (!value && GetOption(RuntimeTypeModelOptions.IsDefaultModel)) { ThrowDefaultUseImplicitZeroDefaults(); } SetOption(RuntimeTypeModelOptions.UseImplicitZeroDefaults, value); } } public bool AllowParseableTypes { get { return GetOption(RuntimeTypeModelOptions.AllowParseableTypes); } set { SetOption(RuntimeTypeModelOptions.AllowParseableTypes, value); } } public bool IncludeDateTimeKind { get { return GetOption(RuntimeTypeModelOptions.IncludeDateTimeKind); } set { SetOption(RuntimeTypeModelOptions.IncludeDateTimeKind, value); } } public bool SkipZeroLengthPackedArrays { get { return GetOption(RuntimeTypeModelOptions.SkipZeroLengthPackedArrays); } set { SetOption(RuntimeTypeModelOptions.SkipZeroLengthPackedArrays, value); } } public bool AllowPackedEncodingAtRoot { get { return GetOption(RuntimeTypeModelOptions.AllowPackedEncodingAtRoot); } set { SetOption(RuntimeTypeModelOptions.AllowPackedEncodingAtRoot, value); } } public bool InternStrings { get { return GetOption(RuntimeTypeModelOptions.InternStrings); } set { SetOption(RuntimeTypeModelOptions.InternStrings, value); } } public static RuntimeTypeModel Default => (TypeModel.DefaultModel as RuntimeTypeModel) ?? CreateDefaultModelInstance(); public CompatibilityLevel DefaultCompatibilityLevel { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _defaultCompatibilityLevel; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (value != _defaultCompatibilityLevel) { CompatibilityLevelAttribute.AssertValid(value); ThrowIfFrozen(); if (GetOption(RuntimeTypeModelOptions.IsDefaultModel)) { ThrowHelper.ThrowInvalidOperationException("The default compatibility level of the default model cannot be changed", (Exception)null); } if (types.Any()) { ThrowHelper.ThrowInvalidOperationException("The default compatibility level of cannot be changed once types have been added", (Exception)null); } _defaultCompatibilityLevel = value; } } } public MetaType this[Type type] => (MetaType)types[FindOrAddAuto(type, demand: true, addWithContractOnly: false, addEvenIfAutoDisabled: false, DefaultCompatibilityLevel)]; public bool AutoCompile { get { return GetOption(RuntimeTypeModelOptions.AutoCompile); } set { SetOption(RuntimeTypeModelOptions.AutoCompile, value); } } public bool AutoAddMissingTypes { get { return GetOption(RuntimeTypeModelOptions.AutoAddMissingTypes); } set { if (!value && GetOption(RuntimeTypeModelOptions.IsDefaultModel)) { ThrowDefaultAutoAddMissingTypes(); } ThrowIfFrozen(); SetOption(RuntimeTypeModelOptions.AutoAddMissingTypes, value); } } public int MetadataTimeoutMilliseconds { get { return metadataTimeoutMilliseconds; } set { if (value <= 0) { throw new ArgumentOutOfRangeException("MetadataTimeoutMilliseconds"); } metadataTimeoutMilliseconds = value; } } public event EventHandler BeforeApplyDefaultBehaviour; public event EventHandler AfterApplyDefaultBehaviour; public event LockContentedEventHandler LockContended; public static void Initialize() { _ = Default; } private bool GetOption(RuntimeTypeModelOptions option) { return (_options & option) != 0; } private void SetOption(RuntimeTypeModelOptions option, bool value) { if (value) { _options |= option; } else { _options &= ~option; } } public IEnumerable GetTypes() { return types; } public override string GetSchema(SchemaGenerationOptions options) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Invalid comparison between Unknown and I4 //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_0471: Unknown result type (might be due to invalid IL or missing references) //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_0508: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Unknown result type (might be due to invalid IL or missing references) if (options == null) { throw new ArgumentNullException("options"); } ProtoSyntax val = Serializer.GlobalOptions.Normalize(options.Syntax); List requiredTypes = new List(); List list = null; HashSet forceGenerationTypes = null; string package = options.Package; string origin = options.Origin; HashSet imports = new HashSet(StringComparer.Ordinal); if (!options.HasTypes && !options.HasServices) { BasicList.NodeEnumerator enumerator = types.GetEnumerator(); while (enumerator.MoveNext()) { MetaType metaType = (MetaType)enumerator.Current; MetaType surrogateOrBaseOrSelf = metaType.GetSurrogateOrBaseOrSelf(deep: false); AddMetaType(surrogateOrBaseOrSelf); } } else { if (options.HasTypes) { foreach (Type type2 in options.Types) { Type type = Nullable.GetUnderlyingType(type2) ?? type2; if (ValueMember.TryGetCoreSerializer(this, (DataFormat)0, DefaultCompatibilityLevel, type, out var _, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false) != null) { (list ?? (list = new List())).Add(type); continue; } bool flag = options.Types.Count == 1; MetaType metaType2 = AddType(type, flag, flag); } } if (options.HasServices) { foreach (Service service in options.Services) { foreach (ServiceMethod method in service.Methods) { AddType(method.InputType, forceOutput: true, inferPackageAndOrigin: false); AddType(method.OutputType, forceOutput: true, inferPackageAndOrigin: false); } } } } StringBuilder stringBuilder = new StringBuilder(); if (package == null) { IEnumerable enumerable; if (!options.HasTypes && !options.HasServices) { enumerable = types.Cast(); } else { IEnumerable enumerable2 = requiredTypes; enumerable = enumerable2; } IEnumerable enumerable3 = enumerable; foreach (MetaType item in enumerable3) { if (TryGetRepeatedProvider(item.Type, (CompatibilityLevel)0) != null) { continue; } string text = item.Type.Namespace; if (!string.IsNullOrEmpty(text) && !text.StartsWith("System.")) { if (package == null) { package = text; } else if (!(package == text)) { package = null; break; } } } } if ((int)val != 0) { if ((int)val != 1) { throw new ArgumentOutOfRangeException("syntax"); } stringBuilder.AppendLine("syntax = \"proto3\";"); } else { stringBuilder.AppendLine("syntax = \"proto2\";"); } if (!string.IsNullOrEmpty(package)) { stringBuilder.Append("package ").Append(package).Append(';') .AppendLine(); } foreach (MetaType item2 in requiredTypes) { _ = item2.Serializer; } StringBuilder stringBuilder2 = new StringBuilder(); HashSet callstack = new HashSet(); MetaType[] array = new MetaType[requiredTypes.Count]; requiredTypes.CopyTo(array, 0); Array.Sort(array, new MetaType.Comparer(callstack)); if (list != null) { foreach (Type item3 in list) { stringBuilder2.AppendLine().Append("message ").Append(item3.Name) .Append(" {"); MetaType.NewLine(stringBuilder2, 1).Append(((int)val == 0) ? "optional " : "").Append(GetSchemaTypeName(callstack, item3, (DataFormat)0, DefaultCompatibilityLevel, asReference: false, dynamicType: false, imports)) .Append(" value = 1;") .AppendLine() .Append('}'); } } foreach (MetaType metaType3 in array) { if ((object)metaType3.SerializerType == null && (IsOutputForcedFor(metaType3.Type) || TryGetRepeatedProvider(metaType3.Type, (CompatibilityLevel)0) == null)) { metaType3.WriteSchema(callstack, stringBuilder2, 0, imports, val, package, options.Flags); } } if (options.HasServices) { foreach (Service service2 in options.Services) { MetaType.NewLine(stringBuilder2, 0).Append("service ").Append(service2.Name) .Append(" {"); foreach (ServiceMethod method2 in service2.Methods) { string schemaTypeName = GetSchemaTypeName(callstack, method2.InputType, (DataFormat)0, DefaultCompatibilityLevel, asReference: false, dynamicType: false, imports); string schemaTypeName2 = GetSchemaTypeName(callstack, method2.OutputType, (DataFormat)0, DefaultCompatibilityLevel, asReference: false, dynamicType: false, imports); MetaType.NewLine(stringBuilder2, 1).Append("rpc ").Append(method2.Name) .Append(" (") .Append(method2.ClientStreaming ? "stream " : "") .Append(schemaTypeName) .Append(") returns (") .Append(method2.ServerStreaming ? "stream " : "") .Append(schemaTypeName2) .Append(");"); } MetaType.NewLine(stringBuilder2, 0).Append('}'); } } foreach (string item4 in imports.OrderBy((string _) => _)) { if (string.IsNullOrWhiteSpace(item4)) { continue; } stringBuilder.Append("import \"").Append(item4).Append("\";"); if (!(item4 == "protobuf-net/bcl.proto")) { if (item4 == "protobuf-net/protogen.proto") { stringBuilder.Append(" // custom protobuf-net options"); } } else { stringBuilder.Append(" // schema for protobuf-net's handling of core .NET types"); } stringBuilder.AppendLine(); } return stringBuilder.Append(stringBuilder2).AppendLine().ToString(); void AddMetaType(MetaType toAdd) { if (!string.IsNullOrWhiteSpace(toAdd.Origin) && toAdd.Origin != origin) { imports.Add(toAdd.Origin); } else if (!requiredTypes.Contains(toAdd)) { requiredTypes.Add(toAdd); CascadeDependents(requiredTypes, toAdd, imports, origin); } } MetaType AddType(Type type2, bool forceOutput, bool inferPackageAndOrigin) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (forceOutput && (object)type2 != null) { (forceGenerationTypes ?? (forceGenerationTypes = new HashSet())).Add(type2); } int num = FindOrAddAuto(type2, demand: false, addWithContractOnly: false, addEvenIfAutoDisabled: false, DefaultCompatibilityLevel); if (num < 0) { throw new ArgumentException("The type specified is not a contract-type: '" + TypeHelper.NormalizeName(type2) + "'", "type"); } MetaType surrogateOrBaseOrSelf2 = ((MetaType)types[num]).GetSurrogateOrBaseOrSelf(deep: false); if (inferPackageAndOrigin) { if (origin == null && !string.IsNullOrWhiteSpace(surrogateOrBaseOrSelf2.Origin)) { origin = surrogateOrBaseOrSelf2.Origin; } string text2; if (package == null && !string.IsNullOrWhiteSpace(text2 = surrogateOrBaseOrSelf2.GuessPackage())) { package = text2; } } AddMetaType(surrogateOrBaseOrSelf2); return surrogateOrBaseOrSelf2; } bool IsOutputForcedFor(Type item) { return forceGenerationTypes?.Contains(item) ?? false; } } private void CascadeRepeated(List list, RepeatedSerializerStub provider, CompatibilityLevel ambient, DataFormat keyFormat, HashSet imports, string origin) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (provider.IsMap) { provider.ResolveMapTypes(out var keyType, out var valueType); TryGetCoreSerializer(list, keyType, ambient, imports, origin); TryGetCoreSerializer(list, valueType, ambient, imports, origin); if (!provider.IsValidProtobufMap(this, ambient, keyFormat)) { TryGetCoreSerializer(list, provider.ItemType, ambient, imports, origin); } } else { TryGetCoreSerializer(list, provider.ItemType, ambient, imports, origin); } } private void CascadeDependents(List list, MetaType metaType, HashSet imports, string origin) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) RepeatedSerializerStub repeatedSerializerStub = TryGetRepeatedProvider(metaType.Type, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { CascadeRepeated(list, repeatedSerializerStub, metaType.CompatibilityLevel, (DataFormat)0, imports, origin); return; } if (metaType.IsAutoTuple) { if ((object)MetaType.ResolveTupleConstructor(metaType.Type, out var mappedMembers) != null) { for (int i = 0; i < mappedMembers.Length; i++) { Type itemType = null; if (mappedMembers[i] is PropertyInfo propertyInfo) { itemType = propertyInfo.PropertyType; } else if (mappedMembers[i] is FieldInfo fieldInfo) { itemType = fieldInfo.FieldType; } TryGetCoreSerializer(list, itemType, metaType.CompatibilityLevel, imports, origin); } } } else { foreach (ValueMember field in metaType.Fields) { repeatedSerializerStub = TryGetRepeatedProvider(field.MemberType, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { CascadeRepeated(list, repeatedSerializerStub, field.CompatibilityLevel, field.MapKeyFormat, imports, origin); if (repeatedSerializerStub.IsMap && !field.IsMap) { TryGetCoreSerializer(list, repeatedSerializerStub.ItemType, field.CompatibilityLevel, imports, origin); } } else { TryGetCoreSerializer(list, field.MemberType, field.CompatibilityLevel, imports, origin); } } } foreach (Type allGenericArgument in metaType.GetAllGenericArguments()) { repeatedSerializerStub = TryGetRepeatedProvider(allGenericArgument, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { CascadeRepeated(list, repeatedSerializerStub, metaType.CompatibilityLevel, (DataFormat)0, imports, origin); } else { TryGetCoreSerializer(list, allGenericArgument, metaType.CompatibilityLevel, imports, origin); } } MetaType surrogateOrSelf; if (metaType.HasSubtypes) { SubType[] subtypes = metaType.GetSubtypes(); foreach (SubType subType in subtypes) { surrogateOrSelf = subType.DerivedType.GetSurrogateOrSelf(); if (!list.Contains(surrogateOrSelf)) { list.Add(surrogateOrSelf); CascadeDependents(list, surrogateOrSelf, imports, origin); } } } surrogateOrSelf = metaType.BaseType; if (surrogateOrSelf != null) { surrogateOrSelf = surrogateOrSelf.GetSurrogateOrSelf(); } if (surrogateOrSelf != null && !list.Contains(surrogateOrSelf)) { list.Add(surrogateOrSelf); CascadeDependents(list, surrogateOrSelf, imports, origin); } } private void TryGetCoreSerializer(List list, Type itemType, CompatibilityLevel ambient, HashSet imports, string origin) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) IRuntimeProtoSerializerNode runtimeProtoSerializerNode = ValueMember.TryGetCoreSerializer(this, (DataFormat)0, (CompatibilityLevel)0, itemType, out var defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); if (runtimeProtoSerializerNode != null) { return; } int num = FindOrAddAuto(itemType, demand: false, addWithContractOnly: false, addEvenIfAutoDisabled: false, ambient); if (num < 0) { return; } MetaType metaType = (MetaType)types[num]; if (metaType.HasSurrogate) { runtimeProtoSerializerNode = ValueMember.TryGetCoreSerializer(this, metaType.surrogateDataFormat, metaType.CompatibilityLevel, metaType.surrogateType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); if (runtimeProtoSerializerNode != null) { return; } } MetaType surrogateOrBaseOrSelf = metaType.GetSurrogateOrBaseOrSelf(deep: false); if (!string.IsNullOrWhiteSpace(surrogateOrBaseOrSelf.Origin) && surrogateOrBaseOrSelf.Origin != origin) { imports.Add(surrogateOrBaseOrSelf.Origin); } else if (!list.Contains(surrogateOrBaseOrSelf)) { list.Add(surrogateOrBaseOrSelf); CascadeDependents(list, surrogateOrBaseOrSelf, imports, origin); } } internal RuntimeTypeModel(bool isDefault, string name) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) AutoAddMissingTypes = true; UseImplicitZeroDefaults = true; SetOption(RuntimeTypeModelOptions.IsDefaultModel, isDefault); try { AutoCompile = EnableAutoCompile(); } catch { } if (!string.IsNullOrWhiteSpace(name)) { _name = name; } } [MethodImpl(MethodImplOptions.NoInlining)] internal static bool EnableAutoCompile() { try { DynamicMethod dynamicMethod = new DynamicMethod("CheckCompilerAvailable", typeof(bool), new Type[1] { typeof(int) }); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldc_I4, 42); iLGenerator.Emit(OpCodes.Ceq); iLGenerator.Emit(OpCodes.Ret); Predicate predicate = (Predicate)dynamicMethod.CreateDelegate(typeof(Predicate)); return predicate(42); } catch (Exception) { return false; } } internal MetaType FindWithAmbientCompatibility(Type type, CompatibilityLevel ambient) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) MetaType metaType = (MetaType)types[FindOrAddAuto(type, demand: true, addWithContractOnly: false, addEvenIfAutoDisabled: false, ambient)]; if (metaType != null && metaType.IsAutoTuple && metaType.CompatibilityLevel != ambient) { throw new InvalidOperationException($"The tuple-like type {TypeHelper.NormalizeName(type)} must use a single compatibility level, but '{ambient}' and '{metaType.CompatibilityLevel}' are both observed; this usually means it is being used in different contexts in the same model."); } return metaType; } internal MetaType FindWithoutAdd(Type type) { type = DynamicStub.GetEffectiveType(type); BasicList.NodeEnumerator enumerator = types.GetEnumerator(); while (enumerator.MoveNext()) { MetaType metaType = (MetaType)enumerator.Current; if (metaType.Type == type) { if (metaType.Pending) { WaitOnLock(); } return metaType; } } return null; } private void WaitOnLock() { int opaqueToken = 0; try { TakeLock(ref opaqueToken); } finally { ReleaseLock(opaqueToken); } } internal IRuntimeProtoSerializerNode TryGetBasicTypeSerializer(Type type) { int num = basicTypes.IndexOf(BasicTypeFinder, type); if (num >= 0) { return ((BasicType)basicTypes[num]).Serializer; } lock (basicTypes) { num = basicTypes.IndexOf(BasicTypeFinder, type); if (num >= 0) { return ((BasicType)basicTypes[num]).Serializer; } WireType defaultWireType; IRuntimeProtoSerializerNode runtimeProtoSerializerNode = ((MetaType.GetContractFamily(this, type, null) == MetaType.AttributeFamily.None) ? ValueMember.TryGetCoreSerializer(this, (DataFormat)0, (CompatibilityLevel)0, type, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false) : null); if (runtimeProtoSerializerNode != null) { basicTypes.Add(new BasicType(type, runtimeProtoSerializerNode)); } return runtimeProtoSerializerNode; } } internal int FindOrAddAuto(Type type, bool demand, bool addWithContractOnly, bool addEvenIfAutoDisabled, CompatibilityLevel ambient) { //IL_0108: Unknown result type (might be due to invalid IL or missing references) type = DynamicStub.GetEffectiveType(type); int num = types.IndexOf(MetaTypeFinder, type); if (num >= 0) { MetaType metaType = (MetaType)types[num]; if (metaType.Pending) { WaitOnLock(); } return num; } bool flag = AutoAddMissingTypes || addEvenIfAutoDisabled; if (!type.IsEnum && TryGetBasicTypeSerializer(type) != null) { if (flag && !addWithContractOnly) { throw MetaType.InbuiltType(type); } return -1; } if (num < 0) { int opaqueToken = 0; bool flag2 = false; try { TakeLock(ref opaqueToken); MetaType metaType; if ((metaType = RecogniseCommonTypes(type)) == null) { MetaType.AttributeFamily contractFamily = MetaType.GetContractFamily(this, type, null); if (contractFamily == MetaType.AttributeFamily.AutoTuple) { flag = (addEvenIfAutoDisabled = true); } if (!flag || (!type.IsEnum && addWithContractOnly && contractFamily == MetaType.AttributeFamily.None)) { if (demand) { TypeModel.ThrowUnexpectedType(type, (TypeModel)(object)this); } return num; } metaType = Create(type); } metaType.Pending = true; int num2 = types.IndexOf(MetaTypeFinder, type); if (num2 < 0) { ThrowIfFrozen(); num = types.Add(metaType); flag2 = true; } else { num = num2; } if (flag2) { metaType.ApplyDefaultBehaviour(ambient); metaType.Pending = false; } } finally { ReleaseLock(opaqueToken); } } return num; } private MetaType RecogniseCommonTypes(Type type) { return null; } private MetaType Create(Type type) { ThrowIfFrozen(); return new MetaType(this, type, defaultFactory); } public MetaType Add(bool applyDefaultBehaviour = true, CompatibilityLevel compatibilityLevel = (CompatibilityLevel)0) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return Add(typeof(T), applyDefaultBehaviour, compatibilityLevel); } public MetaType Add(Type type, bool applyDefaultBehaviour) { return Add(type, applyDefaultBehaviour, (CompatibilityLevel)0); } public MetaType Add(Type type, bool applyDefaultBehaviour = true, CompatibilityLevel compatibilityLevel = (CompatibilityLevel)0) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) if ((object)type == null) { throw new ArgumentNullException("type"); } if (type == typeof(object)) { throw new ArgumentException("You cannot reconfigure " + type.FullName); } type = DynamicStub.GetEffectiveType(type); MetaType metaType = FindWithoutAdd(type); if (metaType != null) { if ((int)compatibilityLevel != 0) { metaType.Assert(compatibilityLevel); } return metaType; } int opaqueToken = 0; try { metaType = RecogniseCommonTypes(type); if (metaType != null) { if (!applyDefaultBehaviour) { throw new ArgumentException("Default behaviour must be observed for certain types with special handling; " + type.FullName, "applyDefaultBehaviour"); } applyDefaultBehaviour = false; } if (metaType == null) { metaType = Create(type); } metaType.CompatibilityLevel = compatibilityLevel; metaType.Pending = true; TakeLock(ref opaqueToken); if (FindWithoutAdd(type) != null) { throw new ArgumentException("Duplicate type", "type"); } ThrowIfFrozen(); types.Add(metaType); if (applyDefaultBehaviour) { metaType.ApplyDefaultBehaviour((CompatibilityLevel)0); } metaType.Pending = false; return metaType; } finally { ReleaseLock(opaqueToken); } } internal static void OnBeforeApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) { OnApplyDefaultBehaviour(metaType?.Model?.BeforeApplyDefaultBehaviour, metaType, ref args); } internal static void OnAfterApplyDefaultBehaviour(MetaType metaType, ref TypeAddedEventArgs args) { OnApplyDefaultBehaviour(metaType?.Model?.AfterApplyDefaultBehaviour, metaType, ref args); } private static void OnApplyDefaultBehaviour(EventHandler handler, MetaType metaType, ref TypeAddedEventArgs args) { if (handler != null) { if (args == null) { args = new TypeAddedEventArgs(metaType); } handler(metaType.Model, args); } } private void ThrowIfFrozen() { if (GetOption(RuntimeTypeModelOptions.Frozen)) { throw new InvalidOperationException("The model cannot be changed once frozen"); } } public void Freeze() { if (GetOption(RuntimeTypeModelOptions.IsDefaultModel)) { ThrowDefaultFrozen(); } SetOption(RuntimeTypeModelOptions.Frozen, value: true); } protected override ISerializer GetSerializer() { return GetServices((CompatibilityLevel)0) as ISerializer; } internal override ISerializer GetSerializerCore(CompatibilityLevel ambient) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return GetServices(ambient) as ISerializer; } internal override bool IsKnownType(CompatibilityLevel ambient) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (_serviceCache[typeof(T)] == null) { return FindOrAddAuto(typeof(T), demand: false, addWithContractOnly: true, addEvenIfAutoDisabled: false, ambient) >= 0; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private object GetServices(CompatibilityLevel ambient) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) return _serviceCache[typeof(T)] ?? GetServicesSlow(typeof(T), ambient); } internal void ResetServiceCache(Type type) { if ((object)type != null) { lock (_serviceCache) { _serviceCache.Remove(type); } } } private object GetServicesSlow(Type type, CompatibilityLevel ambient) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) if ((object)type == null) { return null; } object obj; lock (_serviceCache) { obj = _serviceCache[type]; if (obj != null) { return obj; } } obj = GetServicesImpl(this, type, ambient); if (obj != null) { try { _ = this[type]; } catch { } lock (_serviceCache) { _serviceCache[type] = obj; } } return obj; static object GetServicesImpl(RuntimeTypeModel model, Type type2, CompatibilityLevel ambient2) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (type2.IsEnum) { return EnumSerializers.GetSerializer(type2); } Type underlyingType = Nullable.GetUnderlyingType(type2); if ((object)underlyingType != null) { return model.GetServicesSlow(underlyingType, ambient2); } RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(type2, (CompatibilityLevel)0); if (repeatedSerializerStub != null) { return repeatedSerializerStub.Serializer; } int num = model.FindOrAddAuto(type2, demand: false, addWithContractOnly: true, addEvenIfAutoDisabled: false, ambient2); if (num >= 0) { MetaType metaType = (MetaType)model.types[num]; IProtoTypeSerializer serializer = metaType.Serializer; if (serializer is IExternalSerializer externalSerializer) { return externalSerializer.Service; } return serializer; } return null; } } public override string ToString() { return _name ?? ((object)this).ToString(); } internal ProtoSerializer GetSerializer(IRuntimeProtoSerializerNode serializer, bool compiled) { if (serializer == null) { throw new ArgumentNullException("serializer"); } if (compiled) { return CompilerContext.BuildSerializer(Scope, serializer, (TypeModel)(object)this); } return delegate(ref State state, TActual val) { serializer.Write(ref state, val); }; } public void CompileInPlace() { BasicList.NodeEnumerator enumerator = types.GetEnumerator(); while (enumerator.MoveNext()) { MetaType metaType = (MetaType)enumerator.Current; metaType.CompileInPlace(); } } private void BuildAllSerializers() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < types.Count; i++) { MetaType metaType = (MetaType)types[i]; if (GetServicesSlow(metaType.Type, metaType.CompatibilityLevel) == null) { throw new InvalidOperationException("No serializer available for " + TypeHelper.NormalizeName(metaType.Type)); } } } internal static ILGenerator Override(TypeBuilder type, string name) { Type[] genericArgs; return Override(type, name, out genericArgs); } internal static ILGenerator Override(TypeBuilder type, string name, out Type[] genericArgs) { MethodInfo method; try { method = type.BaseType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)method == null) { throw new ArgumentException("Unable to resolve '" + name + "'"); } } catch (Exception ex) { throw new ArgumentException("Unable to resolve '" + name + "': " + ex.Message, "name", ex); } ParameterInfo[] parameters = method.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < array.Length; i++) { array[i] = parameters[i].ParameterType; } MethodBuilder methodBuilder = type.DefineMethod(method.Name, (method.Attributes & ~(MethodAttributes.VtableLayoutMask | MethodAttributes.Abstract)) | MethodAttributes.Final, method.CallingConvention, method.ReturnType, array); if (method.IsGenericMethodDefinition) { genericArgs = method.GetGenericArguments(); string[] names = Array.ConvertAll(genericArgs, (Type x) => x.Name); methodBuilder.DefineGenericParameters(names); } else { genericArgs = Type.EmptyTypes; } for (int num = 0; num < parameters.Length; num++) { methodBuilder.DefineParameter(num + 1, parameters[num].Attributes, parameters[num].Name); } ILGenerator iLGenerator = methodBuilder.GetILGenerator(); type.DefineMethodOverride(methodBuilder, method); return iLGenerator; } public TypeModel Compile(CompilerOptions options = null) { //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Expected O, but got Unknown if (options == null) { options = new CompilerOptions(); } string text = options.TypeName; string outputPath = options.OutputPath; BuildAllSerializers(); Freeze(); bool flag = !string.IsNullOrEmpty(outputPath); if (string.IsNullOrEmpty(text)) { if (flag) { throw new ArgumentNullException("typeName"); } text = "CompiledModel_" + Guid.NewGuid(); } string text2; string name; if (outputPath == null) { text2 = text; name = text2 + ".dll"; } else { text2 = new FileInfo(Path.GetFileNameWithoutExtension(outputPath)).Name; name = text2 + Path.GetExtension(outputPath); } AssemblyName name2 = new AssemblyName { Name = text2, Version = options.AssemblyVersion }; AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(name2, AssemblyBuilderAccess.RunAndCollect); ModuleBuilder module = assemblyBuilder.DefineDynamicModule(name); CompilerContextScope scope = CompilerContextScope.CreateForModule(this, module, isFullEmit: true, text2); WriteAssemblyAttributes(options, text2, assemblyBuilder); TypeBuilder typeBuilder = WriteBasicTypeModel("___PBN_Services___" + text, module, typeof(object), @internal: true); WriteSerializers(scope, typeBuilder); WriteEnumsAndProxies(typeBuilder); Type serviceType = typeBuilder.CreateType(); TypeBuilder typeBuilder2 = WriteBasicTypeModel(text, module, typeof(TypeModel), options.Accessibility == Accessibility.Internal); WriteConstructorsAndOverrides(typeBuilder2, serviceType); Type type = typeBuilder2.CreateType(); if (!string.IsNullOrEmpty(outputPath)) { throw new NotSupportedException("Assembly persistence not supported on this runtime"); } return (TypeModel)Activator.CreateInstance(type, nonPublic: true); } private void WriteConstructorsAndOverrides(TypeBuilder type, Type serviceType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected I4, but got Unknown TypeModelOptions options = ((TypeModel)this).Options; ILGenerator iLGenerator; if ((int)options != 0) { iLGenerator = Override(type, "get_Options"); CompilerContext.LoadValue(iLGenerator, (int)options); iLGenerator.Emit(OpCodes.Ret); } iLGenerator = Override(type, "GetSerializer", out var genericArgs); Type type2 = genericArgs.Single(); MethodInfo methodInfo = typeof(SerializerCache).GetMethod("Get").MakeGenericMethod(serviceType, type2); iLGenerator.EmitCall(OpCodes.Call, methodInfo, null); iLGenerator.Emit(OpCodes.Ret); type.DefineDefaultConstructor(MethodAttributes.Public); } private void WriteEnumsAndProxies(TypeBuilder type) { for (int i = 0; i < types.Count; i++) { MetaType metaType = (MetaType)types[i]; Type type2 = metaType.Type; RepeatedSerializerStub repeatedSerializerStub; if (type2.IsEnum) { MemberInfo provider = EnumSerializers.GetProvider(type2); AddProxy(type, type2, provider, includeNullable: true); } else if (ShouldEmitCustomSerializerProxy(metaType.SerializerType)) { AddProxy(type, type2, metaType.SerializerType, includeNullable: false); } else if ((repeatedSerializerStub = TryGetRepeatedProvider(type2, (CompatibilityLevel)0)) != null) { AddProxy(type, type2, repeatedSerializerStub.Provider, includeNullable: false); } } static bool ShouldEmitCustomSerializerProxy(Type serializerType) { if ((object)serializerType == null) { return false; } if (IsFullyPublic(serializerType)) { return true; } return serializerType.Assembly != typeof(PrimaryTypeProvider).Assembly; } } internal static MemberInfo GetUnderlyingProvider(MemberInfo provider, Type forType) { MemberInfo memberInfo = provider; if (!(memberInfo is PropertyInfo propertyInfo)) { if (memberInfo is Type { IsClass: not false, IsAbstract: false } type && (object)type.GetConstructor(Type.EmptyTypes) != null) { provider = typeof(SerializerCache).GetMethod("Get", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(type, forType); } } else { provider = propertyInfo.GetGetMethod(nonPublic: true); } return provider; } internal static void EmitProvider(MemberInfo provider, ILGenerator il) { if (!(provider is FieldInfo fieldInfo)) { if (provider is MethodInfo { IsStatic: not false } methodInfo) { il.EmitCall(OpCodes.Call, methodInfo, null); return; } } else if (fieldInfo.IsStatic) { il.Emit(OpCodes.Ldsfld, fieldInfo); return; } ThrowHelper.ThrowInvalidOperationException($"Invalid provider: {provider}", (Exception)null); } internal RepeatedSerializerStub TryGetRepeatedProvider(Type type, CompatibilityLevel ambient = (CompatibilityLevel)0) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) if ((object)type == null) { return null; } RepeatedSerializerStub repeatedSerializerStub = RepeatedSerializers.TryGetRepeatedProvider(type, _externalProviders); if (repeatedSerializerStub != null) { int num = FindOrAddAuto(type, demand: false, addWithContractOnly: true, addEvenIfAutoDisabled: false, ambient); if (num >= 0 && ((MetaType)types[num]).IgnoreListHandling) { return null; } } return repeatedSerializerStub; } private static void AddProxy(TypeBuilder building, Type proxying, MemberInfo provider, bool includeNullable) { provider = GetUnderlyingProvider(provider, proxying); if ((object)provider != null) { Type interfaceType = typeof(ISerializerProxy<>).MakeGenericType(proxying); building.AddInterfaceImplementation(interfaceType); ILGenerator iLGenerator = CompilerContextScope.Implement(building, interfaceType, "get_Serializer"); EmitProvider(provider, iLGenerator); iLGenerator.Emit(OpCodes.Ret); if (includeNullable) { interfaceType = typeof(ISerializerProxy<>).MakeGenericType(typeof(Nullable<>).MakeGenericType(proxying)); building.AddInterfaceImplementation(interfaceType); iLGenerator = CompilerContextScope.Implement(building, interfaceType, "get_Serializer"); EmitProvider(provider, iLGenerator); iLGenerator.Emit(OpCodes.Ret); } } } private void WriteSerializers(CompilerContextScope scope, TypeBuilder type) { //IL_01b2: Unknown result type (might be due to invalid IL or missing references) Dictionary featuresLookup = new Dictionary(); for (int i = 0; i < types.Count; i++) { MetaType metaType = (MetaType)types[i]; IProtoTypeSerializer serializer = metaType.Serializer; Type type2 = metaType.Type; metaType.Validate(); if (type2.IsEnum || (object)metaType.SerializerType != null || TryGetRepeatedProvider(metaType.Type, (CompatibilityLevel)0) != null) { continue; } if (!IsFullyPublic(type2, out var cause)) { ThrowHelper.ThrowInvalidOperationException("Non-public type cannot be used with full dll compilation: " + TypeHelper.NormalizeName(cause), (Exception)null); } Type inheritanceRoot = metaType.GetInheritanceRoot(); Type type3 = typeof(ISerializer<>).MakeGenericType(type2); type.AddInterfaceImplementation(type3); ILGenerator il = CompilerContextScope.Implement(type, type3, "Read"); using (CompilerContext compilerContext = new CompilerContext(scope, il, isStatic: false, CompilerContext.SignatureType.ReaderScope_Input, (TypeModel)(object)this, type2, "Read")) { if (serializer.HasInheritance) { serializer.EmitReadRoot(compilerContext, compilerContext.InputValue); } else { serializer.EmitRead(compilerContext, compilerContext.InputValue); compilerContext.LoadValue(compilerContext.InputValue); } compilerContext.Return(); } il = CompilerContextScope.Implement(type, type3, "Write"); using (CompilerContext compilerContext2 = new CompilerContext(scope, il, isStatic: false, CompilerContext.SignatureType.WriterScope_Input, (TypeModel)(object)this, type2, "Write")) { if (serializer.HasInheritance) { serializer.EmitWriteRoot(compilerContext2, compilerContext2.InputValue); } else { serializer.EmitWrite(compilerContext2, compilerContext2.InputValue); } compilerContext2.Return(); } MethodInfo getMethod = type3.GetProperty("Features").GetGetMethod(); type.DefineMethodOverride(GetFeaturesMethod(serializer.Features), getMethod); if (serializer.HasInheritance) { type3 = typeof(ISubTypeSerializer<>).MakeGenericType(type2); type.AddInterfaceImplementation(type3); il = CompilerContextScope.Implement(type, type3, "WriteSubType"); using (CompilerContext compilerContext3 = new CompilerContext(scope, il, isStatic: false, CompilerContext.SignatureType.WriterScope_Input, (TypeModel)(object)this, type2, "WriteSubType")) { serializer.EmitWrite(compilerContext3, compilerContext3.InputValue); compilerContext3.Return(); } il = CompilerContextScope.Implement(type, type3, "ReadSubType"); using CompilerContext compilerContext4 = new CompilerContext(scope, il, isStatic: false, CompilerContext.SignatureType.ReaderScope_Input, (TypeModel)(object)this, typeof(SubTypeState<>).MakeGenericType(type2), "ReadSubType"); serializer.EmitRead(compilerContext4, compilerContext4.InputValue); compilerContext4.Return(); } if (serializer.ShouldEmitCreateInstance) { type3 = typeof(IFactory<>).MakeGenericType(type2); type.AddInterfaceImplementation(type3); il = CompilerContextScope.Implement(type, type3, "Create"); using CompilerContext compilerContext5 = new CompilerContext(scope, il, isStatic: false, CompilerContext.SignatureType.Context, (TypeModel)(object)this, typeof(ISerializationContext), "Create"); serializer.EmitCreateInstance(compilerContext5, callNoteObject: false); compilerContext5.Return(); } } MethodInfo GetFeaturesMethod(SerializerFeatures features) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected I4, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected I4, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (!featuresLookup.TryGetValue(features, out var value)) { string name = "Features_" + ((int)features).ToString(CultureInfo.InvariantCulture); MethodBuilder methodBuilder = type.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Virtual, typeof(SerializerFeatures), Type.EmptyTypes); ILGenerator iLGenerator = methodBuilder.GetILGenerator(); CompilerContext.LoadValue(iLGenerator, (int)features); iLGenerator.Emit(OpCodes.Ret); return featuresLookup[features] = methodBuilder; } return value; } } private static TypeBuilder WriteBasicTypeModel(string typeName, ModuleBuilder module, Type baseType, bool @internal) { TypeAttributes typeAttributes = (baseType.Attributes & ~(TypeAttributes.Abstract | TypeAttributes.Serializable)) | TypeAttributes.Sealed; if (@internal) { typeAttributes &= ~TypeAttributes.Public; } return module.DefineType(typeName, typeAttributes, baseType); } private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm) { if (!string.IsNullOrEmpty(options.TargetFrameworkName)) { Type type = null; try { type = TypeModel.ResolveKnownType("System.Runtime.Versioning.TargetFrameworkAttribute", typeof(string).Assembly); } catch { } if ((object)type != null) { PropertyInfo[] namedProperties; object[] propertyValues; if (string.IsNullOrEmpty(options.TargetFrameworkDisplayName)) { namedProperties = Array.Empty(); propertyValues = Array.Empty(); } else { namedProperties = new PropertyInfo[1] { type.GetProperty("FrameworkDisplayName") }; propertyValues = new object[1] { options.TargetFrameworkDisplayName }; } CustomAttributeBuilder customAttribute = new CustomAttributeBuilder(type.GetConstructor(new Type[1] { typeof(string) }), new object[1] { options.TargetFrameworkName }, namedProperties, propertyValues); asm.SetCustomAttribute(customAttribute); } } Type type2 = null; try { type2 = typeof(InternalsVisibleToAttribute); } catch { } if ((object)type2 != null) { List list = new List(); List list2 = new List(); BasicList.NodeEnumerator enumerator = types.GetEnumerator(); while (enumerator.MoveNext()) { MetaType metaType = (MetaType)enumerator.Current; Assembly assembly = metaType.Type.Assembly; if (list2.IndexOf(assembly) >= 0) { continue; } list2.Add(assembly); AttributeMap[] array = AttributeMap.Create(assembly); for (int i = 0; i < array.Length; i++) { if (!(array[i].AttributeType != type2)) { array[i].TryGet("AssemblyName", out var value); string text = value as string; if (!(text == assemblyName) && !string.IsNullOrEmpty(text) && list.IndexOf(text) < 0) { list.Add(text); CustomAttributeBuilder customAttribute2 = new CustomAttributeBuilder(type2.GetConstructor(new Type[1] { typeof(string) }), new object[1] { text }); asm.SetCustomAttribute(customAttribute2); } } } } } WriteAssemblyInfoAttributes(options, asm); static void WriteAssemblyInfoAttribute(CompilerOptions compilerOptions, AssemblyBuilder assemblyBuilder, string text2) where TAttribute : Attribute { if (!string.IsNullOrEmpty(text2)) { Type typeFromHandle = typeof(TAttribute); Type[] array2 = new Type[1] { typeof(string) }; ConstructorInfo constructor = typeFromHandle.GetConstructor(array2); CustomAttributeBuilder customAttribute3 = new CustomAttributeBuilder(constructor, new object[1] { text2 }); assemblyBuilder.SetCustomAttribute(customAttribute3); } } static void WriteAssemblyInfoAttributes(CompilerOptions compilerOptions, AssemblyBuilder asm2) { WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyVersion?.ToString()); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyCompanyName); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyCopyright); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyDescription); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyProductName); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyTitle); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyTrademark); WriteAssemblyInfoAttribute(compilerOptions, asm2, compilerOptions.AssemblyProductVersion?.ToString()); } } internal bool IsPrepared(Type type) { return FindWithoutAdd(type)?.IsPrepared() ?? false; } internal void TakeLock(ref int opaqueToken) { opaqueToken = 0; if (Monitor.TryEnter(types, metadataTimeoutMilliseconds)) { opaqueToken = GetContention(); return; } AddContention(); throw new TimeoutException("Timeout while inspecting metadata; this may indicate a deadlock. This can often be avoided by preparing necessary serializers during application initialization, rather than allowing multiple threads to perform the initial metadata inspection; please also see the LockContended event"); } private int GetContention() { return Interlocked.CompareExchange(ref contentionCounter, 0, 0); } private void AddContention() { Interlocked.Increment(ref contentionCounter); } internal void ReleaseLock(int opaqueToken) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (opaqueToken == 0) { return; } Monitor.Exit(types); if (opaqueToken == GetContention()) { return; } LockContentedEventHandler lockContentedEventHandler = this.LockContended; if (lockContentedEventHandler != null) { string stackTrace; try { throw new ProtoException(); } catch (Exception ex) { stackTrace = ex.StackTrace; } lockContentedEventHandler(this, new LockContentedEventArgs(stackTrace)); } } internal string GetSchemaTypeName(HashSet callstack, Type effectiveType, DataFormat dataFormat, CompatibilityLevel compatibilityLevel, bool asReference, bool dynamicType, HashSet imports) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) string altName; return GetSchemaTypeName(callstack, effectiveType, dataFormat, compatibilityLevel, asReference, dynamicType, imports, out altName); } private static bool IsWrappersProtoType(Type type, out string name, HashSet imports) { name = null; if (type == typeof(double?)) { name = ".google.protobuf.DoubleValue"; } if (type == typeof(float?)) { name = ".google.protobuf.FloatValue"; } if (type == typeof(long?)) { name = ".google.protobuf.Int64Value"; } if (type == typeof(ulong?)) { name = ".google.protobuf.UInt64Value"; } if (type == typeof(int?)) { name = ".google.protobuf.Int32Value"; } if (type == typeof(uint?)) { name = ".google.protobuf.UInt32Value"; } if (type == typeof(bool?)) { name = ".google.protobuf.BoolValue"; } if (type == typeof(string)) { name = ".google.protobuf.StringValue"; } if (type == typeof(byte[])) { name = ".google.protobuf.BytesValue"; } if (name == null) { return false; } imports.Add("google/protobuf/wrappers.proto"); return true; } private static bool IsWellKnownType(Type type, out string name, HashSet imports) { if (TypeHelper.IsBytesLike(type)) { name = "bytes"; return true; } if (type == typeof(Timestamp)) { imports.Add("google/protobuf/timestamp.proto"); name = ".google.protobuf.Timestamp"; return true; } if (type == typeof(Duration)) { imports.Add("google/protobuf/duration.proto"); name = ".google.protobuf.Duration"; return true; } if (type == typeof(Empty)) { imports.Add("google/protobuf/empty.proto"); name = ".google.protobuf.Empty"; return true; } name = null; return false; } internal string GetSchemaTypeName(HashSet callstack, Type effectiveType, DataFormat dataFormat, CompatibilityLevel compatibilityLevel, bool asReference, bool dynamicType, HashSet imports, out string altName, bool considerWrappersProtoTypes = false) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected I4, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Invalid comparison between Unknown and I4 //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Invalid comparison between Unknown and I4 //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Invalid comparison between Unknown and I4 //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Invalid comparison between Unknown and I4 //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Invalid comparison between Unknown and I4 //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Invalid comparison between Unknown and I4 //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Expected I4, but got Unknown //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Invalid comparison between Unknown and I4 //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Invalid comparison between Unknown and I4 //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Invalid comparison between Unknown and I4 //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Invalid comparison between Unknown and I4 //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_02c9: Invalid comparison between Unknown and I4 //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Invalid comparison between Unknown and I4 //IL_010f: Unknown result type (might be due to invalid IL or missing references) altName = null; if (considerWrappersProtoTypes && IsWrappersProtoType(effectiveType, out var name, imports)) { return name; } compatibilityLevel = ValueMember.GetEffectiveCompatibilityLevel(compatibilityLevel, dataFormat); effectiveType = DynamicStub.GetEffectiveType(effectiveType); if (IsWellKnownType(effectiveType, out var name2, imports)) { return name2; } WireType defaultWireType; IRuntimeProtoSerializerNode runtimeProtoSerializerNode = ValueMember.TryGetCoreSerializer(this, dataFormat, compatibilityLevel, effectiveType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false); if (runtimeProtoSerializerNode == null) { if (asReference || dynamicType) { imports.Add("protobuf-net/bcl.proto"); return ".bcl.NetObjectProxy"; } MetaType metaType = this[effectiveType]; if (metaType.HasSurrogate && ValueMember.TryGetCoreSerializer(this, metaType.surrogateDataFormat, metaType.CompatibilityLevel, metaType.surrogateType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false) != null) { return GetSchemaTypeName(callstack, metaType.surrogateType, metaType.surrogateDataFormat, metaType.CompatibilityLevel, asReference: false, dynamicType: false, imports); } MetaType surrogateOrBaseOrSelf = metaType.GetSurrogateOrBaseOrSelf(deep: true); if (IsWellKnownType(surrogateOrBaseOrSelf.Type, out name2, imports)) { return name2; } string schemaTypeName = surrogateOrBaseOrSelf.GetSchemaTypeName(callstack); if (metaType.Type.IsEnum && !metaType.IsValidEnum()) { altName = schemaTypeName; schemaTypeName = GetSchemaTypeName(callstack, Enum.GetUnderlyingType(metaType.Type), dataFormat, (CompatibilityLevel)0, asReference, dynamicType, imports); } return schemaTypeName; } if (runtimeProtoSerializerNode is ParseableSerializer) { if (asReference) { imports.Add("protobuf-net/bcl.proto"); } if (!asReference) { return "string"; } return ".bcl.NetObjectProxy"; } ProtoTypeCode typeCode = Helpers.GetTypeCode(effectiveType); switch (typeCode - 3) { default: switch (typeCode - 100) { case 9: break; case 8: goto IL_0259; case 0: goto IL_02b8; case 2: goto IL_0313; case 4: return "string"; case 3: return "string"; default: goto end_IL_0156; } goto case 9; case 0: return "bool"; case 10: return "float"; case 11: return "double"; case 15: if (asReference) { imports.Add("protobuf-net/bcl.proto"); } if (!asReference) { return "string"; } return ".bcl.NetObjectProxy"; case 1: case 3: case 5: case 7: if ((int)dataFormat == 3) { return "fixed32"; } return "uint32"; case 2: case 4: case 6: if ((int)dataFormat != 1) { if ((int)dataFormat == 3) { return "sfixed32"; } return "int32"; } return "sint32"; case 9: if ((int)dataFormat == 3) { return "fixed64"; } return "uint64"; case 8: goto IL_0259; case 13: if ((int)dataFormat == 3) { return "sint64"; } if ((int)compatibilityLevel >= 240) { imports.Add("google/protobuf/timestamp.proto"); return ".google.protobuf.Timestamp"; } imports.Add("protobuf-net/bcl.proto"); return ".bcl.DateTime"; case 12: if ((int)compatibilityLevel < 300) { imports.Add("protobuf-net/bcl.proto"); return ".bcl.Decimal"; } return "string"; case 14: break; IL_0313: if ((int)compatibilityLevel < 300) { imports.Add("protobuf-net/bcl.proto"); return ".bcl.Guid"; } if ((int)dataFormat != 3) { return "string"; } return "bytes"; IL_02b8: if ((int)dataFormat == 3) { return "sint64"; } if ((int)compatibilityLevel >= 240) { imports.Add("google/protobuf/duration.proto"); return ".google.protobuf.Duration"; } imports.Add("protobuf-net/bcl.proto"); return ".bcl.TimeSpan"; IL_0259: if ((int)dataFormat != 1) { if ((int)dataFormat == 3) { return "sfixed64"; } return "int64"; } return "sint64"; end_IL_0156: break; } throw new NotSupportedException("No .proto map found for: " + effectiveType.FullName); } public void SetDefaultFactory(MethodInfo methodInfo) { VerifyFactory(methodInfo, null); defaultFactory = methodInfo; } internal static void VerifyFactory(MethodInfo factory, Type type) { if ((object)factory != null) { if ((object)type != null && type.IsValueType) { throw new InvalidOperationException(); } if (!factory.IsStatic) { throw new ArgumentException("A factory-method must be static", "factory"); } if ((object)type != null && factory.ReturnType != type && factory.ReturnType != typeof(object)) { throw new ArgumentException("The factory-method must return object" + (((object)type == null) ? "" : (" or " + type.FullName)), "factory"); } if (!CallbackSet.CheckCallbackParameters(factory)) { throw new ArgumentException("Invalid factory signature in " + factory.DeclaringType.FullName + "." + factory.Name, "factory"); } } } public static RuntimeTypeModel Create([CallerMemberName] string name = null) { return new RuntimeTypeModel(isDefault: false, name); } internal static bool IsFullyPublic(Type type) { Type cause; return IsFullyPublic(type, out cause); } internal static bool IsFullyPublic(Type type, out Type cause) { Type type2 = type; while ((object)type != null) { if (type.IsGenericType) { Type[] genericArguments = type.GetGenericArguments(); Type[] array = genericArguments; foreach (Type type3 in array) { if (!IsFullyPublic(type3)) { cause = type3; return false; } } } cause = type; if (type.IsNestedPublic) { type = type.DeclaringType; continue; } return type.IsPublic; } cause = type2; return false; } public static TypeModel CreateForAssembly() { return AutoCompileTypeModel.CreateForAssembly(); } public static TypeModel CreateForAssembly(Type type) { return AutoCompileTypeModel.CreateForAssembly(type); } public static TypeModel CreateForAssembly(Assembly assembly) { return AutoCompileTypeModel.CreateForAssembly(assembly); } public void MakeDefault() { lock (s_ModelSyncLock) { RuntimeTypeModel runtimeTypeModel = TypeModel.DefaultModel as RuntimeTypeModel; if (this == runtimeTypeModel) { return; } try { SetOption(RuntimeTypeModelOptions.IsDefaultModel, value: true); if (!UseImplicitZeroDefaults) { ThrowDefaultUseImplicitZeroDefaults(); } if (!AutoAddMissingTypes) { ThrowDefaultAutoAddMissingTypes(); } if (GetOption(RuntimeTypeModelOptions.Frozen)) { ThrowDefaultFrozen(); } TypeModel.SetDefaultModel((TypeModel)(object)this); } finally { TypeModel defaultModel = TypeModel.DefaultModel; if ((object)this != defaultModel) { SetOption(RuntimeTypeModelOptions.IsDefaultModel, value: false); } if (runtimeTypeModel != null && (object)runtimeTypeModel != defaultModel) { runtimeTypeModel.SetOption(RuntimeTypeModelOptions.IsDefaultModel, value: false); } } } } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowDefaultAutoAddMissingTypes() { throw new InvalidOperationException("The default model must allow missing types"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowDefaultUseImplicitZeroDefaults() { throw new InvalidOperationException("UseImplicitZeroDefaults cannot be disabled on the default model"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowDefaultFrozen() { throw new InvalidOperationException("The default model cannot be frozen"); } [MethodImpl(MethodImplOptions.NoInlining)] private static RuntimeTypeModel CreateDefaultModelInstance() { lock (s_ModelSyncLock) { RuntimeTypeModel runtimeTypeModel = TypeModel.DefaultModel as RuntimeTypeModel; if (runtimeTypeModel == null) { runtimeTypeModel = new RuntimeTypeModel(isDefault: true, "(default)"); TypeModel.SetDefaultModel((TypeModel)(object)runtimeTypeModel); } return runtimeTypeModel; } } public RuntimeTypeModel SetSurrogate(Func underlyingToSurrogate = null, Func surrogateToUnderlying = null, DataFormat dataFormat = (DataFormat)0, CompatibilityLevel compatibilityLevel = (CompatibilityLevel)0) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) Add(applyDefaultBehaviour: true, compatibilityLevel).SetSurrogate(typeof(TSurrogate), GetMethod(underlyingToSurrogate, "underlyingToSurrogate"), GetMethod(surrogateToUnderlying, "surrogateToUnderlying"), dataFormat); return this; static MethodInfo GetMethod(Delegate value, string paramName) { if ((object)value == null) { return null; } Delegate[] invocationList = value.GetInvocationList(); if (invocationList.Length != 1) { ThrowHelper.ThrowArgumentException("A unicast delegate was expected.", paramName); } value = invocationList[0]; object target = value.Target; if (target != null) { string text = "A delegate to a static method was expected."; if (target.GetType().IsDefined(typeof(CompilerGeneratedAttribute))) { text = text + " The conversion '" + TypeHelper.NormalizeName(target.GetType()) + "." + value.Method.Name + "' is compiler-generated (possibly a lambda); an explicit static method should be used instead."; } ThrowHelper.ThrowArgumentException(text, paramName); } return value.Method; } } public RuntimeTypeModel AddSerializer(Type collectionType, Type serializerType) { Type type = collectionType; if (type.IsGenericType) { type = type.GetGenericTypeDefinition(); } lock (_serviceCache) { if (_externalProviders == null) { _externalProviders = new Hashtable(); } } if (!_externalProviders.ContainsKey(type)) { RepeatedSerializers.Add(type, (Type root, Type current, Type[] targs) => RepeatedSerializers.Resolve(serializerType, "Create", targs), exactOnly: true, _externalProviders); } return this; } } public sealed class LockContentedEventArgs : EventArgs { public string OwnerStackTrace { get; } internal LockContentedEventArgs(string ownerStackTrace) { OwnerStackTrace = ownerStackTrace; } } public delegate void LockContentedEventHandler(object sender, LockContentedEventArgs args); public sealed class SubType { internal sealed class Comparer : IComparer, IComparer { public static readonly Comparer Default = new Comparer(); public int Compare(object x, object y) { return Compare(x as SubType, y as SubType); } public int Compare(SubType x, SubType y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } return x.FieldNumber.CompareTo(y.FieldNumber); } } private int _fieldNumber; private readonly MetaType derivedType; private readonly DataFormat dataFormat; private IRuntimeProtoSerializerNode serializer; public int FieldNumber { get { return _fieldNumber; } internal set { if (_fieldNumber != value) { MetaType.AssertValidFieldNumber(value); ThrowIfFrozen(); _fieldNumber = value; } } } public MetaType DerivedType => derivedType; private void ThrowIfFrozen() { if (serializer != null) { throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); } } public SubType(int fieldNumber, MetaType derivedType, DataFormat format) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (fieldNumber <= 0) { throw new ArgumentOutOfRangeException("fieldNumber"); } _fieldNumber = fieldNumber; this.derivedType = derivedType ?? throw new ArgumentNullException("derivedType"); dataFormat = format; } internal IRuntimeProtoSerializerNode GetSerializer(Type parentType) { return serializer ?? (serializer = BuildSerializer(parentType)); } private IRuntimeProtoSerializerNode BuildSerializer(Type parentType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) WireType wireType = (WireType)2; if ((int)dataFormat == 4) { wireType = (WireType)3; } IRuntimeProtoSerializerNode tail = SubItemSerializer.Create(derivedType.Type, derivedType, parentType); return new TagDecorator(_fieldNumber, wireType, strict: false, tail); } } public sealed class TypeAddedEventArgs : EventArgs { public bool ApplyDefaultBehaviour { get; set; } public MetaType MetaType { get; } public Type Type => MetaType.Type; public RuntimeTypeModel Model => MetaType.Model; internal TypeAddedEventArgs(MetaType metaType) { MetaType = metaType; ApplyDefaultBehaviour = true; } } public class ValueMember { internal sealed class Comparer : IComparer, IComparer { public static readonly Comparer Default = new Comparer(); public int Compare(object x, object y) { return Compare(x as ValueMember, y as ValueMember); } public int Compare(ValueMember x, ValueMember y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } return x.FieldNumber.CompareTo(y.FieldNumber); } } private int _fieldNumber; private MemberInfo backingMember; private object _defaultValue; private CompatibilityLevel _compatibilityLevel; private readonly RuntimeTypeModel model; private IRuntimeProtoSerializerNode serializer; private DataFormat dataFormat; private DataFormat mapKeyFormat; private DataFormat mapValueFormat; private MethodInfo getSpecified; private MethodInfo setSpecified; private string name; private const ushort OPTIONS_IsStrict = 1; private const ushort OPTIONS_IsPacked = 2; private const ushort OPTIONS_IsRequired = 4; private const ushort OPTIONS_OverwriteList = 8; private const ushort OPTIONS_NullWrappedValue = 16; private const ushort OPTIONS_NullWrappedValueGroup = 32; private const ushort OPTIONS_IsMap = 64; private const ushort OPTIONS_NullWrappedCollection = 128; private const ushort OPTIONS_NullWrappedCollectionGroup = 256; private const ushort OPTIONS_SupportNull = 512; private ushort flags; public int FieldNumber { get { return _fieldNumber; } internal set { if (_fieldNumber != value) { MetaType.AssertValidFieldNumber(value); ThrowIfFrozen(); _fieldNumber = value; } } } public MemberInfo Member { get; } public MemberInfo BackingMember { get { return backingMember; } set { if (backingMember != value) { ThrowIfFrozen(); backingMember = value; } } } public Type ItemType { get; } public Type MemberType { get; } public Type DefaultType { get; } public Type ParentType { get; } public object DefaultValue { get { return _defaultValue; } set { if (_defaultValue != value) { ThrowIfFrozen(); _defaultValue = value; } } } public CompatibilityLevel CompatibilityLevel { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return _compatibilityLevel; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (_compatibilityLevel != value) { ThrowIfFrozen(); CompatibilityLevelAttribute.AssertValid(value); _compatibilityLevel = value; } } } internal IRuntimeProtoSerializerNode Serializer => serializer ?? (serializer = BuildSerializer()); public DataFormat DataFormat { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return dataFormat; } set { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (value != dataFormat) { ThrowIfFrozen(); dataFormat = value; } } } public bool IsStrict { get { return HasFlag(1); } set { SetFlag(1, value); } } public bool IsPacked { get { return HasFlag(2); } set { SetFlag(2, value); } } public bool OverwriteList { get { return HasFlag(8); } set { SetFlag(8, value); } } public bool IsRequired { get { return HasFlag(4); } set { SetFlag(4, value); } } public bool AsReference { get { return false; } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] set { if (value != AsReference) { ThrowHelper.ThrowNotSupportedException(); } } } public bool DynamicType { get { return false; } [Obsolete("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited", true)] set { if (value != DynamicType) { ThrowHelper.ThrowNotSupportedException(); } } } public bool IsMap { get { return HasFlag(64); } set { SetFlag(64, value); } } public DataFormat MapKeyFormat { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return mapKeyFormat; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (mapKeyFormat != value) { ThrowIfFrozen(); mapKeyFormat = value; } } } public DataFormat MapValueFormat { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return mapValueFormat; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (mapValueFormat != value) { ThrowIfFrozen(); mapValueFormat = value; } } } public string Name { get { if (!string.IsNullOrEmpty(name)) { return name; } return Member.Name; } set { SetName(value); } } public bool SupportNull { get { return HasFlag(512); } set { SetFlag(512, value); } } internal bool NullWrappedValue { get { return HasFlag(16); } set { SetFlag(16, value); } } internal bool NullWrappedValueGroup { get { return HasFlag(32); } set { SetFlag(32, value); } } internal bool NullWrappedCollection { get { return HasFlag(128); } set { SetFlag(128, value); } } internal bool NullWrappedCollectionGroup { get { return HasFlag(256); } set { SetFlag(256, value); } } internal bool RequiresGroupModifier { get { if (!SupportNull) { return NullWrappedValueGroup; } return true; } } internal static CompatibilityLevel GetEffectiveCompatibilityLevel(CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if ((int)compatibilityLevel <= 200) { if ((int)dataFormat == 5) { return (CompatibilityLevel)240; } return (CompatibilityLevel)200; } return compatibilityLevel; } public ValueMember(RuntimeTypeModel model, Type parentType, int fieldNumber, MemberInfo member, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat, object defaultValue) : this(model, fieldNumber, memberType, itemType, defaultType, dataFormat) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if ((object)parentType == null) { throw new ArgumentNullException("parentType"); } if (fieldNumber < 1 && !parentType.IsEnum) { throw new ArgumentOutOfRangeException("fieldNumber"); } Member = member ?? throw new ArgumentNullException("member"); ParentType = parentType; if (fieldNumber < 1 && !parentType.IsEnum) { throw new ArgumentOutOfRangeException("fieldNumber"); } if (defaultValue != null && defaultValue.GetType() != memberType) { defaultValue = ParseDefaultValue(memberType, defaultValue); } _defaultValue = defaultValue; } internal ValueMember(RuntimeTypeModel model, int fieldNumber, Type memberType, Type itemType, Type defaultType, DataFormat dataFormat) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) FieldNumber = fieldNumber; MemberType = memberType ?? throw new ArgumentNullException("memberType"); ItemType = itemType; if ((object)defaultType == null && (object)itemType != null) { defaultType = memberType; } DefaultType = defaultType; this.model = model ?? throw new ArgumentNullException("model"); this.dataFormat = dataFormat; } internal object GetRawEnumValue() { return ((FieldInfo)Member).GetRawConstantValue(); } private static object ParseDefaultValue(Type type, object value) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Invalid comparison between Unknown and I4 //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected I4, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Invalid comparison between Unknown and I4 //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected I4, but got Unknown Type underlyingType = Nullable.GetUnderlyingType(type); if ((object)underlyingType != null) { type = underlyingType; } if (value is string text) { if (type.IsEnum) { return Enum.Parse(type, text, ignoreCase: true); } ProtoTypeCode typeCode = Helpers.GetTypeCode(type); if ((int)typeCode <= 103) { switch (typeCode - 3) { default: switch (typeCode - 100) { case 0: return TimeSpan.Parse(text); case 3: return text; case 2: return new Guid(text); } break; case 0: return bool.Parse(text); case 3: return byte.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture); case 1: if (text.Length == 1) { return text[0]; } throw new FormatException("Single character expected: \"" + text + "\""); case 13: return DateTime.Parse(text, CultureInfo.InvariantCulture); case 12: return decimal.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 11: return double.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 4: return short.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 6: return int.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 8: return long.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 2: return sbyte.Parse(text, NumberStyles.Integer, CultureInfo.InvariantCulture); case 10: return float.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 15: return text; case 5: return ushort.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 7: return uint.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 9: return ulong.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture); case 14: break; } } else { if ((int)typeCode == 108) { return new IntPtr(long.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture)); } if ((int)typeCode == 109) { return new UIntPtr(ulong.Parse(text, NumberStyles.Any, CultureInfo.InvariantCulture)); } } } if (type.IsEnum) { return Enum.ToObject(type, value); } try { return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } catch (InvalidCastException) when (type == typeof(IntPtr)) { return new IntPtr((long)Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture)); } catch (InvalidCastException) when (type == typeof(UIntPtr)) { return new UIntPtr((ulong)Convert.ChangeType(value, typeof(ulong), CultureInfo.InvariantCulture)); } } public void SetSpecified(MethodInfo getSpecified, MethodInfo setSpecified) { if (this.getSpecified != getSpecified || this.setSpecified != setSpecified) { if ((object)getSpecified != null && (getSpecified.ReturnType != typeof(bool) || getSpecified.IsStatic || getSpecified.GetParameters().Length != 0)) { throw new ArgumentException("Invalid pattern for checking member-specified", "getSpecified"); } ParameterInfo[] parameters; if ((object)setSpecified != null && (setSpecified.ReturnType != typeof(void) || setSpecified.IsStatic || (parameters = setSpecified.GetParameters()).Length != 1 || parameters[0].ParameterType != typeof(bool))) { throw new ArgumentException("Invalid pattern for setting member-specified", "setSpecified"); } ThrowIfFrozen(); this.getSpecified = getSpecified; this.setSpecified = setSpecified; } } private void ThrowIfFrozen() { if (serializer != null) { throw new InvalidOperationException("The type cannot be changed once a serializer has been generated"); } } internal static IRuntimeProtoSerializerNode CreateMap(RepeatedSerializerStub repeated, RuntimeTypeModel model, DataFormat dataFormat, CompatibilityLevel compatibilityLevel, DataFormat keyFormat, DataFormat valueFormat, bool asReference, bool dynamicType, bool isMap, bool overwriteList, int fieldNumber, ValueMember member) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Invalid comparison between Unknown and I4 //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) CompatibilityLevel effectiveCompatibilityLevel = GetEffectiveCompatibilityLevel(compatibilityLevel, keyFormat); CompatibilityLevel effectiveCompatibilityLevel2 = GetEffectiveCompatibilityLevel(compatibilityLevel, valueFormat); repeated.ResolveMapTypes(out var keyType, out var valueType); TryGetCoreSerializer(model, keyFormat, effectiveCompatibilityLevel, FlattenRepeated(model, keyType), out var defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: true); TryGetCoreSerializer(model, valueFormat, effectiveCompatibilityLevel2, FlattenRepeated(model, valueType), out var defaultWireType2, asReference, dynamicType, overwriteList: false, allowComplexTypes: true); WireType val = (WireType)(((int)dataFormat == 4) ? 3 : 2); SerializerFeatures listFeatures = SerializerFeaturesExtensions.AsFeatures(val); if (!isMap) { listFeatures = (SerializerFeatures)(listFeatures | 0x200); } if (overwriteList) { listFeatures = (SerializerFeatures)(listFeatures | 0x100); } member?.ComposeListFeatures(ref listFeatures); SerializerFeatures val2 = SerializerFeaturesExtensions.AsFeatures(defaultWireType2); val2 = (SerializerFeatures)(val2 | (listFeatures & 0x1800)); listFeatures = (SerializerFeatures)(listFeatures & -6145); return MapDecorator.Create(repeated, keyType, valueType, fieldNumber, listFeatures, SerializerFeaturesExtensions.AsFeatures(defaultWireType), effectiveCompatibilityLevel, keyFormat, val2, effectiveCompatibilityLevel2, valueFormat); static Type FlattenRepeated(RuntimeTypeModel runtimeTypeModel, Type type) { if ((object)type == null) { return type; } RepeatedSerializerStub repeatedSerializerStub = ((runtimeTypeModel == null) ? RepeatedSerializers.TryGetRepeatedProvider(type) : runtimeTypeModel.TryGetRepeatedProvider(type, (CompatibilityLevel)0)); if (repeatedSerializerStub != null) { return repeatedSerializerStub.ItemType; } return type; } } private void ComposeListFeatures(ref SerializerFeatures listFeatures) { if (!IsPacked) { listFeatures = (SerializerFeatures)((uint)listFeatures | 0x80u); } if (OverwriteList) { listFeatures = (SerializerFeatures)((uint)listFeatures | 0x100u); } if (SupportNull) { if (NullWrappedValue || NullWrappedCollection || IsPacked) { ThrowHelper.ThrowNotSupportedException("SupportNull cannot be combined with IsPacked, NullWrappedValue or NullWrappedCollection"); } listFeatures = (SerializerFeatures)((uint)listFeatures | 0x1800u); return; } if (NullWrappedCollection) { listFeatures = (SerializerFeatures)((uint)listFeatures | 0x4000u); if (NullWrappedCollectionGroup) { listFeatures = (SerializerFeatures)((uint)listFeatures | 0x8000u); } } if (NullWrappedValue) { listFeatures = (SerializerFeatures)((uint)listFeatures | 0x2800u); if (NullWrappedValueGroup) { listFeatures = (SerializerFeatures)((uint)listFeatures | 0x1000u); } } } private IRuntimeProtoSerializerNode BuildSerializer() { //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) int opaqueToken = 0; try { model.TakeLock(ref opaqueToken); MemberInfo memberInfo = backingMember ?? Member; RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(MemberType, (CompatibilityLevel)0); IRuntimeProtoSerializerNode runtimeProtoSerializerNode; if (repeatedSerializerStub != null) { if (repeatedSerializerStub.IsMap) { runtimeProtoSerializerNode = CreateMap(repeatedSerializerStub, model, DataFormat, CompatibilityLevel, MapKeyFormat, MapValueFormat, AsReference, DynamicType, IsMap, OverwriteList, FieldNumber, this); } else { TryGetCoreSerializer(model, DataFormat, CompatibilityLevel, repeatedSerializerStub.ItemType, out var defaultWireType, AsReference, DynamicType, OverwriteList, allowComplexTypes: true); SerializerFeatures listFeatures = SerializerFeaturesExtensions.AsFeatures(defaultWireType); ComposeListFeatures(ref listFeatures); runtimeProtoSerializerNode = RepeatedDecorator.Create(repeatedSerializerStub, FieldNumber, listFeatures, CompatibilityLevel, DataFormat); } } else { if (NullWrappedCollection) { ThrowHelper.ThrowNotSupportedException("NullWrappedCollection can only be used with collection types"); } runtimeProtoSerializerNode = TryGetCoreSerializer(model, DataFormat, CompatibilityLevel, MemberType, out var defaultWireType2, AsReference, DynamicType, OverwriteList, allowComplexTypes: true); if (runtimeProtoSerializerNode == null) { ThrowHelper.NoSerializerDefined(MemberType); } if (NullWrappedValue) { SerializerFeatures val = (SerializerFeatures)2048; if (NullWrappedValueGroup) { val = (SerializerFeatures)(val | 0x1000); } if (MemberType.IsValueType && (object)Nullable.GetUnderlyingType(MemberType) == null) { ThrowHelper.ThrowNotSupportedException("NullWrappedValue cannot be used with non-nullable values"); } if (_defaultValue != null) { ThrowHelper.ThrowNotSupportedException("NullWrappedValue cannot be used with default values"); } if (IsRequired) { ThrowHelper.ThrowNotSupportedException("NullWrappedValue cannot be used with required values"); } if (IsPacked) { ThrowHelper.ThrowNotSupportedException("NullWrappedValue cannot be used with packed values"); } if ((int)DataFormat != 0) { ThrowHelper.ThrowNotSupportedException("NullWrappedValue can only be used with DataFormat.Default"); } if (!runtimeProtoSerializerNode.IsScalar) { ThrowHelper.ThrowNotSupportedException("NullWrappedValue can only be used with scalar types, or in a collection"); } runtimeProtoSerializerNode = AnyTypeSerializer.Create(MemberType, val, CompatibilityLevel, DataFormat); } runtimeProtoSerializerNode = new TagDecorator(FieldNumber, defaultWireType2, IsStrict, runtimeProtoSerializerNode); if (_defaultValue != null && !IsRequired && (object)getSpecified == null) { runtimeProtoSerializerNode = new DefaultValueDecorator(_defaultValue, runtimeProtoSerializerNode); } if (MemberType == typeof(Uri)) { runtimeProtoSerializerNode = new UriDecorator(runtimeProtoSerializerNode); } } if ((object)memberInfo != null) { if (memberInfo is PropertyInfo property) { runtimeProtoSerializerNode = new PropertyDecorator(ParentType, property, runtimeProtoSerializerNode); } else { if (!(memberInfo is FieldInfo field)) { throw new InvalidOperationException(); } runtimeProtoSerializerNode = new FieldDecorator(ParentType, field, runtimeProtoSerializerNode); } if ((object)getSpecified != null || (object)setSpecified != null) { runtimeProtoSerializerNode = new MemberSpecifiedDecorator(getSpecified, setSpecified, runtimeProtoSerializerNode); } } return runtimeProtoSerializerNode; } finally { model.ReleaseLock(opaqueToken); } } private static WireType GetIntWireType(DataFormat format, int width) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown switch ((int)format) { case 1: return (WireType)8; case 3: if (width == 32) { return (WireType)5; } return (WireType)1; case 2: case 5: return (WireType)0; case 0: return (WireType)0; default: throw new InvalidOperationException(); } } private static WireType GetDateTimeWireType(DataFormat format) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown switch ((int)format) { case 4: return (WireType)3; case 3: return (WireType)1; case 0: case 5: return (WireType)2; default: throw new InvalidOperationException(); } } internal static IRuntimeProtoSerializerNode TryGetCoreSerializer(RuntimeTypeModel model, DataFormat dataFormat, CompatibilityLevel compatibilityLevel, Type type, out WireType defaultWireType, bool asReference, bool dynamicType, bool overwriteList, bool allowComplexTypes) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected I4, but got Unknown //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Expected I4, but got Unknown //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Expected I4, but got Unknown //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Expected I4, but got Unknown //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Expected I4, but got Unknown //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected I4, but got Unknown //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected I4, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected I4, but got Unknown //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Expected I4, but got Unknown //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Expected I4, but got Unknown //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected I4, but got Unknown //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Expected I4, but got Unknown //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Invalid comparison between Unknown and I4 //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Expected I4, but got Unknown //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected I4, but got Unknown //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Invalid comparison between Unknown and I4 //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Invalid comparison between Unknown and I4 //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Expected I4, but got Unknown compatibilityLevel = GetEffectiveCompatibilityLevel(compatibilityLevel, dataFormat); type = DynamicStub.GetEffectiveType(type); if (type.IsEnum) { if (allowComplexTypes && model != null) { defaultWireType = (WireType)0; return new EnumMemberSerializer(type); } defaultWireType = (WireType)(-1); return null; } ProtoTypeCode typeCode = Helpers.GetTypeCode(type); switch (typeCode - 3) { default: switch (typeCode - 100) { case 0: defaultWireType = (WireType)(int)GetDateTimeWireType(dataFormat); return TimeSpanSerializer.Create(compatibilityLevel); case 2: defaultWireType = (WireType)(((int)dataFormat == 4 && (int)compatibilityLevel < 300) ? 3 : 2); return GuidSerializer.Create(compatibilityLevel, dataFormat); case 3: defaultWireType = (WireType)2; return StringSerializer.Instance; case 1: defaultWireType = (WireType)2; return new BlobSerializer(overwriteList); case 5: defaultWireType = (WireType)2; return new BlobSerializer>(overwriteList); case 6: defaultWireType = (WireType)2; return new BlobSerializer>(overwriteList); case 7: defaultWireType = (WireType)2; return new BlobSerializer>(overwriteList); case 4: defaultWireType = (WireType)2; return SystemTypeSerializer.Instance; case 8: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 64); return IntPtrSerializer.Instance; case 9: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 64); return UIntPtrSerializer.Instance; } break; case 6: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 32); return Int32Serializer.Instance; case 7: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 32); return UInt32Serializer.Instance; case 8: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 64); return Int64Serializer.Instance; case 9: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 64); return UInt64Serializer.Instance; case 15: defaultWireType = (WireType)2; if (asReference) { ThrowHelper.ThrowNotSupportedException("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited"); return null; } return StringSerializer.Instance; case 10: defaultWireType = (WireType)5; return SingleSerializer.Instance; case 11: defaultWireType = (WireType)1; return DoubleSerializer.Instance; case 0: defaultWireType = (WireType)0; return BooleanSerializer.Instance; case 13: defaultWireType = (WireType)(int)GetDateTimeWireType(dataFormat); return DateTimeSerializer.Create(compatibilityLevel, (TypeModel)(object)model); case 12: defaultWireType = (WireType)2; return DecimalSerializer.Create(compatibilityLevel); case 3: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 32); return ByteSerializer.Instance; case 2: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 32); return SByteSerializer.Instance; case 1: defaultWireType = (WireType)0; return CharSerializer.Instance; case 4: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 32); return Int16Serializer.Instance; case 5: defaultWireType = (WireType)(int)GetIntWireType(dataFormat, 32); return UInt16Serializer.Instance; case 14: break; } IRuntimeProtoSerializerNode runtimeProtoSerializerNode = (model.AllowParseableTypes ? ParseableSerializer.TryCreate(type) : null); if (runtimeProtoSerializerNode != null) { defaultWireType = (WireType)2; return runtimeProtoSerializerNode; } if (allowComplexTypes && model != null) { MetaType metaType = null; if (((TypeModel)model).IsDefined(type, compatibilityLevel)) { metaType = model.FindWithAmbientCompatibility(type, compatibilityLevel); if ((int)dataFormat == 0 && metaType.IsGroup) { dataFormat = (DataFormat)4; } } if (asReference || dynamicType) { ThrowHelper.ThrowNotSupportedException("Reference-tracking and dynamic-type are not currently implemented in this build; they may be reinstated later; this is partly due to doubts over whether the features are adviseable, and partly over confidence in testing all the scenarios (it takes time; that time hasn't get happened); feedback is invited"); defaultWireType = (WireType)0; return null; } if (metaType != null) { IProtoTypeSerializer protoTypeSerializer; if (metaType.HasSurrogate && (int)SerializerFeaturesExtensions.GetCategory((protoTypeSerializer = metaType.Serializer).Features) == 32) { dataFormat = metaType.surrogateDataFormat; if (TryGetCoreSerializer(model, dataFormat, metaType.CompatibilityLevel, metaType.surrogateType, out defaultWireType, asReference: false, dynamicType: false, overwriteList: false, allowComplexTypes: false) == null) { defaultWireType = (WireType)(int)SerializerFeaturesExtensions.GetWireType(protoTypeSerializer.Features); } return protoTypeSerializer; } return SubItemSerializer.Create(type, metaType, ref dataFormat, out defaultWireType); } } defaultWireType = (WireType)(-1); return null; } internal void SetName(string name) { if (name != this.name) { ThrowIfFrozen(); this.name = name; } } private bool HasFlag(ushort flag) { return (flags & flag) == flag; } private void SetFlag(ushort flag, bool value, bool throwIfFrozen = true) { if (throwIfFrozen && HasFlag(flag) != value) { ThrowIfFrozen(); } if (value) { flags |= flag; } else { flags = (ushort)(flags & ~flag); } } internal bool HasExtendedNullSupport() { if (!SupportNull && !NullWrappedValueGroup) { return NullWrappedValue; } return true; } internal bool RequiresExtraLayerInSchema() { if ((object)ItemType != null) { return HasExtendedNullSupport(); } return false; } internal string GetSchemaTypeName(HashSet callstack, bool applyNetObjectProxy, HashSet imports, out string altName, bool considerWrappersProtoTypes = false) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) Type effectiveType = ItemType ?? MemberType; return model.GetSchemaTypeName(callstack, effectiveType, DataFormat, CompatibilityLevel, applyNetObjectProxy && AsReference, applyNetObjectProxy && DynamicType, imports, out altName, considerWrappersProtoTypes); } } } namespace ProtoBuf.Internal { internal sealed class BasicList : IEnumerable { [StructLayout(LayoutKind.Auto)] public struct NodeEnumerator : IEnumerator { private int position; private readonly Node node; public readonly object Current => node[position]; internal NodeEnumerator(Node node) { position = -1; this.node = node; } void IEnumerator.Reset() { position = -1; } public bool MoveNext() { int length = node.Length; if (position <= length) { return ++position < length; } return false; } } [StructLayout(LayoutKind.Auto)] internal readonly struct Node { private readonly object[] data; public object this[int index] { get { if (index >= 0 && index < Length) { return data[index]; } throw new ArgumentOutOfRangeException("index"); } set { if (index >= 0 && index < Length) { data[index] = value; return; } throw new ArgumentOutOfRangeException("index"); } } public int Length { get; } internal Node(object[] data, int length) { this.data = data; Length = length; } public Node Append(object value) { int length = Length + 1; object[] array; if (data == null) { array = new object[10]; } else if (Length == data.Length) { array = new object[data.Length * 2]; Array.Copy(data, array, Length); } else { array = data; } array[Length] = value; return new Node(array, length); } internal int IndexOfReference(object instance) { for (int i = 0; i < Length; i++) { if (instance == data[i]) { return i; } } return -1; } internal int IndexOf(MatchPredicate predicate, object ctx) { for (int i = 0; i < Length; i++) { if (predicate(data[i], ctx)) { return i; } } return -1; } } internal delegate bool MatchPredicate(object value, object ctx); [StructLayout(LayoutKind.Auto)] internal readonly struct Group { public readonly int First; public readonly List Items; public bool IsEmpty => Items == null; public Group(int first) { First = first; Items = new List(); } } private static readonly Node nil = new Node(null, 0); private Node head = nil; public object this[int index] => head[index]; public int Count => head.Length; public int Add(object value) { Node node = (head = head.Append(value)); return node.Length - 1; } IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(head); } public NodeEnumerator GetEnumerator() { return new NodeEnumerator(head); } internal int IndexOf(MatchPredicate predicate, object ctx) { return head.IndexOf(predicate, ctx); } internal bool Contains(object value) { NodeEnumerator enumerator = GetEnumerator(); while (enumerator.MoveNext()) { object current = enumerator.Current; if (object.Equals(current, value)) { return true; } } return false; } internal static List> GetContiguousGroups(int[] keys, T[] values) { if (keys == null) { throw new ArgumentNullException("keys"); } if (values == null) { throw new ArgumentNullException("values"); } if (values.Length < keys.Length) { throw new ArgumentException("Not all keys are covered by values", "values"); } List> list = new List>(); Group item = default(Group); for (int i = 0; i < keys.Length; i++) { if (i == 0 || keys[i] != keys[i - 1]) { item = default(Group); } if (item.IsEmpty) { item = new Group(keys[i]); list.Add(item); } item.Items.Add(values[i]); } return list; } internal bool Any() { return Count != 0; } } internal static class TypeCompatibilityHelper { private static readonly Dictionary s_ByModule = new Dictionary(); internal static CompatibilityLevel GetModuleCompatibilityLevel(Module module) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) if ((object)module == null) { return (CompatibilityLevel)0; } lock (s_ByModule) { if (s_ByModule.TryGetValue(module, out var value)) { return value; } } CompatibilityLevel val = Calculate(module); lock (s_ByModule) { s_ByModule[module] = val; return val; } static CompatibilityLevel Calculate(Module module2) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 //IL_0058: Unknown result type (might be due to invalid IL or missing references) Attribute? customAttribute = Attribute.GetCustomAttribute(module2, typeof(CompatibilityLevelAttribute), inherit: true); CompatibilityLevelAttribute val2 = (CompatibilityLevelAttribute)(object)((customAttribute is CompatibilityLevelAttribute) ? customAttribute : null); if (val2 == null || (int)val2.Level <= 0) { Assembly assembly = module2.Assembly; if ((object)assembly != null) { Attribute? customAttribute2 = Attribute.GetCustomAttribute(assembly, typeof(CompatibilityLevelAttribute), inherit: true); CompatibilityLevelAttribute val3 = (CompatibilityLevelAttribute)(object)((customAttribute2 is CompatibilityLevelAttribute) ? customAttribute2 : null); if (val3 != null && (int)val3.Level > 0) { return val3.Level; } } return (CompatibilityLevel)0; } return val2.Level; } } internal static CompatibilityLevel GetTypeCompatibilityLevel(Type type, CompatibilityLevel defaultLevel) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Invalid comparison between Unknown and I4 //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) Attribute? customAttribute = Attribute.GetCustomAttribute(type, typeof(CompatibilityLevelAttribute), inherit: true); CompatibilityLevelAttribute val = (CompatibilityLevelAttribute)(object)((customAttribute is CompatibilityLevelAttribute) ? customAttribute : null); if (val != null && (int)val.Level > 0) { return val.Level; } CompatibilityLevel moduleCompatibilityLevel = GetModuleCompatibilityLevel(type.Module); if ((int)moduleCompatibilityLevel > 0) { return moduleCompatibilityLevel; } if ((int)defaultLevel >= 200) { return defaultLevel; } return (CompatibilityLevel)200; } internal static CompatibilityLevel GetMemberCompatibilityLevel(MemberInfo member, CompatibilityLevel typeLevel) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) Attribute? customAttribute = Attribute.GetCustomAttribute(member, typeof(CompatibilityLevelAttribute), inherit: true); CompatibilityLevelAttribute val = (CompatibilityLevelAttribute)(object)((customAttribute is CompatibilityLevelAttribute) ? customAttribute : null); if (val == null || (int)val.Level <= 0) { return typeLevel; } return val.Level; } } } namespace ProtoBuf.Internal.Serializers { internal sealed class AnyTypeSerializer : IRuntimeProtoSerializerNode, IDirectWriteNode, IDirectRuntimeWriteNode { private readonly SerializerFeatures _features; private readonly CompatibilityLevel _compatibilityLevel; private readonly DataFormat _dataFormat; private static readonly MethodInfo ReadAnyT = AnyTypeSerializer.ReadAnyT.MakeGenericMethod(typeof(T)); private static readonly MethodInfo WriteAnyT = AnyTypeSerializer.WriteAnyT.MakeGenericMethod(typeof(T)); bool IRuntimeProtoSerializerNode.IsScalar => SerializerFeaturesExtensions.IsScalar(_features); public Type ExpectedType => typeof(T); bool IRuntimeProtoSerializerNode.RequiresOldValue => true; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public AnyTypeSerializer(SerializerFeatures features, CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) _features = features; _compatibilityLevel = compatibilityLevel; _dataFormat = dataFormat; } public object Read(ref State state, object value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return ((State)(ref state)).ReadAny(_features, (T)value, (ISerializer)null); } public void Write(ref State state, object value) { throw new NotSupportedException("Only DirectWrite should be used"); } void IDirectRuntimeWriteNode.DirectWrite(int fieldNumber, WireType wireType, ref State state, object value) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) ((State)(ref state)).WriteAny(fieldNumber, (SerializerFeatures)(_features | SerializerFeaturesExtensions.AsFeatures(wireType)), (T)value, (ISerializer)null); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { throw new NotSupportedException("Only EmitDirectWrite should be used"); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected I4, but got Unknown //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) using Local local = ctx.GetLocalWithValue(typeof(T), entity); ctx.LoadState(); ctx.LoadValue((int)_features); ctx.LoadValue(local); ctx.LoadSelfAsService, T>(_compatibilityLevel, _dataFormat); ctx.EmitCall(ReadAnyT); } bool IDirectWriteNode.CanEmitDirectWrite(WireType wireType) { return true; } bool IDirectRuntimeWriteNode.CanDirectWrite(WireType wireType) { return true; } void IDirectWriteNode.EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected I4, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) using Local local = ctx.GetLocalWithValue(typeof(T), valueFrom); ctx.LoadState(); ctx.LoadValue(fieldNumber); ctx.LoadValue(_features | SerializerFeaturesExtensions.AsFeatures(wireType)); ctx.LoadValue(local); ctx.LoadSelfAsService, T>(_compatibilityLevel, _dataFormat); ctx.EmitCall(WriteAnyT); } } internal static class AnyTypeSerializer { internal static readonly MethodInfo ReadAnyT = FindSerializerFeaturesMethod(typeof(State), "ReadAny"); internal static readonly MethodInfo WriteAnyT = FindSerializerFeaturesMethod(typeof(State), "WriteAny"); private static bool FindSerializerFeaturesMethodFilter(MemberInfo member, object state) { if (member is MethodInfo methodInfo && state is string text && member.Name == text) { ParameterInfo[] parameters = methodInfo.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { if (parameterInfo.ParameterType == typeof(SerializerFeatures)) { return true; } } } return false; } private static MethodInfo FindSerializerFeaturesMethod(Type type, string name) { return (MethodInfo)type.FindMembers(MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public, FindSerializerFeaturesMethodFilter, name).Single(); } internal static IRuntimeProtoSerializerNode Create(Type memberType, SerializerFeatures features, CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) return (IRuntimeProtoSerializerNode)Activator.CreateInstance(typeof(AnyTypeSerializer<>).MakeGenericType(memberType), features, compatibilityLevel, dataFormat); } } internal sealed class BlobSerializer : IRuntimeProtoSerializerNode { private static readonly Type expectedType = typeof(T); private readonly bool overwriteList; bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => !overwriteList; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public BlobSerializer(bool overwriteList) { this.overwriteList = overwriteList; } public object Read(ref State state, object value) { return ((State)(ref state)).AppendBytes(overwriteList ? default(T) : ((T)value), (IMemoryConverter)null); } public void Write(ref State state, object value) { ((State)(ref state)).WriteBytes((T)value, (IMemoryConverter)null); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteBytes", valueFrom, null, typeof(T)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { using Local local = (overwriteList ? null : ctx.GetLocalWithValue(typeof(T), entity)); ctx.LoadState(); if (overwriteList) { ctx.LoadNullRef(); } else { ctx.LoadValue(local); } ctx.EmitCall(typeof(State).GetMethod("AppendBytes", new Type[1] { typeof(T) })); } } internal sealed class BooleanSerializer : IRuntimeProtoSerializerNode { internal static readonly BooleanSerializer Instance = new BooleanSerializer(); private static readonly Type expectedType = typeof(bool); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private BooleanSerializer() { } public void Write(ref State state, object value) { ((State)(ref state)).WriteBoolean((bool)value); } public object Read(ref State state, object value) { return ((State)(ref state)).ReadBoolean(); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteBoolean", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadBoolean", ExpectedType); } } internal sealed class ByteSerializer : IRuntimeProtoSerializerNode { internal static readonly ByteSerializer Instance = new ByteSerializer(); private static readonly Type expectedType = typeof(byte); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private ByteSerializer() { } public void Write(ref State state, object value) { ((State)(ref state)).WriteByte((byte)value); } public object Read(ref State state, object value) { return ((State)(ref state)).ReadByte(); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteByte", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadByte", ExpectedType); } } internal sealed class CharSerializer : UInt16Serializer { internal new static readonly CharSerializer Instance = new CharSerializer(); private static readonly Type expectedType = typeof(char); public override Type ExpectedType => expectedType; private CharSerializer() { } public override void Write(ref State state, object value) { ((State)(ref state)).WriteUInt16((ushort)(char)value); } public override object Read(ref State state, object value) { return (char)((State)(ref state)).ReadUInt16(); } } internal sealed class InheritanceCompiledSerializer : CompiledSerializer, ISerializer, ISubTypeSerializer, IFactory where TBase : class where T : class, TBase { private readonly ProtoSerializer subTypeSerializer; private readonly ProtoSubTypeDeserializer subTypeDeserializer; private readonly Func factory; T ISerializer.Read(ref State state, T value) { return ((State)(ref state)).ReadBaseType(value, (ISubTypeSerializer)null); } T IFactory.Create(ISerializationContext context) { Func func = factory; if (func == null) { return null; } return func(context); } public override object Read(ref State state, object value) { return ((State)(ref state)).ReadBaseType(TypeHelper.FromObject(value), (ISubTypeSerializer)null); } void ISerializer.Write(ref State state, T value) { ((State)(ref state)).WriteBaseType((TBase)value, (ISubTypeSerializer)null); } public override void Write(ref State state, object value) { ((State)(ref state)).WriteBaseType((TBase)TypeHelper.FromObject(value), (ISubTypeSerializer)null); } void ISubTypeSerializer.WriteSubType(ref State state, T value) { subTypeSerializer(ref state, value); } T ISubTypeSerializer.ReadSubType(ref State state, SubTypeState value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return subTypeDeserializer(ref state, value); } public InheritanceCompiledSerializer(IProtoTypeSerializer head, RuntimeTypeModel model) : base(head) { try { subTypeSerializer = CompilerContext.BuildSerializer(model.Scope, head, (TypeModel)(object)model); } catch (Exception ex) { throw new InvalidOperationException("Unable to bind serializer: " + ex.Message, ex); } try { subTypeDeserializer = CompilerContext.BuildSubTypeDeserializer(model.Scope, head, (TypeModel)(object)model); } catch (Exception ex2) { throw new InvalidOperationException("Unable to bind deserializer: " + ex2.Message, ex2); } factory = CompilerContext.BuildFactory(model.Scope, head, (TypeModel)(object)model); } } internal class SimpleCompiledSerializer : CompiledSerializer, ISerializer, IFactory { protected readonly ProtoSerializer serializer; protected readonly ProtoDeserializer deserializer; private readonly Func factory; public SimpleCompiledSerializer(IProtoTypeSerializer head, RuntimeTypeModel model) : base(head) { try { serializer = CompilerContext.BuildSerializer(model.Scope, head, (TypeModel)(object)model); } catch (Exception ex) { throw new InvalidOperationException("Unable to bind serializer: " + ex.Message, ex); } try { deserializer = CompilerContext.BuildDeserializer(model.Scope, head, (TypeModel)(object)model); } catch (Exception ex2) { throw new InvalidOperationException("Unable to bind deserializer: " + ex2.Message, ex2); } factory = CompilerContext.BuildFactory(model.Scope, head, (TypeModel)(object)model); } T ISerializer.Read(ref State state, T value) { return deserializer(ref state, value); } public override object Read(ref State state, object value) { return deserializer(ref state, TypeHelper.FromObject(value)); } void ISerializer.Write(ref State state, T value) { serializer(ref state, value); } public override void Write(ref State state, object value) { serializer(ref state, TypeHelper.FromObject(value)); } T IFactory.Create(ISerializationContext context) { if (factory != null) { return factory(context); } return default(T); } } internal interface ICompiledSerializer { Type ExpectedType { get; } } internal abstract class CompiledSerializer : IProtoTypeSerializer, IRuntimeProtoSerializerNode, ICompiledSerializer { protected readonly IProtoTypeSerializer head; bool IRuntimeProtoSerializerNode.IsScalar => head.IsScalar; public SerializerFeatures Features => head.Features; bool IProtoTypeSerializer.IsSubType => head.IsSubType; Type IProtoTypeSerializer.BaseType => head.BaseType; bool IRuntimeProtoSerializerNode.RequiresOldValue => head.RequiresOldValue; bool IRuntimeProtoSerializerNode.ReturnsValue => head.ReturnsValue; public Type ExpectedType => head.ExpectedType; bool IProtoTypeSerializer.HasInheritance => head.HasInheritance; bool IProtoTypeSerializer.ShouldEmitCreateInstance => head.ShouldEmitCreateInstance; bool IProtoTypeSerializer.HasCallbacks(CallbackType callbackType) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return head.HasCallbacks(callbackType); } bool IProtoTypeSerializer.CanCreateInstance() { return head.CanCreateInstance(); } object IProtoTypeSerializer.CreateInstance(ISerializationContext context) { return head.CreateInstance(context); } public void Callback(object value, CallbackType callbackType, ISerializationContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) head.Callback(value, callbackType, context); } public static ICompiledSerializer Wrap(IProtoTypeSerializer head, RuntimeTypeModel model) { ICompiledSerializer compiledSerializer = head as ICompiledSerializer; if (compiledSerializer == null) { ConstructorInfo constructorInfo; try { constructorInfo = ((!head.IsSubType) ? Helpers.GetConstructor(typeof(SimpleCompiledSerializer<>).MakeGenericType(head.BaseType), new Type[2] { typeof(IProtoTypeSerializer), typeof(RuntimeTypeModel) }, true) : Helpers.GetConstructor(typeof(InheritanceCompiledSerializer<, >).MakeGenericType(head.BaseType, head.ExpectedType), new Type[2] { typeof(IProtoTypeSerializer), typeof(RuntimeTypeModel) }, true)); } catch (Exception innerException) { throw new InvalidOperationException("Unable to wrap " + TypeHelper.NormalizeName(head.BaseType) + "/" + TypeHelper.NormalizeName(head.ExpectedType), innerException); } try { compiledSerializer = (CompiledSerializer)constructorInfo.Invoke(new object[2] { head, model }); } catch (TargetInvocationException ex) { throw new InvalidOperationException("Unable to wrap " + TypeHelper.NormalizeName(head.BaseType) + "/" + TypeHelper.NormalizeName(head.ExpectedType) + ": " + ex.InnerException.Message + " (" + TypeHelper.NormalizeName(head.GetType()) + ")", ex.InnerException); } } return compiledSerializer; } protected CompiledSerializer(IProtoTypeSerializer head) { this.head = head; } public abstract void Write(ref State state, object value); public abstract object Read(ref State state, object value); void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { head.EmitWrite(ctx, valueFrom); } void IProtoTypeSerializer.EmitWriteRoot(CompilerContext ctx, Local valueFrom) { head.EmitWriteRoot(ctx, valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local valueFrom) { head.EmitRead(ctx, valueFrom); } void IProtoTypeSerializer.EmitReadRoot(CompilerContext ctx, Local valueFrom) { head.EmitReadRoot(ctx, valueFrom); } void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) head.EmitCallback(ctx, valueFrom, callbackType); } void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { head.EmitCreateInstance(ctx, callNoteObject); } } internal sealed class DateTimeSerializer : IRuntimeProtoSerializerNode { private static readonly Type expectedType = typeof(DateTime); private static DateTimeSerializer s_Timestamp; private readonly bool _includeKind; private readonly bool _useTimestamp; bool IRuntimeProtoSerializerNode.IsScalar => false; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public static DateTimeSerializer Create(CompatibilityLevel compatibilityLevel, TypeModel model) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)compatibilityLevel < 240) { return new DateTimeSerializer(useTimestamp: false, TypeModelExtensions.HasOption(model, (TypeModelOptions)2)); } return s_Timestamp ?? (s_Timestamp = new DateTimeSerializer(useTimestamp: true, includeKind: false)); } private DateTimeSerializer(bool useTimestamp, bool includeKind) { _useTimestamp = useTimestamp; _includeKind = includeKind; } public object Read(ref State state, object value) { if (_useTimestamp) { return BclHelpers.ReadTimestamp(ref state); } return BclHelpers.ReadDateTime(ref state); } public void Write(ref State state, object value) { if (_useTimestamp) { BclHelpers.WriteTimestamp(ref state, (DateTime)value); } else if (_includeKind) { BclHelpers.WriteDateTimeWithKind(ref state, (DateTime)value); } else { BclHelpers.WriteDateTime(ref state, (DateTime)value); } } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite(_useTimestamp ? "WriteTimestamp" : (_includeKind ? "WriteDateTimeWithKind" : "WriteDateTime"), valueFrom, typeof(BclHelpers)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { if (_useTimestamp) { ctx.LoadValue(entity); } ctx.EmitStateBasedRead(typeof(BclHelpers), _useTimestamp ? "ReadTimestamp" : "ReadDateTime", ExpectedType); } } internal sealed class DecimalSerializer : IRuntimeProtoSerializerNode { private enum Variant { BclDecimal, String } private static DecimalSerializer s_BclDecimal; private static DecimalSerializer s_String; private readonly Variant _variant; private static readonly Type expectedType = typeof(decimal); bool IRuntimeProtoSerializerNode.IsScalar => _variant == Variant.String; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public static DecimalSerializer Create(CompatibilityLevel compatibilityLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)compatibilityLevel < 300) { return s_BclDecimal ?? (s_BclDecimal = new DecimalSerializer(Variant.BclDecimal)); } return s_String ?? (s_String = new DecimalSerializer(Variant.String)); } private DecimalSerializer(Variant variant) { _variant = variant; } public object Read(ref State state, object value) { Variant variant = _variant; decimal num = ((variant != Variant.String) ? BclHelpers.ReadDecimal(ref state) : BclHelpers.ReadDecimalString(ref state)); return num; } public void Write(ref State state, object value) { Variant variant = _variant; if (variant == Variant.String) { BclHelpers.WriteDecimalString(ref state, (decimal)value); } else { BclHelpers.WriteDecimal(ref state, (decimal)value); } } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { Variant variant = _variant; string methodName = ((variant != Variant.String) ? "WriteDecimal" : "WriteDecimalString"); ctx.EmitStateBasedWrite(methodName, valueFrom, typeof(BclHelpers)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { Type typeFromHandle = typeof(BclHelpers); Variant variant = _variant; string methodName = ((variant != Variant.String) ? "ReadDecimal" : "ReadDecimalString"); ctx.EmitStateBasedRead(typeFromHandle, methodName, ExpectedType); } } internal sealed class DefaultValueDecorator : ProtoDecoratorBase { private readonly object defaultValue; public override Type ExpectedType => Tail.ExpectedType; public override bool RequiresOldValue => Tail.RequiresOldValue; public override bool ReturnsValue => Tail.ReturnsValue; public DefaultValueDecorator(object defaultValue, IRuntimeProtoSerializerNode tail) : base(tail) { if (defaultValue == null) { throw new ArgumentNullException("defaultValue"); } Type type = defaultValue.GetType(); if (type != tail.ExpectedType) { throw new ArgumentException("Default value is of incorrect type", "defaultValue"); } this.defaultValue = defaultValue; } public override void Write(ref State state, object value) { if (!object.Equals(value, defaultValue)) { Tail.Write(ref state, value); } } public override object Read(ref State state, object value) { return Tail.Read(ref state, value); } protected override void EmitWrite(CompilerContext ctx, Local valueFrom) { CodeLabel label = ctx.DefineLabel(); using (Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom)) { ctx.LoadValue(local); EmitBranchIfDefaultValue(ctx, label); Tail.EmitWrite(ctx, local); } ctx.MarkLabel(label); } private static void EmitBeq(CompilerContext ctx, CodeLabel label, Type type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 ProtoTypeCode typeCode = Helpers.GetTypeCode(type); if (typeCode - 3 <= 11) { ctx.BranchIfEqual(label, @short: false); return; } MethodInfo method = type.GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { type, type }, null); if ((object)method == null || method.ReturnType != typeof(bool)) { throw new InvalidOperationException("No suitable equality operator found for default-values of type: " + type.FullName); } ctx.EmitCall(method); ctx.BranchIfTrue(label, @short: false); } private void EmitBranchIfDefaultValue(CompilerContext ctx, CodeLabel label) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected I4, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Invalid comparison between Unknown and I4 //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Invalid comparison between Unknown and I4 //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Invalid comparison between Unknown and I4 Type expectedType = ExpectedType; ProtoTypeCode typeCode = Helpers.GetTypeCode(expectedType); if ((int)typeCode <= 100) { switch (typeCode - 3) { default: { if ((int)typeCode != 100) { break; } TimeSpan timeSpan = (TimeSpan)defaultValue; if (timeSpan == TimeSpan.Zero) { ctx.LoadValue(typeof(TimeSpan).GetField("Zero")); } else { ctx.LoadValue(timeSpan.Ticks); ctx.EmitCall(typeof(TimeSpan).GetMethod("FromTicks")); } EmitBeq(ctx, label, expectedType); return; } case 0: if ((bool)defaultValue) { ctx.BranchIfTrue(label, @short: false); } else { ctx.BranchIfFalse(label, @short: false); } return; case 3: if ((byte)defaultValue == 0) { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((byte)defaultValue); EmitBeq(ctx, label, expectedType); return; case 2: if ((sbyte)defaultValue == 0) { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((sbyte)defaultValue); EmitBeq(ctx, label, expectedType); return; case 4: if ((short)defaultValue == 0) { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((short)defaultValue); EmitBeq(ctx, label, expectedType); return; case 5: if ((ushort)defaultValue == 0) { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((ushort)defaultValue); EmitBeq(ctx, label, expectedType); return; case 6: if ((int)defaultValue == 0) { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((int)defaultValue); EmitBeq(ctx, label, expectedType); return; case 7: if ((uint)defaultValue == 0) { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((int)(uint)defaultValue); EmitBeq(ctx, label, expectedType); return; case 1: if ((char)defaultValue == '\0') { ctx.BranchIfFalse(label, @short: false); return; } ctx.LoadValue((char)defaultValue); EmitBeq(ctx, label, expectedType); return; case 8: ctx.LoadValue((long)defaultValue); EmitBeq(ctx, label, expectedType); return; case 9: ctx.LoadValue((ulong)defaultValue); EmitBeq(ctx, label, expectedType); return; case 11: ctx.LoadValue((double)defaultValue); EmitBeq(ctx, label, expectedType); return; case 10: ctx.LoadValue((float)defaultValue); EmitBeq(ctx, label, expectedType); return; case 15: ctx.LoadValue((string)defaultValue); EmitBeq(ctx, label, expectedType); return; case 12: { decimal value = (decimal)defaultValue; ctx.LoadValue(value); EmitBeq(ctx, label, expectedType); return; } case 13: ctx.LoadValue(((DateTime)defaultValue).ToBinary()); ctx.EmitCall(typeof(DateTime).GetMethod("FromBinary")); EmitBeq(ctx, label, expectedType); return; case 14: break; } } else { if ((int)typeCode == 102) { ctx.LoadValue((Guid)defaultValue); EmitBeq(ctx, label, expectedType); return; } if ((int)typeCode == 108) { ctx.Emit(OpCodes.Conv_I8); ctx.LoadValue(((IntPtr)defaultValue).ToInt64()); EmitBeq(ctx, label, typeof(long)); return; } if ((int)typeCode == 109) { ctx.Emit(OpCodes.Conv_U8); ctx.LoadValue(((UIntPtr)defaultValue).ToUInt64()); EmitBeq(ctx, label, typeof(ulong)); return; } } throw new NotSupportedException("Type cannot be represented as a default value: " + expectedType.FullName); } protected override void EmitRead(CompilerContext ctx, Local valueFrom) { Tail.EmitRead(ctx, valueFrom); } } internal sealed class DoubleSerializer : IRuntimeProtoSerializerNode { internal static readonly DoubleSerializer Instance = new DoubleSerializer(); private static readonly Type expectedType = typeof(double); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private DoubleSerializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadDouble(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteDouble((double)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteDouble", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadDouble", ExpectedType); } } internal class EnumMemberSerializer : IRuntimeProtoSerializerNode, IDirectWriteNode { private readonly IRuntimeProtoSerializerNode _tail; bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType { get; } bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public EnumMemberSerializer(Type enumType) { ExpectedType = enumType ?? throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) { ThrowHelper.ThrowInvalidOperationException("Expected an enum type; got " + TypeHelper.NormalizeName(enumType), (Exception)null); } _tail = Type.GetTypeCode(enumType) switch { TypeCode.SByte => SByteSerializer.Instance, TypeCode.Int16 => Int16Serializer.Instance, TypeCode.Int32 => Int32Serializer.Instance, TypeCode.Int64 => Int64Serializer.Instance, TypeCode.Byte => ByteSerializer.Instance, TypeCode.UInt16 => UInt16Serializer.Instance, TypeCode.UInt32 => UInt32Serializer.Instance, TypeCode.UInt64 => UInt64Serializer.Instance, _ => null, }; if (_tail == null) { ThrowHelper.ThrowInvalidOperationException("Unable to resolve underlying enum type for " + TypeHelper.NormalizeName(enumType), (Exception)null); } } internal static object EnumToWire(object value, Type type) { return Type.GetTypeCode(type) switch { TypeCode.Byte => (byte)value, TypeCode.SByte => (sbyte)value, TypeCode.Int16 => (short)value, TypeCode.Int32 => (int)value, TypeCode.Int64 => (long)value, TypeCode.UInt16 => (ushort)value, TypeCode.UInt32 => (uint)value, TypeCode.UInt64 => (ulong)value, _ => throw new InvalidOperationException(), }; } private object EnumToWire(object value) { return EnumToWire(value, ExpectedType); } public object Read(ref State state, object value) { return Enum.ToObject(ExpectedType, _tail.Read(ref state, value)); } public void Write(ref State state, object value) { _tail.Write(ref state, EnumToWire(value)); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { _tail.EmitWrite(ctx, valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { _tail.EmitRead(ctx, entity); } bool IDirectWriteNode.CanEmitDirectWrite(WireType wireType) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (_tail is IDirectWriteNode directWriteNode) { return directWriteNode.CanEmitDirectWrite(wireType); } return false; } void IDirectWriteNode.EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) ((IDirectWriteNode)_tail).EmitDirectWrite(fieldNumber, wireType, ctx, valueFrom); } } internal class ExternalSerializer { internal static IProtoTypeSerializer Create(Type target, Type serializer) { return (IProtoTypeSerializer)Activator.CreateInstance(typeof(ExternalSerializer<, >).MakeGenericType(serializer, target), nonPublic: true); } } internal interface IExternalSerializer { object Service { get; } } internal sealed class ExternalSerializer : IRuntimeProtoSerializerNode, IExternalSerializer, ICompiledSerializer, IProtoTypeSerializer where TProvider : class { object IExternalSerializer.Service => Serializer; private static ISerializer Serializer => SerializerCache.InstanceField; public Type ExpectedType => typeof(T); bool IRuntimeProtoSerializerNode.RequiresOldValue => true; bool IRuntimeProtoSerializerNode.ReturnsValue => true; SerializerFeatures IProtoTypeSerializer.Features => ((ISerializer)(object)Serializer).Features; bool IRuntimeProtoSerializerNode.IsScalar => SerializerFeaturesExtensions.IsScalar(((ISerializer)(object)Serializer).Features); Type IProtoTypeSerializer.BaseType => ExpectedType; bool IProtoTypeSerializer.ShouldEmitCreateInstance => false; bool IProtoTypeSerializer.HasInheritance => false; bool IProtoTypeSerializer.IsSubType => false; void IRuntimeProtoSerializerNode.Write(ref State state, object value) { ((ISerializer)(object)Serializer).Write(ref state, TypeHelper.FromObject(value)); } object IRuntimeProtoSerializerNode.Read(ref State state, object value) { return ((ISerializer)(object)Serializer).Read(ref state, TypeHelper.FromObject(value)); } bool IProtoTypeSerializer.CanCreateInstance() { return Serializer is IFactory; } object IProtoTypeSerializer.CreateInstance(ISerializationContext context) { if (Serializer is IFactory val) { return ((IFactory)(object)val).Create(context); } return null; } void IProtoTypeSerializer.Callback(object value, CallbackType callbackType, ISerializationContext context) { } bool IProtoTypeSerializer.HasCallbacks(CallbackType callbackType) { return false; } void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { ThrowHelper.ThrowNotSupportedException(); } void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { ThrowHelper.ThrowNotSupportedException(); } void IProtoTypeSerializer.EmitReadRoot(CompilerContext ctx, Local entity) { ThrowHelper.ThrowNotSupportedException(); } void IProtoTypeSerializer.EmitWriteRoot(CompilerContext ctx, Local entity) { ThrowHelper.ThrowNotSupportedException(); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(typeof(T), valueFrom); if (ctx.NonPublic || RuntimeTypeModel.IsFullyPublic(typeof(TProvider))) { ctx.EmitCall(typeof(SerializerCache).GetMethod("Get").MakeGenericMethod(typeof(TProvider), typeof(T))); } else { ctx.LoadState(); ctx.EmitCall(typeof(State).GetMethod("GetSerializer").MakeGenericMethod(typeof(T))); } ctx.LoadState(); ctx.LoadValue(local); ctx.EmitCall(typeof(ISerializer).GetMethod("Write")); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { using Local local = ctx.GetLocalWithValue(typeof(T), entity); if (ctx.NonPublic || RuntimeTypeModel.IsFullyPublic(typeof(TProvider))) { ctx.EmitCall(typeof(SerializerCache).GetMethod("Get").MakeGenericMethod(typeof(TProvider), typeof(T))); } else { ctx.LoadState(); ctx.EmitCall(typeof(State).GetMethod("GetSerializer").MakeGenericMethod(typeof(T))); } ctx.LoadState(); ctx.LoadValue(local); ctx.EmitCall(typeof(ISerializer).GetMethod("Read")); ctx.StoreValue(entity); } } internal sealed class FieldDecorator : ProtoDecoratorBase { private readonly FieldInfo field; public override Type ExpectedType { get; } public override bool RequiresOldValue => true; public override bool ReturnsValue => false; public FieldDecorator(Type forType, FieldInfo field, IRuntimeProtoSerializerNode tail) : base(tail) { if (tail == null) { ThrowHelper.ThrowArgumentNullException("tail"); } if ((object)field == null) { ThrowHelper.ThrowArgumentNullException("field"); } if ((object)forType == null) { ThrowHelper.ThrowArgumentNullException("forType"); } ExpectedType = forType; this.field = field; } public override void Write(ref State state, object value) { value = field.GetValue(value); if (value != null) { Tail.Write(ref state, value); } } public override object Read(ref State state, object value) { object obj = Tail.Read(ref state, Tail.RequiresOldValue ? field.GetValue(value) : null); if (obj != null) { field.SetValue(value, obj); } return null; } protected override void EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.LoadAddress(valueFrom, ExpectedType); ctx.LoadValue(field); ctx.WriteNullCheckedTail(field.FieldType, Tail, null); } protected override void EmitRead(CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); if (Tail.RequiresOldValue) { ctx.LoadAddress(local, ExpectedType); ctx.LoadValue(field); } ctx.ReadNullCheckedTail(field.FieldType, Tail, null); MemberInfo member = field; ctx.CheckAccessibility(ref member); if (member is FieldInfo) { if (!Tail.ReturnsValue) { return; } Type type = PropertyDecorator.ChooseReadLocalType(field.FieldType, Tail.ExpectedType); using Local local2 = new Local(ctx, type); ctx.StoreValue(local2); if (field.FieldType.IsValueType) { ctx.LoadAddress(local, ExpectedType); ctx.LoadValue(local2); ctx.StoreValue(field); return; } CodeLabel label = ctx.DefineLabel(); ctx.LoadValue(local2); ctx.BranchIfFalse(label, @short: true); ctx.LoadAddress(local, ExpectedType); ctx.LoadValue(local2); if (!field.FieldType.IsValueType && !type.IsValueType && !field.FieldType.IsAssignableFrom(type)) { ctx.Cast(field.FieldType); } ctx.StoreValue(field); ctx.MarkLabel(label); return; } if (Tail.ReturnsValue) { ctx.DiscardValue(); } } } internal sealed class GuidSerializer : IRuntimeProtoSerializerNode { private enum Variant { BclGuid, GuidString, GuidBytes } private readonly Variant _variant; private static GuidSerializer s_Legacy; private static GuidSerializer s_String; private static GuidSerializer s_Bytes; private static readonly Type expectedType = typeof(Guid); bool IRuntimeProtoSerializerNode.IsScalar => _variant switch { Variant.GuidString => true, Variant.GuidBytes => true, _ => false, }; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; internal static GuidSerializer Create(CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 if ((int)compatibilityLevel < 300) { return s_Legacy ?? (s_Legacy = new GuidSerializer(Variant.BclGuid)); } if ((int)dataFormat == 3) { return s_Bytes ?? (s_Bytes = new GuidSerializer(Variant.GuidBytes)); } return s_String ?? (s_String = new GuidSerializer(Variant.GuidString)); } private GuidSerializer(Variant variant) { _variant = variant; } public void Write(ref State state, object value) { switch (_variant) { case Variant.GuidString: BclHelpers.WriteGuidString(ref state, (Guid)value); break; case Variant.GuidBytes: BclHelpers.WriteGuidBytes(ref state, (Guid)value); break; default: BclHelpers.WriteGuid(ref state, (Guid)value); break; } } public object Read(ref State state, object value) { return _variant switch { Variant.GuidString => BclHelpers.ReadGuidString(ref state), Variant.GuidBytes => BclHelpers.ReadGuidBytes(ref state), _ => BclHelpers.ReadGuid(ref state), }; } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite(_variant switch { Variant.GuidString => "WriteGuidString", Variant.GuidBytes => "WriteGuidBytes", _ => "WriteGuid", }, valueFrom, typeof(BclHelpers)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { Type typeFromHandle = typeof(BclHelpers); ctx.EmitStateBasedRead(typeFromHandle, _variant switch { Variant.GuidString => "ReadGuidString", Variant.GuidBytes => "ReadGuidBytes", _ => "ReadGuid", }, ExpectedType); } } internal interface IDirectWriteNode { bool CanEmitDirectWrite(WireType wireType); void EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom); } internal interface IDirectRuntimeWriteNode { bool CanDirectWrite(WireType wireType); void DirectWrite(int fieldNumber, WireType wireType, ref State state, object value); } internal sealed class Int16Serializer : IRuntimeProtoSerializerNode { internal static readonly Int16Serializer Instance = new Int16Serializer(); private static readonly Type expectedType = typeof(short); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private Int16Serializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadInt16(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteInt16((short)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteInt16", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadInt16", ExpectedType); } } internal sealed class Int32Serializer : IRuntimeProtoSerializerNode, IDirectWriteNode { internal static readonly Int32Serializer Instance = new Int32Serializer(); private static readonly Type expectedType = typeof(int); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private Int32Serializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadInt32(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteInt32((int)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteInt32", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadInt32", ExpectedType); } bool IDirectWriteNode.CanEmitDirectWrite(WireType wireType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 return (int)wireType == 0; } void IDirectWriteNode.EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(typeof(int), valueFrom); ctx.LoadState(); ctx.LoadValue(fieldNumber); ctx.LoadValue(local); ctx.EmitCall(typeof(State).GetMethod("WriteInt32Varint", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { typeof(int), typeof(int) }, null)); } } internal sealed class Int64Serializer : IRuntimeProtoSerializerNode { internal static readonly Int64Serializer Instance = new Int64Serializer(); private static readonly Type expectedType = typeof(long); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private Int64Serializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadInt64(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteInt64((long)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteInt64", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadInt64", ExpectedType); } } internal sealed class IntPtrSerializer : IRuntimeProtoSerializerNode { internal static readonly IntPtrSerializer Instance = new IntPtrSerializer(); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => typeof(IntPtr); bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private IntPtrSerializer() { } public void Write(ref State state, object value) { ((State)(ref state)).WriteIntPtr((IntPtr)value); } public object Read(ref State state, object value) { return ((State)(ref state)).ReadIntPtr(); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteIntPtr", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadIntPtr", ExpectedType); } } internal interface IRuntimeProtoSerializerNode { bool IsScalar { get; } Type ExpectedType { get; } bool RequiresOldValue { get; } bool ReturnsValue { get; } void Write(ref State state, object value); object Read(ref State state, object value); void EmitWrite(CompilerContext ctx, Local valueFrom); void EmitRead(CompilerContext ctx, Local entity); } internal interface IProtoTypeSerializer : IRuntimeProtoSerializerNode { Type BaseType { get; } bool ShouldEmitCreateInstance { get; } bool HasInheritance { get; } bool IsSubType { get; } SerializerFeatures Features { get; } bool HasCallbacks(CallbackType callbackType); bool CanCreateInstance(); object CreateInstance(ISerializationContext context); void Callback(object value, CallbackType callbackType, ISerializationContext context); void EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType); void EmitCreateInstance(CompilerContext ctx, bool callNoteObject = true); void EmitReadRoot(CompilerContext ctx, Local entity); void EmitWriteRoot(CompilerContext ctx, Local entity); } internal interface ISerializerProxy { IRuntimeProtoSerializerNode Serializer { get; } } internal static class MapDecorator { public static IRuntimeProtoSerializerNode Create(RepeatedSerializerStub provider, Type keyType, Type valueType, int fieldNumber, SerializerFeatures features, SerializerFeatures keyFeatures, CompatibilityLevel keyCompatibilityLevel, DataFormat keyDataFormat, SerializerFeatures valueFeatures, CompatibilityLevel valueCompatibilityLevel, DataFormat valueDataFormat) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) if (provider == null) { ThrowHelper.ThrowArgumentNullException("provider"); } _ = provider.Serializer; return (IRuntimeProtoSerializerNode)Activator.CreateInstance(typeof(MapDecorator<, , >).MakeGenericType(provider.ForType, keyType, valueType), fieldNumber, features, keyFeatures, keyCompatibilityLevel, keyDataFormat, valueFeatures, valueCompatibilityLevel, valueDataFormat, provider); } } internal class MapDecorator : IRuntimeProtoSerializerNode, ICompiledSerializer { private readonly int _fieldNumber; private readonly SerializerFeatures _features; private readonly SerializerFeatures _keyFeatures; private readonly SerializerFeatures _valueFeatures; private readonly CompatibilityLevel _keyCompatibilityLevel; private readonly CompatibilityLevel _valueCompatibilityLevel; private readonly DataFormat _keyDataFormat; private readonly DataFormat _valueDataFormat; private readonly RepeatedSerializerStub _provider; bool IRuntimeProtoSerializerNode.IsScalar => false; private MapSerializer Serializer => (MapSerializer)_provider.Serializer; public Type ExpectedType => typeof(TCollection); bool IRuntimeProtoSerializerNode.ReturnsValue => true; public bool RequiresOldValue => true; public MapDecorator(int fieldNumber, SerializerFeatures features, SerializerFeatures keyFeatures, CompatibilityLevel keyCompatibilityLevel, DataFormat keyDataFormat, SerializerFeatures valueFeatures, CompatibilityLevel valueCompatibilityLevel, DataFormat valueDataFormat, RepeatedSerializerStub provider) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) _provider = provider; _features = features; _keyFeatures = keyFeatures; _keyCompatibilityLevel = keyCompatibilityLevel; _keyDataFormat = keyDataFormat; _valueFeatures = valueFeatures; _valueCompatibilityLevel = valueCompatibilityLevel; _valueDataFormat = valueDataFormat; _fieldNumber = fieldNumber; } public object Read(ref State state, object value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) return Serializer.ReadMap(ref state, _features, (TCollection)value, _keyFeatures, _valueFeatures, TypeModel.GetInbuiltSerializer(_keyCompatibilityLevel, _keyDataFormat), TypeModel.GetInbuiltSerializer(_valueCompatibilityLevel, _valueDataFormat)); } public void Write(ref State state, object value) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) Serializer.WriteMap(ref state, _fieldNumber, _features, (TCollection)value, _keyFeatures, _valueFeatures, TypeModel.GetInbuiltSerializer(_keyCompatibilityLevel, _keyDataFormat), TypeModel.GetInbuiltSerializer(_valueCompatibilityLevel, _valueDataFormat)); } public void EmitWrite(CompilerContext ctx, Local valueFrom) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected I4, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected I4, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected I4, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) _ = Serializer; MethodInfo method = typeof(MapSerializer).GetMethod("WriteMap"); using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); _provider.EmitProvider(ctx); ctx.LoadState(); ctx.LoadValue(_fieldNumber); ctx.LoadValue((int)_features); ctx.LoadValue(local); ctx.LoadValue((int)_keyFeatures); ctx.LoadValue((int)_valueFeatures); ctx.LoadSelfAsService, TKey>(_keyCompatibilityLevel, _keyDataFormat); ctx.LoadSelfAsService, TValue>(_valueCompatibilityLevel, _valueDataFormat); ctx.EmitCall(method); } public void EmitRead(CompilerContext ctx, Local valueFrom) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected I4, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected I4, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected I4, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) MethodInfo method = typeof(MapSerializer).GetMethod("ReadMap"); using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); _provider.EmitProvider(ctx); ctx.LoadState(); ctx.LoadValue((int)_features); ctx.LoadValue(local); ctx.LoadValue((int)_keyFeatures); ctx.LoadValue((int)_valueFeatures); ctx.LoadSelfAsService, TKey>(_keyCompatibilityLevel, _keyDataFormat); ctx.LoadSelfAsService, TValue>(_valueCompatibilityLevel, _valueDataFormat); ctx.EmitCall(method); } } internal sealed class MemberSpecifiedDecorator : ProtoDecoratorBase { private readonly MethodInfo getSpecified; private readonly MethodInfo setSpecified; public override Type ExpectedType => Tail.ExpectedType; public override bool RequiresOldValue => Tail.RequiresOldValue; public override bool ReturnsValue => Tail.ReturnsValue; public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IRuntimeProtoSerializerNode tail) : base(tail) { if ((object)getSpecified == null && (object)setSpecified == null) { throw new InvalidOperationException(); } this.getSpecified = getSpecified; this.setSpecified = setSpecified; } public override void Write(ref State state, object value) { if ((object)getSpecified == null || (bool)getSpecified.Invoke(value, null)) { Tail.Write(ref state, value); } } public override object Read(ref State state, object value) { object result = Tail.Read(ref state, value); if ((object)setSpecified != null) { setSpecified.Invoke(value, new object[1] { true }); } return result; } protected override void EmitWrite(CompilerContext ctx, Local valueFrom) { if ((object)getSpecified == null) { Tail.EmitWrite(ctx, valueFrom); return; } using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); ctx.LoadAddress(local, ExpectedType); ctx.EmitCall(getSpecified); CodeLabel label = ctx.DefineLabel(); ctx.BranchIfFalse(label, @short: false); Tail.EmitWrite(ctx, local); ctx.MarkLabel(label); } protected override void EmitRead(CompilerContext ctx, Local valueFrom) { if ((object)setSpecified == null) { Tail.EmitRead(ctx, valueFrom); return; } using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); Tail.EmitRead(ctx, local); ctx.LoadAddress(local, ExpectedType); ctx.LoadValue(1); ctx.EmitCall(setSpecified); } } internal sealed class ParseableSerializer : IRuntimeProtoSerializerNode { private readonly MethodInfo parse; bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => parse.DeclaringType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public static ParseableSerializer TryCreate(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } MethodInfo method = type.GetMethod("Parse", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null); if ((object)method != null && method.ReturnType == type) { if (type.IsValueType) { MethodInfo customToString = GetCustomToString(type); if ((object)customToString == null || customToString.ReturnType != typeof(string)) { return null; } } return new ParseableSerializer(method); } return null; } private static MethodInfo GetCustomToString(Type type) { return type.GetMethod("ToString", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null); } private ParseableSerializer(MethodInfo parse) { this.parse = parse; } public object Read(ref State state, object value) { return parse.Invoke(null, new object[1] { ((State)(ref state)).ReadString((StringMap)null) }); } public void Write(ref State state, object value) { ((State)(ref state)).WriteString(value.ToString(), (StringMap)null); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { Type expectedType = ExpectedType; using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); ctx.LoadState(); ctx.LoadAddress(local, expectedType); if (expectedType.IsValueType) { ctx.EmitCall(GetCustomToString(expectedType)); } else { ctx.EmitCall(typeof(object).GetMethod("ToString")); } ctx.LoadNullRef(); ctx.EmitCall(typeof(State).GetMethod("WriteString", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { typeof(string), typeof(StringMap) }, null)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.LoadState(); ctx.LoadNullRef(); ctx.EmitCall(typeof(State).GetMethod("ReadString", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(StringMap) }, null)); ctx.EmitCall(parse); } } internal sealed class PropertyDecorator : ProtoDecoratorBase { private readonly PropertyInfo property; private readonly bool readOptionsWriteValue; private readonly MethodInfo shadowSetter; public override Type ExpectedType { get; } public override bool RequiresOldValue => true; public override bool ReturnsValue => false; public PropertyDecorator(Type forType, PropertyInfo property, IRuntimeProtoSerializerNode tail) : base(tail) { if (tail == null) { ThrowHelper.ThrowArgumentNullException("tail"); } if ((object)property == null) { ThrowHelper.ThrowArgumentNullException("property"); } if ((object)forType == null) { ThrowHelper.ThrowArgumentNullException("forType"); } ExpectedType = forType; this.property = property; SanityCheck(property, tail, out readOptionsWriteValue, nonPublic: true, allowInternal: true); shadowSetter = GetShadowSetter(property); } private static void SanityCheck(PropertyInfo property, IRuntimeProtoSerializerNode tail, out bool writeValue, bool nonPublic, bool allowInternal) { if ((object)property == null) { throw new ArgumentNullException("property"); } writeValue = tail.ReturnsValue && ((object)GetShadowSetter(property) != null || (property.CanWrite && (object)Helpers.GetSetMethod(property, nonPublic, allowInternal) != null)); if (!property.CanRead || (object)Helpers.GetGetMethod(property, nonPublic, allowInternal) == null) { throw new InvalidOperationException("Cannot serialize property without an accessible get accessor: " + property.DeclaringType.FullName + "." + property.Name); } if (!writeValue && (!tail.RequiresOldValue || tail.ExpectedType.IsValueType)) { throw new InvalidOperationException("Cannot apply changes to property " + property.DeclaringType.FullName + "." + property.Name); } } private static MethodInfo GetShadowSetter(PropertyInfo property) { Type reflectedType = property.ReflectedType; MethodInfo instanceMethod = Helpers.GetInstanceMethod(reflectedType, "Set" + property.Name, new Type[1] { property.PropertyType }); if ((object)instanceMethod == null || !instanceMethod.IsPublic || instanceMethod.ReturnType != typeof(void)) { return null; } return instanceMethod; } public override void Write(ref State state, object value) { value = property.GetValue(value, null); if (value != null) { Tail.Write(ref state, value); } } public override object Read(ref State state, object value) { object value2 = (Tail.RequiresOldValue ? property.GetValue(value, null) : null); object obj = Tail.Read(ref state, value2); if (readOptionsWriteValue && obj != null) { if ((object)shadowSetter == null) { property.SetValue(value, obj, null); } else { shadowSetter.Invoke(value, new object[1] { obj }); } } return null; } protected override void EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.LoadAddress(valueFrom, ExpectedType); ctx.LoadValue(property); ctx.WriteNullCheckedTail(property.PropertyType, Tail, null); } internal static Type ChooseReadLocalType(Type memberType, Type tailType) { if (memberType == tailType) { return memberType; } if (memberType.IsClass && tailType.IsClass) { return tailType; } if (memberType.IsValueType && tailType.IsValueType && tailType == Nullable.GetUnderlyingType(memberType)) { return memberType; } return tailType; } protected override void EmitRead(CompilerContext ctx, Local valueFrom) { SanityCheck(property, Tail, out var writeValue, ctx.NonPublic, ctx.AllowInternal(property)); if (ExpectedType.IsValueType && valueFrom == null) { throw new InvalidOperationException("Attempt to mutate struct on the head of the stack; changes would be lost"); } using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); if (Tail.RequiresOldValue) { ctx.LoadAddress(local, ExpectedType); ctx.LoadValue(property); } Type propertyType = property.PropertyType; ctx.ReadNullCheckedTail(propertyType, Tail, null); if (writeValue) { Type type = ChooseReadLocalType(property.PropertyType, Tail.ExpectedType); using Local local2 = new Local(ctx, type); ctx.StoreValue(local2); CodeLabel label = default(CodeLabel); if (!type.IsValueType) { label = ctx.DefineLabel(); ctx.LoadValue(local2); ctx.BranchIfFalse(label, @short: true); } ctx.LoadAddress(local, ExpectedType); ctx.LoadValue(local2); if (!property.PropertyType.IsValueType && !type.IsValueType && !property.PropertyType.IsAssignableFrom(type)) { ctx.Cast(property.PropertyType); } if ((object)shadowSetter == null) { ctx.StoreValue(property); } else { ctx.EmitCall(shadowSetter); } if (!propertyType.IsValueType) { ctx.MarkLabel(label); } return; } if (Tail.ReturnsValue) { ctx.DiscardValue(); } } } internal abstract class ProtoDecoratorBase : IRuntimeProtoSerializerNode { protected readonly IRuntimeProtoSerializerNode Tail; public virtual bool IsScalar => Tail.IsScalar; public abstract Type ExpectedType { get; } public abstract bool ReturnsValue { get; } public abstract bool RequiresOldValue { get; } protected ProtoDecoratorBase(IRuntimeProtoSerializerNode tail) { Tail = tail; } public abstract void Write(ref State state, object value); public abstract object Read(ref State state, object value); void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { EmitWrite(ctx, valueFrom); } protected abstract void EmitWrite(CompilerContext ctx, Local valueFrom); void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { EmitRead(ctx, entity); } protected abstract void EmitRead(CompilerContext ctx, Local valueFrom); } internal static class RepeatedDecorator { public static IRuntimeProtoSerializerNode Create(RepeatedSerializerStub stub, int fieldNumber, SerializerFeatures features, CompatibilityLevel compatibilityLevel, DataFormat dataFormat) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if (stub == null) { ThrowHelper.ThrowArgumentNullException("stub", "No suitable repeated serializer resolved for stub"); } _ = stub.Serializer; return (IRuntimeProtoSerializerNode)Activator.CreateInstance(typeof(RepeatedDecorator<, >).MakeGenericType(stub.ForType, stub.ItemType), fieldNumber, features, compatibilityLevel, dataFormat, stub); } internal static IRepeatedSerializer GetSerializer(MemberInfo original) { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(original, typeof(T)); MemberInfo memberInfo = underlyingProvider; object obj; if (!(memberInfo is FieldInfo fieldInfo)) { if (!(memberInfo is MethodInfo { IsStatic: not false } methodInfo)) { goto IL_0057; } obj = methodInfo.Invoke(null, null); } else { if (!fieldInfo.IsStatic) { goto IL_0057; } obj = fieldInfo.GetValue(null); } goto IL_005a; IL_0057: obj = null; goto IL_005a; IL_005a: object obj2 = obj; if (obj2 is IRepeatedSerializer result) { return result; } ThrowHelper.ThrowInvalidOperationException("No suitable repeated serializer resolved for " + TypeHelper.NormalizeName(typeof(T)), (Exception)null); return null; } } internal sealed class RepeatedDecorator : IRuntimeProtoSerializerNode, ICompiledSerializer { private readonly int _fieldNumber; private readonly SerializerFeatures _features; private readonly CompatibilityLevel _compatibilityLevel; private readonly DataFormat _dataFormat; private readonly RepeatedSerializerStub _stub; bool IRuntimeProtoSerializerNode.IsScalar { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) ISerializer inbuiltSerializer = TypeModel.GetInbuiltSerializer(_compatibilityLevel, _dataFormat); if (inbuiltSerializer != null) { return SerializerFeaturesExtensions.IsScalar(((ISerializer)(object)inbuiltSerializer).Features); } return false; } } private RepeatedSerializer Serializer => (RepeatedSerializer)_stub.Serializer; public Type ExpectedType => typeof(TCollection); public bool RequiresOldValue => true; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public RepeatedDecorator(int fieldNumber, SerializerFeatures features, CompatibilityLevel compatibilityLevel, DataFormat dataFormat, RepeatedSerializerStub stub) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) _stub = stub; _fieldNumber = fieldNumber; _features = features; _compatibilityLevel = ValueMember.GetEffectiveCompatibilityLevel(compatibilityLevel, dataFormat); _dataFormat = dataFormat; } public object Read(ref State state, object value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) return Serializer.ReadRepeated(ref state, _features, (TCollection)value, TypeModel.GetInbuiltSerializer(_compatibilityLevel, _dataFormat)); } public void EmitRead(CompilerContext ctx, Local valueFrom) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected I4, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) _ = Serializer; MethodInfo method = typeof(RepeatedSerializer).GetMethod("ReadRepeated"); using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); _stub.EmitProvider(ctx); ctx.LoadState(); ctx.LoadValue((int)_features); ctx.LoadValue(local); ctx.LoadSelfAsService, T>(_compatibilityLevel, _dataFormat); ctx.EmitCall(method); } public void Write(ref State state, object value) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) Serializer.WriteRepeated(ref state, _fieldNumber, _features, (TCollection)value, TypeModel.GetInbuiltSerializer(_compatibilityLevel, _dataFormat)); } public void EmitWrite(CompilerContext ctx, Local valueFrom) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected I4, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) MethodInfo method = typeof(RepeatedSerializer).GetMethod("WriteRepeated"); using Local local = ctx.GetLocalWithValue(ExpectedType, valueFrom); _stub.EmitProvider(ctx); ctx.LoadState(); ctx.LoadValue(_fieldNumber); ctx.LoadValue((int)_features); ctx.LoadValue(local); ctx.LoadSelfAsService, T>(_compatibilityLevel, _dataFormat); ctx.EmitCall(method); } } internal sealed class SByteSerializer : IRuntimeProtoSerializerNode { internal static readonly SByteSerializer Instance = new SByteSerializer(); private static readonly Type expectedType = typeof(sbyte); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private SByteSerializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadSByte(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteSByte((sbyte)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteSByte", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadSByte", ExpectedType); } } internal sealed class SingleSerializer : IRuntimeProtoSerializerNode { internal static readonly SingleSerializer Instance = new SingleSerializer(); private static readonly Type expectedType = typeof(float); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private SingleSerializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadSingle(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteSingle((float)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteSingle", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadSingle", ExpectedType); } } internal sealed class StringSerializer : IRuntimeProtoSerializerNode, IDirectWriteNode { internal static readonly StringSerializer Instance = new StringSerializer(); private static readonly Type expectedType = typeof(string); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private StringSerializer() { } public void Write(ref State state, object value) { ((State)(ref state)).WriteString((string)value, (StringMap)null); } public object Read(ref State state, object value) { return ((State)(ref state)).ReadString((StringMap)null); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(typeof(string), valueFrom); ctx.LoadState(); ctx.LoadValue(local); ctx.LoadNullRef(); ctx.EmitCall(typeof(State).GetMethod("WriteString", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { typeof(string), typeof(StringMap) }, null)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.LoadState(); ctx.LoadNullRef(); ctx.EmitCall(typeof(State).GetMethod("ReadString", BindingFlags.Instance | BindingFlags.Public, null, new Type[1] { typeof(StringMap) }, null)); } bool IDirectWriteNode.CanEmitDirectWrite(WireType wireType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 return (int)wireType == 2; } void IDirectWriteNode.EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(typeof(string), valueFrom); ctx.LoadState(); ctx.LoadValue(fieldNumber); ctx.LoadValue(local); ctx.LoadNullRef(); ctx.EmitCall(typeof(State).GetMethod("WriteString", BindingFlags.Instance | BindingFlags.Public, null, new Type[3] { typeof(int), typeof(string), typeof(StringMap) }, null)); } } internal sealed class SubTypeSerializer : SubItemSerializer, IDirectWriteNode where TParent : class where TChild : class, TParent { private static readonly Dictionary s_WriteSubType = (from method in typeof(State).GetMethods(BindingFlags.Instance | BindingFlags.Public) where method.Name == "WriteSubType" && method.IsGenericMethod select new { ArgCount = method.GetParameters().Length, Method = method }).ToDictionary(x => x.ArgCount, x => x.Method); public override bool IsSubType => true; public override Type ExpectedType => typeof(TChild); public override Type BaseType => typeof(TParent); public override void Write(ref State state, object value) { ((State)(ref state)).WriteSubType((TChild)value, (ISubTypeSerializer)null); } public override object Read(ref State state, object value) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) SubTypeState val = (SubTypeState)value; val.ReadSubType(ref state, (ISubTypeSerializer)null); return val; } public override void EmitWrite(CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(typeof(TChild), valueFrom); ctx.LoadState(); ctx.LoadValue(local); ctx.LoadSelfAsService, TChild>((CompatibilityLevel)0, (DataFormat)0); ctx.EmitCall(s_WriteSubType[2].MakeGenericMethod(typeof(TChild))); } bool IDirectWriteNode.CanEmitDirectWrite(WireType wireType) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 return (int)wireType == 2; } void IDirectWriteNode.EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(typeof(TChild), valueFrom); ctx.LoadState(); ctx.LoadValue(fieldNumber); ctx.LoadValue(local); ctx.LoadSelfAsService, TChild>((CompatibilityLevel)0, (DataFormat)0); ctx.EmitCall(s_WriteSubType[3].MakeGenericMethod(typeof(TChild))); } public override void EmitRead(CompilerContext ctx, Local valueFrom) { Type typeFromHandle = typeof(SubTypeState); ctx.LoadAddress(valueFrom, typeFromHandle); ctx.LoadState(); ctx.LoadSelfAsService, TChild>((CompatibilityLevel)0, (DataFormat)0); ctx.EmitCall(typeFromHandle.GetMethod("ReadSubType").MakeGenericMethod(typeof(TChild))); } } internal class SubValueSerializer : SubItemSerializer, IDirectWriteNode { private ISerializer _customSerializer; public override bool IsSubType => false; public override Type ExpectedType => typeof(T); private ISerializer CustomSerializer { get { object obj; if ((object)base.MetaType.SerializerType != null) { obj = _customSerializer; if (obj == null) { return CreateExternal(); } } else { obj = null; } return (ISerializer)obj; } } private ISerializer CreateExternal() { return _customSerializer = (ISerializer)SerializerCache.GetInstance(base.MetaType.SerializerType, typeof(T)); } public override void Write(ref State state, object value) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_003d: Unknown result type (might be due to invalid IL or missing references) SerializerFeatures category = GetCategory(); if ((int)category != 32) { if ((int)category == 64 || (int)category == 96) { ((State)(ref state)).WriteMessage((SerializerFeatures)0, TypeHelper.FromObject(value), CustomSerializer); } else { SerializerFeaturesExtensions.ThrowInvalidCategory(category); } } else { CustomSerializer.Write(ref state, TypeHelper.FromObject(value)); } } private SerializerFeatures GetCategory() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) ISerializer customSerializer = CustomSerializer; if (customSerializer != null) { return SerializerFeaturesExtensions.GetCategory(customSerializer.Features); } return (SerializerFeatures)64; } public override object Read(ref State state, object value) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0047: Unknown result type (might be due to invalid IL or missing references) SerializerFeatures category = GetCategory(); if ((int)category != 32) { if ((int)category == 64 || (int)category == 96) { return ((State)(ref state)).ReadMessage((SerializerFeatures)0, TypeHelper.FromObject(value), CustomSerializer); } SerializerFeaturesExtensions.ThrowInvalidCategory(category); return null; } return CustomSerializer.Read(ref state, TypeHelper.FromObject(value)); } protected override WireType GetDefaultWireType(ref DataFormat dataFormat) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) ISerializer customSerializer = CustomSerializer; if (customSerializer != null) { SerializerFeatures features = customSerializer.Features; if ((int)SerializerFeaturesExtensions.GetCategory(features) == 32) { return SerializerFeaturesExtensions.GetWireType(features); } } return base.GetDefaultWireType(ref dataFormat); } public override void EmitWrite(CompilerContext ctx, Local valueFrom) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_00a1: Unknown result type (might be due to invalid IL or missing references) SerializerFeatures category = GetCategory(); SerializerFeatures category2 = GetCategory(); if ((int)category2 != 32) { if ((int)category2 == 64 || (int)category2 == 96) { SubItemSerializer.EmitWriteMessage(null, (WireType)2, ctx, valueFrom, null, applyRecursionCheck: true, base.MetaType.SerializerType); } else { SerializerFeaturesExtensions.ThrowInvalidCategory(category); } return; } using Local local = ctx.GetLocalWithValue(typeof(T), valueFrom); SubItemSerializer.EmitLoadCustomSerializer(ctx, base.MetaType.SerializerType, typeof(T)); ctx.LoadState(); ctx.LoadValue(local); ctx.EmitCall(typeof(ISerializer).GetMethod("Write", BindingFlags.Instance | BindingFlags.Public)); } public override void EmitRead(CompilerContext ctx, Local valueFrom) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Invalid comparison between Unknown and I4 //IL_0083: Unknown result type (might be due to invalid IL or missing references) using Local local = ctx.GetLocalWithValue(typeof(T), valueFrom); SerializerFeatures category = GetCategory(); if ((int)category != 32) { if ((int)category == 64 || (int)category == 96) { SubItemSerializer.EmitReadMessage(ctx, local, null, base.MetaType.SerializerType); } else { SerializerFeaturesExtensions.ThrowInvalidCategory(category); } } else { SubItemSerializer.EmitLoadCustomSerializer(ctx, base.MetaType.SerializerType, typeof(T)); ctx.LoadState(); ctx.LoadValue(local); ctx.EmitCall(typeof(ISerializer).GetMethod("Read", BindingFlags.Instance | BindingFlags.Public)); } } bool IDirectWriteNode.CanEmitDirectWrite(WireType wireType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 SerializerFeatures category = GetCategory(); if ((int)category == 64 || (int)category == 96) { if ((int)wireType != 2) { if ((int)wireType == 3) { return true; } return false; } return true; } return false; } void IDirectWriteNode.EmitDirectWrite(int fieldNumber, WireType wireType, CompilerContext ctx, Local valueFrom) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) SubItemSerializer.EmitWriteMessage(fieldNumber, wireType, ctx, valueFrom, null, applyRecursionCheck: true, base.MetaType.SerializerType); } } internal abstract class SubItemSerializer : IProtoTypeSerializer, IRuntimeProtoSerializerNode { private static readonly Dictionary s_WriteMessage = (from method in typeof(State).GetMethods(BindingFlags.Instance | BindingFlags.Public) where method.Name == "WriteMessage" && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 1 select new { ArgCount = method.GetParameters().Length, Method = method }).ToDictionary(x => x.ArgCount, x => x.Method); private static readonly Dictionary s_WriteGroup = (from method in typeof(State).GetMethods(BindingFlags.Instance | BindingFlags.Public) where method.Name == "WriteGroup" && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 1 select new { ArgCount = method.GetParameters().Length, Method = method }).ToDictionary(x => x.ArgCount, x => x.Method); private static readonly MethodInfo s_ReadMessage = (from method in typeof(State).GetMethods(BindingFlags.Instance | BindingFlags.Public) where method.Name == "ReadMessage" && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 1 && method.GetParameters().Length == 3 select method).Single(); bool IRuntimeProtoSerializerNode.IsScalar => false; SerializerFeatures IProtoTypeSerializer.Features { get { ThrowHelper.ThrowNotImplementedException("Features"); return (SerializerFeatures)0; } } public abstract bool IsSubType { get; } public abstract Type ExpectedType { get; } public virtual Type BaseType => ExpectedType; bool IProtoTypeSerializer.HasInheritance => false; bool IProtoTypeSerializer.ShouldEmitCreateInstance { get { if (Proxy.Serializer is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.ShouldEmitCreateInstance; } return false; } } bool IRuntimeProtoSerializerNode.RequiresOldValue => true; bool IRuntimeProtoSerializerNode.ReturnsValue => true; protected ISerializerProxy Proxy => MetaType; protected MetaType MetaType { get; private set; } public abstract void Write(ref State state, object value); public abstract object Read(ref State state, object value); public abstract void EmitWrite(CompilerContext ctx, Local valueFrom); public abstract void EmitRead(CompilerContext ctx, Local valueFrom); void IProtoTypeSerializer.EmitReadRoot(CompilerContext ctx, Local valueFrom) { ((IRuntimeProtoSerializerNode)this).EmitRead(ctx, valueFrom); } void IProtoTypeSerializer.EmitWriteRoot(CompilerContext ctx, Local valueFrom) { ((IRuntimeProtoSerializerNode)this).EmitWrite(ctx, valueFrom); } bool IProtoTypeSerializer.HasCallbacks(CallbackType callbackType) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (Proxy.Serializer is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.HasCallbacks(callbackType); } return false; } bool IProtoTypeSerializer.CanCreateInstance() { if (Proxy.Serializer is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.CanCreateInstance(); } return false; } void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) ((IProtoTypeSerializer)Proxy.Serializer).EmitCallback(ctx, valueFrom, callbackType); } void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { ((IProtoTypeSerializer)Proxy.Serializer).EmitCreateInstance(ctx, callNoteObject); } void IProtoTypeSerializer.Callback(object value, CallbackType callbackType, ISerializationContext context) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) ((IProtoTypeSerializer)Proxy.Serializer).Callback(value, callbackType, context); } object IProtoTypeSerializer.CreateInstance(ISerializationContext source) { return ((IProtoTypeSerializer)Proxy.Serializer).CreateInstance(source); } protected static void EmitLoadCustomSerializer(CompilerContext ctx, Type serializerType, Type forType) { MemberInfo underlyingProvider = RuntimeTypeModel.GetUnderlyingProvider(serializerType, forType); RuntimeTypeModel.EmitProvider(underlyingProvider, ctx.IL); } public static void EmitWriteMessage(int? fieldNumber, WireType wireType, CompilerContext ctx, Local value = null, FieldInfo serializer = null, bool applyRecursionCheck = true, Type serializerType = null) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 using Local local = ctx.GetLocalWithValue(typeof(T), value); ctx.LoadState(); if (fieldNumber.HasValue) { ctx.LoadValue(fieldNumber.Value); } ctx.LoadValue((!applyRecursionCheck) ? 1024 : 0); ctx.LoadValue(local); LoadSerializer(ctx, serializer, serializerType); Dictionary dictionary = (((int)wireType != 3) ? s_WriteMessage : s_WriteGroup); Dictionary dictionary2 = dictionary; ctx.EmitCall(dictionary2[fieldNumber.HasValue ? 4 : 3].MakeGenericMethod(typeof(T))); } private static void LoadSerializer(CompilerContext ctx, FieldInfo serializer, Type serializerType) { if ((object)serializerType != null && (ctx.NonPublic || RuntimeTypeModel.IsFullyPublic(serializerType))) { EmitLoadCustomSerializer(ctx, serializerType, typeof(T)); } else if ((object)serializer != null) { ctx.LoadValue(serializer, checkAccessibility: false); } else { ctx.LoadSelfAsService, T>((CompatibilityLevel)0, (DataFormat)0); } } public static void EmitReadMessage(CompilerContext ctx, Local value = null, FieldInfo serializer = null, Type serializerType = null) { ctx.LoadState(); ctx.LoadValue(0); if (value == null) { if (TypeHelper.IsReferenceType) { ctx.LoadNullRef(); } else { using Local local = new Local(ctx, typeof(T)); ctx.InitLocal(typeof(T), local); ctx.LoadValue(local); } } else { ctx.LoadValue(value); } LoadSerializer(ctx, serializer, serializerType); ctx.EmitCall(s_ReadMessage.MakeGenericMethod(typeof(T))); } internal static IRuntimeProtoSerializerNode Create(Type type, MetaType metaType, ref DataFormat dataFormat, out WireType defaultWireType) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected I4, but got Unknown SubItemSerializer subItemSerializer = (SubItemSerializer)Activator.CreateInstance(typeof(SubValueSerializer<>).MakeGenericType(type), nonPublic: true); subItemSerializer.MetaType = metaType ?? throw new ArgumentNullException("metaType"); defaultWireType = (WireType)(int)subItemSerializer.GetDefaultWireType(ref dataFormat); return subItemSerializer; } protected virtual WireType GetDefaultWireType(ref DataFormat dataFormat) { if ((int)dataFormat == 4) { return (WireType)3; } return (WireType)2; } internal static IRuntimeProtoSerializerNode Create(Type actualType, MetaType metaType, Type parentType) { SubItemSerializer subItemSerializer = (SubItemSerializer)Activator.CreateInstance(typeof(SubTypeSerializer<, >).MakeGenericType(parentType, actualType), nonPublic: true); subItemSerializer.MetaType = metaType ?? throw new ArgumentNullException("metaType"); return subItemSerializer; } } internal sealed class SurrogateSerializer : IProtoTypeSerializer, IRuntimeProtoSerializerNode, ISerializer { private readonly Type declaredType; private readonly MethodInfo toTail; private readonly MethodInfo fromTail; private readonly IRuntimeProtoSerializerNode rootTail; private readonly SerializerFeatures features; public SerializerFeatures Features => features; bool IProtoTypeSerializer.IsSubType => false; bool IProtoTypeSerializer.ShouldEmitCreateInstance => false; bool IRuntimeProtoSerializerNode.IsScalar => SerializerFeaturesExtensions.IsScalar(features); public bool ReturnsValue => rootTail.ReturnsValue; public bool RequiresOldValue => rootTail.RequiresOldValue; public Type ExpectedType => typeof(T); Type IProtoTypeSerializer.BaseType => ExpectedType; bool IProtoTypeSerializer.HasInheritance => false; bool IProtoTypeSerializer.HasCallbacks(CallbackType callbackType) { return false; } void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { } void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { throw new NotSupportedException(); } bool IProtoTypeSerializer.CanCreateInstance() { return false; } object IProtoTypeSerializer.CreateInstance(ISerializationContext source) { throw new NotSupportedException(); } void IProtoTypeSerializer.Callback(object value, CallbackType callbackType, ISerializationContext context) { } T ISerializer.Read(ref State state, T value) { return (T)Read(ref state, value); } void ISerializer.Write(ref State state, T value) { Write(ref state, value); } public SurrogateSerializer(Type declaredType, MethodInfo toTail, MethodInfo fromTail, IRuntimeProtoSerializerNode rootTail, SerializerFeatures features) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) this.declaredType = declaredType; this.rootTail = rootTail; this.toTail = toTail ?? GetConversion(toTail: true); this.fromTail = fromTail ?? GetConversion(toTail: false); this.features = features; } private static bool HasCast(Type type, Type from, Type to, out MethodInfo op) { MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Type type2 = null; foreach (MethodInfo methodInfo in methods) { if (methodInfo.ReturnType != to) { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length != 1 || !(parameters[0].ParameterType == from)) { continue; } if ((object)type2 == null) { type2 = typeof(ProtoConverterAttribute); if ((object)type2 == null) { break; } } if (methodInfo.IsDefined(type2, inherit: true)) { op = methodInfo; return true; } } foreach (MethodInfo methodInfo2 in methods) { if ((!(methodInfo2.Name != "op_Implicit") || !(methodInfo2.Name != "op_Explicit")) && !(methodInfo2.ReturnType != to)) { ParameterInfo[] parameters = methodInfo2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == from) { op = methodInfo2; return true; } } } op = null; return false; } public MethodInfo GetConversion(bool toTail) { Type to = (toTail ? declaredType : ExpectedType); Type type = (toTail ? ExpectedType : declaredType); if (HasCast(declaredType, type, to, out var op) || HasCast(ExpectedType, type, to, out op)) { return op; } throw new InvalidOperationException("No suitable conversion operator found for surrogate: " + ExpectedType.FullName + " / " + declaredType.FullName); } public void Write(ref State state, object value) { rootTail.Write(ref state, toTail.Invoke(null, new object[1] { value })); } public object Read(ref State state, object value) { object[] array = new object[1]; if (rootTail.RequiresOldValue) { array[0] = value; value = toTail.Invoke(null, array); } else { value = null; } array[0] = rootTail.Read(ref state, value); return fromTail.Invoke(null, array); } void IProtoTypeSerializer.EmitReadRoot(CompilerContext ctx, Local valueFrom) { ((IRuntimeProtoSerializerNode)this).EmitRead(ctx, valueFrom); } void IProtoTypeSerializer.EmitWriteRoot(CompilerContext ctx, Local valueFrom) { ((IRuntimeProtoSerializerNode)this).EmitWrite(ctx, valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local valueFrom) { using Local local = (rootTail.RequiresOldValue ? new Local(ctx, declaredType) : null); if (rootTail.RequiresOldValue) { ctx.LoadValue(valueFrom); ctx.EmitCall(toTail); ctx.StoreValue(local); } rootTail.EmitRead(ctx, local); ctx.LoadValue(local); ctx.EmitCall(fromTail); ctx.StoreValue(valueFrom); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.LoadValue(valueFrom); ctx.EmitCall(toTail); rootTail.EmitWrite(ctx, null); } } internal sealed class SystemTypeSerializer : IRuntimeProtoSerializerNode { internal static readonly SystemTypeSerializer Instance = new SystemTypeSerializer(); private static readonly Type expectedType = typeof(Type); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private SystemTypeSerializer() { } void IRuntimeProtoSerializerNode.Write(ref State state, object value) { ((State)(ref state)).WriteType((Type)value); } object IRuntimeProtoSerializerNode.Read(ref State state, object value) { return ((State)(ref state)).ReadType(); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteType", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadType", ExpectedType); } } internal sealed class TagDecorator : ProtoDecoratorBase, IProtoTypeSerializer, IRuntimeProtoSerializerNode { private readonly bool strict; private readonly int fieldNumber; private readonly WireType wireType; SerializerFeatures IProtoTypeSerializer.Features => SerializerFeaturesExtensions.AsFeatures(wireType); bool IProtoTypeSerializer.IsSubType { get { if (Tail is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.IsSubType; } return false; } } bool IProtoTypeSerializer.ShouldEmitCreateInstance { get { if (Tail is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.ShouldEmitCreateInstance; } return false; } } public override Type ExpectedType => Tail.ExpectedType; Type IProtoTypeSerializer.BaseType => ExpectedType; public override bool RequiresOldValue => Tail.RequiresOldValue; public override bool ReturnsValue => Tail.ReturnsValue; private bool NeedsHint => (wireType & -8) > 0; bool IProtoTypeSerializer.HasInheritance => false; public bool HasCallbacks(CallbackType callbackType) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (Tail is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.HasCallbacks(callbackType); } return false; } public bool CanCreateInstance() { if (Tail is IProtoTypeSerializer protoTypeSerializer) { return protoTypeSerializer.CanCreateInstance(); } return false; } public object CreateInstance(ISerializationContext source) { return ((IProtoTypeSerializer)Tail).CreateInstance(source); } public void Callback(object value, CallbackType callbackType, ISerializationContext context) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) (Tail as IProtoTypeSerializer)?.Callback(value, callbackType, context); } public void EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) ((IProtoTypeSerializer)Tail).EmitCallback(ctx, valueFrom, callbackType); } public void EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { ((IProtoTypeSerializer)Tail).EmitCreateInstance(ctx, callNoteObject); } public TagDecorator(int fieldNumber, WireType wireType, bool strict, IRuntimeProtoSerializerNode tail) : base(tail) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) this.fieldNumber = fieldNumber; this.wireType = wireType; this.strict = strict; } public override object Read(ref State state, object value) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (strict) { ((State)(ref state)).Assert(wireType); } else if (NeedsHint) { ((State)(ref state)).Hint(wireType); } return Tail.Read(ref state, value); } public override void Write(ref State state, object value) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (Tail is IDirectRuntimeWriteNode directRuntimeWriteNode && directRuntimeWriteNode.CanDirectWrite(wireType)) { directRuntimeWriteNode.DirectWrite(fieldNumber, wireType, ref state, value); return; } ((State)(ref state)).WriteFieldHeader(fieldNumber, wireType); Tail.Write(ref state, value); } void IProtoTypeSerializer.EmitReadRoot(CompilerContext ctx, Local valueFrom) { EmitRead(ctx, valueFrom); } void IProtoTypeSerializer.EmitWriteRoot(CompilerContext ctx, Local valueFrom) { EmitWrite(ctx, valueFrom); } protected override void EmitWrite(CompilerContext ctx, Local valueFrom) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected I4, but got Unknown //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (Tail is IDirectWriteNode directWriteNode && directWriteNode.CanEmitDirectWrite(wireType)) { directWriteNode.EmitDirectWrite(fieldNumber, wireType, ctx, valueFrom); return; } ctx.LoadState(); ctx.LoadValue(fieldNumber); ctx.LoadValue((int)wireType); ctx.EmitCall(typeof(State).GetMethod("WriteFieldHeader")); Tail.EmitWrite(ctx, valueFrom); } public bool CanEmitDirectWrite() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (Tail is IDirectWriteNode directWriteNode) { return directWriteNode.CanEmitDirectWrite(wireType); } return false; } public void EmitDirectWrite(CompilerContext ctx, Local valueFrom) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) ((IDirectWriteNode)Tail).EmitDirectWrite(fieldNumber, wireType, ctx, valueFrom); } protected override void EmitRead(CompilerContext ctx, Local valueFrom) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected I4, but got Unknown if (strict || NeedsHint) { ctx.LoadState(); ctx.LoadValue((int)wireType); string name = (strict ? "Assert" : "Hint"); ctx.EmitCall(typeof(State).GetMethod(name, new Type[1] { typeof(WireType) })); } Tail.EmitRead(ctx, valueFrom); } } internal sealed class TimeSpanSerializer : IRuntimeProtoSerializerNode { private static TimeSpanSerializer s_Legacy; private static TimeSpanSerializer s_Duration; private static readonly Type expectedType = typeof(TimeSpan); private readonly bool _useDuration; bool IRuntimeProtoSerializerNode.IsScalar => false; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; public static TimeSpanSerializer Create(CompatibilityLevel compatibilityLevel) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 object obj; if ((int)compatibilityLevel < 240) { obj = s_Legacy; if (obj == null) { return s_Legacy = new TimeSpanSerializer(useDuration: false); } } else { obj = s_Duration ?? (s_Duration = new TimeSpanSerializer(useDuration: true)); } return (TimeSpanSerializer)obj; } private TimeSpanSerializer(bool useDuration) { _useDuration = useDuration; } public object Read(ref State state, object value) { if (_useDuration) { return BclHelpers.ReadDuration(ref state); } return BclHelpers.ReadTimeSpan(ref state); } public void Write(ref State state, object value) { if (_useDuration) { BclHelpers.WriteDuration(ref state, (TimeSpan)value); } else { BclHelpers.WriteTimeSpan(ref state, (TimeSpan)value); } } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite(_useDuration ? "WriteDuration" : "WriteTimeSpan", valueFrom, typeof(BclHelpers)); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { if (_useDuration) { ctx.LoadValue(entity); } ctx.EmitStateBasedRead(typeof(BclHelpers), _useDuration ? "ReadDuration" : "ReadTimeSpan", ExpectedType); } } internal sealed class TupleSerializer : IProtoTypeSerializer, IRuntimeProtoSerializerNode, ISerializer { private readonly MemberInfo[] members; private readonly ConstructorInfo ctor; private readonly IRuntimeProtoSerializerNode[] tails; bool IRuntimeProtoSerializerNode.IsScalar => false; public SerializerFeatures Features { get; private set; } = (SerializerFeatures)82; bool IProtoTypeSerializer.IsSubType => false; public Type ExpectedType => typeof(T); Type IProtoTypeSerializer.BaseType => typeof(T); public bool RequiresOldValue => true; public bool ReturnsValue => false; bool IProtoTypeSerializer.ShouldEmitCreateInstance => false; bool IProtoTypeSerializer.HasInheritance => false; public TupleSerializer(RuntimeTypeModel model, ConstructorInfo ctor, MemberInfo[] members, SerializerFeatures features, CompatibilityLevel compatibilityLevel) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) this.ctor = ctor ?? throw new ArgumentNullException("ctor"); this.members = members ?? throw new ArgumentNullException("members"); tails = new IRuntimeProtoSerializerNode[members.Length]; Features = features; ParameterInfo[] parameters = ctor.GetParameters(); for (int i = 0; i < members.Length; i++) { Type parameterType = parameters[i].ParameterType; RepeatedSerializerStub repeatedSerializerStub = model.TryGetRepeatedProvider(parameterType, (CompatibilityLevel)0); Type type = repeatedSerializerStub?.ItemType ?? parameterType; bool asReference = false; int num = model.FindOrAddAuto(type, demand: false, addWithContractOnly: true, addEvenIfAutoDisabled: false, compatibilityLevel); if (num >= 0) { asReference = model[type].AsReferenceDefault; } WireType defaultWireType; IRuntimeProtoSerializerNode runtimeProtoSerializerNode = ValueMember.TryGetCoreSerializer(model, (DataFormat)0, compatibilityLevel, type, out defaultWireType, asReference, dynamicType: false, overwriteList: false, allowComplexTypes: true); if (runtimeProtoSerializerNode == null) { ThrowHelper.NoSerializerDefined(type); } IRuntimeProtoSerializerNode runtimeProtoSerializerNode2; if (repeatedSerializerStub == null) { runtimeProtoSerializerNode2 = new TagDecorator(i + 1, defaultWireType, strict: false, runtimeProtoSerializerNode); } else if (repeatedSerializerStub.IsMap) { runtimeProtoSerializerNode2 = ValueMember.CreateMap(repeatedSerializerStub, model, (DataFormat)0, compatibilityLevel, (DataFormat)0, (DataFormat)0, asReference, dynamicType: false, isMap: true, overwriteList: false, i + 1, null); } else { SerializerFeatures features2 = (SerializerFeatures)(SerializerFeaturesExtensions.AsFeatures(defaultWireType) | 0x80); runtimeProtoSerializerNode2 = RepeatedDecorator.Create(repeatedSerializerStub, i + 1, features2, compatibilityLevel, (DataFormat)0); } tails[i] = runtimeProtoSerializerNode2; } } public bool HasCallbacks(CallbackType callbackType) { return false; } public void EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { } void IProtoTypeSerializer.Callback(object value, CallbackType callbackType, ISerializationContext context) { } object IProtoTypeSerializer.CreateInstance(ISerializationContext source) { throw new NotSupportedException(); } private object GetValue(object obj, int index) { if (members[index] is PropertyInfo propertyInfo) { if (obj == null) { if (!propertyInfo.PropertyType.IsValueType) { return null; } return Activator.CreateInstance(propertyInfo.PropertyType, nonPublic: true); } return propertyInfo.GetValue(obj, null); } if (members[index] is FieldInfo fieldInfo) { if (obj == null) { if (!fieldInfo.FieldType.IsValueType) { return null; } return Activator.CreateInstance(fieldInfo.FieldType, nonPublic: true); } return fieldInfo.GetValue(obj); } throw new InvalidOperationException(); } T ISerializer.Read(ref State state, T value) { return (T)Read(ref state, value); } void ISerializer.Write(ref State state, T value) { Write(ref state, value); } public object Read(ref State state, object value) { object[] array = new object[members.Length]; bool flag = false; if (value == null) { flag = true; } for (int i = 0; i < array.Length; i++) { array[i] = GetValue(value, i); } int num; while ((num = ((State)(ref state)).ReadFieldHeader()) > 0) { flag = true; if (num <= tails.Length) { IRuntimeProtoSerializerNode runtimeProtoSerializerNode = tails[num - 1]; array[num - 1] = tails[num - 1].Read(ref state, runtimeProtoSerializerNode.RequiresOldValue ? array[num - 1] : null); } else { ((State)(ref state)).SkipField(); } } if (!flag) { return value; } return ctor.Invoke(array); } public void Write(ref State state, object value) { for (int i = 0; i < tails.Length; i++) { object value2 = GetValue(value, i); if (value2 != null) { tails[i].Write(ref state, value2); } } } bool IProtoTypeSerializer.CanCreateInstance() { return false; } private Type GetMemberType(int index) { return Helpers.GetMemberType(members[index]) ?? throw new InvalidOperationException(); } public void EmitWrite(CompilerContext ctx, Local valueFrom) { using Local local = ctx.GetLocalWithValue(ctor.DeclaringType, valueFrom); for (int i = 0; i < tails.Length; i++) { Type memberType = GetMemberType(i); ctx.LoadAddress(local, ExpectedType); if (members[i] is FieldInfo field) { ctx.LoadValue(field); } else if (members[i] is PropertyInfo property) { ctx.LoadValue(property); } ctx.WriteNullCheckedTail(memberType, tails[i], null); } } void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { throw new NotSupportedException(); } void IProtoTypeSerializer.EmitReadRoot(CompilerContext ctx, Local valueFrom) { EmitRead(ctx, valueFrom); } void IProtoTypeSerializer.EmitWriteRoot(CompilerContext ctx, Local valueFrom) { EmitWrite(ctx, valueFrom); } public void EmitRead(CompilerContext ctx, Local incoming) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected I4, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Invalid comparison between Unknown and I4 using Local local = ctx.GetLocalWithValue(ExpectedType, incoming); Local[] array = new Local[members.Length]; try { for (int i = 0; i < array.Length; i++) { Type memberType = GetMemberType(i); bool flag = true; array[i] = new Local(ctx, memberType); if (ExpectedType.IsValueType) { continue; } if (memberType.IsValueType) { ProtoTypeCode typeCode = Helpers.GetTypeCode(memberType); switch (typeCode - 3) { default: if ((int)typeCode != 102) { goto case 1; } ctx.LoadValue(Guid.Empty); break; case 0: case 2: case 3: case 4: case 5: case 6: case 7: ctx.LoadValue(0); break; case 8: case 9: ctx.LoadValue(0L); break; case 10: ctx.LoadValue(0f); break; case 11: ctx.LoadValue(0.0); break; case 12: ctx.LoadValue(0m); break; case 1: ctx.LoadAddress(array[i], memberType); ctx.EmitCtor(memberType); flag = false; break; } } else { ctx.LoadNullRef(); } if (flag) { ctx.StoreValue(array[i]); } } CodeLabel label = (ExpectedType.IsValueType ? default(CodeLabel) : ctx.DefineLabel()); if (!ExpectedType.IsValueType) { ctx.LoadAddress(local, ExpectedType); ctx.BranchIfFalse(label, @short: false); } for (int j = 0; j < members.Length; j++) { ctx.LoadAddress(local, ExpectedType); if (members[j] is FieldInfo field) { ctx.LoadValue(field); } else if (members[j] is PropertyInfo property) { ctx.LoadValue(property); } ctx.StoreValue(array[j]); } if (!ExpectedType.IsValueType) { ctx.MarkLabel(label); } using (Local local2 = new Local(ctx, typeof(int))) { CodeLabel label2 = ctx.DefineLabel(); CodeLabel label3 = ctx.DefineLabel(); CodeLabel label4 = ctx.DefineLabel(); ctx.Branch(label2, @short: false); CodeLabel[] array2 = new CodeLabel[members.Length]; for (int k = 0; k < members.Length; k++) { array2[k] = ctx.DefineLabel(); } ctx.MarkLabel(label3); ctx.LoadValue(local2); ctx.LoadValue(1); ctx.Subtract(); ctx.Switch(array2); ctx.Branch(label4, @short: false); for (int l = 0; l < array2.Length; l++) { ctx.MarkLabel(array2[l]); IRuntimeProtoSerializerNode runtimeProtoSerializerNode = tails[l]; Local valueFrom = (runtimeProtoSerializerNode.RequiresOldValue ? array[l] : null); ctx.ReadNullCheckedTail(array[l].Type, runtimeProtoSerializerNode, valueFrom); if (runtimeProtoSerializerNode.ReturnsValue) { if (array[l].Type.IsValueType) { ctx.StoreValue(array[l]); } else { CodeLabel label5 = ctx.DefineLabel(); CodeLabel label6 = ctx.DefineLabel(); ctx.CopyValue(); ctx.BranchIfTrue(label5, @short: true); ctx.DiscardValue(); ctx.Branch(label6, @short: true); ctx.MarkLabel(label5); ctx.StoreValue(array[l]); ctx.MarkLabel(label6); } } ctx.Branch(label2, @short: false); } ctx.MarkLabel(label4); ctx.LoadState(); ctx.EmitCall(typeof(State).GetMethod("SkipField", Type.EmptyTypes)); ctx.MarkLabel(label2); ctx.EmitStateBasedRead("ReadFieldHeader", typeof(int)); ctx.CopyValue(); ctx.StoreValue(local2); ctx.LoadValue(0); ctx.BranchIfGreater(label3, @short: false); } for (int m = 0; m < array.Length; m++) { ctx.LoadValue(array[m]); } ctx.EmitCtor(ctor); ctx.StoreValue(local); } finally { for (int n = 0; n < array.Length; n++) { if (array[n] != null) { array[n].Dispose(); } } } } } internal abstract class TypeSerializer { public static IProtoTypeSerializer Create(Type forType, int[] fieldNumbers, IRuntimeProtoSerializerNode[] serializers, MethodInfo[] baseCtorCallbacks, bool isRootType, bool useConstructor, bool assertKnownType, CallbackSet callbacks, Type constructType, MethodInfo factory, Type rootType, SerializerFeatures features) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) TypeSerializer typeSerializer = (TypeSerializer)(((object)rootType != null) ? Activator.CreateInstance(typeof(InheritanceTypeSerializer<, >).MakeGenericType(rootType, forType), nonPublic: true) : Activator.CreateInstance(typeof(TypeSerializer<>).MakeGenericType(forType), nonPublic: true)); typeSerializer.Init(fieldNumbers, serializers, baseCtorCallbacks, isRootType, useConstructor, assertKnownType, callbacks, constructType, factory, features); return (IProtoTypeSerializer)typeSerializer; } internal abstract void Init(int[] fieldNumbers, IRuntimeProtoSerializerNode[] serializers, MethodInfo[] baseCtorCallbacks, bool isRootType, bool useConstructor, bool assertKnownType, CallbackSet callbacks, Type constructType, MethodInfo factory, SerializerFeatures features); } internal sealed class InheritanceTypeSerializer : TypeSerializer, ISubTypeSerializer where TBase : class where T : class, TBase { public override bool HasInheritance => true; internal override Type BaseType => typeof(TBase); public override bool IsSubType => true; public override void Write(ref State state, T value) { ((State)(ref state)).WriteBaseType((TBase)value, (ISubTypeSerializer)null); } public override T Read(ref State state, T value) { return ((State)(ref state)).ReadBaseType(value, (ISubTypeSerializer)null); } unsafe T ISubTypeSerializer.ReadSubType(ref State state, SubTypeState value) { ((SubTypeState*)(&value))->OnBeforeDeserialize((Action)(object)_subTypeOnBeforeDeserialize); DeserializeBody(ref state, ref value, delegate(ref SubTypeState s) { return Unsafe.As, SubTypeState>(ref s).Value; }, delegate(ref SubTypeState s, T v) { Unsafe.As, SubTypeState>(ref s).Value = v; }); T value2 = ((SubTypeState*)(&value))->Value; Callback(ref value2, (CallbackType)3, ((State)(ref state)).Context); return value2; } void ISubTypeSerializer.WriteSubType(ref State state, T value) { SerializeImpl(ref state, value); } public override void EmitReadRoot(CompilerContext context, Local valueFrom) { if (context.IsService) { using (Local local = context.GetLocalWithValue(typeof(T), valueFrom)) { context.LoadSelfAsService, TBase>((CompatibilityLevel)0, (DataFormat)0); context.LoadState(); context.LoadSerializationContext(typeof(ISerializationContext)); context.LoadValue(local); context.EmitCall(typeof(SubTypeState).GetMethod("Create", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeof(T))); context.EmitCall(typeof(ISubTypeSerializer).GetMethod("ReadSubType", BindingFlags.Instance | BindingFlags.Public)); if (typeof(T) != typeof(TBase)) { context.Cast(typeof(T)); } return; } } context.LoadState(); context.LoadValue(valueFrom); context.LoadSelfAsService, TBase>((CompatibilityLevel)0, (DataFormat)0); context.EmitCall(typeof(State).GetMethod("ReadBaseType", BindingFlags.Instance | BindingFlags.Public).MakeGenericMethod(typeof(TBase), typeof(T))); } public override void EmitWriteRoot(CompilerContext context, Local valueFrom) { using Local local = context.GetLocalWithValue(typeof(T), valueFrom); if (context.IsService) { context.LoadSelfAsService, TBase>((CompatibilityLevel)0, (DataFormat)0); context.LoadState(); context.LoadValue(local); context.EmitCall(typeof(ISubTypeSerializer).GetMethod("WriteSubType", BindingFlags.Instance | BindingFlags.Public)); } else { context.LoadState(); context.LoadValue(local); context.LoadSelfAsService, TBase>((CompatibilityLevel)0, (DataFormat)0); context.EmitCall(typeof(ProtoWriter).GetMethod("WriteBaseType", BindingFlags.Instance | BindingFlags.Public).MakeGenericMethod(typeof(TBase))); } } } internal class TypeSerializer : TypeSerializer, ISerializer, IFactory, IProtoTypeSerializer, IRuntimeProtoSerializerNode { private enum StateFlags { None = 0, IsRootType = 1, HasConstructor = 2, UseConstructor = 4, IsExtensible = 8, IsTypedExtensible = 0x10, AssertKnownType = 0x20 } protected delegate T StateGetter(ref TState state); protected delegate void StateSetter(ref TState state, T value); private Type constructType; private IRuntimeProtoSerializerNode[] serializers; private int[] fieldNumbers; private StateFlags flags; private CallbackSet callbacks; private MethodInfo[] baseCtorCallbacks; private MethodInfo factory; protected Action _subTypeOnBeforeDeserialize; bool IRuntimeProtoSerializerNode.IsScalar => false; public virtual bool HasInheritance => false; public virtual bool IsSubType => false; public Type ExpectedType => typeof(T); internal virtual Type BaseType => typeof(T); Type IProtoTypeSerializer.BaseType => BaseType; public SerializerFeatures Features { get; private set; } private bool CanHaveInheritance { get { if (ExpectedType.IsClass || ExpectedType.IsInterface) { return !ExpectedType.IsSealed; } return false; } } bool IRuntimeProtoSerializerNode.RequiresOldValue => true; bool IRuntimeProtoSerializerNode.ReturnsValue => false; private bool UseTypedExtensible { get { if (GetFlag(StateFlags.IsTypedExtensible)) { if (!HasInheritance) { return !GetFlag(StateFlags.IsExtensible); } return true; } return false; } } bool IProtoTypeSerializer.ShouldEmitCreateInstance { get { if ((object)factory == null) { return !GetFlag(StateFlags.UseConstructor); } return true; } } public virtual void EmitReadRoot(CompilerContext context, Local valueFrom) { ((IRuntimeProtoSerializerNode)this).EmitRead(context, valueFrom); } public virtual void EmitWriteRoot(CompilerContext context, Local valueFrom) { ((IRuntimeProtoSerializerNode)this).EmitWrite(context, valueFrom); } T IFactory.Create(ISerializationContext context) { return (T)CreateInstance(context); } public virtual void Write(ref State state, T value) { SerializeImpl(ref state, value); } public virtual T Read(ref State state, T value) { T val = value; if (val == null) { value = (T)CreateInstance(((State)(ref state)).Context); } Callback(ref value, (CallbackType)2, ((State)(ref state)).Context); DeserializeBody(ref state, ref value, delegate(ref T o) { return o; }, delegate(ref T o, T v) { o = v; }); Callback(ref value, (CallbackType)3, ((State)(ref state)).Context); return value; } void IRuntimeProtoSerializerNode.Write(ref State state, object value) { Write(ref state, TypeHelper.FromObject(value)); } object IRuntimeProtoSerializerNode.Read(ref State state, object value) { return Read(ref state, TypeHelper.FromObject(value)); } public bool HasCallbacks(CallbackType callbackType) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (!GetFlag(StateFlags.IsRootType)) { return false; } if (callbacks != null && (object)callbacks[callbackType] != null) { return true; } for (int i = 0; i < serializers.Length; i++) { if (serializers[i].ExpectedType != ExpectedType && ((IProtoTypeSerializer)serializers[i]).HasCallbacks(callbackType)) { return true; } } return false; } private void SetFlag(StateFlags flag, bool value) { if (value) { flags |= flag; } else { flags &= ~flag; } } private bool GetFlag(StateFlags flag) { return (flags & flag) != 0; } internal override void Init(int[] fieldNumbers, IRuntimeProtoSerializerNode[] serializers, MethodInfo[] baseCtorCallbacks, bool isRootType, bool useConstructor, bool assertKnownType, CallbackSet callbacks, Type constructType, MethodInfo factory, SerializerFeatures features) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) Array.Sort(fieldNumbers, serializers); Features = features; bool flag = false; Type expectedType = ExpectedType; for (int i = 0; i < fieldNumbers.Length; i++) { if (i != 0 && fieldNumbers[i] == fieldNumbers[i - 1]) { throw new InvalidOperationException("Duplicate field-number detected; " + fieldNumbers[i] + " on: " + expectedType.FullName); } if (!flag && serializers[i].ExpectedType != expectedType) { flag = true; } } this.factory = factory; if ((object)constructType == null) { constructType = expectedType; } else if (!expectedType.IsAssignableFrom(constructType)) { throw new InvalidOperationException(expectedType.FullName + " cannot be assigned from " + constructType.FullName); } this.constructType = constructType; this.serializers = serializers; this.fieldNumbers = fieldNumbers; this.callbacks = callbacks; SetFlag(StateFlags.IsRootType, isRootType); SetFlag(StateFlags.UseConstructor, useConstructor); SetFlag(StateFlags.AssertKnownType, assertKnownType); if (baseCtorCallbacks != null) { MethodInfo[] array = baseCtorCallbacks; foreach (MethodInfo methodInfo in array) { if (!methodInfo.ReflectedType.IsAssignableFrom(expectedType)) { throw new InvalidOperationException("Trying to assign incompatible callback to " + expectedType.FullName); } } if (baseCtorCallbacks.Length == 0) { baseCtorCallbacks = null; } } this.baseCtorCallbacks = baseCtorCallbacks; if ((object)Nullable.GetUnderlyingType(expectedType) != null) { throw new ArgumentException("Cannot create a TypeSerializer for nullable types", "forType"); } bool flag2 = TypeSerializerMethodCache.Type_IExtensible.IsAssignableFrom(expectedType); bool flag3 = TypeSerializerMethodCache.Type_ITypedIExtensible.IsAssignableFrom(expectedType); if (flag2 || flag3) { if (expectedType.IsValueType || ((!isRootType || flag) && !flag3)) { throw new NotSupportedException("IExtensible is not supported in structs or classes with inheritance without ITypedExtensible"); } SetFlag(StateFlags.IsExtensible, flag2); SetFlag(StateFlags.IsTypedExtensible, flag3); } bool flag4 = !constructType.IsAbstract && (object)Helpers.GetConstructor(constructType, Type.EmptyTypes, true) != null; SetFlag(StateFlags.HasConstructor, flag4); if (constructType != expectedType && useConstructor && !flag4) { throw new ArgumentException("The supplied default implementation cannot be created: " + constructType.FullName, "constructType"); } if (HasInheritance && callbacks != null) { _subTypeOnBeforeDeserialize = delegate(T val, ISerializationContext ctx) { Callback(ref val, (CallbackType)2, ctx); }; } } bool IProtoTypeSerializer.CanCreateInstance() { return true; } object IProtoTypeSerializer.CreateInstance(ISerializationContext context) { return CreateInstance(context); } void IProtoTypeSerializer.Callback(object value, CallbackType callbackType, ISerializationContext context) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (GetFlag(StateFlags.IsRootType) && callbacks != null) { InvokeCallback(callbacks[callbackType], value, context); } } public void Callback(ref T value, CallbackType callbackType, ISerializationContext context) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (GetFlag(StateFlags.IsRootType) && callbacks != null) { object obj = value; InvokeCallback(callbacks[callbackType], obj, context); value = (T)obj; } } private IRuntimeProtoSerializerNode GetMoreSpecificSerializer(object value) { if (!CanHaveInheritance) { return null; } Type type = value.GetType(); if (type == ExpectedType) { return null; } for (int i = 0; i < serializers.Length; i++) { IRuntimeProtoSerializerNode runtimeProtoSerializerNode = serializers[i]; if (runtimeProtoSerializerNode is IProtoTypeSerializer { IsSubType: not false } && runtimeProtoSerializerNode.ExpectedType.IsAssignableFrom(type)) { return runtimeProtoSerializerNode; } } if (type == constructType) { return null; } if (GetFlag(StateFlags.AssertKnownType)) { TypeModel.ThrowUnexpectedSubtype(ExpectedType, type); } return null; } protected void SerializeImpl(ref State state, T value) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown Callback(ref value, (CallbackType)0, ((State)(ref state)).Context); if (CanHaveInheritance) { GetMoreSpecificSerializer(value)?.Write(ref state, value); } for (int i = 0; i < serializers.Length; i++) { IRuntimeProtoSerializerNode runtimeProtoSerializerNode = serializers[i]; if (!(runtimeProtoSerializerNode is IProtoTypeSerializer { IsSubType: not false })) { runtimeProtoSerializerNode.Write(ref state, value); } } if (UseTypedExtensible) { ((State)(ref state)).AppendExtensionData((ITypedExtensible)(object)value, ExpectedType); } else if (GetFlag(StateFlags.IsExtensible)) { ((State)(ref state)).AppendExtensionData((IExtensible)(object)value); } Callback(ref value, (CallbackType)1, ((State)(ref state)).Context); } protected void DeserializeBody(ref State state, ref TState bodyState, StateGetter getter, StateSetter setter) { //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown int num = 0; int num2 = 0; int num3; while ((num3 = ((State)(ref state)).ReadFieldHeader()) > 0) { bool flag = false; if (num3 < num) { num = (num2 = 0); } for (int i = num2; i < fieldNumbers.Length; i++) { if (fieldNumbers[i] != num3) { continue; } IRuntimeProtoSerializerNode runtimeProtoSerializerNode = serializers[i]; if (runtimeProtoSerializerNode is IProtoTypeSerializer { IsSubType: not false }) { bodyState = (TState)runtimeProtoSerializerNode.Read(ref state, bodyState); } else { T val = getter(ref bodyState); object obj = val; object obj2 = runtimeProtoSerializerNode.Read(ref state, obj); if (runtimeProtoSerializerNode.ReturnsValue) { setter(ref bodyState, (T)obj2); } else if (ExpectedType.IsValueType) { setter(ref bodyState, (T)obj); } } num2 = i; num = num3; flag = true; break; } if (!flag) { if (UseTypedExtensible) { T val2 = getter(ref bodyState); ((State)(ref state)).AppendExtensionData((ITypedExtensible)(object)val2, ExpectedType); } else if (GetFlag(StateFlags.IsExtensible)) { T val3 = getter(ref bodyState); ((State)(ref state)).AppendExtensionData((IExtensible)(object)val3); } else { ((State)(ref state)).SkipField(); } } } } private object InvokeCallback(MethodInfo method, object obj, ISerializationContext serializationContext) { object result = null; if ((object)method != null) { ParameterInfo[] parameters = method.GetParameters(); object[] array; bool flag; if (parameters.Length == 0) { array = null; flag = true; } else { array = new object[parameters.Length]; flag = true; for (int i = 0; i < array.Length; i++) { Type parameterType = parameters[i].ParameterType; object obj2; if (parameterType == typeof(ISerializationContext)) { obj2 = serializationContext; } else if (parameterType == typeof(SerializationContext)) { obj2 = SerializationContext.AsSerializationContext(serializationContext); } else if (parameterType == typeof(StreamingContext)) { obj2 = SerializationContext.AsStreamingContext(serializationContext); } else if (parameterType == typeof(Type)) { obj2 = constructType; } else { obj2 = null; flag = false; } array[i] = obj2; } } if (!flag) { throw CallbackSet.CreateInvalidCallbackSignature(method); } result = method.Invoke(obj, array); } return result; } private object CreateInstance(ISerializationContext context) { if ((object)factory != null) { return InvokeCallback(factory, null, context); } if (GetFlag(StateFlags.UseConstructor)) { if (!GetFlag(StateFlags.HasConstructor)) { TypeModel.ThrowCannotCreateInstance(constructType, (Exception)null); } return Activator.CreateInstance(constructType, nonPublic: true); } return BclHelpers.GetUninitializedObject(constructType); } private void LoadFromState(CompilerContext ctx, Local value) { if (HasInheritance) { Type type = typeof(SubTypeState<>).MakeGenericType(typeof(T)); PropertyInfo property = type.GetProperty("Value"); ctx.LoadAddress(value, type); ctx.EmitCall(property.GetGetMethod()); } else { ctx.LoadValue(value); } } private void WriteToState(CompilerContext ctx, Local state, Local value, Type type) { if (HasInheritance) { Type type2 = typeof(SubTypeState<>).MakeGenericType(typeof(T)); PropertyInfo property = type2.GetProperty("Value"); if (value == null) { using (Local local = new Local(ctx, type)) { ctx.LoadValue(value); ctx.StoreValue(local); ctx.LoadAddress(state, type2); ctx.LoadValue(local); ctx.EmitCall(property.GetSetMethod()); return; } } ctx.LoadAddress(state, type2); ctx.LoadValue(value); ctx.EmitCall(property.GetSetMethod()); } else { ctx.LoadValue(value); ctx.StoreValue(state); } } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { Type expectedType = ExpectedType; using Local local = ctx.GetLocalWithValue(expectedType, valueFrom); EmitCallbackIfNeeded(ctx, local, (CallbackType)0); CodeLabel label = ctx.DefineLabel(); if (CanHaveInheritance) { if (serializers.Any((IRuntimeProtoSerializerNode x) => x is IProtoTypeSerializer protoTypeSerializer3 && protoTypeSerializer3.IsSubType)) { ctx.LoadValue(local); ctx.EmitCall(typeof(TypeModel).GetMethod("IsSubType", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeof(T))); ctx.BranchIfFalse(label, @short: false); for (int num = 0; num < serializers.Length; num++) { IRuntimeProtoSerializerNode runtimeProtoSerializerNode = serializers[num]; Type expectedType2 = runtimeProtoSerializerNode.ExpectedType; if (!(runtimeProtoSerializerNode is IProtoTypeSerializer { IsSubType: not false })) { continue; } CodeLabel label2 = ctx.DefineLabel(); ctx.LoadValue(local); ctx.TryCast(expectedType2); using Local local2 = new Local(ctx, expectedType2); ctx.StoreValue(local2); ctx.LoadValue(local2); ctx.BranchIfFalse(label2, @short: false); if (expectedType2.IsValueType) { ctx.LoadValue(local); ctx.CastFromObject(expectedType2); runtimeProtoSerializerNode.EmitWrite(ctx, null); } else { runtimeProtoSerializerNode.EmitWrite(ctx, local2); } ctx.Branch(label, @short: false); ctx.MarkLabel(label2); } } if (GetFlag(StateFlags.AssertKnownType)) { MethodInfo method = (((object)constructType == null || !(constructType != ExpectedType)) ? TypeSerializerMethodCache.ThrowUnexpectedSubtype[1].MakeGenericMethod(ExpectedType) : TypeSerializerMethodCache.ThrowUnexpectedSubtype[2].MakeGenericMethod(ExpectedType, constructType)); ctx.LoadValue(local); ctx.EmitCall(method); } } ctx.MarkLabel(label); for (int num2 = 0; num2 < serializers.Length; num2++) { IRuntimeProtoSerializerNode runtimeProtoSerializerNode2 = serializers[num2]; if (!(runtimeProtoSerializerNode2 is IProtoTypeSerializer { IsSubType: not false })) { runtimeProtoSerializerNode2.EmitWrite(ctx, local); } } if (UseTypedExtensible) { using Local local3 = ctx.GetLocalWithValue(typeof(ITypedExtensible), local); ctx.LoadState(); ctx.LoadValue(local3); ctx.LoadValue(ExpectedType); ctx.EmitCall(TypeSerializerMethodCache.Method_Write_AppendExtensionData_ITypedExtensible); } else if (GetFlag(StateFlags.IsExtensible)) { using Local local4 = ctx.GetLocalWithValue(typeof(IExtensible), local); ctx.LoadState(); ctx.LoadValue(local4); ctx.EmitCall(TypeSerializerMethodCache.Method_Write_AppendExtensionData_IExtensible); } EmitCallbackIfNeeded(ctx, local, (CallbackType)1); } private static void EmitInvokeCallback(CompilerContext ctx, MethodInfo method, Type constructType, Type type, Local valueFrom) { if ((object)method == null) { return; } if (!method.IsStatic) { if (type.IsValueType) { ctx.LoadAddress(valueFrom, type); } else { ctx.LoadValue(valueFrom); } } ParameterInfo[] parameters = method.GetParameters(); bool flag = true; for (int i = 0; i < parameters.Length; i++) { Type parameterType = parameters[i].ParameterType; if (parameterType == typeof(ISerializationContext) || parameterType == typeof(StreamingContext) || parameterType == typeof(SerializationContext)) { ctx.LoadSerializationContext(parameterType); } else if (parameterType == typeof(Type)) { Type type2 = constructType ?? type; ctx.LoadValue(type2); } else { flag = false; } } if (flag) { ctx.EmitCall(method); if ((object)constructType != null && method.ReturnType == typeof(object)) { ctx.CastFromObject(type); } return; } throw CallbackSet.CreateInvalidCallbackSignature(method); } private void EmitCallbackIfNeeded(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (GetFlag(StateFlags.IsRootType) && ((IProtoTypeSerializer)this).HasCallbacks(callbackType)) { if (HasInheritance && (int)callbackType == 2) { ThrowHelper.ThrowInvalidOperationException("Should be using sub-type-state API", (Exception)null); } else if (HasInheritance && (int)callbackType == 3) { LoadFromState(ctx, valueFrom); ((IProtoTypeSerializer)this).EmitCallback(ctx, (Local)null, callbackType); } else { ((IProtoTypeSerializer)this).EmitCallback(ctx, valueFrom, callbackType); } } } void IProtoTypeSerializer.EmitCallback(CompilerContext ctx, Local valueFrom, CallbackType callbackType) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) bool flag = false; if (CanHaveInheritance) { for (int i = 0; i < serializers.Length; i++) { IRuntimeProtoSerializerNode runtimeProtoSerializerNode = serializers[i]; if (runtimeProtoSerializerNode.ExpectedType != ExpectedType && ((IProtoTypeSerializer)runtimeProtoSerializerNode).HasCallbacks(callbackType)) { flag = true; break; } } } MethodInfo methodInfo = callbacks?[callbackType]; if ((object)methodInfo != null || flag) { EmitInvokeCallback(ctx, methodInfo, null, ExpectedType, valueFrom); if (flag && BaseType != ExpectedType) { throw new NotSupportedException("Currently, serializatation callbacks are limited to the base-type in a hierarchy, but " + TypeHelper.NormalizeName(ExpectedType) + " defines callbacks; this may be resolved in later versions; it is recommended to make the serialization callbacks 'virtual' methods on " + TypeHelper.NormalizeName(BaseType) + "; or for the best compatibility with other serializers (DataContractSerializer, etc) - make the callbacks non-virtual methods on " + TypeHelper.NormalizeName(BaseType) + " that *call* protected virtual methods on " + TypeHelper.NormalizeName(BaseType)); } } } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local valueFrom) { Type type = (HasInheritance ? typeof(SubTypeState<>).MakeGenericType(ExpectedType) : ExpectedType); using Local local = ctx.GetLocalWithValue(type, valueFrom); using Local local2 = new Local(ctx, typeof(int)); if (!ExpectedType.IsValueType && !HasInheritance) { EmitCreateIfNull(ctx, local); } if (HasCallbacks((CallbackType)2)) { if (HasInheritance) { MethodInfo methodInfo = callbacks?[(CallbackType)2]; if ((object)methodInfo != null) { ctx.LoadAddress(local, type); FieldInfo field = ctx.Scope.DefineSubTypeStateCallbackField(methodInfo); ctx.LoadValue(field, checkAccessibility: false); ctx.EmitCall(type.GetMethod("OnBeforeDeserialize")); } } else { EmitCallbackIfNeeded(ctx, local, (CallbackType)2); } } CodeLabel codeLabel = ctx.DefineLabel(); CodeLabel label = ctx.DefineLabel(); ctx.Branch(codeLabel, @short: false); ctx.MarkLabel(label); foreach (BasicList.Group contiguousGroup in BasicList.GetContiguousGroups(fieldNumbers, serializers)) { CodeLabel label2 = ctx.DefineLabel(); int count = contiguousGroup.Items.Count; if (count == 1) { ctx.LoadValue(local2); ctx.LoadValue(contiguousGroup.First); CodeLabel codeLabel2 = ctx.DefineLabel(); ctx.BranchIfEqual(codeLabel2, @short: true); ctx.Branch(label2, @short: false); WriteFieldHandler(ctx, ExpectedType, local, codeLabel2, codeLabel, contiguousGroup.Items[0]); } else { ctx.LoadValue(local2); ctx.LoadValue(contiguousGroup.First); ctx.Subtract(); CodeLabel[] array = new CodeLabel[count]; for (int i = 0; i < count; i++) { array[i] = ctx.DefineLabel(); } ctx.Switch(array); ctx.Branch(label2, @short: false); for (int j = 0; j < count; j++) { WriteFieldHandler(ctx, ExpectedType, local, array[j], codeLabel, contiguousGroup.Items[j]); } } ctx.MarkLabel(label2); } ctx.LoadState(); if (UseTypedExtensible) { LoadFromState(ctx, local); ctx.LoadValue(ExpectedType); ctx.EmitCall(TypeSerializerMethodCache.Method_Read_AppendExtensionData_ITypedExtensible); } else if (GetFlag(StateFlags.IsExtensible)) { LoadFromState(ctx, local); ctx.EmitCall(TypeSerializerMethodCache.Method_Read_AppendExtensionData_IExtensible); } else { ctx.EmitCall(typeof(State).GetMethod("SkipField", Type.EmptyTypes)); } ctx.MarkLabel(codeLabel); ctx.EmitStateBasedRead("ReadFieldHeader", typeof(int)); ctx.CopyValue(); ctx.StoreValue(local2); ctx.LoadValue(0); ctx.BranchIfGreater(label, @short: false); if (HasCallbacks((CallbackType)3)) { EmitCallbackIfNeeded(ctx, local, (CallbackType)3); } if (HasInheritance) { LoadFromState(ctx, local); } else if (valueFrom != null && !local.IsSame(valueFrom)) { LoadFromState(ctx, local); ctx.StoreValue(valueFrom); } } private void WriteFieldHandler(CompilerContext ctx, Type expected, Local loc, CodeLabel handler, CodeLabel @continue, IRuntimeProtoSerializerNode serializer) { ctx.MarkLabel(handler); bool flag = false; if (HasInheritance) { if (serializer is IProtoTypeSerializer { IsSubType: not false }) { flag = true; serializer.EmitRead(ctx, loc); } else { LoadFromState(ctx, loc); serializer.EmitRead(ctx, null); } } else { serializer.EmitRead(ctx, loc); } if (!flag && serializer.ReturnsValue) { WriteToState(ctx, loc, null, serializer.ExpectedType); } ctx.Branch(@continue, @short: false); } void IProtoTypeSerializer.EmitCreateInstance(CompilerContext ctx, bool callNoteObject) { if ((object)factory != null) { EmitInvokeCallback(ctx, factory, constructType, ExpectedType, null); } else if (!GetFlag(StateFlags.UseConstructor)) { ctx.LoadValue(constructType); ctx.EmitCall(typeof(BclHelpers).GetMethod("GetUninitializedObject")); ctx.Cast(ExpectedType); } else if (constructType.IsClass && GetFlag(StateFlags.HasConstructor)) { ctx.EmitCtor(constructType); } else { ctx.LoadValue(ExpectedType); ctx.LoadNullRef(); ctx.EmitCall(typeof(TypeModel).GetMethod("ThrowCannotCreateInstance", BindingFlags.Static | BindingFlags.Public)); ctx.LoadNullRef(); callNoteObject = false; } if (callNoteObject || baseCtorCallbacks != null) { using (Local local = new Local(ctx, ExpectedType)) { ctx.StoreValue(local); ctx.LoadValue(local); } } } private void EmitCreateIfNull(CompilerContext ctx, Local storage) { if (!ExpectedType.IsValueType) { CodeLabel label = ctx.DefineLabel(); ctx.LoadValue(storage); ctx.BranchIfTrue(label, @short: false); ((IProtoTypeSerializer)this).EmitCreateInstance(ctx, callNoteObject: true); ctx.StoreValue(storage); ctx.MarkLabel(label); } } } internal static class TypeSerializerMethodCache { internal static readonly Type Type_IExtensible = typeof(IExtensible); internal static readonly Type Type_ITypedIExtensible = typeof(ITypedExtensible); internal static readonly MethodInfo Method_Write_AppendExtensionData_IExtensible = typeof(State).GetMethod("AppendExtensionData", new Type[1] { typeof(IExtensible) }); internal static readonly MethodInfo Method_Write_AppendExtensionData_ITypedExtensible = typeof(State).GetMethod("AppendExtensionData", new Type[2] { typeof(ITypedExtensible), typeof(Type) }); internal static readonly MethodInfo Method_Read_AppendExtensionData_IExtensible = typeof(State).GetMethod("AppendExtensionData", new Type[1] { typeof(IExtensible) }); internal static readonly MethodInfo Method_Read_AppendExtensionData_ITypedExtensible = typeof(State).GetMethod("AppendExtensionData", new Type[2] { typeof(ITypedExtensible), typeof(Type) }); internal static readonly Dictionary ThrowUnexpectedSubtype = (from method in typeof(TypeModel).GetMethods(BindingFlags.Static | BindingFlags.Public) where method.Name == "ThrowUnexpectedSubtype" && method.IsGenericMethodDefinition where method.GetParameters().Length == 1 let args = method.GetGenericArguments() select new { Count = args.Length, Method = method }).ToDictionary(x => x.Count, x => x.Method); } internal class UInt16Serializer : IRuntimeProtoSerializerNode { internal static readonly UInt16Serializer Instance = new UInt16Serializer(); private static readonly Type expectedType = typeof(ushort); bool IRuntimeProtoSerializerNode.IsScalar => true; public virtual Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; protected UInt16Serializer() { } public virtual object Read(ref State state, object value) { return ((State)(ref state)).ReadUInt16(); } public virtual void Write(ref State state, object value) { ((State)(ref state)).WriteUInt16((ushort)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteUInt16", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadUInt16", typeof(ushort)); } } internal sealed class UInt32Serializer : IRuntimeProtoSerializerNode { internal static readonly UInt32Serializer Instance = new UInt32Serializer(); private static readonly Type expectedType = typeof(uint); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private UInt32Serializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadUInt32(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteUInt32((uint)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteUInt32", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadUInt32", typeof(uint)); } } internal sealed class UInt64Serializer : IRuntimeProtoSerializerNode { internal static readonly UInt64Serializer Instance = new UInt64Serializer(); private static readonly Type expectedType = typeof(ulong); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => expectedType; bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private UInt64Serializer() { } public object Read(ref State state, object value) { return ((State)(ref state)).ReadUInt64(); } public void Write(ref State state, object value) { ((State)(ref state)).WriteUInt64((ulong)value); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteUInt64", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadUInt64", ExpectedType); } } internal sealed class UIntPtrSerializer : IRuntimeProtoSerializerNode { internal static readonly UIntPtrSerializer Instance = new UIntPtrSerializer(); bool IRuntimeProtoSerializerNode.IsScalar => true; public Type ExpectedType => typeof(UIntPtr); bool IRuntimeProtoSerializerNode.RequiresOldValue => false; bool IRuntimeProtoSerializerNode.ReturnsValue => true; private UIntPtrSerializer() { } public void Write(ref State state, object value) { ((State)(ref state)).WriteUIntPtr((UIntPtr)value); } public object Read(ref State state, object value) { return ((State)(ref state)).ReadUIntPtr(); } void IRuntimeProtoSerializerNode.EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.EmitStateBasedWrite("WriteUIntPtr", valueFrom); } void IRuntimeProtoSerializerNode.EmitRead(CompilerContext ctx, Local entity) { ctx.EmitStateBasedRead("ReadUIntPtr", ExpectedType); } } internal sealed class UriDecorator : ProtoDecoratorBase { private static readonly Type expectedType = typeof(Uri); public override bool IsScalar => true; public override Type ExpectedType => expectedType; public override bool RequiresOldValue => false; public override bool ReturnsValue => true; public UriDecorator(IRuntimeProtoSerializerNode tail) : base(tail) { } public override void Write(ref State state, object value) { Tail.Write(ref state, ((Uri)value).OriginalString); } public override object Read(ref State state, object value) { string text = (string)Tail.Read(ref state, null); if (text.Length != 0) { return new Uri(text, UriKind.RelativeOrAbsolute); } return null; } protected override void EmitWrite(CompilerContext ctx, Local valueFrom) { ctx.LoadValue(valueFrom); ctx.LoadValue(typeof(Uri).GetProperty("OriginalString")); Tail.EmitWrite(ctx, null); } protected override void EmitRead(CompilerContext ctx, Local valueFrom) { Tail.EmitRead(ctx, valueFrom); ctx.CopyValue(); CodeLabel label = ctx.DefineLabel(); CodeLabel label2 = ctx.DefineLabel(); ctx.LoadValue(typeof(string).GetProperty("Length")); ctx.BranchIfTrue(label, @short: true); ctx.DiscardValue(); ctx.LoadNullRef(); ctx.Branch(label2, @short: true); ctx.MarkLabel(label); ctx.LoadValue(0); ctx.EmitCtor(typeof(Uri), typeof(string), typeof(UriKind)); ctx.MarkLabel(label2); } } } namespace ProtoBuf.Extensions { internal static class StringBuilderExtensions { public static StringBuilder NewLine(this StringBuilder builder, ref int pos, int indent) { return builder.Insert(Environment.NewLine, ref pos).Insert(" ", ref pos, indent * 3); } public static StringBuilder Insert(this StringBuilder builder, string value, ref int pos, Func condition, int count = 1) { if (!condition()) { return builder; } return builder.Insert(value, ref pos, count); } public static StringBuilder Insert(this StringBuilder builder, string value, ref int pos, int count = 1) { int length = builder.Length; builder.Insert(pos, value, count); int num = builder.Length - length; pos += num; return builder; } } } namespace ProtoBuf.Compiler { [StructLayout(LayoutKind.Auto)] internal readonly struct CodeLabel { public readonly Label Value; public readonly int Index; public CodeLabel(Label value, int index) { Value = value; Index = index; } } internal sealed class CompilerContext : IDisposable { internal enum SignatureType { WriterScope_Input, ReaderScope_Input, Context } internal static class StateBasedReadMethods { internal static readonly Type ByRefStateType = typeof(State).MakeByRefType(); private static readonly Hashtable s_perTypeCache = new Hashtable(); private static Dictionary CreateAndAdd(Type parentType) { Dictionary dictionary = new Dictionary(StringComparer.Ordinal); MethodInfo[] methods = parentType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.IsDefined(typeof(ObsoleteAttribute), inherit: true)) { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (methodInfo.IsStatic) { if (parameters.Length != 1 || parameters[0].ParameterType != ByRefStateType) { continue; } } else if (parameters.Length != 0) { continue; } dictionary.Add(methodInfo.Name, methodInfo); } lock (s_perTypeCache) { s_perTypeCache[parentType] = dictionary; return dictionary; } } internal static bool Find(Type parentType, string methodName, out MethodInfo method) { Dictionary dictionary = ((Dictionary)s_perTypeCache[parentType]) ?? CreateAndAdd(parentType); return dictionary.TryGetValue(methodName, out method); } } private sealed class UsingBlock : IDisposable { private Local local; private CompilerContext ctx; private CodeLabel label; public UsingBlock(CompilerContext ctx, Local local) { if (local == null) { throw new ArgumentNullException("local"); } Type type = local.Type; if ((!type.IsValueType && !type.IsSealed) || typeof(IDisposable).IsAssignableFrom(type)) { this.local = local; this.ctx = ctx ?? throw new ArgumentNullException("ctx"); label = ctx.BeginTry(); } } public void Dispose() { if (this.local == null || ctx == null) { return; } ctx.EndTry(label, @short: false); ctx.BeginFinally(); Type typeFromHandle = typeof(IDisposable); MethodInfo method = typeFromHandle.GetMethod("Dispose"); Type type = this.local.Type; if (type.IsValueType) { ctx.LoadAddress(this.local, type); ctx.Constrain(type); ctx.EmitCall(method); } else { CodeLabel codeLabel = ctx.DefineLabel(); if (typeFromHandle.IsAssignableFrom(type)) { ctx.LoadValue(this.local); ctx.BranchIfFalse(codeLabel, @short: true); ctx.LoadAddress(this.local, type); } else { using Local local = new Local(ctx, typeFromHandle); ctx.LoadValue(this.local); ctx.TryCast(typeFromHandle); ctx.CopyValue(); ctx.StoreValue(local); ctx.BranchIfFalse(codeLabel, @short: true); ctx.LoadAddress(local, typeFromHandle); } ctx.EmitCall(method); ctx.MarkLabel(codeLabel); } ctx.EndFinally(); this.local = null; ctx = null; label = default(CodeLabel); } } private readonly DynamicMethod method; private static int next; private static readonly MethodInfo s_CreateInstance = typeof(State).GetMethod("CreateInstance", BindingFlags.Instance | BindingFlags.Public); private readonly string _traceName; private readonly OpCode _state; private readonly byte _inputArg; private readonly SignatureType _signature; private static readonly MethodInfo s_GetInbuiltSerializer = typeof(TypeModel).GetMethod("GetInbuiltSerializer", BindingFlags.Static | BindingFlags.Public); private readonly ILGenerator il; private readonly List locals = new List(); private int nextLabel; private List knownTrustedAssemblies; private List knownUntrustedAssemblies; public TypeModel Model { get; } internal bool NonPublic { get; } public Local InputValue { get; } public bool IsStatic { get; } internal CompilerContextScope Scope { get; } public bool IsService { get { if (Scope.IsFullEmit) { return !IsStatic; } return false; } } internal ILGenerator IL => il; internal CodeLabel DefineLabel() { CodeLabel result = new CodeLabel(il.DefineLabel(), nextLabel++); return result; } [Conditional("DEBUG_COMPILE")] private void TraceCompile(string value) { } internal void MarkLabel(CodeLabel label) { il.MarkLabel(label.Value); } public static ProtoSerializer BuildSerializer(CompilerContextScope scope, IRuntimeProtoSerializerNode head, TypeModel model) { Type expectedType = head.ExpectedType; try { using CompilerContext compilerContext = new CompilerContext(scope, expectedType, SignatureType.WriterScope_Input, isStatic: true, model, typeof(TActual), null); compilerContext.WriteNullCheckedTail(expectedType, head, compilerContext.InputValue); compilerContext.Emit(OpCodes.Ret); return (ProtoSerializer)compilerContext.method.CreateDelegate(typeof(ProtoSerializer)); } catch (Exception innerException) { string text = expectedType.FullName; if (string.IsNullOrEmpty(text)) { text = expectedType.Name; } throw new InvalidOperationException("It was not possible to prepare a serializer for: " + text, innerException); } } public static ProtoSubTypeDeserializer BuildSubTypeDeserializer(CompilerContextScope scope, IRuntimeProtoSerializerNode head, TypeModel model) where T : class { using CompilerContext compilerContext = new CompilerContext(scope, head.ExpectedType, SignatureType.ReaderScope_Input, isStatic: true, model, typeof(SubTypeState), typeof(T)); head.EmitRead(compilerContext, compilerContext.InputValue); compilerContext.Return(); return (ProtoSubTypeDeserializer)compilerContext.method.CreateDelegate(typeof(ProtoSubTypeDeserializer)); } public static ProtoDeserializer BuildDeserializer(CompilerContextScope scope, IRuntimeProtoSerializerNode head, TypeModel model, bool isScalar = false) { using CompilerContext compilerContext = new CompilerContext(scope, head.ExpectedType, SignatureType.ReaderScope_Input, isStatic: true, model, typeof(T), typeof(T)); head.EmitRead(compilerContext, compilerContext.InputValue); if (!isScalar) { compilerContext.LoadValue(compilerContext.InputValue); } compilerContext.Return(); return (ProtoDeserializer)compilerContext.method.CreateDelegate(typeof(ProtoDeserializer)); } public static Func BuildFactory(CompilerContextScope scope, IRuntimeProtoSerializerNode head, TypeModel model) { if (head is IProtoTypeSerializer { ShouldEmitCreateInstance: not false } protoTypeSerializer) { using CompilerContext compilerContext = new CompilerContext(scope, head.ExpectedType, SignatureType.Context, isStatic: true, model, typeof(ISerializationContext), typeof(T)); protoTypeSerializer.EmitCreateInstance(compilerContext, callNoteObject: false); compilerContext.Return(); return (Func)compilerContext.method.CreateDelegate(typeof(Func)); } return null; } internal void CreateInstance() { LoadState(); LoadNullRef(); EmitCall(s_CreateInstance.MakeGenericMethod(typeof(T))); } internal void Return() { Emit(OpCodes.Ret); } private static bool IsObject(Type type) { return type == typeof(object); } internal void CastToObject(Type type) { if (!IsObject(type)) { if (type.IsValueType) { il.Emit(OpCodes.Box, type); } else { il.Emit(OpCodes.Castclass, typeof(object)); } } } internal void CastFromObject(Type type) { if (!IsObject(type)) { if (type.IsValueType) { il.Emit(OpCodes.Unbox_Any, type); } else { il.Emit(OpCodes.Castclass, type); } } } internal CompilerContext(CompilerContext parent, ILGenerator il, bool isStatic, SignatureType signature, Type inputType, string traceName) : this(parent.Scope, il, isStatic, signature, parent.Model, inputType, traceName) { } internal void ThrowException(Type exceptionType) { il.ThrowException(exceptionType); } internal CompilerContext(CompilerContextScope scope, ILGenerator il, bool isStatic, SignatureType signature, TypeModel model, Type inputType, string traceName) { Scope = scope; this.il = il ?? throw new ArgumentNullException("il"); Model = model ?? throw new ArgumentNullException("model"); if ((object)inputType != null) { InputValue = new Local(null, inputType); } _traceName = traceName; IsStatic = isStatic; _signature = signature; GetOpCodes(signature, isStatic, out _state, out _inputArg); } public override string ToString() { return _traceName; } private static void GetOpCodes(SignatureType signature, bool isStatic, out OpCode state, out byte inputArg) { if ((uint)signature <= 1u) { state = (isStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1); inputArg = (byte)(isStatic ? 1u : 2u); } else { state = default(OpCode); inputArg = ((!isStatic) ? ((byte)1) : ((byte)0)); } } private CompilerContext(CompilerContextScope scope, Type associatedType, SignatureType signature, bool isStatic, TypeModel model, Type inputType, Type returnType) { Scope = scope; Model = model ?? throw new ArgumentNullException("model"); NonPublic = true; _signature = signature; GetOpCodes(signature, isStatic, out _state, out _inputArg); Type[] parameterTypes = signature switch { SignatureType.ReaderScope_Input => new Type[2] { StateBasedReadMethods.ByRefStateType, inputType }, SignatureType.WriterScope_Input => new Type[2] { WriterUtil.ByRefStateType, inputType }, _ => new Type[1] { inputType }, }; method = new DynamicMethod("proto_" + Interlocked.Increment(ref next).ToString(CultureInfo.InvariantCulture), returnType ?? typeof(void), parameterTypes, associatedType.IsInterface ? typeof(object) : associatedType, skipVisibility: true); il = method.GetILGenerator(); if ((object)inputType != null) { InputValue = new Local(null, inputType); } _traceName = method.Name; IsStatic = isStatic; } public void LoadSelfAsService(CompatibilityLevel compatibilityLevel, DataFormat dataFormat) where TService : class { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected I4, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected I4, but got Unknown ISerializer inbuiltSerializer = TypeModel.GetInbuiltSerializer(compatibilityLevel, dataFormat); if (IsStatic || inbuiltSerializer != null) { if (inbuiltSerializer != null && typeof(TService) == typeof(ISerializer) && !(inbuiltSerializer is PrimaryTypeProvider)) { LoadValue((int)compatibilityLevel); LoadValue((int)dataFormat); EmitCall(s_GetInbuiltSerializer.MakeGenericMethod(typeof(T))); } else { LoadNullRef(); } } else { Emit(OpCodes.Ldarg_0); if (!Scope.IsFullEmit || !Scope.ImplementsServiceFor(compatibilityLevel)) { TryCast(typeof(TService)); } } } internal void Emit(OpCode opcode) { il.Emit(opcode); } public void LoadValue(string value) { if (value == null) { LoadNullRef(); } else { il.Emit(OpCodes.Ldstr, value); } } public void LoadValue(float value) { il.Emit(OpCodes.Ldc_R4, value); } public void LoadValue(double value) { il.Emit(OpCodes.Ldc_R8, value); } public void LoadValue(ulong value) { LoadValue((long)value); } public void LoadValue(long value) { il.Emit(OpCodes.Ldc_I8, value); } public void LoadValue(bool value) { Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } public void LoadValue(int value) { switch (value) { case 0: Emit(OpCodes.Ldc_I4_0); return; case 1: Emit(OpCodes.Ldc_I4_1); return; case 2: Emit(OpCodes.Ldc_I4_2); return; case 3: Emit(OpCodes.Ldc_I4_3); return; case 4: Emit(OpCodes.Ldc_I4_4); return; case 5: Emit(OpCodes.Ldc_I4_5); return; case 6: Emit(OpCodes.Ldc_I4_6); return; case 7: Emit(OpCodes.Ldc_I4_7); return; case 8: Emit(OpCodes.Ldc_I4_8); return; case -1: Emit(OpCodes.Ldc_I4_M1); return; } if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } } void IDisposable.Dispose() { } internal LocalBuilder GetFromPool(Type type) { int count = locals.Count; for (int i = 0; i < count; i++) { LocalBuilder localBuilder = locals[i]; if (localBuilder != null && localBuilder.LocalType == type) { locals[i] = null; return localBuilder; } } return il.DeclareLocal(type); } internal void ReleaseToPool(LocalBuilder value) { int count = locals.Count; for (int i = 0; i < count; i++) { if (locals[i] == null) { locals[i] = value; return; } } locals.Add(value); } public void LoadState() { Emit(_state); } public void StoreValue(Local local) { if (local == InputValue) { il.Emit(OpCodes.Starg_S, _inputArg); } else if (local != null) { switch (local.Value.LocalIndex) { case 0: Emit(OpCodes.Stloc_0); break; case 1: Emit(OpCodes.Stloc_1); break; case 2: Emit(OpCodes.Stloc_2); break; case 3: Emit(OpCodes.Stloc_3); break; default: { OpCode opcode = (UseShortForm(local) ? OpCodes.Stloc_S : OpCodes.Stloc); il.Emit(opcode, local.Value); break; } } } } public void LoadValue(Local local) { if (local == null) { return; } if (local == InputValue) { switch (_inputArg) { case 0: Emit(OpCodes.Ldarg_0); break; case 1: Emit(OpCodes.Ldarg_1); break; case 2: Emit(OpCodes.Ldarg_2); break; case 3: Emit(OpCodes.Ldarg_3); break; default: il.Emit(OpCodes.Ldarg_S, _inputArg); break; } return; } switch (local.Value.LocalIndex) { case 0: Emit(OpCodes.Ldloc_0); break; case 1: Emit(OpCodes.Ldloc_1); break; case 2: Emit(OpCodes.Ldloc_2); break; case 3: Emit(OpCodes.Ldloc_3); break; default: { OpCode opcode = (UseShortForm(local) ? OpCodes.Ldloc_S : OpCodes.Ldloc); il.Emit(opcode, local.Value); break; } } } public Local GetLocalWithValue(Type type, Local fromValue) { if (fromValue != null) { if (fromValue.Type == type) { return fromValue.AsCopy(); } LoadValue(fromValue); if (!type.IsValueType && ((object)fromValue.Type == null || !type.IsAssignableFrom(fromValue.Type))) { Cast(type); } } Local local = new Local(this, type); StoreValue(local); return local; } internal void EmitStateBasedRead(string methodName, Type expectedType) { EmitStateBasedRead(typeof(State), methodName, expectedType); } internal void EmitStateBasedRead(Type ownerType, string methodName, Type expectedType) { if (!StateBasedReadMethods.Find(ownerType, methodName, out var methodInfo)) { throw new ArgumentException("No suitable '" + methodName + "' method found on " + ownerType.Name); } if (methodInfo.ReturnType != expectedType) { throw new ArgumentException("Method '" + methodName + "' has wrong return type; got " + methodInfo.ReturnType.Name + ", expected " + expectedType.Name); } LoadState(); EmitCall(methodInfo); } internal void EmitStateBasedWrite(string methodName, Local fromValue, Type type = null, Type argType = null) { if (string.IsNullOrEmpty(methodName)) { throw new ArgumentNullException("methodName"); } if ((object)type == null) { type = typeof(State); } Type type2; MethodInfo methodInfo; try { var anon = (from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public) where method.Name == methodName && !method.IsGenericMethodDefinition && method.ReturnType == typeof(void) let args = method.GetParameters() where args.Length == ((!method.IsStatic) ? 1 : 2) && (!method.IsStatic || args[0].ParameterType == WriterUtil.ByRefStateType) let paramType = args[method.IsStatic ? 1u : 0u].ParameterType where (object)argType == null || argType == paramType select new { Method = method, Type = paramType }).Single(); type2 = anon.Type; methodInfo = anon.Method; } catch (Exception innerException) { throw new InvalidOperationException("Unable to uniquely resolve " + type.Name + "." + methodName, innerException); } using Local local = GetLocalWithValue(type2, fromValue); LoadState(); LoadValue(local); EmitCall(methodInfo); } public void EmitCall(MethodInfo method) { EmitCall(method, null); } public void EmitCall(MethodInfo method, Type targetType) { MemberInfo member = method ?? throw new ArgumentNullException("method"); CheckAccessibility(ref member); OpCode opcode; if (method.IsStatic || method.DeclaringType.IsValueType) { opcode = OpCodes.Call; } else { opcode = OpCodes.Callvirt; if ((object)targetType != null && targetType.IsValueType && !method.DeclaringType.IsValueType) { Constrain(targetType); } } il.EmitCall(opcode, method, null); } public void LoadNullRef() { Emit(OpCodes.Ldnull); } internal void WriteNullCheckedTail(Type type, IRuntimeProtoSerializerNode tail, Local valueFrom) { if (tail is TagDecorator tagDecorator && tagDecorator.ExpectedType == type && tagDecorator.CanEmitDirectWrite()) { tagDecorator.EmitDirectWrite(this, valueFrom); } else if (type.IsValueType) { Type underlyingType = Nullable.GetUnderlyingType(type); if ((object)underlyingType != null) { using (Local local = GetLocalWithValue(type, valueFrom)) { LoadAddress(local, type); LoadValue(type.GetProperty("HasValue")); CodeLabel label = DefineLabel(); BranchIfFalse(label, @short: false); LoadAddress(local, type); EmitCall(type.GetMethod("GetValueOrDefault", Type.EmptyTypes)); tail.EmitWrite(this, null); MarkLabel(label); return; } } tail.EmitWrite(this, valueFrom); } else { LoadValue(valueFrom); CopyValue(); CodeLabel label2 = DefineLabel(); CodeLabel label3 = DefineLabel(); BranchIfTrue(label2, @short: true); DiscardValue(); Branch(label3, @short: false); MarkLabel(label2); tail.EmitWrite(this, null); MarkLabel(label3); } } internal void ReadNullCheckedTail(Type type, IRuntimeProtoSerializerNode tail, Local valueFrom) { Type underlyingType; if (type.IsValueType && type != tail.ExpectedType && (object)(underlyingType = Nullable.GetUnderlyingType(type)) != null && underlyingType == tail.ExpectedType) { if (tail.RequiresOldValue) { using Local local = GetLocalWithValue(type, valueFrom); LoadAddress(local, type); EmitCall(type.GetMethod("GetValueOrDefault", Type.EmptyTypes)); } tail.EmitRead(this, null); if (tail.ReturnsValue) { EmitCtor(type, underlyingType); } } else { tail.EmitRead(this, valueFrom); } } public void EmitCtor(Type type) { EmitCtor(type, Type.EmptyTypes); } public void EmitCtor(ConstructorInfo ctor) { if ((object)ctor == null) { throw new ArgumentNullException("ctor"); } MemberInfo member = ctor; CheckAccessibility(ref member); il.Emit(OpCodes.Newobj, ctor); } public void InitLocal(Type type, Local target) { LoadAddress(target, type, evenIfClass: true); il.Emit(OpCodes.Initobj, type); } public void EmitCtor(Type type, params Type[] parameterTypes) { if (type.IsValueType && parameterTypes.Length == 0) { il.Emit(OpCodes.Initobj, type); return; } ConstructorInfo ctor = Helpers.GetConstructor(type, parameterTypes, true) ?? throw new InvalidOperationException("No suitable constructor found for " + type.FullName); EmitCtor(ctor); } private bool InternalsVisible(Assembly assembly) { if (string.IsNullOrEmpty(Scope.AssemblyName)) { return false; } if (knownTrustedAssemblies != null && knownTrustedAssemblies.IndexOf(assembly) >= 0) { return true; } if (knownUntrustedAssemblies != null && knownUntrustedAssemblies.IndexOf(assembly) >= 0) { return false; } bool flag = false; Type typeFromHandle = typeof(InternalsVisibleToAttribute); if ((object)typeFromHandle == null) { return false; } object[] customAttributes = assembly.GetCustomAttributes(typeFromHandle, inherit: false); for (int i = 0; i < customAttributes.Length; i++) { InternalsVisibleToAttribute internalsVisibleToAttribute = (InternalsVisibleToAttribute)customAttributes[i]; if (internalsVisibleToAttribute.AssemblyName == Scope.AssemblyName || internalsVisibleToAttribute.AssemblyName.StartsWith(Scope.AssemblyName + ",", StringComparison.Ordinal)) { flag = true; break; } } if (flag) { (knownTrustedAssemblies ?? (knownTrustedAssemblies = new List())).Add(assembly); } else { (knownUntrustedAssemblies ?? (knownUntrustedAssemblies = new List())).Add(assembly); } return flag; } internal void CheckAccessibility(ref MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("member"); } if (NonPublic) { return; } if (member is FieldInfo && (member.Name.StartsWith("<", StringComparison.Ordinal) & member.Name.EndsWith(">k__BackingField", StringComparison.Ordinal))) { string name = member.Name.Substring(1, member.Name.Length - 17); PropertyInfo property = member.DeclaringType.GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); if ((object)property != null) { member = property; } } MemberTypes memberType = member.MemberType; bool flag; switch (memberType) { case MemberTypes.TypeInfo: { Type type = (Type)member; flag = type.IsPublic || InternalsVisible(type.Assembly); break; } case MemberTypes.NestedType: { Type type = (Type)member; do { flag = type.IsNestedPublic || type.IsPublic || (((object)type.DeclaringType == null || type.IsNestedAssembly || type.IsNestedFamORAssem) && InternalsVisible(type.Assembly)); } while (flag && (object)(type = type.DeclaringType) != null); break; } case MemberTypes.Field: { FieldInfo fieldInfo = (FieldInfo)member; flag = fieldInfo.IsPublic || ((fieldInfo.IsAssembly || fieldInfo.IsFamilyOrAssembly) && InternalsVisible(fieldInfo.DeclaringType.Assembly)); break; } case MemberTypes.Constructor: { ConstructorInfo constructorInfo = (ConstructorInfo)member; flag = constructorInfo.IsPublic || ((constructorInfo.IsAssembly || constructorInfo.IsFamilyOrAssembly) && InternalsVisible(constructorInfo.DeclaringType.Assembly)); break; } case MemberTypes.Method: { MethodInfo methodInfo = (MethodInfo)member; flag = methodInfo.IsPublic || ((methodInfo.IsAssembly || methodInfo.IsFamilyOrAssembly) && InternalsVisible(methodInfo.DeclaringType.Assembly)); if (!flag && (member is MethodBuilder || member.DeclaringType == typeof(TypeModel))) { flag = true; } break; } case MemberTypes.Property: flag = true; break; default: throw new NotSupportedException(memberType.ToString()); } if (!flag) { MemberInfo memberInfo = member; if (!(memberInfo is FieldBuilder) && !(memberInfo is TypeBuilder) && !(memberInfo is PropertyBuilder)) { InvalidOperationException ex = ((memberType != MemberTypes.TypeInfo && memberType != MemberTypes.NestedType) ? new InvalidOperationException("Non-public member cannot be used with full dll compilation: " + TypeHelper.NormalizeName(member.DeclaringType) + "." + member.Name) : new InvalidOperationException("Non-public type cannot be used with full dll compilation: " + TypeHelper.NormalizeName((Type)member))); throw ex; } } } public void LoadValue(FieldInfo field, bool checkAccessibility = true) { MemberInfo member = field; if (checkAccessibility) { CheckAccessibility(ref member); } if (member is PropertyInfo property) { LoadValue(property); return; } OpCode opcode = (field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld); il.Emit(opcode, field); } public void StoreValue(FieldInfo field) { MemberInfo member = field; CheckAccessibility(ref member); if (member is PropertyInfo property) { StoreValue(property); return; } OpCode opcode = (field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld); il.Emit(opcode, field); } public void LoadValue(PropertyInfo property) { MemberInfo member = property; CheckAccessibility(ref member); EmitCall(Helpers.GetGetMethod(property, true, true)); } public void StoreValue(PropertyInfo property) { MemberInfo member = property; CheckAccessibility(ref member); EmitCall(Helpers.GetSetMethod(property, true, true)); } internal static void LoadValue(ILGenerator il, int value) { switch (value) { case 0: il.Emit(OpCodes.Ldc_I4_0); return; case 1: il.Emit(OpCodes.Ldc_I4_1); return; case 2: il.Emit(OpCodes.Ldc_I4_2); return; case 3: il.Emit(OpCodes.Ldc_I4_3); return; case 4: il.Emit(OpCodes.Ldc_I4_4); return; case 5: il.Emit(OpCodes.Ldc_I4_5); return; case 6: il.Emit(OpCodes.Ldc_I4_6); return; case 7: il.Emit(OpCodes.Ldc_I4_7); return; case 8: il.Emit(OpCodes.Ldc_I4_8); return; case -1: il.Emit(OpCodes.Ldc_I4_M1); return; } if (value >= -128 && value <= 127) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } } private static bool UseShortForm(Local local) { return local.Value.LocalIndex < 256; } internal void LoadAddress(Local local, Type type, bool evenIfClass = false) { if (evenIfClass || type.IsValueType) { if (local == null) { throw new InvalidOperationException("Cannot load the address of the head of the stack"); } if (local == InputValue) { il.Emit(OpCodes.Ldarga_S, _inputArg); return; } OpCode opcode = (UseShortForm(local) ? OpCodes.Ldloca_S : OpCodes.Ldloca); il.Emit(opcode, local.Value); } else { LoadValue(local); } } internal void Branch(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Br_S : OpCodes.Br); il.Emit(opcode, label.Value); } internal void BranchIfFalse(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Brfalse_S : OpCodes.Brfalse); il.Emit(opcode, label.Value); } internal void BranchIfTrue(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Brtrue_S : OpCodes.Brtrue); il.Emit(opcode, label.Value); } internal void BranchIfEqual(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Beq_S : OpCodes.Beq); il.Emit(opcode, label.Value); } internal void CopyValue() { Emit(OpCodes.Dup); } internal void BranchIfGreater(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Bgt_S : OpCodes.Bgt); il.Emit(opcode, label.Value); } internal void BranchIfLess(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Blt_S : OpCodes.Blt); il.Emit(opcode, label.Value); } internal void DiscardValue() { Emit(OpCodes.Pop); } public void Subtract() { Emit(OpCodes.Sub); } public void Switch(CodeLabel[] jumpTable) { if (jumpTable.Length <= 128) { Label[] array = new Label[jumpTable.Length]; for (int i = 0; i < array.Length; i++) { array[i] = jumpTable[i].Value; } il.Emit(OpCodes.Switch, array); return; } using Local local = GetLocalWithValue(typeof(int), null); int num = jumpTable.Length; int num2 = 0; int num3 = num / 128; if (num % 128 != 0) { num3++; } Label[] array2 = new Label[num3]; for (int j = 0; j < num3; j++) { array2[j] = il.DefineLabel(); } CodeLabel label = DefineLabel(); LoadValue(local); LoadValue(128); Emit(OpCodes.Div); il.Emit(OpCodes.Switch, array2); Branch(label, @short: false); Label[] array3 = new Label[128]; for (int k = 0; k < num3; k++) { il.MarkLabel(array2[k]); int num4 = Math.Min(128, num); num -= num4; if (array3.Length != num4) { array3 = new Label[num4]; } int num5 = num2; for (int l = 0; l < num4; l++) { array3[l] = jumpTable[num2++].Value; } LoadValue(local); if (num5 != 0) { LoadValue(num5); Emit(OpCodes.Sub); } il.Emit(OpCodes.Switch, array3); if (num != 0) { Branch(label, @short: false); } } MarkLabel(label); } internal void EndFinally() { il.EndExceptionBlock(); } internal void BeginFinally() { il.BeginFinallyBlock(); } internal void EndTry(CodeLabel label, bool @short) { OpCode opcode = (@short ? OpCodes.Leave_S : OpCodes.Leave); il.Emit(opcode, label.Value); } internal CodeLabel BeginTry() { CodeLabel result = new CodeLabel(il.BeginExceptionBlock(), nextLabel++); return result; } internal void Constrain(Type type) { il.Emit(OpCodes.Constrained, type); } internal void TryCast(Type type) { il.Emit(OpCodes.Isinst, type); } internal void Cast(Type type) { il.Emit(OpCodes.Castclass, type); } public IDisposable Using(Local local) { return new UsingBlock(this, local); } internal void Add() { Emit(OpCodes.Add); } internal void LoadLength(Local arr, bool zeroIfNull) { if (zeroIfNull) { CodeLabel label = DefineLabel(); CodeLabel label2 = DefineLabel(); LoadValue(arr); CopyValue(); BranchIfTrue(label, @short: true); DiscardValue(); LoadValue(0); Branch(label2, @short: true); MarkLabel(label); Emit(OpCodes.Ldlen); Emit(OpCodes.Conv_I4); MarkLabel(label2); } else { LoadValue(arr); Emit(OpCodes.Ldlen); Emit(OpCodes.Conv_I4); } } internal void CreateArray(Type elementType, Local length) { LoadValue(length); il.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayValue(Local arr, Local i) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected I4, but got Unknown Type type = arr.Type; type = type.GetElementType(); LoadValue(arr); LoadValue(i); ProtoTypeCode typeCode = Helpers.GetTypeCode(type); switch (typeCode - 5) { case 0: Emit(OpCodes.Ldelem_I1); return; case 2: Emit(OpCodes.Ldelem_I2); return; case 4: Emit(OpCodes.Ldelem_I4); return; case 6: Emit(OpCodes.Ldelem_I8); return; case 1: Emit(OpCodes.Ldelem_U1); return; case 3: Emit(OpCodes.Ldelem_U2); return; case 5: Emit(OpCodes.Ldelem_U4); return; case 7: Emit(OpCodes.Ldelem_I8); return; case 8: Emit(OpCodes.Ldelem_R4); return; case 9: Emit(OpCodes.Ldelem_R8); return; } if (type.IsValueType) { il.Emit(OpCodes.Ldelema, type); il.Emit(OpCodes.Ldobj, type); } else { Emit(OpCodes.Ldelem_Ref); } } internal static void LoadValue(ILGenerator il, Type type) { il.Emit(OpCodes.Ldtoken, type); il.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null); } internal void LoadValue(Type type) { il.Emit(OpCodes.Ldtoken, type); EmitCall(typeof(Type).GetMethod("GetTypeFromHandle")); } internal unsafe void ConvertToInt32(ProtoTypeCode typeCode, bool uint32Overflow) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected I4, but got Unknown switch (typeCode - 5) { case 0: case 1: case 2: case 3: Emit(OpCodes.Conv_I4); break; case 6: Emit(OpCodes.Conv_Ovf_I4); break; case 5: Emit(uint32Overflow ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4); break; case 7: Emit(OpCodes.Conv_Ovf_I4_Un); break; default: throw new InvalidOperationException("ConvertToInt32 not implemented for: " + ((object)(*(ProtoTypeCode*)(&typeCode))/*cast due to .constrained prefix*/).ToString()); case 4: break; } } internal void ConvertFromInt32(ProtoTypeCode typeCode, bool uint32Overflow) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected I4, but got Unknown switch (typeCode - 5) { case 0: Emit(OpCodes.Conv_Ovf_I1); break; case 1: Emit(OpCodes.Conv_Ovf_U1); break; case 2: Emit(OpCodes.Conv_Ovf_I2); break; case 3: Emit(OpCodes.Conv_Ovf_U2); break; case 5: Emit(uint32Overflow ? OpCodes.Conv_Ovf_U4 : OpCodes.Conv_U4); break; case 6: Emit(OpCodes.Conv_I8); break; case 7: Emit(OpCodes.Conv_U8); break; default: throw new InvalidOperationException(); case 4: break; } } internal void LoadValue(decimal value) { if (value == 0m) { LoadValue(typeof(decimal).GetField("Zero")); return; } int[] bits = decimal.GetBits(value); LoadValue(bits[0]); LoadValue(bits[1]); LoadValue(bits[2]); LoadValue(bits[3] >>> 31); LoadValue((bits[3] >> 16) & 0xFF); EmitCtor(typeof(decimal), typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte)); } internal void LoadValue(Guid value) { if (value == Guid.Empty) { LoadValue(typeof(Guid).GetField("Empty")); return; } byte[] array = value.ToByteArray(); int value2 = array[0] | (array[1] << 8) | (array[2] << 16) | (array[3] << 24); LoadValue(value2); short value3 = (short)(array[4] | (array[5] << 8)); LoadValue(value3); value3 = (short)(array[6] | (array[7] << 8)); LoadValue(value3); for (value2 = 8; value2 <= 15; value2++) { LoadValue(array[value2]); } EmitCtor(typeof(Guid), typeof(int), typeof(short), typeof(short), typeof(byte), typeof(byte), typeof(byte), typeof(byte), typeof(byte), typeof(byte), typeof(byte), typeof(byte)); } internal void LoadSerializationContext(Type asType) { LoadState(); switch (_signature) { case SignatureType.WriterScope_Input: LoadValue(typeof(State).GetProperty("Context")); break; case SignatureType.ReaderScope_Input: LoadValue(typeof(State).GetProperty("Context")); break; case SignatureType.Context: LoadValue(InputValue); break; default: ThrowHelper.ThrowInvalidOperationException($"Cannot load context for {_signature}", (Exception)null); break; } if (!(asType == typeof(ISerializationContext))) { if (asType == typeof(SerializationContext)) { EmitCall(typeof(SerializationContext).GetMethod("AsSerializationContext")); } else if (asType == typeof(StreamingContext)) { EmitCall(typeof(SerializationContext).GetMethod("AsStreamingContext")); } else { ThrowHelper.ThrowArgumentException("Unexpected context type: " + TypeHelper.NormalizeName(asType)); } } } internal bool AllowInternal(PropertyInfo property) { if (!NonPublic) { return InternalsVisible(property.DeclaringType.Assembly); } return true; } } internal sealed class CompilerContextScope { private static class SharedModule { internal static readonly ModuleBuilder Shared = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("SharedModule"), AssemblyBuilderAccess.RunAndCollect).DefineDynamicModule("SharedModule"); } private ModuleBuilder _module; private readonly RuntimeTypeModel _model; private int _localUniqueId; private static int s_globalUniqueId; internal string AssemblyName { get; } public bool IsFullEmit { get; } internal static CompilerContextScope CreateInProcess() { return new CompilerContextScope(null, null, isFullEmit: false, null); } internal static CompilerContextScope CreateForModule(RuntimeTypeModel model, ModuleBuilder module, bool isFullEmit, string assemblyName) { return new CompilerContextScope(model, module, isFullEmit, assemblyName); } private CompilerContextScope(RuntimeTypeModel model, ModuleBuilder module, bool isFullEmit, string assemblyName) { _model = model; _module = module; IsFullEmit = isFullEmit; AssemblyName = assemblyName; } private ModuleBuilder GetModule() { return _module ?? (_module = GetSharedModule()); } [MethodImpl(MethodImplOptions.NoInlining)] private static ModuleBuilder GetSharedModule() { return SharedModule.Shared; } internal static ILGenerator Implement(TypeBuilder type, Type interfaceType, string name, bool @explicit = true) { MethodInfo methodInfo = interfaceType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public) ?? throw new ArgumentException("Declaration not found for '" + name + "'", "name"); ParameterInfo[] parameters = methodInfo.GetParameters(); string text = name; MethodAttributes methodAttributes = (methodInfo.Attributes & ~MethodAttributes.Abstract) | MethodAttributes.Final; if (@explicit) { text = TypeHelper.NormalizeName(interfaceType) + "." + text; methodAttributes &= ~MethodAttributes.MemberAccessMask; methodAttributes |= MethodAttributes.Private | MethodAttributes.HideBySig; } MethodBuilder methodBuilder = type.DefineMethod(text, methodAttributes, methodInfo.ReturnType, Array.ConvertAll(parameters, (ParameterInfo x) => x.ParameterType)); for (int num = 0; num < parameters.Length; num++) { methodBuilder.DefineParameter(num + 1, parameters[num].Attributes, parameters[num].Name); } type.DefineMethodOverride(methodBuilder, methodInfo); return methodBuilder.GetILGenerator(); } private int Uniquify() { if (!IsFullEmit) { return Interlocked.Increment(ref s_globalUniqueId); } return Interlocked.Increment(ref _localUniqueId); } internal FieldInfo DefineSubTypeStateCallbackField(MethodInfo callback) { if (typeof(T).IsValueType) { ThrowHelper.ThrowInvalidOperationException("Not expected for value-type", (Exception)null); } Type typeFromHandle = typeof(Action); ModuleBuilder module = GetModule(); lock (module) { string text = "<" + callback.Name + ">_helper_" + Uniquify(); TypeBuilder typeBuilder; try { typeBuilder = module.DefineType(text, TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit); } catch (Exception innerException) { throw new InvalidOperationException("Unable to define type: " + text, innerException); } string text2 = "s_" + callback.Name; FieldAttributes fieldAttributes = FieldAttributes.Assembly | FieldAttributes.Static; if (IsFullEmit) { fieldAttributes |= FieldAttributes.InitOnly; } FieldBuilder field = typeBuilder.DefineField(text2, typeFromHandle, fieldAttributes); if (IsFullEmit) { MethodBuilder methodBuilder = typeBuilder.DefineMethod(callback.Name, MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, typeof(void), new Type[2] { typeof(T), typeof(ISerializationContext) }); methodBuilder.DefineParameter(1, ParameterAttributes.None, "obj"); methodBuilder.DefineParameter(2, ParameterAttributes.None, "context"); WriteCall(methodBuilder.GetILGenerator(), callback); ConstructorBuilder constructorBuilder = typeBuilder.DefineTypeInitializer(); ILGenerator iLGenerator = constructorBuilder.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldnull); iLGenerator.Emit(OpCodes.Ldftn, methodBuilder); iLGenerator.Emit(OpCodes.Newobj, typeFromHandle.GetConstructors().Single()); iLGenerator.Emit(OpCodes.Stsfld, field); iLGenerator.Emit(OpCodes.Ret); } Type type = typeBuilder.CreateType(); FieldInfo field2 = type.GetField(text2, BindingFlags.Static | BindingFlags.NonPublic); if (!IsFullEmit) { DynamicMethod dynamicMethod = new DynamicMethod(callback.Name, typeof(void), new Type[2] { typeof(T), typeof(ISerializationContext) }, typeof(T), skipVisibility: true); WriteCall(dynamicMethod.GetILGenerator(), callback); field2.SetValue(null, dynamicMethod.CreateDelegate(typeFromHandle)); } return field2; } static void WriteCall(ILGenerator il, MethodInfo methodInfo) { il.Emit(OpCodes.Ldarg_0); ParameterInfo[] parameters = methodInfo.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { Type parameterType = parameterInfo.ParameterType; if (parameterType == typeof(ISerializationContext)) { il.Emit(OpCodes.Ldarg_1); } else if (parameterType == typeof(SerializationContext)) { il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Call, typeof(SerializationContext).GetMethod("AsSerializationContext"), null); } else if (parameterType == typeof(StreamingContext)) { il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Call, typeof(SerializationContext).GetMethod("AsStreamingContext"), null); } else { ThrowHelper.ThrowNotSupportedException($"Unknown callback parameter: {parameterInfo.Name}, {parameterType}"); } } il.EmitCall(OpCodes.Callvirt, methodInfo, null); il.Emit(OpCodes.Ret); } } internal bool ImplementsServiceFor(CompatibilityLevel ambient) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (_model == null || typeof(T).IsEnum || (object)Nullable.GetUnderlyingType(typeof(T)) != null) { return false; } if (!((TypeModel)_model).IsKnownType(ambient)) { return false; } MetaType metaType = _model[typeof(T)]; if (metaType == null) { return false; } if ((object)metaType.SerializerType != null) { return false; } if (_model.TryGetRepeatedProvider(metaType.Type, (CompatibilityLevel)0) != null) { return false; } return true; } } internal delegate void ProtoSerializer(ref State state, T value); internal delegate T ProtoDeserializer(ref State state, T value); internal delegate T ProtoSubTypeDeserializer(ref State state, SubTypeState value) where T : class; internal sealed class Local : IDisposable { private LocalBuilder value; private readonly Type type; private CompilerContext ctx; internal LocalBuilder Value => value ?? throw new ObjectDisposedException(GetType().Name); public Type Type => type; private Local(LocalBuilder value, Type type) { this.value = value; this.type = type; } internal Local(CompilerContext ctx, Type type) { this.ctx = ctx; if (ctx != null) { value = ctx.GetFromPool(type); } this.type = type; } public Local AsCopy() { if (ctx == null) { return this; } return new Local(value, type); } public void Dispose() { if (ctx != null) { ctx.ReleaseToPool(value); value = null; ctx = null; } } internal bool IsSame(Local other) { if (this == other) { return true; } object obj = value; if (other != null) { return obj == other.value; } return false; } } internal static class WriterUtil { internal static readonly Type ByRefStateType = typeof(State).MakeByRefType(); } }