Decompiled source of Auto Publicizer v1.0.2

folder/AsmResolver.dll

Decompiled 11 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using AsmResolver.IO;
using AsmResolver.Patching;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("AsmResolver")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Washi 2016-2024")]
[assembly: AssemblyDescription("The base library for the AsmResolver executable file inspection toolsuite.")]
[assembly: AssemblyFileVersion("5.5.1.0")]
[assembly: AssemblyInformationalVersion("5.5.1+78ce89adebcc7e5dbeb1d4a1a35afcd513fb87a1")]
[assembly: AssemblyProduct("AsmResolver")]
[assembly: AssemblyTitle("AsmResolver")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Washi1337/AsmResolver")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.5.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AsmResolver
{
	public class ByteArrayEqualityComparer : IEqualityComparer<byte[]>, IComparer<byte[]>
	{
		public static ByteArrayEqualityComparer Instance { get; } = new ByteArrayEqualityComparer();


		private ByteArrayEqualityComparer()
		{
		}

		public unsafe bool Equals(byte[]? x, byte[]? y)
		{
			if (x == y)
			{
				return true;
			}
			if (x == null || y == null || x.Length != y.Length)
			{
				return false;
			}
			fixed (byte* ptr = x)
			{
				fixed (byte* ptr3 = y)
				{
					byte* ptr2 = ptr;
					byte* ptr4 = ptr3;
					int num = x.Length;
					int num2 = 0;
					while (num2 < num / 8)
					{
						if (*(long*)ptr2 != *(long*)ptr4)
						{
							return false;
						}
						num2++;
						ptr2 += 8;
						ptr4 += 8;
					}
					if (((uint)num & 4u) != 0)
					{
						if (*(int*)ptr2 != *(int*)ptr4)
						{
							return false;
						}
						ptr2 += 4;
						ptr4 += 4;
					}
					if (((uint)num & 2u) != 0)
					{
						if (*(short*)ptr2 != *(short*)ptr4)
						{
							return false;
						}
						ptr2 += 2;
						ptr4 += 2;
					}
					if (((uint)num & (true ? 1u : 0u)) != 0 && *ptr2 != *ptr4)
					{
						return false;
					}
					return true;
				}
			}
		}

		public int GetHashCode(byte[] obj)
		{
			int num = 0;
			foreach (byte b in obj)
			{
				num = (num * 31) ^ b;
			}
			return num;
		}

		public int Compare(byte[]? x, byte[]? y)
		{
			if (x == y)
			{
				return 0;
			}
			if (x == null)
			{
				return -1;
			}
			if (y == null)
			{
				return 1;
			}
			int num = Math.Min(x.Length, y.Length);
			for (int i = 0; i < num; i++)
			{
				int num2 = x[i].CompareTo(y[i]);
				if (num2 != 0)
				{
					return num2;
				}
			}
			return x.Length.CompareTo(y.Length);
		}
	}
	public class DataSegment : SegmentBase, IReadableSegment, ISegment, IOffsetProvider, IWritable
	{
		public byte[] Data { get; }

		public static DataSegment FromReader(ref BinaryStreamReader reader)
		{
			return FromReader(ref reader, (int)(reader.StartOffset + reader.Length - reader.Offset));
		}

		public static DataSegment FromReader(ref BinaryStreamReader reader, int count)
		{
			ulong offset = reader.Offset;
			uint rva = reader.Rva;
			byte[] array = new byte[count];
			reader.ReadBytes(array, 0, count);
			return new DataSegment(array)
			{
				Offset = offset,
				Rva = rva
			};
		}

		public DataSegment(byte[] data)
		{
			Data = data;
		}

		public override uint GetPhysicalSize()
		{
			return (uint)Data.Length;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			writer.WriteBytes(Data, 0, Data.Length);
		}

		public BinaryStreamReader CreateReader(ulong fileOffset, uint size)
		{
			if (fileOffset < base.Offset || fileOffset > (ulong)((long)base.Offset + (long)Data.Length))
			{
				throw new ArgumentOutOfRangeException("fileOffset");
			}
			if (fileOffset + size > (ulong)((long)base.Offset + (long)Data.Length))
			{
				throw new EndOfStreamException();
			}
			return new BinaryStreamReader(new ByteArrayDataSource(Data, base.Offset), fileOffset, (uint)(fileOffset - base.Offset + base.Rva), size);
		}
	}
	public class DataSourceSegment : SegmentBase, IReadableSegment, ISegment, IOffsetProvider, IWritable
	{
		private readonly IDataSource _dataSource;

		private readonly ulong _originalOffset;

		private readonly uint _originalSize;

		private DisplacedDataSource? _displacedDataSource;

		public DataSourceSegment(IDataSource dataSource, ulong offset, uint rva, uint size)
		{
			_dataSource = dataSource;
			base.Offset = (_originalOffset = offset);
			base.Rva = rva;
			_originalSize = size;
		}

		public override void UpdateOffsets(in RelocationParameters parameters)
		{
			base.UpdateOffsets(in parameters);
			long num = (long)(parameters.Offset - _originalOffset);
			_displacedDataSource = ((num != 0L) ? new DisplacedDataSource(_dataSource, num) : null);
		}

		public override uint GetPhysicalSize()
		{
			return _originalSize;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			CreateReader(base.Offset, _originalSize).WriteToOutput(writer);
		}

		public BinaryStreamReader CreateReader(ulong fileOffset, uint size)
		{
			if (fileOffset < base.Offset || fileOffset > base.Offset + _dataSource.Length)
			{
				throw new ArgumentOutOfRangeException("fileOffset");
			}
			if (fileOffset + size > base.Offset + _dataSource.Length)
			{
				throw new EndOfStreamException();
			}
			IDataSource displacedDataSource = _displacedDataSource;
			return new BinaryStreamReader(displacedDataSource ?? _dataSource, fileOffset, (uint)(fileOffset - base.Offset + base.Rva), size);
		}
	}
	public class DiagnosticBag : IErrorListener
	{
		public IList<Exception> Exceptions { get; } = new List<Exception>();


		public bool HasErrors => Exceptions.Count > 0;

		public bool IsFatal { get; private set; }

		public void MarkAsFatal()
		{
			IsFatal = true;
		}

		public void RegisterException(Exception exception)
		{
			Exceptions.Add(exception);
		}
	}
	public class EmptyErrorListener : IErrorListener
	{
		public static EmptyErrorListener Instance { get; } = new EmptyErrorListener();


		private EmptyErrorListener()
		{
		}

		public void MarkAsFatal()
		{
		}

		public void RegisterException(Exception exception)
		{
		}
	}
	public interface IErrorListener
	{
		void MarkAsFatal();

		void RegisterException(Exception exception);
	}
	public static class ErrorListenerExtensions
	{
		public static void BadImage(this IErrorListener self, string message)
		{
			self.RegisterException(new BadImageFormatException(message));
		}

		public static void NotSupported(this IErrorListener self, string message)
		{
			self.RegisterException(new NotSupportedException(message));
		}

		public static T? RegisterExceptionAndReturnDefault<T>(this IErrorListener self, Exception exception)
		{
			self.RegisterException(exception);
			return default(T);
		}

		public static T? NotSupportedAndReturn<T>(this IErrorListener self)
		{
			self.RegisterException(new NotSupportedException());
			return default(T);
		}

		public static T? NotSupportedAndReturn<T>(this IErrorListener self, string message)
		{
			self.RegisterException(new NotSupportedException(message));
			return default(T);
		}

		public static T? BadImageAndReturn<T>(this IErrorListener self, string message)
		{
			self.RegisterException(new BadImageFormatException(message));
			return default(T);
		}
	}
	public enum IndexSize
	{
		Short = 2,
		Long = 4
	}
	public interface IOffsetConverter
	{
		uint FileOffsetToRva(ulong fileOffset);

		ulong RvaToFileOffset(uint rva);
	}
	public interface IOffsetProvider
	{
		ulong Offset { get; }

		uint Rva { get; }
	}
	public interface IReadableSegment : ISegment, IOffsetProvider, IWritable
	{
		BinaryStreamReader CreateReader(ulong fileOffset, uint size);
	}
	public static class Extensions
	{
		[ThreadStatic]
		private static StringBuilder? _buffer;

		public static BinaryStreamReader CreateReader(this IReadableSegment segment)
		{
			return segment.CreateReader(segment.Offset, segment.GetPhysicalSize());
		}

		public static BinaryStreamReader CreateReader(this IReadableSegment segment, ulong fileOffset)
		{
			return segment.CreateReader(fileOffset, (uint)(segment.GetPhysicalSize() - (fileOffset - segment.Offset)));
		}

		public static byte[] ToArray(this IReadableSegment segment)
		{
			return segment.CreateReader().ReadToEnd();
		}

		public static uint Align(this uint value, uint alignment)
		{
			alignment--;
			return (value + alignment) & ~alignment;
		}

		public static ulong Align(this ulong value, ulong alignment)
		{
			alignment--;
			return (value + alignment) & ~alignment;
		}

		public static uint GetCompressedSize(this uint value)
		{
			if (value >= 128)
			{
				if (value < 16384)
				{
					return 2u;
				}
				return 4u;
			}
			return 1u;
		}

		public static uint Get7BitEncodedSize(this uint value)
		{
			if (value < 2097152)
			{
				if (value >= 128)
				{
					if (value < 16384)
					{
						return 2u;
					}
					return 3u;
				}
				return 1u;
			}
			if (value < 268435456)
			{
				return 4u;
			}
			return 5u;
		}

		public static uint GetBinaryFormatterSize(this string value)
		{
			return value.GetBinaryFormatterSize(Encoding.UTF8);
		}

		public static uint GetBinaryFormatterSize(this string value, Encoding encoding)
		{
			uint byteCount = (uint)encoding.GetByteCount(value);
			return byteCount.Get7BitEncodedSize() + byteCount;
		}

		public static string CreateEscapedString(this string literal)
		{
			if (_buffer == null)
			{
				_buffer = new StringBuilder(literal.Length + 2);
			}
			_buffer.Clear();
			_buffer.Append('"');
			foreach (char c in literal)
			{
				string text = c switch
				{
					'\0' => "\\0", 
					'\\' => "\\\\", 
					'"' => "\\\"", 
					'\t' => "\\t", 
					'\r' => "\\r", 
					'\n' => "\\n", 
					'\b' => "\\b", 
					_ => null, 
				};
				if (text != null)
				{
					_buffer.Append(text);
				}
				else
				{
					_buffer.Append(c);
				}
			}
			_buffer.Append('"');
			return _buffer.ToString();
		}

		public static ISegmentReference ToReference(this ISegment segment)
		{
			return new SegmentReference(segment);
		}

		public static ISegmentReference ToReference(this ISegment segment, int additive)
		{
			if (additive != 0)
			{
				return new RelativeReference(segment, additive);
			}
			return new SegmentReference(segment);
		}

		public static byte[] WriteIntoArray(this ISegment segment)
		{
			using MemoryStream memoryStream = new MemoryStream();
			segment.Write(new BinaryStreamWriter(memoryStream));
			return memoryStream.ToArray();
		}

		public static byte[] WriteIntoArray(this ISegment segment, MemoryStreamWriterPool pool)
		{
			using MemoryStreamWriterPool.RentedWriter rentedWriter = pool.Rent();
			segment.Write(rentedWriter.Writer);
			return rentedWriter.GetData();
		}

		public static PatchedSegment AsPatchedSegment(this ISegment segment)
		{
			return segment.AsPatchedSegment(alwaysCreateNew: false);
		}

		public static PatchedSegment AsPatchedSegment(this ISegment segment, bool alwaysCreateNew)
		{
			if (alwaysCreateNew)
			{
				return new PatchedSegment(segment);
			}
			return (segment as PatchedSegment) ?? new PatchedSegment(segment);
		}
	}
	public interface ISegment : IOffsetProvider, IWritable
	{
		bool CanUpdateOffsets { get; }

		uint GetVirtualSize();

		void UpdateOffsets(in RelocationParameters parameters);
	}
	public interface ISegmentReference : IOffsetProvider
	{
		bool CanRead { get; }

		bool IsBounded { get; }

		BinaryStreamReader CreateReader();

		ISegment? GetSegment();
	}
	public interface ISegmentReferenceFactory
	{
		ISegmentReference GetReferenceToRva(uint rva);
	}
	public interface ISymbol
	{
		ISegmentReference? GetReference();
	}
	public interface IWritable
	{
		uint GetPhysicalSize();

		void Write(IBinaryStreamWriter writer);
	}
	public sealed class LazyVariable<TValue>
	{
		private TValue? _value;

		private readonly Func<TValue?>? _getValue;

		[MemberNotNullWhen(false, "_getValue")]
		public bool IsInitialized
		{
			[MemberNotNullWhen(false, "_getValue")]
			get;
			[MemberNotNullWhen(false, "_getValue")]
			private set;
		}

		public TValue Value
		{
			get
			{
				if (!IsInitialized)
				{
					InitializeValue();
				}
				return _value;
			}
			set
			{
				lock (this)
				{
					_value = value;
					IsInitialized = true;
				}
			}
		}

		public LazyVariable(TValue value)
		{
			_value = value;
			IsInitialized = true;
		}

		public LazyVariable(Func<TValue?> getValue)
		{
			_getValue = getValue ?? throw new ArgumentNullException("getValue");
		}

		private void InitializeValue()
		{
			lock (this)
			{
				if (!IsInitialized)
				{
					_value = _getValue();
					IsInitialized = true;
				}
			}
		}
	}
	public sealed class LazyVariable<TOwner, TValue>
	{
		private TValue? _value;

		private readonly Func<TOwner, TValue?>? _getValue;

		[MemberNotNullWhen(false, "_getValue")]
		public bool IsInitialized
		{
			[MemberNotNullWhen(false, "_getValue")]
			get;
			[MemberNotNullWhen(false, "_getValue")]
			private set;
		}

		public LazyVariable(TValue value)
		{
			_value = value;
			IsInitialized = true;
		}

		public LazyVariable(Func<TOwner, TValue?> getValue)
		{
			_getValue = getValue ?? throw new ArgumentNullException("getValue");
		}

		public TValue GetValue(TOwner owner)
		{
			if (!IsInitialized)
			{
				InitializeValue(owner);
			}
			return _value;
		}

		public void SetValue(TValue value)
		{
			lock (this)
			{
				_value = value;
				IsInitialized = true;
			}
		}

		private void InitializeValue(TOwner owner)
		{
			lock (this)
			{
				if (!IsInitialized)
				{
					_value = _getValue(owner);
					IsInitialized = true;
				}
			}
		}
	}
	public readonly struct OffsetRange
	{
		public ulong Start { get; }

		public ulong End { get; }

		public int Length => (int)(End - Start);

		public bool IsEmpty => Start == End;

		public static implicit operator OffsetRange((ulong Start, ulong End) tuple)
		{
			return new OffsetRange(tuple.Start, tuple.End);
		}

		public OffsetRange(ulong start, ulong end)
		{
			if (start > end)
			{
				throw new ArgumentException("Start offset must be smaller or equal to end offset.");
			}
			Start = start;
			End = end;
		}

		public bool Contains(ulong offset)
		{
			if (Start <= offset)
			{
				return End > offset;
			}
			return false;
		}

		public bool Contains(OffsetRange range)
		{
			if (Contains(range.Start))
			{
				return Contains(range.End);
			}
			return false;
		}

		public bool Intersects(OffsetRange other)
		{
			if (!Contains(other.Start) && !Contains(other.End) && !other.Contains(Start))
			{
				return other.Contains(End);
			}
			return true;
		}

		public OffsetRange Intersect(OffsetRange other)
		{
			if (!Intersects(other))
			{
				return new OffsetRange(0uL, 0uL);
			}
			return new OffsetRange(Math.Max(Start, other.Start), Math.Min(End, other.End));
		}

		public (OffsetRange left, OffsetRange right) Exclude(OffsetRange other)
		{
			if (Intersect(other).IsEmpty)
			{
				return (this, (End, End));
			}
			if (Contains(other))
			{
				return ((Start, other.Start), (other.End, End));
			}
			if (Contains(other.Start))
			{
				return (new OffsetRange(Start, other.Start), new OffsetRange(other.End, other.End));
			}
			return ((other.Start, other.Start), (other.Start, End));
		}

		public void Deconstruct(out ulong start, out ulong end)
		{
			start = Start;
			end = End;
		}

		public override string ToString()
		{
			return $"[{Start:X8}, {End:X8})";
		}
	}
	public sealed class RelativeReference : ISegmentReference, IOffsetProvider
	{
		public IOffsetProvider Base { get; }

		public int Additive { get; }

		public ulong Offset => Base.Offset + (ulong)Additive;

		public uint Rva => (uint)(Base.Rva + Additive);

		public bool CanRead
		{
			get
			{
				if (Base is ISegmentReference segmentReference)
				{
					return segmentReference.CanRead;
				}
				return false;
			}
		}

		public bool IsBounded => false;

		public RelativeReference(IOffsetProvider @base, int additive)
		{
			Base = @base;
			Additive = additive;
		}

		public BinaryStreamReader CreateReader()
		{
			if (CanRead)
			{
				BinaryStreamReader result = ((ISegmentReference)Base).CreateReader();
				result.Offset += (ulong)Additive;
				return result;
			}
			throw new InvalidOperationException();
		}

		public ISegment? GetSegment()
		{
			throw new InvalidOperationException();
		}
	}
	public struct RelocationParameters
	{
		public ulong ImageBase { get; }

		public ulong Offset { get; set; }

		public uint Rva { get; set; }

		public bool Is32Bit { get; }

		public bool Is64Bit => !Is32Bit;

		public RelocationParameters(ulong offset, uint rva)
			: this(0uL, offset, rva, is32Bit: true)
		{
		}

		public RelocationParameters(ulong imageBase, ulong offset, uint rva, bool is32Bit)
		{
			ImageBase = imageBase;
			Offset = offset;
			Rva = rva;
			Is32Bit = is32Bit;
		}

		public RelocationParameters WithOffsetRva(ulong offset, uint rva)
		{
			return new RelocationParameters(ImageBase, offset, rva, Is32Bit);
		}

		public void Align(uint alignment)
		{
			Offset = Offset.Align(alignment);
			Rva = Rva.Align(alignment);
		}

		public readonly RelocationParameters WithAdvance(uint count)
		{
			return new RelocationParameters(ImageBase, Offset + count, Rva + count, Is32Bit);
		}

		public void Advance(uint count)
		{
			Offset += count;
			Rva += count;
		}

		public void Advance(uint physicalCount, uint virtualCount)
		{
			Offset += physicalCount;
			Rva += virtualCount;
		}

		public override string ToString()
		{
			return string.Format("{0}: {1:X8}, {2}: {3:X8}, {4}: {5:X8}", "ImageBase", ImageBase, "Offset", Offset, "Rva", Rva);
		}
	}
	public abstract class SegmentBase : ISegment, IOffsetProvider, IWritable
	{
		public ulong Offset { get; protected set; }

		public uint Rva { get; protected set; }

		public bool CanUpdateOffsets => true;

		public virtual void UpdateOffsets(in RelocationParameters parameters)
		{
			Offset = parameters.Offset;
			Rva = parameters.Rva;
		}

		public abstract uint GetPhysicalSize();

		public uint GetVirtualSize()
		{
			return GetPhysicalSize();
		}

		public abstract void Write(IBinaryStreamWriter writer);
	}
	public class SegmentBuilder : ISegment, IOffsetProvider, IWritable, IEnumerable<ISegment>, IEnumerable
	{
		[DebuggerDisplay("Segment, Alignment: Alignment")]
		private readonly struct AlignedSegment
		{
			public ISegment Segment { get; }

			public uint Alignment { get; }

			public AlignedSegment(ISegment segment, uint alignment)
			{
				Segment = segment;
				Alignment = alignment;
			}
		}

		private readonly List<AlignedSegment> _items = new List<AlignedSegment>();

		private uint _physicalSize;

		private uint _virtualSize;

		public int Count => _items.Count;

		public ulong Offset { get; private set; }

		public uint Rva { get; private set; }

		public bool CanUpdateOffsets => true;

		public void Add(ISegment segment)
		{
			Add(segment, 1u);
		}

		public void Add(ISegment segment, uint alignment)
		{
			_items.Add(new AlignedSegment(segment, alignment));
		}

		public void UpdateOffsets(in RelocationParameters parameters)
		{
			Offset = parameters.Offset;
			Rva = parameters.Rva;
			RelocationParameters parameters2 = parameters;
			foreach (AlignedSegment item in _items)
			{
				parameters2.Align(item.Alignment);
				item.Segment.UpdateOffsets(in parameters2);
				uint physicalSize = item.Segment.GetPhysicalSize();
				uint virtualSize = item.Segment.GetVirtualSize();
				parameters2.Advance(physicalSize, virtualSize);
			}
			_physicalSize = (uint)(parameters2.Offset - parameters.Offset);
			_virtualSize = parameters2.Rva - parameters.Rva;
		}

		public uint GetPhysicalSize()
		{
			return _physicalSize;
		}

		public uint GetVirtualSize()
		{
			return _virtualSize;
		}

		public void Write(IBinaryStreamWriter writer)
		{
			for (int i = 0; i < _items.Count; i++)
			{
				AlignedSegment alignedSegment = _items[i];
				writer.Align(alignedSegment.Alignment);
				alignedSegment.Segment.Write(writer);
			}
		}

		public IEnumerator<ISegment> GetEnumerator()
		{
			return _items.Select((AlignedSegment s) => s.Segment).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		void ISegment.UpdateOffsets(in RelocationParameters parameters)
		{
			UpdateOffsets(in parameters);
		}
	}
	public sealed class SegmentReference : ISegmentReference, IOffsetProvider
	{
		public static ISegmentReference Null { get; } = new SegmentReference(null);


		public ulong Offset => Segment?.Offset ?? 0;

		public uint Rva => Segment?.Rva ?? 0;

		public bool IsBounded => true;

		[MemberNotNullWhen(true, "Segment")]
		public bool CanRead
		{
			[MemberNotNullWhen(true, "Segment")]
			get
			{
				return Segment is IReadableSegment;
			}
		}

		public ISegment? Segment { get; }

		public SegmentReference(ISegment? segment)
		{
			Segment = segment;
		}

		public BinaryStreamReader CreateReader()
		{
			if (!CanRead)
			{
				throw new InvalidOperationException("Cannot read the segment using a binary reader.");
			}
			return ((IReadableSegment)Segment).CreateReader();
		}

		ISegment? ISegmentReference.GetSegment()
		{
			return Segment;
		}

		public override string ToString()
		{
			return Segment?.ToString() ?? "null";
		}
	}
	public class Symbol : ISymbol
	{
		public ISegmentReference Address { get; }

		public Symbol(ISegmentReference address)
		{
			Address = address;
		}

		public ISegmentReference GetReference()
		{
			return Address;
		}

		public override string? ToString()
		{
			return Address.ToString();
		}
	}
	public sealed class ThrowErrorListener : IErrorListener
	{
		public static ThrowErrorListener Instance { get; } = new ThrowErrorListener();


		private ThrowErrorListener()
		{
		}

		public void MarkAsFatal()
		{
		}

		public void RegisterException(Exception exception)
		{
			throw exception;
		}
	}
	[DebuggerDisplay("{DebugDisplay}")]
	public sealed class Utf8String : IEquatable<Utf8String>, IEquatable<string>, IEquatable<byte[]>, IComparable<Utf8String>, IEnumerable<char>, IEnumerable
	{
		public static readonly Utf8String Empty = new Utf8String(Array.Empty<byte>());

		private readonly byte[] _data;

		private string? _cachedString;

		public string Value => _cachedString ?? (_cachedString = Encoding.UTF8.GetString(_data));

		public int ByteCount => _data.Length;

		public int Length
		{
			get
			{
				if (_cachedString != null)
				{
					return Value.Length;
				}
				return Encoding.UTF8.GetCharCount(_data);
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		internal string DebugDisplay => Value.CreateEscapedString();

		public char this[int index] => Value[index];

		public Utf8String(byte[] data)
			: this(data, 0, data.Length)
		{
		}

		public Utf8String(byte[] data, int index, int count)
		{
			_data = new byte[count];
			Buffer.BlockCopy(data, index, _data, 0, count);
		}

		public Utf8String(string value)
		{
			_data = Encoding.UTF8.GetBytes(value);
			_cachedString = value;
		}

		public byte[] GetBytes()
		{
			byte[] array = new byte[_data.Length];
			GetBytes(array, 0, array.Length);
			return array;
		}

		public int GetBytes(byte[] buffer, int index, int length)
		{
			length = Math.Min(length, ByteCount);
			Buffer.BlockCopy(_data, 0, buffer, index, length);
			return length;
		}

		public byte[] GetBytesUnsafe()
		{
			return _data;
		}

		public Utf8String Concat(Utf8String? other)
		{
			if (IsNullOrEmpty(other))
			{
				return this;
			}
			return Concat(other._data);
		}

		public Utf8String Concat(string? other)
		{
			if (string.IsNullOrEmpty(other))
			{
				return this;
			}
			return Concat(Encoding.UTF8.GetBytes(other));
		}

		public Utf8String Concat(byte[]? other)
		{
			if (other == null || other.Length == 0)
			{
				return this;
			}
			byte[] array = new byte[Length + other.Length];
			Buffer.BlockCopy(_data, 0, array, 0, _data.Length);
			Buffer.BlockCopy(other, 0, array, _data.Length, other.Length);
			return array;
		}

		public int IndexOf(char needle)
		{
			return Value.IndexOf(needle);
		}

		public int IndexOf(char needle, int startIndex)
		{
			return Value.IndexOf(needle, startIndex);
		}

		public int IndexOf(string needle)
		{
			return Value.IndexOf(needle);
		}

		public int IndexOf(string needle, int startIndex)
		{
			return Value.IndexOf(needle, startIndex);
		}

		public int IndexOf(string needle, StringComparison comparison)
		{
			return Value.IndexOf(needle, comparison);
		}

		public int IndexOf(string needle, int startIndex, StringComparison comparison)
		{
			return Value.IndexOf(needle, startIndex, comparison);
		}

		public int LastIndexOf(char needle)
		{
			return Value.LastIndexOf(needle);
		}

		public int LastIndexOf(char needle, int startIndex)
		{
			return Value.LastIndexOf(needle, startIndex);
		}

		public int LastIndexOf(string needle)
		{
			return Value.LastIndexOf(needle);
		}

		public int LastIndexOf(string needle, int startIndex)
		{
			return Value.LastIndexOf(needle, startIndex);
		}

		public int LastIndexOf(string needle, StringComparison comparison)
		{
			return Value.LastIndexOf(needle, comparison);
		}

		public int LastIndexOf(string needle, int startIndex, StringComparison comparison)
		{
			return Value.LastIndexOf(needle, startIndex, comparison);
		}

		public bool Contains(string needle)
		{
			return IndexOf(needle) >= 0;
		}

		public static bool IsNullOrEmpty([NotNullWhen(false)] Utf8String? value)
		{
			if ((object)value != null)
			{
				return value.ByteCount == 0;
			}
			return true;
		}

		public bool Equals(Utf8String? other)
		{
			if ((object)other != null)
			{
				return ByteArrayEqualityComparer.Instance.Equals(_data, other._data);
			}
			return false;
		}

		public bool Equals(byte[]? other)
		{
			if (other != null)
			{
				return ByteArrayEqualityComparer.Instance.Equals(_data, other);
			}
			return false;
		}

		public bool Equals(string? other)
		{
			if (other != null)
			{
				return Value.Equals(other);
			}
			return false;
		}

		public int CompareTo(Utf8String? other)
		{
			if ((object)other == null)
			{
				return 1;
			}
			return ByteArrayEqualityComparer.Instance.Compare(_data, other._data);
		}

		public IEnumerator<char> GetEnumerator()
		{
			return Value.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public override bool Equals(object? obj)
		{
			if (this != obj)
			{
				if (obj is Utf8String other)
				{
					return Equals(other);
				}
				return false;
			}
			return true;
		}

		public override int GetHashCode()
		{
			return ByteArrayEqualityComparer.Instance.GetHashCode(_data);
		}

		public override string ToString()
		{
			return Value;
		}

		[return: NotNullIfNotNull("value")]
		public static implicit operator string?(Utf8String? value)
		{
			if ((object)value == null)
			{
				return null;
			}
			if (value.ByteCount == 0)
			{
				return string.Empty;
			}
			return value.Value;
		}

		[return: NotNullIfNotNull("value")]
		public static implicit operator Utf8String?(string? value)
		{
			if (value == null)
			{
				return null;
			}
			if (value.Length == 0)
			{
				return Empty;
			}
			return new Utf8String(value);
		}

		[return: NotNullIfNotNull("data")]
		public static implicit operator Utf8String?(byte[]? data)
		{
			if (data == null)
			{
				return null;
			}
			if (data.Length == 0)
			{
				return Empty;
			}
			return new Utf8String(data);
		}

		public static bool operator ==(Utf8String? a, Utf8String? b)
		{
			if ((object)a == b)
			{
				return true;
			}
			if ((object)a == null || (object)b == null)
			{
				return false;
			}
			return a.Equals(b);
		}

		public static bool operator !=(Utf8String? a, Utf8String? b)
		{
			return !(a == b);
		}

		public static bool operator ==(Utf8String? a, string? b)
		{
			if ((object)a == null)
			{
				return b == null;
			}
			if (b != null)
			{
				return a.Equals(b);
			}
			return false;
		}

		public static bool operator !=(Utf8String? a, string? b)
		{
			return !(a == b);
		}

		public static bool operator ==(Utf8String? a, byte[]? b)
		{
			if ((object)a == null)
			{
				return b == null;
			}
			if (b != null)
			{
				return a.Equals(b);
			}
			return false;
		}

		public static bool operator !=(Utf8String? a, byte[]? b)
		{
			return !(a == b);
		}

		public static Utf8String operator +(Utf8String? a, Utf8String? b)
		{
			if (IsNullOrEmpty(a))
			{
				if (!IsNullOrEmpty(b))
				{
					return b;
				}
				return Empty;
			}
			return a.Concat(b);
		}

		public static Utf8String operator +(Utf8String? a, string? b)
		{
			if (IsNullOrEmpty(a))
			{
				if (!string.IsNullOrEmpty(b))
				{
					return b;
				}
				return Empty;
			}
			return a.Concat(b);
		}

		public static Utf8String operator +(Utf8String? a, byte[]? b)
		{
			if (IsNullOrEmpty(a))
			{
				if (b != null && b.Length != 0)
				{
					return b;
				}
				return Empty;
			}
			return a.Concat(b);
		}
	}
	public sealed class VirtualAddress : ISegmentReference, IOffsetProvider
	{
		ulong IOffsetProvider.Offset => Rva;

		public uint Rva { get; }

		public bool CanRead => false;

		bool ISegmentReference.IsBounded => false;

		public VirtualAddress(uint rva)
		{
			Rva = rva;
		}

		BinaryStreamReader ISegmentReference.CreateReader()
		{
			throw new InvalidOperationException();
		}

		ISegment? ISegmentReference.GetSegment()
		{
			throw new InvalidOperationException();
		}

		public override string ToString()
		{
			return $"0x{Rva:X8}";
		}
	}
	public class VirtualAddressFactory : ISegmentReferenceFactory
	{
		public static VirtualAddressFactory Instance { get; } = new VirtualAddressFactory();


		public ISegmentReference GetReferenceToRva(uint rva)
		{
			if (rva == 0)
			{
				return SegmentReference.Null;
			}
			return new VirtualAddress(rva);
		}
	}
	public class VirtualSegment : IReadableSegment, ISegment, IOffsetProvider, IWritable
	{
		private uint _rva;

		public ISegment? PhysicalContents { get; set; }

		public uint VirtualSize { get; set; }

		public ulong Offset => PhysicalContents?.Offset ?? 0;

		public uint Rva => _rva;

		public bool CanUpdateOffsets => PhysicalContents?.CanUpdateOffsets ?? false;

		[MemberNotNullWhen(true, "PhysicalContents")]
		public bool IsReadable
		{
			[MemberNotNullWhen(true, "PhysicalContents")]
			get
			{
				return PhysicalContents is IReadableSegment;
			}
		}

		public VirtualSegment(ISegment? physicalContents, uint virtualSize)
		{
			PhysicalContents = physicalContents;
			VirtualSize = virtualSize;
		}

		public void UpdateOffsets(in RelocationParameters parameters)
		{
			_rva = parameters.Rva;
			PhysicalContents?.UpdateOffsets(in parameters);
		}

		public uint GetPhysicalSize()
		{
			return PhysicalContents?.GetPhysicalSize() ?? 0;
		}

		public uint GetVirtualSize()
		{
			return VirtualSize;
		}

		public BinaryStreamReader CreateReader(ulong fileOffset, uint size)
		{
			if (!(PhysicalContents is IReadableSegment readableSegment))
			{
				throw new InvalidOperationException("Physical contents of the virtual segment is not readable.");
			}
			return readableSegment.CreateReader(fileOffset, size);
		}

		public void Write(IBinaryStreamWriter writer)
		{
			PhysicalContents?.Write(writer);
		}

		void ISegment.UpdateOffsets(in RelocationParameters parameters)
		{
			UpdateOffsets(in parameters);
		}
	}
	public class ZeroesSegment : SegmentBase, IReadableSegment, ISegment, IOffsetProvider, IWritable
	{
		private ZeroesDataSource? _dataSource;

		public uint Size { get; }

		public ZeroesSegment(uint size)
		{
			Size = size;
		}

		public override uint GetPhysicalSize()
		{
			return Size;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			writer.WriteZeroes((int)Size);
		}

		public BinaryStreamReader CreateReader(ulong fileOffset, uint size)
		{
			if (fileOffset < base.Offset || fileOffset > base.Offset + Size)
			{
				throw new ArgumentOutOfRangeException("fileOffset");
			}
			if (fileOffset + size > base.Offset + Size)
			{
				throw new EndOfStreamException();
			}
			if (_dataSource == null)
			{
				_dataSource = new ZeroesDataSource(base.Offset, Size);
			}
			return new BinaryStreamReader(_dataSource, fileOffset, (uint)(fileOffset - base.Offset + base.Rva), size);
		}
	}
}
namespace AsmResolver.Patching
{
	[DebuggerDisplay("Patch {RelativeOffset} with {NewData.Length} bytes")]
	public sealed class BytesPatch : IPatch
	{
		public uint RelativeOffset { get; }

		public byte[] NewData { get; }

		public BytesPatch(uint relativeOffset, byte[] newData)
		{
			RelativeOffset = relativeOffset;
			NewData = newData;
		}

		public void Apply(in PatchContext context)
		{
			context.Writer.Offset = context.Segment.Offset + RelativeOffset;
			context.Writer.WriteBytes(NewData);
		}

		void IPatch.Apply(in PatchContext context)
		{
			Apply(in context);
		}
	}
	public interface IPatch
	{
		void Apply(in PatchContext context);
	}
	public readonly struct PatchContext
	{
		public ISegment Segment { get; }

		public ulong ImageBase { get; }

		public IBinaryStreamWriter Writer { get; }

		public PatchContext(ISegment segment, ulong imageBase, IBinaryStreamWriter writer)
		{
			Segment = segment;
			ImageBase = imageBase;
			Writer = writer;
		}
	}
	[DebuggerDisplay("Patched {Contents} (Count = {Patches.Count})")]
	public class PatchedSegment : IReadableSegment, ISegment, IOffsetProvider, IWritable
	{
		private ulong _imageBase;

		public ISegment Contents { get; }

		public IList<IPatch> Patches { get; } = new List<IPatch>();


		public ulong Offset => Contents.Offset;

		public uint Rva => Contents.Rva;

		public bool CanUpdateOffsets => Contents.CanUpdateOffsets;

		public PatchedSegment(ISegment contents)
		{
			Contents = contents;
		}

		public uint GetPhysicalSize()
		{
			return Contents.GetPhysicalSize();
		}

		public uint GetVirtualSize()
		{
			return Contents.GetVirtualSize();
		}

		public void UpdateOffsets(in RelocationParameters parameters)
		{
			Contents.UpdateOffsets(in parameters);
			_imageBase = parameters.ImageBase;
		}

		public BinaryStreamReader CreateReader(ulong fileOffset, uint size)
		{
			if (!(Contents is IReadableSegment readableSegment))
			{
				throw new InvalidOperationException("Segment is not readable.");
			}
			return readableSegment.CreateReader(fileOffset, size);
		}

		public void Write(IBinaryStreamWriter writer)
		{
			Contents.Write(writer);
			ApplyPatches(writer);
		}

		private void ApplyPatches(IBinaryStreamWriter writer)
		{
			ulong offset = writer.Offset;
			for (int i = 0; i < Patches.Count; i++)
			{
				IPatch patch = Patches[i];
				PatchContext context = new PatchContext(Contents, _imageBase, writer);
				patch.Apply(in context);
			}
			writer.Offset = offset;
		}

		public PatchedSegment Patch(IPatch patch)
		{
			Patches.Add(patch);
			return this;
		}

		public PatchedSegment Patch(uint relativeOffset, byte[] newData)
		{
			Patches.Add(new BytesPatch(relativeOffset, newData));
			return this;
		}

		void ISegment.UpdateOffsets(in RelocationParameters parameters)
		{
			UpdateOffsets(in parameters);
		}
	}
}
namespace AsmResolver.IO
{
	[DebuggerDisplay("[{StartOffset}..{EndOffset}) at {Offset} ({RelativeOffset})")]
	public struct BinaryStreamReader
	{
		[ThreadStatic]
		private static int[]? _buffer;

		public IDataSource DataSource { get; }

		public ulong StartOffset { get; }

		public uint StartRva { get; }

		public uint Length { get; private set; }

		public ulong EndOffset => StartOffset + Length;

		public ulong EndRva => StartRva + Length;

		public ulong Offset { get; set; }

		public uint RelativeOffset
		{
			get
			{
				return (uint)(Offset - StartOffset);
			}
			set
			{
				Offset = value + StartOffset;
			}
		}

		public uint RemainingLength => Length - RelativeOffset;

		public uint Rva
		{
			get
			{
				return RelativeOffset + StartRva;
			}
			set
			{
				RelativeOffset = value - StartRva;
			}
		}

		public bool IsValid => DataSource != null;

		public BinaryStreamReader(byte[] data)
			: this(new ByteArrayDataSource(data))
		{
		}

		public BinaryStreamReader(IDataSource dataSource)
			: this(dataSource, 0uL, 0u, (uint)dataSource.Length)
		{
		}

		public BinaryStreamReader(IDataSource dataSource, ulong offset, uint rva, uint length)
		{
			if (dataSource == null)
			{
				throw new ArgumentNullException("dataSource");
			}
			if (length != 0)
			{
				if (!dataSource.IsValidAddress(offset))
				{
					throw new ArgumentOutOfRangeException("offset");
				}
				if (!dataSource.IsValidAddress(offset + length - 1))
				{
					throw new EndOfStreamException("Offset and address reach outside of the boundaries of the data source.");
				}
			}
			DataSource = dataSource;
			ulong num2 = (Offset = offset);
			StartOffset = num2;
			StartRva = rva;
			Length = length;
		}

		public bool CanRead(uint count)
		{
			return RelativeOffset + count <= Length;
		}

		private void AssertCanRead(uint count)
		{
			if (!CanRead(count))
			{
				throw new EndOfStreamException();
			}
		}

		public int PeekByte()
		{
			if (!CanRead(1u))
			{
				return -1;
			}
			return DataSource[Offset];
		}

		public byte ReadByte()
		{
			AssertCanRead(1u);
			return DataSource[Offset++];
		}

		public ushort ReadUInt16()
		{
			AssertCanRead(2u);
			ushort result = (ushort)(DataSource[Offset] | (DataSource[Offset + 1] << 8));
			Offset += 2uL;
			return result;
		}

		public uint ReadUInt32()
		{
			AssertCanRead(4u);
			int result = DataSource[Offset] | (DataSource[Offset + 1] << 8) | (DataSource[Offset + 2] << 16) | (DataSource[Offset + 3] << 24);
			Offset += 4uL;
			return (uint)result;
		}

		public ulong ReadUInt64()
		{
			AssertCanRead(8u);
			ulong result = DataSource[Offset] | ((ulong)DataSource[Offset + 1] << 8) | ((ulong)DataSource[Offset + 2] << 16) | ((ulong)DataSource[Offset + 3] << 24) | ((ulong)DataSource[Offset + 4] << 32) | ((ulong)DataSource[Offset + 5] << 40) | ((ulong)DataSource[Offset + 6] << 48) | ((ulong)DataSource[Offset + 7] << 56);
			Offset += 8uL;
			return result;
		}

		public sbyte ReadSByte()
		{
			AssertCanRead(1u);
			return (sbyte)DataSource[Offset++];
		}

		public short ReadInt16()
		{
			AssertCanRead(2u);
			short result = (short)(DataSource[Offset] | (DataSource[Offset + 1] << 8));
			Offset += 2uL;
			return result;
		}

		public int ReadInt32()
		{
			AssertCanRead(4u);
			int result = DataSource[Offset] | (DataSource[Offset + 1] << 8) | (DataSource[Offset + 2] << 16) | (DataSource[Offset + 3] << 24);
			Offset += 4uL;
			return result;
		}

		public long ReadInt64()
		{
			AssertCanRead(8u);
			ulong result = DataSource[Offset] | ((ulong)DataSource[Offset + 1] << 8) | ((ulong)DataSource[Offset + 2] << 16) | ((ulong)DataSource[Offset + 3] << 24) | ((ulong)DataSource[Offset + 4] << 32) | ((ulong)DataSource[Offset + 5] << 40) | ((ulong)DataSource[Offset + 6] << 48) | ((ulong)DataSource[Offset + 7] << 56);
			Offset += 8uL;
			return (long)result;
		}

		public unsafe float ReadSingle()
		{
			uint num = ReadUInt32();
			return *(float*)(&num);
		}

		public unsafe double ReadDouble()
		{
			ulong num = ReadUInt64();
			return *(double*)(&num);
		}

		public decimal ReadDecimal()
		{
			AssertCanRead(16u);
			if (_buffer == null)
			{
				_buffer = new int[4];
			}
			for (int i = 0; i < 4; i++)
			{
				_buffer[i] = ReadInt32();
			}
			return new decimal(_buffer);
		}

		public int ReadBytes(byte[] buffer, int index, int count)
		{
			int num = DataSource.ReadBytes(Offset, buffer, index, count);
			Offset += (uint)num;
			return num;
		}

		public IReadableSegment ReadSegment(uint count)
		{
			DataSourceSegment result = new DataSourceSegment(DataSource, Offset, Rva, count);
			Offset += count;
			return result;
		}

		public byte[] ReadToEnd()
		{
			byte[] array = new byte[RemainingLength];
			ReadBytes(array, 0, array.Length);
			return array;
		}

		public byte[] ReadBytesUntil(byte delimiter)
		{
			return ReadBytesUntil(delimiter, includeDelimiterInReturn: true);
		}

		public byte[] ReadBytesUntil(byte delimiter, bool includeDelimiterInReturn)
		{
			BinaryStreamReader binaryStreamReader = Fork();
			bool num = binaryStreamReader.AdvanceUntil(delimiter, includeDelimiterInReturn);
			byte[] array = new byte[binaryStreamReader.RelativeOffset - RelativeOffset];
			ReadBytes(array, 0, array.Length);
			if (num)
			{
				ReadByte();
			}
			return array;
		}

		public bool AdvanceUntil(byte delimiter, bool consumeDelimiter)
		{
			while (RelativeOffset < Length)
			{
				if (ReadByte() == delimiter)
				{
					if (!consumeDelimiter)
					{
						RelativeOffset--;
						return true;
					}
					return false;
				}
			}
			return false;
		}

		public string ReadAsciiString()
		{
			return Encoding.ASCII.GetString(ReadBytesUntil(0, includeDelimiterInReturn: false));
		}

		public string ReadUnicodeString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			while (true)
			{
				char c = (char)ReadUInt16();
				if (c == '\0')
				{
					break;
				}
				stringBuilder.Append(c);
			}
			return stringBuilder.ToString();
		}

		public Utf8String ReadUtf8String()
		{
			byte[] array = ReadBytesUntil(0, includeDelimiterInReturn: false);
			if (array.Length == 0)
			{
				return Utf8String.Empty;
			}
			return new Utf8String(array);
		}

		public ulong ReadNativeInt(bool is32Bit)
		{
			if (!is32Bit)
			{
				return ReadUInt64();
			}
			return ReadUInt32();
		}

		public uint ReadCompressedUInt32()
		{
			byte b = ReadByte();
			if ((b & 0x80) == 0)
			{
				return b;
			}
			if ((b & 0x40) == 0)
			{
				return (uint)(((b & 0x7F) << 8) | ReadByte());
			}
			return (uint)(((b & 0x3F) << 24) | (ReadByte() << 16) | (ReadByte() << 8) | ReadByte());
		}

		public bool TryReadCompressedUInt32(out uint value)
		{
			value = 0u;
			if (!CanRead(1u))
			{
				return false;
			}
			byte b = ReadByte();
			Offset--;
			if (((b & 0x80) == 0 && CanRead(1u)) || ((b & 0x40) == 0 && CanRead(2u)) || CanRead(4u))
			{
				value = ReadCompressedUInt32();
				return true;
			}
			return false;
		}

		public int Read7BitEncodedInt32()
		{
			int num = 0;
			byte b;
			for (int i = 0; i < 4; i++)
			{
				b = ReadByte();
				num |= (b & 0x7F) << i * 7;
				if ((b & 0x80) == 0)
				{
					return num;
				}
			}
			b = ReadByte();
			if (b > 31)
			{
				throw new FormatException("Invalid 7-bit encoded integer.");
			}
			return num | (b << 28);
		}

		public uint ReadIndex(IndexSize size)
		{
			return size switch
			{
				IndexSize.Short => ReadUInt16(), 
				IndexSize.Long => ReadUInt32(), 
				_ => throw new ArgumentOutOfRangeException("size"), 
			};
		}

		public Utf8String? ReadSerString()
		{
			if (!CanRead(1u) || DataSource[Offset] == byte.MaxValue)
			{
				Offset++;
				return null;
			}
			if (!TryReadCompressedUInt32(out var value))
			{
				return null;
			}
			byte[] array = new byte[value];
			value = (uint)ReadBytes(array, 0, (int)value);
			return new Utf8String(array, 0, (int)value);
		}

		public string ReadBinaryFormatterString()
		{
			return ReadBinaryFormatterString(Encoding.UTF8);
		}

		public string ReadBinaryFormatterString(Encoding encoding)
		{
			int num = Read7BitEncodedInt32();
			if (num >= 0)
			{
				if (num == 0)
				{
					return string.Empty;
				}
				byte[] array = new byte[num];
				int count = ReadBytes(array, 0, num);
				return encoding.GetString(array, 0, count);
			}
			throw new FormatException("Negative string length.");
		}

		public void Align(uint alignment)
		{
			Offset = Offset.Align(alignment);
		}

		public void AlignRelative(uint alignment)
		{
			RelativeOffset = RelativeOffset.Align(alignment);
		}

		public readonly BinaryStreamReader Fork()
		{
			return this;
		}

		public readonly BinaryStreamReader ForkAbsolute(ulong offset)
		{
			return ForkAbsolute(offset, (uint)(Length - (offset - StartOffset)));
		}

		public readonly BinaryStreamReader ForkAbsolute(ulong offset, uint size)
		{
			return new BinaryStreamReader(DataSource, offset, (uint)(StartRva + (offset - StartOffset)), size);
		}

		public readonly BinaryStreamReader ForkRelative(uint relativeOffset)
		{
			return ForkRelative(relativeOffset, Length - relativeOffset);
		}

		public readonly BinaryStreamReader ForkRelative(uint relativeOffset, uint size)
		{
			return new BinaryStreamReader(DataSource, StartOffset + relativeOffset, StartRva + relativeOffset, size);
		}

		public void ChangeSize(uint newSize)
		{
			if (newSize > Length)
			{
				throw new EndOfStreamException();
			}
			Length = newSize;
		}

		public void WriteToOutput(IBinaryStreamWriter writer)
		{
			byte[] array = new byte[4096];
			while (RelativeOffset < Length)
			{
				int count = (int)Math.Min(array.Length, Length - RelativeOffset);
				int num = ReadBytes(array, 0, count);
				if (num == 0)
				{
					writer.WriteZeroes((int)(Length - RelativeOffset));
					break;
				}
				writer.WriteBytes(array, 0, num);
			}
		}
	}
	public class BinaryStreamWriter : IBinaryStreamWriter
	{
		public Stream BaseStream { get; }

		public ulong Offset
		{
			get
			{
				return (uint)BaseStream.Position;
			}
			set
			{
				if (BaseStream.Position != (long)value)
				{
					BaseStream.Position = (long)value;
				}
			}
		}

		public uint Length => (uint)BaseStream.Length;

		public BinaryStreamWriter(Stream stream)
		{
			BaseStream = stream ?? throw new ArgumentNullException("stream");
		}

		public void WriteBytes(byte[] buffer, int startIndex, int count)
		{
			BaseStream.Write(buffer, startIndex, count);
		}

		public void WriteByte(byte value)
		{
			BaseStream.WriteByte(value);
		}

		public void WriteUInt16(ushort value)
		{
			BaseStream.WriteByte((byte)(value & 0xFFu));
			BaseStream.WriteByte((byte)((uint)(value >> 8) & 0xFFu));
		}

		public void WriteUInt32(uint value)
		{
			BaseStream.WriteByte((byte)(value & 0xFFu));
			BaseStream.WriteByte((byte)((value >> 8) & 0xFFu));
			BaseStream.WriteByte((byte)((value >> 16) & 0xFFu));
			BaseStream.WriteByte((byte)((value >> 24) & 0xFFu));
		}

		public void WriteUInt64(ulong value)
		{
			BaseStream.WriteByte((byte)(value & 0xFF));
			BaseStream.WriteByte((byte)((value >> 8) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 16) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 24) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 32) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 40) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 48) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 56) & 0xFF));
		}

		public void WriteSByte(sbyte value)
		{
			BaseStream.WriteByte((byte)value);
		}

		public void WriteInt16(short value)
		{
			BaseStream.WriteByte((byte)((uint)value & 0xFFu));
			BaseStream.WriteByte((byte)((uint)(value >> 8) & 0xFFu));
		}

		public void WriteInt32(int value)
		{
			BaseStream.WriteByte((byte)((uint)value & 0xFFu));
			BaseStream.WriteByte((byte)((uint)(value >> 8) & 0xFFu));
			BaseStream.WriteByte((byte)((uint)(value >> 16) & 0xFFu));
			BaseStream.WriteByte((byte)((uint)(value >> 24) & 0xFFu));
		}

		public void WriteInt64(long value)
		{
			BaseStream.WriteByte((byte)(value & 0xFF));
			BaseStream.WriteByte((byte)((value >> 8) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 16) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 24) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 32) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 40) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 48) & 0xFF));
			BaseStream.WriteByte((byte)((value >> 56) & 0xFF));
		}

		public unsafe void WriteSingle(float value)
		{
			WriteUInt32(*(uint*)(&value));
		}

		public unsafe void WriteDouble(double value)
		{
			WriteUInt64(*(ulong*)(&value));
		}

		public void WriteDecimal(decimal value)
		{
			int[] bits = decimal.GetBits(value);
			WriteInt32(bits[0]);
			WriteInt32(bits[1]);
			WriteInt32(bits[2]);
			WriteInt32(bits[3]);
		}
	}
	public sealed class ByteArrayDataSource : IDataSource
	{
		private readonly byte[] _data;

		public ulong BaseAddress { get; }

		public byte this[ulong address] => _data[address - BaseAddress];

		public ulong Length => (ulong)_data.Length;

		public ByteArrayDataSource(byte[] data)
			: this(data, 0uL)
		{
		}

		public ByteArrayDataSource(byte[] data, ulong baseAddress)
		{
			_data = data ?? throw new ArgumentNullException("data");
			BaseAddress = baseAddress;
		}

		[Obsolete("Use the constructor of AsmResolver.IO.BinaryStreamReader instead.")]
		public static BinaryStreamReader CreateReader(byte[] data)
		{
			return new BinaryStreamReader(data);
		}

		public bool IsValidAddress(ulong address)
		{
			return address - BaseAddress < (ulong)_data.Length;
		}

		public int ReadBytes(ulong address, byte[] buffer, int index, int count)
		{
			int num = (int)(address - BaseAddress);
			int num2 = Math.Min(count, _data.Length - num);
			Buffer.BlockCopy(_data, num, buffer, index, num2);
			return num2;
		}
	}
	public class ByteArrayFileService : IFileService, IDisposable
	{
		private readonly ConcurrentDictionary<string, ByteArrayInputFile> _files = new ConcurrentDictionary<string, ByteArrayInputFile>();

		public IEnumerable<string> GetOpenedFiles()
		{
			return _files.Keys;
		}

		public IInputFile OpenFile(string filePath)
		{
			return _files.GetOrAdd(filePath, (string x) => new ByteArrayInputFile(x));
		}

		public void InvalidateFile(string filePath)
		{
			_files.TryRemove(filePath, out ByteArrayInputFile _);
		}

		void IDisposable.Dispose()
		{
			_files.Clear();
		}
	}
	public sealed class ByteArrayInputFile : IInputFile, IDisposable
	{
		private readonly ByteArrayDataSource _dataSource;

		public string? FilePath { get; }

		public uint Length => (uint)_dataSource.Length;

		public ByteArrayInputFile(string filePath)
			: this(filePath, File.ReadAllBytes(filePath), 0uL)
		{
		}

		public ByteArrayInputFile(byte[] contents)
			: this(null, contents, 0uL)
		{
		}

		public ByteArrayInputFile(string? filePath, byte[] data, ulong baseAddress)
		{
			FilePath = filePath;
			_dataSource = new ByteArrayDataSource(data, baseAddress);
		}

		public BinaryStreamReader CreateReader(ulong address, uint rva, uint length)
		{
			return new BinaryStreamReader(_dataSource, address, rva, length);
		}

		void IDisposable.Dispose()
		{
		}
	}
	public static class DataSourceExtensions
	{
	}
	public class DataSourceSlice : IDataSource
	{
		private readonly IDataSource _source;

		public ulong BaseAddress { get; }

		public ulong Length { get; }

		public byte this[ulong address]
		{
			get
			{
				if (!IsValidAddress(address))
				{
					throw new IndexOutOfRangeException();
				}
				return _source[address];
			}
		}

		public DataSourceSlice(IDataSource source, ulong start, ulong length)
		{
			_source = source;
			if (!source.IsValidAddress(start))
			{
				throw new ArgumentOutOfRangeException("start");
			}
			if (length != 0 && !source.IsValidAddress(start + length - 1))
			{
				throw new ArgumentOutOfRangeException("length");
			}
			BaseAddress = start;
			Length = length;
		}

		public bool IsValidAddress(ulong address)
		{
			if (address >= BaseAddress)
			{
				return address - BaseAddress < Length;
			}
			return false;
		}

		public int ReadBytes(ulong address, byte[] buffer, int index, int count)
		{
			int val = Math.Max(0, (int)(Length - (address - BaseAddress)));
			return _source.ReadBytes(address, buffer, index, Math.Min(val, count));
		}
	}
	public class DisplacedDataSource : IDataSource
	{
		private readonly IDataSource _dataSource;

		private readonly long _displacement;

		public ulong BaseAddress => _dataSource.BaseAddress + (ulong)_displacement;

		public byte this[ulong address] => _dataSource[address - (ulong)_displacement];

		public ulong Length => _dataSource.Length;

		public DisplacedDataSource(IDataSource dataSource, long displacement)
		{
			_dataSource = dataSource ?? throw new ArgumentNullException("dataSource");
			_displacement = displacement;
		}

		public bool IsValidAddress(ulong address)
		{
			return _dataSource.IsValidAddress(address - (ulong)_displacement);
		}

		public int ReadBytes(ulong address, byte[] buffer, int index, int count)
		{
			return _dataSource.ReadBytes(address - (ulong)_displacement, buffer, index, count);
		}
	}
	public interface IBinaryStreamWriter
	{
		ulong Offset { get; set; }

		uint Length { get; }

		void WriteBytes(byte[] buffer, int startIndex, int count);

		void WriteByte(byte value);

		void WriteUInt16(ushort value);

		void WriteUInt32(uint value);

		void WriteUInt64(ulong value);

		void WriteSByte(sbyte value);

		void WriteInt16(short value);

		void WriteInt32(int value);

		void WriteInt64(long value);

		void WriteSingle(float value);

		void WriteDouble(double value);

		void WriteDecimal(decimal value);
	}
	public static class IOExtensions
	{
		public static void WriteNativeInt(this IBinaryStreamWriter writer, ulong value, bool is32Bit)
		{
			if (is32Bit)
			{
				writer.WriteUInt32((uint)value);
			}
			else
			{
				writer.WriteUInt64(value);
			}
		}

		public static void WriteBytes(this IBinaryStreamWriter writer, byte[] buffer)
		{
			writer.WriteBytes(buffer, 0, buffer.Length);
		}

		public static void WriteZeroes(this IBinaryStreamWriter writer, int count)
		{
			while (count >= 8)
			{
				writer.WriteUInt64(0uL);
				count -= 8;
			}
			while (count >= 4)
			{
				writer.WriteUInt32(0u);
				count -= 4;
			}
			while (count >= 2)
			{
				writer.WriteUInt16(0);
				count -= 2;
			}
			while (count >= 1)
			{
				writer.WriteByte(0);
				count--;
			}
		}

		public static void WriteAsciiString(this IBinaryStreamWriter writer, string value)
		{
			writer.WriteBytes(Encoding.ASCII.GetBytes(value));
		}

		public static void Align(this IBinaryStreamWriter writer, uint align)
		{
			writer.AlignRelative(align, 0uL);
		}

		public static void AlignRelative(this IBinaryStreamWriter writer, uint align, ulong startOffset)
		{
			ulong num = writer.Offset - startOffset;
			writer.WriteZeroes((int)(num.Align(align) - num));
		}

		public static void WriteIndex(this IBinaryStreamWriter writer, uint value, IndexSize size)
		{
			switch (size)
			{
			case IndexSize.Short:
				writer.WriteUInt16((ushort)value);
				break;
			case IndexSize.Long:
				writer.WriteUInt32(value);
				break;
			default:
				throw new ArgumentOutOfRangeException("size", size, null);
			}
		}

		public static void WriteCompressedUInt32(this IBinaryStreamWriter writer, uint value)
		{
			if (value < 128)
			{
				writer.WriteByte((byte)value);
				return;
			}
			if (value < 16384)
			{
				writer.WriteByte((byte)(0x80u | (value >> 8)));
				writer.WriteByte((byte)(value & 0xFFu));
				return;
			}
			writer.WriteByte((byte)(0xC0u | (value >> 24)));
			writer.WriteByte((byte)((value >> 16) & 0xFFu));
			writer.WriteByte((byte)((value >> 8) & 0xFFu));
			writer.WriteByte((byte)(value & 0xFFu));
		}

		public static void Write7BitEncodedInt32(this IBinaryStreamWriter writer, int value)
		{
			uint num = (uint)value;
			do
			{
				byte b = (byte)(num & 0x7Fu);
				if (num > 127)
				{
					b = (byte)(b | 0x80u);
				}
				writer.WriteByte(b);
				num >>= 7;
			}
			while (num != 0);
		}

		public static void WriteSerString(this IBinaryStreamWriter writer, string? value)
		{
			if (value == null)
			{
				writer.WriteByte(byte.MaxValue);
				return;
			}
			byte[] bytes = Encoding.UTF8.GetBytes(value);
			writer.WriteCompressedUInt32((uint)bytes.Length);
			writer.WriteBytes(bytes);
		}

		public static void WriteBinaryFormatterString(this IBinaryStreamWriter writer, string value)
		{
			writer.WriteBinaryFormatterString(value, Encoding.UTF8);
		}

		public static void WriteBinaryFormatterString(this IBinaryStreamWriter writer, string value, Encoding encoding)
		{
			byte[] bytes = encoding.GetBytes(value);
			writer.Write7BitEncodedInt32(bytes.Length);
			writer.WriteBytes(bytes);
		}

		public static void WriteSerString(this IBinaryStreamWriter writer, Utf8String? value)
		{
			if ((object)value == null)
			{
				writer.WriteByte(byte.MaxValue);
				return;
			}
			byte[] bytesUnsafe = value.GetBytesUnsafe();
			writer.WriteCompressedUInt32((uint)bytesUnsafe.Length);
			writer.WriteBytes(bytesUnsafe);
		}

		public static BinaryStreamReader CreateReader(this IInputFile factory)
		{
			return factory.CreateReader(0uL, 0u, factory.Length);
		}
	}
	public interface IDataSource
	{
		ulong BaseAddress { get; }

		byte this[ulong address] { get; }

		ulong Length { get; }

		bool IsValidAddress(ulong address);

		int ReadBytes(ulong address, byte[] buffer, int index, int count);
	}
	public interface IFileService : IDisposable
	{
		IEnumerable<string> GetOpenedFiles();

		IInputFile OpenFile(string filePath);

		void InvalidateFile(string filePath);
	}
	public interface IInputFile : IDisposable
	{
		string? FilePath { get; }

		uint Length { get; }

		BinaryStreamReader CreateReader(ulong address, uint rva, uint length);
	}
	public sealed class MemoryMappedDataSource : IDataSource, IDisposable
	{
		private readonly MemoryMappedViewAccessor _accessor;

		public ulong BaseAddress => 0uL;

		public byte this[ulong address] => _accessor.ReadByte((long)address);

		public ulong Length { get; }

		public MemoryMappedDataSource(MemoryMappedViewAccessor accessor, ulong length)
		{
			Length = length;
			_accessor = accessor ?? throw new ArgumentNullException("accessor");
		}

		public bool IsValidAddress(ulong address)
		{
			return address < Length;
		}

		public int ReadBytes(ulong address, byte[] buffer, int index, int count)
		{
			return _accessor.ReadArray((long)address, buffer, index, count);
		}

		public void Dispose()
		{
			_accessor?.Dispose();
		}
	}
	public class MemoryMappedFileService : IFileService, IDisposable
	{
		private readonly ConcurrentDictionary<string, MemoryMappedInputFile> _files = new ConcurrentDictionary<string, MemoryMappedInputFile>();

		public IEnumerable<string> GetOpenedFiles()
		{
			return _files.Keys;
		}

		public IInputFile OpenFile(string filePath)
		{
			return _files.GetOrAdd(filePath, (string x) => new MemoryMappedInputFile(x));
		}

		public void InvalidateFile(string filePath)
		{
			if (_files.TryRemove(filePath, out MemoryMappedInputFile value))
			{
				value.Dispose();
			}
		}

		public void Dispose()
		{
			foreach (MemoryMappedInputFile value in _files.Values)
			{
				value.Dispose();
			}
			_files.Clear();
		}
	}
	public sealed class MemoryMappedInputFile : IInputFile, IDisposable
	{
		private readonly MemoryMappedFile _file;

		private readonly MemoryMappedDataSource _dataSource;

		public string FilePath { get; }

		public uint Length => (uint)_dataSource.Length;

		public MemoryMappedInputFile(string filePath)
		{
			FilePath = filePath ?? throw new ArgumentNullException("filePath");
			_file = MemoryMappedFile.CreateFromFile(filePath);
			long length = new FileInfo(filePath).Length;
			_dataSource = new MemoryMappedDataSource(_file.CreateViewAccessor(0L, length), (ulong)length);
		}

		public BinaryStreamReader CreateReader(ulong address, uint rva, uint length)
		{
			return new BinaryStreamReader(_dataSource, address, rva, length);
		}

		public void Dispose()
		{
			_file.Dispose();
			_dataSource.Dispose();
		}
	}
	public class MemoryStreamWriterPool
	{
		public ref struct RentedWriter
		{
			private bool _isDisposed;

			private readonly BinaryStreamWriter _writer;

			public MemoryStreamWriterPool Pool { get; }

			public BinaryStreamWriter Writer
			{
				get
				{
					if (_isDisposed)
					{
						throw new ObjectDisposedException("Writer");
					}
					return _writer;
				}
			}

			internal RentedWriter(MemoryStreamWriterPool pool, BinaryStreamWriter writer)
			{
				_isDisposed = false;
				Pool = pool;
				_writer = writer;
			}

			public byte[] GetData()
			{
				return ((MemoryStream)Writer.BaseStream).ToArray();
			}

			public void Dispose()
			{
				if (!_isDisposed)
				{
					Pool.Return(Writer);
					_isDisposed = true;
				}
			}
		}

		private readonly ConcurrentQueue<BinaryStreamWriter> _writers = new ConcurrentQueue<BinaryStreamWriter>();

		public RentedWriter Rent()
		{
			if (!_writers.TryDequeue(out BinaryStreamWriter result))
			{
				result = new BinaryStreamWriter(new MemoryStream());
			}
			result.BaseStream.SetLength(0L);
			return new RentedWriter(this, result);
		}

		private void Return(BinaryStreamWriter writer)
		{
			_writers.Enqueue(writer);
		}
	}
	public sealed class UncachedFileService : IFileService, IDisposable
	{
		public static UncachedFileService Instance { get; } = new UncachedFileService();


		private UncachedFileService()
		{
		}

		IEnumerable<string> IFileService.GetOpenedFiles()
		{
			return Enumerable.Empty<string>();
		}

		public IInputFile OpenFile(string filePath)
		{
			return new ByteArrayInputFile(filePath);
		}

		void IFileService.InvalidateFile(string filePath)
		{
		}

		void IDisposable.Dispose()
		{
		}
	}
	public sealed class UnmanagedDataSource : IDataSource
	{
		private unsafe readonly void* _basePointer;

		public unsafe ulong BaseAddress => (ulong)_basePointer;

		public unsafe byte this[ulong address]
		{
			get
			{
				if (!IsValidAddress(address))
				{
					throw new ArgumentOutOfRangeException("address");
				}
				return *(byte*)address;
			}
		}

		public ulong Length { get; }

		public unsafe UnmanagedDataSource(IntPtr basePointer, ulong length)
			: this(basePointer.ToPointer(), length)
		{
		}

		public unsafe UnmanagedDataSource(void* basePointer, ulong length)
		{
			_basePointer = basePointer;
			Length = length;
		}

		public unsafe bool IsValidAddress(ulong address)
		{
			if (address >= (ulong)_basePointer)
			{
				return (ulong)((long)address - (long)_basePointer) < Length;
			}
			return false;
		}

		public unsafe int ReadBytes(ulong address, byte[] buffer, int index, int count)
		{
			if (!IsValidAddress(address))
			{
				return 0;
			}
			ulong num = address - (ulong)_basePointer;
			int num2 = (int)Math.Min((ulong)count, Length - num);
			Marshal.Copy((IntPtr)(long)address, buffer, index, num2);
			return num2;
		}
	}
	public sealed class ZeroesDataSource : IDataSource
	{
		public ulong BaseAddress { get; }

		public byte this[ulong address]
		{
			get
			{
				if (IsValidAddress(address))
				{
					return 0;
				}
				throw new IndexOutOfRangeException("address");
			}
		}

		public ulong Length { get; }

		public ZeroesDataSource(ulong length)
			: this(0uL, length)
		{
		}

		public ZeroesDataSource(ulong baseAddress, ulong length)
		{
			BaseAddress = baseAddress;
			Length = length;
		}

		public bool IsValidAddress(ulong address)
		{
			return address - BaseAddress < Length;
		}

		public int ReadBytes(ulong address, byte[] buffer, int index, int count)
		{
			int num = (int)Math.Min(Length, (ulong)count);
			Array.Clear(buffer, index, num);
			return num;
		}
	}
}
namespace AsmResolver.Collections
{
	public class BitList : IList<bool>, ICollection<bool>, IEnumerable<bool>, IEnumerable
	{
		public struct Enumerator : IEnumerator<bool>, IEnumerator, IDisposable
		{
			private readonly BitList _list;

			private readonly int _version;

			private int _index;

			public bool Current => _list[_index];

			object IEnumerator.Current => Current;

			public Enumerator(BitList list)
			{
				_index = -1;
				_version = list._version;
				_list = list;
			}

			public bool MoveNext()
			{
				if (_version != _list._version)
				{
					throw new InvalidOperationException("Collection was modified.");
				}
				if (_index >= _list.Count)
				{
					return false;
				}
				_index++;
				return true;
			}

			public void Reset()
			{
				_index = -1;
			}

			public void Dispose()
			{
			}
		}

		private const int WordSize = 32;

		private uint[] _words;

		private int _version;

		public int Count { get; private set; }

		public bool IsReadOnly => false;

		public bool this[int index]
		{
			get
			{
				if (index < 0 || index >= Count)
				{
					throw new IndexOutOfRangeException();
				}
				var (num, num2) = SplitWordBitIndex(index);
				return ((_words[num] >> num2) & 1) != 0;
			}
			set
			{
				if (index < 0 || index >= Count)
				{
					throw new IndexOutOfRangeException();
				}
				var (num, num2) = SplitWordBitIndex(index);
				_words[num] = (_words[num] & (uint)(~(1 << num2))) | (value ? ((uint)(1 << num2)) : 0u);
				_version++;
			}
		}

		public BitList()
		{
			_words = new uint[1];
		}

		public BitList(int capacity)
		{
			_words = new uint[((uint)capacity).Align(32u)];
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static (int wordIndex, int bitIndex) SplitWordBitIndex(int index)
		{
			int result;
			return (Math.DivRem(index, 32, out result), result);
		}

		public void Add(bool item)
		{
			EnsureCapacity(Count + 1);
			Count++;
			this[Count - 1] = item;
			_version++;
		}

		public void Clear()
		{
			Count = 0;
		}

		public bool Contains(bool item)
		{
			return IndexOf(item) != -1;
		}

		public void CopyTo(bool[] array, int arrayIndex)
		{
			for (int i = 0; i < Count; i++)
			{
				array[arrayIndex + i] = this[i];
			}
		}

		public bool Remove(bool item)
		{
			int num = IndexOf(item);
			if (num == -1)
			{
				return false;
			}
			RemoveAt(num);
			return true;
		}

		public int IndexOf(bool item)
		{
			for (int i = 0; i < Count; i++)
			{
				var (num, num2) = SplitWordBitIndex(i);
				if (((_words[num] >> num2) & 1) != 0 == item)
				{
					return i;
				}
			}
			return -1;
		}

		public void Insert(int index, bool item)
		{
			if (index < 0 || index > Count)
			{
				throw new IndexOutOfRangeException();
			}
			EnsureCapacity(Count++);
			(int wordIndex, int bitIndex) tuple = SplitWordBitIndex(index);
			int item2 = tuple.wordIndex;
			int item3 = tuple.bitIndex;
			uint num = _words[item2] & 0x80000000u;
			uint num2 = (uint)((1 << item3) - 1);
			uint num3 = ~num2;
			_words[item2] = ((_words[item2] & num3) << 1) | (item ? ((uint)(1 << item3)) : 0u) | (_words[item2] & num2);
			for (int i = item2 + 1; i < _words.Length; i++)
			{
				int num4 = (int)_words[i] & int.MinValue;
				_words[i] = (_words[i] << 1) | (num >> 31);
				num = (uint)num4;
			}
			_version++;
		}

		public void RemoveAt(int index)
		{
			Count--;
			(int wordIndex, int bitIndex) tuple = SplitWordBitIndex(index);
			int item = tuple.wordIndex;
			int item2 = tuple.bitIndex;
			uint num = ((item + 1 < _words.Length && ((uint)index).Align(32u) < Count) ? (_words[item + 1] & 1u) : 0u);
			uint num2 = (uint)((1 << item2) - 1);
			uint num3 = (uint)(~((1 << item2 + 1) - 1));
			_words[item] = ((_words[item] & num3) >> 1) | (_words[item] & num2) | (num << 31);
			for (int i = item + 1; i < _words.Length; i++)
			{
				uint num4 = ((i + 1 < _words.Length && ((uint)index).Align(32u) < Count) ? (_words[i + 1] & 1) : 0);
				_words[i] = (_words[i] >> 1) | (num << 31);
				num = num4;
			}
			_version++;
		}

		public void EnsureCapacity(int capacity)
		{
			if (capacity >= 32 * _words.Length)
			{
				int newSize = (int)(((uint)capacity).Align(32u) / 8);
				Array.Resize(ref _words, newSize);
			}
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator<bool> IEnumerable<bool>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public interface IOwnedCollectionElement<TOwner>
	{
		TOwner? Owner { get; set; }
	}
	[DebuggerDisplay("Count = {Count}")]
	public abstract class LazyList<TItem> : IList<TItem>, ICollection<TItem>, IEnumerable<TItem>, IEnumerable
	{
		public struct Enumerator : IEnumerator<TItem?>, IEnumerator, IDisposable
		{
			private readonly LazyList<TItem> _list;

			private List<TItem>.Enumerator _enumerator;

			private bool hasEnumerator;

			public TItem? Current
			{
				get
				{
					if (!hasEnumerator)
					{
						return default(TItem);
					}
					return _enumerator.Current;
				}
			}

			object? IEnumerator.Current => Current;

			public Enumerator(LazyList<TItem> list)
			{
				_list = list;
				_enumerator = default(List<TItem>.Enumerator);
				hasEnumerator = false;
			}

			public bool MoveNext()
			{
				if (!hasEnumerator)
				{
					_list.EnsureIsInitialized();
					_enumerator = _list._items.GetEnumerator();
					hasEnumerator = true;
				}
				return _enumerator.MoveNext();
			}

			public void Reset()
			{
				throw new NotSupportedException();
			}

			public void Dispose()
			{
				if (hasEnumerator)
				{
					_enumerator.Dispose();
				}
			}
		}

		private readonly List<TItem> _items;

		public TItem this[int index]
		{
			get
			{
				EnsureIsInitialized();
				return Items[index];
			}
			set
			{
				lock (_items)
				{
					EnsureIsInitialized();
					OnSetItem(index, value);
				}
			}
		}

		public virtual int Count
		{
			get
			{
				EnsureIsInitialized();
				return Items.Count;
			}
		}

		public int Capacity
		{
			get
			{
				return _items.Capacity;
			}
			set
			{
				_items.Capacity = value;
			}
		}

		public bool IsReadOnly => false;

		protected bool IsInitialized { get; private set; }

		protected IList<TItem> Items => _items;

		public LazyList()
		{
			_items = new List<TItem>();
		}

		public LazyList(int capacity)
		{
			_items = new List<TItem>(capacity);
		}

		protected abstract void Initialize();

		protected virtual void PostInitialize()
		{
		}

		private void EnsureIsInitialized()
		{
			if (IsInitialized)
			{
				return;
			}
			lock (_items)
			{
				if (!IsInitialized)
				{
					Initialize();
					IsInitialized = true;
					PostInitialize();
				}
			}
		}

		public void Add(TItem item)
		{
			Insert(Count, item);
		}

		public void AddRange(IEnumerable<TItem> items)
		{
			InsertRange(Count, items);
		}

		public void Clear()
		{
			lock (_items)
			{
				OnClearItems();
				IsInitialized = true;
			}
		}

		public bool Contains(TItem item)
		{
			EnsureIsInitialized();
			return Items.Contains(item);
		}

		public void CopyTo(TItem[] array, int arrayIndex)
		{
			EnsureIsInitialized();
			Items.CopyTo(array, arrayIndex);
		}

		public bool Remove(TItem item)
		{
			lock (_items)
			{
				EnsureIsInitialized();
				int num = Items.IndexOf(item);
				if (num == -1)
				{
					return false;
				}
				OnRemoveItem(num);
			}
			return true;
		}

		public int IndexOf(TItem item)
		{
			EnsureIsInitialized();
			return Items.IndexOf(item);
		}

		public void Insert(int index, TItem item)
		{
			lock (_items)
			{
				EnsureIsInitialized();
				OnInsertItem(index, item);
			}
		}

		private void InsertRange(int index, IEnumerable<TItem> items)
		{
			lock (_items)
			{
				EnsureIsInitialized();
				OnInsertRange(index, items);
			}
		}

		public void RemoveAt(int index)
		{
			lock (_items)
			{
				EnsureIsInitialized();
				OnRemoveItem(index);
			}
		}

		protected virtual void OnSetItem(int index, TItem item)
		{
			_items[index] = item;
		}

		protected virtual void OnInsertItem(int index, TItem item)
		{
			_items.Insert(index, item);
		}

		protected virtual void OnInsertRange(int index, IEnumerable<TItem> items)
		{
			_items.InsertRange(index, items);
		}

		protected virtual void OnRemoveItem(int index)
		{
			_items.RemoveAt(index);
		}

		protected virtual void OnClearItems()
		{
			_items.Clear();
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator<TItem> IEnumerable<TItem>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public sealed class OneToManyRelation<TKey, TValue> where TKey : notnull where TValue : notnull
	{
		public class ValueSet : ICollection<TValue>, IEnumerable<TValue>, IEnumerable
		{
			public struct Enumerator : IEnumerator<TValue>, IEnumerator, IDisposable
			{
				private List<TValue>.Enumerator _enumerator;

				public TValue Current => _enumerator.Current;

				object IEnumerator.Current => ((IEnumerator)_enumerator).Current;

				internal Enumerator(List<TValue>.Enumerator enumerator)
				{
					_enumerator = enumerator;
				}

				public bool MoveNext()
				{
					return _enumerator.MoveNext();
				}

				public void Reset()
				{
					throw new NotSupportedException();
				}

				public void Dispose()
				{
					_enumerator.Dispose();
				}
			}

			public static readonly ValueSet Empty = new ValueSet();

			internal List<TValue> Items { get; } = new List<TValue>();


			public int Count => Items.Count;

			public bool IsReadOnly => true;

			public void Add(TValue item)
			{
				throw new NotSupportedException();
			}

			public void Clear()
			{
				throw new NotSupportedException();
			}

			public bool Contains(TValue item)
			{
				return Items.Contains(item);
			}

			public void CopyTo(TValue[] array, int arrayIndex)
			{
				Items.CopyTo(array, arrayIndex);
			}

			public bool Remove(TValue item)
			{
				throw new NotSupportedException();
			}

			public Enumerator GetEnumerator()
			{
				return new Enumerator(Items.GetEnumerator());
			}

			IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable)Items).GetEnumerator();
			}
		}

		private readonly Dictionary<TKey, ValueSet> _memberLists;

		private readonly Dictionary<TValue, TKey> _memberOwners;

		public OneToManyRelation()
		{
			_memberLists = new Dictionary<TKey, ValueSet>();
			_memberOwners = new Dictionary<TValue, TKey>();
		}

		public OneToManyRelation(int capacity)
		{
			_memberLists = new Dictionary<TKey, ValueSet>(capacity);
			_memberOwners = new Dictionary<TValue, TKey>(capacity);
		}

		public bool Add(TKey key, TValue value)
		{
			if (!_memberOwners.ContainsKey(value))
			{
				if (!_memberLists.TryGetValue(key, out ValueSet value2))
				{
					value2 = new ValueSet();
					_memberLists.Add(key, value2);
				}
				value2.Items.Add(value);
				_memberOwners.Add(value, key);
				return true;
			}
			return false;
		}

		public ValueSet GetValues(TKey key)
		{
			if (!_memberLists.TryGetValue(key, out ValueSet value))
			{
				return ValueSet.Empty;
			}
			return value;
		}

		public TKey? GetKey(TValue value)
		{
			if (!_memberOwners.TryGetValue(value, out var value2))
			{
				return default(TKey);
			}
			return value2;
		}
	}
	public sealed class OneToOneRelation<TKey, TValue> where TKey : notnull where TValue : notnull
	{
		private readonly Dictionary<TKey, TValue> _keyToValue;

		private readonly Dictionary<TValue, TKey> _valueToKey;

		public OneToOneRelation()
		{
			_keyToValue = new Dictionary<TKey, TValue>();
			_valueToKey = new Dictionary<TValue, TKey>();
		}

		public OneToOneRelation(int capacity)
		{
			_keyToValue = new Dictionary<TKey, TValue>(capacity);
			_valueToKey = new Dictionary<TValue, TKey>(capacity);
		}

		public bool Add(TKey key, TValue value)
		{
			if (!_keyToValue.ContainsKey(key) && !_valueToKey.ContainsKey(value))
			{
				_keyToValue.Add(key, value);
				_valueToKey.Add(value, key);
				return true;
			}
			return false;
		}

		public TValue? GetValue(TKey key)
		{
			_keyToValue.TryGetValue(key, out var value);
			return value;
		}

		public TKey? GetKey(TValue value)
		{
			_valueToKey.TryGetValue(value, out var value2);
			return value2;
		}

		public IEnumerable<TKey> GetKeys()
		{
			return _keyToValue.Keys;
		}

		public IEnumerable<TValue> GetValues()
		{
			return _valueToKey.Keys;
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	public class OwnedCollection<TOwner, TItem> : LazyList<TItem> where TOwner : class where TItem : class, IOwnedCollectionElement<TOwner>
	{
		public TOwner Owner { get; }

		public OwnedCollection(TOwner owner)
		{
			Owner = owner ?? throw new ArgumentNullException("owner");
		}

		public OwnedCollection(TOwner owner, int capacity)
			: base(capacity)
		{
			Owner = owner ?? throw new ArgumentNullException("owner");
		}

		protected void AssertNotNullAndHasNoOwner(TItem? item)
		{
			if (item == null)
			{
				throw new ArgumentNullException("item");
			}
			if (item.Owner != null)
			{
				throw new ArgumentException("Item is already added to another collection.");
			}
		}

		protected override void Initialize()
		{
		}

		protected override void OnSetItem(int index, TItem item)
		{
			AssertNotNullAndHasNoOwner(item);
			item.Owner = Owner;
			base.Items[index].Owner = null;
			base.OnSetItem(index, item);
		}

		protected override void OnInsertItem(int index, TItem item)
		{
			AssertNotNullAndHasNoOwner(item);
			item.Owner = Owner;
			base.OnInsertItem(index, item);
		}

		protected override void OnInsertRange(int index, IEnumerable<TItem> items)
		{
			List<TItem> list = items.ToList();
			foreach (TItem item in list)
			{
				AssertNotNullAndHasNoOwner(item);
			}
			base.OnInsertRange(index, list);
			foreach (TItem item2 in list)
			{
				item2.Owner = Owner;
			}
		}

		protected override void OnRemoveItem(int index)
		{
			base[index].Owner = null;
			base.OnRemoveItem(index);
		}

		protected override void OnClearItems()
		{
			foreach (TItem item in base.Items)
			{
				item.Owner = null;
			}
			base.OnClearItems();
		}
	}
	public class ReferenceTable : Collection<ISegmentReference>, ISegment, IOffsetProvider, IWritable
	{
		private ulong _imageBase;

		private bool _is32Bit;

		public ReferenceTableAttributes Attributes { get; }

		public ReferenceTableAttributes ReferenceType => Attributes & ReferenceTableAttributes.ReferenceTypeMask;

		public bool IsOffsetTable => ReferenceType == ReferenceTableAttributes.Offset;

		public bool IsRvaTable => ReferenceType == ReferenceTableAttributes.Rva;

		public bool IsVaTable => ReferenceType == ReferenceTableAttributes.Va;

		public ReferenceTableAttributes ReferenceSize => Attributes & ReferenceTableAttributes.SizeMask;

		public bool IsAdaptive => ReferenceSize == ReferenceTableAttributes.Offset;

		public bool Is32BitTable
		{
			get
			{
				if (ReferenceSize != ReferenceTableAttributes.Force32Bit)
				{
					if (IsAdaptive)
					{
						return _is32Bit;
					}
					return false;
				}
				return true;
			}
		}

		public bool Is64BitTable
		{
			get
			{
				if (ReferenceSize != ReferenceTableAttributes.Force64Bit)
				{
					if (IsAdaptive)
					{
						return !_is32Bit;
					}
					return false;
				}
				return true;
			}
		}

		public bool IsZeroTerminated => (Attributes & ReferenceTableAttributes.ZeroTerminated) != 0;

		public ulong Offset { get; private set; }

		public uint Rva { get; private set; }

		public bool CanUpdateOffsets => true;

		public ReferenceTable(ReferenceTableAttributes attributes)
		{
			Attributes = attributes;
		}

		public void UpdateOffsets(in RelocationParameters parameters)
		{
			_imageBase = parameters.ImageBase;
			_is32Bit = parameters.Is32Bit;
			Offset = parameters.Offset;
			Rva = parameters.Rva;
		}

		public uint GetPhysicalSize()
		{
			return (uint)((base.Count + (IsZeroTerminated ? 1 : 0)) * (_is32Bit ? 4 : 8));
		}

		public uint GetVirtualSize()
		{
			return GetPhysicalSize();
		}

		public void Write(IBinaryStreamWriter writer)
		{
			for (int i = 0; i < base.Items.Count; i++)
			{
				ISegmentReference segmentReference = base.Items[i];
				writer.WriteNativeInt(ReferenceType switch
				{
					ReferenceTableAttributes.Offset => segmentReference.Offset, 
					ReferenceTableAttributes.Rva => segmentReference.Rva, 
					ReferenceTableAttributes.Va => segmentReference.Rva + _imageBase, 
					_ => throw new ArgumentOutOfRangeException(), 
				}, Is32BitTable);
			}
			if (IsZeroTerminated)
			{
				writer.WriteNativeInt(0uL, Is32BitTable);
			}
		}

		void ISegment.UpdateOffsets(in RelocationParameters parameters)
		{
			UpdateOffsets(in parameters);
		}
	}
	[Flags]
	public enum ReferenceTableAttributes
	{
		Offset = 0,
		Rva = 1,
		Va = 2,
		ReferenceTypeMask = 3,
		Adaptive = 0,
		Force32Bit = 4,
		Force64Bit = 8,
		SizeMask = 0xC,
		ZeroTerminated = 0x10
	}
	public class RefList<T> : ICollection, IEnumerable, IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T> where T : struct
	{
		public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable
		{
			private readonly RefList<T> _list;

			private readonly int _version;

			private int _index;

			public T Current
			{
				get
				{
					if (_index < 0 || _index >= _list._count)
					{
						return default(T);
					}
					return _list[_index];
				}
			}

			object IEnumerator.Current => Current;

			public Enumerator(RefList<T> list)
			{
				_list = list;
				_version = list._version;
				_index = -1;
			}

			public bool MoveNext()
			{
				if (_version != _list._version)
				{
					throw new InvalidOperationException("Collection was modified.");
				}
				_index++;
				if (_index >= 0)
				{
					return _index < _list._count;
				}
				return false;
			}

			public void Reset()
			{
				throw new NotSupportedException();
			}

			void IDisposable.Dispose()
			{
			}
		}

		public const int DefaultCapacity = 4;

		private T[] _items;

		private int _count;

		private int _version;

		public int Count => _count;

		public int Capacity
		{
			get
			{
				return _items.Length;
			}
			set
			{
				if (value != _items.Length)
				{
					if (value < _count)
					{
						throw new ArgumentException("Capacity must be equal or larger than the current number of elements in the list.");
					}
					EnsureCapacity(value);
					IncrementVersion();
				}
			}
		}

		public int Version => _version;

		bool ICollection<T>.IsReadOnly => false;

		bool ICollection.IsSynchronized => false;

		object ICollection.SyncRoot => this;

		public T this[int index]
		{
			get
			{
				AssertIsValidIndex(index);
				return _items[index];
			}
			set
			{
				AssertIsValidIndex(index);
				_items[index] = value;
				IncrementVersion();
			}
		}

		public RefList()
			: this(4)
		{
		}

		public RefList(int capacity)
		{
			_items = new T[capacity];
		}

		public ref T GetElementRef(int index)
		{
			AssertIsValidIndex(index);
			return ref _items[index];
		}

		public ref T GetElementRef(int index, out int version)
		{
			AssertIsValidIndex(index);
			version = _version;
			return ref _items[index];
		}

		public void Add(in T item)
		{
			EnsureCapacity(_count + 1);
			_items[_count] = item;
			_count++;
			IncrementVersion();
		}

		void ICollection<T>.Add(T item)
		{
			Add(in item);
		}

		public void Clear()
		{
			Array.Clear(_items, 0, _items.Length);
			_count = 0;
			IncrementVersion();
		}

		bool ICollection<T>.Contains(T item)
		{
			return this.IndexOf(item) >= 0;
		}

		public bool Contains(in T item)
		{
			return this.IndexOf(item) >= 0;
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			_items.CopyTo(array, arrayIndex);
		}

		public void CopyTo(Array array, int index)
		{
			_items.CopyTo(array, index);
		}

		public bool Remove(in T item)
		{
			int num = this.IndexOf(item);
			if (num > 0)
			{
				RemoveAt(num);
				return true;
			}
			return false;
		}

		bool ICollection<T>.Remove(T item)
		{
			return Remove(in item);
		}

		public int IndexOf(in T item)
		{
			return Array.IndexOf(_items, item, 0, _count);
		}

		public void Insert(int index, in T item)
		{
			EnsureCapacity(_count + 1);
			if (index < _count)
			{
				Array.Copy(_items, index, _items, index + 1, _count - index);
			}
			_items[index] = item;
			_count++;
			IncrementVersion();
		}

		void IList<T>.Insert(int index, T item)
		{
			Insert(index, in item);
		}

		public int IndexOf(T item)
		{
			return Array.IndexOf(_items, item, 0, _count);
		}

		public void RemoveAt(int index)
		{
			if (index < 0 || index >= _count)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			_count--;
			if (index < _count)
			{
				Array.Copy(_items, index + 1, _items, index, _count - index);
			}
			_items[_count] = default(T);
			IncrementVersion();
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(this);
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		private void AssertIsValidIndex(int index)
		{
			if (index < 0 || index >= Count)
			{
				throw new IndexOutOfRangeException();
			}
		}

		private void EnsureCapacity(int requiredCount)
		{
			if (_items.Length < requiredCount)
			{
				int num = ((_items.Length == 0) ? 1 : (_items.Length * 2));
				if (num < requiredCount)
				{
					num = requiredCount;
				}
				Array.Resize(ref _items, num);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void IncrementVersion()
		{
			_version++;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
}

folder/AsmResolver.DotNet.dll

Decompiled 11 months ago
using System;
using System.Buffers.Binary;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.DotNet.Builder;
using AsmResolver.DotNet.Builder.Discovery;
using AsmResolver.DotNet.Builder.Metadata;
using AsmResolver.DotNet.Builder.Metadata.Blob;
using AsmResolver.DotNet.Builder.Metadata.Guid;
using AsmResolver.DotNet.Builder.Metadata.Strings;
using AsmResolver.DotNet.Builder.Metadata.Tables;
using AsmResolver.DotNet.Builder.Metadata.UserStrings;
using AsmResolver.DotNet.Builder.Resources;
using AsmResolver.DotNet.Builder.VTableFixups;
using AsmResolver.DotNet.Code;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Code.Native;
using AsmResolver.DotNet.Collections;
using AsmResolver.DotNet.Config.Json;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
using AsmResolver.DotNet.Signatures.Marshal;
using AsmResolver.DotNet.Signatures.Security;
using AsmResolver.DotNet.Signatures.Types;
using AsmResolver.DotNet.Signatures.Types.Parsing;
using AsmResolver.IO;
using AsmResolver.PE;
using AsmResolver.PE.Builder;
using AsmResolver.PE.Code;
using AsmResolver.PE.Debug;
using AsmResolver.PE.DotNet;
using AsmResolver.PE.DotNet.Builder;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata;
using AsmResolver.PE.DotNet.Metadata.Blob;
using AsmResolver.PE.DotNet.Metadata.Guid;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using AsmResolver.PE.DotNet.Metadata.UserStrings;
using AsmResolver.PE.DotNet.Resources;
using AsmResolver.PE.DotNet.StrongName;
using AsmResolver.PE.DotNet.VTableFixups;
using AsmResolver.PE.Exports;
using AsmResolver.PE.File;
using AsmResolver.PE.File.Headers;
using AsmResolver.PE.Imports;
using AsmResolver.PE.Platforms;
using AsmResolver.PE.Relocations;
using AsmResolver.PE.Win32Resources;
using AsmResolver.PE.Win32Resources.Builder;
using AsmResolver.Patching;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("AsmResolver.DotNet")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Washi 2016-2024")]
[assembly: AssemblyDescription("High level .NET image models for the AsmResolver executable file inspection toolsuite.")]
[assembly: AssemblyFileVersion("5.5.1.0")]
[assembly: AssemblyInformationalVersion("5.5.1+78ce89adebcc7e5dbeb1d4a1a35afcd513fb87a1")]
[assembly: AssemblyProduct("AsmResolver.DotNet")]
[assembly: AssemblyTitle("AsmResolver.DotNet")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Washi1337/AsmResolver")]
[assembly: AssemblyVersion("5.5.1.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
}
namespace AsmResolver.DotNet
{
	public class AssemblyDefinition : AssemblyDescriptor, IModuleProvider, IHasSecurityDeclaration, IMetadataMember
	{
		private IList<ModuleDefinition>? _modules;

		private IList<SecurityDeclaration>? _securityDeclarations;

		private readonly LazyVariable<AssemblyDefinition, byte[]?> _publicKey;

		private byte[]? _publicKeyToken;

		public AssemblyHashAlgorithm HashAlgorithm { get; set; }

		[MemberNotNullWhen(true, "ManifestModule")]
		public bool HasManifestModule
		{
			[MemberNotNullWhen(true, "ManifestModule")]
			get
			{
				return ManifestModule != null;
			}
		}

		public ModuleDefinition? ManifestModule
		{
			get
			{
				if (Modules.Count <= 0)
				{
					return null;
				}
				return Modules[0];
			}
		}

		ModuleDefinition? IModuleProvider.Module => ManifestModule;

		public IList<ModuleDefinition> Modules
		{
			get
			{
				if (_modules == null)
				{
					Interlocked.CompareExchange(ref _modules, GetModules(), null);
				}
				return _modules;
			}
		}

		public IList<SecurityDeclaration> SecurityDeclarations
		{
			get
			{
				if (_securityDeclarations == null)
				{
					Interlocked.CompareExchange(ref _securityDeclarations, GetSecurityDeclarations(), null);
				}
				return _securityDeclarations;
			}
		}

		public byte[]? PublicKey
		{
			get
			{
				return _publicKey.GetValue(this);
			}
			set
			{
				_publicKey.SetValue(value);
				_publicKeyToken = null;
			}
		}

		public override bool IsCorLib
		{
			get
			{
				if (base.Name != null)
				{
					return KnownCorLibs.KnownCorLibNames.Contains(Utf8String.op_Implicit(base.Name));
				}
				return false;
			}
		}

		public static AssemblyDefinition FromBytes(byte[] buffer)
		{
			return FromImage(PEImage.FromBytes(buffer));
		}

		public static AssemblyDefinition FromFile(string filePath)
		{
			return FromImage(PEImage.FromFile(filePath), new ModuleReaderParameters(Path.GetDirectoryName(filePath)));
		}

		public static AssemblyDefinition FromFile(PEFile file)
		{
			return FromImage(PEImage.FromFile((IPEFile)(object)file));
		}

		public static AssemblyDefinition FromFile(IInputFile file)
		{
			return FromImage(PEImage.FromFile(file));
		}

		public static AssemblyDefinition FromReader(in BinaryStreamReader reader, PEMappingMode mode = 0)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return FromImage(PEImage.FromReader(ref reader, mode));
		}

		public static AssemblyDefinition FromImage(IPEImage peImage)
		{
			return FromImage(peImage, new ModuleReaderParameters(Path.GetDirectoryName(peImage.FilePath)));
		}

		public static AssemblyDefinition FromImage(IPEImage peImage, ModuleReaderParameters readerParameters)
		{
			return ModuleDefinition.FromImage(peImage, readerParameters).Assembly ?? throw new BadImageFormatException("The provided PE image does not contain an assembly manifest.");
		}

		protected AssemblyDefinition(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_publicKey = new LazyVariable<AssemblyDefinition, byte[]>((Func<AssemblyDefinition, byte[]>)((AssemblyDefinition x) => x.GetPublicKey()));
		}

		public AssemblyDefinition(Utf8String? name, Version version)
			: this(new MetadataToken((TableIndex)32, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			base.Name = name;
			base.Version = version;
		}

		protected virtual IList<ModuleDefinition> GetModules()
		{
			return (IList<ModuleDefinition>)new OwnedCollection<AssemblyDefinition, ModuleDefinition>(this);
		}

		protected virtual IList<SecurityDeclaration> GetSecurityDeclarations()
		{
			return (IList<SecurityDeclaration>)new OwnedCollection<IHasSecurityDeclaration, SecurityDeclaration>((IHasSecurityDeclaration)this);
		}

		protected virtual byte[]? GetPublicKey()
		{
			return null;
		}

		public override byte[]? GetPublicKeyToken()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!base.HasPublicKey)
			{
				return PublicKey;
			}
			if (_publicKeyToken == null)
			{
				_publicKeyToken = ((PublicKey != null) ? AssemblyDescriptor.ComputePublicKeyToken(PublicKey, HashAlgorithm) : null);
			}
			return _publicKeyToken;
		}

		public override bool IsImportedInModule(ModuleDefinition module)
		{
			return ManifestModule == module;
		}

		public override AssemblyReference ImportWith(ReferenceImporter importer)
		{
			return (AssemblyReference)importer.ImportScope(new AssemblyReference(this));
		}

		public override AssemblyDefinition Resolve()
		{
			return this;
		}

		public virtual bool TryGetTargetFramework(out DotNetRuntimeInfo info)
		{
			for (int i = 0; i < base.CustomAttributes.Count; i++)
			{
				ICustomAttributeType constructor = base.CustomAttributes[i].Constructor;
				if (constructor?.DeclaringType != null && constructor.DeclaringType.IsTypeOf("System.Runtime.Versioning", "TargetFrameworkAttribute"))
				{
					string text = base.CustomAttributes[i].Signature?.FixedArguments[0].Element?.ToString();
					if (text != null && DotNetRuntimeInfo.TryParse(text, out info))
					{
						return true;
					}
				}
			}
			info = default(DotNetRuntimeInfo);
			return false;
		}

		public void Write(string filePath)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			Write(filePath, new ManagedPEImageBuilder(), (IPEFileBuilder)new ManagedPEFileBuilder());
		}

		public void Write(string filePath, IPEImageBuilder imageBuilder)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			Write(filePath, imageBuilder, (IPEFileBuilder)new ManagedPEFileBuilder());
		}

		public void Write(string filePath, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
		{
			string directoryName = Path.GetDirectoryName(Path.GetFullPath(filePath));
			if (directoryName == null || !Directory.Exists(directoryName))
			{
				throw new DirectoryNotFoundException();
			}
			for (int i = 0; i < Modules.Count; i++)
			{
				ModuleDefinition moduleDefinition = Modules[i];
				string text;
				if (moduleDefinition != ManifestModule)
				{
					Utf8String? name = moduleDefinition.Name;
					text = Path.Combine(directoryName, ((name != null) ? name.Value : null) ?? $"module{i}.bin");
				}
				else
				{
					text = filePath;
				}
				string filePath2 = text;
				moduleDefinition.Write(filePath2, imageBuilder, fileBuilder);
			}
		}

		public void WriteManifest(Stream stream)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			WriteManifest(stream, new ManagedPEImageBuilder(), (IPEFileBuilder)new ManagedPEFileBuilder());
		}

		public void WriteManifest(Stream stream, IPEImageBuilder imageBuilder)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			WriteManifest(stream, imageBuilder, (IPEFileBuilder)new ManagedPEFileBuilder());
		}

		public void WriteManifest(Stream stream, IPEImageBuilder imageBuilder, IPEFileBuilder fileBuilder)
		{
			ManifestModule?.Write(stream, imageBuilder, fileBuilder);
		}
	}
	public abstract class AssemblyDescriptor : MetadataMember, IHasCustomAttribute, IMetadataMember, IFullNameProvider, INameProvider, IImportable
	{
		private const int PublicKeyTokenLength = 8;

		private readonly LazyVariable<AssemblyDescriptor, Utf8String?> _name;

		private readonly LazyVariable<AssemblyDescriptor, Utf8String?> _culture;

		private IList<CustomAttribute>? _customAttributes;

		public Utf8String? Name
		{
			get
			{
				return _name.GetValue(this);
			}
			set
			{
				_name.SetValue(value);
			}
		}

		string? INameProvider.Name => Utf8String.op_Implicit(Name);

		public string FullName
		{
			get
			{
				string text = ((!Utf8String.IsNullOrEmpty(Culture)) ? Utf8String.op_Implicit(Culture) : "neutral");
				byte[] publicKeyToken = GetPublicKeyToken();
				string text2 = ((publicKeyToken != null) ? string.Join(string.Empty, publicKeyToken.Select((byte x) => x.ToString("x2"))) : "null");
				return $"{Name}, Version={Version}, Culture={text}, PublicKeyToken={text2}";
			}
		}

		public Version Version { get; set; }

		public AssemblyAttributes Attributes { get; set; }

		public bool HasPublicKey
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 1) > 0;
			}
			set
			{
				//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_0011: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (AssemblyAttributes)((Attributes & -2) | (value ? 1 : 0));
			}
		}

		public bool EnableJitCompileTracking
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x8000) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (AssemblyAttributes)((Attributes & -32769) | (value ? 32768 : 0));
			}
		}

		public bool DisableJitCompileOptimizer
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x4000) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (AssemblyAttributes)((Attributes & -16385) | (value ? 16384 : 0));
			}
		}

		public bool IsWindowsRuntime
		{
			get
			{
				//IL_0001: 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_0011: Invalid comparison between Unknown and I4
				return (Attributes & 0xE00) == 512;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (AssemblyAttributes)((Attributes & -3585) | (value ? 512 : 0));
			}
		}

		public bool IsRetargetable
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x100) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (AssemblyAttributes)((Attributes & -257) | (value ? 256 : 0));
			}
		}

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		public Utf8String? Culture
		{
			get
			{
				return _culture.GetValue(this);
			}
			set
			{
				_culture.SetValue(value);
			}
		}

		public abstract bool IsCorLib { get; }

		protected AssemblyDescriptor(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_name = new LazyVariable<AssemblyDescriptor, Utf8String>((Func<AssemblyDescriptor, Utf8String>)((AssemblyDescriptor x) => x.GetName()));
			_culture = new LazyVariable<AssemblyDescriptor, Utf8String>((Func<AssemblyDescriptor, Utf8String>)((AssemblyDescriptor x) => x.GetCulture()));
			Version = new Version(0, 0, 0, 0);
		}

		protected virtual IList<CustomAttribute> GetCustomAttributes()
		{
			return (IList<CustomAttribute>)new OwnedCollection<IHasCustomAttribute, CustomAttribute>((IHasCustomAttribute)this);
		}

		public abstract byte[]? GetPublicKeyToken();

		protected virtual Utf8String? GetName()
		{
			return null;
		}

		protected virtual Utf8String? GetCulture()
		{
			return null;
		}

		public override string ToString()
		{
			return FullName;
		}

		public abstract bool IsImportedInModule(ModuleDefinition module);

		public abstract AssemblyReference ImportWith(ReferenceImporter importer);

		IImportable IImportable.ImportWith(ReferenceImporter importer)
		{
			return ImportWith(importer);
		}

		protected static byte[] ComputePublicKeyToken(byte[] publicKey, AssemblyHashAlgorithm algorithm)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_0008: 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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected I4, but got Unknown
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			HashAlgorithm hashAlgorithm;
			if ((int)algorithm <= 32771)
			{
				if ((int)algorithm != 0)
				{
					if ((int)algorithm != 32771)
					{
						goto IL_0067;
					}
					hashAlgorithm = MD5.Create();
				}
				else
				{
					hashAlgorithm = SHA1.Create();
				}
			}
			else if ((int)algorithm != 32772)
			{
				switch (algorithm - 32780)
				{
				case 0:
					break;
				case 1:
					goto IL_0057;
				case 2:
					goto IL_005f;
				default:
					goto IL_0067;
				}
				hashAlgorithm = SHA256.Create();
			}
			else
			{
				hashAlgorithm = SHA1.Create();
			}
			goto IL_007d;
			IL_007d:
			using (HashAlgorithm hashAlgorithm2 = hashAlgorithm)
			{
				byte[] array = hashAlgorithm2.ComputeHash(publicKey);
				byte[] array2 = new byte[8];
				for (int i = 0; i < 8; i++)
				{
					array2[i] = array[array.Length - 1 - i];
				}
				return array2;
			}
			IL_0067:
			throw new NotSupportedException($"Unsupported hashing algorithm {algorithm}.");
			IL_0057:
			hashAlgorithm = SHA384.Create();
			goto IL_007d;
			IL_005f:
			hashAlgorithm = SHA512.Create();
			goto IL_007d;
		}

		public abstract AssemblyDefinition? Resolve();
	}
	public class AssemblyReference : AssemblyDescriptor, IResolutionScope, IMetadataMember, INameProvider, IModuleProvider, IImportable, IOwnedCollectionElement<ModuleDefinition>, IImplementation, IFullNameProvider, IHasCustomAttribute
	{
		private readonly LazyVariable<AssemblyReference, byte[]?> _publicKeyOrToken;

		private readonly LazyVariable<AssemblyReference, byte[]?> _hashValue;

		private byte[]? _publicKeyToken;

		public ModuleDefinition? Module { get; private set; }

		ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
		{
			get
			{
				return Module;
			}
			set
			{
				Module = value;
			}
		}

		public byte[]? PublicKeyOrToken
		{
			get
			{
				return _publicKeyOrToken.GetValue(this);
			}
			set
			{
				_publicKeyOrToken.SetValue(value);
			}
		}

		public byte[]? HashValue
		{
			get
			{
				return _hashValue.GetValue(this);
			}
			set
			{
				_hashValue.SetValue(value);
			}
		}

		public override bool IsCorLib => KnownCorLibs.KnownCorLibReferences.Contains(this);

		protected AssemblyReference(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_publicKeyOrToken = new LazyVariable<AssemblyReference, byte[]>((Func<AssemblyReference, byte[]>)((AssemblyReference x) => x.GetPublicKeyOrToken()));
			_hashValue = new LazyVariable<AssemblyReference, byte[]>((Func<AssemblyReference, byte[]>)((AssemblyReference x) => x.GetHashValue()));
		}

		public AssemblyReference(Utf8String? name, Version version)
			: this(new MetadataToken((TableIndex)35, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			base.Name = name;
			base.Version = version;
		}

		public AssemblyReference(Utf8String? name, Version version, bool publicKey, byte[]? publicKeyOrToken)
			: this(new MetadataToken((TableIndex)35, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			base.Name = name;
			base.Version = version;
			base.HasPublicKey = publicKey;
			PublicKeyOrToken = publicKeyOrToken;
		}

		public AssemblyReference(AssemblyDescriptor descriptor)
			: this(new MetadataToken((TableIndex)35, 0u))
		{
			//IL_0004: 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)
			base.Name = descriptor.Name;
			base.Version = descriptor.Version;
			base.Attributes = descriptor.Attributes;
			base.HasPublicKey = false;
			PublicKeyOrToken = descriptor.GetPublicKeyToken();
			byte[]? publicKeyOrToken = PublicKeyOrToken;
			if (publicKeyOrToken != null && publicKeyOrToken.Length == 0)
			{
				PublicKeyOrToken = null;
			}
			base.Culture = descriptor.Culture;
			if (Utf8String.IsNullOrEmpty(base.Culture))
			{
				base.Culture = null;
			}
		}

		public override byte[]? GetPublicKeyToken()
		{
			if (!base.HasPublicKey)
			{
				return PublicKeyOrToken;
			}
			if (_publicKeyToken == null && PublicKeyOrToken != null)
			{
				lock (_publicKeyOrToken)
				{
					if (_publicKeyToken == null && PublicKeyOrToken != null)
					{
						_publicKeyToken = AssemblyDescriptor.ComputePublicKeyToken(PublicKeyOrToken, (AssemblyHashAlgorithm)32772);
					}
				}
			}
			return _publicKeyToken;
		}

		protected virtual byte[]? GetPublicKeyOrToken()
		{
			return null;
		}

		protected virtual byte[]? GetHashValue()
		{
			return null;
		}

		public override bool IsImportedInModule(ModuleDefinition module)
		{
			return Module == module;
		}

		public override AssemblyReference ImportWith(ReferenceImporter importer)
		{
			return (AssemblyReference)importer.ImportScope(this);
		}

		public override AssemblyDefinition? Resolve()
		{
			return Module?.MetadataResolver.AssemblyResolver.Resolve(this);
		}

		AssemblyDescriptor IResolutionScope.GetAssembly()
		{
			return this;
		}
	}
	public abstract class AssemblyResolverBase : IAssemblyResolver
	{
		private static readonly string[] BinaryFileExtensions = new string[2] { ".dll", ".exe" };

		private static readonly SignatureComparer Comparer = new SignatureComparer(SignatureComparisonFlags.AcceptNewerVersions);

		private readonly ConcurrentDictionary<AssemblyDescriptor, AssemblyDefinition> _cache = new ConcurrentDictionary<AssemblyDescriptor, AssemblyDefinition>(new SignatureComparer());

		public IFileService FileService { get; }

		public IList<string> SearchDirectories { get; } = new List<string>();


		protected AssemblyResolverBase(IFileService fileService)
		{
			FileService = fileService ?? throw new ArgumentNullException("fileService");
		}

		public AssemblyDefinition? Resolve(AssemblyDescriptor assembly)
		{
			AssemblyDefinition value;
			while (!_cache.TryGetValue(assembly, out value))
			{
				AssemblyDefinition assemblyDefinition = ResolveImpl(assembly);
				if (assemblyDefinition == null)
				{
					break;
				}
				_cache.TryAdd(assembly, assemblyDefinition);
			}
			return value;
		}

		public void AddToCache(AssemblyDescriptor descriptor, AssemblyDefinition definition)
		{
			if (_cache.ContainsKey(descriptor))
			{
				throw new ArgumentException("The cache already contains an entry of assembly " + descriptor.FullName + ".", "descriptor");
			}
			if (!Comparer.Equals(descriptor, definition))
			{
				throw new ArgumentException("Assembly descriptor and definition do not refer to the same assembly.");
			}
			_cache.TryAdd(descriptor, definition);
		}

		public bool RemoveFromCache(AssemblyDescriptor descriptor)
		{
			AssemblyDefinition value;
			return _cache.TryRemove(descriptor, out value);
		}

		public bool HasCached(AssemblyDescriptor descriptor)
		{
			return _cache.ContainsKey(descriptor);
		}

		public void ClearCache()
		{
			_cache.Clear();
		}

		protected virtual AssemblyDefinition? ResolveImpl(AssemblyDescriptor assembly)
		{
			string text = ProbeSearchDirectories(assembly);
			if (string.IsNullOrEmpty(text))
			{
				if (assembly.GetPublicKeyToken() != null)
				{
					text = ProbeRuntimeDirectories(assembly);
				}
				if (string.IsNullOrEmpty(text))
				{
					return null;
				}
			}
			AssemblyDefinition result = null;
			try
			{
				result = LoadAssemblyFromFile(text);
			}
			catch
			{
			}
			return result;
		}

		protected virtual AssemblyDefinition LoadAssemblyFromFile(string path)
		{
			return AssemblyDefinition.FromFile(FileService.OpenFile(path));
		}

		protected string? ProbeSearchDirectories(AssemblyDescriptor assembly)
		{
			for (int i = 0; i < SearchDirectories.Count; i++)
			{
				string text = ProbeDirectory(assembly, SearchDirectories[i]);
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			return null;
		}

		protected abstract string? ProbeRuntimeDirectories(AssemblyDescriptor assembly);

		protected static string? ProbeDirectory(AssemblyDescriptor assembly, string directory)
		{
			if (assembly.Name == null)
			{
				return null;
			}
			string text;
			if (!string.IsNullOrEmpty(Utf8String.op_Implicit(assembly.Culture)))
			{
				text = Path.Combine(directory, Utf8String.op_Implicit(assembly.Culture), Utf8String.op_Implicit(assembly.Name));
				if ((ProbeFileFromFilePathWithoutExtension(text) ?? ProbeFileFromFilePathWithoutExtension(Path.Combine(text, Utf8String.op_Implicit(assembly.Name)))) == null)
				{
					return null;
				}
			}
			text = Path.Combine(directory, Utf8String.op_Implicit(assembly.Name));
			return ProbeFileFromFilePathWithoutExtension(text) ?? ProbeFileFromFilePathWithoutExtension(Path.Combine(text, Utf8String.op_Implicit(assembly.Name)));
		}

		internal static string? ProbeFileFromFilePathWithoutExtension(string baseFilePath)
		{
			string[] binaryFileExtensions = BinaryFileExtensions;
			foreach (string text in binaryFileExtensions)
			{
				string text2 = baseFilePath + text;
				if (File.Exists(text2))
				{
					return text2;
				}
			}
			return null;
		}
	}
	public class ClassLayout : MetadataMember
	{
		private readonly LazyVariable<ClassLayout, TypeDefinition?> _parent;

		public ushort PackingSize { get; set; }

		public uint ClassSize { get; set; }

		public TypeDefinition? Parent
		{
			get
			{
				return _parent.GetValue(this);
			}
			internal set
			{
				_parent.SetValue(value);
			}
		}

		protected ClassLayout(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_parent = new LazyVariable<ClassLayout, TypeDefinition>((Func<ClassLayout, TypeDefinition>)((ClassLayout x) => x.GetParent()));
		}

		public ClassLayout(ushort packingSize, uint classSize)
			: this(new MetadataToken((TableIndex)15, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			PackingSize = packingSize;
			ClassSize = classSize;
		}

		protected virtual TypeDefinition? GetParent()
		{
			return null;
		}

		public override string ToString()
		{
			return string.Format("{0}: {1}, {2}: {3}", "PackingSize", PackingSize, "ClassSize", ClassSize);
		}
	}
	public class Constant : MetadataMember
	{
		private readonly LazyVariable<Constant, IHasConstant?> _parent;

		private readonly LazyVariable<Constant, DataBlobSignature?> _value;

		public ElementType Type { get; set; }

		public IHasConstant? Parent
		{
			get
			{
				return _parent.GetValue(this);
			}
			internal set
			{
				_parent.SetValue(value);
			}
		}

		public DataBlobSignature? Value
		{
			get
			{
				return _value.GetValue(this);
			}
			set
			{
				_value.SetValue(value);
			}
		}

		protected Constant(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_parent = new LazyVariable<Constant, IHasConstant>((Func<Constant, IHasConstant>)((Constant x) => x.GetParent()));
			_value = new LazyVariable<Constant, DataBlobSignature>((Func<Constant, DataBlobSignature>)((Constant x) => x.GetValue()));
		}

		public Constant(ElementType type, DataBlobSignature? value)
			: this(new MetadataToken((TableIndex)11, 0u))
		{
			//IL_0004: 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)
			Type = type;
			Value = value;
		}

		protected virtual IHasConstant? GetParent()
		{
			return null;
		}

		protected virtual DataBlobSignature? GetValue()
		{
			return null;
		}

		public static Constant FromValue(bool value)
		{
			return new Constant((ElementType)2, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(char value)
		{
			return new Constant((ElementType)3, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(byte value)
		{
			return new Constant((ElementType)5, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(sbyte value)
		{
			return new Constant((ElementType)4, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(ushort value)
		{
			return new Constant((ElementType)7, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(short value)
		{
			return new Constant((ElementType)6, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(uint value)
		{
			return new Constant((ElementType)9, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(int value)
		{
			return new Constant((ElementType)8, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(ulong value)
		{
			return new Constant((ElementType)11, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(long value)
		{
			return new Constant((ElementType)10, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(float value)
		{
			return new Constant((ElementType)12, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(double value)
		{
			return new Constant((ElementType)13, DataBlobSignature.FromValue(value));
		}

		public static Constant FromValue(string value)
		{
			return new Constant((ElementType)14, DataBlobSignature.FromValue(value));
		}
	}
	public class CustomAttribute : MetadataMember, IOwnedCollectionElement<IHasCustomAttribute>
	{
		private readonly LazyVariable<CustomAttribute, IHasCustomAttribute?> _parent;

		private readonly LazyVariable<CustomAttribute, ICustomAttributeType?> _constructor;

		private readonly LazyVariable<CustomAttribute, CustomAttributeSignature?> _signature;

		public IHasCustomAttribute? Parent
		{
			get
			{
				return _parent.GetValue(this);
			}
			private set
			{
				_parent.SetValue(value);
			}
		}

		IHasCustomAttribute? IOwnedCollectionElement<IHasCustomAttribute>.Owner
		{
			get
			{
				return Parent;
			}
			set
			{
				Parent = value;
			}
		}

		public ICustomAttributeType? Constructor
		{
			get
			{
				return _constructor.GetValue(this);
			}
			set
			{
				_constructor.SetValue(value);
			}
		}

		public CustomAttributeSignature? Signature
		{
			get
			{
				return _signature.GetValue(this);
			}
			set
			{
				_signature.SetValue(value);
			}
		}

		protected CustomAttribute(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_parent = new LazyVariable<CustomAttribute, IHasCustomAttribute>((Func<CustomAttribute, IHasCustomAttribute>)((CustomAttribute x) => x.GetParent()));
			_constructor = new LazyVariable<CustomAttribute, ICustomAttributeType>((Func<CustomAttribute, ICustomAttributeType>)((CustomAttribute x) => x.GetConstructor()));
			_signature = new LazyVariable<CustomAttribute, CustomAttributeSignature>((Func<CustomAttribute, CustomAttributeSignature>)((CustomAttribute x) => x.GetSignature()));
		}

		public CustomAttribute(ICustomAttributeType? constructor)
			: this(new MetadataToken((TableIndex)12, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			Constructor = constructor;
			Signature = new CustomAttributeSignature();
		}

		public CustomAttribute(ICustomAttributeType? constructor, CustomAttributeSignature? signature)
			: this(new MetadataToken((TableIndex)12, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			Constructor = constructor;
			Signature = signature;
		}

		protected virtual IHasCustomAttribute? GetParent()
		{
			return null;
		}

		protected virtual ICustomAttributeType? GetConstructor()
		{
			return null;
		}

		protected virtual CustomAttributeSignature? GetSignature()
		{
			return null;
		}

		public override string ToString()
		{
			return Constructor?.FullName ?? "<<<NULL CONSTRUCTOR>>>";
		}
	}
	public class DefaultMetadataResolver : IMetadataResolver
	{
		private readonly struct TypeResolution
		{
			private readonly IAssemblyResolver _assemblyResolver;

			private readonly Stack<IResolutionScope> _scopeStack;

			private readonly Stack<IImplementation> _implementationStack;

			public TypeResolution(IAssemblyResolver resolver)
			{
				_assemblyResolver = resolver ?? throw new ArgumentNullException("resolver");
				_scopeStack = new Stack<IResolutionScope>();
				_implementationStack = new Stack<IImplementation>();
			}

			public TypeDefinition? ResolveTypeReference(TypeReference? reference)
			{
				//IL_003e: 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)
				//IL_0047: 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: Unknown result type (might be due to invalid IL or missing references)
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				//IL_0055: Invalid comparison between Unknown and I4
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Invalid comparison between Unknown and I4
				if (reference == null)
				{
					return null;
				}
				IResolutionScope resolutionScope = reference.Scope ?? reference.Module;
				if (reference.Name == null || resolutionScope == null || _scopeStack.Contains(resolutionScope))
				{
					return null;
				}
				_scopeStack.Push(resolutionScope);
				MetadataToken metadataToken = resolutionScope.MetadataToken;
				TableIndex table = ((MetadataToken)(ref metadataToken)).Table;
				if ((int)table != 0)
				{
					if ((int)table != 1)
					{
						if ((int)table == 35)
						{
							AssemblyDefinition assemblyDefinition = reference.Module?.Assembly;
							if (assemblyDefinition != null && SignatureComparer.Default.Equals(resolutionScope.GetAssembly(), assemblyDefinition))
							{
								return FindTypeInModule(reference.Module, reference.Namespace, reference.Name);
							}
							AssemblyDefinition assemblyDefinition2 = _assemblyResolver.Resolve((AssemblyReference)resolutionScope);
							if (assemblyDefinition2 == null)
							{
								return null;
							}
							return FindTypeInAssembly(assemblyDefinition2, reference.Namespace, reference.Name);
						}
						return null;
					}
					TypeDefinition typeDefinition = ResolveTypeReference((TypeReference)resolutionScope);
					if (typeDefinition == null)
					{
						return null;
					}
					return FindTypeInType(typeDefinition, reference.Name);
				}
				return FindTypeInModule((ModuleDefinition)resolutionScope, reference.Namespace, reference.Name);
			}

			public TypeDefinition? ResolveExportedType(ExportedType? exportedType)
			{
				//IL_003b: 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)
				//IL_0044: 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_004b: 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_0069: Expected I4, but got Unknown
				IImplementation implementation = exportedType?.Implementation;
				if (exportedType?.Name == null || implementation == null || _implementationStack.Contains(implementation))
				{
					return null;
				}
				_implementationStack.Push(implementation);
				MetadataToken metadataToken = implementation.MetadataToken;
				TableIndex table = ((MetadataToken)(ref metadataToken)).Table;
				switch (table - 35)
				{
				case 0:
				{
					AssemblyDefinition assemblyDefinition = _assemblyResolver.Resolve((AssemblyReference)implementation);
					if (assemblyDefinition == null)
					{
						return null;
					}
					return FindTypeInAssembly(assemblyDefinition, exportedType.Namespace, exportedType.Name);
				}
				case 3:
					if (!string.IsNullOrEmpty(implementation.Name))
					{
						ModuleDefinition moduleDefinition = FindModuleInAssembly(exportedType.Module.Assembly, Utf8String.op_Implicit(implementation.Name));
						if (moduleDefinition == null)
						{
							return null;
						}
						return FindTypeInModule(moduleDefinition, exportedType.Namespace, exportedType.Name);
					}
					break;
				case 4:
				{
					ExportedType exportedType2 = (ExportedType)implementation;
					TypeDefinition typeDefinition = ResolveExportedType(exportedType2);
					if (typeDefinition == null)
					{
						return null;
					}
					return FindTypeInType(typeDefinition, exportedType.Name);
				}
				}
				throw new ArgumentOutOfRangeException();
			}

			private TypeDefinition? FindTypeInAssembly(AssemblyDefinition assembly, Utf8String? ns, Utf8String name)
			{
				for (int i = 0; i < assembly.Modules.Count; i++)
				{
					ModuleDefinition module = assembly.Modules[i];
					TypeDefinition typeDefinition = FindTypeInModule(module, ns, name);
					if (typeDefinition != null)
					{
						return typeDefinition;
					}
				}
				return null;
			}

			private TypeDefinition? FindTypeInModule(ModuleDefinition module, Utf8String? ns, Utf8String name)
			{
				for (int i = 0; i < module.TopLevelTypes.Count; i++)
				{
					TypeDefinition typeDefinition = module.TopLevelTypes[i];
					if (typeDefinition.IsTypeOfUtf8(ns, name))
					{
						return typeDefinition;
					}
				}
				for (int j = 0; j < module.ExportedTypes.Count; j++)
				{
					ExportedType exportedType = module.ExportedTypes[j];
					if (exportedType.IsTypeOfUtf8(ns, name))
					{
						return ResolveExportedType(exportedType);
					}
				}
				return null;
			}

			private static TypeDefinition? FindTypeInType(TypeDefinition enclosingType, Utf8String name)
			{
				for (int i = 0; i < enclosingType.NestedTypes.Count; i++)
				{
					TypeDefinition typeDefinition = enclosingType.NestedTypes[i];
					if (typeDefinition.Name == name)
					{
						return typeDefinition;
					}
				}
				return null;
			}

			private static ModuleDefinition? FindModuleInAssembly(AssemblyDefinition assembly, Utf8String name)
			{
				for (int i = 0; i < assembly.Modules.Count; i++)
				{
					ModuleDefinition moduleDefinition = assembly.Modules[i];
					if (moduleDefinition.Name == name)
					{
						return moduleDefinition;
					}
				}
				return null;
			}
		}

		private readonly ConcurrentDictionary<ITypeDescriptor, TypeDefinition> _typeCache;

		private readonly SignatureComparer _comparer = new SignatureComparer(SignatureComparisonFlags.VersionAgnostic);

		public IAssemblyResolver AssemblyResolver { get; }

		public DefaultMetadataResolver(IAssemblyResolver assemblyResolver)
		{
			AssemblyResolver = assemblyResolver ?? throw new ArgumentNullException("assemblyResolver");
			_typeCache = new ConcurrentDictionary<ITypeDescriptor, TypeDefinition>();
		}

		public TypeDefinition? ResolveType(ITypeDescriptor? type)
		{
			if (!(type is TypeDefinition result))
			{
				if (!(type is TypeReference reference))
				{
					if (!(type is TypeSpecification typeSpecification))
					{
						if (!(type is TypeSignature signature))
						{
							if (type is ExportedType exportedType)
							{
								return ResolveExportedType(exportedType);
							}
							return null;
						}
						return ResolveTypeSignature(signature);
					}
					return ResolveType(typeSpecification.Signature);
				}
				return ResolveTypeReference(reference);
			}
			return result;
		}

		private TypeDefinition? LookupInCache(ITypeDescriptor type)
		{
			if (_typeCache.TryGetValue(type, out TypeDefinition value))
			{
				if (value.IsTypeOf(type.Namespace, type.Name))
				{
					return value;
				}
				_typeCache.TryRemove(type, out TypeDefinition _);
			}
			return null;
		}

		private TypeDefinition? ResolveTypeReference(TypeReference? reference)
		{
			if (reference == null)
			{
				return null;
			}
			TypeDefinition typeDefinition = LookupInCache(reference);
			if (typeDefinition != null)
			{
				return typeDefinition;
			}
			typeDefinition = new TypeResolution(AssemblyResolver).ResolveTypeReference(reference);
			if (typeDefinition != null)
			{
				_typeCache[reference] = typeDefinition;
			}
			return typeDefinition;
		}

		private TypeDefinition? ResolveExportedType(ExportedType? exportedType)
		{
			if (exportedType == null)
			{
				return null;
			}
			TypeDefinition typeDefinition = LookupInCache(exportedType);
			if (typeDefinition != null)
			{
				return typeDefinition;
			}
			typeDefinition = new TypeResolution(AssemblyResolver).ResolveExportedType(exportedType);
			if (typeDefinition != null)
			{
				_typeCache[exportedType] = typeDefinition;
			}
			return typeDefinition;
		}

		private TypeDefinition? ResolveTypeSignature(TypeSignature? signature)
		{
			//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_001b: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			ITypeDefOrRef typeDefOrRef = signature?.GetUnderlyingTypeDefOrRef();
			if (typeDefOrRef == null)
			{
				return null;
			}
			MetadataToken metadataToken = typeDefOrRef.MetadataToken;
			TableIndex table = ((MetadataToken)(ref metadataToken)).Table;
			if ((int)table != 1)
			{
				if ((int)table != 2)
				{
					if ((int)table == 27)
					{
						return ResolveTypeSignature(((TypeSpecification)typeDefOrRef).Signature);
					}
					return null;
				}
				return (TypeDefinition)typeDefOrRef;
			}
			return ResolveTypeReference((TypeReference)typeDefOrRef);
		}

		public MethodDefinition? ResolveMethod(IMethodDescriptor? method)
		{
			if (method == null)
			{
				return null;
			}
			TypeDefinition typeDefinition = ResolveType(method.DeclaringType);
			if (typeDefinition == null)
			{
				return null;
			}
			for (int i = 0; i < typeDefinition.Methods.Count; i++)
			{
				MethodDefinition methodDefinition = typeDefinition.Methods[i];
				if (methodDefinition.Name == method.Name && _comparer.Equals(method.Signature, methodDefinition.Signature))
				{
					return methodDefinition;
				}
			}
			return null;
		}

		public FieldDefinition? ResolveField(IFieldDescriptor? field)
		{
			if (field == null)
			{
				return null;
			}
			TypeDefinition typeDefinition = ResolveType(field.DeclaringType);
			if (typeDefinition == null)
			{
				return null;
			}
			if (!(field is MemberReference memberReference))
			{
				_ = field.Name;
			}
			else
			{
				_ = memberReference.Name;
			}
			for (int i = 0; i < typeDefinition.Fields.Count; i++)
			{
				FieldDefinition fieldDefinition = typeDefinition.Fields[i];
				if (fieldDefinition.Name == field.Name && _comparer.Equals(field.Signature, fieldDefinition.Signature))
				{
					return fieldDefinition;
				}
			}
			return null;
		}
	}
	public class DotNetCoreAssemblyResolver : AssemblyResolverBase
	{
		private sealed class RuntimeNameComparer : IComparer<string>
		{
			public static readonly RuntimeNameComparer Instance = new RuntimeNameComparer();

			public int Compare(string? x, string? y)
			{
				if (x == y)
				{
					return 0;
				}
				if (x == null)
				{
					return -1;
				}
				if (y == null)
				{
					return 1;
				}
				if (x == "Microsoft.NETCore.App")
				{
					return 1;
				}
				if (y == "Microsoft.NETCore.App")
				{
					return -1;
				}
				return 0;
			}
		}

		private readonly List<string> _runtimeDirectories = new List<string>();

		public DotNetCoreAssemblyResolver(Version runtimeVersion)
			: this((IFileService)(object)UncachedFileService.Instance, null, runtimeVersion, DotNetCorePathProvider.Default)
		{
		}

		public DotNetCoreAssemblyResolver(IFileService fileService, Version runtimeVersion)
			: this(fileService, null, runtimeVersion, DotNetCorePathProvider.Default)
		{
		}

		public DotNetCoreAssemblyResolver(RuntimeConfiguration? configuration, Version fallbackVersion)
			: this((IFileService)(object)UncachedFileService.Instance, configuration, fallbackVersion, DotNetCorePathProvider.Default)
		{
		}

		public DotNetCoreAssemblyResolver(IFileService fileService, RuntimeConfiguration? configuration, Version fallbackVersion)
			: this(fileService, configuration, fallbackVersion, DotNetCorePathProvider.Default)
		{
		}

		public DotNetCoreAssemblyResolver(IFileService fileService, RuntimeConfiguration? configuration, DotNetCorePathProvider pathProvider)
			: this(fileService, configuration, null, pathProvider)
		{
		}

		public DotNetCoreAssemblyResolver(IFileService fileService, RuntimeConfiguration? configuration, Version? fallbackVersion, DotNetCorePathProvider pathProvider)
			: base(fileService)
		{
			if ((object)fallbackVersion == null)
			{
				throw new ArgumentNullException("fallbackVersion");
			}
			if (pathProvider == null)
			{
				throw new ArgumentNullException("pathProvider");
			}
			bool flag = false;
			RuntimeOptions runtimeOptions = configuration?.RuntimeOptions;
			if (runtimeOptions != null)
			{
				foreach (RuntimeFramework item in runtimeOptions.GetAllFrameworks().OrderBy<RuntimeFramework, string>((RuntimeFramework framework) => framework.Name, RuntimeNameComparer.Instance))
				{
					string[] frameworkDirectories = GetFrameworkDirectories(pathProvider, item);
					if (frameworkDirectories.Length != 0)
					{
						flag |= item.Name == "Microsoft.NETCore.App";
						_runtimeDirectories.AddRange(frameworkDirectories);
					}
				}
			}
			if (pathProvider.HasRuntimeInstalled(fallbackVersion))
			{
				if (_runtimeDirectories.Count == 0)
				{
					_runtimeDirectories.AddRange(pathProvider.GetRuntimePathCandidates(fallbackVersion));
				}
				else if (!flag)
				{
					_runtimeDirectories.AddRange(pathProvider.GetRuntimePathCandidates("Microsoft.NETCore.App", fallbackVersion));
				}
			}
		}

		private static string[] GetFrameworkDirectories(DotNetCorePathProvider pathProvider, RuntimeFramework framework)
		{
			if (TryParseVersion(framework.Version, out Version version) && pathProvider.HasRuntimeInstalled(framework.Name, version))
			{
				return pathProvider.GetRuntimePathCandidates(framework.Name, version).ToArray();
			}
			return Array.Empty<string>();
		}

		protected override string? ProbeRuntimeDirectories(AssemblyDescriptor assembly)
		{
			foreach (string runtimeDirectory in _runtimeDirectories)
			{
				string text = AssemblyResolverBase.ProbeDirectory(assembly, runtimeDirectory);
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			return null;
		}

		private static bool TryParseVersion(string? versionString, [NotNullWhen(true)] out Version? version)
		{
			if (string.IsNullOrEmpty(versionString))
			{
				version = null;
				return false;
			}
			int num = versionString.IndexOf('-');
			if (num >= 0)
			{
				versionString = versionString.Remove(num);
			}
			return Version.TryParse(versionString, out version);
		}
	}
	public class DotNetCorePathProvider
	{
		private readonly struct DotNetInstallationInfo : IComparable<DotNetInstallationInfo>
		{
			public string Name { get; }

			public string FullPath { get; }

			public IReadOnlyList<DotNetRuntimeVersionInfo> InstalledVersions { get; }

			public DotNetInstallationInfo(string path)
			{
				string fileName = Path.GetFileName(path);
				List<DotNetRuntimeVersionInfo> list = DetectInstalledVersionsInDirectory(fileName, path);
				Name = fileName;
				FullPath = path;
				InstalledVersions = list.AsReadOnly();
			}

			public bool TryFindBestMatchingVersion(Version requestedVersion, out DotNetRuntimeVersionInfo versionInfo)
			{
				versionInfo = default(DotNetRuntimeVersionInfo);
				Version version = new Version();
				bool result = false;
				for (int i = 0; i < InstalledVersions.Count; i++)
				{
					DotNetRuntimeVersionInfo dotNetRuntimeVersionInfo = InstalledVersions[i];
					Version version2 = dotNetRuntimeVersionInfo.Version;
					if (version2 == requestedVersion)
					{
						versionInfo = dotNetRuntimeVersionInfo;
						return true;
					}
					if (version2.Major == requestedVersion.Major && version < requestedVersion)
					{
						versionInfo = dotNetRuntimeVersionInfo;
						version = version2;
						result = true;
					}
				}
				return result;
			}

			private static List<DotNetRuntimeVersionInfo> DetectInstalledVersionsInDirectory(string name, string path)
			{
				List<DotNetRuntimeVersionInfo> list = new List<DotNetRuntimeVersionInfo>();
				foreach (string item in Directory.EnumerateDirectories(path))
				{
					string text = Path.GetFileName(item);
					int num = text.IndexOf('-');
					if (num >= 0)
					{
						text = text.Remove(num);
					}
					if (Version.TryParse(text, out Version result))
					{
						list.Add(new DotNetRuntimeVersionInfo(name, result, item));
					}
				}
				return list;
			}

			public int CompareTo(DotNetInstallationInfo other)
			{
				if (Name == other.Name)
				{
					return 0;
				}
				if (Name == "Microsoft.NETCore.App")
				{
					return 1;
				}
				if (other.Name == "Microsoft.NETCore.App")
				{
					return -1;
				}
				return 0;
			}
		}

		private readonly struct DotNetRuntimeVersionInfo
		{
			public string RuntimeName { get; }

			public Version Version { get; }

			public string FullPath { get; }

			public DotNetRuntimeVersionInfo(string runtimeName, Version version, string fullPath)
			{
				RuntimeName = runtimeName;
				Version = version;
				FullPath = fullPath;
			}

			public bool IsCompatibleWithStandard(Version standardVersion)
			{
				if (standardVersion.Major == 2)
				{
					if (standardVersion.Minor == 0)
					{
						return Version.Major >= 2;
					}
					if (standardVersion.Minor == 1)
					{
						return Version.Major >= 3;
					}
				}
				return true;
			}
		}

		private static readonly string[] DefaultDotNetUnixPaths;

		private static readonly Regex NetCoreRuntimePattern;

		private readonly List<DotNetInstallationInfo> _installedRuntimes = new List<DotNetInstallationInfo>();

		public static DotNetCorePathProvider Default { get; }

		public static string? DefaultInstallationPath { get; }

		static DotNetCorePathProvider()
		{
			DefaultDotNetUnixPaths = new string[3] { "/usr/share/dotnet/", "/usr/local/share/dotnet/", "/opt/dotnet/" };
			NetCoreRuntimePattern = new Regex("\\.NET( Core)? \\d+\\.\\d+\\.\\d+");
			DefaultInstallationPath = FindDotNetPath();
			Default = new DotNetCorePathProvider();
		}

		public DotNetCorePathProvider()
			: this(DefaultInstallationPath)
		{
		}

		public DotNetCorePathProvider(string? installationDirectory)
		{
			if (!string.IsNullOrEmpty(installationDirectory) && Directory.Exists(installationDirectory))
			{
				DetectInstalledRuntimes(installationDirectory);
			}
		}

		public bool TryGetLatestStandardCompatibleVersion(Version standardVersion, [NotNullWhen(true)] out Version? coreVersion)
		{
			bool result = false;
			coreVersion = null;
			foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes)
			{
				for (int i = 0; i < installedRuntime.InstalledVersions.Count; i++)
				{
					DotNetRuntimeVersionInfo dotNetRuntimeVersionInfo = installedRuntime.InstalledVersions[i];
					if (dotNetRuntimeVersionInfo.IsCompatibleWithStandard(standardVersion) && ((object)coreVersion == null || dotNetRuntimeVersionInfo.Version > coreVersion))
					{
						result = true;
						coreVersion = dotNetRuntimeVersionInfo.Version;
					}
				}
			}
			return result;
		}

		public IEnumerable<string> GetRuntimePathCandidates(Version requestedRuntimeVersion)
		{
			foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes)
			{
				if (installedRuntime.TryFindBestMatchingVersion(requestedRuntimeVersion, out var versionInfo))
				{
					yield return versionInfo.FullPath;
				}
			}
		}

		public IEnumerable<string> GetRuntimePathCandidates(string runtimeName, Version runtimeVersion)
		{
			foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes)
			{
				if (installedRuntime.Name == runtimeName && installedRuntime.TryFindBestMatchingVersion(runtimeVersion, out var versionInfo))
				{
					yield return versionInfo.FullPath;
				}
			}
		}

		public bool HasRuntimeInstalled(Version runtimeVersion)
		{
			foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes)
			{
				if (installedRuntime.TryFindBestMatchingVersion(runtimeVersion, out var _))
				{
					return true;
				}
			}
			return false;
		}

		public bool HasRuntimeInstalled(string runtimeName, Version runtimeVersion)
		{
			foreach (DotNetInstallationInfo installedRuntime in _installedRuntimes)
			{
				if (installedRuntime.Name == runtimeName && installedRuntime.TryFindBestMatchingVersion(runtimeVersion, out var _))
				{
					return true;
				}
			}
			return false;
		}

		private void DetectInstalledRuntimes(string installationDirectory)
		{
			installationDirectory = Path.Combine(installationDirectory, "shared");
			if (!Directory.Exists(installationDirectory))
			{
				return;
			}
			foreach (string item in Directory.EnumerateDirectories(installationDirectory))
			{
				_installedRuntimes.Add(new DotNetInstallationInfo(item));
			}
			_installedRuntimes.Sort();
		}

		private static string? FindDotNetPath()
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				string[] array = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(new char[1] { Path.PathSeparator });
				foreach (string text in array)
				{
					if (File.Exists(Path.Combine(text, "dotnet.exe")))
					{
						return text;
					}
				}
			}
			else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
			{
				string[] array = DefaultDotNetUnixPaths;
				foreach (string text2 in array)
				{
					if (File.Exists(Path.Combine(text2, "dotnet")))
					{
						return text2;
					}
				}
			}
			if (NetCoreRuntimePattern.Match(RuntimeInformation.FrameworkDescription).Success)
			{
				return Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Assembly.Location))));
			}
			return null;
		}
	}
	public class DotNetFrameworkAssemblyResolver : AssemblyResolverBase
	{
		public IList<GacDirectory> Gac32Directories { get; } = new List<GacDirectory>();


		public IList<GacDirectory> Gac64Directories { get; } = new List<GacDirectory>();


		public IList<GacDirectory> GacMsilDirectories { get; } = new List<GacDirectory>();


		public DotNetFrameworkAssemblyResolver()
			: this((IFileService)(object)UncachedFileService.Instance)
		{
		}

		public DotNetFrameworkAssemblyResolver(IFileService fileService)
			: base(fileService)
		{
			DetectGacDirectories();
		}

		private void DetectGacDirectories()
		{
			if (Environment.OSVersion.Platform == PlatformID.Win32NT)
			{
				DetectWindowsGacDirectories();
			}
			else if (Directory.Exists("/usr/lib/mono"))
			{
				DetectMonoGacDirectories();
			}
		}

		private void DetectWindowsGacDirectories()
		{
			string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
			string windowsGac = Path.Combine(folderPath, "assembly");
			AddGacDirectories(windowsGac, null);
			string windowsGac2 = Path.Combine(folderPath, "Microsoft.NET", "assembly");
			AddGacDirectories(windowsGac2, "v4.0_");
		}

		private void DetectMonoGacDirectories()
		{
			if (Directory.Exists("/usr/lib/mono/gac"))
			{
				GacMsilDirectories.Add(new GacDirectory("/usr/lib/mono/gac"));
			}
			string text = (from d in Directory.EnumerateDirectories("/usr/lib/mono")
				where d.EndsWith("-api")
				select d into x
				orderby x descending
				select x).FirstOrDefault();
			if (text != null)
			{
				base.SearchDirectories.Add(text);
			}
		}

		private void AddGacDirectories(string windowsGac, string? prefix)
		{
			if (!Directory.Exists(windowsGac))
			{
				return;
			}
			foreach (string item in Directory.EnumerateDirectories(windowsGac))
			{
				GetGacDirectoryCollection(item).Add(new GacDirectory(item, prefix));
			}
			IList<GacDirectory> GetGacDirectoryCollection(string directory)
			{
				string fileName = Path.GetFileName(directory);
				if (fileName == "GAC_32")
				{
					return Gac32Directories;
				}
				if (fileName == "GAC_64")
				{
					return Gac64Directories;
				}
				return GacMsilDirectories;
			}
		}

		protected override string? ProbeRuntimeDirectories(AssemblyDescriptor assembly)
		{
			AssemblyDescriptor assembly2 = assembly;
			bool flag;
			bool flag2;
			if (assembly2 is IModuleProvider moduleProvider)
			{
				ModuleDefinition module = moduleProvider.Module;
				if (module != null)
				{
					flag = module.IsBit32Preferred;
					flag2 = module.IsBit32Required;
					goto IL_0038;
				}
			}
			flag = false;
			flag2 = false;
			goto IL_0038;
			IL_0038:
			string text;
			if (flag2)
			{
				text = ProbeGacDirectories(Gac32Directories);
			}
			else if (flag)
			{
				text = ProbeGacDirectories(Gac32Directories);
				if (text == null)
				{
					text = ProbeGacDirectories(Gac64Directories);
				}
			}
			else
			{
				text = ProbeGacDirectories(Gac64Directories);
				if (text == null)
				{
					text = ProbeGacDirectories(Gac32Directories);
				}
			}
			return text ?? ProbeGacDirectories(GacMsilDirectories);
			string? ProbeGacDirectories(IList<GacDirectory> directories)
			{
				for (int i = 0; i < directories.Count; i++)
				{
					string text2 = directories[i].Probe(assembly2);
					if (text2 != null)
					{
						return text2;
					}
				}
				return null;
			}
		}
	}
	public readonly struct DotNetRuntimeInfo
	{
		public const string NetCoreApp = ".NETCoreApp";

		public const string NetStandard = ".NETStandard";

		public const string NetFramework = ".NETFramework";

		private static readonly Regex FormatRegex = new Regex("([a-zA-Z.]+)\\s*,\\s*Version=v(\\d+\\.\\d+)");

		public string Name { get; }

		public Version Version { get; }

		public bool IsNetCoreApp => Name == ".NETCoreApp";

		public bool IsNetFramework => Name == ".NETFramework";

		public bool IsNetStandard => Name == ".NETStandard";

		public DotNetRuntimeInfo(string name, Version version)
		{
			Name = name ?? throw new ArgumentNullException("name");
			Version = version ?? throw new ArgumentNullException("version");
		}

		public static DotNetRuntimeInfo Parse(string frameworkName)
		{
			if (!TryParse(frameworkName, out var info))
			{
				throw new FormatException();
			}
			return info;
		}

		public static bool TryParse(string frameworkName, out DotNetRuntimeInfo info)
		{
			Match match = FormatRegex.Match(frameworkName);
			if (!match.Success)
			{
				info = default(DotNetRuntimeInfo);
				return false;
			}
			string value = match.Groups[1].Value;
			Version version = new Version(match.Groups[2].Value);
			info = new DotNetRuntimeInfo(value, version);
			return true;
		}

		public AssemblyReference GetDefaultCorLib()
		{
			return KnownCorLibs.FromRuntimeInfo(this);
		}

		public override string ToString()
		{
			return $"{Name},Version=v{Version}";
		}
	}
	public class EventDefinition : MetadataMember, IHasSemantics, IMetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IHasCustomAttribute, IOwnedCollectionElement<TypeDefinition>
	{
		private readonly LazyVariable<EventDefinition, Utf8String?> _name;

		private readonly LazyVariable<EventDefinition, TypeDefinition?> _declaringType;

		private readonly LazyVariable<EventDefinition, ITypeDefOrRef?> _eventType;

		private IList<MethodSemantics>? _semantics;

		private IList<CustomAttribute>? _customAttributes;

		public EventAttributes Attributes { get; set; }

		public bool IsSpecialName
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x200) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (EventAttributes)((Attributes & 0xFDFF) | (value ? 512 : 0));
			}
		}

		public bool IsRuntimeSpecialName
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x400) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (EventAttributes)((Attributes & 0xFBFF) | (value ? 1024 : 0));
			}
		}

		public Utf8String? Name
		{
			get
			{
				return _name.GetValue(this);
			}
			set
			{
				_name.SetValue(value);
			}
		}

		string? INameProvider.Name => Utf8String.op_Implicit(Name);

		public string FullName => MemberNameGenerator.GetEventFullName(this);

		public ITypeDefOrRef? EventType
		{
			get
			{
				return _eventType.GetValue(this);
			}
			set
			{
				_eventType.SetValue(value);
			}
		}

		public ModuleDefinition? Module => DeclaringType?.Module;

		public TypeDefinition? DeclaringType
		{
			get
			{
				return _declaringType.GetValue(this);
			}
			private set
			{
				_declaringType.SetValue(value);
			}
		}

		ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;

		TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
		{
			get
			{
				return DeclaringType;
			}
			set
			{
				DeclaringType = value;
			}
		}

		public IList<MethodSemantics> Semantics
		{
			get
			{
				if (_semantics == null)
				{
					Interlocked.CompareExchange(ref _semantics, GetSemantics(), null);
				}
				return _semantics;
			}
		}

		public MethodDefinition? AddMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 8)?.Method;

		public MethodDefinition? RemoveMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 16)?.Method;

		public MethodDefinition? FireMethod => Semantics.FirstOrDefault((MethodSemantics s) => (int)s.Attributes == 32)?.Method;

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		protected EventDefinition(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_name = new LazyVariable<EventDefinition, Utf8String>((Func<EventDefinition, Utf8String>)((EventDefinition x) => x.GetName()));
			_eventType = new LazyVariable<EventDefinition, ITypeDefOrRef>((Func<EventDefinition, ITypeDefOrRef>)((EventDefinition x) => x.GetEventType()));
			_declaringType = new LazyVariable<EventDefinition, TypeDefinition>((Func<EventDefinition, TypeDefinition>)((EventDefinition x) => x.GetDeclaringType()));
		}

		public EventDefinition(Utf8String? name, EventAttributes attributes, ITypeDefOrRef? eventType)
			: this(new MetadataToken((TableIndex)20, 0u))
		{
			//IL_0004: 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)
			Name = name;
			Attributes = attributes;
			EventType = eventType;
		}

		public void SetSemanticMethods(MethodDefinition? addMethod, MethodDefinition? removeMethod, MethodDefinition? fireMethod)
		{
			Semantics.Clear();
			if (addMethod != null)
			{
				Semantics.Add(new MethodSemantics(addMethod, (MethodSemanticsAttributes)8));
			}
			if (removeMethod != null)
			{
				Semantics.Add(new MethodSemantics(removeMethod, (MethodSemanticsAttributes)16));
			}
			if (fireMethod != null)
			{
				Semantics.Add(new MethodSemantics(fireMethod, (MethodSemanticsAttributes)32));
			}
		}

		public bool IsAccessibleFromType(TypeDefinition type)
		{
			TypeDefinition type2 = type;
			return Semantics.Any((MethodSemantics s) => s.Method?.IsAccessibleFromType(type2) ?? false);
		}

		IMemberDefinition IMemberDescriptor.Resolve()
		{
			return this;
		}

		public bool IsImportedInModule(ModuleDefinition module)
		{
			if (Module == module)
			{
				return EventType?.IsImportedInModule(module) ?? false;
			}
			return false;
		}

		IImportable IImportable.ImportWith(ReferenceImporter importer)
		{
			throw new NotSupportedException();
		}

		protected virtual IList<CustomAttribute> GetCustomAttributes()
		{
			return (IList<CustomAttribute>)new OwnedCollection<IHasCustomAttribute, CustomAttribute>((IHasCustomAttribute)this);
		}

		protected virtual Utf8String? GetName()
		{
			return null;
		}

		protected virtual ITypeDefOrRef? GetEventType()
		{
			return null;
		}

		protected virtual TypeDefinition? GetDeclaringType()
		{
			return null;
		}

		protected virtual IList<MethodSemantics> GetSemantics()
		{
			return (IList<MethodSemantics>)new MethodSemanticsCollection(this);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	public class ExportedType : MetadataMember, IImplementation, IFullNameProvider, INameProvider, IModuleProvider, IHasCustomAttribute, IMetadataMember, IImportable, ITypeDescriptor, IMemberDescriptor, IOwnedCollectionElement<ModuleDefinition>
	{
		private readonly LazyVariable<ExportedType, Utf8String?> _name;

		private readonly LazyVariable<ExportedType, Utf8String?> _namespace;

		private readonly LazyVariable<ExportedType, IImplementation?> _implementation;

		private IList<CustomAttribute>? _customAttributes;

		public TypeAttributes Attributes { get; set; }

		public uint TypeDefId { get; set; }

		public Utf8String? Name
		{
			get
			{
				return _name.GetValue(this);
			}
			set
			{
				_name.SetValue(value);
			}
		}

		string? INameProvider.Name => Utf8String.op_Implicit(Name);

		public Utf8String? Namespace
		{
			get
			{
				return _namespace.GetValue(this);
			}
			set
			{
				_namespace.SetValue(value);
			}
		}

		string? ITypeDescriptor.Namespace => Utf8String.op_Implicit(Namespace);

		public string FullName => MemberNameGenerator.GetTypeFullName(this);

		public ModuleDefinition? Module { get; private set; }

		ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
		{
			get
			{
				return Module;
			}
			set
			{
				Module = value;
			}
		}

		public IImplementation? Implementation
		{
			get
			{
				return _implementation.GetValue(this);
			}
			set
			{
				_implementation.SetValue(value);
			}
		}

		public ExportedType? DeclaringType => Implementation as ExportedType;

		ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;

		public IResolutionScope? Scope => Module;

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		public bool IsValueType => Resolve()?.IsValueType ?? false;

		protected ExportedType(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_name = new LazyVariable<ExportedType, Utf8String>((Func<ExportedType, Utf8String>)((ExportedType x) => x.GetName()));
			_namespace = new LazyVariable<ExportedType, Utf8String>((Func<ExportedType, Utf8String>)((ExportedType x) => x.GetNamespace()));
			_implementation = new LazyVariable<ExportedType, IImplementation>((Func<ExportedType, IImplementation>)((ExportedType x) => x.GetImplementation()));
		}

		public ExportedType(IImplementation? implementation, string? ns, string? name)
			: this(new MetadataToken((TableIndex)39, 1u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			Implementation = implementation;
			Namespace = Utf8String.op_Implicit(ns);
			Name = Utf8String.op_Implicit(name);
		}

		public TypeDefinition? Resolve()
		{
			return Module?.MetadataResolver.ResolveType(this);
		}

		public bool IsImportedInModule(ModuleDefinition module)
		{
			if (Module == module)
			{
				return Implementation?.IsImportedInModule(module) ?? false;
			}
			return false;
		}

		public ExportedType ImportWith(ReferenceImporter importer)
		{
			return importer.ImportType(this);
		}

		IImportable IImportable.ImportWith(ReferenceImporter importer)
		{
			return ImportWith(importer);
		}

		IMemberDefinition? IMemberDescriptor.Resolve()
		{
			return Resolve();
		}

		public ITypeDefOrRef ToTypeDefOrRef()
		{
			return new TypeReference(Module, Scope, Namespace, Name);
		}

		public TypeSignature ToTypeSignature()
		{
			return new TypeDefOrRefSignature(ToTypeDefOrRef());
		}

		protected virtual Utf8String? GetNamespace()
		{
			return null;
		}

		protected virtual Utf8String? GetName()
		{
			return null;
		}

		protected virtual IImplementation? GetImplementation()
		{
			return null;
		}

		protected virtual IList<CustomAttribute> GetCustomAttributes()
		{
			return (IList<CustomAttribute>)new OwnedCollection<IHasCustomAttribute, CustomAttribute>((IHasCustomAttribute)this);
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	public class FieldDefinition : MetadataMember, IMemberDefinition, IMemberDescriptor, IFullNameProvider, INameProvider, IModuleProvider, IImportable, IMetadataMember, IFieldDescriptor, IHasCustomAttribute, IHasConstant, IMemberForwarded, IHasFieldMarshal, IOwnedCollectionElement<TypeDefinition>
	{
		private readonly LazyVariable<FieldDefinition, Utf8String?> _name;

		private readonly LazyVariable<FieldDefinition, FieldSignature?> _signature;

		private readonly LazyVariable<FieldDefinition, TypeDefinition?> _declaringType;

		private readonly LazyVariable<FieldDefinition, Constant?> _constant;

		private readonly LazyVariable<FieldDefinition, MarshalDescriptor?> _marshalDescriptor;

		private readonly LazyVariable<FieldDefinition, ImplementationMap?> _implementationMap;

		private readonly LazyVariable<FieldDefinition, ISegment?> _fieldRva;

		private readonly LazyVariable<FieldDefinition, int?> _fieldOffset;

		private IList<CustomAttribute>? _customAttributes;

		public Utf8String? Name
		{
			get
			{
				return _name.GetValue(this);
			}
			set
			{
				_name.SetValue(value);
			}
		}

		string? INameProvider.Name => Utf8String.op_Implicit(Name);

		public FieldSignature? Signature
		{
			get
			{
				return _signature.GetValue(this);
			}
			set
			{
				_signature.SetValue(value);
			}
		}

		public string FullName => MemberNameGenerator.GetFieldFullName(this);

		public FieldAttributes Attributes { get; set; }

		public bool IsPrivateScope
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 0;
			}
			set
			{
				//IL_000d: 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_0005: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)(value ? (Attributes & 0xFFF8) : Attributes);
			}
		}

		public bool IsPrivate
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 1;
			}
			set
			{
				//IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 1 : 0));
			}
		}

		public bool IsFamilyAndAssembly
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 2;
			}
			set
			{
				//IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 2 : 0));
			}
		}

		public bool IsAssembly
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 3;
			}
			set
			{
				//IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 3 : 0));
			}
		}

		public bool IsFamily
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 4;
			}
			set
			{
				//IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 4 : 0));
			}
		}

		public bool IsFamilyOrAssembly
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 5;
			}
			set
			{
				//IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 5 : 0));
			}
		}

		public bool IsPublic
		{
			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_0009: Invalid comparison between Unknown and I4
				return (Attributes & 7) == 6;
			}
			set
			{
				//IL_0002: 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_0014: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFF8) | (value ? 6 : 0));
			}
		}

		public bool IsStatic
		{
			get
			{
				//IL_0001: 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
				return (Attributes & 0x10) > 0;
			}
			set
			{
				//IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFEF) | (value ? 16 : 0));
			}
		}

		public bool IsInitOnly
		{
			get
			{
				//IL_0001: 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
				return (Attributes & 0x20) > 0;
			}
			set
			{
				//IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFDF) | (value ? 32 : 0));
			}
		}

		public bool IsLiteral
		{
			get
			{
				//IL_0001: 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
				return (Attributes & 0x40) > 0;
			}
			set
			{
				//IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFFBF) | (value ? 64 : 0));
			}
		}

		public bool IsNotSerialized
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x80) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFF7F) | (value ? 128 : 0));
			}
		}

		public bool IsSpecialName
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x200) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFDFF) | (value ? 512 : 0));
			}
		}

		public bool IsPInvokeImpl
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x2000) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xDFFF) | (value ? 8192 : 0));
			}
		}

		public bool IsRuntimeSpecialName
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x400) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFBFF) | (value ? 1024 : 0));
			}
		}

		public bool HasFieldMarshal
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x1000) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xEFFF) | (value ? 4096 : 0));
			}
		}

		public bool HasDefault
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x8000) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0x7FFF) | (value ? 32768 : 0));
			}
		}

		public bool HasFieldRva
		{
			get
			{
				//IL_0001: 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_000d: Invalid comparison between Unknown and I4
				return (Attributes & 0x100) > 0;
			}
			set
			{
				//IL_0002: 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_0018: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FieldAttributes)((Attributes & 0xFEFF) | (value ? 256 : 0));
			}
		}

		public ModuleDefinition? Module => DeclaringType?.Module;

		public TypeDefinition? DeclaringType
		{
			get
			{
				return _declaringType.GetValue(this);
			}
			private set
			{
				_declaringType.SetValue(value);
			}
		}

		TypeDefinition? IOwnedCollectionElement<TypeDefinition>.Owner
		{
			get
			{
				return DeclaringType;
			}
			set
			{
				DeclaringType = value;
			}
		}

		ITypeDescriptor? IMemberDescriptor.DeclaringType => DeclaringType;

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		public Constant? Constant
		{
			get
			{
				return _constant.GetValue(this);
			}
			set
			{
				_constant.SetValue(value);
			}
		}

		public MarshalDescriptor? MarshalDescriptor
		{
			get
			{
				return _marshalDescriptor.GetValue(this);
			}
			set
			{
				_marshalDescriptor.SetValue(value);
			}
		}

		public ImplementationMap? ImplementationMap
		{
			get
			{
				return _implementationMap.GetValue(this);
			}
			set
			{
				if (value?.MemberForwarded != null)
				{
					throw new ArgumentException("Cannot add an implementation map that was already added to another member.");
				}
				ImplementationMap value2 = _implementationMap.GetValue(this);
				if (value2 != null)
				{
					value2.MemberForwarded = null;
				}
				_implementationMap.SetValue(value);
				if (value != null)
				{
					value.MemberForwarded = this;
				}
			}
		}

		public ISegment? FieldRva
		{
			get
			{
				return _fieldRva.GetValue(this);
			}
			set
			{
				_fieldRva.SetValue(value);
			}
		}

		public int? FieldOffset
		{
			get
			{
				return _fieldOffset.GetValue(this);
			}
			set
			{
				_fieldOffset.SetValue(value);
			}
		}

		protected FieldDefinition(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_name = new LazyVariable<FieldDefinition, Utf8String>((Func<FieldDefinition, Utf8String>)((FieldDefinition x) => x.GetName()));
			_signature = new LazyVariable<FieldDefinition, FieldSignature>((Func<FieldDefinition, FieldSignature>)((FieldDefinition x) => x.GetSignature()));
			_declaringType = new LazyVariable<FieldDefinition, TypeDefinition>((Func<FieldDefinition, TypeDefinition>)((FieldDefinition x) => x.GetDeclaringType()));
			_constant = new LazyVariable<FieldDefinition, Constant>((Func<FieldDefinition, Constant>)((FieldDefinition x) => x.GetConstant()));
			_marshalDescriptor = new LazyVariable<FieldDefinition, MarshalDescriptor>((Func<FieldDefinition, MarshalDescriptor>)((FieldDefinition x) => x.GetMarshalDescriptor()));
			_implementationMap = new LazyVariable<FieldDefinition, ImplementationMap>((Func<FieldDefinition, ImplementationMap>)((FieldDefinition x) => x.GetImplementationMap()));
			_fieldRva = new LazyVariable<FieldDefinition, ISegment>((Func<FieldDefinition, ISegment>)((FieldDefinition x) => x.GetFieldRva()));
			_fieldOffset = new LazyVariable<FieldDefinition, int?>((Func<FieldDefinition, int?>)((FieldDefinition x) => x.GetFieldOffset()));
		}

		public FieldDefinition(Utf8String? name, FieldAttributes attributes, FieldSignature? signature)
			: this(new MetadataToken((TableIndex)4, 0u))
		{
			//IL_0003: 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)
			Name = name;
			Attributes = attributes;
			Signature = signature;
		}

		public FieldDefinition(Utf8String name, FieldAttributes attributes, TypeSignature? fieldType)
			: this(new MetadataToken((TableIndex)4, 0u))
		{
			//IL_0003: 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)
			Name = name;
			Attributes = attributes;
			Signature = ((fieldType != null) ? new FieldSignature(fieldType) : null);
		}

		FieldDefinition IFieldDescriptor.Resolve()
		{
			return this;
		}

		public bool IsImportedInModule(ModuleDefinition module)
		{
			if (Module == module)
			{
				return Signature?.IsImportedInModule(module) ?? false;
			}
			return false;
		}

		public IFieldDescriptor ImportWith(ReferenceImporter importer)
		{
			return importer.ImportField(this);
		}

		IImportable IImportable.ImportWith(ReferenceImporter importer)
		{
			return ImportWith(importer);
		}

		IMemberDefinition IMemberDescriptor.Resolve()
		{
			return this;
		}

		public bool IsAccessibleFromType(TypeDefinition type)
		{
			TypeDefinition declaringType = DeclaringType;
			if (declaringType == null || !declaringType.IsAccessibleFromType(type))
			{
				return false;
			}
			SignatureComparer signatureComparer = new SignatureComparer();
			bool flag = signatureComparer.Equals(declaringType.Module, type.Module);
			if (!IsPublic && (!flag || !IsAssembly))
			{
				return signatureComparer.Equals(DeclaringType, type);
			}
			return true;
		}

		protected virtual IList<CustomAttribute> GetCustomAttributes()
		{
			return (IList<CustomAttribute>)new OwnedCollection<IHasCustomAttribute, CustomAttribute>((IHasCustomAttribute)this);
		}

		protected virtual Utf8String? GetName()
		{
			return null;
		}

		protected virtual FieldSignature? GetSignature()
		{
			return null;
		}

		protected virtual TypeDefinition? GetDeclaringType()
		{
			return null;
		}

		protected virtual Constant? GetConstant()
		{
			return null;
		}

		protected virtual MarshalDescriptor? GetMarshalDescriptor()
		{
			return null;
		}

		protected virtual ImplementationMap? GetImplementationMap()
		{
			return null;
		}

		protected virtual ISegment? GetFieldRva()
		{
			return null;
		}

		protected virtual int? GetFieldOffset()
		{
			return null;
		}

		public override string ToString()
		{
			return FullName;
		}
	}
	public class FileReference : MetadataMember, IImplementation, IFullNameProvider, INameProvider, IModuleProvider, IHasCustomAttribute, IMetadataMember, IImportable, IManagedEntryPoint, IOwnedCollectionElement<ModuleDefinition>
	{
		private readonly LazyVariable<FileReference, Utf8String?> _name;

		private readonly LazyVariable<FileReference, byte[]?> _hashValue;

		private IList<CustomAttribute>? _customAttributes;

		public FileAttributes Attributes { get; set; }

		public bool ContainsMetadata
		{
			get
			{
				return !ContainsNoMetadata;
			}
			set
			{
				ContainsNoMetadata = !value;
			}
		}

		public bool ContainsNoMetadata
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				return (int)Attributes == 1;
			}
			set
			{
				//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_0011: Unknown result type (might be due to invalid IL or missing references)
				Attributes = (FileAttributes)((Attributes & -2) | (value ? 1 : 0));
			}
		}

		public Utf8String? Name
		{
			get
			{
				return _name.GetValue(this);
			}
			set
			{
				_name.SetValue(value);
			}
		}

		string? INameProvider.Name => Utf8String.op_Implicit(Name);

		public string FullName => Utf8String.op_Implicit(Name ?? MetadataMember.NullName);

		public ModuleDefinition? Module { get; private set; }

		ModuleDefinition? IOwnedCollectionElement<ModuleDefinition>.Owner
		{
			get
			{
				return Module;
			}
			set
			{
				Module = value;
			}
		}

		public byte[]? HashValue
		{
			get
			{
				return _hashValue.GetValue(this);
			}
			set
			{
				_hashValue.SetValue(value);
			}
		}

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		protected FileReference(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_name = new LazyVariable<FileReference, Utf8String>((Func<FileReference, Utf8String>)((FileReference x) => x.GetName()));
			_hashValue = new LazyVariable<FileReference, byte[]>((Func<FileReference, byte[]>)((FileReference x) => x.GetHashValue()));
		}

		public FileReference(Utf8String? name, FileAttributes attributes)
			: this(new MetadataToken((TableIndex)38, 0u))
		{
			//IL_0004: 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)
			Name = name;
			Attributes = attributes;
		}

		public bool IsImportedInModule(ModuleDefinition module)
		{
			return Module == module;
		}

		public FileReference ImportWith(ReferenceImporter importer)
		{
			return (FileReference)importer.ImportImplementation(this);
		}

		IImportable IImportable.ImportWith(ReferenceImporter importer)
		{
			return ImportWith(importer);
		}

		protected virtual Utf8String? GetName()
		{
			return null;
		}

		protected virtual byte[]? GetHashValue()
		{
			return null;
		}

		protected virtual IList<CustomAttribute> GetCustomAttributes()
		{
			return (IList<CustomAttribute>)new OwnedCollection<IHasCustomAttribute, CustomAttribute>((IHasCustomAttribute)this);
		}
	}
	public readonly struct GacDirectory
	{
		private readonly string _basePath;

		private readonly string? _prefix;

		private bool IsPrefixed => !string.IsNullOrEmpty(_prefix);

		public GacDirectory(string basePath, string? prefix = null)
		{
			_basePath = basePath ?? throw new ArgumentNullException("basePath");
			_prefix = prefix;
		}

		public string? Probe(AssemblyDescriptor assembly)
		{
			if (string.IsNullOrEmpty(Utf8String.op_Implicit(assembly.Name)))
			{
				return null;
			}
			byte[] publicKeyToken = assembly.GetPublicKeyToken();
			if (publicKeyToken == null)
			{
				throw new ArgumentException("Only signed assemblies can be looked up in the GAC.");
			}
			string text = Path.Combine(_basePath, Utf8String.op_Implicit(assembly.Name));
			if (Directory.Exists(text))
			{
				string arg = string.Join(string.Empty, publicKeyToken.Select((byte x) => x.ToString("x2")));
				string text2 = $"{assembly.Version}__{arg}";
				if (IsPrefixed)
				{
					text2 = _prefix + text2;
				}
				string text3 = AssemblyResolverBase.ProbeFileFromFilePathWithoutExtension(Path.Combine(text, text2, Utf8String.op_Implicit(assembly.Name)));
				if (!string.IsNullOrEmpty(text3))
				{
					return text3;
				}
			}
			return null;
		}

		public override string ToString()
		{
			return _basePath;
		}
	}
	public class GenericParameter : MetadataMember, INameProvider, IHasCustomAttribute, IMetadataMember, IModuleProvider, IOwnedCollectionElement<IHasGenericParameters>
	{
		private readonly LazyVariable<GenericParameter, Utf8String?> _name;

		private readonly LazyVariable<GenericParameter, IHasGenericParameters?> _owner;

		private IList<GenericParameterConstraint>? _constraints;

		private IList<CustomAttribute>? _customAttributes;

		public IHasGenericParameters? Owner
		{
			get
			{
				return _owner.GetValue(this);
			}
			private set
			{
				_owner.SetValue(value);
			}
		}

		IHasGenericParameters? IOwnedCollectionElement<IHasGenericParameters>.Owner
		{
			get
			{
				return Owner;
			}
			set
			{
				Owner = value;
			}
		}

		public Utf8String? Name
		{
			get
			{
				return _name.GetValue(this);
			}
			set
			{
				_name.SetValue(value);
			}
		}

		string? INameProvider.Name => Utf8String.op_Implicit(Name);

		public GenericParameterAttributes Attributes { get; set; }

		public ushort Number
		{
			get
			{
				if (Owner != null)
				{
					return (ushort)Owner.GenericParameters.IndexOf(this);
				}
				return 0;
			}
		}

		public ModuleDefinition? Module => Owner?.Module;

		public IList<GenericParameterConstraint> Constraints
		{
			get
			{
				if (_constraints == null)
				{
					Interlocked.CompareExchange(ref _constraints, GetConstraints(), null);
				}
				return _constraints;
			}
		}

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		protected GenericParameter(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_name = new LazyVariable<GenericParameter, Utf8String>((Func<GenericParameter, Utf8String>)((GenericParameter x) => x.GetName()));
			_owner = new LazyVariable<GenericParameter, IHasGenericParameters>((Func<GenericParameter, IHasGenericParameters>)((GenericParameter x) => x.GetOwner()));
		}

		public GenericParameter(Utf8String? name)
			: this(new MetadataToken((TableIndex)42, 0u))
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			Name = name;
		}

		public GenericParameter(Utf8String? name, GenericParameterAttributes attributes)
			: this(new MetadataToken((TableIndex)42, 0u))
		{
			//IL_0004: 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)
			Name = name;
			Attributes = attributes;
		}

		protected virtual Utf8String? GetName()
		{
			return null;
		}

		protected virtual IHasGenericParameters? GetOwner()
		{
			return null;
		}

		protected virtual IList<GenericParameterConstraint> GetConstraints()
		{
			return (IList<GenericParameterConstraint>)new OwnedCollection<GenericParameter, GenericParameterConstraint>(this);
		}

		protected virtual IList<CustomAttribute> GetCustomAttributes()
		{
			return (IList<CustomAttribute>)new OwnedCollection<IHasCustomAttribute, CustomAttribute>((IHasCustomAttribute)this);
		}

		public override string ToString()
		{
			return Utf8String.op_Implicit(Name ?? MetadataMember.NullName);
		}
	}
	public class GenericParameterConstraint : MetadataMember, IHasCustomAttribute, IMetadataMember, IModuleProvider, IOwnedCollectionElement<GenericParameter>
	{
		private readonly LazyVariable<GenericParameterConstraint, GenericParameter?> _owner;

		private readonly LazyVariable<GenericParameterConstraint, ITypeDefOrRef?> _constraint;

		private IList<CustomAttribute>? _customAttributes;

		public GenericParameter? Owner
		{
			get
			{
				return _owner.GetValue(this);
			}
			private set
			{
				_owner.SetValue(value);
			}
		}

		GenericParameter? IOwnedCollectionElement<GenericParameter>.Owner
		{
			get
			{
				return Owner;
			}
			set
			{
				Owner = value;
			}
		}

		public ITypeDefOrRef? Constraint
		{
			get
			{
				return _constraint.GetValue(this);
			}
			set
			{
				_constraint.SetValue(value);
			}
		}

		public ModuleDefinition? Module => Owner?.Module;

		public IList<CustomAttribute> CustomAttributes
		{
			get
			{
				if (_customAttributes == null)
				{
					Interlocked.CompareExchange(ref _customAttributes, GetCustomAttributes(), null);
				}
				return _customAttributes;
			}
		}

		protected GenericParameterConstraint(MetadataToken token)
			: base(token)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			_owner = new LazyVariable<GenericParameterConstraint, GenericParameter>((Func<GenericParameterConstraint, GenericParameter>)((GenericParameterConstraint x) => x.GetOwner()));
			_constraint = new LazyVariable<GenericParameterConstraint, ITypeDefOrRef>((F

folder/AsmResolver.PE.dll

Decompiled 11 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using AsmResolver.Collections;
using AsmResolver.IO;
using AsmResolver.PE.Builder;
using AsmResolver.PE.Certificates;
using AsmResolver.PE.Code;
using AsmResolver.PE.Debug;
using AsmResolver.PE.Debug.Builder;
using AsmResolver.PE.Debug.CodeView;
using AsmResolver.PE.DotNet;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata;
using AsmResolver.PE.DotNet.Metadata.Blob;
using AsmResolver.PE.DotNet.Metadata.Guid;
using AsmResolver.PE.DotNet.Metadata.Pdb;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using AsmResolver.PE.DotNet.Metadata.UserStrings;
using AsmResolver.PE.DotNet.ReadyToRun;
using AsmResolver.PE.DotNet.Resources;
using AsmResolver.PE.DotNet.VTableFixups;
using AsmResolver.PE.Exceptions;
using AsmResolver.PE.Exceptions.X64;
using AsmResolver.PE.Exports;
using AsmResolver.PE.Exports.Builder;
using AsmResolver.PE.File;
using AsmResolver.PE.File.Headers;
using AsmResolver.PE.Imports;
using AsmResolver.PE.Imports.Builder;
using AsmResolver.PE.Platforms;
using AsmResolver.PE.Relocations;
using AsmResolver.PE.Relocations.Builder;
using AsmResolver.PE.Tls;
using AsmResolver.PE.Win32Resources;
using AsmResolver.PE.Win32Resources.Builder;
using AsmResolver.Patching;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("AsmResolver.PE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Washi 2016-2024")]
[assembly: AssemblyDescription("PE image models for the AsmResolver executable file inspection toolsuite.")]
[assembly: AssemblyFileVersion("5.5.1.0")]
[assembly: AssemblyInformationalVersion("5.5.1+78ce89adebcc7e5dbeb1d4a1a35afcd513fb87a1")]
[assembly: AssemblyProduct("AsmResolver.PE")]
[assembly: AssemblyTitle("AsmResolver.PE")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Washi1337/AsmResolver")]
[assembly: AssemblyVersion("5.5.1.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AsmResolver.PE
{
	public interface IPEImage
	{
		string? FilePath { get; }

		MachineType MachineType { get; set; }

		Characteristics Characteristics { get; set; }

		DateTime TimeDateStamp { get; set; }

		OptionalHeaderMagic PEKind { get; set; }

		SubSystem SubSystem { get; set; }

		DllCharacteristics DllCharacteristics { get; set; }

		ulong ImageBase { get; set; }

		IList<IImportedModule> Imports { get; }

		IExportDirectory? Exports { get; set; }

		IResourceDirectory? Resources { get; set; }

		IExceptionDirectory? Exceptions { get; set; }

		IList<BaseRelocation> Relocations { get; }

		IDotNetDirectory? DotNetDirectory { get; set; }

		IList<DebugDataEntry> DebugData { get; }

		ITlsDirectory? TlsDirectory { get; set; }

		CertificateCollection Certificates { get; }
	}
	public class PEImage : IPEImage
	{
		private IList<IImportedModule>? _imports;

		private readonly LazyVariable<PEImage, IExportDirectory?> _exports;

		private readonly LazyVariable<PEImage, IResourceDirectory?> _resources;

		private readonly LazyVariable<PEImage, IExceptionDirectory?> _exceptions;

		private IList<BaseRelocation>? _relocations;

		private readonly LazyVariable<PEImage, IDotNetDirectory?> _dotNetDirectory;

		private IList<DebugDataEntry>? _debugData;

		private readonly LazyVariable<PEImage, ITlsDirectory?> _tlsDirectory;

		private CertificateCollection? _certificates;

		public string? FilePath { get; protected set; }

		public MachineType MachineType { get; set; } = (MachineType)332;


		public Characteristics Characteristics { get; set; } = (Characteristics)34;


		public DateTime TimeDateStamp { get; set; } = new DateTime(1970, 1, 1);


		public OptionalHeaderMagic PEKind { get; set; } = (OptionalHeaderMagic)267;


		public SubSystem SubSystem { get; set; } = (SubSystem)3;


		public DllCharacteristics DllCharacteristics { get; set; } = (DllCharacteristics)34112;


		public ulong ImageBase { get; set; } = 4194304uL;


		public IList<IImportedModule> Imports
		{
			get
			{
				if (_imports == null)
				{
					Interlocked.CompareExchange(ref _imports, GetImports(), null);
				}
				return _imports;
			}
		}

		public IExportDirectory? Exports
		{
			get
			{
				return _exports.GetValue(this);
			}
			set
			{
				_exports.SetValue(value);
			}
		}

		public IResourceDirectory? Resources
		{
			get
			{
				return _resources.GetValue(this);
			}
			set
			{
				_resources.SetValue(value);
			}
		}

		public IExceptionDirectory? Exceptions
		{
			get
			{
				return _exceptions.GetValue(this);
			}
			set
			{
				_exceptions.SetValue(value);
			}
		}

		public IList<BaseRelocation> Relocations
		{
			get
			{
				if (_relocations == null)
				{
					Interlocked.CompareExchange(ref _relocations, GetRelocations(), null);
				}
				return _relocations;
			}
		}

		public IDotNetDirectory? DotNetDirectory
		{
			get
			{
				return _dotNetDirectory.GetValue(this);
			}
			set
			{
				_dotNetDirectory.SetValue(value);
			}
		}

		public IList<DebugDataEntry> DebugData
		{
			get
			{
				if (_debugData == null)
				{
					Interlocked.CompareExchange(ref _debugData, GetDebugData(), null);
				}
				return _debugData;
			}
		}

		public ITlsDirectory? TlsDirectory
		{
			get
			{
				return _tlsDirectory.GetValue(this);
			}
			set
			{
				_tlsDirectory.SetValue(value);
			}
		}

		public CertificateCollection Certificates
		{
			get
			{
				if (_certificates == null)
				{
					Interlocked.CompareExchange(ref _certificates, GetCertificates(), null);
				}
				return _certificates;
			}
		}

		public static IPEImage FromFile(string filePath)
		{
			return FromFile((IPEFile)(object)PEFile.FromFile(filePath));
		}

		public static IPEImage FromFile(string filePath, PEReaderParameters readerParameters)
		{
			return FromFile((IPEFile)(object)PEFile.FromFile(readerParameters.FileService.OpenFile(filePath)), readerParameters);
		}

		public static IPEImage FromBytes(byte[] bytes)
		{
			return FromFile((IPEFile)(object)PEFile.FromBytes(bytes));
		}

		public static IPEImage FromBytes(byte[] bytes, PEReaderParameters readerParameters)
		{
			return FromFile((IPEFile)(object)PEFile.FromBytes(bytes), readerParameters);
		}

		public static IPEImage FromModuleBaseAddress(IntPtr hInstance)
		{
			return FromModuleBaseAddress(hInstance, (PEMappingMode)1, new PEReaderParameters());
		}

		public static IPEImage FromModuleBaseAddress(IntPtr hInstance, PEReaderParameters readerParameters)
		{
			return FromFile((IPEFile)(object)PEFile.FromModuleBaseAddress(hInstance), readerParameters);
		}

		public static IPEImage FromModuleBaseAddress(IntPtr hInstance, PEMappingMode mode, PEReaderParameters readerParameters)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return FromFile((IPEFile)(object)PEFile.FromModuleBaseAddress(hInstance, mode), readerParameters);
		}

		public static IPEImage FromDataSource(IDataSource dataSource, PEMappingMode mode = 0)
		{
			//IL_000f: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			BinaryStreamReader reader = new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0u, (uint)dataSource.Length);
			return FromReader(in reader, mode);
		}

		public static IPEImage FromDataSource(IDataSource dataSource, PEMappingMode mode, PEReaderParameters readerParameters)
		{
			//IL_000f: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			BinaryStreamReader reader = new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0u, (uint)dataSource.Length);
			return FromReader(in reader, mode, readerParameters);
		}

		public static IPEImage FromReader(in BinaryStreamReader reader, PEMappingMode mode = 0)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return FromFile((IPEFile)(object)PEFile.FromReader(ref reader, mode));
		}

		public static IPEImage FromReader(in BinaryStreamReader reader, PEMappingMode mode, PEReaderParameters readerParameters)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return FromFile((IPEFile)(object)PEFile.FromReader(ref reader, mode), readerParameters);
		}

		public static IPEImage FromFile(IInputFile inputFile)
		{
			return FromFile((IPEFile)(object)PEFile.FromFile(inputFile), new PEReaderParameters());
		}

		public static IPEImage FromFile(IPEFile peFile)
		{
			return FromFile(peFile, new PEReaderParameters());
		}

		public static IPEImage FromFile(IPEFile peFile, PEReaderParameters readerParameters)
		{
			return new SerializedPEImage(peFile, readerParameters);
		}

		public PEImage()
		{
			//IL_0006: 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_002b: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			_exports = new LazyVariable<PEImage, IExportDirectory>((Func<PEImage, IExportDirectory>)((PEImage x) => x.GetExports()));
			_resources = new LazyVariable<PEImage, IResourceDirectory>((Func<PEImage, IResourceDirectory>)((PEImage x) => x.GetResources()));
			_exceptions = new LazyVariable<PEImage, IExceptionDirectory>((Func<PEImage, IExceptionDirectory>)((PEImage x) => x.GetExceptions()));
			_dotNetDirectory = new LazyVariable<PEImage, IDotNetDirectory>((Func<PEImage, IDotNetDirectory>)((PEImage x) => x.GetDotNetDirectory()));
			_tlsDirectory = new LazyVariable<PEImage, ITlsDirectory>((Func<PEImage, ITlsDirectory>)((PEImage x) => x.GetTlsDirectory()));
		}

		protected virtual IList<IImportedModule> GetImports()
		{
			return new List<IImportedModule>();
		}

		protected virtual IExportDirectory? GetExports()
		{
			return null;
		}

		protected virtual IResourceDirectory? GetResources()
		{
			return null;
		}

		protected virtual IExceptionDirectory? GetExceptions()
		{
			return null;
		}

		protected virtual IList<BaseRelocation> GetRelocations()
		{
			return new List<BaseRelocation>();
		}

		protected virtual IDotNetDirectory? GetDotNetDirectory()
		{
			return null;
		}

		protected virtual IList<DebugDataEntry> GetDebugData()
		{
			return new List<DebugDataEntry>();
		}

		protected virtual ITlsDirectory? GetTlsDirectory()
		{
			return null;
		}

		protected virtual CertificateCollection GetCertificates()
		{
			return new CertificateCollection();
		}
	}
	public class PEReaderContext : IErrorListener
	{
		public IPEFile File { get; }

		public PEReaderParameters Parameters { get; }

		public PEReaderContext(IPEFile file)
			: this(file, new PEReaderParameters())
		{
		}

		public PEReaderContext(IPEFile file, PEReaderParameters parameters)
		{
			File = file;
			Parameters = parameters;
		}

		public RelocationParameters GetRelocation(ulong offset, uint rva)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			return new RelocationParameters(File.OptionalHeader.ImageBase, offset, rva, (int)File.OptionalHeader.Magic == 267);
		}

		public void MarkAsFatal()
		{
			Parameters.ErrorListener.MarkAsFatal();
		}

		public void RegisterException(Exception exception)
		{
			Parameters.ErrorListener.RegisterException(exception);
		}
	}
	public class PEReaderParameters
	{
		public IErrorListener ErrorListener { get; set; }

		public IMetadataStreamReader MetadataStreamReader { get; set; }

		public IDebugDataReader DebugDataReader { get; set; }

		public ICertificateReader CertificateReader { get; set; }

		public IFileService FileService { get; set; } = (IFileService)(object)UncachedFileService.Instance;


		public IReadyToRunSectionReader ReadyToRunSectionReader { get; set; }

		public PEReaderParameters()
			: this((IErrorListener)(object)ThrowErrorListener.Instance)
		{
		}

		public PEReaderParameters(IErrorListener errorListener)
		{
			MetadataStreamReader = new DefaultMetadataStreamReader();
			DebugDataReader = new DefaultDebugDataReader();
			CertificateReader = new DefaultCertificateReader();
			ReadyToRunSectionReader = new DefaultReadyToRunSectionReader();
			ErrorListener = errorListener ?? throw new ArgumentNullException("errorListener");
		}
	}
	public class SerializedPEImage : PEImage
	{
		private readonly MachineType _originalArchitecture;

		public IPEFile PEFile { get; }

		public PEReaderContext ReaderContext { get; }

		public SerializedPEImage(IPEFile peFile, PEReaderParameters readerParameters)
		{
			//IL_0041: 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)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			PEFile = peFile ?? throw new ArgumentNullException("peFile");
			ReaderContext = new PEReaderContext(peFile, readerParameters);
			base.FilePath = peFile.FilePath;
			base.MachineType = PEFile.FileHeader.Machine;
			base.Characteristics = PEFile.FileHeader.Characteristics;
			base.TimeDateStamp = new DateTime(1970, 1, 1) + TimeSpan.FromSeconds(peFile.FileHeader.TimeDateStamp);
			base.PEKind = PEFile.OptionalHeader.Magic;
			base.SubSystem = PEFile.OptionalHeader.SubSystem;
			base.DllCharacteristics = PEFile.OptionalHeader.DllCharacteristics;
			base.ImageBase = PEFile.OptionalHeader.ImageBase;
			_originalArchitecture = base.MachineType;
		}

		protected override IList<IImportedModule> GetImports()
		{
			//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)
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)1);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE)
			{
				return new List<IImportedModule>();
			}
			return (IList<IImportedModule>)new SerializedImportedModuleList(ReaderContext, in dataDirectory);
		}

		protected override IExportDirectory? GetExports()
		{
			//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_0021: Unknown result type (might be due to invalid IL or missing references)
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)0);
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE || !PEFile.TryCreateDataDirectoryReader(dataDirectory, ref reader))
			{
				return null;
			}
			return new SerializedExportDirectory(ReaderContext, ref reader);
		}

		protected override IResourceDirectory? GetResources()
		{
			//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_0021: Unknown result type (might be due to invalid IL or missing references)
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)2);
			BinaryStreamReader directoryReader = default(BinaryStreamReader);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE || !PEFile.TryCreateDataDirectoryReader(dataDirectory, ref directoryReader))
			{
				return null;
			}
			return new SerializedResourceDirectory(ReaderContext, null, ref directoryReader);
		}

		protected override IExceptionDirectory? GetExceptions()
		{
			//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_0021: 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_0038: Invalid comparison between Unknown and I4
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)3);
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE || !PEFile.TryCreateDataDirectoryReader(dataDirectory, ref reader))
			{
				return null;
			}
			if ((int)_originalArchitecture == 34404)
			{
				return new X64ExceptionDirectory(ReaderContext, in reader);
			}
			return ErrorListenerExtensions.NotSupportedAndReturn<IExceptionDirectory>((IErrorListener)(object)ReaderContext);
		}

		protected override IList<BaseRelocation> GetRelocations()
		{
			//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)
			DataDirectory relocDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)5);
			if (!((DataDirectory)(ref relocDirectory)).IsPresentInPE)
			{
				return new List<BaseRelocation>();
			}
			return (IList<BaseRelocation>)new SerializedRelocationList(ReaderContext, in relocDirectory);
		}

		protected override IDotNetDirectory? GetDotNetDirectory()
		{
			//IL_000d: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)14);
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE || !PEFile.TryCreateDataDirectoryReader(dataDirectory, ref reader))
			{
				return null;
			}
			return new SerializedDotNetDirectory(ReaderContext, ref reader);
		}

		protected override IList<DebugDataEntry> GetDebugData()
		{
			//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_0027: Unknown result type (might be due to invalid IL or missing references)
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)6);
			List<DebugDataEntry> list = new List<DebugDataEntry>();
			BinaryStreamReader directoryReader = default(BinaryStreamReader);
			if (((DataDirectory)(ref dataDirectory)).IsPresentInPE && PEFile.TryCreateDataDirectoryReader(dataDirectory, ref directoryReader))
			{
				uint num = ((DataDirectory)(ref dataDirectory)).Size / 28;
				for (int i = 0; i < num; i++)
				{
					list.Add(new SerializedDebugDataEntry(ReaderContext, ref directoryReader));
				}
			}
			return list;
		}

		protected override ITlsDirectory? GetTlsDirectory()
		{
			//IL_000d: 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_0022: Unknown result type (might be due to invalid IL or missing references)
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)9);
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE || !PEFile.TryCreateDataDirectoryReader(dataDirectory, ref reader))
			{
				return null;
			}
			return new SerializedTlsDirectory(ReaderContext, ref reader);
		}

		protected override CertificateCollection GetCertificates()
		{
			//IL_0012: 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_0052: 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)
			//IL_0095: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			CertificateCollection certificateCollection = new CertificateCollection();
			DataDirectory dataDirectory = PEFile.OptionalHeader.GetDataDirectory((DataDirectoryIndex)4);
			if (!((DataDirectory)(ref dataDirectory)).IsPresentInPE)
			{
				return certificateCollection;
			}
			BinaryStreamReader val = default(BinaryStreamReader);
			if (!PEFile.TryCreateReaderAtFileOffset(((DataDirectory)(ref dataDirectory)).VirtualAddress, ((DataDirectory)(ref dataDirectory)).Size, ref val))
			{
				return certificateCollection;
			}
			RelocationParameters parameters = new RelocationParameters((ulong)((DataDirectory)(ref dataDirectory)).VirtualAddress, ((DataDirectory)(ref dataDirectory)).VirtualAddress);
			certificateCollection.UpdateOffsets(in parameters);
			ICertificateReader certificateReader = ReaderContext.Parameters.CertificateReader;
			while (((BinaryStreamReader)(ref val)).CanRead(8u))
			{
				uint num = ((BinaryStreamReader)(ref val)).ReadUInt32();
				CertificateRevision revision = (CertificateRevision)((BinaryStreamReader)(ref val)).ReadUInt16();
				CertificateType type = (CertificateType)((BinaryStreamReader)(ref val)).ReadUInt16();
				BinaryStreamReader reader = ((BinaryStreamReader)(ref val)).ForkRelative(8u, num - 8);
				certificateCollection.Add(certificateReader.ReadCertificate(ReaderContext, revision, type, reader));
				((BinaryStreamReader)(ref val)).RelativeOffset = ((BinaryStreamReader)(ref val)).RelativeOffset + (num - 8);
				((BinaryStreamReader)(ref val)).Align(8u);
			}
			return certificateCollection;
		}
	}
}
namespace AsmResolver.PE.Win32Resources
{
	public interface IResourceData : IResourceEntry, IOwnedCollectionElement<IResourceDirectory>
	{
		ISegment? Contents { get; set; }

		uint CodePage { get; set; }

		[MemberNotNullWhen(true, "Contents")]
		bool CanRead
		{
			[MemberNotNullWhen(true, "Contents")]
			get;
		}

		BinaryStreamReader CreateReader();
	}
	public interface IResourceDirectory : IResourceEntry, IOwnedCollectionElement<IResourceDirectory>
	{
		ResourceType Type { get; }

		uint Characteristics { get; set; }

		uint TimeDateStamp { get; set; }

		ushort MajorVersion { get; set; }

		ushort MinorVersion { get; set; }

		IList<IResourceEntry> Entries { get; }

		IResourceEntry GetEntry(uint id);

		IResourceDirectory GetDirectory(uint id);

		IResourceDirectory GetDirectory(ResourceType type);

		IResourceData GetData(uint id);

		bool TryGetEntry(uint id, [NotNullWhen(true)] out IResourceEntry? entry);

		bool TryGetDirectory(uint id, [NotNullWhen(true)] out IResourceDirectory? directory);

		bool TryGetDirectory(ResourceType type, [NotNullWhen(true)] out IResourceDirectory? directory);

		bool TryGetData(uint id, [NotNullWhen(true)] out IResourceData? data);

		void AddOrReplaceEntry(IResourceEntry entry);

		bool RemoveEntry(uint id);

		bool RemoveEntry(ResourceType type);
	}
	public interface IResourceEntry : IOwnedCollectionElement<IResourceDirectory>
	{
		IResourceDirectory? ParentDirectory { get; }

		string? Name { get; set; }

		uint Id { get; set; }

		bool IsDirectory { get; }

		bool IsData { get; }
	}
	public class ResourceData : IResourceData, IResourceEntry, IOwnedCollectionElement<IResourceDirectory>
	{
		private readonly LazyVariable<ResourceData, ISegment?> _contents;

		public IResourceDirectory? ParentDirectory { get; private set; }

		IResourceDirectory? IOwnedCollectionElement<IResourceDirectory>.Owner
		{
			get
			{
				return ParentDirectory;
			}
			set
			{
				ParentDirectory = value;
			}
		}

		public string? Name { get; set; }

		public uint Id { get; set; }

		bool IResourceEntry.IsDirectory => false;

		bool IResourceEntry.IsData => true;

		public ISegment? Contents
		{
			get
			{
				return _contents.GetValue(this);
			}
			set
			{
				_contents.SetValue(value);
			}
		}

		public uint CodePage { get; set; }

		public bool CanRead => Contents is IReadableSegment;

		protected ResourceData()
		{
			_contents = new LazyVariable<ResourceData, ISegment>((Func<ResourceData, ISegment>)((ResourceData x) => x.GetContents()));
		}

		public ResourceData(string name, ISegment contents)
			: this()
		{
			Name = name ?? throw new ArgumentNullException("name");
			Contents = contents ?? throw new ArgumentNullException("contents");
		}

		public ResourceData(uint id, ISegment contents)
			: this()
		{
			Id = id;
			Contents = contents ?? throw new ArgumentNullException("contents");
		}

		public BinaryStreamReader CreateReader()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			ISegment? contents = Contents;
			IReadableSegment val = (IReadableSegment)(object)((contents is IReadableSegment) ? contents : null);
			if (val == null)
			{
				throw new InvalidOperationException("Resource file is not readable.");
			}
			return Extensions.CreateReader(val);
		}

		protected virtual ISegment? GetContents()
		{
			return null;
		}

		public override string ToString()
		{
			return "Data (" + (Name ?? Id.ToString()) + ")";
		}
	}
	public class ResourceDirectory : IResourceDirectory, IResourceEntry, IOwnedCollectionElement<IResourceDirectory>
	{
		private IList<IResourceEntry>? _entries;

		public IResourceDirectory? ParentDirectory { get; private set; }

		IResourceDirectory? IOwnedCollectionElement<IResourceDirectory>.Owner
		{
			get
			{
				return ParentDirectory;
			}
			set
			{
				ParentDirectory = value;
			}
		}

		public string? Name { get; set; }

		public uint Id { get; set; }

		bool IResourceEntry.IsDirectory => true;

		bool IResourceEntry.IsData => false;

		public ResourceType Type
		{
			get
			{
				return (ResourceType)Id;
			}
			set
			{
				Id = (uint)value;
			}
		}

		public uint Characteristics { get; set; }

		public uint TimeDateStamp { get; set; }

		public ushort MajorVersion { get; set; }

		public ushort MinorVersion { get; set; }

		public IList<IResourceEntry> Entries
		{
			get
			{
				if (_entries == null)
				{
					Interlocked.CompareExchange(ref _entries, GetEntries(), null);
				}
				return _entries;
			}
		}

		protected ResourceDirectory()
		{
		}

		public ResourceDirectory(string name)
		{
			Name = name ?? throw new ArgumentNullException("name");
		}

		public ResourceDirectory(uint id)
		{
			Id = id;
		}

		public ResourceDirectory(ResourceType type)
		{
			Type = type;
		}

		private int GetEntryIndex(uint id)
		{
			for (int i = 0; i < Entries.Count; i++)
			{
				if (Entries[i].Id == id)
				{
					return i;
				}
			}
			return -1;
		}

		public IResourceEntry GetEntry(uint id)
		{
			if (!TryGetEntry(id, out IResourceEntry entry))
			{
				throw new KeyNotFoundException($"Directory does not contain an entry with id {id}.");
			}
			return entry;
		}

		public IResourceDirectory GetDirectory(uint id)
		{
			if (!TryGetDirectory(id, out IResourceDirectory directory))
			{
				throw new KeyNotFoundException($"Directory does not contain a directory with id {id}.");
			}
			return directory;
		}

		public IResourceDirectory GetDirectory(ResourceType type)
		{
			if (!TryGetDirectory(type, out IResourceDirectory directory))
			{
				throw new KeyNotFoundException($"Directory does not contain a directory of type {type}.");
			}
			return directory;
		}

		public IResourceData GetData(uint id)
		{
			if (!TryGetData(id, out IResourceData data))
			{
				throw new KeyNotFoundException($"Directory does not contain a data entry with id {id}.");
			}
			return data;
		}

		public bool TryGetEntry(uint id, [NotNullWhen(true)] out IResourceEntry? entry)
		{
			int entryIndex = GetEntryIndex(id);
			if (entryIndex != -1)
			{
				entry = Entries[entryIndex];
				return true;
			}
			entry = null;
			return false;
		}

		public bool TryGetDirectory(uint id, [NotNullWhen(true)] out IResourceDirectory? directory)
		{
			if (TryGetEntry(id, out IResourceEntry entry) && entry.IsDirectory)
			{
				directory = (IResourceDirectory)entry;
				return true;
			}
			directory = null;
			return false;
		}

		public bool TryGetDirectory(ResourceType type, [NotNullWhen(true)] out IResourceDirectory? directory)
		{
			return TryGetDirectory((uint)type, out directory);
		}

		public bool TryGetData(uint id, [NotNullWhen(true)] out IResourceData? data)
		{
			if (TryGetEntry(id, out IResourceEntry entry) && entry.IsData)
			{
				data = (IResourceData)entry;
				return true;
			}
			data = null;
			return false;
		}

		public void AddOrReplaceEntry(IResourceEntry entry)
		{
			int entryIndex = GetEntryIndex(entry.Id);
			if (entryIndex == -1)
			{
				Entries.Add(entry);
			}
			else
			{
				Entries[entryIndex] = entry;
			}
		}

		public bool RemoveEntry(uint id)
		{
			int entryIndex = GetEntryIndex(id);
			if (entryIndex == -1)
			{
				return false;
			}
			Entries.RemoveAt(entryIndex);
			return true;
		}

		public bool RemoveEntry(ResourceType type)
		{
			return RemoveEntry((uint)type);
		}

		protected virtual IList<IResourceEntry> GetEntries()
		{
			return (IList<IResourceEntry>)new OwnedCollection<IResourceDirectory, IResourceEntry>((IResourceDirectory)this);
		}

		public override string ToString()
		{
			return "Directory (" + (Name ?? Id.ToString()) + ")";
		}
	}
	public readonly struct ResourceDirectoryEntry
	{
		public const int EntrySize = 8;

		private readonly uint _idOrNameOffset;

		private readonly uint _dataOrSubDirOffset;

		public string? Name { get; }

		public uint IdOrNameOffset => _idOrNameOffset & 0x7FFFFFFFu;

		public bool IsByName => (_idOrNameOffset & 0x80000000u) != 0;

		public uint DataOrSubDirOffset => _dataOrSubDirOffset & 0x7FFFFFFFu;

		public bool IsData => (_dataOrSubDirOffset & 0x80000000u) == 0;

		public bool IsSubDirectory => (_dataOrSubDirOffset & 0x80000000u) != 0;

		public ResourceDirectoryEntry(PEReaderContext context, ref BinaryStreamReader reader)
		{
			//IL_0033: 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)
			_idOrNameOffset = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			_dataOrSubDirOffset = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			Name = null;
			if (IsByName)
			{
				DataDirectory dataDirectory = context.File.OptionalHeader.GetDataDirectory((DataDirectoryIndex)2);
				uint virtualAddress = ((DataDirectory)(ref dataDirectory)).VirtualAddress;
				BinaryStreamReader val = default(BinaryStreamReader);
				if (!context.File.TryCreateReaderAtRva(virtualAddress + IdOrNameOffset, ref val))
				{
					ErrorListenerExtensions.BadImage(context.Parameters.ErrorListener, "Resource directory entry contains an invalid name RVA.");
					return;
				}
				int num = ((BinaryStreamReader)(ref val)).ReadUInt16() * 2;
				byte[] array = new byte[num];
				num = ((BinaryStreamReader)(ref val)).ReadBytes(array, 0, num);
				Name = Encoding.Unicode.GetString(array, 0, num);
			}
		}

		public override string ToString()
		{
			return $"Entry: {(IsByName ? Name : IdOrNameOffset.ToString())}, Offset: {DataOrSubDirOffset:X8}";
		}
	}
	public enum ResourceType
	{
		Cursor = 1,
		Bitmap = 2,
		Icon = 3,
		Menu = 4,
		Dialog = 5,
		String = 6,
		FontDirectory = 7,
		Font = 8,
		Accelerator = 9,
		RcData = 10,
		MessageTable = 11,
		GroupCursor = 12,
		GroupIcon = 14,
		Version = 16,
		DialogInclude = 17,
		PlugPlay = 18,
		Vxd = 20,
		AniCursor = 21,
		AniIcon = 22,
		Html = 23,
		Manifest = 24
	}
	public class SerializedResourceData : ResourceData
	{
		public const uint ResourceDataEntrySize = 16u;

		private readonly PEReaderContext _context;

		private readonly uint _contentsRva;

		private readonly uint _contentsSize;

		public SerializedResourceData(PEReaderContext context, ResourceDirectoryEntry entry, ref BinaryStreamReader entryReader)
		{
			_context = context ?? throw new ArgumentNullException("context");
			if (entry.IsByName)
			{
				base.Name = entry.Name;
			}
			else
			{
				base.Id = entry.IdOrNameOffset;
			}
			_contentsRva = ((BinaryStreamReader)(ref entryReader)).ReadUInt32();
			_contentsSize = ((BinaryStreamReader)(ref entryReader)).ReadUInt32();
			base.CodePage = ((BinaryStreamReader)(ref entryReader)).ReadUInt32();
		}

		protected override ISegment? GetContents()
		{
			BinaryStreamReader val = default(BinaryStreamReader);
			if (!_context.File.TryCreateReaderAtRva(_contentsRva, _contentsSize, ref val))
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Resource data entry contains an invalid RVA and/or size.");
				return null;
			}
			return (ISegment?)(object)DataSegment.FromReader(ref val);
		}
	}
	public class SerializedResourceDirectory : ResourceDirectory
	{
		public const uint ResourceDirectorySize = 16u;

		public const int MaxDepth = 10;

		private readonly PEReaderContext _context;

		private readonly ushort _namedEntries;

		private readonly ushort _idEntries;

		private readonly uint _entriesRva;

		private readonly int _depth;

		public SerializedResourceDirectory(PEReaderContext context, ResourceDirectoryEntry? entry, ref BinaryStreamReader directoryReader, int depth = 0)
		{
			_context = context ?? throw new ArgumentNullException("context");
			_depth = depth;
			if (entry.HasValue)
			{
				ResourceDirectoryEntry value = entry.Value;
				if (value.IsByName)
				{
					base.Name = value.Name;
				}
				else
				{
					base.Id = value.IdOrNameOffset;
				}
			}
			if (((BinaryStreamReader)(ref directoryReader)).IsValid)
			{
				base.Characteristics = ((BinaryStreamReader)(ref directoryReader)).ReadUInt32();
				base.TimeDateStamp = ((BinaryStreamReader)(ref directoryReader)).ReadUInt32();
				base.MajorVersion = ((BinaryStreamReader)(ref directoryReader)).ReadUInt16();
				base.MinorVersion = ((BinaryStreamReader)(ref directoryReader)).ReadUInt16();
				_namedEntries = ((BinaryStreamReader)(ref directoryReader)).ReadUInt16();
				_idEntries = ((BinaryStreamReader)(ref directoryReader)).ReadUInt16();
				_entriesRva = ((BinaryStreamReader)(ref directoryReader)).Rva;
				((BinaryStreamReader)(ref directoryReader)).Offset = ((BinaryStreamReader)(ref directoryReader)).Offset + (ulong)((_namedEntries + _idEntries) * 8);
			}
		}

		protected override IList<IResourceEntry> GetEntries()
		{
			//IL_0053: 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)
			OwnedCollection<IResourceDirectory, IResourceEntry> val = new OwnedCollection<IResourceDirectory, IResourceEntry>((IResourceDirectory)this);
			if (_namedEntries + _idEntries == 0 || _depth >= 10)
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, $"Reached maximum recursion depth of {_depth} sub resource directories.");
				return (IList<IResourceEntry>)val;
			}
			DataDirectory dataDirectory = _context.File.OptionalHeader.GetDataDirectory((DataDirectoryIndex)2);
			uint virtualAddress = ((DataDirectory)(ref dataDirectory)).VirtualAddress;
			uint num = (uint)((_namedEntries + _idEntries) * 8);
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!_context.File.TryCreateReaderAtRva(_entriesRva, num, ref reader))
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Resource directory contains an invalid entry table RVA and/or entry count.");
				return (IList<IResourceEntry>)val;
			}
			BinaryStreamReader entryReader = default(BinaryStreamReader);
			for (int i = 0; i < _namedEntries + _idEntries; i++)
			{
				ResourceDirectoryEntry resourceDirectoryEntry = new ResourceDirectoryEntry(_context, ref reader);
				if (!_context.File.TryCreateReaderAtRva(virtualAddress + resourceDirectoryEntry.DataOrSubDirOffset, ref entryReader))
				{
					ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Resource directory entry " + i + " has an invalid data offset.");
				}
				IResourceEntry resourceEntry2;
				if (!resourceDirectoryEntry.IsSubDirectory)
				{
					IResourceEntry resourceEntry = new SerializedResourceData(_context, resourceDirectoryEntry, ref entryReader);
					resourceEntry2 = resourceEntry;
				}
				else
				{
					IResourceEntry resourceEntry = new SerializedResourceDirectory(_context, resourceDirectoryEntry, ref entryReader, _depth + 1);
					resourceEntry2 = resourceEntry;
				}
				((LazyList<IResourceEntry>)(object)val).Add(resourceEntry2);
			}
			return (IList<IResourceEntry>)val;
		}
	}
}
namespace AsmResolver.PE.Win32Resources.Builder
{
	public class ResourceDataTableBuffer : ResourceTableBuffer<IResourceData>
	{
		public ResourceDataTableBuffer(ISegment parentBuffer)
			: base(parentBuffer)
		{
		}

		public override uint GetEntrySize(IResourceData entry)
		{
			return 16u;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			for (int i = 0; i < base.Entries.Count; i++)
			{
				WriteDataEntry(writer, base.Entries[i]);
			}
		}

		private static void WriteDataEntry(IBinaryStreamWriter writer, IResourceData entry)
		{
			if (entry.Contents == null)
			{
				writer.WriteUInt64(0uL);
			}
			else
			{
				writer.WriteUInt32(((IOffsetProvider)entry.Contents).Rva);
				writer.WriteUInt32(((IWritable)entry.Contents).GetPhysicalSize());
			}
			writer.WriteUInt32(entry.CodePage);
			writer.WriteUInt32(0u);
		}
	}
	public class ResourceDirectoryBuffer : ISegment, IOffsetProvider, IWritable
	{
		private readonly SegmentBuilder _segments;

		public ulong Offset => _segments.Offset;

		public uint Rva => _segments.Rva;

		public bool CanUpdateOffsets => true;

		public ResourceTableBuffer<IResourceDirectory> DirectoryTable { get; }

		public ResourceTableBuffer<IResourceData> DataEntryTable { get; }

		public ResourceTableBuffer<string> NameTable { get; }

		public SegmentBuilder DataTable { get; }

		public ResourceDirectoryBuffer()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0042: 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)
			//IL_0053: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			NameTable = new ResourceNameTableBuffer((ISegment)(object)this);
			DataEntryTable = new ResourceDataTableBuffer((ISegment)(object)this);
			DirectoryTable = new ResourceDirectoryTableBuffer((ISegment)(object)this, NameTable, DataEntryTable);
			DataTable = new SegmentBuilder();
			SegmentBuilder val = new SegmentBuilder();
			val.Add((ISegment)(object)DirectoryTable);
			val.Add((ISegment)(object)NameTable);
			val.Add((ISegment)(object)DataEntryTable);
			val.Add((ISegment)(object)DataTable);
			_segments = val;
		}

		public void AddDirectory(IResourceDirectory directory)
		{
			DirectoryTable.AddEntry(directory);
			if (directory.Name != null)
			{
				NameTable.AddEntry(directory.Name);
			}
			foreach (IResourceEntry entry in directory.Entries)
			{
				AddEntry(entry);
			}
		}

		private void AddEntry(IResourceEntry entry)
		{
			if (entry.IsDirectory)
			{
				AddDirectory((IResourceDirectory)entry);
				return;
			}
			if (entry.IsData)
			{
				AddDataEntry(entry);
				return;
			}
			throw new NotSupportedException();
		}

		private void AddDataEntry(IResourceEntry entry)
		{
			IResourceData resourceData = (IResourceData)entry;
			DataEntryTable.AddEntry(resourceData);
			if (resourceData.Contents != null)
			{
				DataTable.Add(resourceData.Contents, 4u);
			}
		}

		public void UpdateOffsets(in RelocationParameters parameters)
		{
			_segments.UpdateOffsets(ref parameters);
		}

		public uint GetPhysicalSize()
		{
			return _segments.GetPhysicalSize();
		}

		public uint GetVirtualSize()
		{
			return _segments.GetVirtualSize();
		}

		public void Write(IBinaryStreamWriter writer)
		{
			_segments.Write(writer);
		}

		void ISegment.UpdateOffsets(in RelocationParameters parameters)
		{
			UpdateOffsets(in parameters);
		}
	}
	public class ResourceDirectoryTableBuffer : ResourceTableBuffer<IResourceDirectory>
	{
		private readonly ResourceTableBuffer<string> _nameTable;

		private readonly ResourceTableBuffer<IResourceData> _dataEntryTable;

		public ResourceDirectoryTableBuffer(ISegment parentBuffer, ResourceTableBuffer<string> nameTable, ResourceTableBuffer<IResourceData> dataEntryTable)
			: base(parentBuffer)
		{
			_nameTable = nameTable ?? throw new ArgumentNullException("nameTable");
			_dataEntryTable = dataEntryTable ?? throw new ArgumentNullException("dataEntryTable");
		}

		public override uint GetEntrySize(IResourceDirectory entry)
		{
			return (uint)(16 + entry.Entries.Count * 8);
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			foreach (IResourceDirectory entry in base.Entries)
			{
				if (entry.IsDirectory)
				{
					WriteDirectory(writer, entry);
					continue;
				}
				throw new ArgumentException("Directory table contains a data entry.");
			}
		}

		private void WriteDirectory(IBinaryStreamWriter writer, IResourceDirectory directory)
		{
			ushort num = (ushort)directory.Entries.Count((IResourceEntry e) => e.Name != null);
			ushort num2 = (ushort)(directory.Entries.Count - num);
			writer.WriteUInt32(directory.Characteristics);
			writer.WriteUInt32(directory.TimeDateStamp);
			writer.WriteUInt16(directory.MajorVersion);
			writer.WriteUInt16(directory.MinorVersion);
			writer.WriteUInt16(num);
			writer.WriteUInt16(num2);
			foreach (IResourceEntry entry in directory.Entries)
			{
				WriteEntry(writer, entry);
			}
		}

		private void WriteEntry(IBinaryStreamWriter writer, IResourceEntry entry)
		{
			writer.WriteUInt32((entry.Name != null) ? (_nameTable.GetEntryOffset(entry.Name) | 0x80000000u) : entry.Id);
			writer.WriteUInt32(entry.IsDirectory ? (GetEntryOffset((IResourceDirectory)entry) | 0x80000000u) : _dataEntryTable.GetEntryOffset((IResourceData)entry));
		}
	}
	public class ResourceNameTableBuffer : ResourceTableBuffer<string>
	{
		public ResourceNameTableBuffer(ISegment parentBuffer)
			: base(parentBuffer)
		{
		}

		public override uint GetEntrySize(string entry)
		{
			return (uint)(2 + Encoding.Unicode.GetByteCount(entry));
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			foreach (string entry in base.Entries)
			{
				writer.WriteUInt16((ushort)entry.Length);
				byte[] bytes = Encoding.Unicode.GetBytes(entry);
				writer.WriteBytes(bytes, 0, bytes.Length);
			}
		}
	}
	public abstract class ResourceTableBuffer<TEntry> : SegmentBase where TEntry : notnull
	{
		private readonly Dictionary<TEntry, uint> _entryOffsets = new Dictionary<TEntry, uint>();

		private readonly ISegment _parentBuffer;

		private uint _length;

		public uint RelativeOffset => ((SegmentBase)this).Rva - ((IOffsetProvider)_parentBuffer).Rva;

		protected IList<TEntry> Entries { get; } = new List<TEntry>();


		protected ResourceTableBuffer(ISegment parentBuffer)
		{
			_parentBuffer = parentBuffer ?? throw new ArgumentNullException("parentBuffer");
		}

		public void AddEntry(TEntry entry)
		{
			if (!_entryOffsets.ContainsKey(entry))
			{
				Entries.Add(entry);
				_entryOffsets[entry] = _length;
				_length += GetEntrySize(entry);
			}
		}

		public abstract uint GetEntrySize(TEntry entry);

		public uint GetEntryOffset(TEntry entry)
		{
			return RelativeOffset + _entryOffsets[entry];
		}

		public override uint GetPhysicalSize()
		{
			return _length;
		}
	}
}
namespace AsmResolver.PE.Tls
{
	public interface ITlsDirectory : ISegment, IOffsetProvider, IWritable
	{
		IReadableSegment? TemplateData { get; set; }

		ISegmentReference Index { get; set; }

		ReferenceTable CallbackFunctions { get; }

		uint SizeOfZeroFill { get; set; }

		TlsCharacteristics Characteristics { get; set; }

		IEnumerable<BaseRelocation> GetRequiredBaseRelocations();
	}
	public class SerializedTlsDirectory : TlsDirectory
	{
		private readonly PEReaderContext _context;

		private readonly ulong _templateStart;

		private readonly ulong _templateEnd;

		private readonly ulong _addressOfCallbacks;

		public SerializedTlsDirectory(PEReaderContext context, ref BinaryStreamReader reader)
		{
			//IL_001a: 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)
			_context = context;
			RelocationParameters relocation = context.GetRelocation(((BinaryStreamReader)(ref reader)).Offset, ((BinaryStreamReader)(ref reader)).Rva);
			_templateStart = ((BinaryStreamReader)(ref reader)).ReadNativeInt(((RelocationParameters)(ref relocation)).Is32Bit);
			_templateEnd = ((BinaryStreamReader)(ref reader)).ReadNativeInt(((RelocationParameters)(ref relocation)).Is32Bit);
			base.Index = ((ISegmentReferenceFactory)context.File).GetReferenceToRva((uint)(((BinaryStreamReader)(ref reader)).ReadNativeInt(((RelocationParameters)(ref relocation)).Is32Bit) - ((RelocationParameters)(ref relocation)).ImageBase));
			_addressOfCallbacks = ((BinaryStreamReader)(ref reader)).ReadNativeInt(((RelocationParameters)(ref relocation)).Is32Bit);
			base.SizeOfZeroFill = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			base.Characteristics = (TlsCharacteristics)((BinaryStreamReader)(ref reader)).ReadUInt32();
			((SegmentBase)this).UpdateOffsets(ref relocation);
		}

		protected override IReadableSegment? GetTemplateData()
		{
			if (_templateEnd < _templateStart)
			{
				return ErrorListenerExtensions.BadImageAndReturn<IReadableSegment>((IErrorListener)(object)_context, "End address of TLS template data is smaller than the start address.");
			}
			ulong imageBase = _context.File.OptionalHeader.ImageBase;
			BinaryStreamReader val = default(BinaryStreamReader);
			if (!_context.File.TryCreateReaderAtRva((uint)(_templateStart - imageBase), ref val))
			{
				return ErrorListenerExtensions.BadImageAndReturn<IReadableSegment>((IErrorListener)(object)_context, $"TLS template data start address 0x{_templateStart:X8} is invalid.");
			}
			uint num = (uint)(_templateEnd - _templateStart);
			if (!((BinaryStreamReader)(ref val)).CanRead(num))
			{
				return ErrorListenerExtensions.BadImageAndReturn<IReadableSegment>((IErrorListener)(object)_context, $"TLS template data end address 0x{_templateEnd:X8} is invalid.");
			}
			return ((BinaryStreamReader)(ref val)).ReadSegment(num);
		}

		protected override ReferenceTable GetCallbackFunctions()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			ReferenceTable callbackFunctions = base.GetCallbackFunctions();
			IPEFile file = _context.File;
			OptionalHeader optionalHeader = file.OptionalHeader;
			ulong imageBase = optionalHeader.ImageBase;
			bool flag = (int)optionalHeader.Magic == 267;
			BinaryStreamReader val = default(BinaryStreamReader);
			if (!file.TryCreateReaderAtRva((uint)(_addressOfCallbacks - imageBase), ref val))
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, $"TLS callback function table start address 0x{_addressOfCallbacks:X8} is invalid.");
				return callbackFunctions;
			}
			while (true)
			{
				if (!((BinaryStreamReader)(ref val)).CanRead(flag ? 4u : 8u))
				{
					ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "TLS callback function table does not end with a zero entry.");
					break;
				}
				ulong num = ((BinaryStreamReader)(ref val)).ReadNativeInt(flag);
				if (num == 0L)
				{
					break;
				}
				((Collection<ISegmentReference>)(object)callbackFunctions).Add(((ISegmentReferenceFactory)file).GetReferenceToRva((uint)(num - imageBase)));
			}
			return callbackFunctions;
		}
	}
	public enum TlsCharacteristics
	{
		Align1Bytes = 1048576,
		Align2Bytes = 2097152,
		Align4Bytes = 3145728,
		Align8Bytes = 4194304,
		Align16Bytes = 5242880,
		Align32Bytes = 6291456,
		Align64Bytes = 7340032,
		Align128Bytes = 8388608,
		Align256Bytes = 9437184,
		Align512Bytes = 10485760,
		Align1024Bytes = 11534336,
		Align2048Bytes = 12582912,
		Align4096Bytes = 13631488,
		Align8192Bytes = 14680064
	}
	public class TlsDirectory : SegmentBase, ITlsDirectory, ISegment, IOffsetProvider, IWritable
	{
		private readonly LazyVariable<TlsDirectory, IReadableSegment?> _templateData;

		private ReferenceTable? _callbackFunctions;

		private ulong _imageBase = 4194304uL;

		private bool _is32Bit = true;

		public IReadableSegment? TemplateData
		{
			get
			{
				return _templateData.GetValue(this);
			}
			set
			{
				_templateData.SetValue(value);
			}
		}

		public ISegmentReference Index { get; set; }

		public ReferenceTable CallbackFunctions
		{
			get
			{
				if (_callbackFunctions == null)
				{
					Interlocked.CompareExchange(ref _callbackFunctions, GetCallbackFunctions(), null);
				}
				return _callbackFunctions;
			}
		}

		public uint SizeOfZeroFill { get; set; }

		public TlsCharacteristics Characteristics { get; set; }

		public TlsDirectory()
		{
			_templateData = new LazyVariable<TlsDirectory, IReadableSegment>((Func<TlsDirectory, IReadableSegment>)((TlsDirectory x) => x.GetTemplateData()));
			Index = SegmentReference.Null;
		}

		public override void UpdateOffsets(in RelocationParameters parameters)
		{
			_imageBase = ((RelocationParameters)(ref parameters)).ImageBase;
			_is32Bit = ((RelocationParameters)(ref parameters)).Is32Bit;
			((SegmentBase)this).UpdateOffsets(ref parameters);
		}

		protected virtual IReadableSegment? GetTemplateData()
		{
			return null;
		}

		protected virtual ReferenceTable GetCallbackFunctions()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			return new ReferenceTable((ReferenceTableAttributes)18);
		}

		public IEnumerable<BaseRelocation> GetRequiredBaseRelocations()
		{
			int num = (_is32Bit ? 4 : 8);
			RelocationType type = (_is32Bit ? RelocationType.HighLow : RelocationType.Dir64);
			List<BaseRelocation> list = new List<BaseRelocation>(4 + ((Collection<ISegmentReference>)(object)CallbackFunctions).Count);
			for (int i = 0; i < 4; i++)
			{
				list.Add(new BaseRelocation(type, Extensions.ToReference((ISegment)(object)this, i * num)));
			}
			for (int j = 0; j < ((Collection<ISegmentReference>)(object)CallbackFunctions).Count; j++)
			{
				list.Add(new BaseRelocation(type, Extensions.ToReference((ISegment)(object)CallbackFunctions, j * num)));
			}
			return list;
		}

		public override uint GetPhysicalSize()
		{
			return (uint)((_is32Bit ? 4 : 8) * 4 + 8);
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			ulong imageBase = _imageBase;
			bool is32Bit = _is32Bit;
			IReadableSegment templateData = TemplateData;
			if (templateData != null)
			{
				IOExtensions.WriteNativeInt(writer, imageBase + ((IOffsetProvider)templateData).Rva, is32Bit);
				IOExtensions.WriteNativeInt(writer, imageBase + ((IOffsetProvider)templateData).Rva + ((IWritable)templateData).GetPhysicalSize(), is32Bit);
			}
			else
			{
				IOExtensions.WriteNativeInt(writer, 0uL, is32Bit);
				IOExtensions.WriteNativeInt(writer, 0uL, is32Bit);
			}
			IOExtensions.WriteNativeInt(writer, imageBase + ((IOffsetProvider)Index).Rva, is32Bit);
			IOExtensions.WriteNativeInt(writer, imageBase + CallbackFunctions.Rva, is32Bit);
			writer.WriteUInt32(SizeOfZeroFill);
			writer.WriteUInt32((uint)Characteristics);
		}
	}
}
namespace AsmResolver.PE.Relocations
{
	public readonly struct BaseRelocation
	{
		public RelocationType Type { get; }

		public ISegmentReference Location { get; }

		public BaseRelocation(RelocationType type, ISegmentReference location)
		{
			Type = type;
			Location = location ?? throw new ArgumentNullException("location");
		}

		public override string ToString()
		{
			return $"{((IOffsetProvider)Location).Rva:X8} ({Type})";
		}

		public bool Equals(BaseRelocation other)
		{
			if (Type == other.Type)
			{
				return ((IOffsetProvider)Location).Rva == ((IOffsetProvider)other.Location).Rva;
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			if (obj is BaseRelocation other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ((int)Type * 397) ^ (int)((IOffsetProvider)Location).Rva;
		}
	}
	public readonly struct RelocatableSegment
	{
		public ISegment Segment { get; }

		public IReadOnlyList<BaseRelocation> Relocations { get; }

		public RelocatableSegment(ISegment segment, IReadOnlyList<BaseRelocation> relocations)
		{
			Segment = segment;
			Relocations = relocations;
		}
	}
	public enum RelocationType
	{
		Absolute = 0,
		High = 1,
		Low = 2,
		HighLow = 3,
		HighAdj = 4,
		MipsJmpAddr = 5,
		ArmMov32 = 5,
		RiscVHigh20 = 5,
		ThumbMov32 = 7,
		RiscVLow12I = 7,
		RiscVLow12S = 8,
		MipsJmpAddr16 = 9,
		Dir64 = 10
	}
	[DebuggerDisplay("Count = {Count}")]
	public class SerializedRelocationList : LazyList<BaseRelocation>
	{
		private readonly PEReaderContext _context;

		private readonly DataDirectory _relocDirectory;

		public SerializedRelocationList(PEReaderContext context, in DataDirectory relocDirectory)
		{
			//IL_001e: 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)
			_context = context ?? throw new ArgumentNullException("context");
			_relocDirectory = relocDirectory;
		}

		protected override void Initialize()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!_context.File.TryCreateDataDirectoryReader(_relocDirectory, ref reader))
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Invalid base relocation data directory RVA and/or size.");
				return;
			}
			while (((BinaryStreamReader)(ref reader)).Offset < ((BinaryStreamReader)(ref reader)).StartOffset + ((BinaryStreamReader)(ref reader)).Length)
			{
				ReadBlock(ref reader);
			}
		}

		private void ReadBlock(ref BinaryStreamReader reader)
		{
			uint pageRva = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			int num = (int)((((BinaryStreamReader)(ref reader)).ReadUInt32() - 8) / 2);
			for (int i = 0; i < num; i++)
			{
				ReadRelocationEntry(ref reader, pageRva);
			}
		}

		private void ReadRelocationEntry(ref BinaryStreamReader reader, uint pageRva)
		{
			ushort num = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			RelocationType type = (RelocationType)(num >> 12);
			int num2 = num & 0xFFF;
			base.Items.Add(new BaseRelocation(type, ((ISegmentReferenceFactory)_context.File).GetReferenceToRva((uint)(pageRva + num2))));
		}
	}
}
namespace AsmResolver.PE.Relocations.Builder
{
	public sealed class RelocationBlock : SegmentBase
	{
		public uint PageRva { get; }

		public IList<RelocationEntry> Entries { get; }

		public RelocationBlock(uint pageRva)
		{
			PageRva = pageRva;
			Entries = new List<RelocationEntry>();
		}

		public override uint GetPhysicalSize()
		{
			return (uint)((Entries.Count + 1) * 2 + 8);
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			writer.WriteUInt32(PageRva);
			writer.WriteUInt32(((SegmentBase)this).GetPhysicalSize());
			for (int i = 0; i < Entries.Count; i++)
			{
				Entries[i].Write(writer);
			}
			default(RelocationEntry).Write(writer);
		}
	}
	public readonly struct RelocationEntry : IWritable
	{
		private readonly ushort _value;

		public RelocationType RelocationType => (RelocationType)(_value >> 12);

		public int Offset => _value & 0xFFF;

		public RelocationEntry(ushort value)
		{
			_value = value;
		}

		public RelocationEntry(RelocationType type, int offset)
		{
			if (offset >= 0)
			{
				if (offset > 4095)
				{
					throw new ArgumentOutOfRangeException("offset", "Offset cannot be larger than 0xFFF.");
				}
				ushort value = (ushort)((uint)((byte)type << 12) | ((uint)offset & 0xFFFu));
				_value = value;
				return;
			}
			throw new ArgumentOutOfRangeException("offset", "Offset cannot be negative.");
		}

		public uint GetPhysicalSize()
		{
			return 2u;
		}

		public void Write(IBinaryStreamWriter writer)
		{
			writer.WriteUInt16(_value);
		}
	}
	public class RelocationsDirectoryBuffer : SegmentBase
	{
		private readonly List<BaseRelocation> _relocations = new List<BaseRelocation>();

		private List<RelocationBlock>? _blocks = new List<RelocationBlock>();

		public void Add(BaseRelocation relocation)
		{
			_relocations.Add(relocation);
			_blocks = null;
		}

		private void EnsureBlocksCreated()
		{
			if (_blocks == null)
			{
				_blocks = CreateBlocks();
			}
		}

		private List<RelocationBlock> CreateBlocks()
		{
			Dictionary<uint, RelocationBlock> dictionary = new Dictionary<uint, RelocationBlock>();
			for (int i = 0; i < _relocations.Count; i++)
			{
				BaseRelocation relocation = _relocations[i];
				uint pageRva = GetPageRva(relocation);
				GetOrCreateBlock(dictionary, pageRva).Entries.Add(CreateEntry(relocation));
			}
			return (from x in dictionary
				orderby x.Key
				select x.Value).ToList();
		}

		private static uint GetPageRva(BaseRelocation relocation)
		{
			return (uint)(((IOffsetProvider)relocation.Location).Rva & -4096);
		}

		private static RelocationEntry CreateEntry(BaseRelocation relocation)
		{
			return new RelocationEntry(relocation.Type, (int)(((IOffsetProvider)relocation.Location).Rva & 0xFFF));
		}

		private static RelocationBlock GetOrCreateBlock(IDictionary<uint, RelocationBlock> blocks, uint pageRva)
		{
			if (!blocks.TryGetValue(pageRva, out RelocationBlock value))
			{
				value = new RelocationBlock(pageRva);
				blocks.Add(pageRva, value);
			}
			return value;
		}

		public override void UpdateOffsets(in RelocationParameters parameters)
		{
			((SegmentBase)this).UpdateOffsets(ref parameters);
			_blocks = null;
		}

		public override uint GetPhysicalSize()
		{
			EnsureBlocksCreated();
			return (uint)_blocks.Sum((RelocationBlock b) => ((SegmentBase)b).GetPhysicalSize());
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			EnsureBlocksCreated();
			for (int i = 0; i < _blocks.Count; i++)
			{
				((SegmentBase)_blocks[i]).Write(writer);
			}
		}
	}
}
namespace AsmResolver.PE.Platforms
{
	public class Amd64Platform : Platform
	{
		public static Amd64Platform Instance { get; } = new Amd64Platform();


		public override MachineType TargetMachine => (MachineType)34404;

		public override bool IsClrBootstrapperRequired => false;

		public override bool Is32Bit => false;

		public override RelocatableSegment CreateThunkStub(ISymbol entryPoint)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			PatchedSegment val = Extensions.AsPatchedSegment((ISegment)new DataSegment(new byte[12]
			{
				72, 161, 0, 0, 0, 0, 0, 0, 0, 0,
				255, 224
			})).Patch(2u, AddressFixupType.Absolute64BitAddress, entryPoint);
			return new RelocatableSegment((ISegment)(object)val, new BaseRelocation[1]
			{
				new BaseRelocation(RelocationType.Dir64, Extensions.ToReference((ISegment)(object)val, 2))
			});
		}

		public override bool TryExtractThunkAddress(IPEImage image, BinaryStreamReader reader, out uint rva)
		{
			if (((BinaryStreamReader)(ref reader)).ReadUInt16() != 41288)
			{
				rva = 0u;
				return false;
			}
			rva = (uint)(((BinaryStreamReader)(ref reader)).ReadUInt64() - image.ImageBase);
			return ((BinaryStreamReader)(ref reader)).ReadUInt16() == 57599;
		}
	}
	public class I386Platform : Platform
	{
		public static I386Platform Instance { get; } = new I386Platform();


		public override MachineType TargetMachine => (MachineType)332;

		public override bool IsClrBootstrapperRequired => true;

		public override bool Is32Bit => true;

		public override RelocatableSegment CreateThunkStub(ISymbol entryPoint)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			PatchedSegment val = Extensions.AsPatchedSegment((ISegment)new DataSegment(new byte[6] { 255, 37, 0, 0, 0, 0 })).Patch(2u, AddressFixupType.Absolute32BitAddress, entryPoint);
			return new RelocatableSegment((ISegment)(object)val, new BaseRelocation[1]
			{
				new BaseRelocation(RelocationType.HighLow, Extensions.ToReference((ISegment)(object)val, 2))
			});
		}

		public override bool TryExtractThunkAddress(IPEImage image, BinaryStreamReader reader, out uint rva)
		{
			if (((BinaryStreamReader)(ref reader)).ReadUInt16() != 9727)
			{
				rva = 0u;
				return false;
			}
			rva = (uint)(((BinaryStreamReader)(ref reader)).ReadUInt32() - image.ImageBase);
			return true;
		}
	}
	public abstract class Platform
	{
		public abstract MachineType TargetMachine { get; }

		public abstract bool IsClrBootstrapperRequired { get; }

		public abstract bool Is32Bit { get; }

		public bool Is64Bit => !Is32Bit;

		public int PointerSize
		{
			get
			{
				if (!Is32Bit)
				{
					return 8;
				}
				return 4;
			}
		}

		public static Platform Get(MachineType machineType)
		{
			//IL_0000: 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 (!TryGet(machineType, out Platform platform))
			{
				throw new NotSupportedException($"Unsupported machine type {machineType}.");
			}
			return platform;
		}

		public static bool TryGet(MachineType machineType, [NotNullWhen(true)] out Platform? platform)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Invalid comparison between Unknown and I4
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Invalid comparison between Unknown and I4
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Invalid comparison between Unknown and I4
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Invalid comparison between Unknown and I4
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			//IL_0018: 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: Invalid comparison between Unknown and I4
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Invalid comparison between Unknown and I4
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Invalid comparison between Unknown and I4
			if ((int)machineType <= 31285)
			{
				if ((int)machineType <= 6367)
				{
					if ((int)machineType == 332 || machineType - 6366 <= 1)
					{
						goto IL_0074;
					}
				}
				else
				{
					if ((int)machineType == 11168)
					{
						goto IL_007c;
					}
					if ((int)machineType == 18184 || (int)machineType == 31285)
					{
						goto IL_0074;
					}
				}
			}
			else if ((int)machineType <= 40951)
			{
				if ((int)machineType == 34404 || machineType - 40950 <= 1)
				{
					goto IL_007c;
				}
			}
			else
			{
				if ((int)machineType == 44168)
				{
					goto IL_0074;
				}
				if ((int)machineType == 49184 || (int)machineType == 64797)
				{
					goto IL_007c;
				}
			}
			Platform platform2 = null;
			goto IL_0086;
			IL_0086:
			platform = platform2;
			return platform != null;
			IL_0074:
			platform2 = I386Platform.Instance;
			goto IL_0086;
			IL_007c:
			platform2 = Amd64Platform.Instance;
			goto IL_0086;
		}

		public abstract RelocatableSegment CreateThunkStub(ISymbol entryPoint);

		public abstract bool TryExtractThunkAddress(IPEImage image, BinaryStreamReader reader, out uint rva);
	}
}
namespace AsmResolver.PE.Imports
{
	public sealed class DefaultSymbolResolver : ISymbolResolver
	{
		private static readonly Dictionary<uint, string> _ws2_32OrdinalMapping = new Dictionary<uint, string>
		{
			[1u] = "accept",
			[2u] = "bind",
			[3u] = "closesocket",
			[4u] = "connect",
			[5u] = "getpeername",
			[6u] = "getsockname",
			[7u] = "getsockopt",
			[8u] = "htonl",
			[9u] = "htons",
			[10u] = "ioctlsocket",
			[11u] = "inet_addr",
			[12u] = "inet_ntoa",
			[13u] = "listen",
			[14u] = "ntohl",
			[15u] = "ntohs",
			[16u] = "recv",
			[17u] = "recvfrom",
			[18u] = "select",
			[19u] = "send",
			[20u] = "sendto",
			[21u] = "setsockopt",
			[22u] = "shutdown",
			[23u] = "socket",
			[24u] = "WSApSetPostRoutine",
			[25u] = "FreeAddrInfoEx",
			[26u] = "FreeAddrInfoExW",
			[27u] = "FreeAddrInfoW",
			[28u] = "GetAddrInfoExA",
			[29u] = "GetAddrInfoExCancel",
			[30u] = "GetAddrInfoExOverlappedResult",
			[31u] = "GetAddrInfoExW",
			[32u] = "GetAddrInfoW",
			[33u] = "GetHostNameW",
			[34u] = "GetNameInfoW",
			[35u] = "InetNtopW",
			[36u] = "InetPtonW",
			[37u] = "SetAddrInfoExA",
			[38u] = "SetAddrInfoExW",
			[39u] = "WPUCompleteOverlappedRequest",
			[40u] = "WPUGetProviderPathEx",
			[41u] = "WSAAccept",
			[42u] = "WSAAddressToStringA",
			[43u] = "WSAAddressToStringW",
			[44u] = "WSAAdvertiseProvider",
			[45u] = "WSACloseEvent",
			[46u] = "WSAConnect",
			[47u] = "WSAConnectByList",
			[48u] = "WSAConnectByNameA",
			[49u] = "WSAConnectByNameW",
			[50u] = "WSACreateEvent",
			[51u] = "gethostbyaddr",
			[52u] = "gethostbyname",
			[53u] = "getprotobyname",
			[54u] = "getprotobynumber",
			[55u] = "getservbyname",
			[56u] = "getservbyport",
			[57u] = "gethostname",
			[58u] = "WSADuplicateSocketA",
			[59u] = "WSADuplicateSocketW",
			[60u] = "WSAEnumNameSpaceProvidersA",
			[61u] = "WSAEnumNameSpaceProvidersExA",
			[62u] = "WSAEnumNameSpaceProvidersExW",
			[63u] = "WSAEnumNameSpaceProvidersW",
			[64u] = "WSAEnumNetworkEvents",
			[65u] = "WSAEnumProtocolsA",
			[66u] = "WSAEnumProtocolsW",
			[67u] = "WSAEventSelect",
			[68u] = "WSAGetOverlappedResult",
			[69u] = "WSAGetQOSByName",
			[70u] = "WSAGetServiceClassInfoA",
			[71u] = "WSAGetServiceClassInfoW",
			[72u] = "WSAGetServiceClassNameByClassIdA",
			[73u] = "WSAGetServiceClassNameByClassIdW",
			[74u] = "WSAHtonl",
			[75u] = "WSAHtons",
			[76u] = "WSAInstallServiceClassA",
			[77u] = "WSAInstallServiceClassW",
			[78u] = "WSAIoctl",
			[79u] = "WSAJoinLeaf",
			[80u] = "WSALookupServiceBeginA",
			[81u] = "WSALookupServiceBeginW",
			[82u] = "WSALookupServiceEnd",
			[83u] = "WSALookupServiceNextA",
			[84u] = "WSALookupServiceNextW",
			[85u] = "WSANSPIoctl",
			[86u] = "WSANtohl",
			[87u] = "WSANtohs",
			[88u] = "WSAPoll",
			[89u] = "WSAProviderCompleteAsyncCall",
			[90u] = "WSAProviderConfigChange",
			[91u] = "WSARecv",
			[92u] = "WSARecvDisconnect",
			[93u] = "WSARecvFrom",
			[94u] = "WSARemoveServiceClass",
			[95u] = "WSAResetEvent",
			[96u] = "WSASend",
			[97u] = "WSASendDisconnect",
			[98u] = "WSASendMsg",
			[99u] = "WSASendTo",
			[100u] = "WSASetEvent",
			[101u] = "WSAAsyncSelect",
			[102u] = "WSAAsyncGetHostByAddr",
			[103u] = "WSAAsyncGetHostByName",
			[104u] = "WSAAsyncGetProtoByNumber",
			[105u] = "WSAAsyncGetProtoByName",
			[106u] = "WSAAsyncGetServByPort",
			[107u] = "WSAAsyncGetServByName",
			[108u] = "WSACancelAsyncRequest",
			[109u] = "WSASetBlockingHook",
			[110u] = "WSAUnhookBlockingHook",
			[111u] = "WSAGetLastError",
			[112u] = "WSASetLastError",
			[113u] = "WSACancelBlockingCall",
			[114u] = "WSAIsBlocking",
			[115u] = "WSAStartup",
			[116u] = "WSACleanup",
			[117u] = "WSASetServiceA",
			[118u] = "WSASetServiceW",
			[119u] = "WSASocketA",
			[120u] = "WSASocketW",
			[121u] = "WSAStringToAddressA",
			[122u] = "WSAStringToAddressW",
			[123u] = "WSAUnadvertiseProvider",
			[124u] = "WSAWaitForMultipleEvents",
			[125u] = "WSCDeinstallProvider",
			[126u] = "WSCDeinstallProvider32",
			[127u] = "WSCDeinstallProviderEx",
			[128u] = "WSCEnableNSProvider",
			[129u] = "WSCEnableNSProvider32",
			[130u] = "WSCEnumNameSpaceProviders32",
			[131u] = "WSCEnumNameSpaceProvidersEx32",
			[132u] = "WSCEnumProtocols",
			[133u] = "WSCEnumProtocols32",
			[134u] = "WSCEnumProtocolsEx",
			[135u] = "WSCGetApplicationCategory",
			[136u] = "WSCGetApplicationCategoryEx",
			[137u] = "WSCGetProviderInfo",
			[138u] = "WSCGetProviderInfo32",
			[139u] = "WSCGetProviderPath",
			[140u] = "WSCGetProviderPath32",
			[141u] = "WSCInstallNameSpace",
			[142u] = "WSCInstallNameSpace32",
			[143u] = "WSCInstallNameSpaceEx",
			[144u] = "WSCInstallNameSpaceEx2",
			[145u] = "WSCInstallNameSpaceEx32",
			[146u] = "WSCInstallProvider",
			[147u] = "WSCInstallProvider64_32",
			[148u] = "WSCInstallProviderAndChains64_32",
			[149u] = "WSCInstallProviderEx",
			[150u] = "WSCSetApplicationCategory",
			[151u] = "__WSAFDIsSet",
			[152u] = "WSCSetApplicationCategoryEx",
			[153u] = "WSCSetProviderInfo",
			[154u] = "WSCSetProviderInfo32",
			[155u] = "WSCUnInstallNameSpace",
			[156u] = "WSCUnInstallNameSpace32",
			[157u] = "WSCUnInstallNameSpaceEx2",
			[158u] = "WSCUpdateProvider",
			[159u] = "WSCUpdateProvider32",
			[160u] = "WSCUpdateProviderEx",
			[161u] = "WSCWriteNameSpaceOrder",
			[162u] = "WSCWriteNameSpaceOrder32",
			[163u] = "WSCWriteProviderOrder",
			[164u] = "WSCWriteProviderOrder32",
			[165u] = "WSCWriteProviderOrderEx",
			[166u] = "WahCloseApcHelper",
			[167u] = "WahCloseHandleHelper",
			[168u] = "WahCloseNotificationHandleHelper",
			[169u] = "WahCloseSocketHandle",
			[170u] = "WahCloseThread",
			[171u] = "WahCompleteRequest",
			[172u] = "WahCreateHandleContextTable",
			[173u] = "WahCreateNotificationHandle",
			[174u] = "WahCreateSocketHandle",
			[175u] = "WahDestroyHandleContextTable",
			[176u] = "WahDisableNonIFSHandleSupport",
			[177u] = "WahEnableNonIFSHandleSupport",
			[178u] = "WahEnumerateHandleContexts",
			[179u] = "WahInsertHandleContext",
			[180u] = "WahNotifyAllProcesses",
			[181u] = "WahOpenApcHelper",
			[182u] = "WahOpenCurrentThread",
			[183u] = "WahOpenHandleHelper",
			[184u] = "WahOpenNotificationHandleHelper",
			[185u] = "WahQueueUserApc",
			[186u] = "WahReferenceContextByHandle",
			[187u] = "WahRemoveHandleContext",
			[188u] = "WahWaitForNotification",
			[189u] = "WahWriteLSPEvent",
			[190u] = "freeaddrinfo",
			[191u] = "getaddrinfo",
			[192u] = "getnameinfo",
			[193u] = "inet_ntop",
			[194u] = "inet_pton",
			[500u] = "WEP"
		};

		private static readonly Dictionary<uint, string> _oleaut32OrdinalMapping = new Dictionary<uint, string>
		{
			[2u] = "SysAllocString",
			[3u] = "SysReAllocString",
			[4u] = "SysAllocStringLen",
			[5u] = "SysReAllocStringLen",
			[6u] = "SysFreeString",
			[7u] = "SysStringLen",
			[8u] = "VariantInit",
			[9u] = "VariantClear",
			[10u] = "VariantCopy",
			[11u] = "VariantCopyInd",
			[12u] = "VariantChangeType",
			[13u] = "VariantTimeToDosDateTime",
			[14u] = "DosDateTimeToVariantTime",
			[15u] = "SafeArrayCreate",
			[16u] = "SafeArrayDestroy",
			[17u] = "SafeArrayGetDim",
			[18u] = "SafeArrayGetElemsize",
			[19u] = "SafeArrayGetUBound",
			[20u] = "SafeArrayGetLBound",
			[21u] = "SafeArrayLock",
			[22u] = "SafeArrayUnlock",
			[23u] = "SafeArrayAccessData",
			[24u] = "SafeArrayUnaccessData",
			[25u] = "SafeArrayGetElement",
			[26u] = "SafeArrayPutElement",
			[27u] = "SafeArrayCopy",
			[28u] = "DispGetParam",
			[29u] = "DispGetIDsOfNames",
			[30u] = "DispInvoke",
			[31u] = "CreateDispTypeInfo",
			[32u] = "CreateStdDispatch",
			[33u] = "RegisterActiveObject",
			[34u] = "RevokeActiveObject",
			[35u] = "GetActiveObject",
			[36u] = "SafeArrayAllocDescriptor",
			[37u] = "SafeArrayAllocData",
			[38u] = "SafeArrayDestroyDescriptor",
			[39u] = "SafeArrayDestroyData",
			[40u] = "SafeArrayRedim",
			[41u] = "SafeArrayAllocDescriptorEx",
			[42u] = "SafeArrayCreateEx",
			[43u] = "SafeArrayCreateVectorEx",
			[44u] = "SafeArraySetRecordInfo",
			[45u] = "SafeArrayGetRecordInfo",
			[46u] = "VarParseNumFromStr",
			[47u] = "VarNumFromParseNum",
			[48u] = "VarI2FromUI1",
			[49u] = "VarI2FromI4",
			[50u] = "VarI2FromR4",
			[51u] = "VarI2FromR8",
			[52u] = "VarI2FromCy",
			[53u] = "VarI2FromDate",
			[54u] = "VarI2FromStr",
			[55u] = "VarI2FromDisp",
			[56u] = "VarI2FromBool",
			[57u] = "SafeArraySetIID",
			[58u] = "VarI4FromUI1",
			[59u] = "VarI4FromI2",
			[60u] = "VarI4FromR4",
			[61u] = "VarI4FromR8",
			[62u] = "VarI4FromCy",
			[63u] = "VarI4FromDate",
			[64u] = "VarI4FromStr",
			[65u] = "VarI4FromDisp",
			[66u] = "VarI4FromBool",
			[67u] = "SafeArrayGetIID",
			[68u] = "VarR4FromUI1",
			[69u] = "VarR4FromI2",
			[70u] = "VarR4FromI4",
			[71u] = "VarR4FromR8",
			[72u] = "VarR4FromCy",
			[73u] = "VarR4FromDate",
			[74u] = "VarR4FromStr",
			[75u] = "VarR4FromDisp",
			[76u] = "VarR4FromBool",
			[77u] = "SafeArrayGetVartype",
			[78u] = "VarR8FromUI1",
			[79u] = "VarR8FromI2",
			[80u] = "VarR8FromI4",
			[81u] = "VarR8FromR4",
			[82u] = "VarR8FromCy",
			[83u] = "VarR8FromDate",
			[84u] = "VarR8FromStr",
			[85u] = "VarR8FromDisp",
			[86u] = "VarR8FromBool",
			[87u] = "VarFormat",
			[88u] = "VarDateFromUI1",
			[89u] = "VarDateFromI2",
			[90u] = "VarDateFromI4",
			[91u] = "VarDateFromR4",
			[92u] = "VarDateFromR8",
			[93u] = "VarDateFromCy",
			[94u] = "VarDateFromStr",
			[95u] = "VarDateFromDisp",
			[96u] = "VarDateFromBool",
			[97u] = "VarFormatDateTime",
			[98u] = "VarCyFromUI1",
			[99u] = "VarCyFromI2",
			[100u] = "VarCyFromI4",
			[101u] = "VarCyFromR4",
			[102u] = "VarCyFromR8",
			[103u] = "VarCyFromDate",
			[104u] = "VarCyFromStr",
			[105u] = "VarCyFromDisp",
			[106u] = "VarCyFromBool",
			[107u] = "VarFormatNumber",
			[108u] = "VarBstrFromUI1",
			[109u] = "VarBstrFromI2",
			[110u] = "VarBstrFromI4",
			[111u] = "VarBstrFromR4",
			[112u] = "VarBstrFromR8",
			[113u] = "VarBstrFromCy",
			[114u] = "VarBstrFromDate",
			[115u] = "VarBstrFromDisp",
			[116u] = "VarBstrFromBool",
			[117u] = "VarFormatPercent",
			[118u] = "VarBoolFromUI1",
			[119u] = "VarBoolFromI2",
			[120u] = "VarBoolFromI4",
			[121u] = "VarBoolFromR4",
			[122u] = "VarBoolFromR8",
			[123u] = "VarBoolFromDate",
			[124u] = "VarBoolFromCy",
			[125u] = "VarBoolFromStr",
			[126u] = "VarBoolFromDisp",
			[127u] = "VarFormatCurrency",
			[128u] = "VarWeekdayName",
			[129u] = "VarMonthName",
			[130u] = "VarUI1FromI2",
			[131u] = "VarUI1FromI4",
			[132u] = "VarUI1FromR4",
			[133u] = "VarUI1FromR8",
			[134u] = "VarUI1FromCy",
			[135u] = "VarUI1FromDate",
			[136u] = "VarUI1FromStr",
			[137u] = "VarUI1FromDisp",
			[138u] = "VarUI1FromBool",
			[139u] = "VarFormatFromTokens",
			[140u] = "VarTokenizeFormatString",
			[141u] = "VarAdd",
			[142u] = "VarAnd",
			[143u] = "VarDiv",
			[144u] = "BSTR_UserFree64",
			[145u] = "BSTR_UserMarshal64",
			[146u] = "DispCallFunc",
			[147u] = "VariantChangeTypeEx",
			[148u] = "SafeArrayPtrOfIndex",
			[149u] = "SysStringByteLen",
			[150u] = "SysAllocStringByteLen",
			[151u] = "BSTR_UserSize64",
			[152u] = "VarEqv",
			[153u] = "VarIdiv",
			[154u] = "VarImp",
			[155u] = "VarMod",
			[156u] = "VarMul",
			[157u] = "VarOr",
			[158u] = "VarPow",
			[159u] = "VarSub",
			[160u] = "CreateTypeLib",
			[161u] = "LoadTypeLib",
			[162u] = "LoadRegTypeLib",
			[163u] = "RegisterTypeLib",
			[164u] = "QueryPathOfRegTypeLib",
			[165u] = "LHashValOfNameSys",
			[166u] = "LHashValOfNameSysA",
			[167u] = "VarXor",
			[168u] = "VarAbs",
			[169u] = "VarFix",
			[170u] = "OaBuildVersion",
			[171u] = "ClearCustData",
			[172u] = "VarInt",
			[173u] = "VarNeg",
			[174u] = "VarNot",
			[175u] = "VarRound",
			[176u] = "VarCmp",
			[177u] = "VarDecAdd",
			[178u] = "VarDecDiv",
			[179u] = "VarDecMul",
			[180u] = "CreateTypeLib2",
			[181u] = "VarDecSub",
			[182u] = "VarDecAbs",
			[183u] = "LoadTypeLibEx",
			[184u] = "SystemTimeToVariantTime",
			[185u] = "VariantTimeToSystemTime",
			[186u] = "UnRegisterTypeLib",
			[187u] = "VarDecFix",
			[188u] = "VarDecInt",
			[189u] = "VarDecNeg",
			[190u] = "VarDecFromUI1",
			[191u] = "VarDecFromI2",
			[192u] = "VarDecFromI4",
			[193u] = "VarDecFromR4",
			[194u] = "VarDecFromR8",
			[195u] = "VarDecFromDate",
			[196u] = "VarDecFromCy",
			[197u] = "VarDecFromStr",
			[198u] = "VarDecFromDisp",
			[199u] = "VarDecFromBool",
			[200u] = "GetErrorInfo",
			[201u] = "SetErrorInfo",
			[202u] = "CreateErrorInfo",
			[203u] = "VarDecRound",
			[204u] = "VarDecCmp",
			[205u] = "VarI2FromI1",
			[206u] = "VarI2FromUI2",
			[207u] = "VarI2FromUI4",
			[208u] = "VarI2FromDec",
			[209u] = "VarI4FromI1",
			[210u] = "VarI4FromUI2",
			[211u] = "VarI4FromUI4",
			[212u] = "VarI4FromDec",
			[213u] = "VarR4FromI1",
			[214u] = "VarR4FromUI2",
			[215u] = "VarR4FromUI4",
			[216u] = "VarR4FromDec",
			[217u] = "VarR8FromI1",
			[218u] = "VarR8FromUI2",
			[219u] = "VarR8FromUI4",
			[220u] = "VarR8FromDec",
			[221u] = "VarDateFromI1",
			[222u] = "VarDateFromUI2",
			[223u] = "VarDateFromUI4",
			[224u] = "VarDateFromDec",
			[225u] = "VarCyFromI1",
			[226u] = "VarCyFromUI2",
			[227u] = "VarCyFromUI4",
			[228u] = "VarCyFromDec",
			[229u] = "VarBstrFromI1",
			[230u] = "VarBstrFromUI2",
			[231u] = "VarBstrFromUI4",
			[232u] = "VarBstrFromDec",
			[233u] = "VarBoolFromI1",
			[234u] = "VarBoolFromUI2",
			[235u] = "VarBoolFromUI4",
			[236u] = "VarBoolFromDec",
			[237u] = "VarUI1FromI1",
			[238u] = "VarUI1FromUI2",
			[239u] = "VarUI1FromUI4",
			[240u] = "VarUI1FromDec",
			[241u] = "VarDecFromI1",
			[242u] = "VarDecFromUI2",
			[243u] = "VarDecFromUI4",
			[244u] = "VarI1FromUI1",
			[245u] = "VarI1FromI2",
			[246u] = "VarI1FromI4",
			[247u] = "VarI1FromR4",
			[248u] = "VarI1FromR8",
			[249u] = "VarI1FromDate",
			[250u] = "VarI1FromCy",
			[251u] = "VarI1FromStr",
			[252u] = "VarI1FromDisp",
			[253u] = "VarI1FromBool",
			[254u] = "VarI1FromUI2",
			[255u] = "VarI1FromUI4",
			[256u] = "VarI1FromDec",
			[257u] = "VarUI2FromUI1",
			[258u] = "VarUI2FromI2",
			[259u] = "VarUI2FromI4",
			[260u] = "VarUI2FromR4",
			[261u] = "VarUI2FromR8",
			[262u] = "VarUI2FromDate",
			[263u] = "VarUI2FromCy",
			[264u] = "VarUI2FromStr",
			[265u] = "VarUI2FromDisp",
			[266u] = "VarUI2FromBool",
			[267u] = "VarUI2FromI1",
			[268u] = "VarUI2FromUI4",
			[269u] = "VarUI2FromDec",
			[270u] = "VarUI4FromUI1",
			[271u] = "VarUI4FromI2",
			[272u] = "VarUI4FromI4",
			[273u] = "VarUI4FromR4",
			[274u] = "VarUI4FromR8",
			[275u] = "VarUI4FromDate",
			[276u] = "VarUI4FromCy",
			[277u] = "VarUI4FromStr",
			[278u] = "VarUI4FromDisp",
			[279u] = "VarUI4FromBool",
			[280u] = "VarUI4FromI1",
			[281u] = "VarUI4FromUI2",
			[282u] = "VarUI4FromDec",
			[283u] = "BSTR_UserSize",
			[284u] = "BSTR_UserMarshal",
			[285u] = "BSTR_UserUnmarshal",
			[286u] = "BSTR_UserFree",
			[287u] = "VARIANT_UserSize",
			[288u] = "VARIANT_UserMarshal",
			[289u] = "VARIANT_UserUnmarshal",
			[290u] = "VARIANT_UserFree",
			[291u] = "LPSAFEARRAY_UserSize",
			[292u] = "LPSAFEARRAY_UserMarshal",
			[293u] = "LPSAFEARRAY_UserUnmarshal",
			[294u] = "LPSAFEARRAY_UserFree",
			[295u] = "LPSAFEARRAY_Size",
			[296u] = "LPSAFEARRAY_Marshal",
			[297u] = "LPSAFEARRAY_Unmarshal",
			[298u] = "VarDecCmpR8",
			[299u] = "VarCyAdd",
			[300u] = "BSTR_UserUnmarshal64",
			[301u] = "DllCanUnloadNow",
			[302u] = "DllGetClassObject",
			[303u] = "VarCyMul",
			[304u] = "VarCyMulI4",
			[305u] = "VarCySub",
			[306u] = "VarCyAbs",
			[307u] = "VarCyFix",
			[308u] = "VarCyInt",
			[309u] = "VarCyNeg",
			[310u] = "VarCyRound",
			[311u] = "VarCyCmp",
			[312u] = "VarCyCmpR8",
			[313u] = "VarBstrCat",
			[314u] = "VarBstrCmp",
			[315u] = "VarR8Pow",
			[316u] = "VarR4CmpR8",
			[317u] = "VarR8Round",
			[318u] = "VarCat",
			[319u] = "VarDateFromUdateEx",
			[320u] = "DllRegisterServer",
			[321u] = "DllUnregisterServer",
			[322u] = "GetRecordInfoFromGuids",
			[323u] = "GetRecordInfoFromTypeInfo",
			[324u] = "LPSAFEARRAY_UserFree64",
			[325u] = "SetVarConversionLocaleSetting",
			[326u] = "GetVarConversionLocaleSetting",
			[327u] = "SetOaNoCache",
			[328u] = "LPSAFEARRAY_UserMarshal64",
			[329u] = "VarCyMulI8",
			[330u] = "VarDateFromUdate",
			[331u] = "VarUdateFromDate",
			[332u] = "GetAltMonthNames",
			[333u] = "VarI8FromUI1",
			[334u] = "VarI8FromI2",
			[335u] = "VarI8FromR4",
			[336u] = "VarI8FromR8",
			[337u] = "VarI8FromCy",
			[338u] = "VarI8FromDate",
			[339u] = "VarI8FromStr",
			[340u] = "VarI8FromDisp",
			[341u] = "VarI8FromBool",
			[342u] = "VarI8FromI1",
			[343u] = "VarI8FromUI2",
			[344u] = "VarI8FromUI4",
			[345u] = "VarI8FromDec",
			[346u] = "VarI2FromI8",
			[347u] = "VarI2FromUI8",
			[348u] = "VarI4FromI8",
			[349u] = "VarI4FromUI8",
			[350u] = "LPSAFEARRAY_UserSize64",
			[351u] = "LPSAFEARRAY_UserUnmarshal64",
			[352u] = "OACreateTypeLib2",
			[353u] = "SafeArrayAddRef",
			[354u] = "SafeArrayReleaseData",
			[355u] = "SafeArrayReleaseDescriptor",
			[356u] = "SysAddRefString",
			[357u] = "SysReleaseString",
			[358u] = "VARIANT_UserFree64",
			[359u] = "VARIANT_UserMarshal64",
			[360u] = "VarR4FromI8",
			[361u] = "VarR4FromUI8",
			[362u] = "VarR8FromI8",
			[363u] = "VarR8FromUI8",
			[364u] = "VarDateFromI8",
			[365u] = "VarDateFromUI8",
			[366u] = "VarCyFromI8",
			[367u] = "VarCyFromUI8",
			[368u] = "VarBstrFromI8",
			[369u] = "VarBstrFromUI8",
			[370u] = "VarBoolFromI8",
			[371u] = "VarBoolFromUI8",
			[372u] = "VarUI1FromI8",
			[373u] = "VarUI1FromUI8",
			[374u] = "VarDecFromI8",
			[375u] = "VarDecFromUI8",
			[376u] = "VarI1FromI8",
			[377u] = "VarI1FromUI8",
			[378u] = "VarUI2FromI8",
			[379u] = "VarUI2FromUI8",
			[380u] = "VARIANT_UserSize64",
			[381u] = "VARIANT_UserUnmarshal64",
			[401u] = "OleLoadPictureEx",
			[402u] = "OleLoadPictureFileEx",
			[411u] = "SafeArrayCreateVector",
			[412u] = "SafeArrayCopyData",
			[413u] = "VectorFromBstr",
			[414u] = "BstrFromVector",
			[415u] = "OleIconToCursor",
			[416u] = "OleCreatePropertyFrameIndirect",
			[417u] = "OleCreatePropertyFrame",
			[418u] = "OleLoadPicture",
			[419u] = "OleCreatePictureIndirect",
			[420u] = "OleCreateFontIndirect",
			[421u] = "OleTranslateColor",
			[422u] = "OleLoadPictureFile",
			[423u] = "OleSavePictureFile",
			[424u] = "OleLoadPicturePath",
			[425u] = "VarUI4FromI8",
			[426u] = "VarUI4FromUI8",
			[427u] = "VarI8FromUI8",
			[428u] = "VarUI8FromI8",
			[429u] = "VarUI8FromUI1",
			[430u] = "VarUI8FromI2",
			[431u] = "VarUI8FromR4",
			[432u] = "VarUI8FromR8",
			[433u] = "VarUI8FromCy",
			[434u] = "VarUI8FromDate",
			[435u] = "VarUI8FromStr",
			[436u] = "VarUI8FromDisp",
			[437u] = "VarUI8FromBool",
			[438u] = "VarUI8FromI1",
			[439u] = "VarUI8FromUI2",
			[440u] = "VarUI8FromUI4",
			[441u] = "VarUI8FromDec",
			[442u] = "RegisterTypeLibForUser",
			[443u] = "UnRegisterTypeLibForUser",
			[444u] = "OaEnablePerUserTLibRegistration",
			[445u] = "HWND_UserFree",
			[446u] = "HWND_UserMarshal",
			[447u] = "HWND_UserSize",
			[448u] = "HWND_UserUnmarshal",
			[449u] = "HWND_UserFree64",
			[450u] = "HWND_UserMarshal64",
			[451u] = "HWND_UserSize64",
			[452u] = "HWND_UserUnmarshal64",
			[500u] = "OACleanup"
		};

		private static readonly Dictionary<string, Dictionary<uint, string>> _staticMappings = new Dictionary<string, Dictionary<uint, string>>
		{
			["ws2_32"] = _ws2_32OrdinalMapping,
			["oleaut32"] = _oleaut32OrdinalMapping
		};

		public static DefaultSymbolResolver Instance { get; } = new DefaultSymbolResolver();


		private DefaultSymbolResolver()
		{
		}

		public ExportedSymbol? Resolve(ImportedSymbol symbol)
		{
			if (symbol.DeclaringModule?.Name == null)
			{
				return null;
			}
			string text = symbol.DeclaringModule.Name;
			if (text.EndsWith(".dll"))
			{
				text = text.Remove(text.Length - 4);
			}
			if (!_staticMappings.TryGetValue(text, out Dictionary<uint, string> value))
			{
				return null;
			}
			if (!value.TryGetValue(symbol.Ordinal, out var value2))
			{
				return null;
			}
			return new ExportedSymbol(SegmentReference.Null, value2);
		}
	}
	public sealed class EmptySymbolResolver : ISymbolResolver
	{
		public static EmptySymbolResolver Instance { get; } = new EmptySymbolResolver();


		private EmptySymbolResolver()
		{
		}

		public ExportedSymbol? Resolve(ImportedSymbol symbol)
		{
			return null;
		}
	}
	public interface IImportedModule
	{
		string? Name { get; set; }

		uint TimeDateStamp { get; set; }

		uint ForwarderChain { get; set; }

		IList<ImportedSymbol> Symbols { get; }
	}
	public class ImportedModule : IImportedModule
	{
		private IList<ImportedSymbol>? _members;

		public string? Name { get; set; }

		public uint TimeDateStamp { get; set; }

		public uint ForwarderChain { get; set; }

		public IList<ImportedSymbol> Symbols
		{
			get
			{
				if (_members == null)
				{
					Interlocked.CompareExchange(ref _members, GetSymbols(), null);
				}
				return _members;
			}
		}

		protected ImportedModule()
		{
		}

		public ImportedModule(string name)
		{
			Name = name ?? throw new ArgumentNullException("name");
		}

		public static IImportedModule? FromReader(PEReaderContext context, ref BinaryStreamReader reader)
		{
			SerializedImportedModule serializedImportedModule = new SerializedImportedModule(context, ref reader);
			if (!serializedImportedModule.IsEmpty)
			{
				return serializedImportedModule;
			}
			return null;
		}

		protected virtual IList<ImportedSymbol> GetSymbols()
		{
			return (IList<ImportedSymbol>)new OwnedCollection<IImportedModule, ImportedSymbol>((IImportedModule)this);
		}

		public override string ToString()
		{
			return Name + " (" + Symbols.Count + " symbols)";
		}
	}
	public class ImportedSymbol : IOwnedCollectionElement<IImportedModule>, ISymbol
	{
		private ushort _ordinalOrHint;

		public IImportedModule? DeclaringModule { get; private set; }

		IImportedModule? IOwnedCollectionElement<IImportedModule>.Owner
		{
			get
			{
				return DeclaringModule;
			}
			set
			{
				DeclaringModule = value;
			}
		}

		public ushort Ordinal
		{
			get
			{
				return _ordinalOrHint;
			}
			set
			{
				_ordinalOrHint = value;
				Name = null;
			}
		}

		public ushort Hint
		{
			get
			{
				return _ordinalOrHint;
			}
			set
			{
				_ordinalOrHint = value;
			}
		}

		public string? Name { get; set; }

		public ISegmentReference? AddressTableEntry { get; set; }

		public bool IsImportByOrdinal => Name == null;

		[MemberNotNullWhen(true, "Name")]
		public bool IsImportByName
		{
			[MemberNotNullWhen(true, "Name")]
			get
			{
				return Name != null;
			}
		}

		public ImportedSymbol(ushort ordinal)
		{
			Ordinal = ordinal;
		}

		public ImportedSymbol(ushort hint, string name)
		{
			Hint = hint;
			Name = name ?? throw new ArgumentNullException("name");
		}

		public override string ToString()
		{
			string text = ((DeclaringModule == null) ? string.Empty : (DeclaringModule.Name + "!"));
			string text2 = ((AddressTableEntry == null) ? "???" : ((IOffsetProvider)AddressTableEntry).Rva.ToString("X8"));
			if (!IsImportByOrdinal)
			{
				return text + Name + " (" + text2 + ")";
			}
			return text + "#" + Ordinal + " (" + text2 + ")";
		}

		public ISegmentReference? GetReference()
		{
			return AddressTableEntry;
		}
	}
	public static class ImportHash
	{
		private static readonly string[] Extensions = new string[3] { ".dll", ".sys", ".ocx" };

		public static byte[] GetImportHash(this IPEImage image)
		{
			return image.GetImportHash(DefaultSymbolResolver.Instance);
		}

		public static byte[] GetImportHash(this IPEImage image, ISymbolResolver symbolResolver)
		{
			List<string> list = new List<string>();
			for (int i = 0; i < image.Imports.Count; i++)
			{
				IImportedModule importedModule = image.Imports[i];
				string text = FormatModuleName(importedModule);
				for (int j = 0; j < importedModule.Symbols.Count; j++)
				{
					list.Add(text + "." + FormatSymbolName(importedModule.Symbols[j], symbolResolver));
				}
			}
			using MD5 mD = MD5.Create();
			return mD.ComputeHash(Encoding.ASCII.GetBytes(string.Join(",", list)));
		}

		private static string FormatModuleName(IImportedModule module)
		{
			string text = module.Name;
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			string[] extensions = Extensions;
			foreach (string text2 in extensions)
			{
				if (text.EndsWith(text2))
				{
					text = text.Remove(text.Length - text2.Length);
					break;
				}
			}
			return text.ToLowerInvariant();
		}

		private static string FormatSymbolName(ImportedSymbol symbol, ISymbolResolver symbolResolver)
		{
			if (symbol.IsImportByName)
			{
				return symbol.Name.ToLowerInvariant();
			}
			ExportedSymbol? obj = symbolResolver.Resolve(symbol) ?? throw new ArgumentException($"Failed to resolve {symbol}.");
			if (!obj.IsByName)
			{
				throw new ArgumentException($"Resolved export for {symbol} has no name.");
			}
			return obj.Name.ToLowerInvariant();
		}
	}
	public interface ISymbolResolver
	{
		ExportedSymbol? Resolve(ImportedSymbol symbol);
	}
	public class SerializedImportedModule : ImportedModule
	{
		public const uint ModuleImportSize = 20u;

		private readonly PEReaderContext _context;

		private readonly uint _originalFirstThunkRva;

		private readonly uint _firstThunkRva;

		public bool IsEmpty
		{
			get
			{
				if (_originalFirstThunkRva == 0 && base.TimeDateStamp == 0 && base.ForwarderChain == 0 && base.Name == null)
				{
					return _firstThunkRva == 0;
				}
				return false;
			}
		}

		public SerializedImportedModule(PEReaderContext context, ref BinaryStreamReader reader)
		{
			if (!((BinaryStreamReader)(ref reader)).IsValid)
			{
				throw new ArgumentNullException("reader");
			}
			_context = context ?? throw new ArgumentNullException("context");
			_originalFirstThunkRva = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			base.TimeDateStamp = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			base.ForwarderChain = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			uint num = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			_firstThunkRva = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			if (num != 0)
			{
				BinaryStreamReader val = default(BinaryStreamReader);
				if (_context.File.TryCreateReaderAtRva(num, ref val))
				{
					base.Name = ((BinaryStreamReader)(ref val)).ReadAsciiString();
				}
				else
				{
					ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Import module contains an invalid name RVA.");
				}
			}
		}

		protected override IList<ImportedSymbol> GetSymbols()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			OwnedCollection<IImportedModule, ImportedSymbol> val = new OwnedCollection<IImportedModule, ImportedSymbol>((IImportedModule)this);
			if (IsEmpty)
			{
				return (IList<ImportedSymbol>)val;
			}
			bool flag = (int)_context.File.OptionalHeader.Magic == 267;
			ulong num;
			int num2;
			if (!flag)
			{
				num = 9223372036854775808uL;
				num2 = 8;
			}
			else
			{
				num = 2147483648uL;
				num2 = 4;
			}
			BinaryStreamReader val2 = default(BinaryStreamReader);
			if (!_context.File.TryCreateReaderAtRva(_originalFirstThunkRva, ref val2) && !_context.File.TryCreateReaderAtRva(_firstThunkRva, ref val2))
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Imported module \"" + base.Name + "\" has an invalid import lookup thunk table RVA.");
				return (IList<ImportedSymbol>)val;
			}
			BinaryStreamReader val3 = default(BinaryStreamReader);
			while (true)
			{
				ulong num3 = ((BinaryStreamReader)(ref val2)).ReadNativeInt(flag);
				if (num3 == 0L)
				{
					break;
				}
				ImportedSymbol importedSymbol;
				if ((num3 & num) != 0L)
				{
					importedSymbol = new ImportedSymbol((ushort)(num3 & 0xFFFF));
				}
				else
				{
					uint num4 = (uint)(num3 & 0xFFFFFFFFu);
					if (!_context.File.TryCreateReaderAtRva(num4, ref val3))
					{
						ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Invalid Hint-Name RVA for import " + base.Name + "!#" + ((LazyList<ImportedSymbol>)(object)val).Count + ".");
						importedSymbol = new ImportedSymbol(0, "<<<INVALID_NAME_RVA>>>");
					}
					else
					{
						importedSymbol = new ImportedSymbol(((BinaryStreamReader)(ref val3)).ReadUInt16(), ((BinaryStreamReader)(ref val3)).ReadAsciiString());
					}
				}
				importedSymbol.AddressTableEntry = ((ISegmentReferenceFactory)_context.File).GetReferenceToRva((uint)(_firstThunkRva + ((LazyList<ImportedSymbol>)(object)val).Count * num2));
				((LazyList<ImportedSymbol>)(object)val).Add(importedSymbol);
			}
			return (IList<ImportedSymbol>)val;
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	public class SerializedImportedModuleList : LazyList<IImportedModule>
	{
		private readonly PEReaderContext _context;

		private readonly DataDirectory _dataDirectory;

		public SerializedImportedModuleList(PEReaderContext context, in DataDirectory dataDirectory)
		{
			//IL_001e: 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)
			_context = context ?? throw new ArgumentNullException("context");
			_dataDirectory = dataDirectory;
		}

		protected override void Initialize()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			BinaryStreamReader reader = default(BinaryStreamReader);
			if (!_context.File.TryCreateDataDirectoryReader(_dataDirectory, ref reader))
			{
				ErrorListenerExtensions.BadImage((IErrorListener)(object)_context, "Invalid import data directory RVA and/or size.");
				return;
			}
			while (true)
			{
				IImportedModule importedModule = ImportedModule.FromReader(_context, ref reader);
				if (importedModule != null)
				{
					base.Items.Add(importedModule);
					continue;
				}
				break;
			}
		}
	}
}
namespace AsmResolver.PE.Imports.Builder
{
	public class HintNameTableBuffer : SegmentBase
	{
		private readonly List<IImportedModule> _modules = new List<IImportedModule>();

		private readonly Dictionary<IImportedModule, uint> _moduleNameOffsets = new Dictionary<IImportedModule, uint>();

		private readonly Dictionary<ImportedSymbol, uint> _hintNameOffsets = new Dictionary<ImportedSymbol, uint>();

		private uint _length;

		public override void UpdateOffsets(in RelocationParameters parameters)
		{
			((SegmentBase)this).UpdateOffsets(ref parameters);
			ulong num = ((RelocationParameters)(ref parameters)).Offset;
			foreach (IImportedModule module in _modules)
			{
				foreach (ImportedSymbol symbol in module.Symbols)
				{
					if (symbol.IsImportByName)
					{
						_hintNameOffsets[symbol] = (uint)(num - ((RelocationParameters)(ref parameters)).Offset);
						num += (uint)(2 + Encoding.ASCII.GetByteCount(symbol.Name) + 1);
						num = Extensions.Align(num, 2uL);
					}
				}
				_moduleNameOffsets[module] = (uint)(num - ((RelocationParameters)(ref parameters)).Offset);
				if (module.Name != null)
				{
					num += (uint)Encoding.ASCII.GetByteCount(module.Name);
				}
				num++;
			}
			_length = (uint)(num - ((RelocationParameters)(ref parameters)).Offset);
		}

		public void AddModule(IImportedModule module)
		{
			_modules.Add(module);
		}

		public uint GetModuleNameRva(IImportedModule module)
		{
			return ((SegmentBase)this).Rva + _moduleNameOffsets[module];
		}

		public uint GetHintNameRva(ImportedSymbol member)
		{
			return ((SegmentBase)this).Rva + _hintNameOffsets[member];
		}

		public override uint GetPhysicalSize()
		{
			return _length;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			foreach (IImportedModule module in _modules)
			{
				foreach (ImportedSymbol symbol in module.Symbols)
				{
					if (symbol.IsImportByName)
					{
						WriteHintName(writer, symbol.Hint, symbol.Name);
					}
				}
				WriteModuleName(writer, module);
			}
		}

		private static void WriteHintName(IBinaryStreamWriter writer, ushort hint, string name)
		{
			writer.WriteUInt16(hint);
			IOExtensions.WriteAsciiString(writer, name);
			writer.WriteByte((byte)0);
			IOExtensions.Align(writer, 2u);
		}

		private static void WriteModuleName(IBinaryStreamWriter writer, IImportedModule module)
		{
			IOExtensions.WriteAsciiString(writer, module.Name ?? string.Empty);
			writer.WriteByte((byte)0);
		}
	}
	public interface IImportAddressProvider
	{
		uint GetThunkRva(string module, string member);
	}
	public class ImportAddressDirectoryBuffer : ImportDirectoryBufferBase
	{
		public ImportAddressDirectoryBuffer(HintNameTableBuffer hintNameTable, bool is32Bit)
			: base(hintNameTable, is32Bit)
		{
		}

		public override void UpdateOffsets(in RelocationParameters parameters)
		{
			//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)
			((SegmentBase)this).UpdateOffsets(ref parameters);
			RelocationParameters val = parameters;
			for (int i = 0; i < base.Modules.Count; i++)
			{
				IImportedModule module = base.Modules[i];
				ThunkTableBuffer moduleThunkTable = GetModuleThunkTable(module);
				uint physicalSize = ((SegmentBase)moduleThunkTable).GetPhysicalSize();
				((SegmentBase)moduleThunkTable).UpdateOffsets(ref val);
				((RelocationParameters)(ref val)).Advance(physicalSize);
			}
		}

		protected override ThunkTableBuffer CreateThunkTable()
		{
			return new ThunkTableBuffer(base.HintNameTable, base.Is32Bit, isIat: true);
		}
	}
	public class ImportDirectoryBuffer : ImportDirectoryBufferBase
	{
		private uint _entriesLength;

		public ImportAddressDirectoryBuffer ImportAddressDirectory { get; }

		public ImportDirectoryBuffer(bool is32Bit)
			: base(new HintNameTableBuffer(), is32Bit)
		{
			ImportAddressDirectory = new ImportAddressDirectoryBuffer(base.HintNameTable, is32Bit);
		}

		public override void AddModule(IImportedModule module)
		{
			if (_entriesLength == 0)
			{
				_entriesLength = 20u;
			}
			_entriesLength += 20u;
			ImportAddressDirectory.AddModule(module);
			base.AddModule(module);
			base.HintNameTable.AddModule(module);
		}

		public override void UpdateOffsets(in RelocationParameters parameters)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			((SegmentBase)this).UpdateOffsets(ref parameters);
			RelocationParameters val = ((RelocationParameters)(ref parameters)).WithAdvance(_entriesLength);
			foreach (IImportedModule module in base.Modules)
			{
				ThunkTableBuffer moduleThunkTable = GetModuleThunkTable(module);
				uint physicalSize = ((SegmentBa

folder/AsmResolver.PE.File.dll

Decompiled 11 months ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using AsmResolver.IO;
using AsmResolver.PE.File.Headers;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("AsmResolver.PE.File")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Washi 2016-2024")]
[assembly: AssemblyDescription("Raw PE file models for the AsmResolver executable file inspection toolsuite.")]
[assembly: AssemblyFileVersion("5.5.1.0")]
[assembly: AssemblyInformationalVersion("5.5.1+78ce89adebcc7e5dbeb1d4a1a35afcd513fb87a1")]
[assembly: AssemblyProduct("AsmResolver.PE.File")]
[assembly: AssemblyTitle("AsmResolver.PE.File")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Washi1337/AsmResolver")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("5.5.1.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace AsmResolver.PE.File
{
	public interface IPEFile : ISegmentReferenceFactory, IOffsetConverter
	{
		string? FilePath { get; }

		DosHeader DosHeader { get; }

		FileHeader FileHeader { get; }

		OptionalHeader OptionalHeader { get; }

		IList<PESection> Sections { get; }

		PEMappingMode MappingMode { get; }

		ISegment? ExtraSectionData { get; set; }

		ISegment? EofData { get; set; }

		PESection GetSectionContainingRva(uint rva);

		bool TryGetSectionContainingRva(uint rva, [NotNullWhen(true)] out PESection? section);

		BinaryStreamReader CreateDataDirectoryReader(DataDirectory dataDirectory);

		bool TryCreateDataDirectoryReader(DataDirectory dataDirectory, out BinaryStreamReader reader);

		BinaryStreamReader CreateReaderAtRva(uint rva);

		bool TryCreateReaderAtRva(uint rva, out BinaryStreamReader reader);

		BinaryStreamReader CreateReaderAtRva(uint rva, uint size);

		bool TryCreateReaderAtRva(uint rva, uint size, out BinaryStreamReader reader);

		BinaryStreamReader CreateReaderAtFileOffset(uint fileOffset);

		bool TryCreateReaderAtFileOffset(uint fileOffset, out BinaryStreamReader reader);

		BinaryStreamReader CreateReaderAtFileOffset(uint fileOffset, uint size);

		bool TryCreateReaderAtFileOffset(uint fileOffset, uint size, out BinaryStreamReader reader);
	}
	public class PEFile : IPEFile, ISegmentReferenceFactory, IOffsetConverter
	{
		public const uint ValidPESignature = 17744u;

		private readonly LazyVariable<PEFile, ISegment?> _extraSectionData;

		private readonly LazyVariable<PEFile, ISegment?> _eofData;

		private IList<PESection>? _sections;

		public string? FilePath { get; protected set; }

		public DosHeader DosHeader { get; set; }

		public FileHeader FileHeader { get; set; }

		public OptionalHeader OptionalHeader { get; set; }

		public IList<PESection> Sections
		{
			get
			{
				if (_sections == null)
				{
					Interlocked.CompareExchange(ref _sections, GetSections(), null);
				}
				return _sections;
			}
		}

		public PEMappingMode MappingMode { get; protected set; }

		public ISegment? ExtraSectionData
		{
			get
			{
				return _extraSectionData.GetValue(this);
			}
			set
			{
				_extraSectionData.SetValue(value);
			}
		}

		public ISegment? EofData
		{
			get
			{
				return _eofData.GetValue(this);
			}
			set
			{
				_eofData.SetValue(value);
			}
		}

		public PEFile()
			: this(new DosHeader(), new FileHeader(), new OptionalHeader())
		{
		}

		public PEFile(DosHeader dosHeader, FileHeader fileHeader, OptionalHeader optionalHeader)
		{
			DosHeader = dosHeader ?? throw new ArgumentNullException("dosHeader");
			FileHeader = fileHeader ?? throw new ArgumentNullException("fileHeader");
			OptionalHeader = optionalHeader ?? throw new ArgumentNullException("optionalHeader");
			_extraSectionData = new LazyVariable<PEFile, ISegment>((Func<PEFile, ISegment>)((PEFile x) => x.GetExtraSectionData()));
			_eofData = new LazyVariable<PEFile, ISegment>((Func<PEFile, ISegment>)((PEFile x) => x.GetEofData()));
			MappingMode = PEMappingMode.Unmapped;
		}

		public static PEFile FromFile(string path)
		{
			return FromFile(UncachedFileService.Instance.OpenFile(path));
		}

		public static PEFile FromFile(IInputFile file)
		{
			//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)
			BinaryStreamReader reader = IOExtensions.CreateReader(file);
			PEFile pEFile = FromReader(in reader);
			pEFile.FilePath = file.FilePath;
			return pEFile;
		}

		public static PEFile FromBytes(byte[] raw)
		{
			//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)
			BinaryStreamReader reader = new BinaryStreamReader(raw);
			return FromReader(in reader);
		}

		public static PEFile FromModuleBaseAddress(IntPtr hInstance)
		{
			return FromModuleBaseAddress(hInstance, PEMappingMode.Mapped);
		}

		public unsafe static PEFile FromModuleBaseAddress(IntPtr hInstance, PEMappingMode mode)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			uint num = *(uint*)((byte*)(void*)hInstance + 60);
			uint num2 = *(uint*)((byte*)(void*)hInstance + num + 4 + 20 + 56);
			return FromDataSource((IDataSource)new UnmanagedDataSource(hInstance, (ulong)num2), mode);
		}

		public static PEFile FromDataSource(IDataSource dataSource, PEMappingMode mode = PEMappingMode.Unmapped)
		{
			//IL_000f: 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)
			BinaryStreamReader reader = new BinaryStreamReader(dataSource, dataSource.BaseAddress, 0u, (uint)dataSource.Length);
			return FromReader(in reader, mode);
		}

		public static PEFile FromReader(in BinaryStreamReader reader, PEMappingMode mode = PEMappingMode.Unmapped)
		{
			return new SerializedPEFile(in reader, mode);
		}

		public ISegmentReference GetReferenceToRva(uint rva)
		{
			if (rva == 0)
			{
				return SegmentReference.Null;
			}
			return (ISegmentReference)(object)new PESegmentReference(this, rva);
		}

		public uint FileOffsetToRva(ulong fileOffset)
		{
			return GetSectionContainingOffset(fileOffset).FileOffsetToRva(fileOffset);
		}

		public ulong RvaToFileOffset(uint rva)
		{
			return GetSectionContainingRva(rva).RvaToFileOffset(rva);
		}

		public PESection GetSectionContainingOffset(ulong fileOffset)
		{
			if (!TryGetSectionContainingOffset(fileOffset, out PESection section))
			{
				throw new ArgumentOutOfRangeException("fileOffset");
			}
			return section;
		}

		public bool TryGetSectionContainingOffset(ulong fileOffset, [NotNullWhen(true)] out PESection? section)
		{
			IList<PESection> sections = Sections;
			for (int i = 0; i < sections.Count; i++)
			{
				if (sections[i].ContainsFileOffset(fileOffset))
				{
					section = sections[i];
					return true;
				}
			}
			section = null;
			return false;
		}

		public PESection GetSectionContainingRva(uint rva)
		{
			if (!TryGetSectionContainingRva(rva, out PESection section))
			{
				throw new ArgumentOutOfRangeException("rva");
			}
			return section;
		}

		public bool TryGetSectionContainingRva(uint rva, [NotNullWhen(true)] out PESection? section)
		{
			IList<PESection> sections = Sections;
			for (int i = 0; i < sections.Count; i++)
			{
				if (sections[i].ContainsRva(rva))
				{
					section = sections[i];
					return true;
				}
			}
			section = null;
			return false;
		}

		public BinaryStreamReader CreateDataDirectoryReader(DataDirectory dataDirectory)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			PESection sectionContainingRva = GetSectionContainingRva(dataDirectory.VirtualAddress);
			ulong fileOffset = sectionContainingRva.RvaToFileOffset(dataDirectory.VirtualAddress);
			return sectionContainingRva.CreateReader(fileOffset, dataDirectory.Size);
		}

		public bool TryCreateDataDirectoryReader(DataDirectory dataDirectory, out BinaryStreamReader reader)
		{
			//IL_0036: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			if (TryGetSectionContainingRva(dataDirectory.VirtualAddress, out PESection section))
			{
				ulong fileOffset = section.RvaToFileOffset(dataDirectory.VirtualAddress);
				reader = section.CreateReader(fileOffset, dataDirectory.Size);
				return true;
			}
			reader = default(BinaryStreamReader);
			return false;
		}

		public BinaryStreamReader CreateReaderAtFileOffset(uint fileOffset)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (TryCreateReaderAtFileOffset(fileOffset, out var reader))
			{
				return reader;
			}
			throw new ArgumentOutOfRangeException("fileOffset");
		}

		public bool TryCreateReaderAtFileOffset(uint fileOffset, out BinaryStreamReader reader)
		{
			//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_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (TryGetSectionContainingOffset(fileOffset, out PESection section))
			{
				reader = Extensions.CreateReader((IReadableSegment)(object)section, (ulong)fileOffset);
				return true;
			}
			ISegment? eofData = EofData;
			IReadableSegment val = (IReadableSegment)(object)((eofData is IReadableSegment) ? eofData : null);
			if (val != null && fileOffset >= ((IOffsetProvider)val).Offset && fileOffset < ((IOffsetProvider)val).Offset + ((IWritable)val).GetPhysicalSize())
			{
				reader = Extensions.CreateReader(val, (ulong)fileOffset);
				return true;
			}
			reader = default(BinaryStreamReader);
			return false;
		}

		public BinaryStreamReader CreateReaderAtFileOffset(uint fileOffset, uint size)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			return GetSectionContainingOffset(fileOffset).CreateReader(fileOffset, size);
		}

		public bool TryCreateReaderAtFileOffset(uint fileOffset, uint size, out BinaryStreamReader reader)
		{
			//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)
			//IL_005a: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			if (TryGetSectionContainingOffset(fileOffset, out PESection section))
			{
				reader = section.CreateReader(fileOffset, size);
				return true;
			}
			ISegment? eofData = EofData;
			IReadableSegment val = (IReadableSegment)(object)((eofData is IReadableSegment) ? eofData : null);
			if (val != null && fileOffset >= ((IOffsetProvider)val).Offset && fileOffset < ((IOffsetProvider)val).Offset + ((IWritable)val).GetPhysicalSize())
			{
				reader = val.CreateReader((ulong)fileOffset, size);
				return true;
			}
			reader = default(BinaryStreamReader);
			return false;
		}

		public BinaryStreamReader CreateReaderAtRva(uint rva)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			PESection sectionContainingRva = GetSectionContainingRva(rva);
			return Extensions.CreateReader((IReadableSegment)(object)sectionContainingRva, sectionContainingRva.RvaToFileOffset(rva));
		}

		public bool TryCreateReaderAtRva(uint rva, out BinaryStreamReader reader)
		{
			//IL_0021: 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_0019: Unknown result type (might be due to invalid IL or missing references)
			if (TryGetSectionContainingRva(rva, out PESection section))
			{
				reader = Extensions.CreateReader((IReadableSegment)(object)section, section.RvaToFileOffset(rva));
				return true;
			}
			reader = default(BinaryStreamReader);
			return false;
		}

		public BinaryStreamReader CreateReaderAtRva(uint rva, uint size)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			PESection sectionContainingRva = GetSectionContainingRva(rva);
			return sectionContainingRva.CreateReader(sectionContainingRva.RvaToFileOffset(rva), size);
		}

		public bool TryCreateReaderAtRva(uint rva, uint size, out BinaryStreamReader reader)
		{
			//IL_0022: 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_001a: Unknown result type (might be due to invalid IL or missing references)
			if (TryGetSectionContainingRva(rva, out PESection section))
			{
				reader = section.CreateReader(section.RvaToFileOffset(rva), size);
				return true;
			}
			reader = default(BinaryStreamReader);
			return false;
		}

		public void UpdateHeaders()
		{
			//IL_003c: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: 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_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			RelocationParameters val = default(RelocationParameters);
			((RelocationParameters)(ref val))..ctor(OptionalHeader.ImageBase, 0uL, 0u, OptionalHeader.Magic == OptionalHeaderMagic.PE32);
			FileHeader fileHeader = FileHeader;
			RelocationParameters val2 = ((RelocationParameters)(ref val)).WithAdvance(DosHeader.NextHeaderOffset + 4);
			((SegmentBase)fileHeader).UpdateOffsets(ref val2);
			OptionalHeader optionalHeader = OptionalHeader;
			val2 = ((RelocationParameters)(ref val)).WithAdvance((uint)(int)((SegmentBase)FileHeader).Offset + ((SegmentBase)FileHeader).GetPhysicalSize());
			((SegmentBase)optionalHeader).UpdateOffsets(ref val2);
			FileHeader.NumberOfSections = (ushort)Sections.Count;
			FileHeader.SizeOfOptionalHeader = (ushort)((SegmentBase)OptionalHeader).GetPhysicalSize();
			uint num = (uint)((int)((SegmentBase)OptionalHeader).Offset + FileHeader.SizeOfOptionalHeader + 40 * Sections.Count);
			ISegment? extraSectionData = ExtraSectionData;
			if (extraSectionData != null)
			{
				val2 = ((RelocationParameters)(ref val)).WithAdvance(num);
				extraSectionData.UpdateOffsets(ref val2);
			}
			ISegment? extraSectionData2 = ExtraSectionData;
			uint num2 = num + ((extraSectionData2 != null) ? ((IWritable)extraSectionData2).GetPhysicalSize() : 0);
			OptionalHeader.SizeOfHeaders = Extensions.Align(num2, OptionalHeader.FileAlignment);
			List<SectionHeader> oldHeaders = Sections.Select((PESection x) => x.CreateHeader()).ToList();
			AlignSections();
			AlignDataDirectoryEntries(oldHeaders);
			PESection pESection = Sections[Sections.Count - 1];
			OptionalHeader.SizeOfImage = pESection.Rva + Extensions.Align(pESection.GetVirtualSize(), OptionalHeader.SectionAlignment);
			ISegment? eofData = EofData;
			if (eofData != null)
			{
				val2 = ((RelocationParameters)(ref val)).WithOffsetRva(pESection.Offset + pESection.GetPhysicalSize(), OptionalHeader.SizeOfImage);
				eofData.UpdateOffsets(ref val2);
			}
		}

		public void AlignSections()
		{
			RelocationParameters parameters = default(RelocationParameters);
			((RelocationParameters)(ref parameters))..ctor(OptionalHeader.ImageBase, (ulong)Extensions.Align(OptionalHeader.SizeOfHeaders, OptionalHeader.FileAlignment), Extensions.Align(OptionalHeader.SizeOfHeaders, OptionalHeader.SectionAlignment), OptionalHeader.Magic == OptionalHeaderMagic.PE32);
			for (int i = 0; i < Sections.Count; i++)
			{
				PESection pESection = Sections[i];
				pESection.UpdateOffsets(in parameters);
				((RelocationParameters)(ref parameters)).Advance(Extensions.Align(pESection.GetPhysicalSize(), OptionalHeader.FileAlignment), Extensions.Align(pESection.GetVirtualSize(), OptionalHeader.SectionAlignment));
			}
		}

		public void AlignDataDirectoryEntries(IList<SectionHeader> oldHeaders)
		{
			IList<DataDirectory> dataDirectories = OptionalHeader.DataDirectories;
			for (int i = 0; i < dataDirectories.Count; i++)
			{
				DataDirectory dataDirectory = dataDirectories[i];
				if (!dataDirectory.IsPresentInPE)
				{
					continue;
				}
				uint virtualAddress = dataDirectory.VirtualAddress;
				for (int j = 0; j < oldHeaders.Count; j++)
				{
					SectionHeader sectionHeader = oldHeaders[j];
					if (sectionHeader.VirtualAddress <= virtualAddress && sectionHeader.VirtualAddress + sectionHeader.SizeOfRawData > virtualAddress)
					{
						if (Sections[j].Rva >= sectionHeader.VirtualAddress)
						{
							uint num = Sections[j].Rva - sectionHeader.VirtualAddress;
							virtualAddress += num;
						}
						else
						{
							uint num2 = sectionHeader.VirtualAddress - Sections[j].Rva;
							virtualAddress -= num2;
						}
						dataDirectories[i] = new DataDirectory(virtualAddress, dataDirectory.Size);
						break;
					}
				}
			}
		}

		public void Write(string filePath)
		{
			using FileStream stream = System.IO.File.Create(filePath);
			Write((Stream)stream);
		}

		public void Write(Stream stream)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			Write((IBinaryStreamWriter)new BinaryStreamWriter(stream));
		}

		public void Write(IBinaryStreamWriter writer)
		{
			UpdateHeaders();
			((SegmentBase)DosHeader).Write(writer);
			writer.Offset = DosHeader.NextHeaderOffset;
			writer.WriteUInt32(17744u);
			((SegmentBase)FileHeader).Write(writer);
			((SegmentBase)OptionalHeader).Write(writer);
			writer.Offset = ((SegmentBase)OptionalHeader).Offset + FileHeader.SizeOfOptionalHeader;
			for (int i = 0; i < Sections.Count; i++)
			{
				((SegmentBase)Sections[i].CreateHeader()).Write(writer);
			}
			ISegment? extraSectionData = ExtraSectionData;
			if (extraSectionData != null)
			{
				((IWritable)extraSectionData).Write(writer);
			}
			writer.Offset = OptionalHeader.SizeOfHeaders;
			for (int j = 0; j < Sections.Count; j++)
			{
				PESection pESection = Sections[j];
				writer.Offset = pESection.Offset;
				ISegment? contents = pESection.Contents;
				if (contents != null)
				{
					((IWritable)contents).Write(writer);
				}
				IOExtensions.Align(writer, OptionalHeader.FileAlignment);
			}
			ISegment? eofData = EofData;
			if (eofData != null)
			{
				((IWritable)eofData).Write(writer);
			}
		}

		protected virtual IList<PESection> GetSections()
		{
			return new PESectionCollection(this);
		}

		protected virtual ISegment? GetExtraSectionData()
		{
			return null;
		}

		protected virtual ISegment? GetEofData()
		{
			return null;
		}
	}
	public enum PEMappingMode
	{
		Unmapped,
		Mapped
	}
	public class PESection : IReadableSegment, ISegment, IOffsetProvider, IWritable, IOffsetConverter
	{
		private string _name;

		public PEFile? ContainingFile { get; internal set; }

		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				SectionHeader.AssertIsValidName(value);
				_name = value;
			}
		}

		public SectionFlags Characteristics { get; set; }

		public bool IsContentCode
		{
			get
			{
				return (Characteristics & SectionFlags.ContentCode) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.ContentCode) | (value ? SectionFlags.ContentCode : ((SectionFlags)0u));
			}
		}

		public bool IsContentInitializedData
		{
			get
			{
				return (Characteristics & SectionFlags.ContentInitializedData) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.ContentInitializedData) | (value ? SectionFlags.ContentInitializedData : ((SectionFlags)0u));
			}
		}

		public bool IsContentUninitializedData
		{
			get
			{
				return (Characteristics & SectionFlags.ContentUninitializedData) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.ContentUninitializedData) | (value ? SectionFlags.ContentUninitializedData : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryDiscardable
		{
			get
			{
				return (Characteristics & SectionFlags.MemoryDiscardable) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryDiscardable) | (value ? SectionFlags.MemoryDiscardable : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryNotCached
		{
			get
			{
				return (Characteristics & SectionFlags.MemoryNotCached) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryNotCached) | (value ? SectionFlags.MemoryNotCached : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryNotPaged
		{
			get
			{
				return (Characteristics & SectionFlags.MemoryNotPaged) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryNotPaged) | (value ? SectionFlags.MemoryNotPaged : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryShared
		{
			get
			{
				return (Characteristics & SectionFlags.MemoryShared) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryShared) | (value ? SectionFlags.MemoryShared : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryExecute
		{
			get
			{
				return (Characteristics & SectionFlags.MemoryExecute) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryExecute) | (value ? SectionFlags.MemoryExecute : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryRead
		{
			get
			{
				return (Characteristics & SectionFlags.MemoryRead) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryRead) | (value ? SectionFlags.MemoryRead : ((SectionFlags)0u));
			}
		}

		public bool IsMemoryWrite
		{
			get
			{
				return ((uint)Characteristics & 0x80000000u) != 0;
			}
			set
			{
				Characteristics = (Characteristics & ~SectionFlags.MemoryWrite) | (value ? SectionFlags.MemoryWrite : ((SectionFlags)0u));
			}
		}

		public ISegment? Contents { get; set; }

		[MemberNotNullWhen(true, "Contents")]
		public bool IsReadable
		{
			[MemberNotNullWhen(true, "Contents")]
			get
			{
				ISegment? contents = Contents;
				VirtualSegment val = (VirtualSegment)(object)((contents is VirtualSegment) ? contents : null);
				if (val == null)
				{
					return Contents is IReadableSegment;
				}
				return val.IsReadable;
			}
		}

		public ulong Offset
		{
			get
			{
				ISegment? contents = Contents;
				if (contents == null)
				{
					return 0uL;
				}
				return ((IOffsetProvider)contents).Offset;
			}
		}

		public uint Rva
		{
			get
			{
				ISegment? contents = Contents;
				if (contents == null)
				{
					return 0u;
				}
				return ((IOffsetProvider)contents).Rva;
			}
		}

		public bool CanUpdateOffsets => true;

		public PESection(string name, SectionFlags characteristics)
		{
			SectionHeader.AssertIsValidName(name);
			_name = name;
			Characteristics = characteristics;
		}

		public PESection(string name, SectionFlags characteristics, ISegment? contents)
		{
			SectionHeader.AssertIsValidName(name);
			_name = name;
			Characteristics = characteristics;
			Contents = contents;
		}

		public PESection(PESection section)
			: this(section.Name, section.Characteristics, section.Contents)
		{
		}

		public PESection(SectionHeader header, ISegment contents)
		{
			_name = header.Name;
			Characteristics = header.Characteristics;
			Contents = contents;
		}

		public void UpdateOffsets(in RelocationParameters parameters)
		{
			ISegment? contents = Contents;
			if (contents != null)
			{
				contents.UpdateOffsets(ref parameters);
			}
		}

		public uint GetPhysicalSize()
		{
			ISegment? contents = Contents;
			if (contents == null)
			{
				return 0u;
			}
			return ((IWritable)contents).GetPhysicalSize();
		}

		public uint GetVirtualSize()
		{
			ISegment? contents = Contents;
			if (contents == null)
			{
				return 0u;
			}
			return contents.GetVirtualSize();
		}

		public BinaryStreamReader CreateReader(ulong fileOffset, uint size)
		{
			//IL_0019: 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 (!IsReadable)
			{
				throw new InvalidOperationException("Section contents is not readable.");
			}
			return ((IReadableSegment)Contents).CreateReader(fileOffset, size);
		}

		public SectionHeader CreateHeader()
		{
			uint num = ContainingFile?.OptionalHeader.FileAlignment ?? 512;
			return new SectionHeader(Name, Characteristics)
			{
				PointerToRawData = (uint)Offset,
				SizeOfRawData = Extensions.Align(GetPhysicalSize(), num),
				VirtualAddress = Rva,
				VirtualSize = GetVirtualSize(),
				NumberOfRelocations = 0,
				PointerToRelocations = 0u,
				NumberOfLineNumbers = 0,
				PointerToLineNumbers = 0u
			};
		}

		public bool ContainsFileOffset(ulong fileOffset)
		{
			if (Offset <= fileOffset)
			{
				return fileOffset < Offset + GetPhysicalSize();
			}
			return false;
		}

		public bool ContainsRva(uint rva)
		{
			if (Rva <= rva)
			{
				return rva < Rva + GetVirtualSize();
			}
			return false;
		}

		public uint FileOffsetToRva(ulong fileOffset)
		{
			if (!ContainsFileOffset(fileOffset))
			{
				throw new ArgumentOutOfRangeException("fileOffset");
			}
			return (uint)(fileOffset - Offset + Rva);
		}

		public ulong RvaToFileOffset(uint rva)
		{
			if (!ContainsRva(rva))
			{
				throw new ArgumentOutOfRangeException("rva");
			}
			return rva - Rva + Offset;
		}

		public override string ToString()
		{
			return Name;
		}

		public void Write(IBinaryStreamWriter writer)
		{
			ISegment? contents = Contents;
			if (contents != null)
			{
				((IWritable)contents).Write(writer);
			}
		}

		void ISegment.UpdateOffsets(in RelocationParameters parameters)
		{
			UpdateOffsets(in parameters);
		}
	}
	public class PESectionCollection : Collection<PESection>
	{
		public PEFile Owner { get; }

		public PESectionCollection(PEFile owner)
		{
			Owner = owner ?? throw new ArgumentNullException("owner");
		}

		private void AssertHasNoOwner(PESection section)
		{
			if (section.ContainingFile != null)
			{
				throw new ArgumentException("Section was already added to another portable executable file.");
			}
		}

		protected override void ClearItems()
		{
			foreach (PESection item in base.Items)
			{
				item.ContainingFile = null;
			}
			base.ClearItems();
		}

		protected override void InsertItem(int index, PESection item)
		{
			AssertHasNoOwner(item);
			base.InsertItem(index, item);
			item.ContainingFile = Owner;
		}

		protected override void SetItem(int index, PESection item)
		{
			AssertHasNoOwner(item);
			RemoveItem(index);
			InsertItem(index, item);
		}

		protected override void RemoveItem(int index)
		{
			base.Items[index].ContainingFile = null;
			base.RemoveItem(index);
		}
	}
	public sealed class PESegmentReference : ISegmentReference, IOffsetProvider
	{
		private readonly IPEFile _peFile;

		public ulong Offset
		{
			get
			{
				if (!_peFile.TryGetSectionContainingRva(Rva, out PESection _))
				{
					return 0uL;
				}
				return ((IOffsetConverter)_peFile).RvaToFileOffset(Rva);
			}
		}

		public uint Rva { get; }

		public bool CanRead
		{
			get
			{
				if (_peFile.TryGetSectionContainingRva(Rva, out PESection section))
				{
					return section.IsReadable;
				}
				return false;
			}
		}

		public bool IsBounded => false;

		public bool IsValidAddress
		{
			get
			{
				PESection section;
				return _peFile.TryGetSectionContainingRva(Rva, out section);
			}
		}

		internal PESegmentReference(IPEFile peFile, uint rva)
		{
			_peFile = peFile;
			Rva = rva;
		}

		public BinaryStreamReader CreateReader()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return _peFile.CreateReaderAtRva(Rva);
		}

		public ISegment? GetSegment()
		{
			throw new InvalidOperationException();
		}

		public override string ToString()
		{
			return $"0x{Rva:X8}";
		}
	}
	public class SerializedPEFile : PEFile
	{
		private readonly List<SectionHeader> _sectionHeaders;

		private readonly BinaryStreamReader _reader;

		private readonly ulong _originalImageBase;

		private readonly bool _is32Bit;

		public SerializedPEFile(in BinaryStreamReader reader, PEMappingMode mode)
		{
			//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)
			_reader = reader;
			base.MappingMode = mode;
			base.DosHeader = AsmResolver.PE.File.Headers.DosHeader.FromReader(ref _reader);
			((BinaryStreamReader)(ref _reader)).Offset = ((SegmentBase)base.DosHeader).Offset + base.DosHeader.NextHeaderOffset;
			if (((BinaryStreamReader)(ref _reader)).ReadUInt32() != 17744)
			{
				throw new BadImageFormatException();
			}
			base.FileHeader = AsmResolver.PE.File.Headers.FileHeader.FromReader(ref _reader);
			base.OptionalHeader = AsmResolver.PE.File.Headers.OptionalHeader.FromReader(ref _reader);
			_originalImageBase = base.OptionalHeader.ImageBase;
			_is32Bit = base.OptionalHeader.Magic == OptionalHeaderMagic.PE32;
			((BinaryStreamReader)(ref _reader)).Offset = ((SegmentBase)base.OptionalHeader).Offset + base.FileHeader.SizeOfOptionalHeader;
			_sectionHeaders = new List<SectionHeader>(base.FileHeader.NumberOfSections);
			for (int i = 0; i < base.FileHeader.NumberOfSections; i++)
			{
				_sectionHeaders.Add(SectionHeader.FromReader(ref _reader));
			}
			int num = (int)(((SegmentBase)base.DosHeader).Offset + base.OptionalHeader.SizeOfHeaders - ((BinaryStreamReader)(ref _reader)).Offset);
			if (num != 0)
			{
				base.ExtraSectionData = (ISegment?)(object)((BinaryStreamReader)(ref _reader)).ReadSegment((uint)num);
			}
		}

		protected unsafe override IList<PESection> GetSections()
		{
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00cf: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			PESectionCollection pESectionCollection = new PESectionCollection(this);
			for (int i = 0; i < _sectionHeaders.Count; i++)
			{
				SectionHeader sectionHeader = _sectionHeaders[i];
				object obj = base.MappingMode switch
				{
					PEMappingMode.Unmapped => (((BinaryStreamReader)(ref _reader)).StartOffset + sectionHeader.PointerToRawData, sectionHeader.SizeOfRawData), 
					PEMappingMode.Mapped => (((BinaryStreamReader)(ref _reader)).StartOffset + sectionHeader.VirtualAddress, sectionHeader.VirtualSize), 
					_ => throw new ArgumentOutOfRangeException(), 
				};
				ulong item = ((ValueTuple<ulong, uint>*)(&obj))->Item1;
				uint item2 = ((ValueTuple<ulong, uint>*)(&obj))->Item2;
				ISegment val = null;
				if (item2 != 0)
				{
					val = (ISegment)new DataSourceSegment(((BinaryStreamReader)(ref _reader)).DataSource, item, sectionHeader.VirtualAddress, item2);
				}
				VirtualSegment val2 = new VirtualSegment(val, sectionHeader.VirtualSize);
				RelocationParameters val3 = new RelocationParameters(_originalImageBase, item, sectionHeader.VirtualAddress, _is32Bit);
				val2.UpdateOffsets(ref val3);
				pESectionCollection.Add(new PESection(sectionHeader, (ISegment)(object)val2));
			}
			return pESectionCollection;
		}

		protected override ISegment? GetEofData()
		{
			//IL_0039: 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)
			if (base.MappingMode != 0)
			{
				return null;
			}
			SectionHeader sectionHeader = _sectionHeaders[_sectionHeaders.Count - 1];
			ulong num = sectionHeader.PointerToRawData + sectionHeader.SizeOfRawData;
			BinaryStreamReader val = ((BinaryStreamReader)(ref _reader)).ForkAbsolute(num);
			if (((BinaryStreamReader)(ref val)).Length == 0)
			{
				return null;
			}
			return (ISegment?)(object)((BinaryStreamReader)(ref val)).ReadSegment(((BinaryStreamReader)(ref val)).Length);
		}
	}
}
namespace AsmResolver.PE.File.Headers
{
	[Flags]
	public enum Characteristics : ushort
	{
		RelocsStripped = 1,
		Image = 2,
		LineNumsStripped = 4,
		LocalSymsStripped = 8,
		AggressiveWsTrim = 0x10,
		LargeAddressAware = 0x20,
		BytesReversedLo = 0x80,
		Machine32Bit = 0x100,
		DebugStripped = 0x200,
		RemovableRunFromSwap = 0x400,
		NetRunFromSwap = 0x800,
		System = 0x1000,
		Dll = 0x2000,
		UpSystemOnly = 0x4000,
		BytesReversedHi = 0x8000
	}
	public readonly struct DataDirectory : IWritable
	{
		public const uint DataDirectorySize = 8u;

		public uint VirtualAddress { get; }

		public uint Size { get; }

		public bool IsPresentInPE
		{
			get
			{
				if (VirtualAddress == 0)
				{
					return Size != 0;
				}
				return true;
			}
		}

		public static DataDirectory FromReader(ref BinaryStreamReader reader)
		{
			return new DataDirectory(((BinaryStreamReader)(ref reader)).ReadUInt32(), ((BinaryStreamReader)(ref reader)).ReadUInt32());
		}

		public DataDirectory(uint virtualAddress, uint size)
		{
			VirtualAddress = virtualAddress;
			Size = size;
		}

		public uint GetPhysicalSize()
		{
			return 8u;
		}

		public void Write(IBinaryStreamWriter writer)
		{
			writer.WriteUInt32(VirtualAddress);
			writer.WriteUInt32(Size);
		}

		public void Deconstruct(out uint virtualAddress, out uint size)
		{
			virtualAddress = VirtualAddress;
			size = Size;
		}

		public override string ToString()
		{
			return $"RVA: 0x{VirtualAddress:X8}, Size: 0x{Size:X8}";
		}
	}
	public enum DataDirectoryIndex
	{
		ExportDirectory,
		ImportDirectory,
		ResourceDirectory,
		ExceptionDirectory,
		CertificateDirectory,
		BaseRelocationDirectory,
		DebugDirectory,
		ArchitectureDirectory,
		GlobalPtrDirectory,
		TlsDirectory,
		LoadConfigDirectory,
		BoundImportDirectory,
		IatDirectory,
		DelayImportDescrDirectory,
		ClrDirectory,
		ReservedDirectory
	}
	[Flags]
	public enum DllCharacteristics
	{
		HighEntropyVA = 0x20,
		DynamicBase = 0x40,
		ForceIntegrity = 0x80,
		NxCompat = 0x100,
		NoIsolation = 0x200,
		NoSeh = 0x400,
		NoBind = 0x800,
		AppContainer = 0x1000,
		WdmDriver = 0x2000,
		ControlFLowGuard = 0x4000,
		TerminalServerAware = 0x8000
	}
	public class DosHeader : SegmentBase
	{
		public const ushort ValidPEMagic = 23117;

		public const int MinimalDosHeaderLength = 64;

		public const int NextHeaderFieldOffset = 60;

		public const int DefaultNewHeaderOffset = 128;

		private static readonly byte[] DefaultDosHeader = new byte[128]
		{
			77, 90, 144, 0, 3, 0, 0, 0, 4, 0,
			0, 0, 255, 255, 0, 0, 184, 0, 0, 0,
			0, 0, 0, 0, 64, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			128, 0, 0, 0, 14, 31, 186, 14, 0, 180,
			9, 205, 33, 184, 1, 76, 205, 33, 84, 104,
			105, 115, 32, 112, 114, 111, 103, 114, 97, 109,
			32, 99, 97, 110, 110, 111, 116, 32, 98, 101,
			32, 114, 117, 110, 32, 105, 110, 32, 68, 79,
			83, 32, 109, 111, 100, 101, 46, 13, 13, 10,
			36, 0, 0, 0, 0, 0, 0, 0
		};

		private readonly byte[] _stub;

		public uint NextHeaderOffset { get; set; }

		public static DosHeader FromReader(ref BinaryStreamReader reader)
		{
			ulong offset = ((BinaryStreamReader)(ref reader)).Offset;
			uint rva = ((BinaryStreamReader)(ref reader)).Rva;
			byte[] array = new byte[128];
			if (((BinaryStreamReader)(ref reader)).ReadUInt16() != 23117)
			{
				throw new BadImageFormatException();
			}
			((BinaryStreamReader)(ref reader)).Offset = ((BinaryStreamReader)(ref reader)).Offset + 58;
			uint num = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			if (num != 128)
			{
				Array.Resize(ref array, (int)num);
			}
			((BinaryStreamReader)(ref reader)).Offset = ((BinaryStreamReader)(ref reader)).Offset - 64;
			((BinaryStreamReader)(ref reader)).ReadBytes(array, 0, array.Length);
			DosHeader dosHeader = new DosHeader(array);
			((SegmentBase)dosHeader).Offset = offset;
			((SegmentBase)dosHeader).Rva = rva;
			dosHeader.NextHeaderOffset = num;
			return dosHeader;
		}

		public DosHeader()
			: this(DefaultDosHeader)
		{
			NextHeaderOffset = 128u;
		}

		private DosHeader(byte[] stub)
		{
			_stub = stub ?? throw new ArgumentNullException("stub");
		}

		public override uint GetPhysicalSize()
		{
			return (uint)_stub.Length;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			writer.WriteBytes(_stub, 0, 60);
			writer.WriteUInt32(NextHeaderOffset);
			writer.WriteBytes(_stub, 64, _stub.Length - 60 - 4);
		}
	}
	public class FileHeader : SegmentBase
	{
		public const int FileHeaderSize = 20;

		public MachineType Machine { get; set; } = MachineType.I386;


		public ushort NumberOfSections { get; set; }

		public uint TimeDateStamp { get; set; }

		public uint PointerToSymbolTable { get; set; }

		public uint NumberOfSymbols { get; set; }

		public ushort SizeOfOptionalHeader { get; set; } = 224;


		public Characteristics Characteristics { get; set; } = Characteristics.Image | Characteristics.Machine32Bit;


		public static FileHeader FromReader(ref BinaryStreamReader reader)
		{
			FileHeader fileHeader = new FileHeader();
			((SegmentBase)fileHeader).Offset = ((BinaryStreamReader)(ref reader)).Offset;
			((SegmentBase)fileHeader).Rva = ((BinaryStreamReader)(ref reader)).Rva;
			fileHeader.Machine = (MachineType)((BinaryStreamReader)(ref reader)).ReadUInt16();
			fileHeader.NumberOfSections = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			fileHeader.TimeDateStamp = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			fileHeader.PointerToSymbolTable = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			fileHeader.NumberOfSymbols = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			fileHeader.SizeOfOptionalHeader = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			fileHeader.Characteristics = (Characteristics)((BinaryStreamReader)(ref reader)).ReadUInt16();
			return fileHeader;
		}

		public override uint GetPhysicalSize()
		{
			return 20u;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			writer.WriteUInt16((ushort)Machine);
			writer.WriteUInt16(NumberOfSections);
			writer.WriteUInt32(TimeDateStamp);
			writer.WriteUInt32(PointerToSymbolTable);
			writer.WriteUInt32(NumberOfSymbols);
			writer.WriteUInt16(SizeOfOptionalHeader);
			writer.WriteUInt16((ushort)Characteristics);
		}
	}
	public enum MachineType : ushort
	{
		Unknown = 0,
		DotNetAppleOSOverride = 17988,
		DotNetFreeBsdOSOverride = 44484,
		DotNetLinuxOSOverride = 31609,
		DotNetNetBsdOSOverride = 6547,
		DotNetSunOSOverride = 6546,
		Am33 = 467,
		Amd64 = 34404,
		Amd64DotNetApple = 49184,
		Amd64DotNetFreeBsd = 11168,
		Amd64DotNetLinux = 64797,
		Amd64DotNetNetBsd = 40951,
		Amd64DotNetSun = 40950,
		Arm = 448,
		ArmNt = 452,
		ArmNtDotNetApple = 18304,
		ArmNtDotNetFreeBsd = 44032,
		ArmNtDotNetLinux = 31421,
		ArmNtDotNetNetBsd = 6231,
		Arm64 = 43620,
		Arm64DotNetApple = 60448,
		Arm64DotNetFreeBsd = 1952,
		Arm64DotNetLinux = 53533,
		Arm64DotNetNetBsd = 46071,
		Ebc = 3772,
		I386 = 332,
		I386DotNetApple = 18184,
		I386DotNetFreeBsd = 44168,
		I386DotNetLinux = 31285,
		I386DotNetNetBsd = 6367,
		I386DotNetSun = 6366,
		Ia64 = 512,
		M32R = 36929,
		Mips16 = 614,
		MipsFpu = 870,
		MipsFpu16 = 1126,
		PowerPc = 496,
		PowerPcFp = 497,
		R4000 = 358,
		Sh3 = 418,
		Sh3Dsp = 419,
		Sh4 = 422,
		Sh5 = 424,
		Thumb = 450,
		WceMipsV2 = 361,
		RiscV32 = 20530,
		RiscV64 = 20580,
		RiscV128 = 20776
	}
	public class OptionalHeader : SegmentBase
	{
		public const uint OptionalHeaderSizeOfImageFieldOffset = 56u;

		public const uint OptionalHeader32SizeExcludingDataDirectories = 96u;

		public const uint OptionalHeader64SizeExcludingDataDirectories = 112u;

		public const int DefaultNumberOfRvasAndSizes = 16;

		public OptionalHeaderMagic Magic { get; set; } = OptionalHeaderMagic.PE32;


		public byte MajorLinkerVersion { get; set; } = 48;


		public byte MinorLinkerVersion { get; set; } = 24;


		public uint SizeOfCode { get; set; }

		public uint SizeOfInitializedData { get; set; }

		public uint SizeOfUninitializedData { get; set; }

		public uint AddressOfEntryPoint { get; set; }

		public uint BaseOfCode { get; set; }

		public uint BaseOfData { get; set; }

		public ulong ImageBase { get; set; } = 4194304uL;


		public uint SectionAlignment { get; set; } = 8192u;


		public uint FileAlignment { get; set; } = 512u;


		public ushort MajorOperatingSystemVersion { get; set; } = 4;


		public ushort MinorOperatingSystemVersion { get; set; }

		public ushort MajorImageVersion { get; set; }

		public ushort MinorImageVersion { get; set; }

		public ushort MajorSubsystemVersion { get; set; } = 4;


		public ushort MinorSubsystemVersion { get; set; }

		public uint Win32VersionValue { get; set; }

		public uint SizeOfImage { get; set; }

		public uint SizeOfHeaders { get; set; }

		public uint CheckSum { get; set; }

		public SubSystem SubSystem { get; set; } = SubSystem.WindowsCui;


		public DllCharacteristics DllCharacteristics { get; set; } = DllCharacteristics.DynamicBase | DllCharacteristics.NxCompat | DllCharacteristics.TerminalServerAware;


		public ulong SizeOfStackReserve { get; set; } = 16777216uL;


		public ulong SizeOfStackCommit { get; set; } = 4096uL;


		public ulong SizeOfHeapReserve { get; set; } = 16777216uL;


		public ulong SizeOfHeapCommit { get; set; } = 4096uL;


		public uint LoaderFlags { get; set; }

		public uint NumberOfRvaAndSizes { get; set; } = 16u;


		public IList<DataDirectory> DataDirectories { get; } = new DataDirectory[16].ToList();


		public static OptionalHeader FromReader(ref BinaryStreamReader reader, bool ignoreNumberOfRvasAndSizes = true)
		{
			OptionalHeader optionalHeader = new OptionalHeader();
			((SegmentBase)optionalHeader).Offset = ((BinaryStreamReader)(ref reader)).Offset;
			((SegmentBase)optionalHeader).Rva = ((BinaryStreamReader)(ref reader)).Rva;
			optionalHeader.Magic = (OptionalHeaderMagic)((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader.MajorLinkerVersion = ((BinaryStreamReader)(ref reader)).ReadByte();
			optionalHeader.MinorLinkerVersion = ((BinaryStreamReader)(ref reader)).ReadByte();
			optionalHeader.SizeOfCode = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader.SizeOfInitializedData = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader.SizeOfUninitializedData = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader.AddressOfEntryPoint = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader.BaseOfCode = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			OptionalHeader optionalHeader2 = optionalHeader;
			switch (optionalHeader2.Magic)
			{
			case OptionalHeaderMagic.PE32:
				optionalHeader2.BaseOfData = ((BinaryStreamReader)(ref reader)).ReadUInt32();
				optionalHeader2.ImageBase = ((BinaryStreamReader)(ref reader)).ReadUInt32();
				break;
			case OptionalHeaderMagic.PE32Plus:
				optionalHeader2.ImageBase = ((BinaryStreamReader)(ref reader)).ReadUInt64();
				break;
			default:
				throw new BadImageFormatException("Unrecognized or unsupported optional header format.");
			}
			optionalHeader2.SectionAlignment = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.FileAlignment = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.MajorOperatingSystemVersion = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.MinorOperatingSystemVersion = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.MajorImageVersion = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.MinorImageVersion = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.MajorSubsystemVersion = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.MinorSubsystemVersion = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.Win32VersionValue = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.SizeOfImage = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.SizeOfHeaders = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.CheckSum = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.SubSystem = (SubSystem)((BinaryStreamReader)(ref reader)).ReadUInt16();
			optionalHeader2.DllCharacteristics = (DllCharacteristics)((BinaryStreamReader)(ref reader)).ReadUInt16();
			if (optionalHeader2.Magic == OptionalHeaderMagic.PE32)
			{
				optionalHeader2.SizeOfStackReserve = ((BinaryStreamReader)(ref reader)).ReadUInt32();
				optionalHeader2.SizeOfStackCommit = ((BinaryStreamReader)(ref reader)).ReadUInt32();
				optionalHeader2.SizeOfHeapReserve = ((BinaryStreamReader)(ref reader)).ReadUInt32();
				optionalHeader2.SizeOfHeapCommit = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			}
			else
			{
				optionalHeader2.SizeOfStackReserve = ((BinaryStreamReader)(ref reader)).ReadUInt64();
				optionalHeader2.SizeOfStackCommit = ((BinaryStreamReader)(ref reader)).ReadUInt64();
				optionalHeader2.SizeOfHeapReserve = ((BinaryStreamReader)(ref reader)).ReadUInt64();
				optionalHeader2.SizeOfHeapCommit = ((BinaryStreamReader)(ref reader)).ReadUInt64();
			}
			optionalHeader2.LoaderFlags = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			optionalHeader2.NumberOfRvaAndSizes = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			int num = (int)(ignoreNumberOfRvasAndSizes ? 16 : optionalHeader2.NumberOfRvaAndSizes);
			optionalHeader2.DataDirectories.Clear();
			for (int i = 0; i < num; i++)
			{
				optionalHeader2.DataDirectories.Add(DataDirectory.FromReader(ref reader));
			}
			return optionalHeader2;
		}

		public DataDirectory GetDataDirectory(DataDirectoryIndex index)
		{
			return DataDirectories[(int)index];
		}

		public void SetDataDirectory(DataDirectoryIndex index, DataDirectory directory)
		{
			DataDirectories[(int)index] = directory;
		}

		public override uint GetPhysicalSize()
		{
			if (Magic != OptionalHeaderMagic.PE32)
			{
				return 240u;
			}
			return 224u;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			ulong offset = writer.Offset;
			writer.WriteUInt16((ushort)Magic);
			writer.WriteByte(MajorLinkerVersion);
			writer.WriteByte(MinorLinkerVersion);
			writer.WriteUInt32(SizeOfCode);
			writer.WriteUInt32(SizeOfInitializedData);
			writer.WriteUInt32(SizeOfUninitializedData);
			writer.WriteUInt32(AddressOfEntryPoint);
			writer.WriteUInt32(BaseOfCode);
			switch (Magic)
			{
			case OptionalHeaderMagic.PE32:
				writer.WriteUInt32(BaseOfData);
				writer.WriteUInt32((uint)ImageBase);
				break;
			case OptionalHeaderMagic.PE32Plus:
				writer.WriteUInt64(ImageBase);
				break;
			default:
				throw new BadImageFormatException("Unrecognized or unsupported optional header format.");
			}
			writer.WriteUInt32(SectionAlignment);
			writer.WriteUInt32(FileAlignment);
			writer.WriteUInt16(MajorOperatingSystemVersion);
			writer.WriteUInt16(MinorOperatingSystemVersion);
			writer.WriteUInt16(MajorImageVersion);
			writer.WriteUInt16(MinorImageVersion);
			writer.WriteUInt16(MajorSubsystemVersion);
			writer.WriteUInt16(MinorSubsystemVersion);
			writer.WriteUInt32(Win32VersionValue);
			writer.WriteUInt32(SizeOfImage);
			writer.WriteUInt32(SizeOfHeaders);
			writer.WriteUInt32(CheckSum);
			writer.WriteUInt16((ushort)SubSystem);
			writer.WriteUInt16((ushort)DllCharacteristics);
			if (Magic == OptionalHeaderMagic.PE32)
			{
				writer.WriteUInt32((uint)SizeOfStackReserve);
				writer.WriteUInt32((uint)SizeOfStackCommit);
				writer.WriteUInt32((uint)SizeOfHeapReserve);
				writer.WriteUInt32((uint)SizeOfHeapCommit);
			}
			else
			{
				writer.WriteUInt64(SizeOfStackReserve);
				writer.WriteUInt64(SizeOfStackCommit);
				writer.WriteUInt64(SizeOfHeapReserve);
				writer.WriteUInt64(SizeOfHeapCommit);
			}
			writer.WriteUInt32(LoaderFlags);
			writer.WriteUInt32(NumberOfRvaAndSizes);
			foreach (DataDirectory dataDirectory in DataDirectories)
			{
				dataDirectory.Write(writer);
			}
			IOExtensions.WriteZeroes(writer, (int)(((SegmentBase)this).GetPhysicalSize() - (writer.Offset - offset)));
		}
	}
	public enum OptionalHeaderMagic : ushort
	{
		PE32 = 267,
		PE32Plus = 523,
		PE64 = 523
	}
	[Flags]
	public enum SectionFlags : uint
	{
		TypeDsect = 1u,
		TypeNoLoad = 2u,
		TypeGroup = 4u,
		TypeNoPadded = 8u,
		TypeCopy = 0x10u,
		ContentCode = 0x20u,
		ContentInitializedData = 0x40u,
		ContentUninitializedData = 0x80u,
		LinkOther = 0x100u,
		LinkInfo = 0x200u,
		TypeOver = 0x400u,
		LinkRemove = 0x800u,
		LinkComDat = 0x1000u,
		NoDeferSpecExceptions = 0x4000u,
		RelativeGp = 0x8000u,
		MemPurgeable = 0x20000u,
		Memory16Bit = 0x20000u,
		MemoryLocked = 0x40000u,
		MemoryPreload = 0x80000u,
		Align1Bytes = 0x100000u,
		Align2Bytes = 0x200000u,
		Align4Bytes = 0x300000u,
		Align8Bytes = 0x400000u,
		Align16Bytes = 0x500000u,
		Align32Bytes = 0x600000u,
		Align64Bytes = 0x700000u,
		Align128Bytes = 0x800000u,
		Align256Bytes = 0x900000u,
		Align512Bytes = 0xA00000u,
		Align1024Bytes = 0xB00000u,
		Align2048Bytes = 0xC00000u,
		Align4096Bytes = 0xD00000u,
		Align8192Bytes = 0xE00000u,
		LinkExtendedRelocationOverflow = 0x1000000u,
		MemoryDiscardable = 0x2000000u,
		MemoryNotCached = 0x4000000u,
		MemoryNotPaged = 0x8000000u,
		MemoryShared = 0x10000000u,
		MemoryExecute = 0x20000000u,
		MemoryRead = 0x40000000u,
		MemoryWrite = 0x80000000u
	}
	public class SectionHeader : SegmentBase, IOffsetConverter
	{
		public const uint SectionHeaderSize = 40u;

		private string _name;

		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				if (Encoding.UTF8.GetByteCount(value) > 8)
				{
					throw new ArgumentException("Name is too long.");
				}
				_name = value;
			}
		}

		public uint VirtualSize { get; set; }

		public uint VirtualAddress { get; set; }

		public uint SizeOfRawData { get; set; }

		public uint PointerToRawData { get; set; }

		public uint PointerToRelocations { get; set; }

		public uint PointerToLineNumbers { get; set; }

		public ushort NumberOfRelocations { get; set; }

		public ushort NumberOfLineNumbers { get; set; }

		public SectionFlags Characteristics { get; set; }

		public SectionHeader(string name, SectionFlags characteristics)
		{
			AssertIsValidName(name);
			_name = name;
			Characteristics = characteristics;
		}

		public SectionHeader(SectionHeader value)
		{
			((SegmentBase)this).Offset = ((SegmentBase)value).Offset;
			((SegmentBase)this).Rva = ((SegmentBase)value).Rva;
			_name = value.Name;
			VirtualSize = value.VirtualSize;
			VirtualAddress = value.VirtualAddress;
			SizeOfRawData = value.SizeOfRawData;
			PointerToRawData = value.PointerToRawData;
			PointerToRelocations = value.PointerToRelocations;
			PointerToLineNumbers = value.PointerToLineNumbers;
			NumberOfRelocations = value.NumberOfRelocations;
			NumberOfLineNumbers = value.NumberOfLineNumbers;
			Characteristics = value.Characteristics;
		}

		public static SectionHeader FromReader(ref BinaryStreamReader reader)
		{
			ulong offset = ((BinaryStreamReader)(ref reader)).Offset;
			uint rva = ((BinaryStreamReader)(ref reader)).Rva;
			byte[] array = new byte[8];
			((BinaryStreamReader)(ref reader)).ReadBytes(array, 0, array.Length);
			string text = Encoding.UTF8.GetString(array).Replace("\ufffd", "");
			int num = text.IndexOf('\0');
			if (num >= 0)
			{
				text = text.Remove(num);
			}
			SectionHeader sectionHeader = new SectionHeader(text, (SectionFlags)0u);
			((SegmentBase)sectionHeader).Offset = offset;
			((SegmentBase)sectionHeader).Rva = rva;
			sectionHeader.VirtualSize = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			sectionHeader.VirtualAddress = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			sectionHeader.SizeOfRawData = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			sectionHeader.PointerToRawData = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			sectionHeader.PointerToRelocations = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			sectionHeader.PointerToLineNumbers = ((BinaryStreamReader)(ref reader)).ReadUInt32();
			sectionHeader.NumberOfRelocations = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			sectionHeader.NumberOfLineNumbers = ((BinaryStreamReader)(ref reader)).ReadUInt16();
			sectionHeader.Characteristics = (SectionFlags)((BinaryStreamReader)(ref reader)).ReadUInt32();
			return sectionHeader;
		}

		public override uint GetPhysicalSize()
		{
			return 40u;
		}

		public bool ContainsFileOffset(ulong fileOffset)
		{
			if (PointerToRawData <= fileOffset)
			{
				return fileOffset < PointerToRawData + SizeOfRawData;
			}
			return false;
		}

		public bool ContainsRva(uint rva)
		{
			if (VirtualAddress <= rva)
			{
				return rva < VirtualAddress + VirtualSize;
			}
			return false;
		}

		public uint FileOffsetToRva(ulong fileOffset)
		{
			if (!ContainsFileOffset(fileOffset))
			{
				throw new ArgumentOutOfRangeException("fileOffset");
			}
			return (uint)(fileOffset - PointerToRawData + VirtualAddress);
		}

		public ulong RvaToFileOffset(uint rva)
		{
			if (!ContainsRva(rva))
			{
				throw new ArgumentOutOfRangeException("rva");
			}
			return rva - VirtualAddress + PointerToRawData;
		}

		public override void Write(IBinaryStreamWriter writer)
		{
			byte[] bytes = Encoding.UTF8.GetBytes(Name);
			IOExtensions.WriteBytes(writer, bytes);
			IOExtensions.WriteZeroes(writer, 8 - bytes.Length);
			writer.WriteUInt32(VirtualSize);
			writer.WriteUInt32(VirtualAddress);
			writer.WriteUInt32(SizeOfRawData);
			writer.WriteUInt32(PointerToRawData);
			writer.WriteUInt32(PointerToRelocations);
			writer.WriteUInt32(PointerToLineNumbers);
			writer.WriteUInt16(NumberOfRelocations);
			writer.WriteUInt16(NumberOfLineNumbers);
			writer.WriteUInt32((uint)Characteristics);
		}

		public override string ToString()
		{
			return string.Format("{0} ({1}: {2:X8}, ", Name, "VirtualAddress", VirtualAddress) + string.Format("{0}: {1:X8}, ", "VirtualSize", VirtualSize) + string.Format("{0}: {1:X8}, ", "PointerToRawData", PointerToRawData) + string.Format("{0}: {1:X8}, ", "SizeOfRawData", SizeOfRawData) + string.Format("{0}: {1})", "Characteristics", Characteristics);
		}

		internal static void AssertIsValidName(string value)
		{
			if (Encoding.UTF8.GetByteCount(value) > 8)
			{
				throw new ArgumentException("Section name cannot be longer than 8 characters.");
			}
		}
	}
	public enum SubSystem
	{
		Unknown = 0,
		Native = 1,
		WindowsGui = 2,
		WindowsCui = 3,
		PosixCui = 7,
		NativeWindows = 8,
		WindowsCeGui = 9,
		EfiApplication = 10,
		EfiBootServiceDriver = 11,
		EfiRuntime = 12,
		EfiRom = 13,
		Xbox = 14,
		WindowsBootApplication = 16
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
}

folder/BepInEx.AssemblyPublicizer.dll

Decompiled 11 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using AsmResolver;
using AsmResolver.DotNet;
using AsmResolver.DotNet.Builder;
using AsmResolver.DotNet.Code.Cil;
using AsmResolver.DotNet.Serialized;
using AsmResolver.DotNet.Signatures;
using AsmResolver.DotNet.Signatures.Types;
using AsmResolver.IO;
using AsmResolver.PE;
using AsmResolver.PE.Builder;
using AsmResolver.PE.DotNet.Builder;
using AsmResolver.PE.DotNet.Cil;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("BepInEx")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Yet another assembly publicizer/stripper")]
[assembly: AssemblyFileVersion("0.4.3.0")]
[assembly: AssemblyInformationalVersion("0.4.3+874cfb60160c053cbefc7277f5f0cb6f7a732748")]
[assembly: AssemblyProduct("BepInEx.AssemblyPublicizer")]
[assembly: AssemblyTitle("BepInEx.AssemblyPublicizer")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/BepInEx/BepInEx.AssemblyPublicizer")]
[assembly: AssemblyVersion("0.4.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace BepInEx.AssemblyPublicizer
{
	public static class AssemblyPublicizer
	{
		public static void Publicize(string assemblyPath, string outputPath, AssemblyPublicizerOptions? options = null)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			AssemblyDefinition val = FatalAsmResolver.FromFile(assemblyPath);
			ModuleDefinition obj = val.ManifestModule ?? throw new NullReferenceException();
			obj.MetadataResolver = (IMetadataResolver)new DefaultMetadataResolver((IAssemblyResolver)(object)NoopAssemblyResolver.Instance);
			Publicize(val, options);
			obj.FatalWrite(outputPath);
		}

		public static AssemblyDefinition Publicize(AssemblyDefinition assembly, AssemblyPublicizerOptions? options = null)
		{
			if (options == null)
			{
				options = new AssemblyPublicizerOptions();
			}
			ModuleDefinition manifestModule = assembly.ManifestModule;
			OriginalAttributesAttribute originalAttributesAttribute = (options.IncludeOriginalAttributesAttribute ? new OriginalAttributesAttribute(manifestModule) : null);
			foreach (TypeDefinition allType in manifestModule.GetAllTypes())
			{
				if (originalAttributesAttribute == null || allType != originalAttributesAttribute.Type)
				{
					Publicize(allType, originalAttributesAttribute, options);
				}
			}
			return assembly;
		}

		private static void Publicize(TypeDefinition typeDefinition, OriginalAttributesAttribute? attribute, AssemblyPublicizerOptions options)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: 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)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0043: Expected O, but got Unknown
			//IL_004a: 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_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_024c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			if (options.Strip && !typeDefinition.IsEnum && !typeDefinition.IsInterface)
			{
				foreach (MethodDefinition method in typeDefinition.Methods)
				{
					if (method.HasMethodBody)
					{
						CilMethodBody val = new CilMethodBody(method);
						CilMethodBody val2 = val;
						method.CilMethodBody = val;
						val2.Instructions.Add(CilOpCodes.Ldnull);
						val2.Instructions.Add(CilOpCodes.Throw);
						method.NoInlining = true;
					}
				}
			}
			if (!options.PublicizeCompilerGenerated && HasCustomAttributeExtensions.IsCompilerGenerated((IHasCustomAttribute)(object)typeDefinition))
			{
				return;
			}
			if (options.HasTarget(PublicizeTarget.Types) && ((!typeDefinition.IsNested && !typeDefinition.IsPublic) || (typeDefinition.IsNested && !typeDefinition.IsNestedPublic)))
			{
				if (attribute != null)
				{
					typeDefinition.CustomAttributes.Add(attribute.ToCustomAttribute((TypeAttributes)(typeDefinition.Attributes & 7)));
				}
				typeDefinition.Attributes = (TypeAttributes)(typeDefinition.Attributes & -8);
				typeDefinition.Attributes = (TypeAttributes)(typeDefinition.Attributes | ((!typeDefinition.IsNested) ? 1 : 2));
			}
			if (options.HasTarget(PublicizeTarget.Methods))
			{
				foreach (MethodDefinition method2 in typeDefinition.Methods)
				{
					Publicize(method2, attribute, options);
				}
				if (!options.PublicizeCompilerGenerated)
				{
					foreach (PropertyDefinition property in typeDefinition.Properties)
					{
						if (!HasCustomAttributeExtensions.IsCompilerGenerated((IHasCustomAttribute)(object)property))
						{
							MethodDefinition getMethod = property.GetMethod;
							if (getMethod != null)
							{
								Publicize(getMethod, attribute, options, ignoreCompilerGeneratedCheck: true);
							}
							MethodDefinition setMethod = property.SetMethod;
							if (setMethod != null)
							{
								Publicize(setMethod, attribute, options, ignoreCompilerGeneratedCheck: true);
							}
						}
					}
				}
			}
			if (!options.HasTarget(PublicizeTarget.Fields))
			{
				return;
			}
			HashSet<Utf8String> hashSet = new HashSet<Utf8String>(typeDefinition.Events.Select((EventDefinition e) => e.Name));
			foreach (FieldDefinition field in typeDefinition.Fields)
			{
				if (!field.IsPrivateScope && !field.IsPublic && !hashSet.Contains(field.Name) && (options.PublicizeCompilerGenerated || !HasCustomAttributeExtensions.IsCompilerGenerated((IHasCustomAttribute)(object)field)))
				{
					if (attribute != null)
					{
						field.CustomAttributes.Add(attribute.ToCustomAttribute((FieldAttributes)(field.Attributes & 7)));
					}
					field.Attributes = (FieldAttributes)(field.Attributes & 0xFFF8);
					field.Attributes = (FieldAttributes)(field.Attributes | 6);
				}
			}
		}

		private static void Publicize(MethodDefinition methodDefinition, OriginalAttributesAttribute? attribute, AssemblyPublicizerOptions options, bool ignoreCompilerGeneratedCheck = false)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: 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_008b: 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_003d: Unknown result type (might be due to invalid IL or missing references)
			if (methodDefinition.IsCompilerControlled)
			{
				return;
			}
			if (methodDefinition != null && methodDefinition.IsVirtual && methodDefinition.IsFinal && methodDefinition.DeclaringType != null)
			{
				foreach (MethodImplementation methodImplementation in methodDefinition.DeclaringType.MethodImplementations)
				{
					MethodImplementation current = methodImplementation;
					if (((MethodImplementation)(ref current)).Body == methodDefinition)
					{
						return;
					}
				}
			}
			if (!methodDefinition.IsPublic && (ignoreCompilerGeneratedCheck || options.PublicizeCompilerGenerated || !HasCustomAttributeExtensions.IsCompilerGenerated((IHasCustomAttribute)(object)methodDefinition)))
			{
				if (attribute != null)
				{
					methodDefinition.CustomAttributes.Add(attribute.ToCustomAttribute((MethodAttributes)(methodDefinition.Attributes & 7)));
				}
				methodDefinition.Attributes = (MethodAttributes)(methodDefinition.Attributes & 0xFFF8);
				methodDefinition.Attributes = (MethodAttributes)(methodDefinition.Attributes | 6);
			}
		}
	}
	public class AssemblyPublicizerOptions
	{
		public PublicizeTarget Target { get; set; } = PublicizeTarget.All;


		public bool PublicizeCompilerGenerated { get; set; }

		public bool IncludeOriginalAttributesAttribute { get; set; } = true;


		public bool Strip { get; set; }

		internal bool HasTarget(PublicizeTarget target)
		{
			return (Target & target) != 0;
		}
	}
	[Flags]
	public enum PublicizeTarget
	{
		All = 7,
		None = 0,
		Types = 1,
		Methods = 2,
		Fields = 4
	}
	internal static class FatalAsmResolver
	{
		private sealed class FatalThrowErrorListener : IErrorListener
		{
			public static FatalThrowErrorListener Instance { get; } = new FatalThrowErrorListener();


			public IList<Exception> Exceptions { get; } = new List<Exception>();


			public void MarkAsFatal()
			{
				throw new AggregateException(Exceptions);
			}

			public void RegisterException(Exception exception)
			{
				Exceptions.Add(exception);
			}
		}

		public static AssemblyDefinition FromFile(string filePath)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			return AssemblyDefinition.FromImage(PEImage.FromFile(filePath), new ModuleReaderParameters((IErrorListener)(object)FatalThrowErrorListener.Instance));
		}

		public static void FatalWrite(this ModuleDefinition module, string filePath)
		{
			//IL_0000: 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_0048: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			PEImageBuildResult val = new ManagedPEImageBuilder().CreateImage(module);
			if (val.HasFailed)
			{
				FatalThrowErrorListener fatalThrowErrorListener = (FatalThrowErrorListener)(object)val.ErrorListener;
				throw new AggregateException("Construction of the PE image failed with one or more errors.", fatalThrowErrorListener.Exceptions);
			}
			using FileStream fileStream = File.Create(filePath);
			((PEFileBuilderBase<ManagedPEBuilderContext>)new ManagedPEFileBuilder()).CreateFile(val.ConstructedImage).Write((IBinaryStreamWriter)new BinaryStreamWriter((Stream)fileStream));
		}
	}
	internal class NoopAssemblyResolver : IAssemblyResolver
	{
		internal static NoopAssemblyResolver Instance { get; } = new NoopAssemblyResolver();


		public AssemblyDefinition? Resolve(AssemblyDescriptor assembly)
		{
			return null;
		}

		public void AddToCache(AssemblyDescriptor descriptor, AssemblyDefinition definition)
		{
		}

		public bool RemoveFromCache(AssemblyDescriptor descriptor)
		{
			return false;
		}

		public bool HasCached(AssemblyDescriptor descriptor)
		{
			return false;
		}

		public void ClearCache()
		{
		}
	}
	internal class OriginalAttributesAttribute
	{
		private static Dictionary<PublicizeTarget, string> _typeNames = new Dictionary<PublicizeTarget, string>
		{
			[PublicizeTarget.Types] = "TypeAttributes",
			[PublicizeTarget.Methods] = "MethodAttributes",
			[PublicizeTarget.Fields] = "FieldAttributes"
		};

		private Dictionary<PublicizeTarget, TypeSignature> _attributesTypes = new Dictionary<PublicizeTarget, TypeSignature>();

		private Dictionary<PublicizeTarget, MethodDefinition> _constructors = new Dictionary<PublicizeTarget, MethodDefinition>();

		public TypeDefinition Type { get; }

		public OriginalAttributesAttribute(ModuleDefinition module)
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Expected O, but got Unknown
			//IL_0149: Expected O, but got Unknown
			//IL_0151: 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_0173: Unknown result type (might be due to invalid IL or missing references)
			IResolutionScope corLibScope = module.CorLibTypeFactory.CorLibScope;
			ITypeDefOrRef val = TypeDescriptorExtensions.CreateTypeReference(corLibScope, "System", "Attribute").ImportWith(module.DefaultImporter);
			MemberReference val2 = TypeDescriptorExtensions.CreateMemberReference((IMemberRefParent)(object)val, ".ctor", (MemberSignature)(object)MethodSignature.CreateInstance((TypeSignature)(object)module.CorLibTypeFactory.Void)).ImportWith(module.DefaultImporter);
			Type = new TypeDefinition(Utf8String.op_Implicit("BepInEx.AssemblyPublicizer"), Utf8String.op_Implicit("OriginalAttributesAttribute"), (TypeAttributes)256, val);
			module.TopLevelTypes.Add(Type);
			foreach (KeyValuePair<PublicizeTarget, string> typeName in _typeNames)
			{
				TypeSignature val4 = (_attributesTypes[typeName.Key] = ((ITypeDescriptor)TypeDescriptorExtensions.CreateTypeReference(corLibScope, "System.Reflection", typeName.Value).ImportWith(module.DefaultImporter)).ToTypeSignature());
				TypeSignature val5 = val4;
				MethodDefinition val6 = new MethodDefinition(Utf8String.op_Implicit(".ctor"), (MethodAttributes)6278, MethodSignature.CreateInstance((TypeSignature)(object)module.CorLibTypeFactory.Void, (TypeSignature[])(object)new TypeSignature[1] { val5 }));
				Type.Methods.Add(val6);
				CilMethodBody val7 = new CilMethodBody(val6);
				CilMethodBody val8 = val7;
				val6.CilMethodBody = val7;
				val8.Instructions.Add(CilOpCodes.Ldarg_0);
				val8.Instructions.Add(CilOpCodes.Call, val2);
				val8.Instructions.Add(CilOpCodes.Ret);
				_constructors[typeName.Key] = val6;
			}
		}

		private CustomAttribute ToCustomAttribute(PublicizeTarget target, int value)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			return new CustomAttribute((ICustomAttributeType)(object)_constructors[target], new CustomAttributeSignature((CustomAttributeArgument[])(object)new CustomAttributeArgument[1]
			{
				new CustomAttributeArgument(_attributesTypes[target], (object)value)
			}));
		}

		public CustomAttribute ToCustomAttribute(TypeAttributes attributes)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected I4, but got Unknown
			return ToCustomAttribute(PublicizeTarget.Types, (int)attributes);
		}

		public CustomAttribute ToCustomAttribute(MethodAttributes attributes)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected I4, but got Unknown
			return ToCustomAttribute(PublicizeTarget.Methods, (int)attributes);
		}

		public CustomAttribute ToCustomAttribute(FieldAttributes attributes)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected I4, but got Unknown
			return ToCustomAttribute(PublicizeTarget.Fields, (int)attributes);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[ExcludeFromCodeCoverage]
	[DebuggerNonUserCode]
	internal static class IsExternalInit
	{
	}
}

folder/MdsAutoPublicize.dll

Decompiled 11 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.AssemblyPublicizer;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("MdsAutoPublicize")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+8e94abf77f2c8824852b81fc2955d2baf0b993de")]
[assembly: AssemblyProduct("MdsAutoPublicize")]
[assembly: AssemblyTitle("MdsAutoPublicize")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace MdsAutoPublicize
{
	[BepInPlugin("Edsil.MdsAutoPublicize", "MdsAutoPublicize", "1.0.1")]
	public class BepinexLoader : BaseUnityPlugin
	{
		public const string MODNAME = "MdsAutoPublicize";

		public const string AUTHOR = "Edsil";

		public const string GUID = "Edsil.MdsAutoPublicize";

		public const string VERSION = "1.0.1";

		public void Awake()
		{
			((Component)this).gameObject.SetActive(false);
			DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location));
			if (!TryFindParent(directoryInfo, "BepInEx", out DirectoryInfo info))
			{
				throw new Exception("No Bepinex folder found???");
			}
			string text = Path.Combine(info.FullName, "BepInEx.AssemblyPublicizer.Publicized");
			string text2 = Path.Combine(directoryInfo.FullName, "BepInEx.AssemblyPublicizer.Wrapper", "BepInEx.AssemblyPublicizer.Wrapper.exe");
			string text3 = Path.Combine(Application.dataPath, "Managed");
			FileInfo fileInfo = new FileInfo(Path.Combine(text3, "Assembly-CSharp.dll"));
			string path = Path.Combine(text, $"_{fileInfo.Length}_{fileInfo.CreationTime.Ticks}.txt");
			if (File.Exists(path))
			{
				((BaseUnityPlugin)this).Logger.LogMessage((object)"Check file for auto publicizing found. Do nothing.");
				return;
			}
			((BaseUnityPlugin)this).Logger.LogWarning((object)"No publicized game files exist! Starting the auto publicizer.");
			try
			{
				Run(text3, Path.GetFileName(path), text);
			}
			catch (Exception arg)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)$"Something went wrong, while starting the publicizer:\n{arg}");
			}
		}

		private void ReadProcessOutput(StreamReader processReader)
		{
			while (!processReader.EndOfStream)
			{
				((BaseUnityPlugin)this).Logger.LogMessage((object)processReader.ReadLine());
			}
		}

		private bool TryFindParent(DirectoryInfo dir, string findName, out DirectoryInfo info)
		{
			if (dir == null)
			{
				info = null;
				return false;
			}
			if (dir.Name != findName)
			{
				return TryFindParent(dir.Parent, findName, out info);
			}
			info = dir;
			return true;
		}

		private void Run(string managedFolder, string writeFileOnFinish, string outputFolder)
		{
			DateTime now = DateTime.Now;
			((BaseUnityPlugin)this).Logger.LogMessage((object)("Start publicizing all files from " + managedFolder + " into " + outputFolder));
			if (Directory.Exists(outputFolder))
			{
				((BaseUnityPlugin)this).Logger.LogMessage((object)"Removing old publicized gamefiles.");
				try
				{
					Directory.Delete(outputFolder, recursive: true);
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogMessage((object)"Failed deleting existing publicized files, stop execution.");
					((BaseUnityPlugin)this).Logger.LogMessage((object)("Exception:\n" + ex.ToString()));
					return;
				}
				((BaseUnityPlugin)this).Logger.LogMessage((object)"============================================");
			}
			DirectoryInfo directoryInfo = Directory.CreateDirectory(outputFolder);
			foreach (string item in Directory.EnumerateFiles(managedFolder))
			{
				DateTime now2 = DateTime.Now;
				string fileName = Path.GetFileName(item);
				try
				{
					if (fileName == "ICSharpCode.SharpZipLib.dll")
					{
						File.Copy(item, Path.Combine(outputFolder, fileName));
					}
					else
					{
						AssemblyPublicizer.Publicize(item, Path.Combine(outputFolder, fileName), (AssemblyPublicizerOptions)null);
					}
				}
				catch (Exception ex2)
				{
					((BaseUnityPlugin)this).Logger.LogMessage((object)"Error while publicizing assembly.");
					((BaseUnityPlugin)this).Logger.LogMessage((object)ex2);
					continue;
				}
				TimeSpan timeSpan = DateTime.Now - now2;
				((BaseUnityPlugin)this).Logger.LogMessage((object)("Publicized " + timeSpan.TotalSeconds.ToString("0.000") + " seconds for " + fileName));
			}
			((BaseUnityPlugin)this).Logger.LogMessage((object)("Writing check file " + writeFileOnFinish));
			File.WriteAllText(Path.Combine(outputFolder, writeFileOnFinish), "This file is used, to check if the Assembly-CSharp file has still the same MetaData as last game start.\nIf this file gets deleted or does not fit anymore, the publicizing process gets started.");
			TimeSpan timeSpan2 = DateTime.Now - now;
			((BaseUnityPlugin)this).Logger.LogMessage((object)("Completed publicizing all game files in " + timeSpan2.TotalSeconds.ToString("0.000") + " seconds."));
		}
	}
}

folder/Microsoft.Bcl.AsyncInterfaces.dll

Decompiled 11 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides the IAsyncEnumerable<T> and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.\r\n\r\nCommonly Used Types:\r\nSystem.IAsyncDisposable\r\nSystem.Collections.Generic.IAsyncEnumerable\r\nSystem.Collections.Generic.IAsyncEnumerator")]
[assembly: AssemblyFileVersion("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("6.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
}
namespace System
{
	public interface IAsyncDisposable
	{
		ValueTask DisposeAsync();
	}
}
namespace System.Collections.Generic
{
	public interface IAsyncEnumerable<out T>
	{
		IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken));
	}
	public interface IAsyncEnumerator<out T> : IAsyncDisposable
	{
		T Current { get; }

		ValueTask<bool> MoveNextAsync();
	}
}
namespace System.Runtime.CompilerServices
{
	[StructLayout(LayoutKind.Auto)]
	public struct AsyncIteratorMethodBuilder
	{
		private AsyncTaskMethodBuilder _methodBuilder;

		private object _id;

		internal object ObjectIdForDebugger => _id ?? Interlocked.CompareExchange(ref _id, new object(), null) ?? _id;

		public static AsyncIteratorMethodBuilder Create()
		{
			AsyncIteratorMethodBuilder result = default(AsyncIteratorMethodBuilder);
			result._methodBuilder = AsyncTaskMethodBuilder.Create();
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void MoveNext<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.Start(ref stateMachine);
		}

		public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
		}

		public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			_methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
		}

		public void Complete()
		{
			_methodBuilder.SetResult();
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
	public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute
	{
		public AsyncIteratorStateMachineAttribute(Type stateMachineType)
			: base(stateMachineType)
		{
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct ConfiguredAsyncDisposable
	{
		private readonly IAsyncDisposable _source;

		private readonly bool _continueOnCapturedContext;

		internal ConfiguredAsyncDisposable(IAsyncDisposable source, bool continueOnCapturedContext)
		{
			_source = source;
			_continueOnCapturedContext = continueOnCapturedContext;
		}

		public ConfiguredValueTaskAwaitable DisposeAsync()
		{
			return _source.DisposeAsync().ConfigureAwait(_continueOnCapturedContext);
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct ConfiguredCancelableAsyncEnumerable<T>
	{
		[StructLayout(LayoutKind.Auto)]
		public readonly struct Enumerator
		{
			private readonly IAsyncEnumerator<T> _enumerator;

			private readonly bool _continueOnCapturedContext;

			public T Current => _enumerator.Current;

			internal Enumerator(IAsyncEnumerator<T> enumerator, bool continueOnCapturedContext)
			{
				_enumerator = enumerator;
				_continueOnCapturedContext = continueOnCapturedContext;
			}

			public ConfiguredValueTaskAwaitable<bool> MoveNextAsync()
			{
				return _enumerator.MoveNextAsync().ConfigureAwait(_continueOnCapturedContext);
			}

			public ConfiguredValueTaskAwaitable DisposeAsync()
			{
				return _enumerator.DisposeAsync().ConfigureAwait(_continueOnCapturedContext);
			}
		}

		private readonly IAsyncEnumerable<T> _enumerable;

		private readonly CancellationToken _cancellationToken;

		private readonly bool _continueOnCapturedContext;

		internal ConfiguredCancelableAsyncEnumerable(IAsyncEnumerable<T> enumerable, bool continueOnCapturedContext, CancellationToken cancellationToken)
		{
			_enumerable = enumerable;
			_continueOnCapturedContext = continueOnCapturedContext;
			_cancellationToken = cancellationToken;
		}

		public ConfiguredCancelableAsyncEnumerable<T> ConfigureAwait(bool continueOnCapturedContext)
		{
			return new ConfiguredCancelableAsyncEnumerable<T>(_enumerable, continueOnCapturedContext, _cancellationToken);
		}

		public ConfiguredCancelableAsyncEnumerable<T> WithCancellation(CancellationToken cancellationToken)
		{
			return new ConfiguredCancelableAsyncEnumerable<T>(_enumerable, _continueOnCapturedContext, cancellationToken);
		}

		public Enumerator GetAsyncEnumerator()
		{
			return new Enumerator(_enumerable.GetAsyncEnumerator(_cancellationToken), _continueOnCapturedContext);
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	public sealed class EnumeratorCancellationAttribute : Attribute
	{
	}
}
namespace System.Threading.Tasks
{
	public static class TaskAsyncEnumerableExtensions
	{
		public static ConfiguredAsyncDisposable ConfigureAwait(this IAsyncDisposable source, bool continueOnCapturedContext)
		{
			return new ConfiguredAsyncDisposable(source, continueOnCapturedContext);
		}

		public static ConfiguredCancelableAsyncEnumerable<T> ConfigureAwait<T>(this IAsyncEnumerable<T> source, bool continueOnCapturedContext)
		{
			return new ConfiguredCancelableAsyncEnumerable<T>(source, continueOnCapturedContext, default(CancellationToken));
		}

		public static ConfiguredCancelableAsyncEnumerable<T> WithCancellation<T>(this IAsyncEnumerable<T> source, CancellationToken cancellationToken)
		{
			return new ConfiguredCancelableAsyncEnumerable<T>(source, continueOnCapturedContext: true, cancellationToken);
		}
	}
}
namespace System.Threading.Tasks.Sources
{
	[StructLayout(LayoutKind.Auto)]
	public struct ManualResetValueTaskSourceCore<TResult>
	{
		private Action<object> _continuation;

		private object _continuationState;

		private ExecutionContext _executionContext;

		private object _capturedContext;

		private bool _completed;

		private TResult _result;

		private ExceptionDispatchInfo _error;

		private short _version;

		public bool RunContinuationsAsynchronously { get; set; }

		public short Version => _version;

		public void Reset()
		{
			_version++;
			_completed = false;
			_result = default(TResult);
			_error = null;
			_executionContext = null;
			_capturedContext = null;
			_continuation = null;
			_continuationState = null;
		}

		public void SetResult(TResult result)
		{
			_result = result;
			SignalCompletion();
		}

		public void SetException(Exception error)
		{
			_error = ExceptionDispatchInfo.Capture(error);
			SignalCompletion();
		}

		public ValueTaskSourceStatus GetStatus(short token)
		{
			ValidateToken(token);
			if (_continuation != null && _completed)
			{
				if (_error != null)
				{
					if (!(_error.SourceException is OperationCanceledException))
					{
						return ValueTaskSourceStatus.Faulted;
					}
					return ValueTaskSourceStatus.Canceled;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		public TResult GetResult(short token)
		{
			ValidateToken(token);
			if (!_completed)
			{
				throw new InvalidOperationException();
			}
			_error?.Throw();
			return _result;
		}

		public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
		{
			if (continuation == null)
			{
				throw new ArgumentNullException("continuation");
			}
			ValidateToken(token);
			if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
			{
				_executionContext = ExecutionContext.Capture();
			}
			if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
			{
				SynchronizationContext current = SynchronizationContext.Current;
				if (current != null && current.GetType() != typeof(SynchronizationContext))
				{
					_capturedContext = current;
				}
				else
				{
					TaskScheduler current2 = TaskScheduler.Current;
					if (current2 != TaskScheduler.Default)
					{
						_capturedContext = current2;
					}
				}
			}
			object obj = _continuation;
			if (obj == null)
			{
				_continuationState = state;
				obj = Interlocked.CompareExchange(ref _continuation, continuation, null);
			}
			if (obj == null)
			{
				return;
			}
			if (obj != System.Threading.Tasks.Sources.ManualResetValueTaskSourceCoreShared.s_sentinel)
			{
				throw new InvalidOperationException();
			}
			object capturedContext = _capturedContext;
			if (capturedContext != null)
			{
				if (!(capturedContext is SynchronizationContext synchronizationContext))
				{
					if (capturedContext is TaskScheduler scheduler)
					{
						Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler);
					}
				}
				else
				{
					synchronizationContext.Post(delegate(object s)
					{
						Tuple<Action<object>, object> tuple = (Tuple<Action<object>, object>)s;
						tuple.Item1(tuple.Item2);
					}, Tuple.Create(continuation, state));
				}
			}
			else
			{
				Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
			}
		}

		private void ValidateToken(short token)
		{
			if (token != _version)
			{
				throw new InvalidOperationException();
			}
		}

		private void SignalCompletion()
		{
			if (_completed)
			{
				throw new InvalidOperationException();
			}
			_completed = true;
			if (_continuation == null && Interlocked.CompareExchange(ref _continuation, System.Threading.Tasks.Sources.ManualResetValueTaskSourceCoreShared.s_sentinel, null) == null)
			{
				return;
			}
			if (_executionContext != null)
			{
				ExecutionContext.Run(_executionContext, delegate(object s)
				{
					((ManualResetValueTaskSourceCore<TResult>)s).InvokeContinuation();
				}, this);
			}
			else
			{
				InvokeContinuation();
			}
		}

		private void InvokeContinuation()
		{
			object capturedContext = _capturedContext;
			if (capturedContext != null)
			{
				if (!(capturedContext is SynchronizationContext synchronizationContext))
				{
					if (capturedContext is TaskScheduler scheduler)
					{
						Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, scheduler);
					}
				}
				else
				{
					synchronizationContext.Post(delegate(object s)
					{
						Tuple<Action<object>, object> tuple = (Tuple<Action<object>, object>)s;
						tuple.Item1(tuple.Item2);
					}, Tuple.Create(_continuation, _continuationState));
				}
			}
			else if (RunContinuationsAsynchronously)
			{
				Task.Factory.StartNew(_continuation, _continuationState, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
			}
			else
			{
				_continuation(_continuationState);
			}
		}
	}
	internal static class ManualResetValueTaskSourceCoreShared
	{
		internal static readonly Action<object> s_sentinel = CompletionSentinel;

		private static void CompletionSentinel(object _)
		{
			throw new InvalidOperationException();
		}
	}
}

folder/Microsoft.Build.Framework.dll

Decompiled 11 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Markup;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Eventing;
using Microsoft.Build.Execution;
using Microsoft.Build.Experimental.BuildCheck;
using Microsoft.Build.Framework;
using Microsoft.Build.Framework.BuildException;
using Microsoft.Build.Framework.Internal;
using Microsoft.Build.Framework.Logging;
using Microsoft.Build.Framework.Profiler;
using Microsoft.Build.Shared;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Collections.Internal;
using Microsoft.VisualStudio.Setup.Configuration;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Build.Framework.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.Tasks.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("Microsoft.Build.Utilities.Core, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("Microsoft.Build.Tasks.Core, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("MSBuild, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("Microsoft.Build.Engine.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.BuildCheck.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.Engine.OM.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.Utilities.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.CommandLine.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.Build.UnitTests.Shared, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: Guid("D8A9BA71-4724-481d-9CA7-0DA23A1D615C")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/build/2009/properties", "Microsoft.Build.Framework.XamlTypes")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
[assembly: NeutralResourcesLanguage("en")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Microsoft.Build.Framework.dll")]
[assembly: AssemblyFileVersion("17.13.9.7704")]
[assembly: AssemblyInformationalVersion("17.13.9+e0f243f1e205c45b3b04097facd9948a881f9047")]
[assembly: AssemblyProduct("Microsoft® Build Tools®")]
[assembly: AssemblyTitle("Microsoft.Build.Framework.dll")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/msbuild")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("15.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
internal sealed class StringSyntaxAttribute : Attribute
{
	public const string CompositeFormat = "CompositeFormat";

	public const string DateOnlyFormat = "DateOnlyFormat";

	public const string DateTimeFormat = "DateTimeFormat";

	public const string EnumFormat = "EnumFormat";

	public const string GuidFormat = "GuidFormat";

	public const string Json = "Json";

	public const string NumericFormat = "NumericFormat";

	public const string Regex = "Regex";

	public const string TimeOnlyFormat = "TimeOnlyFormat";

	public const string TimeSpanFormat = "TimeSpanFormat";

	public const string Uri = "Uri";

	public const string Xml = "Xml";

	public string Syntax { get; }

	public object?[] Arguments { get; }

	public StringSyntaxAttribute(string syntax)
	{
		Syntax = syntax;
		Arguments = Array.Empty<object>();
	}

	public StringSyntaxAttribute(string syntax, params object?[] arguments)
	{
		Syntax = syntax;
		Arguments = arguments;
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
	internal class SupportedOSPlatformGuard : Attribute
	{
		internal SupportedOSPlatformGuard(string platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property)]
	internal class SupportedOSPlatform : Attribute
	{
		internal SupportedOSPlatform(string platformName)
		{
		}
	}
}
namespace System.Runtime.CompilerServices
{
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Linq
{
	internal static class RoslynEnumerable
	{
		public static SegmentedList<TSource> ToSegmentedList<TSource>(this IEnumerable<TSource> source)
		{
			if (source == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
			}
			return new SegmentedList<TSource>(source);
		}
	}
}
namespace Microsoft.Build
{
	internal abstract class BinaryReaderFactory
	{
		public abstract BinaryReader Create(Stream stream);
	}
}
namespace Microsoft.Build.Eventing
{
	[EventSource(Name = "Microsoft-Build")]
	internal sealed class MSBuildEventSource : EventSource
	{
		public static class Keywords
		{
			public const EventKeywords All = (EventKeywords)1L;

			public const EventKeywords PerformanceLog = (EventKeywords)2L;
		}

		public static MSBuildEventSource Log = new MSBuildEventSource();

		private MSBuildEventSource()
		{
		}

		[Event(1, Keywords = (EventKeywords)1L)]
		public void ApplyLazyItemOperationsStart(string itemType)
		{
			WriteEvent(1, itemType);
		}

		[Event(2, Keywords = (EventKeywords)1L)]
		public void ApplyLazyItemOperationsStop(string itemType)
		{
			WriteEvent(2, itemType);
		}

		[Event(3, Keywords = (EventKeywords)3L)]
		public void BuildStart()
		{
			WriteEvent(3);
		}

		[Event(4, Keywords = (EventKeywords)3L)]
		public void BuildStop()
		{
			WriteEvent(4);
		}

		[Event(5, Keywords = (EventKeywords)3L)]
		public void BuildProjectStart(string projectPath)
		{
			WriteEvent(5, projectPath);
		}

		[Event(6, Keywords = (EventKeywords)3L)]
		public void BuildProjectStop(string projectPath, string targets)
		{
			WriteEvent(6, projectPath, targets);
		}

		[Event(7, Keywords = (EventKeywords)1L)]
		public void RarComputeClosureStart()
		{
			WriteEvent(7);
		}

		[Event(8, Keywords = (EventKeywords)1L)]
		public void RarComputeClosureStop()
		{
			WriteEvent(8);
		}

		[Event(9, Keywords = (EventKeywords)1L)]
		public void EvaluateConditionStart(string condition)
		{
			WriteEvent(9, condition);
		}

		[Event(10, Keywords = (EventKeywords)1L)]
		public void EvaluateConditionStop(string condition, bool result)
		{
			WriteEvent(10, condition, result);
		}

		[Event(11, Keywords = (EventKeywords)3L)]
		public void EvaluateStart(string projectFile)
		{
			WriteEvent(11, projectFile);
		}

		[Event(12, Keywords = (EventKeywords)3L)]
		public void EvaluateStop(string projectFile)
		{
			WriteEvent(12, projectFile);
		}

		[Event(13, Keywords = (EventKeywords)1L)]
		public void EvaluatePass0Start(string projectFile)
		{
			WriteEvent(13, projectFile);
		}

		[Event(14, Keywords = (EventKeywords)1L)]
		public void EvaluatePass0Stop(string projectFile)
		{
			WriteEvent(14, projectFile);
		}

		[Event(15, Keywords = (EventKeywords)1L)]
		public void EvaluatePass1Start(string projectFile)
		{
			WriteEvent(15, projectFile);
		}

		[Event(16, Keywords = (EventKeywords)1L)]
		public void EvaluatePass1Stop(string projectFile)
		{
			WriteEvent(16, projectFile);
		}

		[Event(17, Keywords = (EventKeywords)1L)]
		public void EvaluatePass2Start(string projectFile)
		{
			WriteEvent(17, projectFile);
		}

		[Event(18, Keywords = (EventKeywords)1L)]
		public void EvaluatePass2Stop(string projectFile)
		{
			WriteEvent(18, projectFile);
		}

		[Event(19, Keywords = (EventKeywords)1L)]
		public void EvaluatePass3Start(string projectFile)
		{
			WriteEvent(19, projectFile);
		}

		[Event(20, Keywords = (EventKeywords)1L)]
		public void EvaluatePass3Stop(string projectFile)
		{
			WriteEvent(20, projectFile);
		}

		[Event(21, Keywords = (EventKeywords)1L)]
		public void EvaluatePass4Start(string projectFile)
		{
			WriteEvent(21, projectFile);
		}

		[Event(22, Keywords = (EventKeywords)1L)]
		public void EvaluatePass4Stop(string projectFile)
		{
			WriteEvent(22, projectFile);
		}

		[Event(23, Keywords = (EventKeywords)1L)]
		public void EvaluatePass5Start(string projectFile)
		{
			WriteEvent(23, projectFile);
		}

		[Event(24, Keywords = (EventKeywords)1L)]
		public void EvaluatePass5Stop(string projectFile)
		{
			WriteEvent(24, projectFile);
		}

		[Event(25, Keywords = (EventKeywords)1L)]
		public void GenerateResourceOverallStart()
		{
			WriteEvent(25);
		}

		[Event(26, Keywords = (EventKeywords)1L)]
		public void GenerateResourceOverallStop()
		{
			WriteEvent(26);
		}

		[Event(27, Keywords = (EventKeywords)3L)]
		public void RarOverallStart()
		{
			WriteEvent(27);
		}

		[Event(28, Keywords = (EventKeywords)3L, Version = 1)]
		public void RarOverallStop(int assembliesCount, int assemblyFilesCount, int resolvedFilesCount, int resolvedDependencyFilesCount, int copyLocalFilesCount, bool findDependencies)
		{
			WriteEvent(28, assembliesCount, assemblyFilesCount, resolvedFilesCount, resolvedDependencyFilesCount, copyLocalFilesCount, findDependencies);
		}

		[Event(41, Keywords = (EventKeywords)1L)]
		public void ExpandGlobStart(string rootDirectory, string glob, string excludedPatterns)
		{
			WriteEvent(41, rootDirectory, glob, excludedPatterns);
		}

		[Event(42, Keywords = (EventKeywords)1L)]
		public void ExpandGlobStop(string rootDirectory, string glob, string excludedPatterns)
		{
			WriteEvent(42, rootDirectory, glob, excludedPatterns);
		}

		[Event(29, Keywords = (EventKeywords)3L)]
		public void LoadDocumentStart(string fullPath)
		{
			WriteEvent(29, fullPath);
		}

		[Event(30, Keywords = (EventKeywords)3L)]
		public void LoadDocumentStop(string fullPath)
		{
			WriteEvent(30, fullPath);
		}

		[Event(31, Keywords = (EventKeywords)1L)]
		public void RarLogResultsStart()
		{
			WriteEvent(31);
		}

		[Event(32, Keywords = (EventKeywords)1L)]
		public void RarLogResultsStop()
		{
			WriteEvent(32);
		}

		[Event(33, Keywords = (EventKeywords)1L)]
		public void ParseStart(string projectFileName)
		{
			WriteEvent(33, projectFileName);
		}

		[Event(34, Keywords = (EventKeywords)1L)]
		public void ParseStop(string projectFileName)
		{
			WriteEvent(34, projectFileName);
		}

		[Event(35, Keywords = (EventKeywords)1L)]
		public void RarRemoveReferencesMarkedForExclusionStart()
		{
			WriteEvent(35);
		}

		[Event(36, Keywords = (EventKeywords)1L)]
		public void RarRemoveReferencesMarkedForExclusionStop()
		{
			WriteEvent(36);
		}

		[Event(37, Keywords = (EventKeywords)3L)]
		public void RequestThreadProcStart()
		{
			WriteEvent(37);
		}

		[Event(38, Keywords = (EventKeywords)3L)]
		public void RequestThreadProcStop()
		{
			WriteEvent(38);
		}

		[Event(39, Keywords = (EventKeywords)1L)]
		public void SaveStart(string fileLocation)
		{
			WriteEvent(39, fileLocation);
		}

		[Event(40, Keywords = (EventKeywords)1L)]
		public void SaveStop(string fileLocation)
		{
			WriteEvent(40, fileLocation);
		}

		[Event(43, Keywords = (EventKeywords)3L)]
		public void TargetStart(string targetName)
		{
			WriteEvent(43, targetName);
		}

		[Event(44, Keywords = (EventKeywords)3L)]
		public void TargetStop(string targetName)
		{
			WriteEvent(44, targetName);
		}

		[Event(45, Keywords = (EventKeywords)3L)]
		public void MSBuildExeStart(string commandLine)
		{
			WriteEvent(45, commandLine);
		}

		[Event(46, Keywords = (EventKeywords)3L)]
		public void MSBuildExeStop(string commandLine)
		{
			WriteEvent(46, commandLine);
		}

		[Event(47, Keywords = (EventKeywords)1L)]
		public void ExecuteTaskStart(string taskName, int taskID)
		{
			WriteEvent(47, taskName, taskID);
		}

		[Event(48, Keywords = (EventKeywords)1L)]
		public void ExecuteTaskStop(string taskName, int taskID)
		{
			WriteEvent(48, taskName, taskID);
		}

		[Event(49, Keywords = (EventKeywords)1L)]
		public void ExecuteTaskYieldStart(string taskName, int taskID)
		{
			WriteEvent(49, taskName, taskID);
		}

		[Event(50, Keywords = (EventKeywords)1L)]
		public void ExecuteTaskYieldStop(string taskName, int taskID)
		{
			WriteEvent(50, taskName, taskID);
		}

		[Event(51, Keywords = (EventKeywords)1L)]
		public void ExecuteTaskReacquireStart(string taskName, int taskID)
		{
			WriteEvent(51, taskName, taskID);
		}

		[Event(52, Keywords = (EventKeywords)1L)]
		public void ExecuteTaskReacquireStop(string taskName, int taskID)
		{
			WriteEvent(52, taskName, taskID);
		}

		[Event(53, Keywords = (EventKeywords)1L)]
		public void ProjectGraphConstructionStart(string graphEntryPoints)
		{
			WriteEvent(53, graphEntryPoints);
		}

		[Event(54, Keywords = (EventKeywords)1L)]
		public void ProjectGraphConstructionStop(string graphEntryPoints)
		{
			WriteEvent(54, graphEntryPoints);
		}

		[Event(55, Keywords = (EventKeywords)1L)]
		public void PacketReadSize(int size)
		{
			WriteEvent(55, size);
		}

		[Event(56, Keywords = (EventKeywords)1L)]
		public void TargetUpToDateStart()
		{
			WriteEvent(56);
		}

		[Event(57, Keywords = (EventKeywords)1L)]
		public void TargetUpToDateStop(int result)
		{
			WriteEvent(57, result);
		}

		[Event(58, Keywords = (EventKeywords)1L)]
		public void CopyUpToDateStart(string path)
		{
			WriteEvent(58, path);
		}

		[Event(59, Keywords = (EventKeywords)1L)]
		public void CopyUpToDateStop(string path, bool wasUpToDate)
		{
			WriteEvent(59, path, wasUpToDate);
		}

		[Event(60, Keywords = (EventKeywords)1L)]
		public void WriteLinesToFileUpToDateStart()
		{
			WriteEvent(60);
		}

		[Event(61, Keywords = (EventKeywords)1L)]
		public void WriteLinesToFileUpToDateStop(string fileItemSpec, bool wasUpToDate)
		{
			WriteEvent(61, fileItemSpec, wasUpToDate);
		}

		[Event(62, Keywords = (EventKeywords)1L)]
		public void SdkResolverLoadAllResolversStart()
		{
			WriteEvent(62);
		}

		[Event(63, Keywords = (EventKeywords)1L)]
		public void SdkResolverLoadAllResolversStop(int resolverCount)
		{
			WriteEvent(63, resolverCount);
		}

		[Event(64, Keywords = (EventKeywords)1L)]
		public void SdkResolverResolveSdkStart()
		{
			WriteEvent(64);
		}

		[Event(65, Keywords = (EventKeywords)1L)]
		public void SdkResolverResolveSdkStop(string resolverName, string sdkName, string solutionPath, string projectPath, string sdkPath, bool success)
		{
			WriteEvent(65, resolverName, sdkName, solutionPath, projectPath, sdkPath, success);
		}

		[Event(66, Keywords = (EventKeywords)1L)]
		public void CachedSdkResolverServiceResolveSdkStart(string sdkName, string solutionPath, string projectPath)
		{
			WriteEvent(66, sdkName, solutionPath, projectPath);
		}

		[Event(67, Keywords = (EventKeywords)1L, Version = 2)]
		public void CachedSdkResolverServiceResolveSdkStop(string sdkName, string solutionPath, string projectPath, bool success, bool wasResultCached)
		{
			WriteEvent(67, sdkName, solutionPath, projectPath, success, wasResultCached);
		}

		[Event(68, Keywords = (EventKeywords)1L)]
		public void ReusableStringBuilderFactoryStart(int hash, int newCapacity, int oldCapacity, string type)
		{
			WriteEvent(68, hash, newCapacity, oldCapacity, type);
		}

		[Event(69, Keywords = (EventKeywords)1L)]
		public void ReusableStringBuilderFactoryStop(int hash, int returningCapacity, int returningLength, string type)
		{
			WriteEvent(69, hash, returningCapacity, returningLength, type);
		}

		[Event(70, Keywords = (EventKeywords)1L)]
		public void ReusableStringBuilderFactoryUnbalanced(int oldHash, int newHash)
		{
			WriteEvent(70, oldHash, newHash);
		}

		[Event(71, Keywords = (EventKeywords)1L)]
		public void ProjectCacheCreatePluginInstanceStart(string pluginAssemblyPath)
		{
			WriteEvent(71, pluginAssemblyPath);
		}

		[Event(72, Keywords = (EventKeywords)1L)]
		public void ProjectCacheCreatePluginInstanceStop(string pluginAssemblyPath, string pluginTypeName)
		{
			WriteEvent(72, pluginAssemblyPath, pluginTypeName);
		}

		[Event(73, Keywords = (EventKeywords)1L)]
		public void ProjectCacheBeginBuildStart(string pluginTypeName)
		{
			WriteEvent(73, pluginTypeName);
		}

		[Event(74, Keywords = (EventKeywords)1L)]
		public void ProjectCacheBeginBuildStop(string pluginTypeName)
		{
			WriteEvent(74, pluginTypeName);
		}

		[Event(75, Keywords = (EventKeywords)1L)]
		public void ProjectCacheGetCacheResultStart(string pluginTypeName, string projectPath, string targets)
		{
			WriteEvent(75, pluginTypeName, projectPath, targets);
		}

		[Event(76, Keywords = (EventKeywords)1L)]
		public void ProjectCacheGetCacheResultStop(string pluginTypeName, string projectPath, string targets, string cacheResultType)
		{
			WriteEvent(76, pluginTypeName, projectPath, targets, cacheResultType);
		}

		[Event(77, Keywords = (EventKeywords)1L)]
		public void ProjectCacheEndBuildStart(string pluginTypeName)
		{
			WriteEvent(77, pluginTypeName);
		}

		[Event(78, Keywords = (EventKeywords)1L)]
		public void ProjectCacheEndBuildStop(string pluginTypeName)
		{
			WriteEvent(78, pluginTypeName);
		}

		[Event(79, Keywords = (EventKeywords)1L)]
		public void OutOfProcSdkResolverServiceRequestSdkPathFromMainNodeStart(int submissionId, string sdkName, string solutionPath, string projectPath)
		{
			WriteEvent(79, submissionId, sdkName, solutionPath, projectPath);
		}

		[Event(80, Keywords = (EventKeywords)1L)]
		public void OutOfProcSdkResolverServiceRequestSdkPathFromMainNodeStop(int submissionId, string sdkName, string solutionPath, string projectPath, bool success, bool wasResultCached)
		{
			WriteEvent(80, submissionId, sdkName, solutionPath, projectPath, success, wasResultCached);
		}

		[Event(81, Keywords = (EventKeywords)1L)]
		public void SdkResolverFindResolversManifestsStart()
		{
			WriteEvent(81);
		}

		[Event(82, Keywords = (EventKeywords)1L)]
		public void SdkResolverFindResolversManifestsStop(int resolverManifestCount)
		{
			WriteEvent(82, resolverManifestCount);
		}

		[Event(83, Keywords = (EventKeywords)1L)]
		public void SdkResolverLoadResolversStart()
		{
			WriteEvent(83);
		}

		[Event(84, Keywords = (EventKeywords)1L)]
		public void SdkResolverLoadResolversStop(string manifestName, int resolverCount)
		{
			WriteEvent(84, manifestName, resolverCount);
		}

		[Event(85, Keywords = (EventKeywords)1L)]
		public void CreateLoadedTypeStart(string assemblyName)
		{
			WriteEvent(85, assemblyName);
		}

		[Event(86, Keywords = (EventKeywords)1L)]
		public void CreateLoadedTypeStop(string assemblyName)
		{
			WriteEvent(86, assemblyName);
		}

		[Event(87, Keywords = (EventKeywords)1L)]
		public void LoadAssemblyAndFindTypeStart()
		{
			WriteEvent(87);
		}

		[Event(88, Keywords = (EventKeywords)1L)]
		public void LoadAssemblyAndFindTypeStop(string assemblyPath, int numberOfPublicTypesSearched)
		{
			WriteEvent(88, assemblyPath, numberOfPublicTypesSearched);
		}

		[Event(89, Keywords = (EventKeywords)1L)]
		public void MSBuildServerBuildStart(string commandLine)
		{
			WriteEvent(89, commandLine);
		}

		[Event(90, Keywords = (EventKeywords)1L)]
		public void MSBuildServerBuildStop(string commandLine, int countOfConsoleMessages, long sumSizeOfConsoleMessages, string clientExitType, string serverExitType)
		{
			WriteEvent(90, commandLine, countOfConsoleMessages, sumSizeOfConsoleMessages, clientExitType, serverExitType);
		}

		[Event(91, Keywords = (EventKeywords)1L)]
		public void ProjectCacheHandleBuildResultStart(string pluginTypeName, string projectPath, string targets)
		{
			WriteEvent(91, pluginTypeName, projectPath, targets);
		}

		[Event(92, Keywords = (EventKeywords)1L)]
		public void ProjectCacheHandleBuildResultStop(string pluginTypeName, string projectPath, string targets)
		{
			WriteEvent(92, pluginTypeName, projectPath, targets);
		}
	}
}
namespace Microsoft.Build.Logging.TerminalLogger
{
	internal static class AnsiCodes
	{
		public const string CSI = "\u001b[";

		public const string SetColor = ";1m";

		public const string SetBold = "1m";

		public const string SetDefaultColor = "\u001b[m";

		public const string LinkPrefix = "\u001b]8;;";

		public const string LinkInfix = "\u001b\\";

		public const string LinkSuffix = "\u001b]8;;\u001b\\";

		public const string MoveUpToLineStart = "F";

		public const string MoveForward = "C";

		public const string MoveBackward = "D";

		public const string EraseInDisplay = "J";

		public const string EraseInLine = "K";

		public const string HideCursor = "\u001b[?25l";

		public const string ShowCursor = "\u001b[?25h";

		public const string SetProgressIndeterminate = "\u001b]9;4;3;\u001b\\";

		public const string RemoveProgress = "\u001b]9;4;0;\u001b\\";

		public static string Colorize(string? s, TerminalColor color)
		{
			if (string.IsNullOrWhiteSpace(s))
			{
				return s ?? "";
			}
			return string.Format("{0}{1}{2}{3}{4}", "\u001b[", (int)color, ";1m", s, "\u001b[m");
		}

		public static string MakeBold(string? s)
		{
			if (string.IsNullOrWhiteSpace(s))
			{
				return s ?? "";
			}
			return "\u001b[1m" + s + "\u001b[m";
		}

		public static string MoveCursorBackward(int count)
		{
			return string.Format("{0}{1}{2}", "\u001b[", count, "D");
		}

		public static string SetCursorHorizontal(int column)
		{
			return string.Format("{0}{1}G", "\u001b[", column);
		}
	}
	internal enum TerminalColor
	{
		Black = 30,
		Red = 31,
		Green = 32,
		Yellow = 33,
		Blue = 34,
		Magenta = 35,
		Cyan = 36,
		White = 37,
		Default = 39
	}
}
namespace Microsoft.Build.Execution
{
	[Flags]
	public enum BuildRequestDataFlags
	{
		None = 0,
		ReplaceExistingProjectInstance = 1,
		ProvideProjectStateAfterBuild = 2,
		IgnoreExistingProjectState = 4,
		ClearCachesAfterBuild = 8,
		SkipNonexistentTargets = 0x10,
		ProvideSubsetOfStateAfterBuild = 0x20,
		IgnoreMissingEmptyAndInvalidImports = 0x40,
		FailOnUnresolvedSdk = 0x80
	}
}
namespace Microsoft.Build.Experimental.BuildCheck
{
	internal abstract class BuildCheckEventArgs : BuildEventArgs
	{
	}
	internal sealed class BuildCheckTracingEventArgs : BuildCheckEventArgs
	{
		public bool IsAggregatedGlobalReport { get; private set; }

		public BuildCheckTracingData TracingData { get; private set; }

		public BuildCheckTracingEventArgs(BuildCheckTracingData tracingData)
		{
			TracingData = tracingData;
			base..ctor();
		}

		internal BuildCheckTracingEventArgs()
			: this(new BuildCheckTracingData())
		{
		}

		internal BuildCheckTracingEventArgs(Dictionary<string, TimeSpan> executionData)
			: this(new BuildCheckTracingData(executionData))
		{
		}

		internal BuildCheckTracingEventArgs(BuildCheckTracingData tracingData, bool isAggregatedGlobalReport)
			: this(tracingData)
		{
			IsAggregatedGlobalReport = isAggregatedGlobalReport;
		}

		internal override void WriteToStream(BinaryWriter writer)
		{
			base.WriteToStream(writer);
			BinaryWriterExtensions.Write7BitEncodedInt(writer, TracingData.InfrastructureTracingData.Count);
			foreach (KeyValuePair<string, TimeSpan> infrastructureTracingDatum in TracingData.InfrastructureTracingData)
			{
				writer.Write(infrastructureTracingDatum.Key);
				writer.Write(infrastructureTracingDatum.Value.Ticks);
			}
			BinaryWriterExtensions.Write7BitEncodedInt(writer, TracingData.TelemetryData.Count);
			foreach (BuildCheckRuleTelemetryData value in TracingData.TelemetryData.Values)
			{
				writer.Write(value.RuleId);
				writer.Write(value.CheckFriendlyName);
				writer.Write(value.IsBuiltIn);
				BinaryWriterExtensions.Write7BitEncodedInt(writer, (int)value.DefaultSeverity);
				BinaryWriterExtensions.Write7BitEncodedInt(writer, value.ExplicitSeverities.Count);
				foreach (DiagnosticSeverity explicitSeverity in value.ExplicitSeverities)
				{
					BinaryWriterExtensions.Write7BitEncodedInt(writer, (int)explicitSeverity);
				}
				BinaryWriterExtensions.Write7BitEncodedInt(writer, value.ProjectNamesWhereEnabled.Count);
				foreach (string item in value.ProjectNamesWhereEnabled)
				{
					writer.Write(item);
				}
				BinaryWriterExtensions.Write7BitEncodedInt(writer, value.ViolationMessagesCount);
				BinaryWriterExtensions.Write7BitEncodedInt(writer, value.ViolationWarningsCount);
				BinaryWriterExtensions.Write7BitEncodedInt(writer, value.ViolationErrorsCount);
				writer.Write(value.IsThrottled);
				writer.Write(value.TotalRuntime.Ticks);
			}
		}

		internal override void CreateFromStream(BinaryReader reader, int version)
		{
			base.CreateFromStream(reader, version);
			int num = BinaryReaderExtensions.Read7BitEncodedInt(reader);
			Dictionary<string, TimeSpan> dictionary = new Dictionary<string, TimeSpan>(num);
			for (int i = 0; i < num; i++)
			{
				string key = reader.ReadString();
				TimeSpan value = TimeSpan.FromTicks(reader.ReadInt64());
				dictionary.Add(key, value);
			}
			num = BinaryReaderExtensions.Read7BitEncodedInt(reader);
			List<BuildCheckRuleTelemetryData> list = new List<BuildCheckRuleTelemetryData>(num);
			for (int j = 0; j < num; j++)
			{
				string ruleId = reader.ReadString();
				string checkFriendlyName = reader.ReadString();
				bool isBuiltIn = reader.ReadBoolean();
				DiagnosticSeverity defaultSeverity = (DiagnosticSeverity)BinaryReaderExtensions.Read7BitEncodedInt(reader);
				int num2 = BinaryReaderExtensions.Read7BitEncodedInt(reader);
				HashSet<DiagnosticSeverity> hashSet = EnumerableExtensions.NewHashSet<DiagnosticSeverity>(num2);
				for (int k = 0; k < num2; k++)
				{
					hashSet.Add((DiagnosticSeverity)BinaryReaderExtensions.Read7BitEncodedInt(reader));
				}
				int num3 = BinaryReaderExtensions.Read7BitEncodedInt(reader);
				HashSet<string> hashSet2 = EnumerableExtensions.NewHashSet<string>(num3);
				for (int l = 0; l < num3; l++)
				{
					hashSet2.Add(reader.ReadString());
				}
				int violationMessagesCount = BinaryReaderExtensions.Read7BitEncodedInt(reader);
				int violationWarningsCount = BinaryReaderExtensions.Read7BitEncodedInt(reader);
				int violationErrorsCount = BinaryReaderExtensions.Read7BitEncodedInt(reader);
				bool isThrottled = reader.ReadBoolean();
				TimeSpan totalRuntime = TimeSpan.FromTicks(reader.ReadInt64());
				BuildCheckRuleTelemetryData item = new BuildCheckRuleTelemetryData(ruleId, checkFriendlyName, isBuiltIn, defaultSeverity, hashSet, hashSet2, violationMessagesCount, violationWarningsCount, violationErrorsCount, isThrottled, totalRuntime);
				list.Add(item);
			}
			TracingData = new BuildCheckTracingData(list, dictionary);
		}
	}
	internal sealed class BuildCheckAcquisitionEventArgs : BuildCheckEventArgs
	{
		public string AcquisitionPath { get; private set; }

		public string ProjectPath { get; private set; }

		public BuildCheckAcquisitionEventArgs(string acquisitionPath, string projectPath)
		{
			AcquisitionPath = acquisitionPath;
			ProjectPath = projectPath;
			base..ctor();
		}

		internal BuildCheckAcquisitionEventArgs()
			: this(string.Empty, string.Empty)
		{
		}

		internal override void WriteToStream(BinaryWriter writer)
		{
			base.WriteToStream(writer);
			writer.Write(AcquisitionPath);
			writer.Write(ProjectPath);
		}

		internal override void CreateFromStream(BinaryReader reader, int version)
		{
			base.CreateFromStream(reader, version);
			AcquisitionPath = reader.ReadString();
			ProjectPath = reader.ReadString();
		}
	}
	internal sealed class BuildCheckResultWarning : BuildWarningEventArgs
	{
		public BuildCheckResultWarning(IBuildCheckResult result)
			: base(result.Code, result.Location.File, result.Location.Line, result.Location.Column, result.FormatMessage())
		{
			base.RawMessage = result.FormatMessage();
		}

		internal BuildCheckResultWarning()
		{
		}

		internal override void WriteToStream(BinaryWriter writer)
		{
			base.WriteToStream(writer);
			writer.Write(base.RawMessage);
		}

		internal override void CreateFromStream(BinaryReader reader, int version)
		{
			base.CreateFromStream(reader, version);
			base.RawMessage = reader.ReadString();
		}
	}
	internal sealed class BuildCheckResultError : BuildErrorEventArgs
	{
		public BuildCheckResultError(IBuildCheckResult result)
			: base(result.Code, file: result.Location.File, lineNumber: result.Location.Line, columnNumber: result.Location.Column, message: result.FormatMessage())
		{
			base.RawMessage = result.FormatMessage();
		}

		internal BuildCheckResultError()
		{
		}

		internal override void WriteToStream(BinaryWriter writer)
		{
			base.WriteToStream(writer);
			writer.Write(base.RawMessage);
		}

		internal override void CreateFromStream(BinaryReader reader, int version)
		{
			base.CreateFromStream(reader, version);
			base.RawMessage = reader.ReadString();
		}
	}
	internal sealed class BuildCheckResultMessage : BuildMessageEventArgs
	{
		public BuildCheckResultMessage(IBuildCheckResult result)
			: base(result.Code, file: result.Location.File, lineNumber: result.Location.Line, columnNumber: result.Location.Column, message: result.FormatMessage())
		{
			base.RawMessage = result.FormatMessage();
		}

		internal BuildCheckResultMessage(string formattedMessage)
		{
			base.RawMessage = formattedMessage;
		}

		internal BuildCheckResultMessage()
		{
		}

		internal override void WriteToStream(BinaryWriter writer)
		{
			base.WriteToStream(writer);
			writer.Write(base.RawMessage);
		}

		internal override void CreateFromStream(BinaryReader reader, int version)
		{
			base.CreateFromStream(reader, version);
			base.RawMessage = reader.ReadString();
		}
	}
	internal sealed class BuildCheckRuleTelemetryData
	{
		public string RuleId { get; init; }

		public string CheckFriendlyName { get; init; }

		public bool IsBuiltIn { get; init; }

		public DiagnosticSeverity DefaultSeverity { get; init; }

		public HashSet<DiagnosticSeverity> ExplicitSeverities { get; init; }

		public HashSet<string> ProjectNamesWhereEnabled { get; init; }

		public int ViolationMessagesCount { get; private set; }

		public int ViolationWarningsCount { get; private set; }

		public int ViolationErrorsCount { get; private set; }

		public int ViolationsCount => ViolationMessagesCount + ViolationWarningsCount + ViolationErrorsCount;

		public bool IsThrottled { get; private set; }

		public TimeSpan TotalRuntime { get; set; }

		public BuildCheckRuleTelemetryData(string ruleId, string checkFriendlyName, bool isBuiltIn, DiagnosticSeverity defaultSeverity)
		{
			RuleId = ruleId;
			CheckFriendlyName = checkFriendlyName;
			IsBuiltIn = isBuiltIn;
			DefaultSeverity = defaultSeverity;
			ExplicitSeverities = new HashSet<DiagnosticSeverity>();
			ProjectNamesWhereEnabled = new HashSet<string>();
			base..ctor();
		}

		public BuildCheckRuleTelemetryData(string ruleId, string checkFriendlyName, bool isBuiltIn, DiagnosticSeverity defaultSeverity, HashSet<DiagnosticSeverity> explicitSeverities, HashSet<string> projectNamesWhereEnabled, int violationMessagesCount, int violationWarningsCount, int violationErrorsCount, bool isThrottled, TimeSpan totalRuntime)
			: this(ruleId, checkFriendlyName, isBuiltIn, defaultSeverity)
		{
			ExplicitSeverities = explicitSeverities;
			ProjectNamesWhereEnabled = projectNamesWhereEnabled;
			ViolationMessagesCount = violationMessagesCount;
			ViolationWarningsCount = violationWarningsCount;
			ViolationErrorsCount = violationErrorsCount;
			IsThrottled = isThrottled;
			TotalRuntime = totalRuntime;
		}

		public static BuildCheckRuleTelemetryData Merge(BuildCheckRuleTelemetryData data1, BuildCheckRuleTelemetryData data2)
		{
			if (data1.RuleId != data2.RuleId)
			{
				throw new InvalidOperationException("Cannot merge telemetry data for different rules.");
			}
			return new BuildCheckRuleTelemetryData(data1.RuleId, data1.CheckFriendlyName, data1.IsBuiltIn, data1.DefaultSeverity, new HashSet<DiagnosticSeverity>(data1.ExplicitSeverities.Union(data2.ExplicitSeverities)), new HashSet<string>(data1.ProjectNamesWhereEnabled.Union(data2.ProjectNamesWhereEnabled)), data1.ViolationMessagesCount + data2.ViolationMessagesCount, data1.ViolationWarningsCount + data2.ViolationWarningsCount, data1.ViolationErrorsCount + data2.ViolationErrorsCount, data1.IsThrottled || data2.IsThrottled, data1.TotalRuntime + data2.TotalRuntime);
		}

		public void IncrementMessagesCount()
		{
			ViolationMessagesCount++;
		}

		public void IncrementWarningsCount()
		{
			ViolationWarningsCount++;
		}

		public void IncrementErrorsCount()
		{
			ViolationErrorsCount++;
		}

		public void SetThrottled()
		{
			IsThrottled = true;
		}
	}
	internal sealed class BuildCheckTracingData
	{
		public Dictionary<string, BuildCheckRuleTelemetryData> TelemetryData { get; private set; }

		public Dictionary<string, TimeSpan> InfrastructureTracingData { get; private set; }

		public BuildCheckTracingData(Dictionary<string, BuildCheckRuleTelemetryData> telemetryData, Dictionary<string, TimeSpan> infrastructureTracingData)
		{
			TelemetryData = telemetryData;
			InfrastructureTracingData = infrastructureTracingData;
			base..ctor();
		}

		public BuildCheckTracingData(IReadOnlyList<BuildCheckRuleTelemetryData> telemetryData, Dictionary<string, TimeSpan> infrastructureTracingData)
			: this(telemetryData.ToDictionary((BuildCheckRuleTelemetryData data) => data.RuleId), infrastructureTracingData)
		{
		}

		public BuildCheckTracingData()
			: this(new Dictionary<string, BuildCheckRuleTelemetryData>(), new Dictionary<string, TimeSpan>())
		{
		}

		internal BuildCheckTracingData(Dictionary<string, TimeSpan> executionData)
			: this(new Dictionary<string, BuildCheckRuleTelemetryData>(), executionData)
		{
		}

		public Dictionary<string, TimeSpan> ExtractCheckStats()
		{
			return (from d in TelemetryData
				group d by d.Value.CheckFriendlyName).ToDictionary((IGrouping<string, KeyValuePair<string, BuildCheckRuleTelemetryData>> g) => g.Key, (IGrouping<string, KeyValuePair<string, BuildCheckRuleTelemetryData>> g) => g.First().Value.TotalRuntime);
		}

		public void MergeIn(BuildCheckTracingData other)
		{
			InfrastructureTracingData.Merge(other.InfrastructureTracingData, (TimeSpan span1, TimeSpan span2) => span1 + span2);
			TelemetryData.Merge(other.TelemetryData, BuildCheckRuleTelemetryData.Merge);
		}
	}
	internal enum DiagnosticSeverity
	{
		Default,
		None,
		Suggestion,
		Warning,
		Error
	}
	internal static class EnumerableExtensions
	{
		[CompilerGenerated]
		private sealed class <AsSingleItemEnumerable>d__1<T> : IEnumerable<T>, IEnumerable, IEnumerator<T>, IDisposable, IEnumerator where T : notnull
		{
			private int <>1__state;

			private T <>2__current;

			private int <>l__initialThreadId;

			private T item;

			public T <>3__item;

			T IEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <AsSingleItemEnumerable>d__1(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = item;
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<T> IEnumerable<T>.GetEnumerator()
			{
				<AsSingleItemEnumerable>d__1<T> <AsSingleItemEnumerable>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<AsSingleItemEnumerable>d__ = this;
				}
				else
				{
					<AsSingleItemEnumerable>d__ = new <AsSingleItemEnumerable>d__1<T>(0);
				}
				<AsSingleItemEnumerable>d__.item = <>3__item;
				return <AsSingleItemEnumerable>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<T>)this).GetEnumerator();
			}
		}

		public static string ToCsvString<T>(this IEnumerable<T>? source, bool useSpace = true)
		{
			if (source != null)
			{
				return string.Join(useSpace ? ", " : ",", source);
			}
			return "<NULL>";
		}

		[IteratorStateMachine(typeof(<AsSingleItemEnumerable>d__1<>))]
		public static IEnumerable<T> AsSingleItemEnumerable<T>(this T item)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <AsSingleItemEnumerable>d__1<T>(-2)
			{
				<>3__item = item
			};
		}

		public static HashSet<T> NewHashSet<T>(int capacity)
		{
			return NewHashSet<T>(capacity, null);
		}

		public static HashSet<T> NewHashSet<T>(IEqualityComparer<T> equalityComparer)
		{
			return NewHashSet(0, equalityComparer);
		}

		public static HashSet<T> NewHashSet<T>(int capacity, IEqualityComparer<T>? equalityComparer)
		{
			return new HashSet<T>(capacity, equalityComparer);
		}

		public static HashSet<T>? ToHashSet<T>(this ICollection<T>? source, IEqualityComparer<T>? equalityComparer = null)
		{
			if (source == null)
			{
				return null;
			}
			if (source is HashSet<T> result)
			{
				return result;
			}
			return new HashSet<T>(source, equalityComparer);
		}

		public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
		{
			return new ReadOnlyDictionary<TKey, TValue>(dictionary);
		}

		public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> dict, IReadOnlyDictionary<TKey, TValue> another, Func<TValue, TValue, TValue> mergeValues)
		{
			foreach (KeyValuePair<TKey, TValue> item in another)
			{
				if (!dict.TryGetValue(item.Key, out TValue value))
				{
					dict[item.Key] = item.Value;
				}
				else
				{
					dict[item.Key] = mergeValues(value, item.Value);
				}
			}
		}

		public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> dict, IReadOnlyList<TValue> another, Func<TValue, TKey> extractKey, Func<TValue, TValue, TValue> mergeValues)
		{
			foreach (TValue item in another)
			{
				TKey key = extractKey(item);
				if (!dict.TryGetValue(key, out TValue value))
				{
					dict[key] = item;
				}
				else
				{
					dict[key] = mergeValues(value, item);
				}
			}
		}
	}
	internal interface IBuildCheckResult
	{
		string LocationString { get; }

		string Code { get; }

		IMSBuildElementLocation Location { get; }

		string[] MessageArgs { get; }

		string MessageFormat { get; }

		string FormatMessage();
	}
}
namespace Microsoft.Build.BackEnd
{
	internal static class BinaryTranslator
	{
		private class BinaryReadTranslator : ITranslator, IDisposable
		{
			private Stream _packetStream;

			private BinaryReader _reader;

			public BinaryReader Reader => _reader;

			public BinaryWriter Writer
			{
				get
				{
					EscapeHatches.ThrowInternalError("Cannot get writer from reader.");
					return null;
				}
			}

			public TranslationDirection Mode
			{
				[DebuggerStepThrough]
				get
				{
					return TranslationDirection.ReadFromStream;
				}
			}

			public BinaryReadTranslator(Stream packetStream, BinaryReaderFactory buffer)
			{
				_packetStream = packetStream;
				_reader = buffer.Create(packetStream);
			}

			public void Dispose()
			{
				_reader.Close();
			}

			public void Translate(ref bool value)
			{
				value = _reader.ReadBoolean();
			}

			public void Translate(ref bool[] array)
			{
				if (TranslateNullable(array))
				{
					int num = _reader.ReadInt32();
					array = new bool[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = _reader.ReadBoolean();
					}
				}
			}

			public void Translate(ref byte value)
			{
				value = _reader.ReadByte();
			}

			public void Translate(ref short value)
			{
				value = _reader.ReadInt16();
			}

			public void Translate(ref ushort value)
			{
				value = _reader.ReadUInt16();
			}

			public void Translate(ref int value)
			{
				value = _reader.ReadInt32();
			}

			public void Translate(ref uint unsignedInteger)
			{
				unsignedInteger = _reader.ReadUInt32();
			}

			public void Translate(ref int[] array)
			{
				if (TranslateNullable(array))
				{
					int num = _reader.ReadInt32();
					array = new int[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = _reader.ReadInt32();
					}
				}
			}

			public void Translate(ref long value)
			{
				value = _reader.ReadInt64();
			}

			public void Translate(ref double value)
			{
				value = _reader.ReadDouble();
			}

			public void Translate(ref string value)
			{
				if (TranslateNullable(value))
				{
					value = _reader.ReadString();
				}
			}

			public void Translate(ref byte[] byteArray)
			{
				if (TranslateNullable(byteArray))
				{
					int num = _reader.ReadInt32();
					if (num > 0)
					{
						byteArray = _reader.ReadBytes(num);
					}
					else
					{
						byteArray = new byte[0];
					}
				}
			}

			public void Translate(ref byte[] byteArray, ref int length)
			{
				Translate(ref byteArray);
				length = byteArray.Length;
			}

			public void Translate(ref string[] array)
			{
				if (TranslateNullable(array))
				{
					int num = _reader.ReadInt32();
					array = new string[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = _reader.ReadString();
					}
				}
			}

			public void Translate(ref HashSet<string> set)
			{
				if (TranslateNullable(set))
				{
					int num = _reader.ReadInt32();
					set = new HashSet<string>();
					for (int i = 0; i < num; i++)
					{
						set.Add(_reader.ReadString());
					}
				}
			}

			public void Translate(ref List<string> list)
			{
				if (TranslateNullable(list))
				{
					int num = _reader.ReadInt32();
					list = new List<string>(num);
					for (int i = 0; i < num; i++)
					{
						list.Add(_reader.ReadString());
					}
				}
			}

			public void Translate<T>(ref List<T> list, ObjectTranslator<T> objectTranslator)
			{
				IList<T> list2 = list;
				Translate(ref list2, objectTranslator, (int count) => new List<T>(count));
				list = (List<T>)list2;
			}

			public void Translate<T, L>(ref IList<T> list, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<L> collectionFactory) where L : IList<T>
			{
				if (TranslateNullable(list))
				{
					int num = _reader.ReadInt32();
					list = collectionFactory(num);
					for (int i = 0; i < num; i++)
					{
						T objectToTranslate = default(T);
						objectTranslator(this, ref objectToTranslate);
						list.Add(objectToTranslate);
					}
				}
			}

			public void Translate<T, L>(ref ICollection<T> collection, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<L> collectionFactory) where L : ICollection<T>
			{
				if (TranslateNullable(collection))
				{
					int num = _reader.ReadInt32();
					collection = collectionFactory(num);
					for (int i = 0; i < num; i++)
					{
						T objectToTranslate = default(T);
						objectTranslator(this, ref objectToTranslate);
						collection.Add(objectToTranslate);
					}
				}
			}

			public void Translate(ref DateTime value)
			{
				DateTimeKind value2 = DateTimeKind.Unspecified;
				TranslateEnum(ref value2, 0);
				value = new DateTime(_reader.ReadInt64(), value2);
			}

			public void Translate(ref TimeSpan value)
			{
				long value2 = 0L;
				Translate(ref value2);
				value = new TimeSpan(value2);
			}

			public void Translate(ref BuildEventContext value)
			{
				value = new BuildEventContext(_reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32());
			}

			public void TranslateCulture(ref CultureInfo value)
			{
				string name = _reader.ReadString();
				value = new CultureInfo(name);
			}

			public void TranslateEnum<T>(ref T value, int numericValue) where T : struct, Enum
			{
				numericValue = _reader.ReadInt32();
				Type type = value.GetType();
				value = (T)Enum.ToObject(type, numericValue);
			}

			public void TranslateDotNet<T>(ref T value)
			{
				if (TranslateNullable(value))
				{
					BinaryFormatter binaryFormatter = new BinaryFormatter();
					value = (T)binaryFormatter.Deserialize(_packetStream);
				}
			}

			public void TranslateException(ref Exception value)
			{
				if (TranslateNullable(value))
				{
					value = BuildExceptionBase.ReadExceptionFromTranslator(this);
				}
			}

			public void Translate<T>(ref T value) where T : ITranslatable, new()
			{
				if (TranslateNullable(value))
				{
					value = new T();
					value.Translate(this);
				}
			}

			public void TranslateArray<T>(ref T[] array) where T : ITranslatable, new()
			{
				if (TranslateNullable(array))
				{
					int num = _reader.ReadInt32();
					array = new T[num];
					for (int i = 0; i < num; i++)
					{
						array[i] = new T();
						array[i].Translate(this);
					}
				}
			}

			public void TranslateArray<T>(ref T[] array, ObjectTranslator<T> objectTranslator)
			{
				if (TranslateNullable(array))
				{
					int num = _reader.ReadInt32();
					array = new T[num];
					for (int i = 0; i < num; i++)
					{
						objectTranslator(this, ref array[i]);
					}
				}
			}

			public void TranslateDictionary(ref Dictionary<string, string> dictionary, IEqualityComparer<string> comparer)
			{
				IDictionary<string, string> dictionary2 = dictionary;
				TranslateDictionary(ref dictionary2, (int count) => new Dictionary<string, string>(count, comparer));
				dictionary = (Dictionary<string, string>)dictionary2;
			}

			public void TranslateDictionary(ref Dictionary<string, string> dictionary, IEqualityComparer<string> comparer, ref Dictionary<string, string> additionalEntries, HashSet<string> additionalEntriesKeys)
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int num = _reader.ReadInt32();
				dictionary = new Dictionary<string, string>(num, comparer);
				additionalEntries = new Dictionary<string, string>();
				for (int i = 0; i < num; i++)
				{
					string value = null;
					Translate(ref value);
					string value2 = null;
					Translate(ref value2);
					if (additionalEntriesKeys.Contains(value))
					{
						additionalEntries[value] = value2;
					}
					else if (comparer.Equals(value, "=MSBUILDDICTIONARYWASNULL="))
					{
						dictionary = null;
					}
					else if (dictionary != null)
					{
						dictionary[value] = value2;
					}
				}
			}

			public void TranslateDictionary(ref IDictionary<string, string> dictionary, NodePacketCollectionCreator<IDictionary<string, string>> dictionaryCreator)
			{
				if (TranslateNullable(dictionary))
				{
					int num = _reader.ReadInt32();
					dictionary = dictionaryCreator(num);
					for (int i = 0; i < num; i++)
					{
						string value = null;
						Translate(ref value);
						string value2 = null;
						Translate(ref value2);
						dictionary[value] = value2;
					}
				}
			}

			public void TranslateDictionary<K, V>(ref IDictionary<K, V> dictionary, ObjectTranslator<K> keyTranslator, ObjectTranslator<V> valueTranslator, NodePacketCollectionCreator<IDictionary<K, V>> dictionaryCreator)
			{
				if (TranslateNullable(dictionary))
				{
					int num = _reader.ReadInt32();
					dictionary = dictionaryCreator(num);
					for (int i = 0; i < num; i++)
					{
						K objectToTranslate = default(K);
						keyTranslator(this, ref objectToTranslate);
						V objectToTranslate2 = default(V);
						valueTranslator(this, ref objectToTranslate2);
						dictionary[objectToTranslate] = objectToTranslate2;
					}
				}
			}

			public void TranslateDictionary<T>(ref Dictionary<string, T> dictionary, IEqualityComparer<string> comparer, ObjectTranslator<T> objectTranslator) where T : class
			{
				if (TranslateNullable(dictionary))
				{
					int num = _reader.ReadInt32();
					dictionary = new Dictionary<string, T>(num, comparer);
					for (int i = 0; i < num; i++)
					{
						string value = null;
						Translate(ref value);
						T objectToTranslate = null;
						objectTranslator(this, ref objectToTranslate);
						dictionary[value] = objectToTranslate;
					}
				}
			}

			public void TranslateDictionary<D, T>(ref D dictionary, ObjectTranslator<T> objectTranslator) where D : IDictionary<string, T>, new() where T : class
			{
				if (TranslateNullable(dictionary))
				{
					int num = _reader.ReadInt32();
					dictionary = new D();
					for (int i = 0; i < num; i++)
					{
						string value = null;
						Translate(ref value);
						T objectToTranslate = null;
						objectTranslator(this, ref objectToTranslate);
						dictionary[value] = objectToTranslate;
					}
				}
			}

			public void TranslateDictionary<D, T>(ref D dictionary, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<D> dictionaryCreator) where D : IDictionary<string, T> where T : class
			{
				if (TranslateNullable(dictionary))
				{
					int num = _reader.ReadInt32();
					dictionary = dictionaryCreator(num);
					for (int i = 0; i < num; i++)
					{
						string value = null;
						Translate(ref value);
						T objectToTranslate = null;
						objectTranslator(this, ref objectToTranslate);
						dictionary[value] = objectToTranslate;
					}
				}
			}

			public void TranslateDictionary(ref Dictionary<string, DateTime> dictionary, StringComparer comparer)
			{
				if (TranslateNullable(dictionary))
				{
					int num = _reader.ReadInt32();
					dictionary = new Dictionary<string, DateTime>(num, comparer);
					string value = string.Empty;
					DateTime value2 = DateTime.MinValue;
					for (int i = 0; i < num; i++)
					{
						Translate(ref value);
						Translate(ref value2);
						dictionary.Add(value, value2);
					}
				}
			}

			public bool TranslateNullable<T>(T value)
			{
				return _reader.ReadBoolean();
			}
		}

		private class BinaryWriteTranslator : ITranslator, IDisposable
		{
			private Stream _packetStream;

			private BinaryWriter _writer;

			public BinaryReader Reader
			{
				get
				{
					EscapeHatches.ThrowInternalError("Cannot get reader from writer.");
					return null;
				}
			}

			public BinaryWriter Writer => _writer;

			public TranslationDirection Mode
			{
				[DebuggerStepThrough]
				get
				{
					return TranslationDirection.WriteToStream;
				}
			}

			public BinaryWriteTranslator(Stream packetStream)
			{
				_packetStream = packetStream;
				_writer = new BinaryWriter(packetStream);
			}

			public void Dispose()
			{
				_writer.Close();
			}

			public void Translate(ref bool value)
			{
				_writer.Write(value);
			}

			public void Translate(ref bool[] array)
			{
				if (TranslateNullable(array))
				{
					int num = array.Length;
					_writer.Write(num);
					for (int i = 0; i < num; i++)
					{
						_writer.Write(array[i]);
					}
				}
			}

			public void Translate(ref byte value)
			{
				_writer.Write(value);
			}

			public void Translate(ref short value)
			{
				_writer.Write(value);
			}

			public void Translate(ref ushort value)
			{
				_writer.Write(value);
			}

			public void Translate(ref int value)
			{
				_writer.Write(value);
			}

			public void Translate(ref uint unsignedInteger)
			{
				_writer.Write(unsignedInteger);
			}

			public void Translate(ref int[] array)
			{
				if (TranslateNullable(array))
				{
					int num = array.Length;
					_writer.Write(num);
					for (int i = 0; i < num; i++)
					{
						_writer.Write(array[i]);
					}
				}
			}

			public void Translate(ref long value)
			{
				_writer.Write(value);
			}

			public void Translate(ref double value)
			{
				_writer.Write(value);
			}

			public void Translate(ref string value)
			{
				if (TranslateNullable(value))
				{
					_writer.Write(value);
				}
			}

			public void Translate(ref string[] array)
			{
				if (TranslateNullable(array))
				{
					int num = array.Length;
					_writer.Write(num);
					for (int i = 0; i < num; i++)
					{
						_writer.Write(array[i]);
					}
				}
			}

			public void Translate(ref List<string> list)
			{
				if (TranslateNullable(list))
				{
					int count = list.Count;
					_writer.Write(count);
					for (int i = 0; i < count; i++)
					{
						_writer.Write(list[i]);
					}
				}
			}

			public void Translate(ref HashSet<string> set)
			{
				if (!TranslateNullable(set))
				{
					return;
				}
				int count = set.Count;
				_writer.Write(count);
				foreach (string item in set)
				{
					_writer.Write(item);
				}
			}

			public void Translate<T>(ref List<T> list, ObjectTranslator<T> objectTranslator)
			{
				if (TranslateNullable(list))
				{
					int count = list.Count;
					_writer.Write(count);
					for (int i = 0; i < count; i++)
					{
						T objectToTranslate = list[i];
						objectTranslator(this, ref objectToTranslate);
					}
				}
			}

			public void Translate<T, L>(ref IList<T> list, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<L> collectionFactory) where L : IList<T>
			{
				if (TranslateNullable(list))
				{
					int count = list.Count;
					_writer.Write(count);
					for (int i = 0; i < count; i++)
					{
						T objectToTranslate = list[i];
						objectTranslator(this, ref objectToTranslate);
					}
				}
			}

			public void Translate<T, L>(ref ICollection<T> collection, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<L> collectionFactory) where L : ICollection<T>
			{
				if (!TranslateNullable(collection))
				{
					return;
				}
				_writer.Write(collection.Count);
				foreach (T item in collection)
				{
					T objectToTranslate = item;
					objectTranslator(this, ref objectToTranslate);
				}
			}

			public void Translate(ref DateTime value)
			{
				DateTimeKind value2 = value.Kind;
				TranslateEnum(ref value2, (int)value2);
				_writer.Write(value.Ticks);
			}

			public void Translate(ref TimeSpan value)
			{
				_writer.Write(value.Ticks);
			}

			public void Translate(ref BuildEventContext value)
			{
				_writer.Write(value.SubmissionId);
				_writer.Write(value.NodeId);
				_writer.Write(value.EvaluationId);
				_writer.Write(value.ProjectInstanceId);
				_writer.Write(value.ProjectContextId);
				_writer.Write(value.TargetId);
				_writer.Write(value.TaskId);
			}

			public void TranslateCulture(ref CultureInfo value)
			{
				_writer.Write(value.Name);
			}

			public void TranslateEnum<T>(ref T value, int numericValue) where T : struct, Enum
			{
				_writer.Write(numericValue);
			}

			public void TranslateDotNet<T>(ref T value)
			{
				if (TranslateNullable(value) && ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave17_10))
				{
					new BinaryFormatter().Serialize(_packetStream, value);
				}
			}

			public void TranslateException(ref Exception value)
			{
				if (TranslateNullable(value))
				{
					BuildExceptionBase.WriteExceptionToTranslator(this, value);
				}
			}

			public void Translate<T>(ref T value) where T : ITranslatable, new()
			{
				if (TranslateNullable(value))
				{
					value.Translate(this);
				}
			}

			public void Translate(ref byte[] byteArray)
			{
				byte[] obj = byteArray;
				int length = ((obj != null) ? obj.Length : 0);
				Translate(ref byteArray, ref length);
			}

			public void Translate(ref byte[] byteArray, ref int length)
			{
				if (TranslateNullable(byteArray))
				{
					_writer.Write(length);
					if (length > 0)
					{
						_writer.Write(byteArray, 0, length);
					}
				}
			}

			public void TranslateArray<T>(ref T[] array) where T : ITranslatable, new()
			{
				if (TranslateNullable(array))
				{
					int num = array.Length;
					_writer.Write(num);
					for (int i = 0; i < num; i++)
					{
						array[i].Translate(this);
					}
				}
			}

			public void TranslateArray<T>(ref T[] array, ObjectTranslator<T> objectTranslator)
			{
				if (TranslateNullable(array))
				{
					int num = array.Length;
					_writer.Write(num);
					for (int i = 0; i < num; i++)
					{
						objectTranslator(this, ref array[i]);
					}
				}
			}

			public void TranslateDictionary(ref Dictionary<string, string> dictionary, IEqualityComparer<string> comparer)
			{
				IDictionary<string, string> dictionary2 = dictionary;
				TranslateDictionary(ref dictionary2, null);
			}

			public void TranslateDictionary(ref Dictionary<string, string> dictionary, IEqualityComparer<string> comparer, ref Dictionary<string, string> additionalEntries, HashSet<string> additionalEntriesKeys)
			{
				if (dictionary == null && (additionalEntries == null || additionalEntries.Count == 0))
				{
					_writer.Write(value: false);
					return;
				}
				_writer.Write(value: true);
				int value = ((dictionary == null) ? 1 : 0) + ((additionalEntries != null) ? additionalEntries.Count : 0) + ((dictionary != null) ? dictionary.Count : 0);
				_writer.Write(value);
				if (dictionary == null)
				{
					string value2 = "=MSBUILDDICTIONARYWASNULL=";
					Translate(ref value2);
					string value3 = string.Empty;
					Translate(ref value3);
				}
				if (additionalEntries != null)
				{
					foreach (KeyValuePair<string, string> additionalEntry in additionalEntries)
					{
						string value4 = additionalEntry.Key;
						Translate(ref value4);
						string value5 = additionalEntry.Value;
						Translate(ref value5);
					}
				}
				if (dictionary == null)
				{
					return;
				}
				foreach (KeyValuePair<string, string> item in dictionary)
				{
					string value6 = item.Key;
					Translate(ref value6);
					string value7 = item.Value;
					Translate(ref value7);
				}
			}

			public void TranslateDictionary(ref IDictionary<string, string> dictionary, NodePacketCollectionCreator<IDictionary<string, string>> dictionaryCreator)
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int count = dictionary.Count;
				_writer.Write(count);
				foreach (KeyValuePair<string, string> item in dictionary)
				{
					string value = item.Key;
					Translate(ref value);
					string value2 = item.Value;
					Translate(ref value2);
				}
			}

			public void TranslateDictionary<K, V>(ref IDictionary<K, V> dictionary, ObjectTranslator<K> keyTranslator, ObjectTranslator<V> valueTranslator, NodePacketCollectionCreator<IDictionary<K, V>> collectionCreator)
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int count = dictionary.Count;
				_writer.Write(count);
				foreach (KeyValuePair<K, V> item in dictionary)
				{
					K objectToTranslate = item.Key;
					keyTranslator(this, ref objectToTranslate);
					V objectToTranslate2 = item.Value;
					valueTranslator(this, ref objectToTranslate2);
				}
			}

			public void TranslateDictionary<T>(ref Dictionary<string, T> dictionary, IEqualityComparer<string> comparer, ObjectTranslator<T> objectTranslator) where T : class
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int count = dictionary.Count;
				_writer.Write(count);
				foreach (KeyValuePair<string, T> item in dictionary)
				{
					string value = item.Key;
					Translate(ref value);
					T objectToTranslate = item.Value;
					objectTranslator(this, ref objectToTranslate);
				}
			}

			public void TranslateDictionary<D, T>(ref D dictionary, ObjectTranslator<T> objectTranslator) where D : IDictionary<string, T>, new() where T : class
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int count = dictionary.Count;
				_writer.Write(count);
				foreach (KeyValuePair<string, T> item in dictionary)
				{
					string value = item.Key;
					Translate(ref value);
					T objectToTranslate = item.Value;
					objectTranslator(this, ref objectToTranslate);
				}
			}

			public void TranslateDictionary<D, T>(ref D dictionary, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<D> dictionaryCreator) where D : IDictionary<string, T> where T : class
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int count = dictionary.Count;
				_writer.Write(count);
				foreach (KeyValuePair<string, T> item in dictionary)
				{
					string value = item.Key;
					Translate(ref value);
					T objectToTranslate = item.Value;
					objectTranslator(this, ref objectToTranslate);
				}
			}

			public void TranslateDictionary(ref Dictionary<string, DateTime> dictionary, StringComparer comparer)
			{
				if (!TranslateNullable(dictionary))
				{
					return;
				}
				int count = dictionary.Count;
				_writer.Write(count);
				foreach (KeyValuePair<string, DateTime> item in dictionary)
				{
					string value = item.Key;
					DateTime value2 = item.Value;
					Translate(ref value);
					Translate(ref value2);
				}
			}

			public bool TranslateNullable<T>(T value)
			{
				bool flag = value != null;
				_writer.Write(flag);
				return flag;
			}
		}

		private const string SpecialKeyForDictionaryBeingNull = "=MSBUILDDICTIONARYWASNULL=";

		internal static ITranslator GetReadTranslator(Stream stream, BinaryReaderFactory buffer)
		{
			return new BinaryReadTranslator(stream, buffer);
		}

		internal static ITranslator GetWriteTranslator(Stream stream)
		{
			return new BinaryWriteTranslator(stream);
		}
	}
	internal interface ITranslatable
	{
		void Translate(ITranslator translator);
	}
	internal delegate T NodePacketValueFactory<T>(ITranslator translator);
	internal delegate void ObjectTranslator<T>(ITranslator translator, ref T objectToTranslate);
	internal delegate T NodePacketCollectionCreator<T>(int capacity);
	internal enum TranslationDirection
	{
		WriteToStream,
		ReadFromStream
	}
	internal interface ITranslator : IDisposable
	{
		TranslationDirection Mode { get; }

		BinaryReader Reader { get; }

		BinaryWriter Writer { get; }

		void Translate(ref bool value);

		void Translate(ref bool[] array);

		void Translate(ref byte value);

		void Translate(ref short value);

		void Translate(ref ushort value);

		void Translate(ref int value);

		void Translate(ref uint unsignedInteger);

		void Translate(ref int[] array);

		void Translate(ref long value);

		void Translate(ref string value);

		void Translate(ref double value);

		void Translate(ref string[] array);

		void Translate(ref List<string> list);

		void Translate(ref HashSet<string> set);

		void Translate<T>(ref List<T> list, ObjectTranslator<T> objectTranslator);

		void Translate<T, L>(ref IList<T> list, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<L> collectionFactory) where L : IList<T>;

		void Translate<T, L>(ref ICollection<T> collection, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<L> collectionFactory) where L : ICollection<T>;

		void Translate(ref DateTime value);

		void Translate(ref TimeSpan value);

		void Translate(ref BuildEventContext value);

		void TranslateEnum<T>(ref T value, int numericValue) where T : struct, Enum;

		void TranslateDotNet<T>(ref T value);

		void TranslateException(ref Exception value);

		void Translate<T>(ref T value) where T : ITranslatable, new();

		void TranslateCulture(ref CultureInfo culture);

		void Translate(ref byte[] byteArray);

		void Translate(ref byte[] byteArray, ref int length);

		void TranslateArray<T>(ref T[] array) where T : ITranslatable, new();

		void TranslateArray<T>(ref T[] array, ObjectTranslator<T> objectTranslator);

		void TranslateDictionary(ref Dictionary<string, string> dictionary, IEqualityComparer<string> comparer);

		void TranslateDictionary(ref Dictionary<string, string> dictionary, IEqualityComparer<string> comparer, ref Dictionary<string, string> additionalEntries, HashSet<string> additionalEntriesKeys);

		void TranslateDictionary(ref IDictionary<string, string> dictionary, NodePacketCollectionCreator<IDictionary<string, string>> collectionCreator);

		void TranslateDictionary(ref Dictionary<string, DateTime> dictionary, StringComparer comparer);

		void TranslateDictionary<K, V>(ref IDictionary<K, V> dictionary, ObjectTranslator<K> keyTranslator, ObjectTranslator<V> valueTranslator, NodePacketCollectionCreator<IDictionary<K, V>> dictionaryCreator);

		void TranslateDictionary<T>(ref Dictionary<string, T> dictionary, IEqualityComparer<string> comparer, ObjectTranslator<T> objectTranslator) where T : class;

		void TranslateDictionary<D, T>(ref D dictionary, ObjectTranslator<T> objectTranslator) where D : IDictionary<string, T>, new() where T : class;

		void TranslateDictionary<D, T>(ref D dictionary, ObjectTranslator<T> objectTranslator, NodePacketCollectionCreator<D> collectionCreator) where D : IDictionary<string, T> where T : class;

		bool TranslateNullable<T>(T value);
	}
}
namespace Microsoft.Build.Shared
{
	internal static class AssemblyUtilities
	{
		private static Lazy<Assembly> s_entryAssembly = new Lazy<Assembly>(() => GetEntryAssembly());

		public static Assembly EntryAssembly => s_entryAssembly.Value;

		public static string GetAssemblyLocation(Assembly assembly)
		{
			return assembly.Location;
		}

		public static AssemblyName CloneIfPossible(this AssemblyName assemblyNameToClone)
		{
			AssemblyName assemblyName = new AssemblyName();
			assemblyName.Name = assemblyNameToClone.Name;
			assemblyName.SetPublicKey(assemblyNameToClone.GetPublicKey());
			assemblyName.SetPublicKeyToken(assemblyNameToClone.GetPublicKeyToken());
			assemblyName.Version = assemblyNameToClone.Version;
			assemblyName.Flags = assemblyNameToClone.Flags;
			assemblyName.ProcessorArchitecture = assemblyNameToClone.ProcessorArchitecture;
			assemblyName.CultureInfo = assemblyNameToClone.CultureInfo;
			assemblyName.HashAlgorithm = assemblyNameToClone.HashAlgorithm;
			assemblyName.VersionCompatibility = assemblyNameToClone.VersionCompatibility;
			assemblyName.CodeBase = assemblyNameToClone.CodeBase;
			assemblyName.KeyPair = assemblyNameToClone.KeyPair;
			assemblyName.VersionCompatibility = assemblyNameToClone.VersionCompatibility;
			return assemblyName;
		}

		public static CultureInfo[] GetAllCultures()
		{
			return CultureInfo.GetCultures(CultureTypes.AllCultures);
		}

		private static Assembly GetEntryAssembly()
		{
			return Assembly.GetEntryAssembly();
		}
	}
	internal static class EncodingUtilities
	{
		internal static readonly Encoding Utf8WithoutBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

		private static Encoding s_currentOemEncoding;

		internal const string UseUtf8Always = "ALWAYS";

		internal const string UseUtf8Never = "NEVER";

		internal const string UseUtf8Detect = "DETECT";

		internal const string UseUtf8System = "SYSTEM";

		internal const string UseUtf8True = "TRUE";

		internal static Encoding CurrentSystemOemEncoding
		{
			get
			{
				if (s_currentOemEncoding != null)
				{
					return s_currentOemEncoding;
				}
				s_currentOemEncoding = Encoding.Default;
				try
				{
					if (NativeMethods.IsWindows)
					{
						s_currentOemEncoding = Encoding.GetEncoding(NativeMethods.GetOEMCP());
					}
				}
				catch (ArgumentException)
				{
				}
				catch (NotSupportedException)
				{
				}
				return s_currentOemEncoding;
			}
		}

		internal static bool SimilarToEncoding(this Encoding encoding1, Encoding encoding2)
		{
			if (encoding1 == null)
			{
				return encoding2 == null;
			}
			if (encoding2 == null)
			{
				return false;
			}
			if (object.Equals(encoding1, encoding2))
			{
				return true;
			}
			return encoding1.EncodingName == encoding2.EncodingName;
		}

		internal static bool IsUtf8Encoding(this Encoding encoding)
		{
			return encoding.SimilarToEncoding(Encoding.UTF8);
		}

		internal static bool StartsWithPreamble(this Stream stream)
		{
			return stream.StartsWithPreamble(Encoding.UTF8.GetPreamble());
		}

		internal static bool StartsWithPreamble(this Stream stream, byte[] preamble)
		{
			if (preamble == null)
			{
				return false;
			}
			byte[] array = new byte[preamble.Length];
			long position = stream.Position;
			if (stream.Position != 0L)
			{
				stream.Seek(0L, SeekOrigin.Begin);
			}
			int num;
			try
			{
				num = stream.Read(array, 0, preamble.Length);
			}
			finally
			{
				stream.Seek(position, SeekOrigin.Begin);
			}
			if (num == preamble.Length)
			{
				return !array.Where((byte t, int i) => preamble[i] != t).Any();
			}
			return false;
		}

		internal static bool FileStartsWithPreamble(string file)
		{
			using FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
			return stream.StartsWithPreamble();
		}

		internal static bool CanEncodeString(int codePage, string stringToEncode)
		{
			UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
			byte[] bytes = unicodeEncoding.GetBytes(stringToEncode);
			Encoding encoding = Encoding.GetEncoding(codePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
			try
			{
				Encoding.Convert(unicodeEncoding, encoding, bytes);
				return true;
			}
			catch (EncoderFallbackException)
			{
				return false;
			}
		}

		internal static Encoding BatchFileEncoding(string contents, string encodingSpecification)
		{
			if (!NativeMethods.IsWindows)
			{
				return Utf8WithoutBom;
			}
			Encoding encoding = CurrentSystemOemEncoding;
			if (encoding is UTF8Encoding uTF8Encoding && uTF8Encoding.GetPreamble().Length != 0)
			{
				encoding = Utf8WithoutBom;
			}
			switch ((string.IsNullOrEmpty(encodingSpecification) ? "DETECT" : encodingSpecification).ToUpperInvariant())
			{
			case "ALWAYS":
			case "TRUE":
				return Utf8WithoutBom;
			case "NEVER":
			case "SYSTEM":
				return encoding;
			default:
				if (!CanEncodeString(encoding.CodePage, contents))
				{
					return Utf8WithoutBom;
				}
				return encoding;
			}
		}

		public static CultureInfo? GetExternalOverriddenUILanguageIfSupportableWithEncoding()
		{
			CultureInfo externalOverriddenUILanguage = GetExternalOverriddenUILanguage();
			if (externalOverriddenUILanguage != null)
			{
				if (CurrentPlatformIsWindowsAndOfficiallySupportsUTF8Encoding())
				{
					try
					{
						Console.OutputEncoding = Encoding.UTF8;
						Console.InputEncoding = Encoding.UTF8;
					}
					catch (Exception ex) when (ex is IOException || ex is SecurityException)
					{
					}
					return externalOverriddenUILanguage;
				}
				if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
				{
					return externalOverriddenUILanguage;
				}
			}
			return null;
		}

		public static bool CurrentPlatformIsWindowsAndOfficiallySupportsUTF8Encoding()
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.OSVersion.Version.Major >= 10)
			{
				try
				{
					using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
					string text = registryKey?.GetValue("CurrentBuildNumber")?.ToString();
					return text != null && (int.Parse(text) >= 18363 || ForceUniversalEncodingOptInEnabled());
				}
				catch (Exception ex) when (((ex is SecurityException || ex is ObjectDisposedException) ? 1 : 0) != 0)
				{
					return ForceUniversalEncodingOptInEnabled();
				}
			}
			return false;
		}

		private static bool ForceUniversalEncodingOptInEnabled()
		{
			return string.Equals(Environment.GetEnvironmentVariable("DOTNET_CLI_FORCE_UTF8_ENCODING"), "true", StringComparison.OrdinalIgnoreCase);
		}

		private static CultureInfo? GetExternalOverriddenUILanguage()
		{
			string environmentVariable = Environment.GetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE");
			if (environmentVariable != null)
			{
				try
				{
					return new CultureInfo(environmentVariable);
				}
				catch (CultureNotFoundException)
				{
				}
			}
			return null;
		}
	}
	internal class VisualStudioLocationHelper
	{
		private const int REGDB_E_CLASSNOTREG = -2147221164;

		internal static IList<VisualStudioInstance> GetInstances()
		{
			List<VisualStudioInstance> list = new List<VisualStudioInstance>();
			try
			{
				IEnumSetupInstances enumSetupInstances = ((ISetupConfiguration2)GetQuery()).EnumAllInstances();
				ISetupInstance[] array = new ISetupInstance[1];
				int pceltFetched;
				do
				{
					enumSetupInstances.Next(1, array, out pceltFetched);
					if (pceltFetched > 0)
					{
						ISetupInstance setupInstance = array[0];
						InstanceState state = ((ISetupInstance2)setupInstance).GetState();
						Version version;
						try
						{
							version = new Version(setupInstance.GetInstallationVersion());
						}
						catch (FormatException)
						{
							continue;
						}
						if (state == InstanceState.Complete)
						{
							list.Add(new VisualStudioInstance(setupInstance.GetDisplayName(), setupInstance.GetInstallationPath(), version));
						}
					}
				}
				while (pceltFetched > 0);
			}
			catch (COMException)
			{
			}
			catch (DllNotFoundException)
			{
			}
			return list;
		}

		private static ISetupConfiguration GetQuery()
		{
			try
			{
				return (SetupConfiguration)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("177F0C4A-1CD3-4DE7-A32C-71DBBB9FA36D")));
			}
			catch (COMException ex) when (ex.ErrorCode == -2147221164)
			{
				ISetupConfiguration configuration;
				int setupConfiguration = GetSetupConfiguration(out configuration, IntPtr.Zero);
				if (setupConfiguration < 0)
				{
					throw new COMException("Failed to get query", setupConfiguration);
				}
				return configuration;
			}
		}

		[DllImport("Microsoft.VisualStudio.Setup.Configuration.Native.dll", ExactSpelling = true)]
		private static extern int GetSetupConfiguration([MarshalAs(UnmanagedType.Interface)] out ISetupConfiguration configuration, IntPtr reserved);
	}
	internal class VisualStudioInstance
	{
		internal Version Version { get; }

		internal string Path { get; }

		internal string Name { get; }

		internal VisualStudioInstance(string name, string path, Version version)
		{
			Name = name;
			Path = path;
			Version = version;
		}
	}
	internal static class MSBuildConstants
	{
		internal const string ToolsPath = "MSBuildToolsPath";

		internal const string ToolsPath64 = "MSBuildToolsPath64";

		internal const string SdksPath = "MSBuildSDKsPath";

		internal const string TreatWarningsAsErrors = "MSBuildTreatWarningsAsErrors";

		internal const string WarningsAsErrors = "MSBuildWarningsAsErrors";

		internal const string WarningsNotAsErrors = "MSBuildWarningsNotAsErrors";

		internal const string WarningsAsMessages = "MSBuildWarningsAsMessages";

		internal const string NuGetAssemblyPathEnvironmentVariableName = "MSBUILD_NUGET_PATH";

		internal const string RestoreTargetName = "Restore";

		internal const string CurrentVisualStudioVersion = "17.0";

		internal const string CurrentToolsVersion = "Current";

		internal const string MSBuildDummyGlobalPropertyHeader = "MSBuildProjectInstance";

		internal const string MSBuildRestoreSessionId = "MSBuildRestoreSessionId";

		internal const string MSBuildIsRestoring = "MSBuildIsRestoring";

		internal const string CurrentAssemblyVersion = "15.1.0.0";

		internal const string CurrentProductVersion = "17.0";

		internal const string DefaultTargetsMarker = ".default";

		internal const string StandardTestTargetFrameworkVersion = "v4.8";

		internal const string ProjectReferenceTargetsOrDefaultTargetsMarker = ".projectReferenceTargetsOrDefaultTargets";

		internal static readonly char[] SemicolonChar = new char[1] { ';' };

		internal static readonly char[] SpaceChar = new char[1] { ' ' };

		internal static readonly char[] SingleQuoteChar = new char[1] { '\'' };

		internal static readonly char[] EqualsChar = new char[1] { '=' };

		internal static readonly char[] ColonChar = new char[1] { ':' };

		internal static readonly char[] BackslashChar = new char[1] { '\\' };

		internal static readonly char[] NewlineChar = new char[1] { '\n' };

		internal static readonly char[] CrLf = new char[2] { '\r', '\n' };

		internal static readonly char[] ForwardSlash = new char[1] { '/' };

		internal static readonly char[] ForwardSlashBackslash = new char[2] { '/', '\\' };

		internal static readonly char[] WildcardChars = new char[2] { '*', '?' };

		internal static readonly string[] CharactersForExpansion = new string[5] { "*", "?", "$(", "@(", "%" };

		internal static readonly char[] CommaChar = new char[1] { ',' };

		internal static readonly char[] HyphenChar = new char[1] { '-' };

		internal static readonly char[] DirectorySeparatorChar = new char[1] { Path.DirectorySeparatorChar };

		internal static readonly char[] DotChar = new char[1] { '.' };

		internal static readonly string[] EnvironmentNewLine = new string[1] { Environment.NewLine };

		internal static readonly char[] PipeChar = new char[1] { '|' };

		internal static readonly char[] PathSeparatorChar = new char[1] { Path.PathSeparator };
	}
	internal static class PropertyNames
	{
		internal const string IsGraphBuild = "IsGraphBuild";

		internal const string InnerBuildProperty = "InnerBuildProperty";

		internal const string InnerBuildPropertyValues = "InnerBuildPropertyValues";

		internal const string TargetFrameworks = "TargetFrameworks";

		internal const string TargetFramework = "TargetFramework";
	}
	internal static class DesignTimeProperties
	{
		internal const string DesignTimeBuild = "DesignTimeBuild";

		internal const string BuildingProject = "BuildingProject";
	}
	internal static class ItemTypeNames
	{
		internal const string ProjectReference = "ProjectReference";

		internal const string ProjectReferenceTargets = "ProjectReferenceTargets";

		internal const string GraphIsolationExemptReference = "GraphIsolationExemptReference";

		internal const string ProjectCachePlugin = "ProjectCachePlugin";

		internal const string EmbedInBinlog = "EmbedInBinlog";
	}
	internal static class ItemMetadataNames
	{
		internal const string fusionName = "FusionName";

		internal const string hintPath = "HintPath";

		internal const string assemblyFolderKey = "AssemblyFolderKey";

		internal const string alias = "Alias";

		internal const string aliases = "Aliases";

		internal const string parentFile = "ParentFile";

		internal const string privateMetadata = "Private";

		internal const string copyLocal = "CopyLocal";

		internal const string isRedistRoot = "IsRedistRoot";

		internal const string redist = "Redist";

		internal const string resolvedFrom = "ResolvedFrom";

		internal const string destinationSubDirectory = "DestinationSubDirectory";

		internal const string destinationSubPath = "DestinationSubPath";

		internal const string specificVersion = "SpecificVersion";

		internal const string link = "Link";

		internal const string subType = "SubType";

		internal const string executableExtension = "ExecutableExtension";

		internal const string embedInteropTypes = "EmbedInteropTypes";

		internal const string frameworkReferenceName = "FrameworkReferenceName";

		internal const string assemblyName = "AssemblyName";

		internal const string assemblyVersion = "AssemblyVersion";

		internal const string publicKeyToken = "PublicKeyToken";

		internal const string culture = "Culture";

		internal const string withCulture = "WithCulture";

		internal const string copyToOutputDirectory = "CopyToOutputDirectory";

		internal const string copyAlways = "Always";

		internal const string targetPath = "TargetPath";

		internal const string dependentUpon = "DependentUpon";

		internal const string msbuildSourceProjectFile = "MSBuildSourceProjectFile";

		internal const string msbuildSourceTargetName = "MSBuildSourceTargetName";

		internal const string isPrimary = "IsPrimary";

		internal const string targetFramework = "RequiredTargetFramework";

		internal const string frameworkDirectory = "FrameworkDirectory";

		internal const string version = "Version";

		internal const string imageRuntime = "ImageRuntime";

		internal const string winMDFile = "WinMDFile";

		internal const string winMDFileType = "WinMDFileType";

		internal const string msbuildReferenceSourceTarget = "ReferenceSourceTarget";

		internal const string msbuildReferenceGrouping = "ReferenceGrouping";

		internal const string msbuildReferenceGroupingDisplayName = "ReferenceGroupingDisplayName";

		internal const string msbuildReferenceFromSDK = "ReferenceFromSDK";

		internal const string winmdImplmentationFile = "Implementation";

		internal const string projectReferenceOriginalItemSpec = "ProjectReferenceOriginalItemSpec";

		internal const string IgnoreVersionForFrameworkReference = "IgnoreVersionForFrameworkReference";

		internal const string frameworkFile = "FrameworkFile";

		internal const string ProjectReferenceTargetsMetadataName = "Targets";

		internal const string PropertiesMetadataName = "Properties";

		internal const string UndefinePropertiesMetadataName = "UndefineProperties";

		internal const string AdditionalPropertiesMetadataName = "AdditionalProperties";

		internal const string ProjectConfigurationDescription = "ProjectConfigurationDescription";
	}
	internal static class ItemNames
	{
		internal const string Compile = "Compile";

		internal const string Content = "Content";

		internal const string EmbeddedResource = "EmbeddedResource";

		internal const string None = "None";

		internal const string Reference = "Reference";
	}
	internal static class BinaryReaderExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static string? ReadOptionalString(this BinaryReader reader)
		{
			if (reader.ReadByte() != 0)
			{
				return reader.ReadString();
			}
			return null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int? ReadOptionalInt32(this BinaryReader reader)
		{
			if (reader.ReadByte() != 0)
			{
				return reader.ReadInt32();
			}
			return null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Read7BitEncodedInt(this BinaryReader reader)
		{
			int num = 0;
			int num2 = 0;
			byte b;
			do
			{
				if (num2 == 35)
				{
					throw new FormatException();
				}
				b = reader.ReadByte();
				num |= (b & 0x7F) << num2;
				num2 += 7;
			}
			while ((b & 0x80u) != 0);
			return num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static DateTime ReadTimestamp(this BinaryReader reader)
		{
			long ticks = reader.ReadInt64();
			DateTimeKind kind = (DateTimeKind)reader.ReadInt32();
			return new DateTime(ticks, kind);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static BuildEventContext? ReadOptionalBuildEventContext(this BinaryReader reader)
		{
			if (reader.ReadByte() == 0)
			{
				return null;
			}
			return reader.ReadBuildEventContext();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static BuildEventContext ReadBuildEventContext(this BinaryReader reader)
		{
			int nodeId = reader.ReadInt32();
			int projectContextId = reader.ReadInt32();
			int targetId = reader.ReadInt32();
			int taskId = reader.ReadInt32();
			int submissionId = reader.ReadInt32();
			int projectInstanceId = reader.ReadInt32();
			int evaluationId = reader.ReadInt32();
			return new BuildEventContext(submissionId, nodeId, evaluationId, projectInstanceId, projectContextId, targetId, taskId);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static Guid ReadGuid(this BinaryReader reader)
		{
			return new Guid(reader.ReadBytes(sizeof(Guid)));
		}

		public static void ReadExtendedBuildEventData(this BinaryReader reader, IExtendedBuildEventArgs data)
		{
			data.ExtendedType = reader.ReadString();
			data.ExtendedData = reader.ReadOptionalString();
			if (reader.ReadBoolean())
			{
				data.ExtendedMetadata = new Dictionary<string, string>();
				int num = Read7BitEncodedInt(reader);
				for (int i = 0; i < num; i++)
				{
					string key = reader.ReadString();
					string value = reader.ReadOptionalString();
					data.ExtendedMetadata.Add(key, value);
				}
			}
			else
			{
				data.ExtendedMetadata = null;
			}
		}
	}
	internal static class BinaryWriterExtensions
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteOptionalString(this BinaryWriter writer, string? value)
		{
			if (value == null)
			{
				writer.Write((byte)0);
				return;
			}
			writer.Write((byte)1);
			writer.Write(value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteOptionalInt32(this BinaryWriter writer, int? value)
		{
			if (!value.HasValue)
			{
				writer.Write((byte)0);
				return;
			}
			writer.Write((byte)1);
			writer.Write(value.Value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteTimestamp(this BinaryWriter writer, DateTime timestamp)
		{
			writer.Write(timestamp.Ticks);
			writer.Write((int)timestamp.Kind);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void Write7BitEncodedInt(this BinaryWriter writer, int value)
		{
			uint num;
			for (num = (uint)value; num >= 128; num >>= 7)
			{
				writer.Write((byte)(num | 0x80u));
			}
			writer.Write((byte)num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteOptionalBuildEventContext(this BinaryWriter writer, BuildEventContext? context)
		{
			if (context == null)
			{
				writer.Write((byte)0);
				return;
			}
			writer.Write((byte)1);
			writer.WriteBuildEventContext(context);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void WriteBuildEventContext(this BinaryWriter writer, BuildEventContext context)
		{
			writer.Write(context.NodeId);
			writer.Write(context.ProjectContextId);
			writer.Write(context.TargetId);
			writer.Write(context.TaskId);
			writer.Write(context.SubmissionId);
			writer.Write(context.ProjectInstanceId);
			writer.Write(context.EvaluationId);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static void WriteGuid(this BinaryWriter writer, Guid value)
		{
			Guid guid = value;
			byte* ptr = (byte*)(&guid);
			int num = 0;
			while (num < sizeof(Guid))
			{
				writer.Write(*ptr);
				num++;
				ptr++;
			}
		}

		public static void WriteExtendedBuildEventData(this BinaryWriter writer, IExtendedBuildEventArgs data)
		{
			writer.Write(data.ExtendedType);
			writer.WriteOptionalString(data.ExtendedData);
			writer.Write(data.ExtendedMetadata != null);
			if (data.ExtendedMetadata == null)
			{
				return;
			}
			Write7BitEncodedInt(writer, data.ExtendedMetadata.Count);
			foreach (KeyValuePair<string, string> extendedMetadatum in data.ExtendedMetadata)
			{
				writer.Write(extendedMetadatum.Key);
				writer.WriteOptionalString(extendedMetadatum.Value);
			}
		}
	}
	public interface IMSBuildElementLocation
	{
		string File { get; }

		int Line { get; }

		int Column { get; }

		string LocationString { get; }
	}
}
namespace Microsoft.Build.Shared.Debugging
{
	internal class CommonWriter
	{
		public static Action<string, string, IEnumerable<string>> Writer { get; set; }
	}
}
namespace Microsoft.Build.Framework
{
	public sealed class AssemblyLoadBuildEventArgs : BuildMessageEventArgs
	{
		private const string DefaultAppDomainDescriptor = "[Default]";

		public AssemblyLoadingContext LoadingContext { get; private set; }

		public string? LoadingInitiator { get; private set; }

		public string? AssemblyName { get; private set; }

		public string? AssemblyPath { get; private set; }

		public Guid MVID { get; private set; }

		public string? AppDomainDescriptor { get; private set; }

		public override string Message
		{
			get
			{
				if (base.RawMessage == null)
				{
					string text = ((LoadingInitiator == null) ? null : (" (" + LoadingInitiator + ")"));
					string resourceName = "TaskAssemblyLoaded";
					base.RawMessage = BuildEventArgs.FormatResourceStringIgnoreCodeAndKeyword(resourceName, LoadingContext.ToString(), text, AssemblyName, AssemblyPath, MVID.ToString(), AppDomainDescriptor ?? "[Default]");
				}
				return base.RawMessage;
			}
		}

		public AssemblyLoadBuildEventArgs()
		{
		}

		public AssemblyLoadBuildEventArgs(AssemblyLoadingContext loadingContext, string? loadingInitiator, string? assemblyName, string? assemblyPath, Guid mvid, string? customAppDomainDescriptor, MessageImportance importance = MessageImportance.Low)
			: base(null, null, null, importance, DateTime.UtcNow, null)
		{
			LoadingContext = loadingContext;
			LoadingInitiator = loadingInitiator;
			AssemblyName = assemblyName;
			AssemblyPath = assemblyPath;
			MVID = mvid;
			AppDomainDescriptor = customAppDomainDescriptor;
		}

		internal override void WriteToStream(BinaryWriter writer)
		{
			base.WriteToStream(writer);
			BinaryWriterExtensions.Write7BitEncodedInt(writer, (int)LoadingContext);
			writer.WriteTimestamp(base.RawTimestamp);
			writer.WriteOptionalBuildEventContext(base.BuildEventContext);
			writer.WriteGuid(MVID);
			writer.WriteOptionalString(LoadingInitiator);
			writer.WriteOptionalString(AssemblyName);
			writer.WriteOptionalString(AssemblyPath);
			writer.WriteOptionalString(AppDomainDescriptor);
		}

		internal override void CreateFromStream(BinaryReader reader, int version)
		{
			base.CreateFromStream(reader, version);
			LoadingContext = (AssemblyLoadingContext)BinaryReaderExtensions.Read7BitEncodedInt(reader);
			base.RawTimestamp = reader.ReadTimestamp();
			base.BuildEventContext = reader.ReadOptionalBuildEventContext();
			MVID = reader.ReadGuid();
			LoadingInitiator = reader.ReadOptionalString();
			AssemblyName = reader.ReadOptionalString();
			AssemblyPath = reader.ReadOptionalString();
			AppDomainDescriptor = reader.ReadOptionalString();
		}
	}
	public enum AssemblyLoadingContext
	{
		TaskRun,
		Evaluation,
		SdkResolution,
		LoggerInitialization
	}
	public sealed class BuildCanceledEventArgs : BuildStatusEventArgs
	{
		public BuildCanceledEventArgs(string message)
			: this(message, DateTime.UtcNow)
		{
		}

		public BuildCanceledEventArgs(string message, DateTime eventTimestamp)
			: this(message, eventTimestamp, null)
		{
		}

		public BuildCanceledEventArgs(string message, DateTime eventTimestamp, params object[]? messageArgs)
			: base(message, null, "MSBuild", eventTimestamp, messageArgs)
		{
			if (string.IsNullOrWhiteSpace(message))
			{
				throw new InternalErrorException("Message cannot be null or consist only white-space characters.");
			}
		}
	}
	[Serializable]
	public struct BuildEngineResult
	{
		private bool buildResult;

		private List<IDictionary<string, ITaskItem[]>> targetOutputsPerProject;

		public readonly bool Result => buildResult;

		public IList<IDictionary<string, ITaskItem[]>> TargetOutputsPerProject => targetOutputsPerProject;

		public BuildEngineResult(bool result, List<IDictionary<string, ITaskItem[]>> targetOutputsPerProject)
		{
			buildResult = result;
			this.targetOutputsPerProject = targetOutputsPerProject;
			if (this.targetOutputsPerProject == null)
			{
				this.targetOutputsPerProject = new List<IDictionary<string, ITaskItem[]>>();
			}
		}
	}
	internal static class BuildEnvironmentState
	{
		internal static bool s_runningInVisualStudio;

		internal static bool s_runningTests;
	}
	[Serializable]
	public class BuildErrorEventArgs : LazyFormattedBuildEventArgs
	{
		private string subcategory;

		private string code;

		private string file;

		private string projectFile;

		private int lineNumber;

		private int columnNumber;

		private int endLineNumber;

		private int endColumnNumber;

		private string helpLink;

		public string Subcategory => subcategory;

		public string Code => code;

		public string File => file;

		public string ProjectFile
		{
			get
			{
				return projectFile;
			}
			set
			{
				projectFile = value;
			}
		}

		public int LineNumber => lineNumber;

		public int ColumnNumber => columnNumber;

		public int EndLineNumber => endLineNumber;

		public int EndColumnNumber => endColumnNumber;

		public string HelpLink => helpLink;

		public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName)
			: this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, DateTime.UtcNow)
		{
		}

		public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string helpKeyword, string senderName, DateTime eventTimestamp)
			: this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, null, eventTimestamp, null)
		{
		}

		public BuildErrorEventArgs(string subcategory, string code, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, [StringSyntax("CompositeFormat")] string message, string helpKeyword, string senderName, DateTime eventT

folder/Microsoft.Build.Utilities.Core.dll

Decompiled 11 months ago
#define TRACE
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using Microsoft.Build.Collections;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.AssemblyFoldersFromConfig;
using Microsoft.Build.Shared.Debugging;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Tasks.AssemblyFoldersFromConfig;
using Microsoft.Build.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.IO;
using Microsoft.NET.StringTools;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Build.Utilities.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.SafeDirectories)]
[assembly: NeutralResourcesLanguage("en")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Microsoft.Build.Utilities.Core.dll")]
[assembly: AssemblyFileVersion("17.13.9.7704")]
[assembly: AssemblyInformationalVersion("17.13.9+e0f243f1e205c45b3b04097facd9948a881f9047")]
[assembly: AssemblyProduct("Microsoft® Build Tools®")]
[assembly: AssemblyTitle("Microsoft.Build.Utilities.Core.dll")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/msbuild")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("15.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace Microsoft.Build.Evaluation
{
	internal static class ToolsetConfigurationReaderHelpers
	{
		private static readonly object s_syncLock = new object();

		private static ToolsetConfigurationSection s_toolsetConfigurationSectionCache;

		private static Configuration s_configurationOfCachedSection;

		internal static ToolsetConfigurationSection ReadToolsetConfigurationSection(Configuration configuration)
		{
			if (configuration == null)
			{
				return null;
			}
			lock (s_syncLock)
			{
				if (s_toolsetConfigurationSectionCache == null)
				{
					s_toolsetConfigurationSectionCache = GetToolsetConfigurationSection(configuration);
					s_configurationOfCachedSection = configuration;
				}
				return (s_configurationOfCachedSection == configuration) ? s_toolsetConfigurationSectionCache : GetToolsetConfigurationSection(configuration);
			}
		}

		private static ToolsetConfigurationSection GetToolsetConfigurationSection(Configuration configuration)
		{
			ToolsetConfigurationSection toolsetConfigurationSection = null;
			if (configuration != null)
			{
				ConfigurationSection section = configuration.GetSection("msbuildToolsets");
				toolsetConfigurationSection = section as ToolsetConfigurationSection;
				if (toolsetConfigurationSection == null && section != null && (string.IsNullOrEmpty(section.SectionInformation.Type) || section.SectionInformation.Type.IndexOf("Microsoft.Build", StringComparison.OrdinalIgnoreCase) >= 0))
				{
					section.SectionInformation.Type = typeof(ToolsetConfigurationSection).AssemblyQualifiedName;
					try
					{
						string temporaryFile = FileUtilities.GetTemporaryFile();
						configuration.SaveAs(temporaryFile + ".config");
						configuration = ConfigurationManager.OpenExeConfiguration(temporaryFile);
						toolsetConfigurationSection = configuration.GetSection("msbuildToolsets") as ToolsetConfigurationSection;
						File.Delete(temporaryFile + ".config");
						File.Delete(temporaryFile);
					}
					catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
					{
					}
				}
			}
			return toolsetConfigurationSection;
		}
	}
	internal sealed class ToolsetElement : ConfigurationElement
	{
		internal sealed class ExtensionsPathsElementCollection : ConfigurationElementCollection
		{
			private Dictionary<string, string> _previouslySeenOS = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

			public override ConfigurationElementCollectionType CollectionType => (ConfigurationElementCollectionType)0;

			protected override bool ThrowOnDuplicate => false;

			protected override string ElementName => "searchPaths";

			public ExtensionsPathElement GetElement(string os)
			{
				return (ExtensionsPathElement)(object)((ConfigurationElementCollection)this).BaseGet((object)os);
			}

			public ExtensionsPathElement GetElement(int index)
			{
				return (ExtensionsPathElement)(object)((ConfigurationElementCollection)this).BaseGet(index);
			}

			protected override object GetElementKey(ConfigurationElement element)
			{
				return ((ExtensionsPathElement)(object)element).OS;
			}

			protected override ConfigurationElement CreateNewElement()
			{
				return (ConfigurationElement)(object)new ExtensionsPathElement();
			}

			protected override void BaseAdd(int index, ConfigurationElement element)
			{
				UpdateOSMap(element);
				((ConfigurationElementCollection)this).BaseAdd(index, element);
			}

			protected override void BaseAdd(ConfigurationElement element)
			{
				UpdateOSMap(element);
				((ConfigurationElementCollection)this).BaseAdd(element);
			}

			private void UpdateOSMap(ConfigurationElement element)
			{
				//IL_0099: Unknown result type (might be due to invalid IL or missing references)
				string text = ((ConfigurationElementCollection)this).GetElementKey(element).ToString();
				if (_previouslySeenOS.ContainsKey(text))
				{
					string arg = string.Empty;
					if (!string.IsNullOrEmpty(element.ElementInformation.Source))
					{
						arg = ((element.ElementInformation.LineNumber == 0) ? element.ElementInformation.Source : $"{element.ElementInformation.Source} ({element.ElementInformation.LineNumber})");
					}
					throw new ConfigurationErrorsException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("MultipleDefinitionsForSameExtensionsPathOS", text, arg), element.ElementInformation.Source, element.ElementInformation.LineNumber);
				}
				_previouslySeenOS.Add(text, string.Empty);
			}
		}

		internal sealed class ExtensionsPathElement : ConfigurationElement
		{
			[ConfigurationProperty("os", IsKey = true, IsRequired = true)]
			public string OS
			{
				get
				{
					return (string)((ConfigurationElement)this)["os"];
				}
				set
				{
					((ConfigurationElement)this)["os"] = value;
				}
			}

			[ConfigurationProperty("", IsDefaultCollection = true)]
			public PropertyElementCollection PropertyElements => (PropertyElementCollection)((ConfigurationElement)this)[""];
		}

		internal sealed class PropertyElementCollection : ConfigurationElementCollection
		{
			private Dictionary<string, string> _previouslySeenPropertyNames = new Dictionary<string, string>(MSBuildNameIgnoreCaseComparer.Default);

			public override ConfigurationElementCollectionType CollectionType => (ConfigurationElementCollectionType)0;

			protected override bool ThrowOnDuplicate => false;

			protected override string ElementName => "property";

			public PropertyElement GetElement(string name)
			{
				return (PropertyElement)(object)((ConfigurationElementCollection)this).BaseGet((object)name);
			}

			public PropertyElement GetElement(int index)
			{
				return (PropertyElement)(object)((ConfigurationElementCollection)this).BaseGet(index);
			}

			protected override ConfigurationElement CreateNewElement()
			{
				return (ConfigurationElement)(object)new PropertyElement();
			}

			protected override void BaseAdd(int index, ConfigurationElement element)
			{
				UpdatePropertyNameMap(element);
				((ConfigurationElementCollection)this).BaseAdd(index, element);
			}

			protected override void BaseAdd(ConfigurationElement element)
			{
				UpdatePropertyNameMap(element);
				((ConfigurationElementCollection)this).BaseAdd(element);
			}

			protected override object GetElementKey(ConfigurationElement element)
			{
				return ((PropertyElement)(object)element).Name;
			}

			private void UpdatePropertyNameMap(ConfigurationElement element)
			{
				//IL_003c: Unknown result type (might be due to invalid IL or missing references)
				string text = ((ConfigurationElementCollection)this).GetElementKey(element).ToString();
				if (_previouslySeenPropertyNames.ContainsKey(text))
				{
					throw new ConfigurationErrorsException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("MultipleDefinitionsForSameProperty", text), element.ElementInformation.Source, element.ElementInformation.LineNumber);
				}
				_previouslySeenPropertyNames.Add(text, string.Empty);
			}
		}

		internal sealed class PropertyElement : ConfigurationElement
		{
			[ConfigurationProperty("name", IsKey = true, IsRequired = true)]
			public string Name
			{
				get
				{
					return (string)((ConfigurationElement)this)["name"];
				}
				set
				{
					((ConfigurationElement)this)["name"] = value;
				}
			}

			[ConfigurationProperty("value", IsRequired = true)]
			public string Value
			{
				get
				{
					return (string)((ConfigurationElement)this)["value"];
				}
				set
				{
					((ConfigurationElement)this)["value"] = value;
				}
			}
		}

		[ConfigurationProperty("toolsVersion", IsKey = true, IsRequired = true)]
		public string toolsVersion
		{
			get
			{
				return (string)((ConfigurationElement)this)["toolsVersion"];
			}
			set
			{
				((ConfigurationElement)this)["toolsVersion"] = value;
			}
		}

		[ConfigurationProperty("", IsDefaultCollection = true)]
		public PropertyElementCollection PropertyElements => (PropertyElementCollection)((ConfigurationElement)this)[""];

		[ConfigurationProperty("projectImportSearchPaths")]
		public ExtensionsPathsElementCollection AllProjectImportSearchPaths => (ExtensionsPathsElementCollection)((ConfigurationElement)this)["projectImportSearchPaths"];
	}
	internal sealed class ToolsetElementCollection : ConfigurationElementCollection
	{
		private Dictionary<string, string> _previouslySeenToolsVersions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		public override ConfigurationElementCollectionType CollectionType => (ConfigurationElementCollectionType)0;

		protected override bool ThrowOnDuplicate => false;

		protected override string ElementName => "toolset";

		public ToolsetElement GetElement(string toolsVersion)
		{
			return (ToolsetElement)(object)((ConfigurationElementCollection)this).BaseGet((object)toolsVersion);
		}

		public ToolsetElement GetElement(int index)
		{
			return (ToolsetElement)(object)((ConfigurationElementCollection)this).BaseGet(index);
		}

		protected override object GetElementKey(ConfigurationElement element)
		{
			return ((ToolsetElement)(object)element).toolsVersion;
		}

		protected override ConfigurationElement CreateNewElement()
		{
			return (ConfigurationElement)(object)new ToolsetElement();
		}

		protected override void BaseAdd(int index, ConfigurationElement element)
		{
			UpdateToolsVersionMap(element);
			((ConfigurationElementCollection)this).BaseAdd(index, element);
		}

		protected override void BaseAdd(ConfigurationElement element)
		{
			UpdateToolsVersionMap(element);
			((ConfigurationElementCollection)this).BaseAdd(element);
		}

		private void UpdateToolsVersionMap(ConfigurationElement element)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			string text = ((ConfigurationElementCollection)this).GetElementKey(element).ToString();
			if (_previouslySeenToolsVersions.ContainsKey(text))
			{
				throw new ConfigurationErrorsException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("MultipleDefinitionsForSameToolset", text), element.ElementInformation.Source, element.ElementInformation.LineNumber);
			}
			_previouslySeenToolsVersions.Add(text, string.Empty);
		}
	}
	internal sealed class ToolsetConfigurationSection : ConfigurationSection
	{
		[ConfigurationProperty("", IsDefaultCollection = true)]
		public ToolsetElementCollection Toolsets => (ToolsetElementCollection)((ConfigurationElement)this)[""];

		[ConfigurationProperty("default")]
		public string Default
		{
			get
			{
				string text = (string)((ConfigurationElement)this)["default"];
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
				return null;
			}
			set
			{
				((ConfigurationElement)this)["default"] = value;
			}
		}

		[ConfigurationProperty("msbuildOverrideTasksPath")]
		public string MSBuildOverrideTasksPath
		{
			get
			{
				string text = (string)((ConfigurationElement)this)["msbuildOverrideTasksPath"];
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
				return null;
			}
			set
			{
				((ConfigurationElement)this)["msbuildOverrideTasksPath"] = value;
			}
		}

		[ConfigurationProperty("DefaultOverrideToolsVersion")]
		public string DefaultOverrideToolsVersion
		{
			get
			{
				string text = (string)((ConfigurationElement)this)["DefaultOverrideToolsVersion"];
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
				return null;
			}
			set
			{
				((ConfigurationElement)this)["DefaultOverrideToolsVersion"] = value;
			}
		}
	}
}
namespace Microsoft.Build.Internal
{
	internal static class Tracing
	{
		private static Dictionary<string, int> s_counts;

		private static DateTime s_last = DateTime.MinValue;

		private static TimeSpan s_interval;

		private static string s_slot = string.Empty;

		private static string s_currentAssemblyName;

		[Conditional("DEBUG")]
		internal static void Slot(string tag, string value)
		{
			lock (s_counts)
			{
				s_slot = tag + ": " + value;
			}
		}

		[Conditional("DEBUG")]
		internal static void Slot<K, V>(string tag, KeyValuePair<K, V> value)
		{
		}

		[Conditional("DEBUG")]
		internal static void Record(string counter)
		{
			lock (s_counts)
			{
				s_counts.TryGetValue(counter, out var value);
				int value2 = ++value;
				s_counts[counter] = value2;
				DateTime now = DateTime.Now;
				if (now > s_last + s_interval)
				{
					Trace.WriteLine("================================================");
					Trace.WriteLine(s_slot);
					s_slot = string.Empty;
					Trace.WriteLine(Environment.StackTrace);
					s_last = now;
				}
			}
		}

		[Conditional("DEBUG")]
		internal static void List<T>(IEnumerable<T> items)
		{
			foreach (T item in items)
			{
				Trace.WriteLine(item.ToString());
			}
		}

		[Conditional("DEBUG")]
		internal static void Dump()
		{
			if (s_counts.Count <= 0)
			{
				return;
			}
			Trace.WriteLine(s_currentAssemblyName);
			foreach (KeyValuePair<string, int> s_count in s_counts)
			{
				Trace.WriteLine("# " + s_count.Key + "=" + s_count.Value);
			}
		}
	}
}
namespace Microsoft.Build.Collections
{
	[Serializable]
	internal class CopyOnWriteDictionary<V> : IDictionary<string, V>, ICollection<KeyValuePair<string, V>>, IEnumerable<KeyValuePair<string, V>>, IEnumerable, IDictionary, ICollection, ISerializable
	{
		private static readonly ImmutableDictionary<string, V> NameComparerDictionaryPrototype = ImmutableDictionary.Create<string, V>((IEqualityComparer<string>)MSBuildNameIgnoreCaseComparer.Default);

		private static readonly ImmutableDictionary<string, V> OrdinalIgnoreCaseComparerDictionaryPrototype = ImmutableDictionary.Create<string, V>((IEqualityComparer<string>)StringComparer.OrdinalIgnoreCase);

		private ImmutableDictionary<string, V> _backing;

		public ICollection<string> Keys => ((IDictionary<string, V>)_backing).Keys;

		public ICollection<V> Values => ((IDictionary<string, V>)_backing).Values;

		public int Count => ((ImmutableDictionary<string, string>)(object)_backing).Count;

		public bool IsReadOnly => ((ICollection<KeyValuePair<string, V>>)_backing).IsReadOnly;

		bool IDictionary.IsFixedSize => false;

		bool IDictionary.IsReadOnly => IsReadOnly;

		ICollection IDictionary.Keys => (ICollection)Keys;

		ICollection IDictionary.Values => (ICollection)Values;

		int ICollection.Count => Count;

		bool ICollection.IsSynchronized => false;

		object ICollection.SyncRoot => this;

		internal IEqualityComparer<string> Comparer
		{
			get
			{
				return ((ImmutableDictionary<string, string>)(object)_backing).KeyComparer;
			}
			private set
			{
				_backing = ((ImmutableDictionary<string, string>)(object)_backing).WithComparers(value);
			}
		}

		public V this[string key]
		{
			get
			{
				return ((ImmutableDictionary<string, string>)(object)_backing)[key];
			}
			set
			{
				_backing = ((ImmutableDictionary<string, string>)(object)_backing).SetItem(key, (string)value);
			}
		}

		object? IDictionary.this[object key]
		{
			get
			{
				TryGetValue((string)key, out var value);
				return value;
			}
			set
			{
				this[(string)key] = (V)value;
			}
		}

		internal CopyOnWriteDictionary()
		{
			_backing = ImmutableDictionary<string, V>.Empty;
		}

		internal CopyOnWriteDictionary(IEqualityComparer<string>? keyComparer)
		{
			_backing = GetInitialDictionary(keyComparer);
		}

		protected CopyOnWriteDictionary(SerializationInfo info, StreamingContext context)
		{
			object value = info.GetValue("_backing", typeof(KeyValuePair<string, V>[]));
			ImmutableDictionary<string, V> initialDictionary = GetInitialDictionary((IEqualityComparer<string>)info.GetValue("Comparer", typeof(IEqualityComparer<string>)));
			_backing = ((ImmutableDictionary<string, string>)(object)initialDictionary).AddRange((IEnumerable<KeyValuePair<string, string>>)(object)(KeyValuePair<string, V>[])value);
		}

		private static ImmutableDictionary<string, V> GetInitialDictionary(IEqualityComparer<string>? keyComparer)
		{
			if (!(keyComparer is MSBuildNameIgnoreCaseComparer))
			{
				if (keyComparer != StringComparer.OrdinalIgnoreCase)
				{
					return ImmutableDictionary.Create<string, V>(keyComparer);
				}
				return OrdinalIgnoreCaseComparerDictionaryPrototype;
			}
			return NameComparerDictionaryPrototype;
		}

		private CopyOnWriteDictionary(CopyOnWriteDictionary<V> that)
		{
			_backing = that._backing;
		}

		public CopyOnWriteDictionary(IDictionary<string, V> dictionary)
		{
			_backing = ImmutableDictionary.ToImmutableDictionary<string, V>((IEnumerable<KeyValuePair<string, V>>)dictionary);
		}

		public void Add(string key, V value)
		{
			_backing = ((ImmutableDictionary<string, string>)(object)_backing).SetItem(key, (string)value);
		}

		public void SetItems(IEnumerable<KeyValuePair<string, V>> items)
		{
			_backing = ((ImmutableDictionary<string, string>)(object)_backing).SetItems((IEnumerable<KeyValuePair<string, string>>)items);
		}

		public IEnumerable<KeyValuePair<string, V>> Where(Func<KeyValuePair<string, V>, bool> predicate)
		{
			return ((IEnumerable<KeyValuePair<string, V>>)_backing).Where<KeyValuePair<string, V>>(predicate);
		}

		public bool ContainsKey(string key)
		{
			return ((ImmutableDictionary<string, string>)(object)_backing).ContainsKey(key);
		}

		public bool Remove(string key)
		{
			ImmutableDictionary<string, V> backing = _backing;
			_backing = ((ImmutableDictionary<string, string>)(object)_backing).Remove(key);
			return backing != _backing;
		}

		public bool TryGetValue(string key, out V value)
		{
			return ((ImmutableDictionary<string, string>)(object)_backing).TryGetValue(key, ref System.Runtime.CompilerServices.Unsafe.As<V, string>(ref value));
		}

		public void Add(KeyValuePair<string, V> item)
		{
			_backing = ((ImmutableDictionary<string, string>)(object)_backing).SetItem(item.Key, (string)item.Value);
		}

		public void Clear()
		{
			_backing = ((ImmutableDictionary<string, string>)(object)_backing).Clear();
		}

		public bool Contains(KeyValuePair<string, V> item)
		{
			return ((ImmutableDictionary<string, string>)(object)_backing).Contains((KeyValuePair<string, string>)item);
		}

		public void CopyTo(KeyValuePair<string, V>[] array, int arrayIndex)
		{
			((ICollection<KeyValuePair<string, V>>)_backing).CopyTo(array, arrayIndex);
		}

		public bool Remove(KeyValuePair<string, V> item)
		{
			ImmutableDictionary<string, V> backing = _backing;
			_backing = ((ImmutableDictionary<string, string>)(object)_backing).Remove(item.Key);
			return backing != _backing;
		}

		public IEnumerator<KeyValuePair<string, V>> GetEnumerator()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			return (IEnumerator<KeyValuePair<string, V>>)(object)((ImmutableDictionary<string, string>)(object)_backing).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<KeyValuePair<string, V>>)this).GetEnumerator();
		}

		void IDictionary.Add(object key, object value)
		{
			Add((string)key, (V)value);
		}

		void IDictionary.Clear()
		{
			Clear();
		}

		bool IDictionary.Contains(object key)
		{
			return ContainsKey((string)key);
		}

		IDictionaryEnumerator IDictionary.GetEnumerator()
		{
			return ((IDictionary)_backing).GetEnumerator();
		}

		void IDictionary.Remove(object key)
		{
			Remove((string)key);
		}

		void ICollection.CopyTo(Array array, int index)
		{
			int num = 0;
			using IEnumerator<KeyValuePair<string, V>> enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				KeyValuePair<string, V> current = enumerator.Current;
				array.SetValue(new DictionaryEntry(current.Key, current.Value), index + num);
				num++;
			}
		}

		internal CopyOnWriteDictionary<V> Clone()
		{
			return new CopyOnWriteDictionary<V>(this);
		}

		internal bool HasSameBacking(CopyOnWriteDictionary<V> other)
		{
			return other._backing == _backing;
		}

		public void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			KeyValuePair<string, V>[] value = ((IEnumerable<KeyValuePair<string, V>>)_backing).ToArray();
			info.AddValue("_backing", value);
			info.AddValue("Comparer", Comparer);
		}
	}
	internal interface IConstrainedEqualityComparer<in T> : IEqualityComparer<T>
	{
		bool Equals(T x, T y, int indexY, int length);

		int GetHashCode(T obj, int index, int length);
	}
	internal interface IKeyed
	{
		string Key { get; }
	}
	[Serializable]
	internal class MSBuildNameIgnoreCaseComparer : IConstrainedEqualityComparer<string>, IEqualityComparer<string>
	{
		private static readonly ProcessorArchitectures s_runningProcessorArchitecture = NativeMethods.ProcessorArchitecture;

		internal static MSBuildNameIgnoreCaseComparer Default { get; } = new MSBuildNameIgnoreCaseComparer();


		public bool Equals(string x, string y)
		{
			return Equals(x, y, 0, y?.Length ?? 0);
		}

		public int GetHashCode(string obj)
		{
			return GetHashCode(obj, 0, obj?.Length ?? 0);
		}

		public unsafe bool Equals(string compareToString, string constrainedString, int start, int lengthToCompare)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Invalid comparison between Unknown and I4
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Invalid comparison between Unknown and I4
			if (lengthToCompare < 0)
			{
				ErrorUtilities.ThrowInternalError("Invalid lengthToCompare '{0}' {1} {2}", constrainedString, start, lengthToCompare);
			}
			if (start < 0 || start > (constrainedString?.Length ?? 0) - lengthToCompare)
			{
				ErrorUtilities.ThrowInternalError("Invalid start '{0}' {1} {2}", constrainedString, start, lengthToCompare);
			}
			if ((object)compareToString == constrainedString)
			{
				return true;
			}
			if (compareToString == null || constrainedString == null)
			{
				return false;
			}
			if (lengthToCompare != compareToString.Length)
			{
				return false;
			}
			if ((int)s_runningProcessorArchitecture != 2 && (int)s_runningProcessorArchitecture != 3)
			{
				fixed (char* ptr = compareToString)
				{
					fixed (char* ptr2 = constrainedString)
					{
						for (int i = 0; i < compareToString.Length; i++)
						{
							char num = ptr[i];
							int num2 = ptr2[i + start];
							int num3 = num & 0xDF;
							num2 &= 0xDF;
							if (num3 != num2)
							{
								return false;
							}
						}
					}
				}
				return true;
			}
			return string.Compare(compareToString, 0, constrainedString, start, lengthToCompare, StringComparison.OrdinalIgnoreCase) == 0;
		}

		public unsafe int GetHashCode(string obj, int start, int length)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Invalid comparison between Unknown and I4
			if (obj == null)
			{
				return 0;
			}
			if ((int)s_runningProcessorArchitecture != 2 && (int)s_runningProcessorArchitecture != 3)
			{
				fixed (char* ptr = obj)
				{
					int num = 352654597;
					int num2 = num;
					int* ptr2 = (int*)(ptr + start);
					while (length > 0)
					{
						int num3 = *ptr2 & 0xDF00DF;
						if (length == 1)
						{
							num3 = ((!BitConverter.IsLittleEndian) ? (num3 & -65536) : (num3 & 0xFFFF));
						}
						num = ((num << 5) + num + (num >> 27)) ^ num3;
						if (length <= 2)
						{
							break;
						}
						num3 = ptr2[1] & 0xDF00DF;
						if (length == 3)
						{
							num3 = ((!BitConverter.IsLittleEndian) ? (num3 & -65536) : (num3 & 0xFFFF));
						}
						num2 = ((num2 << 5) + num2 + (num2 >> 27)) ^ num3;
						ptr2 += 2;
						length -= 4;
					}
					return num + num2 * 1566083941;
				}
			}
			return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Substring(start, length));
		}
	}
	internal class ReadOnlyEmptyCollection<T> : ICollection<T>, IEnumerable<T>, IEnumerable, ICollection
	{
		[CompilerGenerated]
		private sealed class <GetEnumerator>d__17 : IEnumerator<T>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private T <>2__current;

			T IEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetEnumerator>d__17(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				if (<>1__state != 0)
				{
					return false;
				}
				<>1__state = -1;
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private static ReadOnlyEmptyCollection<T> s_instance;

		public static ReadOnlyEmptyCollection<T> Instance
		{
			get
			{
				if (s_instance == null)
				{
					s_instance = new ReadOnlyEmptyCollection<T>();
				}
				return s_instance;
			}
		}

		public int Count => 0;

		public bool IsReadOnly => true;

		bool ICollection.IsSynchronized => false;

		object ICollection.SyncRoot => this;

		private ReadOnlyEmptyCollection()
		{
		}

		public void Add(T item)
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
		}

		public void Clear()
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
		}

		public bool Contains(T item)
		{
			return false;
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
		}

		public bool Remove(T item)
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
			return false;
		}

		[IteratorStateMachine(typeof(ReadOnlyEmptyCollection<>.<GetEnumerator>d__17))]
		public IEnumerator<T> GetEnumerator()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetEnumerator>d__17(0);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		void ICollection.CopyTo(Array array, int index)
		{
		}
	}
	internal class ReadOnlyEmptyDictionary<K, V> : IDictionary<K, V>, ICollection<KeyValuePair<K, V>>, IEnumerable<KeyValuePair<K, V>>, IEnumerable, IReadOnlyDictionary<K, V>, IReadOnlyCollection<KeyValuePair<K, V>>, IDictionary, ICollection
	{
		private static readonly Dictionary<K, V> s_backing = new Dictionary<K, V>();

		private static ReadOnlyEmptyDictionary<K, V> s_instance;

		public static ReadOnlyEmptyDictionary<K, V> Instance
		{
			get
			{
				if (s_instance == null)
				{
					s_instance = new ReadOnlyEmptyDictionary<K, V>();
				}
				return s_instance;
			}
		}

		public int Count => 0;

		public bool IsReadOnly => true;

		public ICollection<K> Keys => Array.Empty<K>();

		public ICollection<V> Values => Array.Empty<V>();

		public bool IsFixedSize => true;

		public bool IsSynchronized => false;

		public object SyncRoot => null;

		ICollection IDictionary.Keys => (ICollection)((IDictionary<K, V>)this).Keys;

		ICollection IDictionary.Values => (ICollection)((IDictionary<K, V>)this).Values;

		IEnumerable<K> IReadOnlyDictionary<K, V>.Keys => Keys;

		IEnumerable<V> IReadOnlyDictionary<K, V>.Values => Values;

		public object this[object key]
		{
			get
			{
				return ((IDictionary<K, V>)this)[(K)key];
			}
			set
			{
				((IDictionary<K, V>)this)[(K)key] = (V)value;
			}
		}

		public V this[K key]
		{
			get
			{
				return new Dictionary<K, V>()[key];
			}
			set
			{
				ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
			}
		}

		private ReadOnlyEmptyDictionary()
		{
		}

		public void Add(K key, V value)
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
		}

		public bool ContainsKey(K key)
		{
			return false;
		}

		public bool Remove(K key)
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
			return false;
		}

		public bool TryGetValue(K key, out V value)
		{
			value = default(V);
			return false;
		}

		public void Add(KeyValuePair<K, V> item)
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
		}

		public void Clear()
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
		}

		public bool Contains(KeyValuePair<K, V> item)
		{
			return false;
		}

		public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
		{
		}

		public bool Remove(KeyValuePair<K, V> item)
		{
			ErrorUtilities.ThrowInvalidOperation("OM_NotSupportedReadOnlyCollection");
			return false;
		}

		public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
		{
			return Enumerable.Empty<KeyValuePair<K, V>>().GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public void Add(object key, object value)
		{
			((IDictionary<K, V>)this).Add((K)key, (V)value);
		}

		public bool Contains(object key)
		{
			return ((IDictionary<K, V>)this).ContainsKey((K)key);
		}

		IDictionaryEnumerator IDictionary.GetEnumerator()
		{
			return ((IDictionary)s_backing).GetEnumerator();
		}

		public void Remove(object key)
		{
			((IDictionary<K, V>)this).Remove((K)key);
		}

		public void CopyTo(Array array, int index)
		{
		}
	}
}
namespace Microsoft.Build.Tasks.AssemblyFoldersFromConfig
{
	internal class AssemblyFoldersFromConfig : IEnumerable<AssemblyFoldersFromConfigInfo>, IEnumerable
	{
		private readonly List<AssemblyFoldersFromConfigInfo> _directoryNames = new List<AssemblyFoldersFromConfigInfo>();

		internal AssemblyFoldersFromConfig(string configFile, string targetRuntimeVersion, System.Reflection.ProcessorArchitecture targetArchitecture)
		{
			ErrorUtilities.VerifyThrowArgumentNull(configFile, "configFile");
			ErrorUtilities.VerifyThrowArgumentNull(targetRuntimeVersion, "targetRuntimeVersion");
			AssemblyFolderCollection collection = AssemblyFolderCollection.Load(configFile);
			List<AssemblyFolderItem> assemblyTargets = GatherVersionStrings(targetRuntimeVersion, collection);
			bool flag = targetArchitecture == System.Reflection.ProcessorArchitecture.Amd64 || targetArchitecture == System.Reflection.ProcessorArchitecture.IA64;
			FindDirectories(assemblyTargets, (AssemblyFolderItem target) => string.IsNullOrEmpty(target.Platform));
			if (EnvironmentUtilities.Is64BitOperatingSystem)
			{
				if (flag)
				{
					FindDirectories(assemblyTargets, (AssemblyFolderItem target) => !string.IsNullOrEmpty(target.Platform) && target.Platform.Equals("x64", StringComparison.OrdinalIgnoreCase));
					FindDirectories(assemblyTargets, (AssemblyFolderItem target) => !string.IsNullOrEmpty(target.Platform) && target.Platform.Equals("x86", StringComparison.OrdinalIgnoreCase));
				}
				else
				{
					FindDirectories(assemblyTargets, (AssemblyFolderItem target) => !string.IsNullOrEmpty(target.Platform) && target.Platform.Equals("x86", StringComparison.OrdinalIgnoreCase));
					FindDirectories(assemblyTargets, (AssemblyFolderItem target) => !string.IsNullOrEmpty(target.Platform) && target.Platform.Equals("x64", StringComparison.OrdinalIgnoreCase));
				}
			}
			else
			{
				FindDirectories(assemblyTargets, (AssemblyFolderItem target) => !string.IsNullOrEmpty(target.Platform) && target.Platform.Equals("x86", StringComparison.OrdinalIgnoreCase));
			}
		}

		private void FindDirectories(List<AssemblyFolderItem> assemblyTargets, Func<AssemblyFolderItem, bool> platformFilter)
		{
			IEnumerable<AssemblyFoldersFromConfigInfo> collection = from target in assemblyTargets.Where(platformFilter)
				select new AssemblyFoldersFromConfigInfo(target.Path, GetFrameworkVersion(target.FrameworkVersion));
			_directoryNames.AddRange(collection);
		}

		private static List<AssemblyFolderItem> GatherVersionStrings(string targetRuntimeVersion, AssemblyFolderCollection collection)
		{
			return (from folder in collection.AssemblyFolders
				let targetVersion = VersionUtilities.ConvertToVersion(targetRuntimeVersion)
				let replacementVersion = GetFrameworkVersion(folder.FrameworkVersion)
				where targetVersion != null && targetVersion >= replacementVersion
				orderby folder.FrameworkVersion descending
				select folder).ToList();
		}

		private static Version GetFrameworkVersion(string version)
		{
			Version version2 = VersionUtilities.ConvertToVersion(version);
			return new Version(version2.Major, version2.Minor);
		}

		IEnumerator<AssemblyFoldersFromConfigInfo> IEnumerable<AssemblyFoldersFromConfigInfo>.GetEnumerator()
		{
			return _directoryNames.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<AssemblyFoldersFromConfigInfo>)this).GetEnumerator();
		}
	}
}
namespace Microsoft.Build.Shared
{
	internal static class AssemblyResources
	{
		internal static ResourceManager PrimaryResources { get; } = new ResourceManager("Microsoft.Build.Utilities.Core.Strings", typeof(AssemblyResources).GetTypeInfo().Assembly);


		internal static ResourceManager SharedResources { get; } = new ResourceManager("Microsoft.Build.Utilities.Core.Strings.shared", typeof(AssemblyResources).GetTypeInfo().Assembly);


		internal static string GetString(string name)
		{
			string? obj = PrimaryResources.GetString(name, CultureInfo.CurrentUICulture) ?? SharedResources.GetString(name, CultureInfo.CurrentUICulture);
			ErrorUtilities.VerifyThrow(obj != null, "Missing resource '{0}'", name);
			return obj;
		}

		internal static string FormatString(string unformatted, params object[] args)
		{
			ErrorUtilities.VerifyThrowArgumentNull(unformatted, "unformatted");
			return ResourceUtilities.FormatString(unformatted, args);
		}

		internal static string FormatResourceString(string resourceName, params object[] args)
		{
			ErrorUtilities.VerifyThrowArgumentNull(resourceName, "resourceName");
			return FormatString(GetString(resourceName), args);
		}
	}
	[@SupportedOSPlatform("windows")]
	internal class AssemblyFoldersEx : IEnumerable<AssemblyFoldersExInfo>, IEnumerable
	{
		private List<AssemblyFoldersExInfo> _directoryNames = new List<AssemblyFoldersExInfo>();

		private HashSet<string> _uniqueDirectoryPaths = new HashSet<string>();

		internal IEnumerable<string> UniqueDirectoryPaths => _uniqueDirectoryPaths;

		internal AssemblyFoldersEx(string registryKeyRoot, string targetRuntimeVersion, string registryKeySuffix, string osVersion, string platform, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, System.Reflection.ProcessorArchitecture targetProcessorArchitecture, OpenBaseKey openBaseKey)
		{
			if (!NativeMethods.IsWindows)
			{
				return;
			}
			bool is64BitOperatingSystem = EnvironmentUtilities.Is64BitOperatingSystem;
			bool flag = targetProcessorArchitecture == System.Reflection.ProcessorArchitecture.Amd64 || targetProcessorArchitecture == System.Reflection.ProcessorArchitecture.IA64;
			FindDirectories(RegistryView.Default, RegistryHive.CurrentUser, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey);
			if (is64BitOperatingSystem)
			{
				if (flag)
				{
					FindDirectories(RegistryView.Registry64, RegistryHive.LocalMachine, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey);
					FindDirectories(RegistryView.Registry32, RegistryHive.LocalMachine, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey);
				}
				else
				{
					FindDirectories(RegistryView.Registry32, RegistryHive.LocalMachine, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey);
					FindDirectories(RegistryView.Registry64, RegistryHive.LocalMachine, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey);
				}
			}
			else
			{
				FindDirectories(RegistryView.Default, RegistryHive.LocalMachine, registryKeyRoot, targetRuntimeVersion, registryKeySuffix, osVersion, platform, getRegistrySubKeyNames, getRegistrySubKeyDefaultValue, openBaseKey);
			}
		}

		private void FindDirectories(RegistryView view, RegistryHive hive, string registryKeyRoot, string targetRuntimeVersion, string registryKeySuffix, string osVersion, string platform, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, OpenBaseKey openBaseKey)
		{
			using RegistryKey registryKey = openBaseKey(hive, view);
			IEnumerable<string> enumerable = getRegistrySubKeyNames(registryKey, registryKeyRoot);
			if (enumerable == null)
			{
				return;
			}
			List<ExtensionFoldersRegistryKey> list = GatherVersionStrings(targetRuntimeVersion, enumerable);
			List<ExtensionFoldersRegistryKey> list2 = new List<ExtensionFoldersRegistryKey>();
			foreach (ExtensionFoldersRegistryKey item in list)
			{
				string text = registryKeyRoot + "\\" + item.RegistryKey + "\\" + registryKeySuffix;
				IEnumerable<string> enumerable2 = getRegistrySubKeyNames(registryKey, text);
				if (enumerable2 == null)
				{
					continue;
				}
				List<string> list3 = new List<string>();
				foreach (string item2 in enumerable2)
				{
					list3.Add(item2);
				}
				list3.Sort(ReverseStringGenericComparer.Comparer);
				foreach (string item3 in list3)
				{
					list2.Add(new ExtensionFoldersRegistryKey(text + "\\" + item3, item.TargetFrameworkVersion));
				}
			}
			List<ExtensionFoldersRegistryKey> list4 = new List<ExtensionFoldersRegistryKey>();
			foreach (ExtensionFoldersRegistryKey item4 in list2)
			{
				IEnumerable<string> enumerable3 = getRegistrySubKeyNames(registryKey, item4.RegistryKey);
				if (enumerable3 == null)
				{
					continue;
				}
				List<string> list5 = new List<string>();
				foreach (string item5 in enumerable3)
				{
					list5.Add(item4.RegistryKey + "\\" + item5);
				}
				list5.Sort(ReverseStringGenericComparer.Comparer);
				foreach (string item6 in list5)
				{
					list4.Add(new ExtensionFoldersRegistryKey(item6, item4.TargetFrameworkVersion));
				}
				list4.Add(item4);
			}
			foreach (ExtensionFoldersRegistryKey item7 in list4)
			{
				if (!string.IsNullOrEmpty(platform) || !string.IsNullOrEmpty(osVersion))
				{
					using RegistryKey registryKey2 = registryKey.OpenSubKey(item7.RegistryKey, writable: false);
					if (registryKey2 != null && registryKey2.ValueCount > 0)
					{
						if (!string.IsNullOrEmpty(platform))
						{
							string text2 = registryKey2.GetValue("Platform", null) as string;
							if (!string.IsNullOrEmpty(text2) && !MatchingPlatformExists(platform, text2))
							{
								continue;
							}
						}
						if (!string.IsNullOrEmpty(osVersion))
						{
							Version v = VersionUtilities.ConvertToVersion(osVersion);
							if (!IsVersionInsideRange(v, registryKey2))
							{
								continue;
							}
						}
					}
				}
				string text3 = getRegistrySubKeyDefaultValue(registryKey, item7.RegistryKey);
				if (text3 != null)
				{
					_uniqueDirectoryPaths.Add(text3);
					_directoryNames.Add(new AssemblyFoldersExInfo(hive, view, item7.RegistryKey, text3, item7.TargetFrameworkVersion));
				}
			}
		}

		private bool MatchingPlatformExists(string platform, string platformValue)
		{
			bool result = false;
			if (!string.IsNullOrEmpty(platformValue))
			{
				string[] array = platformValue.Split(MSBuildConstants.SemicolonChar);
				for (int i = 0; i < array.Length; i++)
				{
					if (string.Equals(array[i], platform, StringComparison.OrdinalIgnoreCase))
					{
						result = true;
						break;
					}
				}
			}
			return result;
		}

		private bool IsVersionInsideRange(Version v, RegistryKey keyPlatform)
		{
			bool result = true;
			if (v != null)
			{
				Version version2 = ((!(keyPlatform.GetValue("MinOSVersion", null) is string version)) ? null : VersionUtilities.ConvertToVersion(version));
				if (version2 != null && version2 > v)
				{
					result = false;
				}
				Version version4 = ((!(keyPlatform.GetValue("MaxOSVersion", null) is string version3)) ? null : VersionUtilities.ConvertToVersion(version3));
				if (version4 != null && version4 < v)
				{
					result = false;
				}
			}
			return result;
		}

		internal static List<ExtensionFoldersRegistryKey> GatherVersionStrings(string targetRuntimeVersion, IEnumerable<string> versions)
		{
			List<string> list = new List<string>();
			Version version = VersionUtilities.ConvertToVersion(targetRuntimeVersion);
			List<ExtensionFoldersRegistryKey> list2 = new List<ExtensionFoldersRegistryKey>();
			SortedDictionary<Version, List<string>> sortedDictionary = new SortedDictionary<Version, List<string>>(ReverseVersionGenericComparer.Comparer);
			foreach (string version4 in versions)
			{
				if (version4.Length <= 0 || !string.Equals(version4.Substring(0, 1), "v", StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				Version version2 = VersionUtilities.ConvertToVersion(version4);
				if (version2 == null)
				{
					if (string.Compare(version4, 0, targetRuntimeVersion, 0, targetRuntimeVersion.Length, StringComparison.OrdinalIgnoreCase) == 0)
					{
						list.Add(version4);
					}
					continue;
				}
				Version version3 = ((version2.Build > 255) ? new Version(version2.Major, version2.Minor) : ((version2.Revision == -1) ? version2 : new Version(version2.Major, version2.Minor, version2.Build)));
				bool flag = false;
				if (version == null && string.Compare(version4, 0, targetRuntimeVersion, 0, targetRuntimeVersion.Length, StringComparison.OrdinalIgnoreCase) == 0)
				{
					flag = true;
				}
				bool flag2 = version != null && version >= version3;
				if (version3 != null && (flag2 || flag))
				{
					AddCandidateVersion(sortedDictionary, version4, version3);
				}
			}
			foreach (KeyValuePair<Version, List<string>> item in sortedDictionary)
			{
				List<string> value = item.Value;
				value.Sort(ReverseStringGenericComparer.Comparer);
				foreach (string item2 in value)
				{
					list2.Add(new ExtensionFoldersRegistryKey(item2, item.Key));
				}
			}
			foreach (string item3 in list)
			{
				list2.Add(new ExtensionFoldersRegistryKey(item3, version ?? new Version(0, 0)));
			}
			return list2;
		}

		private static void AddCandidateVersion(SortedDictionary<Version, List<string>> targetFrameworkVersionToRegistryVersions, string version, Version candidateVersion)
		{
			if (targetFrameworkVersionToRegistryVersions.TryGetValue(candidateVersion, out var value))
			{
				value.Add(version);
				return;
			}
			value = new List<string>();
			value.Add(version);
			targetFrameworkVersionToRegistryVersions.Add(candidateVersion, value);
		}

		IEnumerator<AssemblyFoldersExInfo> IEnumerable<AssemblyFoldersExInfo>.GetEnumerator()
		{
			return _directoryNames.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable<AssemblyFoldersExInfo>)this).GetEnumerator();
		}
	}
	internal static class EnvironmentUtilities
	{
		public static bool Is64BitProcess => Marshal.SizeOf<IntPtr>() == 8;

		public static bool Is64BitOperatingSystem => Environment.Is64BitOperatingSystem;

		public static bool IsWellKnownEnvironmentDerivedProperty(string propertyName)
		{
			if (!propertyName.StartsWith("MSBUILD", StringComparison.OrdinalIgnoreCase) && !propertyName.StartsWith("COMPLUS_", StringComparison.OrdinalIgnoreCase))
			{
				return propertyName.StartsWith("DOTNET_", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}
	}
	internal sealed class BuildEnvironmentHelper
	{
		private static class BuildEnvironmentHelperSingleton
		{
			public static BuildEnvironment s_instance;

			static BuildEnvironmentHelperSingleton()
			{
				s_instance = Initialize();
			}
		}

		private const string CurrentVisualStudioVersion = "17.0";

		private const string CurrentToolsVersion = "Current";

		private static readonly string[] s_visualStudioProcess = new string[3] { "DEVENV", "BLEND", "Microsoft.VisualStudio.Web.Host" };

		private static readonly string[] s_msBuildProcess = new string[2] { "MSBUILD", "MSBUILDTASKHOST" };

		private static readonly string[] s_msBuildExeNames = new string[2] { "MSBuild.exe", "MSBuild.dll" };

		private static bool? _runningTests;

		private static readonly object _runningTestsLock = new object();

		private static Func<string> s_getProcessFromRunningProcess = GetProcessFromRunningProcess;

		private static Func<string> s_getExecutingAssemblyPath = GetExecutingAssemblyPath;

		private static Func<string> s_getAppContextBaseDirectory = GetAppContextBaseDirectory;

		private static Func<IEnumerable<VisualStudioInstance>> s_getVisualStudioInstances = VisualStudioLocationHelper.GetInstances;

		private static Func<string, string> s_getEnvironmentVariable = GetEnvironmentVariable;

		private static Func<bool> s_runningTests = CheckIfRunningTests;

		public static BuildEnvironment Instance
		{
			get
			{
				try
				{
					return BuildEnvironmentHelperSingleton.s_instance;
				}
				catch (TypeInitializationException ex)
				{
					if (ex.InnerException != null)
					{
						throw ex.InnerException;
					}
					throw;
				}
			}
		}

		private static BuildEnvironment Initialize()
		{
			Func<BuildEnvironment>[] array = new Func<BuildEnvironment>[7] { TryFromEnvironmentVariable, TryFromVisualStudioProcess, TryFromMSBuildProcess, TryFromMSBuildAssembly, TryFromDevConsole, TryFromSetupApi, TryFromAppContextBaseDirectory };
			for (int i = 0; i < array.Length; i++)
			{
				BuildEnvironment buildEnvironment = array[i]();
				if (buildEnvironment != null)
				{
					return buildEnvironment;
				}
			}
			string currentMSBuildExePath = ((!s_runningTests()) ? s_getProcessFromRunningProcess() : typeof(BuildEnvironmentHelper).Assembly.Location);
			return new BuildEnvironment(BuildEnvironmentMode.None, currentMSBuildExePath, s_runningTests(), runningInMSBuildExe: false, runningInVisualStudio: false, null);
		}

		private static BuildEnvironment TryFromEnvironmentVariable()
		{
			string text = s_getEnvironmentVariable("MSBUILD_EXE_PATH");
			object obj;
			if (text != null)
			{
				obj = TryFromMSBuildExeUnderVisualStudio(text, allowLegacyToolsVersion: true);
				if (obj == null)
				{
					return TryFromStandaloneMSBuildExe(text);
				}
			}
			else
			{
				obj = null;
			}
			return (BuildEnvironment)obj;
		}

		private static BuildEnvironment TryFromVisualStudioProcess()
		{
			if (!NativeMethods.IsWindows)
			{
				return null;
			}
			string text = s_getProcessFromRunningProcess();
			if (!IsProcessInList(text, s_visualStudioProcess))
			{
				return null;
			}
			string folderAbove = FileUtilities.GetFolderAbove(text, 3);
			string mSBuildExeFromVsRoot = GetMSBuildExeFromVsRoot(folderAbove);
			return new BuildEnvironment(BuildEnvironmentMode.VisualStudio, mSBuildExeFromVsRoot, runningTests: false, runningInMSBuildExe: false, runningInVisualStudio: true, folderAbove);
		}

		private static BuildEnvironment TryFromMSBuildProcess()
		{
			string text = s_getProcessFromRunningProcess();
			if (!IsProcessInList(text, s_msBuildProcess))
			{
				return null;
			}
			if (NativeMethods.IsWindows && Regex.IsMatch(text, ".*\\\\MSBuild\\\\Current\\\\Bin\\\\.*MSBuild(?:TaskHost)?\\.exe", RegexOptions.IgnoreCase))
			{
				return new BuildEnvironment(BuildEnvironmentMode.VisualStudio, text, runningTests: false, runningInMSBuildExe: true, runningInVisualStudio: false, GetVsRootFromMSBuildAssembly(text));
			}
			return new BuildEnvironment(BuildEnvironmentMode.Standalone, text, runningTests: false, runningInMSBuildExe: true, runningInVisualStudio: false, null);
		}

		private static BuildEnvironment TryFromMSBuildAssembly()
		{
			string text = s_getExecutingAssemblyPath();
			if (text == null)
			{
				return null;
			}
			string text2 = Path.Combine(FileUtilities.GetFolderAbove(text), "MSBuild.exe");
			string text3 = Path.Combine(FileUtilities.GetFolderAbove(text), "MSBuild.dll");
			BuildEnvironment buildEnvironment = TryFromMSBuildExeUnderVisualStudio(text2);
			if (buildEnvironment != null)
			{
				return buildEnvironment;
			}
			string text4 = null;
			if (FileSystems.Default.FileExists(text2))
			{
				text4 = text2;
			}
			else if (FileSystems.Default.FileExists(text3))
			{
				text4 = text3;
			}
			if (!string.IsNullOrEmpty(text4))
			{
				return new BuildEnvironment(BuildEnvironmentMode.Standalone, text4, s_runningTests(), runningInMSBuildExe: false, runningInVisualStudio: false, null);
			}
			return null;
		}

		private static BuildEnvironment TryFromMSBuildExeUnderVisualStudio(string msbuildExe, bool allowLegacyToolsVersion = false)
		{
			string pattern = (allowLegacyToolsVersion ? ".*\\\\MSBuild\\\\(Current|\\d+\\.0)\\\\Bin\\\\.*" : ".*\\\\MSBuild\\\\Current\\\\Bin\\\\.*");
			if (NativeMethods.IsWindows && Regex.IsMatch(msbuildExe, pattern, RegexOptions.IgnoreCase))
			{
				string vsRootFromMSBuildAssembly = GetVsRootFromMSBuildAssembly(msbuildExe);
				return new BuildEnvironment(BuildEnvironmentMode.VisualStudio, GetMSBuildExeFromVsRoot(vsRootFromMSBuildAssembly), s_runningTests(), runningInMSBuildExe: false, runningInVisualStudio: false, vsRootFromMSBuildAssembly);
			}
			return null;
		}

		private static BuildEnvironment TryFromDevConsole()
		{
			if (s_runningTests())
			{
				return null;
			}
			string text = s_getEnvironmentVariable("VSINSTALLDIR");
			string text2 = s_getEnvironmentVariable("VisualStudioVersion");
			if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(text2) || text2 != "17.0" || !FileSystems.Default.DirectoryExists(text))
			{
				return null;
			}
			return new BuildEnvironment(BuildEnvironmentMode.VisualStudio, GetMSBuildExeFromVsRoot(text), runningTests: false, runningInMSBuildExe: false, runningInVisualStudio: false, text);
		}

		private static BuildEnvironment TryFromSetupApi()
		{
			if (s_runningTests())
			{
				return null;
			}
			Version v = new Version("17.0");
			List<VisualStudioInstance> list = (from i in s_getVisualStudioInstances()
				where i.Version.Major == v.Major && FileSystems.Default.DirectoryExists(i.Path)
				select i).ToList();
			if (list.Count == 0)
			{
				return null;
			}
			_ = list.Count;
			_ = 1;
			return new BuildEnvironment(BuildEnvironmentMode.VisualStudio, GetMSBuildExeFromVsRoot(list[0].Path), runningTests: false, runningInMSBuildExe: false, runningInVisualStudio: false, list[0].Path);
		}

		private static BuildEnvironment TryFromAppContextBaseDirectory()
		{
			string appContextBaseDirectory = s_getAppContextBaseDirectory();
			if (string.IsNullOrEmpty(appContextBaseDirectory))
			{
				return null;
			}
			return s_msBuildExeNames.Select((string name) => TryFromStandaloneMSBuildExe(Path.Combine(appContextBaseDirectory, name))).FirstOrDefault((BuildEnvironment env) => env != null);
		}

		private static BuildEnvironment TryFromStandaloneMSBuildExe(string msBuildExePath)
		{
			if (!string.IsNullOrEmpty(msBuildExePath) && FileSystems.Default.FileExists(msBuildExePath))
			{
				return new BuildEnvironment(BuildEnvironmentMode.Standalone, msBuildExePath, s_runningTests(), runningInMSBuildExe: false, runningInVisualStudio: false, null);
			}
			return null;
		}

		private static string GetVsRootFromMSBuildAssembly(string msBuildAssembly)
		{
			string directoryName = Path.GetDirectoryName(msBuildAssembly);
			return FileUtilities.GetFolderAbove(msBuildAssembly, (directoryName.EndsWith("\\amd64", StringComparison.OrdinalIgnoreCase) || directoryName.EndsWith("\\arm64", StringComparison.OrdinalIgnoreCase)) ? 5 : 4);
		}

		private static string GetMSBuildExeFromVsRoot(string visualStudioRoot)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Invalid comparison between Unknown and I4
			return FileUtilities.CombinePaths(visualStudioRoot, "MSBuild", "Current", "Bin", ((int)NativeMethods.ProcessorArchitecture == 1) ? "amd64" : (((int)NativeMethods.ProcessorArchitecture == 4) ? "arm64" : string.Empty), "MSBuild.exe");
		}

		private static bool CheckIfRunningTests()
		{
			if (_runningTests.HasValue)
			{
				return _runningTests.Value;
			}
			lock (_runningTestsLock)
			{
				if (_runningTests.HasValue)
				{
					return _runningTests.Value;
				}
				FieldInfo field = typeof(ITask).Assembly.GetType("Microsoft.Build.Framework.TestInfo").GetField("s_runningTests", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				_runningTests = (bool)field.GetValue(null);
				return _runningTests.Value;
			}
		}

		private static bool IsProcessInList(string processName, string[] processList)
		{
			string processFileName = Path.GetFileNameWithoutExtension(processName);
			if (string.IsNullOrEmpty(processFileName))
			{
				return false;
			}
			return processList.Any((string s) => processFileName.Equals(s, StringComparison.OrdinalIgnoreCase));
		}

		private static string GetProcessFromRunningProcess()
		{
			return Process.GetCurrentProcess().MainModule.FileName;
		}

		private static string GetExecutingAssemblyPath()
		{
			return FileUtilities.ExecutingAssemblyPath;
		}

		private static string GetAppContextBaseDirectory()
		{
			return AppContext.BaseDirectory;
		}

		private static string GetEnvironmentVariable(string variable)
		{
			return Environment.GetEnvironmentVariable(variable);
		}

		internal static void ResetInstance_ForUnitTestsOnly(Func<string> getProcessFromRunningProcess = null, Func<string> getExecutingAssemblyPath = null, Func<string> getAppContextBaseDirectory = null, Func<IEnumerable<VisualStudioInstance>> getVisualStudioInstances = null, Func<string, string> getEnvironmentVariable = null, Func<bool> runningTests = null)
		{
			s_getProcessFromRunningProcess = getProcessFromRunningProcess ?? new Func<string>(GetProcessFromRunningProcess);
			s_getExecutingAssemblyPath = getExecutingAssemblyPath ?? new Func<string>(GetExecutingAssemblyPath);
			s_getAppContextBaseDirectory = getAppContextBaseDirectory ?? new Func<string>(GetAppContextBaseDirectory);
			s_getVisualStudioInstances = getVisualStudioInstances ?? new Func<IEnumerable<VisualStudioInstance>>(VisualStudioLocationHelper.GetInstances);
			s_getEnvironmentVariable = getEnvironmentVariable ?? new Func<string, string>(GetEnvironmentVariable);
			s_runningTests = runningTests ?? new Func<bool>(CheckIfRunningTests);
			BuildEnvironmentHelperSingleton.s_instance = Initialize();
		}

		internal static void ResetInstance_ForUnitTestsOnly(BuildEnvironment buildEnvironment)
		{
			BuildEnvironmentHelperSingleton.s_instance = buildEnvironment;
		}
	}
	internal enum BuildEnvironmentMode
	{
		VisualStudio,
		Standalone,
		None
	}
	internal sealed class BuildEnvironment
	{
		internal BuildEnvironmentMode Mode { get; }

		internal bool RunningTests { get; }

		internal bool RunningInMSBuildExe { get; }

		internal bool RunningInVisualStudio { get; }

		internal string MSBuildToolsDirectoryRoot { get; }

		internal string MSBuildToolsDirectory32 { get; }

		internal string MSBuildToolsDirectory64 { get; }

		internal string MSBuildToolsDirectoryArm64 { get; }

		internal string MSBuildSDKsPath
		{
			get
			{
				string text = ((VisualStudioInstallRootDirectory == null) ? Path.Combine(CurrentMSBuildToolsDirectory, "Sdks") : FileUtilities.CombinePaths(VisualStudioInstallRootDirectory, "MSBuild", "Sdks"));
				return Environment.GetEnvironmentVariable("MSBuildSDKsPath") ?? text;
			}
		}

		internal string CurrentMSBuildConfigurationFile { get; }

		internal string CurrentMSBuildExePath { get; private set; }

		internal string CurrentMSBuildToolsDirectory { get; }

		internal string VisualStudioInstallRootDirectory { get; }

		internal string MSBuildExtensionsPath { get; set; }

		public BuildEnvironment(BuildEnvironmentMode mode, string currentMSBuildExePath, bool runningTests, bool runningInMSBuildExe, bool runningInVisualStudio, string visualStudioPath)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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_00d2: Expected I4, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: 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)
			FileInfo fileInfo = null;
			DirectoryInfo directoryInfo = null;
			Mode = mode;
			RunningTests = runningTests;
			RunningInMSBuildExe = runningInMSBuildExe;
			RunningInVisualStudio = runningInVisualStudio;
			CurrentMSBuildExePath = currentMSBuildExePath;
			VisualStudioInstallRootDirectory = visualStudioPath;
			BuildEnvironmentState.s_runningTests = runningTests;
			BuildEnvironmentState.s_runningInVisualStudio = runningInVisualStudio;
			if (!string.IsNullOrEmpty(currentMSBuildExePath))
			{
				fileInfo = new FileInfo(currentMSBuildExePath);
				directoryInfo = fileInfo.Directory;
				CurrentMSBuildToolsDirectory = fileInfo.DirectoryName;
				CurrentMSBuildConfigurationFile = currentMSBuildExePath + ".config";
				MSBuildToolsDirectory32 = CurrentMSBuildToolsDirectory;
				MSBuildToolsDirectory64 = CurrentMSBuildToolsDirectory;
				MSBuildToolsDirectoryRoot = CurrentMSBuildToolsDirectory;
			}
			if (mode == BuildEnvironmentMode.None || fileInfo == null || directoryInfo == null)
			{
				return;
			}
			string name = fileInfo.Name;
			if (mode == BuildEnvironmentMode.VisualStudio)
			{
				ProcessorArchitectures processorArchitecture = NativeMethods.ProcessorArchitecture;
				string text;
				switch ((int)processorArchitecture)
				{
				case 0:
					text = CurrentMSBuildToolsDirectory;
					break;
				case 1:
				case 4:
					text = directoryInfo.Parent?.FullName;
					break;
				default:
				{
					ProcessorArchitectures processorArchitecture2 = NativeMethods.ProcessorArchitecture;
					throw new InternalErrorException("Unknown processor architecture " + ((object)(ProcessorArchitectures)(ref processorArchitecture2)).ToString());
				}
				}
				MSBuildToolsDirectoryRoot = text;
			}
			else
			{
				MSBuildToolsDirectoryRoot = CurrentMSBuildToolsDirectory;
				if (string.Equals(directoryInfo.Name, "amd64", StringComparison.OrdinalIgnoreCase) || string.Equals(directoryInfo.Name, "arm64", StringComparison.OrdinalIgnoreCase))
				{
					MSBuildToolsDirectoryRoot = directoryInfo.Parent?.FullName;
				}
			}
			if (MSBuildToolsDirectoryRoot != null)
			{
				string arg = FileUtilities.CombinePaths(MSBuildToolsDirectoryRoot, "amd64", name);
				string arg2 = FileUtilities.CombinePaths(MSBuildToolsDirectoryRoot, "arm64", name);
				Func<string, bool> func = ((mode == BuildEnvironmentMode.VisualStudio) ? ((Func<string, bool>)((string _) => true)) : new Func<string, bool>(File.Exists));
				MSBuildToolsDirectory32 = MSBuildToolsDirectoryRoot;
				MSBuildToolsDirectory64 = (func(arg) ? Path.Combine(MSBuildToolsDirectoryRoot, "amd64") : CurrentMSBuildToolsDirectory);
				MSBuildToolsDirectoryArm64 = (func(arg2) ? Path.Combine(MSBuildToolsDirectoryRoot, "arm64") : null);
			}
			MSBuildExtensionsPath = ((mode == BuildEnvironmentMode.VisualStudio) ? Path.Combine(VisualStudioInstallRootDirectory, "MSBuild") : MSBuildToolsDirectory32);
		}
	}
	internal static class CanonicalError
	{
		internal sealed class Parts
		{
			internal enum Category
			{
				Warning,
				Error
			}

			internal const int numberNotSpecified = 0;

			internal string origin;

			internal int line;

			internal int column;

			internal int endLine;

			internal int endColumn;

			internal Category category;

			internal string subcategory;

			internal string code;

			internal string text;

			internal Parts()
			{
			}
		}

		private static readonly Lazy<Regex> s_originCategoryCodeTextExpression = new Lazy<Regex>(() => new Regex("^\\s*(((?<ORIGIN>(((\\d+>)?[a-zA-Z]?:[^:]*)|([^:]*))):)|())(?<SUBCATEGORY>(()|([^:]*? )))(?<CATEGORY>(error|warning))( \\s*(?<CODE>[^: ]*))?\\s*:(?<TEXT>.*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_originCategoryCodeTextExpression2 = new Lazy<Regex>(() => new Regex("^\\s*(?<ORIGIN>(?<FILENAME>.*):(?<LOCATION>(?<LINE>[0-9]*):(?<COLUMN>[0-9]*))):(?<CATEGORY> error| warning):(?<TEXT>.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_filenameLocationFromOrigin = new Lazy<Regex>(() => new Regex("^(\\d+>)?(?<FILENAME>.*)\\((?<LOCATION>[\\,,0-9,-]*)\\)\\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_lineFromLocation = new Lazy<Regex>(() => new Regex("^(?<LINE>[0-9]*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_lineLineFromLocation = new Lazy<Regex>(() => new Regex("^(?<LINE>[0-9]*)-(?<ENDLINE>[0-9]*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_lineColFromLocation = new Lazy<Regex>(() => new Regex("^(?<LINE>[0-9]*),(?<COLUMN>[0-9]*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_lineColColFromLocation = new Lazy<Regex>(() => new Regex("^(?<LINE>[0-9]*),(?<COLUMN>[0-9]*)-(?<ENDCOLUMN>[0-9]*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static readonly Lazy<Regex> s_lineColLineColFromLocation = new Lazy<Regex>(() => new Regex("^(?<LINE>[0-9]*),(?<COLUMN>[0-9]*),(?<ENDLINE>[0-9]*),(?<ENDCOLUMN>[0-9]*)$", RegexOptions.IgnoreCase | RegexOptions.Compiled));

		private static int ConvertToIntWithDefault(string value)
		{
			if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result < 0)
			{
				return 0;
			}
			return result;
		}

		internal static Parts Parse(string message)
		{
			string text = string.Empty;
			if (message.Length > 400)
			{
				text = message.Substring(400);
				message = message.Substring(0, 400);
			}
			if (message.IndexOf("warning", StringComparison.OrdinalIgnoreCase) == -1 && message.IndexOf("error", StringComparison.OrdinalIgnoreCase) == -1)
			{
				return null;
			}
			Parts parts = new Parts();
			Match match = s_originCategoryCodeTextExpression.Value.Match(message);
			string a;
			if (!match.Success)
			{
				match = s_originCategoryCodeTextExpression2.Value.Match(message);
				if (!match.Success)
				{
					return null;
				}
				a = match.Groups["CATEGORY"].Value.Trim();
				if (string.Equals(a, "error", StringComparison.OrdinalIgnoreCase))
				{
					parts.category = Parts.Category.Error;
				}
				else
				{
					if (!string.Equals(a, "warning", StringComparison.OrdinalIgnoreCase))
					{
						return null;
					}
					parts.category = Parts.Category.Warning;
				}
				parts.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
				parts.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
				parts.text = (match.Groups["TEXT"].Value + text).Trim();
				parts.origin = match.Groups["FILENAME"].Value.Trim();
				string[] array = parts.text.Split(MSBuildConstants.SingleQuoteChar, StringSplitOptions.RemoveEmptyEntries);
				if (array.Length != 0)
				{
					parts.code = "G" + array[0].GetHashCode().ToString("X8");
				}
				else
				{
					parts.code = "G00000000";
				}
				return parts;
			}
			string text2 = match.Groups["ORIGIN"].Value.Trim();
			a = match.Groups["CATEGORY"].Value.Trim();
			parts.code = match.Groups["CODE"].Value.Trim();
			parts.text = (match.Groups["TEXT"].Value + text).Trim();
			parts.subcategory = match.Groups["SUBCATEGORY"].Value.Trim();
			if (string.Equals(a, "error", StringComparison.OrdinalIgnoreCase))
			{
				parts.category = Parts.Category.Error;
			}
			else
			{
				if (!string.Equals(a, "warning", StringComparison.OrdinalIgnoreCase))
				{
					return null;
				}
				parts.category = Parts.Category.Warning;
			}
			match = s_filenameLocationFromOrigin.Value.Match(text2);
			if (match.Success)
			{
				string text3 = match.Groups["LOCATION"].Value.Trim();
				parts.origin = match.Groups["FILENAME"].Value.Trim();
				if (text3.Length > 0)
				{
					match = s_lineFromLocation.Value.Match(text3);
					if (match.Success)
					{
						parts.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
					}
					else
					{
						match = s_lineLineFromLocation.Value.Match(text3);
						if (match.Success)
						{
							parts.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
							parts.endLine = ConvertToIntWithDefault(match.Groups["ENDLINE"].Value.Trim());
						}
						else
						{
							match = s_lineColFromLocation.Value.Match(text3);
							if (match.Success)
							{
								parts.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
								parts.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
							}
							else
							{
								match = s_lineColColFromLocation.Value.Match(text3);
								if (match.Success)
								{
									parts.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
									parts.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
									parts.endColumn = ConvertToIntWithDefault(match.Groups["ENDCOLUMN"].Value.Trim());
								}
								else
								{
									match = s_lineColLineColFromLocation.Value.Match(text3);
									if (match.Success)
									{
										parts.line = ConvertToIntWithDefault(match.Groups["LINE"].Value.Trim());
										parts.column = ConvertToIntWithDefault(match.Groups["COLUMN"].Value.Trim());
										parts.endLine = ConvertToIntWithDefault(match.Groups["ENDLINE"].Value.Trim());
										parts.endColumn = ConvertToIntWithDefault(match.Groups["ENDCOLUMN"].Value.Trim());
									}
								}
							}
						}
					}
				}
			}
			else
			{
				parts.origin = text2;
			}
			return parts;
		}
	}
	internal class ExtensionFoldersRegistryKey
	{
		internal string RegistryKey { get; }

		internal Version TargetFrameworkVersion { get; }

		internal ExtensionFoldersRegistryKey(string registryKey, Version targetFrameworkVersion)
		{
			ErrorUtilities.VerifyThrowArgumentNull(registryKey, "registryKey");
			ErrorUtilities.VerifyThrowArgumentNull(targetFrameworkVersion, "targetFrameworkVersion");
			RegistryKey = registryKey;
			TargetFrameworkVersion = targetFrameworkVersion;
		}
	}
	internal delegate string[] DirectoryGetFiles(string path, string searchPattern);
	internal delegate string[] GetDirectories(string path, string pattern);
	internal delegate bool DirectoryExists(string path);
	internal delegate bool FileExists(string path);
	internal delegate void FileCopy(string source, string destination);
	internal delegate void FileDelete(string path);
	internal delegate FileStream FileCreate(string path);
	internal static class ErrorUtilities
	{
		private static readonly bool s_enableMSBuildDebugTracing = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBUILDENABLEDEBUGTRACING"));

		public static void DebugTraceMessage(string category, string formatstring, params object[]? parameters)
		{
			if (s_enableMSBuildDebugTracing)
			{
				if (parameters != null)
				{
					Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, formatstring, parameters), category);
				}
				else
				{
					Trace.WriteLine(formatstring, category);
				}
			}
		}

		internal static void VerifyThrowInternalError([DoesNotReturnIf(false)] bool condition, string message, params object?[]? args)
		{
			if (!condition)
			{
				ThrowInternalError(message, args);
			}
		}

		[DoesNotReturn]
		internal static void ThrowInternalError(string message, params object?[]? args)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			throw new InternalErrorException(ResourceUtilities.FormatString(message, args));
		}

		[DoesNotReturn]
		internal static void ThrowInternalError(string message, Exception? innerException, params object?[]? args)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			throw new InternalErrorException(ResourceUtilities.FormatString(message, args), innerException);
		}

		[DoesNotReturn]
		internal static void ThrowInternalErrorUnreachable()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			throw new InternalErrorException("Unreachable?");
		}

		internal static void VerifyThrowInternalErrorUnreachable([DoesNotReturnIf(false)] bool condition)
		{
			if (!condition)
			{
				ThrowInternalErrorUnreachable();
			}
		}

		internal static void ThrowIfTypeDoesNotImplementToString(object param)
		{
		}

		internal static void VerifyThrowInternalNull([NotNull] object? parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			if (parameter == null)
			{
				ThrowInternalError("{0} unexpectedly null", parameterName);
			}
		}

		internal static void VerifyThrowInternalLockHeld(object locker)
		{
			if (!Monitor.IsEntered(locker))
			{
				ThrowInternalError("Lock should already have been taken");
			}
		}

		internal static void VerifyThrowInternalLength([NotNull] string? parameterValue, [CallerArgumentExpression("parameterValue")] string? parameterName = null)
		{
			VerifyThrowInternalNull(parameterValue, parameterName);
			if (parameterValue.Length == 0)
			{
				ThrowInternalError("{0} unexpectedly empty", parameterName);
			}
		}

		public static void VerifyThrowInternalLength<T>([NotNull] T[]? parameterValue, [CallerArgumentExpression("parameterValue")] string? parameterName = null)
		{
			VerifyThrowInternalNull(parameterValue, parameterName);
			if (parameterValue.Length == 0)
			{
				ThrowInternalError("{0} unexpectedly empty", parameterName);
			}
		}

		internal static void VerifyThrowInternalRooted(string value)
		{
			if (!Path.IsPathRooted(value))
			{
				ThrowInternalError("{0} unexpectedly not a rooted path", value);
			}
		}

		internal static void VerifyThrow([DoesNotReturnIf(false)] bool condition, string unformattedMessage)
		{
			if (!condition)
			{
				ThrowInternalError(unformattedMessage, null, null);
			}
		}

		internal static void VerifyThrow([DoesNotReturnIf(false)] bool condition, string unformattedMessage, object arg0)
		{
			if (!condition)
			{
				ThrowInternalError(unformattedMessage, arg0);
			}
		}

		internal static void VerifyThrow([DoesNotReturnIf(false)] bool condition, string unformattedMessage, object arg0, object arg1)
		{
			if (!condition)
			{
				ThrowInternalError(unformattedMessage, arg0, arg1);
			}
		}

		internal static void VerifyThrow([DoesNotReturnIf(false)] bool condition, string unformattedMessage, object arg0, object arg1, object arg2)
		{
			if (!condition)
			{
				ThrowInternalError(unformattedMessage, arg0, arg1, arg2);
			}
		}

		internal static void VerifyThrow([DoesNotReturnIf(false)] bool condition, string unformattedMessage, object arg0, object arg1, object arg2, object arg3)
		{
			if (!condition)
			{
				ThrowInternalError(unformattedMessage, arg0, arg1, arg2, arg3);
			}
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperation(string resourceName, params object?[]? args)
		{
			throw new InvalidOperationException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword(resourceName, args));
		}

		internal static void VerifyThrowInvalidOperation([DoesNotReturnIf(false)] bool condition, string resourceName)
		{
			if (!condition)
			{
				ThrowInvalidOperation(resourceName, null);
			}
		}

		internal static void VerifyThrowInvalidOperation([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0)
		{
			if (!condition)
			{
				ThrowInvalidOperation(resourceName, arg0);
			}
		}

		internal static void VerifyThrowInvalidOperation([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0, object arg1)
		{
			if (!condition)
			{
				ThrowInvalidOperation(resourceName, arg0, arg1);
			}
		}

		internal static void VerifyThrowInvalidOperation([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0, object arg1, object arg2)
		{
			if (!condition)
			{
				ThrowInvalidOperation(resourceName, arg0, arg1, arg2);
			}
		}

		internal static void VerifyThrowInvalidOperation([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0, object arg1, object arg2, object arg3)
		{
			if (!condition)
			{
				ThrowInvalidOperation(resourceName, arg0, arg1, arg2, arg3);
			}
		}

		[DoesNotReturn]
		internal static void ThrowArgument(string resourceName, params object?[]? args)
		{
			ThrowArgument(null, resourceName, args);
		}

		[DoesNotReturn]
		internal static void ThrowArgument(Exception? innerException, string resourceName, params object?[]? args)
		{
			throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword(resourceName, args), innerException);
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, string resourceName)
		{
			VerifyThrowArgument(condition, null, resourceName);
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0)
		{
			VerifyThrowArgument(condition, null, resourceName, arg0);
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0, object arg1)
		{
			VerifyThrowArgument(condition, null, resourceName, arg0, arg1);
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0, object arg1, object arg2)
		{
			VerifyThrowArgument(condition, null, resourceName, arg0, arg1, arg2);
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, string resourceName, object arg0, object arg1, object arg2, object arg3)
		{
			VerifyThrowArgument(condition, null, resourceName, arg0, arg1, arg2, arg3);
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, Exception? innerException, string resourceName)
		{
			if (!condition)
			{
				ThrowArgument(innerException, resourceName, null);
			}
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, Exception? innerException, string resourceName, object arg0)
		{
			if (!condition)
			{
				ThrowArgument(innerException, resourceName, arg0);
			}
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, Exception? innerException, string resourceName, object arg0, object arg1)
		{
			if (!condition)
			{
				ThrowArgument(innerException, resourceName, arg0, arg1);
			}
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, Exception? innerException, string resourceName, object arg0, object arg1, object arg2)
		{
			if (!condition)
			{
				ThrowArgument(innerException, resourceName, arg0, arg1, arg2);
			}
		}

		internal static void VerifyThrowArgument([DoesNotReturnIf(false)] bool condition, Exception? innerException, string resourceName, object arg0, object arg1, object arg2, object arg3)
		{
			if (!condition)
			{
				ThrowArgument(innerException, resourceName, arg0, arg1, arg2, arg3);
			}
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRange(string? parameterName)
		{
			throw new ArgumentOutOfRangeException(parameterName);
		}

		internal static void VerifyThrowArgumentOutOfRange([DoesNotReturnIf(false)] bool condition, [CallerArgumentExpression("condition")] string? parameterName = null)
		{
			if (!condition)
			{
				ThrowArgumentOutOfRange(parameterName);
			}
		}

		internal static void VerifyThrowArgumentLength([NotNull] string? parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			VerifyThrowArgumentNull(parameter, parameterName);
			if (parameter.Length == 0)
			{
				ThrowArgumentLength(parameterName);
			}
		}

		internal static void VerifyThrowArgumentLength<T>([NotNull] IReadOnlyCollection<T> parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			VerifyThrowArgumentNull(parameter, parameterName);
			if (parameter.Count == 0)
			{
				ThrowArgumentLength(parameterName);
			}
		}

		internal static void VerifyThrowArgumentLengthIfNotNull<T>([MaybeNull] IReadOnlyCollection<T>? parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			if (parameter != null && parameter.Count == 0)
			{
				ThrowArgumentLength(parameterName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentLength(string? parameterName)
		{
			throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Shared.ParameterCannotHaveZeroLength", parameterName));
		}

		internal static void VerifyThrowArgumentInvalidPath([NotNull] string parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			VerifyThrowArgumentNull(parameter, parameterName);
			if (FileUtilities.PathIsInvalid(parameter))
			{
				ThrowArgument("Shared.ParameterCannotHaveInvalidPathChars", parameterName, parameter);
			}
		}

		internal static void VerifyThrowArgumentLengthIfNotNull(string? parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			if (parameter != null && parameter.Length == 0)
			{
				ThrowArgumentLength(parameterName);
			}
		}

		internal static void VerifyThrowArgumentNull([NotNull] object? parameter, [CallerArgumentExpression("parameter")] string? parameterName = null)
		{
			VerifyThrowArgumentNull(parameter, parameterName, "Shared.ParameterCannotBeNull");
		}

		internal static void VerifyThrowArgumentNull([NotNull] object? parameter, string? parameterName, string resourceName)
		{
			if (parameter == null)
			{
				ThrowArgumentNull(parameterName, resourceName);
			}
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNull(string? parameterName, string resourceName)
		{
			throw new ArgumentNullException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword(resourceName, parameterName), (Exception?)null);
		}

		internal static void VerifyThrowObjectDisposed([DoesNotReturnIf(false)] bool condition, string objectName)
		{
			if (!condition)
			{
				ThrowObjectDisposed(objectName);
			}
		}

		[DoesNotReturn]
		internal static void ThrowObjectDisposed(string objectName)
		{
			throw new ObjectDisposedException(objectName);
		}

		internal static void VerifyCollectionCopyToArguments<T>([NotNull] T[]? array, string arrayParameterName, int arrayIndex, string arrayIndexParameterName, int requiredCapacity)
		{
			VerifyThrowArgumentNull(array, arrayParameterName);
			VerifyThrowArgumentOutOfRange(arrayIndex >= 0 && arrayIndex < array.Length, arrayIndexParameterName);
			int num = array.Length - arrayIndex;
			if (requiredCapacity > num)
			{
				throw new ArgumentException(ResourceUtilities.GetResourceString("Shared.CollectionCopyToFailureProvidedArrayIsTooSmall"), arrayParameterName);
			}
		}
	}
	internal static class EscapingUtilities
	{
		private static Dictionary<string, string> s_unescapedToEscapedStrings = new Dictionary<string, string>(StringComparer.Ordinal);

		private static readonly char[] s_charsToEscape = new char[9] { '%', '*', '?', '@', '$', '(', ')', ';', '\'' };

		private static bool TryDecodeHexDigit(char character, out int value)
		{
			if (character >= '0' && character <= '9')
			{
				value = character - 48;
				return true;
			}
			if (character >= 'A' && character <= 'F')
			{
				value = character - 65 + 10;
				return true;
			}
			if (character >= 'a' && character <= 'f')
			{
				value = character - 97 + 10;
				return true;
			}
			value = 0;
			return false;
		}

		internal static string UnescapeAll(string escapedString, bool trim = false)
		{
			if (string.IsNullOrEmpty(escapedString))
			{
				return escapedString;
			}
			int num = escapedString.IndexOf('%');
			if (num == -1)
			{
				if (!trim)
				{
					return escapedString;
				}
				return escapedString.Trim();
			}
			StringBuilder stringBuilder = StringBuilderCache.Acquire(escapedString.Length);
			int i = 0;
			int num2 = escapedString.Length;
			if (trim)
			{
				for (; i < escapedString.Length && char.IsWhiteSpace(escapedString[i]); i++)
				{
				}
				if (i == escapedString.Length)
				{
					return string.Empty;
				}
				while (char.IsWhiteSpace(escapedString[num2 - 1]))
				{
					num2--;
				}
			}
			while (num != -1)
			{
				if (num <= num2 - 3 && TryDecodeHexDigit(escapedString[num + 1], out var value) && TryDecodeHexDigit(escapedString[num + 2], out var value2))
				{
					stringBuilder.Append(escapedString, i, num - i);
					char value3 = (char)((value << 4) + value2);
					stringBuilder.Append(value3);
					i = num + 3;
				}
				num = escapedString.IndexOf('%', num + 1);
			}
			stringBuilder.Append(escapedString, i, num2 - i);
			return StringBuilderCache.GetStringAndRelease(stringBuilder);
		}

		internal static string EscapeWithCaching(string unescapedString)
		{
			return EscapeWithOptionalCaching(unescapedString, cache: true);
		}

		internal static string Escape(string unescapedString)
		{
			return EscapeWithOptionalCaching(unescapedString, cache: false);
		}

		private static string EscapeWithOptionalCaching(string unescapedString, bool cache)
		{
			if (string.IsNullOrEmpty(unescapedString) || !ContainsReservedCharacters(unescapedString))
			{
				return unescapedString;
			}
			if (cache)
			{
				lock (s_unescapedToEscapedStrings)
				{
					if (s_unescapedToEscapedStrings.TryGetValue(unescapedString, out var value))
					{
						return value;
					}
				}
			}
			StringBuilder stringBuilder = StringBuilderCache.Acquire(unescapedString.Length * 2);
			AppendEscapedString(stringBuilder, unescapedString);
			if (!cache)
			{
				return StringBuilderCache.GetStringAndRelease(stringBuilder);
			}
			string text = Strings.WeakIntern(stringBuilder.ToString());
			StringBuilderCache.Release(stringBuilder);
			lock (s_unescapedToEscapedStrings)
			{
				s_unescapedToEscapedStrings[unescapedString] = text;
				return text;
			}
		}

		private static bool ContainsReservedCharacters(string unescapedString)
		{
			return -1 != unescapedString.IndexOfAny(s_charsToEscape);
		}

		internal static bool ContainsEscapedWildcards(string escapedString)
		{
			if (escapedString.Length < 3)
			{
				return false;
			}
			for (int num = escapedString.IndexOf('%', 0, escapedString.Length - 2); num != -1; num = escapedString.IndexOf('%', num + 1, escapedString.Length - (num + 1) - 2))
			{
				if (escapedString[num + 1] == '2' && (escapedString[num + 2] == 'a' || escapedString[num + 2] == 'A'))
				{
					return true;
				}
				if (escapedString[num + 1] == '3' && (escapedString[num + 2] == 'f' || escapedString[num + 2] == 'F'))
				{
					return true;
				}
			}
			return false;
		}

		private static char HexDigitChar(int x)
		{
			return (char)(x + ((x < 10) ? 48 : 87));
		}

		private static void AppendEscapedChar(StringBuilder sb, char ch)
		{
			sb.Append('%');
			sb.Append(HexDigitChar(ch / 16));
			sb.Append(HexDigitChar(ch & 0xF));
		}

		private static void AppendEscapedString(StringBuilder sb, string unescapedString)
		{
			int num = 0;
			while (true)
			{
				int num2 = unescapedString.IndexOfAny(s_charsToEscape, num);
				if (num2 == -1)
				{
					break;
				}
				sb.Append(unescapedString, num, num2 - num);
				AppendEscapedChar(sb, unescapedString[num2]);
				num = num2 + 1;
			}
			sb.Append(unescapedString, num, unescapedString.Length - num);
		}
	}
	internal static class EventArgsFormatting
	{
		private static readonly string[] s_newLines = new string[2] { "\r\n", "\n" };

		internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile, string projectConfigurationDescription)
		{
			return FormatEventMessage("error", e.Subcategory, ((BuildEventArgs)e).Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, projectConfigurationDescription);
		}

		internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile, string projectConfigurationDescription)
		{
			return FormatEventMessage("warning", e.Subcategory, ((BuildEventArgs)e).Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, projectConfigurationDescription);
		}

		internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile, string projectConfigurationDescription, string nonNullMessage = null)
		{
			return FormatEventMessage("message", e.Subcategory, nonNullMessage ?? ((BuildEventArgs)e).Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, projectConfigurationDescription);
		}

		internal static string FormatEventMessage(BuildErrorEventArgs e)
		{
			ErrorUtilities.VerifyThrowArgumentNull(e, "e");
			return FormatEventMessage("error", e.Subcategory, ((BuildEventArgs)e).Message, e.Code, e.File, null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, null);
		}

		internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile)
		{
			ErrorUtilities.VerifyThrowArgumentNull(e, "e");
			return FormatEventMessage("error", e.Subcategory, ((BuildEventArgs)e).Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, null);
		}

		internal static string FormatEventMessage(BuildWarningEventArgs e)
		{
			ErrorUtilities.VerifyThrowArgumentNull(e, "e");
			return FormatEventMessage("warning", e.Subcategory, ((BuildEventArgs)e).Message, e.Code, e.File, null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, null);
		}

		internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile)
		{
			ErrorUtilities.VerifyThrowArgumentNull(e, "e");
			return FormatEventMessage("warning", e.Subcategory, ((BuildEventArgs)e).Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, null);
		}

		internal static string FormatEventMessage(BuildMessageEventArgs e)
		{
			return FormatEventMessage(e, showProjectFile: false);
		}

		internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile, string nonNullMessage = null)
		{
			ErrorUtilities.VerifyThrowArgumentNull(e, "e");
			return FormatEventMessage("message", e.Subcategory, nonNullMessage ?? ((BuildEventArgs)e).Message, e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, ((BuildEventArgs)e).ThreadId, null);
		}

		internal static string FormatEventMessage(string category, string subcategory, string message, string code, string file, int lineNumber, int endLineNumber, int columnNumber, int endColumnNumber, int threadId)
		{
			return FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId, null);
		}

		internal static string FormatEventMessage(string category, string subcategory, string message, string code, string file, string projectFile, int lineNumber, int endLineNumber, int columnNumber, int endColumnNumber, int threadId, string logOutputProperties)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			ReuseableStringBuilder val = new ReuseableStringBuilder(51);
			try
			{
				if (string.IsNullOrEmpty(file))
				{
					val.Append("MSBUILD : ");
				}
				else
				{
					val.Append("{1}");
					if (lineNumber == 0)
					{
						val.Append(" : ");
					}
					else if (columnNumber == 0)
					{
						if (endLineNumber == 0)
						{
							val.Append("({2}): ");
						}
						else
						{
							val.Append("({2}-{7}): ");
						}
					}
					else if (endLineNumber == 0)
					{
						if (endColumnNumber == 0)
						{
							val.Append("({2},{3}): ");
						}
						else
						{
							val.Append("({2},{3}-{8}): ");
						}
					}
					else if (endColumnNumber == 0)
					{
						val.Append("({2}-{7},{3}): ");
					}
					else
					{
						val.Append("({2},{3},{7},{8}): ");
					}
				}
				if (!string.IsNullOrEmpty(subcategory))
				{
					val.Append("{9} ");
				}
				val.Append("{4} ");
				if (code == null)
				{
					val.Append(": ");
				}
				else
				{
					val.Append("{5}: ");
				}
				if (message != null)
				{
					val.Append("{6}");
				}
				if (projectFile != null)
				{
					if (!string.Equals(projectFile, file))
					{
						if (logOutputProperties != null && logOutputProperties.Length > 0)
						{
							val.Append(" [{10}::{11}]");
						}
						else
						{
							val.Append(" [{10}]");
						}
					}
					else if (logOutputProperties != null && logOutputProperties.Length > 0)
					{
						val.Append(" [{11}]");
					}
				}
				if (message == null)
				{
					message = string.Empty;
				}
				string text = ((object)val).ToString();
				ReuseableStringBuilder val2 = val.Clear();
				string[] array = SplitStringOnNewLines(message);
				for (int i = 0; i < array.Length; i++)
				{
					val2.AppendFormat(CultureInfo.CurrentCulture, text, new object[12]
					{
						threadId,
						file,
						lineNumber,
						columnNumber,
						category,
						code,
						array[i],
						endLineNumber,
						endColumnNumber,
						subcategory,
						projectFile,
						logOutputProperties
					});
					if (i < array.Length - 1)
					{
						val2.AppendLine();
					}
				}
				return ((object)val2).ToString();
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		private static string[] SplitStringOnNewLines(string s)
		{
			return s.Split(s_newLines, StringSplitOptions.None);
		}
	}
	internal static class ExceptionHandling
	{
		internal struct LineAndColumn
		{
			internal int Line { get; set; }

			internal int Column { get; set; }
		}

		private static readonly string s_debugDumpPath = GetDebugDumpPath();

		private static string s_dumpFileName;

		internal static string DebugDumpPath => s_debugDumpPath;

		internal static string DumpFilePath => s_dumpFileName;

		private static string GetDebugDumpPath()
		{
			string debugPath = DebugUtils.DebugPath;
			if (string.IsNullOrEmpty(debugPath))
			{
				return FileUtilities.TempFileDirectory;
			}
			return debugPath;
		}

		internal static bool IsCriticalException(Exception e)
		{
			if (e is OutOfMemoryException || e is StackOverflowException || e is ThreadAbortException || e is ThreadInterruptedException || e is AccessViolationException || e is CriticalTaskException || e is InternalErrorException)
			{
				return true;
			}
			if (e is AggregateException ex && ex.InnerExceptions.Any((Exception innerException) => IsCriticalException(innerException)))
			{
				return true;
			}
			return false;
		}

		internal static bool NotExpectedException(Exception e)
		{
			return !IsIoRelatedException(e);
		}

		internal static bool IsIoRelatedException(Exception e)
		{
			if (!(e is UnauthorizedAccessException) && !(e is NotSupportedException) && (!(e is ArgumentException) || e is ArgumentNullException) && !(e is SecurityException))
			{
				return e is IOException;
			}
			return true;
		}

		internal static bool IsXmlException(Exception e)
		{
			if (!(e is XmlException) && !(e is XmlSyntaxException) && !(e is XmlSchemaException))
			{
				return e is UriFormatException;
			}
			return true;
		}

		internal static LineAndColumn GetXmlLineAndColumn(Exception e)
		{
			int line = 0;
			int column = 0;
			if (e is XmlException ex)
			{
				line = ex.LineNumber;
				column = ex.LinePosition;
			}
			else if (e is XmlSchemaException ex2)
			{
				line = ex2.LineNumber;
				column = ex2.LinePosition;
			}
			LineAndColumn result = default(LineAndColumn);
			result.Line = line;
			result.Column = column;
			return result;
		}

		internal static bool NotExpectedIoOrXmlException(Exception e)
		{
			if (IsXmlException(e) || !NotExpectedException(e))
			{
				return false;
			}
			return true;
		}

		internal static bool NotExpectedReflectionException(Exception e)
		{
			if (e is TypeLoadException || e is MethodAccessException || e is MissingMethodException || e is MemberAccessException || e is BadImageFormatException || e is ReflectionTypeLoadException || e is TargetParameterCountException || e is InvalidCastException || e is AmbiguousMatchException || e is CustomAttributeFormatException || e is InvalidFilterCriteriaException || e is TargetException || e is MissingFieldException || !NotExpectedException(e))
			{
				return false;
			}
			return true;
		}

		internal static bool NotExpectedSerializationException(Exception e)
		{
			if (e is SerializationException || !NotExpectedReflectionException(e))
			{
				return false;
			}
			return true;
		}

		internal static bool NotExpectedRegistryException(Exception e)
		{
			if (e is SecurityException || e is UnauthorizedAccessException || e is IOException || e is ObjectDisposedException || e is ArgumentException)
			{
				return false;
			}
			return true;
		}

		internal static bool NotExpectedFunctionException(Exception e)
		{
			if (e is InvalidCastException || e is ArgumentNullException || e is FormatException || e is InvalidOperationException || !NotExpectedReflectionException(e))
			{
				return false;
			}
			return true;
		}

		internal static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
		{
			DumpExceptionToFile((Exception)e.ExceptionObject);
		}

		internal static void DumpExceptionToFile(Exception ex)
		{
			try
			{
				lock (typeof(ExceptionHandling))
				{
					if (s_dumpFileName == null)
					{
						Guid guid = Guid.NewGuid();
						Directory.CreateDirectory(DebugDumpPath);
						int id = Process.GetCurrentProcess().Id;
						s_dumpFileName = Path.Combine(DebugDumpPath, $"MSBuild_pid-{id}_{guid:n}.failure.txt");
						using StreamWriter streamWriter = FileUtilities.OpenWrite(s_dumpFileName, append: true);
						streamWriter.WriteLine("UNHANDLED EXCEPTIONS FROM PROCESS {0}:", id);
						streamWriter.WriteLine("=====================");
					}
					using StreamWriter streamWriter2 = FileUtilities.OpenWrite(s_dumpFileName, append: true);
					streamWriter2.WriteLine(DateTime.Now.ToString("G", CultureInfo.CurrentCulture));
					streamWriter2.WriteLine(ex.ToString());
					streamWriter2.WriteLine("===================");
				}
			}
			catch
			{
			}
		}

		internal static string ReadAnyExceptionFromFile(DateTime fromTimeUtc)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (string item in FileSystems.Default.EnumerateFiles(DebugDumpPath, "MSBuild*failure.txt"))
			{
				if (File.GetLastWriteTimeUtc(item) >= fromTimeUtc)
				{
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append(item);
					stringBuilder.Append(':');
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append(File.ReadAllText(item));
					stringBuilder.Append(Environment.NewLine);
				}
			}
			return stringBuilder.ToString();
		}
	}
	internal static class FileUtilities
	{
		internal static class ItemSpecModifiers
		{
			internal const string FullPath = "FullPath";

			internal const string RootDir = "RootDir";

			internal const string Filename = "Filename";

			internal const string Extension = "Extension";

			internal const string RelativeDir = "RelativeDir";

			internal const string Directory = "Directory";

			internal const string RecursiveDir = "RecursiveDir";

			internal const string Identity = "Identity";

			internal const string ModifiedTime = "ModifiedTime";

			internal const string CreatedTime = "CreatedTime";

			internal const string AccessedTime = "AccessedTime";

			internal const string DefiningProjectFullPath = "DefiningProjectFullPath";

			internal const string DefiningProjectDirectory = "DefiningProjectDirectory";

			internal const string DefiningProjectName = "DefiningProjectName";

			internal const string DefiningProjectExtension = "DefiningProjectExtension";

			internal static readonly string[] All = new string[15]
			{
				"FullPath", "RootDir", "Filename", "Extension", "RelativeDir", "Directory", "RecursiveDir", "Identity", "ModifiedTime", "CreatedTime",
				"AccessedTime", "DefiningProjectFullPath", "DefiningProjectDirectory", "DefiningProjectName", "DefiningProjectExtension"
			};

			private static HashSet<string> s_tableOfItemSpecModifiers = new HashSet<string>(All, StringComparer.OrdinalIgnoreCase);

			internal static bool IsItemSpecModifier(string name)
			{
				if (name == null)
				{
					return false;
				}
				switch (name.Length)
				{
				case 7:
					switch (name[0])
					{
					default:
						return false;
					case 'R':
						if (name == "RootDir")
						{
							return true;
						}
						break;
					case 'r':
						break;
					}
					break;
				case 8:
					switch (name[0])
					{
					default:
						return false;
					case 'F':
						if (name == "FullPath")
						{
							return true;
						}
						if (name == "Filename")
						{

folder/Microsoft.IO.Redist.dll

Decompiled 11 months ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
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.Threading.Tasks;
using FxResources.Microsoft.IO.Redist;
using Microsoft.CodeAnalysis;
using Microsoft.IO.Enumeration;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyDefaultAlias("Microsoft.IO.Redist")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Downlevel support package for System.IO classes.")]
[assembly: AssemblyFileVersion("6.0.3224.31407")]
[assembly: AssemblyInformationalVersion("6.0.32+e77011b31a3e5c47d931248a64b47f9b2d47853d")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.IO.Redist")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("6.0.0.1")]
[module: UnverifiableCode]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
}
internal static class Interop
{
	internal static class BCrypt
	{
		internal enum NTSTATUS : uint
		{
			STATUS_SUCCESS = 0u,
			STATUS_NOT_FOUND = 3221226021u,
			STATUS_INVALID_PARAMETER = 3221225485u,
			STATUS_NO_MEMORY = 3221225495u,
			STATUS_AUTH_TAG_MISMATCH = 3221266434u
		}

		internal const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 2;

		[DllImport("BCrypt.dll", CharSet = CharSet.Unicode)]
		internal unsafe static extern NTSTATUS BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags);
	}

	internal enum BOOL
	{
		FALSE,
		TRUE
	}

	internal enum BOOLEAN : byte
	{
		FALSE,
		TRUE
	}

	internal static class Kernel32
	{
		internal struct FILE_TIME
		{
			internal uint dwLowDateTime;

			internal uint dwHighDateTime;

			internal FILE_TIME(long fileTime)
			{
				dwLowDateTime = (uint)fileTime;
				dwHighDateTime = (uint)(fileTime >> 32);
			}

			internal long ToTicks()
			{
				return (long)(((ulong)dwHighDateTime << 32) + dwLowDateTime);
			}

			internal DateTime ToDateTimeUtc()
			{
				return DateTime.FromFileTimeUtc(ToTicks());
			}

			internal DateTimeOffset ToDateTimeOffset()
			{
				return DateTimeOffset.FromFileTime(ToTicks());
			}
		}

		internal struct FILE_BASIC_INFO
		{
			internal long CreationTime;

			internal long LastAccessTime;

			internal long LastWriteTime;

			internal long ChangeTime;

			internal uint FileAttributes;
		}

		internal static class FileAttributes
		{
			internal const int FILE_ATTRIBUTE_NORMAL = 128;

			internal const int FILE_ATTRIBUTE_READONLY = 1;

			internal const int FILE_ATTRIBUTE_DIRECTORY = 16;

			internal const int FILE_ATTRIBUTE_REPARSE_POINT = 1024;
		}

		internal enum FINDEX_INFO_LEVELS : uint
		{
			FindExInfoStandard,
			FindExInfoBasic,
			FindExInfoMaxInfoLevel
		}

		internal enum FINDEX_SEARCH_OPS : uint
		{
			FindExSearchNameMatch,
			FindExSearchLimitToDirectories,
			FindExSearchLimitToDevices,
			FindExSearchMaxSearchOp
		}

		internal static class GenericOperations
		{
			internal const int GENERIC_READ = int.MinValue;

			internal const int GENERIC_WRITE = 1073741824;
		}

		internal enum GET_FILEEX_INFO_LEVELS : uint
		{
			GetFileExInfoStandard,
			GetFileExMaxInfoLevel
		}

		internal struct SymbolicLinkReparseBuffer
		{
			internal uint ReparseTag;

			internal ushort ReparseDataLength;

			internal ushort Reserved;

			internal ushort SubstituteNameOffset;

			internal ushort SubstituteNameLength;

			internal ushort PrintNameOffset;

			internal ushort PrintNameLength;

			internal uint Flags;
		}

		internal struct MountPointReparseBuffer
		{
			public uint ReparseTag;

			public ushort ReparseDataLength;

			public ushort Reserved;

			public ushort SubstituteNameOffset;

			public ushort SubstituteNameLength;

			public ushort PrintNameOffset;

			public ushort PrintNameLength;
		}

		internal struct SECURITY_ATTRIBUTES
		{
			internal uint nLength;

			internal IntPtr lpSecurityDescriptor;

			internal BOOL bInheritHandle;
		}

		internal struct WIN32_FILE_ATTRIBUTE_DATA
		{
			internal int dwFileAttributes;

			internal FILE_TIME ftCreationTime;

			internal FILE_TIME ftLastAccessTime;

			internal FILE_TIME ftLastWriteTime;

			internal uint nFileSizeHigh;

			internal uint nFileSizeLow;

			internal void PopulateFrom(ref WIN32_FIND_DATA findData)
			{
				dwFileAttributes = (int)findData.dwFileAttributes;
				ftCreationTime = findData.ftCreationTime;
				ftLastAccessTime = findData.ftLastAccessTime;
				ftLastWriteTime = findData.ftLastWriteTime;
				nFileSizeHigh = findData.nFileSizeHigh;
				nFileSizeLow = findData.nFileSizeLow;
			}
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct WIN32_FIND_DATA
		{
			internal uint dwFileAttributes;

			internal FILE_TIME ftCreationTime;

			internal FILE_TIME ftLastAccessTime;

			internal FILE_TIME ftLastWriteTime;

			internal uint nFileSizeHigh;

			internal uint nFileSizeLow;

			internal uint dwReserved0;

			internal uint dwReserved1;

			private unsafe fixed char _cFileName[260];

			private unsafe fixed char _cAlternateFileName[14];

			internal unsafe ReadOnlySpan<char> cFileName
			{
				get
				{
					fixed (char* pointer = _cFileName)
					{
						return new ReadOnlySpan<char>(pointer, 260);
					}
				}
			}
		}

		internal static class IOReparseOptions
		{
			internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u;

			internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u;

			internal const uint IO_REPARSE_TAG_SYMLINK = 2684354572u;
		}

		internal static class FileOperations
		{
			internal const int OPEN_EXISTING = 3;

			internal const int COPY_FILE_FAIL_IF_EXISTS = 1;

			internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432;

			internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288;

			internal const int FILE_FLAG_OPEN_REPARSE_POINT = 2097152;

			internal const int FILE_FLAG_OVERLAPPED = 1073741824;

			internal const int FILE_LIST_DIRECTORY = 1;

			internal const int FILE_WRITE_ATTRIBUTES = 256;
		}

		internal const int SYMBOLIC_LINK_FLAG_DIRECTORY = 1;

		internal const int SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 2;

		internal const int FSCTL_GET_REPARSE_POINT = 589992;

		internal const int FileBasicInfo = 0;

		private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512;

		private const int FORMAT_MESSAGE_FROM_HMODULE = 2048;

		private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096;

		private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192;

		private const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 256;

		private const int ERROR_INSUFFICIENT_BUFFER = 122;

		internal const uint FILE_NAME_NORMALIZED = 0u;

		internal const int MAX_PATH = 260;

		internal const int MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384;

		internal const uint SYMLINK_FLAG_RELATIVE = 1u;

		internal const uint SEM_FAILCRITICALERRORS = 1u;

		internal const uint FILE_SUPPORTS_ENCRYPTION = 131072u;

		private const uint MOVEFILE_REPLACE_EXISTING = 1u;

		private const uint MOVEFILE_COPY_ALLOWED = 2u;

		internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 2;

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateSymbolicLinkW", ExactSpelling = true, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.U1)]
		private static extern bool CreateSymbolicLinkPrivate(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);

		internal static void CreateSymbolicLink(string symlinkFileName, string targetFileName, bool isDirectory)
		{
			string path = symlinkFileName;
			symlinkFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(symlinkFileName);
			targetFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(targetFileName);
			int num = 0;
			Version version = Environment.OSVersion.Version;
			if (version.Major >= 11 || (version.Major == 10 && version.Build >= 14972))
			{
				num = 2;
			}
			if (isDirectory)
			{
				num |= 1;
			}
			if (!CreateSymbolicLinkPrivate(symlinkFileName, targetFileName, num))
			{
				throw System.IO.Win32Marshal.GetExceptionForLastWin32Error(path);
			}
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, byte[] lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern bool FindClose(IntPtr hFindFile);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "FindFirstFileExW", ExactSpelling = true, SetLastError = true)]
		private static extern SafeFindHandle FindFirstFileExPrivate(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags);

		internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data)
		{
			fileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(fileName);
			return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0);
		}

		[DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", ExactSpelling = true, SetLastError = true)]
		private unsafe static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, void* lpBuffer, int nSize, IntPtr arguments);

		internal static string GetMessage(int errorCode)
		{
			return GetMessage(errorCode, IntPtr.Zero);
		}

		internal unsafe static string GetMessage(int errorCode, IntPtr moduleHandle)
		{
			int num = 12800;
			if (moduleHandle != IntPtr.Zero)
			{
				num |= 0x800;
			}
			Span<char> span = stackalloc char[256];
			fixed (char* lpBuffer = span)
			{
				int num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, span.Length, IntPtr.Zero);
				if (num2 > 0)
				{
					return GetAndTrimString(span.Slice(0, num2));
				}
			}
			if (Marshal.GetLastWin32Error() == 122)
			{
				IntPtr intPtr = default(IntPtr);
				try
				{
					int num3 = FormatMessage(num | 0x100, moduleHandle, (uint)errorCode, 0, &intPtr, 0, IntPtr.Zero);
					if (num3 > 0)
					{
						return GetAndTrimString(new Span<char>((void*)intPtr, num3));
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
			}
			return $"Unknown error (0x{errorCode:x})";
		}

		private static string GetAndTrimString(Span<char> buffer)
		{
			int num = buffer.Length;
			while (num > 0 && buffer[num - 1] <= ' ')
			{
				num--;
			}
			return buffer.Slice(0, num).ToString();
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetFileAttributesExW", ExactSpelling = true, SetLastError = true)]
		private static extern bool GetFileAttributesExPrivate(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);

		internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation)
		{
			name = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(name);
			return GetFileAttributesExPrivate(name, fileInfoLevel, ref lpFileInformation);
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetFinalPathNameByHandleW", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern uint GetFinalPathNameByHandle(SafeFileHandle hFile, char* lpszFilePath, uint cchFilePath, uint dwFlags);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetFullPathNameW(ref char lpFileName, uint nBufferLength, ref char lpBuffer, IntPtr lpFilePart);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern int GetLogicalDrives();

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetLongPathNameW(ref char lpszShortPath, ref char lpszLongPath, uint cchBuffer);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetTempFileNameW(ref char lpPathName, string lpPrefixString, uint uUnique, ref char lpTempFileName);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true)]
		internal static extern uint GetTempPathW(int bufferLen, ref char buffer);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true)]
		internal static extern uint GetTempPath2W(int bufferLen, ref char buffer);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW", SetLastError = true)]
		internal static extern IntPtr GetModuleHandle(string moduleName);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Ansi)]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		[SuppressGCTransition]
		internal static extern bool SetThreadErrorMode(uint dwNewMode, out uint lpOldMode);

		internal static int CopyFile(string src, string dst, bool failIfExists)
		{
			int flags = (failIfExists ? 1 : 0);
			int cancel = 0;
			if (!CopyFileEx(src, dst, IntPtr.Zero, IntPtr.Zero, ref cancel, flags))
			{
				return Marshal.GetLastWin32Error();
			}
			return 0;
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CopyFileExW", SetLastError = true)]
		private static extern bool CopyFileExPrivate(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags);

		internal static bool CopyFileEx(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags)
		{
			src = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(src);
			dst = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(dst);
			return CopyFileExPrivate(src, dst, progressRoutine, progressData, ref cancel, flags);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryW", SetLastError = true)]
		private static extern bool CreateDirectoryPrivate(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes);

		internal static bool CreateDirectory(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes)
		{
			path = System.IO.PathInternal.EnsureExtendedPrefix(path);
			return CreateDirectoryPrivate(path, ref lpSecurityAttributes);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)]
		private unsafe static extern SafeFileHandle CreateFilePrivate(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

		internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)
		{
			lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
		}

		internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes)
		{
			lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)]
		private unsafe static extern IntPtr CreateFilePrivate_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

		internal unsafe static IntPtr CreateFile_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes)
		{
			lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			return CreateFilePrivate_IntPtr(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteFileW", SetLastError = true)]
		private static extern bool DeleteFilePrivate(string path);

		internal static bool DeleteFile(string path)
		{
			path = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(path);
			return DeleteFilePrivate(path);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true)]
		internal static extern bool DeleteVolumeMountPointPrivate(string mountPoint);

		internal static bool DeleteVolumeMountPoint(string mountPoint)
		{
			mountPoint = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint);
			return DeleteVolumeMountPointPrivate(mountPoint);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "FindNextFileW", SetLastError = true)]
		internal static extern bool FindNextFile(SafeFindHandle hndFindFile, ref WIN32_FIND_DATA lpFindFileData);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW", SetLastError = true)]
		internal unsafe static extern bool GetVolumeInformation(string drive, char* volumeName, int volumeNameBufLen, int* volSerialNumber, int* maxFileNameLen, out int fileSystemFlags, char* fileSystemName, int fileSystemNameBufLen);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW", SetLastError = true)]
		private static extern bool MoveFileExPrivate(string src, string dst, uint flags);

		internal static bool MoveFile(string src, string dst, bool overwrite)
		{
			src = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(src);
			dst = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(dst);
			uint num = 2u;
			if (overwrite)
			{
				num |= 1u;
			}
			return MoveFileExPrivate(src, dst, num);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RemoveDirectoryW", SetLastError = true)]
		private static extern bool RemoveDirectoryPrivate(string path);

		internal static bool RemoveDirectory(string path)
		{
			path = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(path);
			return RemoveDirectoryPrivate(path);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "ReplaceFileW", SetLastError = true)]
		private static extern bool ReplaceFilePrivate(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved);

		internal static bool ReplaceFile(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved)
		{
			replacedFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(replacedFileName);
			replacementFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(replacementFileName);
			backupFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(backupFileName);
			return ReplaceFilePrivate(replacedFileName, replacementFileName, backupFileName, dwReplaceFlags, lpExclude, lpReserved);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "SetFileAttributesW", SetLastError = true)]
		private static extern bool SetFileAttributesPrivate(string name, int attr);

		internal static bool SetFileAttributes(string name, int attr)
		{
			name = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(name);
			return SetFileAttributesPrivate(name, attr);
		}

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern bool SetFileInformationByHandle(SafeFileHandle hFile, int FileInformationClass, void* lpFileInformation, uint dwBufferSize);
	}

	internal static class Advapi32
	{
		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "EncryptFileW", SetLastError = true)]
		private static extern bool EncryptFilePrivate(string lpFileName);

		internal static bool EncryptFile(string path)
		{
			path = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(path);
			return EncryptFilePrivate(path);
		}

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "DecryptFileW", SetLastError = true)]
		private static extern bool DecryptFileFilePrivate(string lpFileName, int dwReserved);

		internal static bool DecryptFile(string path)
		{
			path = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(path);
			return DecryptFileFilePrivate(path, 0);
		}
	}

	internal static class Errors
	{
		internal const int ERROR_SUCCESS = 0;

		internal const int ERROR_INVALID_FUNCTION = 1;

		internal const int ERROR_FILE_NOT_FOUND = 2;

		internal const int ERROR_PATH_NOT_FOUND = 3;

		internal const int ERROR_ACCESS_DENIED = 5;

		internal const int ERROR_INVALID_HANDLE = 6;

		internal const int ERROR_NOT_ENOUGH_MEMORY = 8;

		internal const int ERROR_INVALID_DATA = 13;

		internal const int ERROR_INVALID_DRIVE = 15;

		internal const int ERROR_NO_MORE_FILES = 18;

		internal const int ERROR_NOT_READY = 21;

		internal const int ERROR_BAD_COMMAND = 22;

		internal const int ERROR_BAD_LENGTH = 24;

		internal const int ERROR_SHARING_VIOLATION = 32;

		internal const int ERROR_LOCK_VIOLATION = 33;

		internal const int ERROR_HANDLE_EOF = 38;

		internal const int ERROR_NOT_SUPPORTED = 50;

		internal const int ERROR_BAD_NETPATH = 53;

		internal const int ERROR_NETWORK_ACCESS_DENIED = 65;

		internal const int ERROR_BAD_NET_NAME = 67;

		internal const int ERROR_FILE_EXISTS = 80;

		internal const int ERROR_INVALID_PARAMETER = 87;

		internal const int ERROR_BROKEN_PIPE = 109;

		internal const int ERROR_DISK_FULL = 112;

		internal const int ERROR_SEM_TIMEOUT = 121;

		internal const int ERROR_CALL_NOT_IMPLEMENTED = 120;

		internal const int ERROR_INSUFFICIENT_BUFFER = 122;

		internal const int ERROR_INVALID_NAME = 123;

		internal const int ERROR_NEGATIVE_SEEK = 131;

		internal const int ERROR_DIR_NOT_EMPTY = 145;

		internal const int ERROR_BAD_PATHNAME = 161;

		internal const int ERROR_LOCK_FAILED = 167;

		internal const int ERROR_BUSY = 170;

		internal const int ERROR_ALREADY_EXISTS = 183;

		internal const int ERROR_BAD_EXE_FORMAT = 193;

		internal const int ERROR_ENVVAR_NOT_FOUND = 203;

		internal const int ERROR_FILENAME_EXCED_RANGE = 206;

		internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;

		internal const int ERROR_FILE_TOO_LARGE = 223;

		internal const int ERROR_PIPE_BUSY = 231;

		internal const int ERROR_NO_DATA = 232;

		internal const int ERROR_PIPE_NOT_CONNECTED = 233;

		internal const int ERROR_MORE_DATA = 234;

		internal const int ERROR_NO_MORE_ITEMS = 259;

		internal const int ERROR_DIRECTORY = 267;

		internal const int ERROR_NOT_OWNER = 288;

		internal const int ERROR_TOO_MANY_POSTS = 298;

		internal const int ERROR_PARTIAL_COPY = 299;

		internal const int ERROR_ARITHMETIC_OVERFLOW = 534;

		internal const int ERROR_PIPE_CONNECTED = 535;

		internal const int ERROR_PIPE_LISTENING = 536;

		internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 587;

		internal const int ERROR_OPERATION_ABORTED = 995;

		internal const int ERROR_IO_INCOMPLETE = 996;

		internal const int ERROR_IO_PENDING = 997;

		internal const int ERROR_NO_TOKEN = 1008;

		internal const int ERROR_SERVICE_DOES_NOT_EXIST = 1060;

		internal const int ERROR_EXCEPTION_IN_SERVICE = 1064;

		internal const int ERROR_PROCESS_ABORTED = 1067;

		internal const int ERROR_NO_UNICODE_TRANSLATION = 1113;

		internal const int ERROR_DLL_INIT_FAILED = 1114;

		internal const int ERROR_COUNTER_TIMEOUT = 1121;

		internal const int ERROR_NO_ASSOCIATION = 1155;

		internal const int ERROR_DDE_FAIL = 1156;

		internal const int ERROR_DLL_NOT_FOUND = 1157;

		internal const int ERROR_NOT_FOUND = 1168;

		internal const int ERROR_NETWORK_UNREACHABLE = 1231;

		internal const int ERROR_NON_ACCOUNT_SID = 1257;

		internal const int ERROR_NOT_ALL_ASSIGNED = 1300;

		internal const int ERROR_UNKNOWN_REVISION = 1305;

		internal const int ERROR_INVALID_OWNER = 1307;

		internal const int ERROR_INVALID_PRIMARY_GROUP = 1308;

		internal const int ERROR_NO_SUCH_PRIVILEGE = 1313;

		internal const int ERROR_PRIVILEGE_NOT_HELD = 1314;

		internal const int ERROR_INVALID_ACL = 1336;

		internal const int ERROR_INVALID_SECURITY_DESCR = 1338;

		internal const int ERROR_INVALID_SID = 1337;

		internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346;

		internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347;

		internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350;

		internal const int ERROR_CANNOT_IMPERSONATE = 1368;

		internal const int ERROR_CLASS_ALREADY_EXISTS = 1410;

		internal const int ERROR_NO_SYSTEM_RESOURCES = 1450;

		internal const int ERROR_TIMEOUT = 1460;

		internal const int ERROR_EVENTLOG_FILE_CHANGED = 1503;

		internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789;

		internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815;

		internal const int ERROR_NOT_A_REPARSE_POINT = 4390;
	}

	internal static class Libraries
	{
		internal const string Activeds = "activeds.dll";

		internal const string Advapi32 = "advapi32.dll";

		internal const string Authz = "authz.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string Credui = "credui.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string CryptUI = "cryptui.dll";

		internal const string Dnsapi = "dnsapi.dll";

		internal const string Dsrole = "dsrole.dll";

		internal const string Gdi32 = "gdi32.dll";

		internal const string HttpApi = "httpapi.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Logoncli = "logoncli.dll";

		internal const string Mswsock = "mswsock.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string Netapi32 = "netapi32.dll";

		internal const string Netutils = "netutils.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string Odbc32 = "odbc32.dll";

		internal const string Ole32 = "ole32.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string Pdh = "pdh.dll";

		internal const string Secur32 = "secur32.dll";

		internal const string Shell32 = "shell32.dll";

		internal const string SspiCli = "sspicli.dll";

		internal const string User32 = "user32.dll";

		internal const string Version = "version.dll";

		internal const string WebSocket = "websocket.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string WinMM = "winmm.dll";

		internal const string Wkscli = "wkscli.dll";

		internal const string Wldap32 = "wldap32.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Wtsapi32 = "wtsapi32.dll";

		internal const string CompressionNative = "System.IO.Compression.Native";

		internal const string GlobalizationNative = "System.Globalization.Native";

		internal const string MsQuic = "msquic.dll";

		internal const string HostPolicy = "hostpolicy.dll";

		internal const string Ucrtbase = "ucrtbase.dll";
	}

	internal struct LongFileTime
	{
		internal long TicksSince1601;

		internal DateTimeOffset ToDateTimeOffset()
		{
			return new DateTimeOffset(DateTime.FromFileTimeUtc(TicksSince1601));
		}
	}

	internal struct OBJECT_ATTRIBUTES
	{
		public uint Length;

		public IntPtr RootDirectory;

		public unsafe UNICODE_STRING* ObjectName;

		public ObjectAttributes Attributes;

		public unsafe void* SecurityDescriptor;

		public unsafe SECURITY_QUALITY_OF_SERVICE* SecurityQualityOfService;

		public unsafe OBJECT_ATTRIBUTES(UNICODE_STRING* objectName, ObjectAttributes attributes, IntPtr rootDirectory, SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = null)
		{
			Length = (uint)sizeof(OBJECT_ATTRIBUTES);
			RootDirectory = rootDirectory;
			ObjectName = objectName;
			Attributes = attributes;
			SecurityDescriptor = null;
			SecurityQualityOfService = securityQualityOfService;
		}
	}

	[Flags]
	public enum ObjectAttributes : uint
	{
		OBJ_INHERIT = 2u,
		OBJ_PERMANENT = 0x10u,
		OBJ_EXCLUSIVE = 0x20u,
		OBJ_CASE_INSENSITIVE = 0x40u,
		OBJ_OPENIF = 0x80u,
		OBJ_OPENLINK = 0x100u
	}

	internal struct UNICODE_STRING
	{
		internal ushort Length;

		internal ushort MaximumLength;

		internal IntPtr Buffer;
	}

	internal struct SECURITY_QUALITY_OF_SERVICE
	{
		public uint Length;

		public ImpersonationLevel ImpersonationLevel;

		public ContextTrackingMode ContextTrackingMode;

		public BOOLEAN EffectiveOnly;

		public unsafe SECURITY_QUALITY_OF_SERVICE(ImpersonationLevel impersonationLevel, ContextTrackingMode contextTrackingMode, bool effectiveOnly)
		{
			Length = (uint)sizeof(SECURITY_QUALITY_OF_SERVICE);
			ImpersonationLevel = impersonationLevel;
			ContextTrackingMode = contextTrackingMode;
			EffectiveOnly = (effectiveOnly ? BOOLEAN.TRUE : BOOLEAN.FALSE);
		}
	}

	public enum ImpersonationLevel : uint
	{
		Anonymous,
		Identification,
		Impersonation,
		Delegation
	}

	public enum ContextTrackingMode : byte
	{
		Static,
		Dynamic
	}

	internal static class NtDll
	{
		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		public struct FILE_FULL_DIR_INFORMATION
		{
			public uint NextEntryOffset;

			public uint FileIndex;

			public LongFileTime CreationTime;

			public LongFileTime LastAccessTime;

			public LongFileTime LastWriteTime;

			public LongFileTime ChangeTime;

			public long EndOfFile;

			public long AllocationSize;

			public FileAttributes FileAttributes;

			public uint FileNameLength;

			public uint EaSize;

			private char _fileName;

			public unsafe ReadOnlySpan<char> FileName
			{
				get
				{
					fixed (char* pointer = &_fileName)
					{
						return new ReadOnlySpan<char>(pointer, (int)FileNameLength / 2);
					}
				}
			}

			public unsafe static FILE_FULL_DIR_INFORMATION* GetNextInfo(FILE_FULL_DIR_INFORMATION* info)
			{
				if (info == null)
				{
					return null;
				}
				uint nextEntryOffset = info->NextEntryOffset;
				if (nextEntryOffset == 0)
				{
					return null;
				}
				return (FILE_FULL_DIR_INFORMATION*)((byte*)info + nextEntryOffset);
			}
		}

		public enum FILE_INFORMATION_CLASS : uint
		{
			FileDirectoryInformation = 1u,
			FileFullDirectoryInformation,
			FileBothDirectoryInformation,
			FileBasicInformation,
			FileStandardInformation,
			FileInternalInformation,
			FileEaInformation,
			FileAccessInformation,
			FileNameInformation,
			FileRenameInformation,
			FileLinkInformation,
			FileNamesInformation,
			FileDispositionInformation,
			FilePositionInformation,
			FileFullEaInformation,
			FileModeInformation,
			FileAlignmentInformation,
			FileAllInformation,
			FileAllocationInformation,
			FileEndOfFileInformation,
			FileAlternateNameInformation,
			FileStreamInformation,
			FilePipeInformation,
			FilePipeLocalInformation,
			FilePipeRemoteInformation,
			FileMailslotQueryInformation,
			FileMailslotSetInformation,
			FileCompressionInformation,
			FileObjectIdInformation,
			FileCompletionInformation,
			FileMoveClusterInformation,
			FileQuotaInformation,
			FileReparsePointInformation,
			FileNetworkOpenInformation,
			FileAttributeTagInformation,
			FileTrackingInformation,
			FileIdBothDirectoryInformation,
			FileIdFullDirectoryInformation,
			FileValidDataLengthInformation,
			FileShortNameInformation,
			FileIoCompletionNotificationInformation,
			FileIoStatusBlockRangeInformation,
			FileIoPriorityHintInformation,
			FileSfioReserveInformation,
			FileSfioVolumeInformation,
			FileHardLinkInformation,
			FileProcessIdsUsingFileInformation,
			FileNormalizedNameInformation,
			FileNetworkPhysicalNameInformation,
			FileIdGlobalTxDirectoryInformation,
			FileIsRemoteDeviceInformation,
			FileUnusedInformation,
			FileNumaNodeInformation,
			FileStandardLinkInformation,
			FileRemoteProtocolInformation,
			FileRenameInformationBypassAccessCheck,
			FileLinkInformationBypassAccessCheck,
			FileVolumeNameInformation,
			FileIdInformation,
			FileIdExtdDirectoryInformation,
			FileReplaceCompletionInformation,
			FileHardLinkFullIdInformation,
			FileIdExtdBothDirectoryInformation,
			FileDispositionInformationEx,
			FileRenameInformationEx,
			FileRenameInformationExBypassAccessCheck,
			FileDesiredStorageClassInformation,
			FileStatInformation
		}

		public struct IO_STATUS_BLOCK
		{
			[StructLayout(LayoutKind.Explicit)]
			public struct IO_STATUS
			{
				[FieldOffset(0)]
				public uint Status;

				[FieldOffset(0)]
				public IntPtr Pointer;
			}

			public IO_STATUS Status;

			public IntPtr Information;
		}

		public enum CreateDisposition : uint
		{
			FILE_SUPERSEDE,
			FILE_OPEN,
			FILE_CREATE,
			FILE_OPEN_IF,
			FILE_OVERWRITE,
			FILE_OVERWRITE_IF
		}

		public enum CreateOptions : uint
		{
			FILE_DIRECTORY_FILE = 1u,
			FILE_WRITE_THROUGH = 2u,
			FILE_SEQUENTIAL_ONLY = 4u,
			FILE_NO_INTERMEDIATE_BUFFERING = 8u,
			FILE_SYNCHRONOUS_IO_ALERT = 0x10u,
			FILE_SYNCHRONOUS_IO_NONALERT = 0x20u,
			FILE_NON_DIRECTORY_FILE = 0x40u,
			FILE_CREATE_TREE_CONNECTION = 0x80u,
			FILE_COMPLETE_IF_OPLOCKED = 0x100u,
			FILE_NO_EA_KNOWLEDGE = 0x200u,
			FILE_RANDOM_ACCESS = 0x800u,
			FILE_DELETE_ON_CLOSE = 0x1000u,
			FILE_OPEN_BY_FILE_ID = 0x2000u,
			FILE_OPEN_FOR_BACKUP_INTENT = 0x4000u,
			FILE_NO_COMPRESSION = 0x8000u,
			FILE_OPEN_REQUIRING_OPLOCK = 0x10000u,
			FILE_DISALLOW_EXCLUSIVE = 0x20000u,
			FILE_SESSION_AWARE = 0x40000u,
			FILE_RESERVE_OPFILTER = 0x100000u,
			FILE_OPEN_REPARSE_POINT = 0x200000u,
			FILE_OPEN_NO_RECALL = 0x400000u
		}

		[Flags]
		public enum DesiredAccess : uint
		{
			FILE_READ_DATA = 1u,
			FILE_LIST_DIRECTORY = 1u,
			FILE_WRITE_DATA = 2u,
			FILE_ADD_FILE = 2u,
			FILE_APPEND_DATA = 4u,
			FILE_ADD_SUBDIRECTORY = 4u,
			FILE_CREATE_PIPE_INSTANCE = 4u,
			FILE_READ_EA = 8u,
			FILE_WRITE_EA = 0x10u,
			FILE_EXECUTE = 0x20u,
			FILE_TRAVERSE = 0x20u,
			FILE_DELETE_CHILD = 0x40u,
			FILE_READ_ATTRIBUTES = 0x80u,
			FILE_WRITE_ATTRIBUTES = 0x100u,
			FILE_ALL_ACCESS = 0xF01FFu,
			DELETE = 0x10000u,
			READ_CONTROL = 0x20000u,
			WRITE_DAC = 0x40000u,
			WRITE_OWNER = 0x80000u,
			SYNCHRONIZE = 0x100000u,
			STANDARD_RIGHTS_READ = 0x20000u,
			STANDARD_RIGHTS_WRITE = 0x20000u,
			STANDARD_RIGHTS_EXECUTE = 0x20000u,
			FILE_GENERIC_READ = 0x80000000u,
			FILE_GENERIC_WRITE = 0x40000000u,
			FILE_GENERIC_EXECUTE = 0x20000000u
		}

		[DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
		private unsafe static extern uint NtCreateFile(IntPtr* FileHandle, DesiredAccess DesiredAccess, OBJECT_ATTRIBUTES* ObjectAttributes, IO_STATUS_BLOCK* IoStatusBlock, long* AllocationSize, FileAttributes FileAttributes, FileShare ShareAccess, CreateDisposition CreateDisposition, CreateOptions CreateOptions, void* EaBuffer, uint EaLength);

		internal unsafe static (uint status, IntPtr handle) CreateFile(ReadOnlySpan<char> path, IntPtr rootDirectory, CreateDisposition createDisposition, DesiredAccess desiredAccess = DesiredAccess.SYNCHRONIZE | DesiredAccess.FILE_GENERIC_READ, FileShare shareAccess = FileShare.ReadWrite | FileShare.Delete, FileAttributes fileAttributes = (FileAttributes)0, CreateOptions createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT, ObjectAttributes objectAttributes = ObjectAttributes.OBJ_CASE_INSENSITIVE, void* eaBuffer = null, uint eaLength = 0u, long* preallocationSize = null, SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = null)
		{
			checked
			{
				fixed (char* ptr = &MemoryMarshal.GetReference(path))
				{
					UNICODE_STRING uNICODE_STRING = default(UNICODE_STRING);
					uNICODE_STRING.Length = (ushort)(path.Length * 2);
					uNICODE_STRING.MaximumLength = (ushort)(path.Length * 2);
					uNICODE_STRING.Buffer = (IntPtr)ptr;
					UNICODE_STRING uNICODE_STRING2 = uNICODE_STRING;
					OBJECT_ATTRIBUTES oBJECT_ATTRIBUTES = new OBJECT_ATTRIBUTES(&uNICODE_STRING2, objectAttributes, rootDirectory, securityQualityOfService);
					IntPtr item = default(IntPtr);
					IO_STATUS_BLOCK iO_STATUS_BLOCK = default(IO_STATUS_BLOCK);
					uint item2 = NtCreateFile(&item, desiredAccess, &oBJECT_ATTRIBUTES, &iO_STATUS_BLOCK, preallocationSize, fileAttributes, shareAccess, createDisposition, createOptions, eaBuffer, eaLength);
					return (item2, item);
				}
			}
		}

		internal unsafe static (uint status, IntPtr handle) NtCreateFile(ReadOnlySpan<char> path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize)
		{
			SECURITY_QUALITY_OF_SERVICE sECURITY_QUALITY_OF_SERVICE = new SECURITY_QUALITY_OF_SERVICE(ImpersonationLevel.Anonymous, ContextTrackingMode.Static, effectiveOnly: false);
			IntPtr zero = IntPtr.Zero;
			CreateDisposition createDisposition = GetCreateDisposition(mode);
			DesiredAccess desiredAccess = GetDesiredAccess(access, mode, options);
			FileShare shareAccess = GetShareAccess(share);
			FileAttributes fileAttributes = GetFileAttributes(options);
			CreateOptions createOptions = GetCreateOptions(options);
			ObjectAttributes objectAttributes = GetObjectAttributes(share);
			long* preallocationSize2 = &preallocationSize;
			SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = &sECURITY_QUALITY_OF_SERVICE;
			return CreateFile(path, zero, createDisposition, desiredAccess, shareAccess, fileAttributes, createOptions, objectAttributes, null, 0u, preallocationSize2, securityQualityOfService);
		}

		private static CreateDisposition GetCreateDisposition(FileMode mode)
		{
			switch (mode)
			{
			case FileMode.CreateNew:
				return CreateDisposition.FILE_CREATE;
			case FileMode.Create:
				return CreateDisposition.FILE_SUPERSEDE;
			case FileMode.OpenOrCreate:
			case FileMode.Append:
				return CreateDisposition.FILE_OPEN_IF;
			case FileMode.Truncate:
				return CreateDisposition.FILE_OVERWRITE;
			default:
				return CreateDisposition.FILE_OPEN;
			}
		}

		private static DesiredAccess GetDesiredAccess(FileAccess access, FileMode fileMode, FileOptions options)
		{
			DesiredAccess desiredAccess = DesiredAccess.FILE_READ_ATTRIBUTES | DesiredAccess.SYNCHRONIZE;
			if ((access & FileAccess.Read) != 0)
			{
				desiredAccess |= DesiredAccess.FILE_GENERIC_READ;
			}
			if ((access & FileAccess.Write) != 0)
			{
				desiredAccess |= DesiredAccess.FILE_GENERIC_WRITE;
			}
			if (fileMode == FileMode.Append)
			{
				desiredAccess |= DesiredAccess.FILE_APPEND_DATA;
			}
			if ((options & FileOptions.DeleteOnClose) != 0)
			{
				desiredAccess |= DesiredAccess.DELETE;
			}
			return desiredAccess;
		}

		private static FileShare GetShareAccess(FileShare share)
		{
			return share & ~FileShare.Inheritable;
		}

		private static FileAttributes GetFileAttributes(FileOptions options)
		{
			if ((options & FileOptions.Encrypted) == 0)
			{
				return (FileAttributes)0;
			}
			return FileAttributes.Encrypted;
		}

		private static CreateOptions GetCreateOptions(FileOptions options)
		{
			CreateOptions createOptions = CreateOptions.FILE_NON_DIRECTORY_FILE;
			if (((uint)options & 0x80000000u) != 0)
			{
				createOptions |= CreateOptions.FILE_WRITE_THROUGH;
			}
			if ((options & FileOptions.RandomAccess) != 0)
			{
				createOptions |= CreateOptions.FILE_RANDOM_ACCESS;
			}
			if ((options & FileOptions.SequentialScan) != 0)
			{
				createOptions |= CreateOptions.FILE_SEQUENTIAL_ONLY;
			}
			if ((options & FileOptions.DeleteOnClose) != 0)
			{
				createOptions |= CreateOptions.FILE_DELETE_ON_CLOSE;
			}
			if ((options & FileOptions.Asynchronous) == 0)
			{
				createOptions |= CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT;
			}
			if ((options & (FileOptions)536870912) != 0)
			{
				createOptions |= CreateOptions.FILE_NO_INTERMEDIATE_BUFFERING;
			}
			return createOptions;
		}

		private static ObjectAttributes GetObjectAttributes(FileShare share)
		{
			return ObjectAttributes.OBJ_CASE_INSENSITIVE | (((share & FileShare.Inheritable) != 0) ? ObjectAttributes.OBJ_INHERIT : ((ObjectAttributes)0u));
		}

		[DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
		public unsafe static extern int NtQueryDirectoryFile(IntPtr FileHandle, IntPtr Event, IntPtr ApcRoutine, IntPtr ApcContext, IO_STATUS_BLOCK* IoStatusBlock, IntPtr FileInformation, uint Length, FILE_INFORMATION_CLASS FileInformationClass, BOOLEAN ReturnSingleEntry, UNICODE_STRING* FileName, BOOLEAN RestartScan);

		[DllImport("ntdll.dll", ExactSpelling = true)]
		public static extern uint RtlNtStatusToDosError(int Status);
	}

	internal static class StatusOptions
	{
		internal const uint STATUS_SUCCESS = 0u;

		internal const uint STATUS_SOME_NOT_MAPPED = 263u;

		internal const uint STATUS_NO_MORE_FILES = 2147483654u;

		internal const uint STATUS_INVALID_PARAMETER = 3221225485u;

		internal const uint STATUS_FILE_NOT_FOUND = 3221225487u;

		internal const uint STATUS_NO_MEMORY = 3221225495u;

		internal const uint STATUS_ACCESS_DENIED = 3221225506u;

		internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 3221225524u;

		internal const uint STATUS_ACCOUNT_RESTRICTION = 3221225582u;

		internal const uint STATUS_NONE_MAPPED = 3221225587u;

		internal const uint STATUS_INSUFFICIENT_RESOURCES = 3221225626u;

		internal const uint STATUS_DISK_FULL = 3221225599u;

		internal const uint STATUS_FILE_TOO_LARGE = 3221227780u;
	}

	internal unsafe static void GetRandomBytes(byte* buffer, int length)
	{
		switch (BCrypt.BCryptGenRandom(IntPtr.Zero, buffer, length, 2))
		{
		case BCrypt.NTSTATUS.STATUS_NO_MEMORY:
			throw new OutOfMemoryException();
		default:
			throw new InvalidOperationException();
		case BCrypt.NTSTATUS.STATUS_SUCCESS:
			break;
		}
	}
}
namespace FxResources.Microsoft.IO.Redist
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class FixedBufferExtensions
	{
		internal unsafe static string GetStringFromFixedBuffer(this ReadOnlySpan<char> span)
		{
			fixed (char* value = &MemoryMarshal.GetReference(span))
			{
				return new string(value, 0, span.GetFixedBufferStringLength());
			}
		}

		internal static int GetFixedBufferStringLength(this ReadOnlySpan<char> span)
		{
			int num = span.IndexOf('\0');
			if (num >= 0)
			{
				return num;
			}
			return span.Length;
		}

		internal static bool FixedBufferEqualsString(this ReadOnlySpan<char> span, string value)
		{
			if (value == null || value.Length > span.Length)
			{
				return false;
			}
			int i;
			for (i = 0; i < value.Length; i++)
			{
				if (value[i] == '\0' || value[i] != span[i])
				{
					return false;
				}
			}
			if (i != span.Length)
			{
				return span[i] == '\0';
			}
			return true;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Arg_FileIsDirectory_Name => GetResourceString("Arg_FileIsDirectory_Name");

		internal static string Arg_InvalidFileAttrs => GetResourceString("Arg_InvalidFileAttrs");

		internal static string Arg_Path2IsRooted => GetResourceString("Arg_Path2IsRooted");

		internal static string Arg_PathIsVolume => GetResourceString("Arg_PathIsVolume");

		internal static string ArgumentNull_FileName => GetResourceString("ArgumentNull_FileName");

		internal static string ArgumentNull_Path => GetResourceString("ArgumentNull_Path");

		internal static string ArgumentOutOfRange_Enum => GetResourceString("ArgumentOutOfRange_Enum");

		internal static string Argument_EmptyFileName => GetResourceString("Argument_EmptyFileName");

		internal static string Argument_EmptyPath => GetResourceString("Argument_EmptyPath");

		internal static string Argument_InvalidPathChars => GetResourceString("Argument_InvalidPathChars");

		internal static string Argument_InvalidSeekOrigin => GetResourceString("Argument_InvalidSeekOrigin");

		internal static string Argument_InvalidSubPath => GetResourceString("Argument_InvalidSubPath");

		internal static string Argument_PathEmpty => GetResourceString("Argument_PathEmpty");

		internal static string IO_AlreadyExists_Name => GetResourceString("IO_AlreadyExists_Name");

		internal static string IO_CannotCreateDirectory => GetResourceString("IO_CannotCreateDirectory");

		internal static string IO_EOF_ReadBeyondEOF => GetResourceString("IO_EOF_ReadBeyondEOF");

		internal static string IO_FileExists_Name => GetResourceString("IO_FileExists_Name");

		internal static string IO_FileNotFound => GetResourceString("IO_FileNotFound");

		internal static string IO_FileNotFound_FileName => GetResourceString("IO_FileNotFound_FileName");

		internal static string IO_FileTooLong2GB => GetResourceString("IO_FileTooLong2GB");

		internal static string IO_InconsistentLinkType => GetResourceString("IO_InconsistentLinkType");

		internal static string IO_PathNotFound_NoPathName => GetResourceString("IO_PathNotFound_NoPathName");

		internal static string IO_PathNotFound_Path => GetResourceString("IO_PathNotFound_Path");

		internal static string IO_PathTooLong => GetResourceString("IO_PathTooLong");

		internal static string IO_SharingViolation_File => GetResourceString("IO_SharingViolation_File");

		internal static string IO_SharingViolation_NoFileName => GetResourceString("IO_SharingViolation_NoFileName");

		internal static string IO_SourceDestMustBeDifferent => GetResourceString("IO_SourceDestMustBeDifferent");

		internal static string IO_SourceDestMustHaveSameRoot => GetResourceString("IO_SourceDestMustHaveSameRoot");

		internal static string IO_UnknownFileName => GetResourceString("IO_UnknownFileName");

		internal static string UnauthorizedAccess_IODenied_NoPathName => GetResourceString("UnauthorizedAccess_IODenied_NoPathName");

		internal static string UnauthorizedAccess_IODenied_Path => GetResourceString("UnauthorizedAccess_IODenied_Path");

		internal static string PlatformNotSupported_FileEncryption => GetResourceString("PlatformNotSupported_FileEncryption");

		internal static string IO_PathTooLong_Path => GetResourceString("IO_PathTooLong_Path");

		internal static string Arg_BasePathNotFullyQualified => GetResourceString("Arg_BasePathNotFullyQualified");

		internal static string Arg_PathEmpty => GetResourceString("Arg_PathEmpty");

		internal static string Arg_MustBeDriveLetterOrRootDir => GetResourceString("Arg_MustBeDriveLetterOrRootDir");

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum");

		private static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		internal static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.Versioning
{
	internal abstract class OSPlatformAttribute : Attribute
	{
		public string PlatformName { get; }

		private protected OSPlatformAttribute(string platformName)
		{
			PlatformName = platformName;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
	internal sealed class TargetPlatformAttribute : OSPlatformAttribute
	{
		public TargetPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public UnsupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public UnsupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class SuppressGCTransitionAttribute : Attribute
	{
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			if ((uint)pos < (uint)_chars.Length)
			{
				_chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(ReadOnlySpan<char> value)
		{
			int pos = _pos;
			if (pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			char[] array = ArrayPool<char>.Shared.Rent((int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), (uint)(_chars.Length * 2)));
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.IO
{
	internal abstract class Iterator<TSource> : IEnumerable<TSource>, IEnumerable, IEnumerator<TSource>, IDisposable, IEnumerator
	{
		private readonly int _threadId;

		internal int state;

		internal TSource current;

		public TSource Current => current;

		object IEnumerator.Current => Current;

		public Iterator()
		{
			_threadId = Environment.CurrentManagedThreadId;
		}

		protected abstract System.IO.Iterator<TSource> Clone();

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			current = default(TSource);
			state = -1;
		}

		public IEnumerator<TSource> GetEnumerator()
		{
			if (state == 0 && _threadId == Environment.CurrentManagedThreadId)
			{
				state = 1;
				return this;
			}
			System.IO.Iterator<TSource> iterator = Clone();
			iterator.state = 1;
			return iterator;
		}

		public abstract bool MoveNext();

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}
	internal sealed class ReadLinesIterator : System.IO.Iterator<string>
	{
		private readonly string _path;

		private readonly Encoding _encoding;

		private StreamReader _reader;

		private ReadLinesIterator(string path, Encoding encoding, StreamReader reader)
		{
			_path = path;
			_encoding = encoding;
			_reader = reader;
		}

		public override bool MoveNext()
		{
			if (_reader != null)
			{
				current = _reader.ReadLine();
				if (current != null)
				{
					return true;
				}
				Dispose();
			}
			return false;
		}

		protected override System.IO.Iterator<string> Clone()
		{
			return CreateIterator(_path, _encoding, _reader);
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				if (disposing && _reader != null)
				{
					_reader.Dispose();
				}
			}
			finally
			{
				_reader = null;
				base.Dispose(disposing);
			}
		}

		internal static System.IO.ReadLinesIterator CreateIterator(string path, Encoding encoding)
		{
			return CreateIterator(path, encoding, null);
		}

		private static System.IO.ReadLinesIterator CreateIterator(string path, Encoding encoding, StreamReader reader)
		{
			return new System.IO.ReadLinesIterator(path, encoding, reader ?? new StreamReader(path, encoding));
		}
	}
	internal static class DriveInfoInternal
	{
		public static string[] GetLogicalDrives()
		{
			int logicalDrives = global::Interop.Kernel32.GetLogicalDrives();
			if (logicalDrives == 0)
			{
				throw System.IO.Win32Marshal.GetExceptionForLastWin32Error();
			}
			uint num = (uint)logicalDrives;
			int num2 = 0;
			while (num != 0)
			{
				if ((num & (true ? 1u : 0u)) != 0)
				{
					num2++;
				}
				num >>= 1;
			}
			string[] array = new string[num2];
			Span<char> span = stackalloc char[3] { 'A', ':', '\\' };
			num = (uint)logicalDrives;
			num2 = 0;
			while (num != 0)
			{
				if ((num & (true ? 1u : 0u)) != 0)
				{
					array[num2++] = span.ToString();
				}
				num >>= 1;
				span[0] += '\u0001';
			}
			return array;
		}

		public static string NormalizeDriveName(string driveName)
		{
			string text;
			if (driveName.Length == 1)
			{
				text = driveName + ":\\";
			}
			else
			{
				text = Path.GetPathRoot(driveName);
				if (string.IsNullOrEmpty(text) || text.StartsWith("\\\\", StringComparison.Ordinal))
				{
					throw new ArgumentException(System.SR.Arg_MustBeDriveLetterOrRootDir, "driveName");
				}
			}
			if (text.Length == 2 && text[1] == ':')
			{
				text += "\\";
			}
			char c = driveName[0];
			if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z'))
			{
				throw new ArgumentException(System.SR.Arg_MustBeDriveLetterOrRootDir, "driveName");
			}
			return text;
		}
	}
	internal static class PathHelper
	{
		internal static string Normalize(string path)
		{
			Span<char> initialBuffer = stackalloc char[260];
			System.Text.ValueStringBuilder builder = new System.Text.ValueStringBuilder(initialBuffer);
			GetFullPathName(path.AsSpan(), ref builder);
			string result = ((builder.AsSpan().IndexOf('~') >= 0) ? TryExpandShortFileName(ref builder, path) : (MemoryExtensions.Equals(builder.AsSpan(), path.AsSpan(), StringComparison.Ordinal) ? path : builder.ToString()));
			builder.Dispose();
			return result;
		}

		internal static string Normalize(ref System.Text.ValueStringBuilder path)
		{
			Span<char> initialBuffer = stackalloc char[260];
			System.Text.ValueStringBuilder builder = new System.Text.ValueStringBuilder(initialBuffer);
			GetFullPathName(path.AsSpan(terminate: true), ref builder);
			string result = ((builder.AsSpan().IndexOf('~') >= 0) ? TryExpandShortFileName(ref builder, null) : builder.ToString());
			builder.Dispose();
			return result;
		}

		private static void GetFullPathName(ReadOnlySpan<char> path, ref System.Text.ValueStringBuilder builder)
		{
			uint fullPathNameW;
			while ((fullPathNameW = global::Interop.Kernel32.GetFullPathNameW(ref MemoryMarshal.GetReference(path), (uint)builder.Capacity, ref builder.GetPinnableReference(), IntPtr.Zero)) > builder.Capacity)
			{
				builder.EnsureCapacity(checked((int)fullPathNameW));
			}
			if (fullPathNameW == 0)
			{
				int num = Marshal.GetLastWin32Error();
				if (num == 0)
				{
					num = 161;
				}
				throw System.IO.Win32Marshal.GetExceptionForWin32Error(num, path.ToString());
			}
			builder.Length = (int)fullPathNameW;
		}

		internal static int PrependDevicePathChars(ref System.Text.ValueStringBuilder content, bool isDosUnc, ref System.Text.ValueStringBuilder buffer)
		{
			int length = content.Length;
			length += (isDosUnc ? 6 : 4);
			buffer.EnsureCapacity(length + 1);
			buffer.Length = 0;
			if (isDosUnc)
			{
				buffer.Append("\\\\?\\UNC\\");
				buffer.Append(content.AsSpan(2));
				return 6;
			}
			buffer.Append("\\\\?\\");
			buffer.Append(content.AsSpan());
			return 4;
		}

		internal static string TryExpandShortFileName(ref System.Text.ValueStringBuilder outputBuilder, string originalPath)
		{
			int rootLength = System.IO.PathInternal.GetRootLength(outputBuilder.AsSpan());
			bool flag = System.IO.PathInternal.IsDevice(outputBuilder.AsSpan());
			System.Text.ValueStringBuilder buffer = default(System.Text.ValueStringBuilder);
			bool flag2 = false;
			int num = 0;
			bool flag3 = false;
			if (flag)
			{
				buffer.Append(outputBuilder.AsSpan());
				if (outputBuilder[2] == '.')
				{
					flag3 = true;
					buffer[2] = '?';
				}
			}
			else
			{
				flag2 = !System.IO.PathInternal.IsDevice(outputBuilder.AsSpan()) && outputBuilder.Length > 1 && outputBuilder[0] == '\\' && outputBuilder[1] == '\\';
				num = PrependDevicePathChars(ref outputBuilder, flag2, ref buffer);
			}
			rootLength += num;
			int length = buffer.Length;
			bool flag4 = false;
			int num2 = buffer.Length - 1;
			while (!flag4)
			{
				uint longPathNameW = global::Interop.Kernel32.GetLongPathNameW(ref buffer.GetPinnableReference(terminate: true), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity);
				if (buffer[num2] == '\0')
				{
					buffer[num2] = '\\';
				}
				if (longPathNameW == 0)
				{
					int lastWin32Error = Marshal.GetLastWin32Error();
					if (lastWin32Error != 2 && lastWin32Error != 3)
					{
						break;
					}
					num2--;
					while (num2 > rootLength && buffer[num2] != '\\')
					{
						num2--;
					}
					if (num2 == rootLength)
					{
						break;
					}
					buffer[num2] = '\0';
				}
				else if (longPathNameW > outputBuilder.Capacity)
				{
					outputBuilder.EnsureCapacity(checked((int)longPathNameW));
				}
				else
				{
					flag4 = true;
					outputBuilder.Length = checked((int)longPathNameW);
					if (num2 < length - 1)
					{
						outputBuilder.Append(buffer.AsSpan(num2, buffer.Length - num2));
					}
				}
			}
			ref System.Text.ValueStringBuilder reference = ref flag4 ? ref outputBuilder : ref buffer;
			if (flag3)
			{
				reference[2] = '.';
			}
			if (flag2)
			{
				reference[6] = '\\';
			}
			ReadOnlySpan<char> span = reference.AsSpan(num);
			string result = ((originalPath != null && MemoryExtensions.Equals(span, originalPath.AsSpan(), StringComparison.Ordinal)) ? originalPath : span.ToString());
			buffer.Dispose();
			return result;
		}
	}
	internal static class PathInternal
	{
		internal const char DirectorySeparatorChar = '\\';

		internal const char AltDirectorySeparatorChar = '/';

		internal const char VolumeSeparatorChar = ':';

		internal const char PathSeparator = ';';

		internal const string DirectorySeparatorCharAsString = "\\";

		internal const string NTPathPrefix = "\\??\\";

		internal const string ExtendedPathPrefix = "\\\\?\\";

		internal const string UncPathPrefix = "\\\\";

		internal const string UncExtendedPrefixToInsert = "?\\UNC\\";

		internal const string UncExtendedPathPrefix = "\\\\?\\UNC\\";

		internal const string UncNTPathPrefix = "\\??\\UNC\\";

		internal const string DevicePathPrefix = "\\\\.\\";

		internal const string ParentDirectoryPrefix = "..\\";

		internal const int MaxShortPath = 260;

		internal const int MaxShortDirectoryPath = 248;

		internal const int DevicePrefixLength = 4;

		internal const int UncPrefixLength = 2;

		internal const int UncExtendedPrefixLength = 8;

		internal static StringComparison StringComparison
		{
			get
			{
				if (!IsCaseSensitive)
				{
					return StringComparison.OrdinalIgnoreCase;
				}
				return StringComparison.Ordinal;
			}
		}

		internal static bool IsCaseSensitive => false;

		internal static bool StartsWithDirectorySeparator(ReadOnlySpan<char> path)
		{
			if (path.Length > 0)
			{
				return IsDirectorySeparator(path[0]);
			}
			return false;
		}

		internal static string EnsureTrailingSeparator(string path)
		{
			if (!EndsInDirectorySeparator(path))
			{
				return path + "\\";
			}
			return path;
		}

		internal static bool IsRoot(ReadOnlySpan<char> path)
		{
			return path.Length == GetRootLength(path);
		}

		internal static int GetCommonPathLength(string first, string second, bool ignoreCase)
		{
			int num = EqualStartingCharacterCount(first, second, ignoreCase);
			if (num == 0)
			{
				return num;
			}
			if (num == first.Length && (num == second.Length || IsDirectorySeparator(second[num])))
			{
				return num;
			}
			if (num == second.Length && IsDirectorySeparator(first[num]))
			{
				return num;
			}
			while (num > 0 && !IsDirectorySeparator(first[num - 1]))
			{
				num--;
			}
			return num;
		}

		internal unsafe static int EqualStartingCharacterCount(string first, string second, bool ignoreCase)
		{
			if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second))
			{
				return 0;
			}
			int num = 0;
			fixed (char* ptr = first)
			{
				fixed (char* ptr3 = second)
				{
					char* ptr2 = ptr;
					char* ptr4 = ptr3;
					char* ptr5 = ptr2 + first.Length;
					char* ptr6 = ptr4 + second.Length;
					while (ptr2 != ptr5 && ptr4 != ptr6 && (*ptr2 == *ptr4 || (ignoreCase && char.ToUpperInvariant(*ptr2) == char.ToUpperInvariant(*ptr4))))
					{
						num++;
						ptr2++;
						ptr4++;
					}
				}
			}
			return num;
		}

		internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType)
		{
			int rootLength = GetRootLength(first.AsSpan());
			int rootLength2 = GetRootLength(second.AsSpan());
			if (rootLength == rootLength2)
			{
				return string.Compare(first, 0, second, 0, rootLength, comparisonType) == 0;
			}
			return false;
		}

		internal static string RemoveRelativeSegments(string path, int rootLength)
		{
			Span<char> initialBuffer = stackalloc char[260];
			System.Text.ValueStringBuilder sb = new System.Text.ValueStringBuilder(initialBuffer);
			if (RemoveRelativeSegments(path.AsSpan(), rootLength, ref sb))
			{
				path = sb.ToString();
			}
			sb.Dispose();
			return path;
		}

		internal static bool RemoveRelativeSegments(ReadOnlySpan<char> path, int rootLength, ref System.Text.ValueStringBuilder sb)
		{
			bool flag = false;
			int num = rootLength;
			if (IsDirectorySeparator(path[num - 1]))
			{
				num--;
			}
			if (num > 0)
			{
				sb.Append(path.Slice(0, num));
			}
			for (int i = num; i < path.Length; i++)
			{
				char c = path[i];
				if (IsDirectorySeparator(c) && i + 1 < path.Length)
				{
					if (IsDirectorySeparator(path[i + 1]))
					{
						continue;
					}
					if ((i + 2 == path.Length || IsDirectorySeparator(path[i + 2])) && path[i + 1] == '.')
					{
						i++;
						continue;
					}
					if (i + 2 < path.Length && (i + 3 == path.Length || IsDirectorySeparator(path[i + 3])) && path[i + 1] == '.' && path[i + 2] == '.')
					{
						int num2;
						for (num2 = sb.Length - 1; num2 >= num; num2--)
						{
							if (IsDirectorySeparator(sb[num2]))
							{
								sb.Length = ((i + 3 >= path.Length && num2 == num) ? (num2 + 1) : num2);
								break;
							}
						}
						if (num2 < num)
						{
							sb.Length = num;
						}
						i += 2;
						continue;
					}
				}
				if (c != '\\' && c == '/')
				{
					c = '\\';
					flag = true;
				}
				sb.Append(c);
			}
			if (!flag && sb.Length == path.Length)
			{
				return false;
			}
			if (num != rootLength && sb.Length < rootLength)
			{
				sb.Append(path[rootLength - 1]);
			}
			return true;
		}

		[return: NotNullIfNotNull("path")]
		internal static string TrimEndingDirectorySeparator(string path)
		{
			if (!EndsInDirectorySeparator(path) || IsRoot(path.AsSpan()))
			{
				return path;
			}
			return path.Substring(0, path.Length - 1);
		}

		internal static bool EndsInDirectorySeparator(string path)
		{
			if (!string.IsNullOrEmpty(path))
			{
				return IsDirectorySeparator(path[path.Length - 1]);
			}
			return false;
		}

		internal static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path)
		{
			if (!EndsInDirectorySeparator(path) || IsRoot(path))
			{
				return path;
			}
			return path.Slice(0, path.Length - 1);
		}

		internal static bool EndsInDirectorySeparator(ReadOnlySpan<char> path)
		{
			if (path.Length > 0)
			{
				return IsDirectorySeparator(path[path.Length - 1]);
			}
			return false;
		}

		internal static string GetLinkTargetFullPath(string path, string pathToTarget)
		{
			if (!IsPartiallyQualified(pathToTarget.AsSpan()))
			{
				return pathToTarget;
			}
			return Path.Combine(Path.GetDirectoryName(path), pathToTarget);
		}

		internal static bool IsValidDriveChar(char value)
		{
			if (value < 'A' || value > 'Z')
			{
				if (value >= 'a')
				{
					return value <= 'z';
				}
				return false;
			}
			return true;
		}

		internal static bool EndsWithPeriodOrSpace(string path)
		{
			if (string.IsNullOrEmpty(path))
			{
				return false;
			}
			char c = path[path.Length - 1];
			if (c != ' ')
			{
				return c == '.';
			}
			return true;
		}

		[return: NotNullIfNotNull("path")]
		internal static string EnsureExtendedPrefixIfNeeded(string path)
		{
			if (path != null && (path.Length >= 260 || EndsWithPeriodOrSpace(path)))
			{
				return EnsureExtendedPrefix(path);
			}
			return path;
		}

		internal static string EnsureExtendedPrefix(string path)
		{
			if (IsPartiallyQualified(path.AsSpan()) || IsDevice(path.AsSpan()))
			{
				return path;
			}
			if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase))
			{
				return path.Insert(2, "?\\UNC\\");
			}
			return "\\\\?\\" + path;
		}

		internal static bool IsDevice(ReadOnlySpan<char> path)
		{
			if (!IsExtended(path))
			{
				if (path.Length >= 4 && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]) && (path[2] == '.' || path[2] == '?'))
				{
					return IsDirectorySeparator(path[3]);
				}
				return false;
			}
			return true;
		}

		internal static bool IsDeviceUNC(ReadOnlySpan<char> path)
		{
			if (path.Length >= 8 && IsDevice(path) && IsDirectorySeparator(path[7]) && path[4] == 'U' && path[5] == 'N')
			{
				return path[6] == 'C';
			}
			return false;
		}

		internal static bool IsExtended(ReadOnlySpan<char> path)
		{
			if (path.Length >= 4 && path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && path[2] == '?')
			{
				return path[3] == '\\';
			}
			return false;
		}

		internal static int GetRootLength(ReadOnlySpan<char> path)
		{
			int length = path.Length;
			int i = 0;
			bool flag = IsDevice(path);
			bool flag2 = flag && IsDeviceUNC(path);
			if ((!flag || flag2) && length > 0 && IsDirectorySeparator(path[0]))
			{
				if (flag2 || (length > 1 && IsDirectorySeparator(path[1])))
				{
					i = (flag2 ? 8 : 2);
					int num = 2;
					for (; i < length; i++)
					{
						if (IsDirectorySeparator(path[i]) && --num <= 0)
						{
							break;
						}
					}
				}
				else
				{
					i = 1;
				}
			}
			else if (flag)
			{
				for (i = 4; i < length && !IsDirectorySeparator(path[i]); i++)
				{
				}
				if (i < length && i > 4 && IsDirectorySeparator(path[i]))
				{
					i++;
				}
			}
			else if (length >= 2 && path[1] == ':' && IsValidDriveChar(path[0]))
			{
				i = 2;
				if (length > 2 && IsDirectorySeparator(path[2]))
				{
					i++;
				}
			}
			return i;
		}

		internal static bool IsPartiallyQualified(ReadOnlySpan<char> path)
		{
			if (path.Length < 2)
			{
				return true;
			}
			if (IsDirectorySeparator(path[0]))
			{
				if (path[1] != '?')
				{
					return !IsDirectorySeparator(path[1]);
				}
				return false;
			}
			if (path.Length >= 3 && path[1] == ':' && IsDirectorySeparator(path[2]))
			{
				return !IsValidDriveChar(path[0]);
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool IsDirectorySeparator(char c)
		{
			if (c != '\\')
			{
				return c == '/';
			}
			return true;
		}

		[return: NotNullIfNotNull("path")]
		internal static string NormalizeDirectorySeparators(string path)
		{
			if (string.IsNullOrEmpty(path))
			{
				return path;
			}
			bool flag = true;
			for (int i = 0; i < path.Length; i++)
			{
				char c = path[i];
				if (IsDirectorySeparator(c) && (c != '\\' || (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))))
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				return path;
			}
			Span<char> initialBuffer = stackalloc char[260];
			System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer);
			int num = 0;
			if (IsDirectorySeparator(path[num]))
			{
				num++;
				valueStringBuilder.Append('\\');
			}
			for (int j = num; j < path.Length; j++)
			{
				char c = path[j];
				if (IsDirectorySeparator(c))
				{
					if (j + 1 < path.Length && IsDirectorySeparator(path[j + 1]))
					{
						continue;
					}
					c = '\\';
				}
				valueStringBuilder.Append(c);
			}
			return valueStringBuilder.ToString();
		}

		internal static bool IsEffectivelyEmpty(ReadOnlySpan<char> path)
		{
			if (path.IsEmpty)
			{
				return true;
			}
			ReadOnlySpan<char> readOnlySpan = path;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				char c = readOnlySpan[i];
				if (c != ' ')
				{
					return false;
				}
			}
			return true;
		}
	}
	internal static class Win32Marshal
	{
		internal static Exception GetExceptionForLastWin32Error(string path = "")
		{
			return GetExceptionForWin32Error(Marshal.GetLastWin32Error(), path);
		}

		internal static Exception GetExceptionForWin32Error(int errorCode, string path = "")
		{
			switch (errorCode)
			{
			case 2:
				return new FileNotFoundException(string.IsNullOrEmpty(path) ? System.SR.IO_FileNotFound : System.SR.Format(System.SR.IO_FileNotFound_FileName, path), path);
			case 3:
				return new DirectoryNotFoundException(string.IsNullOrEmpty(path) ? System.SR.IO_PathNotFound_NoPathName : System.SR.Format(System.SR.IO_PathNotFound_Path, path));
			case 5:
				return new UnauthorizedAccessException(string.IsNullOrEmpty(path) ? System.SR.UnauthorizedAccess_IODenied_NoPathName : System.SR.Format(System.SR.UnauthorizedAccess_IODenied_Path, path));
			case 183:
				if (!string.IsNullOrEmpty(path))
				{
					return new IOException(System.SR.Format(System.SR.IO_AlreadyExists_Name, path), MakeHRFromErrorCode(errorCode));
				}
				break;
			case 206:
				return new PathTooLongException(string.IsNullOrEmpty(path) ? System.SR.IO_PathTooLong : System.SR.Format(System.SR.IO_PathTooLong_Path, path));
			case 32:
				return new IOException(string.IsNullOrEmpty(path) ? System.SR.IO_SharingViolation_NoFileName : System.SR.Format(System.SR.IO_SharingViolation_File, path), MakeHRFromErrorCode(errorCode));
			case 80:
				if (!string.IsNullOrEmpty(path))
				{
					return new IOException(System.SR.Format(System.SR.IO_FileExists_Name, path), MakeHRFromErrorCode(errorCode));
				}
				break;
			case 995:
				return new OperationCanceledException();
			}
			return new IOException(string.IsNullOrEmpty(path) ? GetMessage(errorCode) : (GetMessage(errorCode) + " : '" + path + "'"), MakeHRFromErrorCode(errorCode));
		}

		internal static int MakeHRFromErrorCode(int errorCode)
		{
			if ((0xFFFF0000u & errorCode) != 0L)
			{
				return errorCode;
			}
			return -2147024896 | errorCode;
		}

		internal static int TryMakeWin32ErrorCodeFromHR(int hr)
		{
			if ((0xFFFF0000u & hr) == 2147942400u)
			{
				hr &= 0xFFFF;
			}
			return hr;
		}

		internal static string GetMessage(int errorCode)
		{
			return global::Interop.Kernel32.GetMessage(errorCode);
		}
	}
}
namespace Microsoft.Win32.SafeHandles
{
	internal sealed class SafeFindHandle : SafeHandle
	{
		public override bool IsInvalid
		{
			get
			{
				if (!(handle == IntPtr.Zero))
				{
					return handle == new IntPtr(-1);
				}
				return true;
			}
		}

		public SafeFindHandle()
			: base(IntPtr.Zero, ownsHandle: true)
		{
		}

		protected override bool ReleaseHandle()
		{
			return global::Interop.Kernel32.FindClose(handle);
		}
	}
}
namespace Microsoft.IO
{
	public static class Directory
	{
		public static DirectoryInfo? GetParent(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (path.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_PathEmpty, "path");
			}
			string fullPath = Path.GetFullPath(path);
			string directoryName = Path.GetDirectoryName(fullPath);
			if (directoryName == null)
			{
				return null;
			}
			return new DirectoryInfo(directoryName);
		}

		public static DirectoryInfo CreateDirectory(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (path.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_PathEmpty, "path");
			}
			string fullPath = Path.GetFullPath(path);
			FileSystem.CreateDirectory(fullPath);
			return new DirectoryInfo(path, fullPath, null, isNormalized: true);
		}

		public static bool Exists([NotNullWhen(true)] string? path)
		{
			try
			{
				if (path == null)
				{
					return false;
				}
				if (path.Length == 0)
				{
					return false;
				}
				string fullPath = Path.GetFullPath(path);
				return FileSystem.DirectoryExists(fullPath);
			}
			catch (ArgumentException)
			{
			}
			catch (IOException)
			{
			}
			catch (UnauthorizedAccessException)
			{
			}
			return false;
		}

		public static void SetCreationTime(string path, DateTime creationTime)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.SetCreationTime(fullPath, creationTime, asDirectory: true);
		}

		public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true);
		}

		public static DateTime GetCreationTime(string path)
		{
			return File.GetCreationTime(path);
		}

		public static DateTime GetCreationTimeUtc(string path)
		{
			return File.GetCreationTimeUtc(path);
		}

		public static void SetLastWriteTime(string path, DateTime lastWriteTime)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true);
		}

		public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true);
		}

		public static DateTime GetLastWriteTime(string path)
		{
			return File.GetLastWriteTime(path);
		}

		public static DateTime GetLastWriteTimeUtc(string path)
		{
			return File.GetLastWriteTimeUtc(path);
		}

		public static void SetLastAccessTime(string path, DateTime lastAccessTime)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true);
		}

		public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true);
		}

		public static DateTime GetLastAccessTime(string path)
		{
			return File.GetLastAccessTime(path);
		}

		public static DateTime GetLastAccessTimeUtc(string path)
		{
			return File.GetLastAccessTimeUtc(path);
		}

		public static string[] GetFiles(string path)
		{
			return GetFiles(path, "*", EnumerationOptions.Compatible);
		}

		public static string[] GetFiles(string path, string searchPattern)
		{
			return GetFiles(path, searchPattern, EnumerationOptions.Compatible);
		}

		public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
		{
			return GetFiles(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public static string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions)
		{
			return new List<string>(InternalEnumeratePaths(path, searchPattern, SearchTarget.Files, enumerationOptions)).ToArray();
		}

		public static string[] GetDirectories(string path)
		{
			return GetDirectories(path, "*", EnumerationOptions.Compatible);
		}

		public static string[] GetDirectories(string path, string searchPattern)
		{
			return GetDirectories(path, searchPattern, EnumerationOptions.Compatible);
		}

		public static string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)
		{
			return GetDirectories(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public static string[] GetDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions)
		{
			return new List<string>(InternalEnumeratePaths(path, searchPattern, SearchTarget.Directories, enumerationOptions)).ToArray();
		}

		public static string[] GetFileSystemEntries(string path)
		{
			return GetFileSystemEntries(path, "*", EnumerationOptions.Compatible);
		}

		public static string[] GetFileSystemEntries(string path, string searchPattern)
		{
			return GetFileSystemEntries(path, searchPattern, EnumerationOptions.Compatible);
		}

		public static string[] GetFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
		{
			return GetFileSystemEntries(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public static string[] GetFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
		{
			return new List<string>(InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions)).ToArray();
		}

		internal static IEnumerable<string> InternalEnumeratePaths(string path, string searchPattern, SearchTarget searchTarget, EnumerationOptions options)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (searchPattern == null)
			{
				throw new ArgumentNullException("searchPattern");
			}
			FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType);
			return searchTarget switch
			{
				SearchTarget.Files => FileSystemEnumerableFactory.UserFiles(path, searchPattern, options), 
				SearchTarget.Directories => FileSystemEnumerableFactory.UserDirectories(path, searchPattern, options), 
				SearchTarget.Both => FileSystemEnumerableFactory.UserEntries(path, searchPattern, options), 
				_ => throw new ArgumentOutOfRangeException("searchTarget"), 
			};
		}

		public static IEnumerable<string> EnumerateDirectories(string path)
		{
			return EnumerateDirectories(path, "*", EnumerationOptions.Compatible);
		}

		public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern)
		{
			return EnumerateDirectories(path, searchPattern, EnumerationOptions.Compatible);
		}

		public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption)
		{
			return EnumerateDirectories(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, EnumerationOptions enumerationOptions)
		{
			return InternalEnumeratePaths(path, searchPattern, SearchTarget.Directories, enumerationOptions);
		}

		public static IEnumerable<string> EnumerateFiles(string path)
		{
			return EnumerateFiles(path, "*", EnumerationOptions.Compatible);
		}

		public static IEnumerable<string> EnumerateFiles(string path, string searchPattern)
		{
			return EnumerateFiles(path, searchPattern, EnumerationOptions.Compatible);
		}

		public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)
		{
			return EnumerateFiles(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, EnumerationOptions enumerationOptions)
		{
			return InternalEnumeratePaths(path, searchPattern, SearchTarget.Files, enumerationOptions);
		}

		public static IEnumerable<string> EnumerateFileSystemEntries(string path)
		{
			return EnumerateFileSystemEntries(path, "*", EnumerationOptions.Compatible);
		}

		public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern)
		{
			return EnumerateFileSystemEntries(path, searchPattern, EnumerationOptions.Compatible);
		}

		public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
		{
			return EnumerateFileSystemEntries(path, searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, EnumerationOptions enumerationOptions)
		{
			return InternalEnumeratePaths(path, searchPattern, SearchTarget.Both, enumerationOptions);
		}

		public static string GetDirectoryRoot(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			string fullPath = Path.GetFullPath(path);
			return Path.GetPathRoot(fullPath);
		}

		public static string GetCurrentDirectory()
		{
			return Environment.CurrentDirectory;
		}

		public static void SetCurrentDirectory(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (path.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_PathEmpty, "path");
			}
			Environment.CurrentDirectory = Path.GetFullPath(path);
		}

		public static void Move(string sourceDirName, string destDirName)
		{
			if (sourceDirName == null)
			{
				throw new ArgumentNullException("sourceDirName");
			}
			if (sourceDirName.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_EmptyFileName, "sourceDirName");
			}
			if (destDirName == null)
			{
				throw new ArgumentNullException("destDirName");
			}
			if (destDirName.Length == 0)
			{
				throw new ArgumentException(System.SR.Argument_EmptyFileName, "destDirName");
			}
			string fullPath = Path.GetFullPath(sourceDirName);
			string text = System.IO.PathInternal.EnsureTrailingSeparator(fullPath);
			string fullPath2 = Path.GetFullPath(destDirName);
			string text2 = System.IO.PathInternal.EnsureTrailingSeparator(fullPath2);
			ReadOnlySpan<char> fileName = Path.GetFileName(fullPath.AsSpan());
			ReadOnlySpan<char> fileName2 = Path.GetFileName(fullPath2.AsSpan());
			StringComparison stringComparison = System.IO.PathInternal.StringComparison;
			bool flag = !fileName.SequenceEqual(fileName2) && MemoryExtensions.Equals(fileName, fileName2, StringComparison.OrdinalIgnoreCase) && MemoryExtensions.Equals(fileName2, fileName, stringComparison);
			if (!flag && string.Equals(text, text2, stringComparison))
			{
				throw new IOException(System.SR.IO_SourceDestMustBeDifferent);
			}
			ReadOnlySpan<char> pathRoot = Path.GetPathRoot(text.AsSpan());
			ReadOnlySpan<char> pathRoot2 = Path.GetPathRoot(text2.AsSpan());
			if (!MemoryExtensions.Equals(pathRoot, pathRoot2, StringComparison.OrdinalIgnoreCase))
			{
				throw new IOException(System.SR.IO_SourceDestMustHaveSameRoot);
			}
			if (!FileSystem.DirectoryExists(fullPath) && !FileSystem.FileExists(fullPath))
			{
				throw new DirectoryNotFoundException(System.SR.Format(System.SR.IO_PathNotFound_Path, fullPath));
			}
			if (!flag && FileSystem.DirectoryExists(fullPath2))
			{
				throw new IOException(System.SR.Format(System.SR.IO_AlreadyExists_Name, fullPath2));
			}
			if (!flag && Exists(fullPath2))
			{
				throw new IOException(System.SR.Format(System.SR.IO_AlreadyExists_Name, fullPath2));
			}
			FileSystem.MoveDirectory(fullPath, fullPath2);
		}

		public static void Delete(string path)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.RemoveDirectory(fullPath, recursive: false);
		}

		public static void Delete(string path, bool recursive)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.RemoveDirectory(fullPath, recursive);
		}

		public static string[] GetLogicalDrives()
		{
			return FileSystem.GetLogicalDrives();
		}

		public static FileSystemInfo CreateSymbolicLink(string path, string pathToTarget)
		{
			string fullPath = Path.GetFullPath(path);
			FileSystem.VerifyValidPath(pathToTarget, "pathToTarget");
			FileSystem.CreateSymbolicLink(path, pathToTarget, isDirectory: true);
			return new DirectoryInfo(path, fullPath, null, isNormalized: true);
		}

		public static FileSystemInfo? ResolveLinkTarget(string linkPath, bool returnFinalTarget)
		{
			FileSystem.VerifyValidPath(linkPath, "linkPath");
			return FileSystem.ResolveLinkTarget(linkPath, returnFinalTarget, isDirectory: true);
		}
	}
	public sealed class DirectoryInfo : FileSystemInfo
	{
		private bool _isNormalized;

		public DirectoryInfo? Parent
		{
			get
			{
				string directoryName = Path.GetDirectoryName(System.IO.PathInternal.IsRoot(FullPath.AsSpan()) ? FullPath : Path.TrimEndingDirectorySeparator(FullPath));
				if (directoryName == null)
				{
					return null;
				}
				return new DirectoryInfo(directoryName, null, null, isNormalized: true);
			}
		}

		public DirectoryInfo Root => new DirectoryInfo(Path.GetPathRoot(FullPath));

		public DirectoryInfo(string path)
		{
			Init(path, Path.GetFullPath(path), null, isNormalized: true);
		}

		internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
		{
			Init(originalPath, fullPath, fileName, isNormalized);
		}

		private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
		{
			OriginalPath = originalPath ?? throw new ArgumentNullException("originalPath");
			fullPath = fullPath ?? originalPath;
			fullPath = (isNormalized ? fullPath : Path.GetFullPath(fullPath));
			_name = fileName ?? (System.IO.PathInternal.IsRoot(fullPath.AsSpan()) ? fullPath.AsSpan() : Path.GetFileName(Path.TrimEndingDirectorySeparator(fullPath.AsSpan()))).ToString();
			FullPath = fullPath;
			_isNormalized = isNormalized;
		}

		public DirectoryInfo CreateSubdirectory(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (System.IO.PathInternal.IsEffectivelyEmpty(path.AsSpan()))
			{
				throw new ArgumentException(System.SR.Argument_PathEmpty, "path");
			}
			if (Path.IsPathRooted(path))
			{
				throw new ArgumentException(System.SR.Arg_Path2IsRooted, "path");
			}
			string fullPath = Path.GetFullPath(Path.Combine(FullPath, path));
			ReadOnlySpan<char> span = Path.TrimEndingDirectorySeparator(fullPath.AsSpan());
			ReadOnlySpan<char> value = Path.TrimEndingDirectorySeparator(FullPath.AsSpan());
			if (span.StartsWith(value, System.IO.PathInternal.StringComparison) && (span.Length == value.Length || System.IO.PathInternal.IsDirectorySeparator(fullPath[value.Length])))
			{
				FileSystem.CreateDirectory(fullPath);
				return new DirectoryInfo(fullPath);
			}
			throw new ArgumentException(System.SR.Format(System.SR.Argument_InvalidSubPath, path, FullPath), "path");
		}

		public void Create()
		{
			FileSystem.CreateDirectory(FullPath);
			Invalidate();
		}

		public FileInfo[] GetFiles()
		{
			return GetFiles("*", EnumerationOptions.Compatible);
		}

		public FileInfo[] GetFiles(string searchPattern)
		{
			return GetFiles(searchPattern, EnumerationOptions.Compatible);
		}

		public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption)
		{
			return GetFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public FileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions)
		{
			return new List<FileInfo>((IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions)).ToArray();
		}

		public FileSystemInfo[] GetFileSystemInfos()
		{
			return GetFileSystemInfos("*", EnumerationOptions.Compatible);
		}

		public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
		{
			return GetFileSystemInfos(searchPattern, EnumerationOptions.Compatible);
		}

		public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption)
		{
			return GetFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public FileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions)
		{
			return new List<FileSystemInfo>(InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions)).ToArray();
		}

		public DirectoryInfo[] GetDirectories()
		{
			return GetDirectories("*", EnumerationOptions.Compatible);
		}

		public DirectoryInfo[] GetDirectories(string searchPattern)
		{
			return GetDirectories(searchPattern, EnumerationOptions.Compatible);
		}

		public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
		{
			return GetDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption));
		}

		public DirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions)
		{
			return new List<DirectoryInfo>((IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath

folder/Microsoft.NET.StringTools.dll

Decompiled 11 months ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.NET.StringTools.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010015c01ae1f50e8cc09ba9eac9147cf8fd9fce2cfe9f8dce4f7301c4132ca9fb50ce8cbf1df4dc18dd4d210e4345c744ecb3365ed327efdbc52603faa5e21daa11234c8c4a73e51f03bf192544581ebe107adee3a34928e39d04e524a9ce729d5090bfd7dad9d10c722c0def9ccc08ff0a03790e48bcd1f9b6c476063e1966a1c4")]
[assembly: InternalsVisibleTo("Microsoft.NET.StringTools.net35.UnitTests, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("Microsoft.NET.StringTools.Benchmark, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Microsoft.NET.StringTools.dll")]
[assembly: AssemblyFileVersion("17.13.9.7704")]
[assembly: AssemblyInformationalVersion("17.13.9+e0f243f1e205c45b3b04097facd9948a881f9047")]
[assembly: AssemblyProduct("Microsoft® Build Tools®")]
[assembly: AssemblyTitle("Microsoft.NET.StringTools.dll")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/msbuild")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace Microsoft.NET.StringTools
{
	public static class FowlerNollVo1aHash
	{
		private const uint fnvPrimeA32Bit = 16777619u;

		private const uint fnvOffsetBasisA32Bit = 2166136261u;

		private const long fnvPrimeA64Bit = 1099511628211L;

		private const long fnvOffsetBasisA64Bit = -3750763034362895579L;

		public static int ComputeHash32(string text)
		{
			uint num = 2166136261u;
			foreach (char c in text)
			{
				byte b = (byte)c;
				num ^= b;
				num *= 16777619;
				b = (byte)((int)c >> 8);
				num ^= b;
				num *= 16777619;
			}
			return (int)num;
		}

		public static int ComputeHash32Fast(string text)
		{
			uint num = 2166136261u;
			foreach (char c in text)
			{
				num = (num ^ c) * 16777619;
			}
			return (int)num;
		}

		public static long ComputeHash64Fast(string text)
		{
			long num = -3750763034362895579L;
			foreach (char c in text)
			{
				num = (num ^ c) * 1099511628211L;
			}
			return num;
		}

		public static long ComputeHash64(string text)
		{
			long num = -3750763034362895579L;
			foreach (char c in text)
			{
				byte b = (byte)c;
				num ^= b;
				num *= 1099511628211L;
				b = (byte)((int)c >> 8);
				num ^= b;
				num *= 1099511628211L;
			}
			return num;
		}

		public static long Combine64(long left, long right)
		{
			return (left ^ right) * 1099511628211L;
		}
	}
	internal ref struct InternableString
	{
		public ref struct Enumerator
		{
			private InternableString _string;

			private int _spanIndex;

			private int _charIndex;

			public readonly ref readonly char Current
			{
				get
				{
					if (_spanIndex == -1)
					{
						return ref _string._inlineSpan[_charIndex];
					}
					return ref _string._spans[_spanIndex].Span[_charIndex];
				}
			}

			internal Enumerator(scoped ref InternableString str)
			{
				_string = str;
				_spanIndex = -1;
				_charIndex = -1;
			}

			public bool MoveNext()
			{
				int num = _charIndex + 1;
				if (_spanIndex == -1)
				{
					if (num < _string._inlineSpan.Length)
					{
						_charIndex = num;
						return true;
					}
					_spanIndex = 0;
					num = 0;
				}
				if (_string._spans != null)
				{
					while (_spanIndex < _string._spans.Count)
					{
						if (num < _string._spans[_spanIndex].Length)
						{
							_charIndex = num;
							return true;
						}
						_spanIndex++;
						num = 0;
					}
				}
				return false;
			}
		}

		private readonly ReadOnlySpan<char> _inlineSpan;

		private List<ReadOnlyMemory<char>>? _spans;

		public int Length { get; private set; }

		internal InternableString(ReadOnlySpan<char> span)
		{
			_inlineSpan = span;
			_spans = null;
			Length = span.Length;
		}

		internal InternableString(string str)
		{
			if (str == null)
			{
				throw new ArgumentNullException("str");
			}
			_inlineSpan = str.AsSpan();
			_spans = null;
			Length = str.Length;
		}

		internal InternableString(SpanBasedStringBuilder stringBuilder)
		{
			_inlineSpan = default(ReadOnlySpan<char>);
			_spans = stringBuilder.Spans;
			Length = stringBuilder.Length;
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(ref this);
		}

		public readonly bool Equals(string other)
		{
			if (other.Length != Length)
			{
				return false;
			}
			if (_inlineSpan.SequenceCompareTo(other.AsSpan(0, _inlineSpan.Length)) != 0)
			{
				return false;
			}
			if (_spans != null)
			{
				int num = _inlineSpan.Length;
				foreach (ReadOnlyMemory<char> span in _spans)
				{
					if (span.Span.SequenceCompareTo(other.AsSpan(num, span.Length)) != 0)
					{
						return false;
					}
					num += span.Length;
				}
			}
			return true;
		}

		public unsafe readonly string ExpensiveConvertToString()
		{
			if (Length == 0)
			{
				return string.Empty;
			}
			if (_inlineSpan.Length == Length)
			{
				return _inlineSpan.ToString();
			}
			if (_inlineSpan.IsEmpty && _spans?[0].Length == Length)
			{
				return _spans[0].ToString();
			}
			string text = new string('\0', Length);
			fixed (char* ptr = text)
			{
				char* ptr2 = ptr;
				if (!_inlineSpan.IsEmpty)
				{
					fixed (char* ptr3 = _inlineSpan)
					{
						System.Runtime.CompilerServices.Unsafe.CopyBlockUnaligned((void*)ptr2, (void*)ptr3, (uint)(2 * _inlineSpan.Length));
					}
					ptr2 += _inlineSpan.Length;
				}
				if (_spans != null)
				{
					foreach (ReadOnlyMemory<char> span in _spans)
					{
						if (span.IsEmpty)
						{
							continue;
						}
						fixed (char* ptr4 = span.Span)
						{
							System.Runtime.CompilerServices.Unsafe.CopyBlockUnaligned((void*)ptr2, (void*)ptr4, (uint)(2 * span.Length));
						}
						ptr2 += span.Length;
					}
				}
				if (ptr2 != ptr + Length)
				{
					throw new InvalidOperationException($"Length of {Length} does not match the sum of span lengths of {ptr2 - ptr}.");
				}
			}
			return text;
		}

		public readonly bool ReferenceEquals(string str)
		{
			if (_inlineSpan.Length == Length)
			{
				return _inlineSpan == str.AsSpan();
			}
			if (_inlineSpan.IsEmpty)
			{
				List<ReadOnlyMemory<char>>? spans = _spans;
				if (spans != null && spans.Count == 1 && _spans[0].Length == Length)
				{
					return _spans[0].Span == str.AsSpan();
				}
			}
			return false;
		}

		public override string ToString()
		{
			return WeakStringCacheInterner.Instance.InternableToString(ref this);
		}

		public unsafe override readonly int GetHashCode()
		{
			uint hash = 352654597u;
			bool hashedOddNumberOfCharacters = false;
			fixed (char* charPtr = _inlineSpan)
			{
				hash = GetHashCodeHelper(charPtr, _inlineSpan.Length, hash, ref hashedOddNumberOfCharacters);
			}
			if (_spans != null)
			{
				foreach (ReadOnlyMemory<char> span in _spans)
				{
					fixed (char* charPtr = span.Span)
					{
						hash = GetHashCodeHelper(charPtr, span.Length, hash, ref hashedOddNumberOfCharacters);
					}
				}
			}
			return (int)hash;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static uint GetHashCodeHelper(char* charPtr, int length, uint hash, ref bool hashedOddNumberOfCharacters)
		{
			if (hashedOddNumberOfCharacters && length > 0)
			{
				hash ^= (BitConverter.IsLittleEndian ? ((uint)(*charPtr) << 16) : (*charPtr));
				length--;
				charPtr++;
				hashedOddNumberOfCharacters = false;
			}
			uint* ptr = (uint*)charPtr;
			while (length >= 2)
			{
				length -= 2;
				hash = (RotateLeft(hash, 5) + hash) ^ *ptr;
				ptr++;
			}
			if (length > 0)
			{
				hash = (RotateLeft(hash, 5) + hash) ^ (uint)(BitConverter.IsLittleEndian ? (*(ushort*)ptr) : (*(ushort*)ptr << 16));
				hashedOddNumberOfCharacters = true;
			}
			return hash;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static uint RotateLeft(uint value, int offset)
		{
			return (value << offset) | (value >> 32 - offset);
		}
	}
	public class SpanBasedStringBuilder : IDisposable
	{
		public struct Enumerator
		{
			private readonly List<ReadOnlyMemory<char>> _spans;

			private int _spanIndex;

			private int _charIndex;

			public readonly char Current => _spans[_spanIndex].Span[_charIndex];

			internal Enumerator(List<ReadOnlyMemory<char>> spans)
			{
				_spans = spans;
				_spanIndex = 0;
				_charIndex = -1;
			}

			public bool MoveNext()
			{
				int num = _charIndex + 1;
				while (_spanIndex < _spans.Count)
				{
					if (num < _spans[_spanIndex].Length)
					{
						_charIndex = num;
						return true;
					}
					_spanIndex++;
					num = 0;
				}
				return false;
			}
		}

		private readonly List<ReadOnlyMemory<char>> _spans;

		internal List<ReadOnlyMemory<char>> Spans => _spans;

		public int Length { get; private set; }

		public int Capacity => _spans.Capacity;

		public SpanBasedStringBuilder(string str)
			: this()
		{
			if (str == null)
			{
				throw new ArgumentNullException("str");
			}
			Append(str);
		}

		public SpanBasedStringBuilder(int capacity = 4)
		{
			_spans = new List<ReadOnlyMemory<char>>(capacity);
			Length = 0;
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_spans);
		}

		public override string ToString()
		{
			return new InternableString(this).ToString();
		}

		public void Dispose()
		{
			Strings.ReturnSpanBasedStringBuilder(this);
		}

		public void Append(string? value)
		{
			if (!string.IsNullOrEmpty(value))
			{
				_spans.Add(value.AsMemory());
				Length += value.Length;
			}
		}

		public void Append(string value, int startIndex, int count)
		{
			if (value != null)
			{
				if (count > 0)
				{
					_spans.Add(value.AsMemory(startIndex, count));
					Length += count;
				}
			}
			else if (startIndex != 0 || count != 0)
			{
				throw new ArgumentNullException("value");
			}
		}

		public void Append(ReadOnlyMemory<char> span)
		{
			if (!span.IsEmpty)
			{
				_spans.Add(span);
				Length += span.Length;
			}
		}

		public void TrimStart()
		{
			for (int i = 0; i < _spans.Count; i++)
			{
				ReadOnlyMemory<char> readOnlyMemory = _spans[i];
				ReadOnlySpan<char> span = readOnlyMemory.Span;
				int j;
				for (j = 0; j < span.Length && char.IsWhiteSpace(span[j]); j++)
				{
				}
				if (j > 0)
				{
					List<ReadOnlyMemory<char>> spans = _spans;
					int index = i;
					readOnlyMemory = _spans[i];
					spans[index] = readOnlyMemory.Slice(j);
					Length -= j;
				}
				readOnlyMemory = _spans[i];
				if (!readOnlyMemory.IsEmpty)
				{
					break;
				}
			}
		}

		public void TrimEnd()
		{
			for (int num = _spans.Count - 1; num >= 0; num--)
			{
				ReadOnlyMemory<char> readOnlyMemory = _spans[num];
				ReadOnlySpan<char> span = readOnlyMemory.Span;
				int num2 = span.Length - 1;
				while (num2 >= 0 && char.IsWhiteSpace(span[num2]))
				{
					num2--;
				}
				if (num2 + 1 < span.Length)
				{
					List<ReadOnlyMemory<char>> spans = _spans;
					int index = num;
					readOnlyMemory = _spans[num];
					spans[index] = readOnlyMemory.Slice(0, num2 + 1);
					Length -= span.Length - (num2 + 1);
				}
				readOnlyMemory = _spans[num];
				if (!readOnlyMemory.IsEmpty)
				{
					break;
				}
			}
		}

		public void Trim()
		{
			TrimStart();
			TrimEnd();
		}

		public void Clear()
		{
			_spans.Clear();
			Length = 0;
		}
	}
	public static class Strings
	{
		[ThreadStatic]
		private static SpanBasedStringBuilder? _spanBasedStringBuilder;

		public static string WeakIntern(string str)
		{
			InternableString candidate = new InternableString(str);
			return WeakStringCacheInterner.Instance.InternableToString(ref candidate);
		}

		public static string WeakIntern(ReadOnlySpan<char> str)
		{
			InternableString candidate = new InternableString(str);
			return WeakStringCacheInterner.Instance.InternableToString(ref candidate);
		}

		public static SpanBasedStringBuilder GetSpanBasedStringBuilder()
		{
			SpanBasedStringBuilder spanBasedStringBuilder = _spanBasedStringBuilder;
			if (spanBasedStringBuilder == null)
			{
				return new SpanBasedStringBuilder();
			}
			_spanBasedStringBuilder = null;
			return spanBasedStringBuilder;
		}

		public static void EnableDiagnostics()
		{
			WeakStringCacheInterner.Instance.EnableStatistics();
		}

		public static string CreateDiagnosticReport()
		{
			return WeakStringCacheInterner.Instance.FormatStatistics();
		}

		internal static void ReturnSpanBasedStringBuilder(SpanBasedStringBuilder stringBuilder)
		{
			stringBuilder.Clear();
			_spanBasedStringBuilder = stringBuilder;
		}
	}
	internal sealed class WeakStringCache : IDisposable
	{
		public struct DebugInfo
		{
			public int LiveStringCount;

			public int CollectedStringCount;
		}

		private class StringWeakHandle
		{
			public GCHandle WeakHandle;

			public bool IsUsed => WeakHandle.Target != null;

			public string? GetString(ref InternableString internable)
			{
				if (WeakHandle.IsAllocated && WeakHandle.Target is string text && internable.Equals(text))
				{
					return text;
				}
				return null;
			}

			public void SetString(string str)
			{
				if (!WeakHandle.IsAllocated)
				{
					WeakHandle = GCHandle.Alloc(str, GCHandleType.Weak);
				}
				else
				{
					WeakHandle.Target = str;
				}
			}

			public void Free()
			{
				WeakHandle.Free();
			}
		}

		private readonly ConcurrentDictionary<int, StringWeakHandle> _stringsByHashCode;

		private const int _initialCapacity = 503;

		private int _scavengeThreshold = 503;

		public WeakStringCache()
		{
			_stringsByHashCode = new ConcurrentDictionary<int, StringWeakHandle>(Environment.ProcessorCount, 503);
		}

		public string GetOrCreateEntry(ref InternableString internable, out bool cacheHit)
		{
			int hashCode = internable.GetHashCode();
			string @string;
			if (_stringsByHashCode.TryGetValue(hashCode, out StringWeakHandle value))
			{
				lock (value)
				{
					@string = value.GetString(ref internable);
					if (@string != null)
					{
						cacheHit = true;
						return @string;
					}
					@string = internable.ExpensiveConvertToString();
					value.SetString(@string);
					cacheHit = false;
					return @string;
				}
			}
			@string = internable.ExpensiveConvertToString();
			value = new StringWeakHandle();
			value.SetString(@string);
			_stringsByHashCode.TryAdd(hashCode, value);
			int scavengeThreshold = _scavengeThreshold;
			if (_stringsByHashCode.Count >= scavengeThreshold && Interlocked.CompareExchange(ref _scavengeThreshold, int.MaxValue, scavengeThreshold) == scavengeThreshold)
			{
				try
				{
					Scavenge();
				}
				finally
				{
					_scavengeThreshold = _stringsByHashCode.Count * 2;
				}
			}
			cacheHit = false;
			return @string;
		}

		public void Scavenge()
		{
			foreach (KeyValuePair<int, StringWeakHandle> item in _stringsByHashCode)
			{
				if (item.Value.IsUsed || !_stringsByHashCode.TryRemove(item.Key, out StringWeakHandle value))
				{
					continue;
				}
				lock (value)
				{
					if (!value.IsUsed || !_stringsByHashCode.TryAdd(item.Key, value))
					{
						value.Free();
					}
				}
			}
		}

		public DebugInfo GetDebugInfo()
		{
			return GetDebugInfoImpl();
		}

		private void DisposeImpl()
		{
			foreach (KeyValuePair<int, StringWeakHandle> item in _stringsByHashCode)
			{
				item.Value.Free();
			}
			_stringsByHashCode.Clear();
		}

		public void Dispose()
		{
			DisposeImpl();
			GC.SuppressFinalize(this);
		}

		~WeakStringCache()
		{
			DisposeImpl();
		}

		private DebugInfo GetDebugInfoImpl()
		{
			DebugInfo result = default(DebugInfo);
			foreach (KeyValuePair<int, StringWeakHandle> item in _stringsByHashCode)
			{
				if (item.Value.IsUsed)
				{
					result.LiveStringCount++;
				}
				else
				{
					result.CollectedStringCount++;
				}
			}
			return result;
		}
	}
	internal class WeakStringCacheInterner : IDisposable
	{
		private enum InternResult
		{
			FoundInWeakStringCache,
			AddedToWeakStringCache
		}

		internal static WeakStringCacheInterner Instance = new WeakStringCacheInterner();

		private readonly WeakStringCache _weakStringCache = new WeakStringCache();

		private int _regularInternHits;

		private int _regularInternMisses;

		private int _internEliminatedStrings;

		private int _internEliminatedChars;

		private Dictionary<string, int>? _internCallCountsByString;

		private InternResult Intern(ref InternableString candidate, out string interned)
		{
			interned = _weakStringCache.GetOrCreateEntry(ref candidate, out var cacheHit);
			if (!cacheHit)
			{
				return InternResult.AddedToWeakStringCache;
			}
			return InternResult.FoundInWeakStringCache;
		}

		public string InternableToString(ref InternableString candidate)
		{
			if (candidate.Length == 0)
			{
				return string.Empty;
			}
			string interned;
			InternResult internResult = Intern(ref candidate, out interned);
			if (_internCallCountsByString != null)
			{
				lock (_internCallCountsByString)
				{
					switch (internResult)
					{
					case InternResult.FoundInWeakStringCache:
						_regularInternHits++;
						break;
					case InternResult.AddedToWeakStringCache:
						_regularInternMisses++;
						break;
					}
					_internCallCountsByString.TryGetValue(interned, out var value);
					_internCallCountsByString[interned] = value + 1;
					if (!candidate.ReferenceEquals(interned))
					{
						_internEliminatedStrings++;
						_internEliminatedChars += candidate.Length;
					}
				}
			}
			return interned;
		}

		public void EnableStatistics()
		{
			_internCallCountsByString = new Dictionary<string, int>();
		}

		public string FormatStatistics()
		{
			StringBuilder stringBuilder = new StringBuilder(1024);
			string text = "Opportunistic Intern";
			if (_internCallCountsByString != null)
			{
				stringBuilder.AppendLine(string.Format("\n{0}{1}{0}", new string('=', 41 - text.Length / 2), text));
				stringBuilder.AppendLine(string.Format("||{0,50}|{1,20:N0}|{2,8}|", "WeakStringCache Hits", _regularInternHits, "hits"));
				stringBuilder.AppendLine(string.Format("||{0,50}|{1,20:N0}|{2,8}|", "WeakStringCache Misses", _regularInternMisses, "misses"));
				stringBuilder.AppendLine(string.Format("||{0,50}|{1,20:N0}|{2,8}|", "Eliminated Strings*", _internEliminatedStrings, "strings"));
				stringBuilder.AppendLine(string.Format("||{0,50}|{1,20:N0}|{2,8}|", "Eliminated Chars", _internEliminatedChars, "chars"));
				stringBuilder.AppendLine(string.Format("||{0,50}|{1,20:N0}|{2,8}|", "Estimated Eliminated Bytes", _internEliminatedChars * 2, "bytes"));
				stringBuilder.AppendLine("Elimination assumes that strings provided were unique objects.");
				stringBuilder.AppendLine("|---------------------------------------------------------------------------------|");
				IEnumerable<string> source = from kv in (from kv in _internCallCountsByString
						orderby kv.Value * kv.Key.Length descending
						where kv.Value > 1
						select kv).Take(15)
					select string.Format(CultureInfo.InvariantCulture, "({1} instances x each {2} chars)\n{0}", kv.Key, kv.Value, kv.Key.Length);
				stringBuilder.AppendLine(string.Format("##########Top Top Interned Strings:  \n{0} ", string.Join("\n==============\n", source.ToArray())));
				stringBuilder.AppendLine();
				WeakStringCache.DebugInfo debugInfo = _weakStringCache.GetDebugInfo();
				stringBuilder.AppendLine("WeakStringCache statistics:");
				stringBuilder.AppendLine($"String count live/collected/total = {debugInfo.LiveStringCount}/{debugInfo.CollectedStringCount}/{debugInfo.LiveStringCount + debugInfo.CollectedStringCount}");
			}
			else
			{
				stringBuilder.Append(text);
				stringBuilder.AppendLine(" - EnableStatisticsGathering() has not been called");
			}
			return stringBuilder.ToString();
		}

		public void Dispose()
		{
			_weakStringCache.Dispose();
		}
	}
}

folder/System.Text.Json.dll

Decompiled 11 months ago
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Encodings.Web;
using System.Text.Json.Nodes;
using System.Text.Json.Reflection;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using FxResources.System.Text.Json;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyDefaultAlias("System.Text.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nCommonly Used Types:\r\nSystem.Text.Json.JsonSerializer\r\nSystem.Text.Json.JsonDocument\r\nSystem.Text.Json.JsonElement\r\nSystem.Text.Json.Utf8JsonWriter\r\nSystem.Text.Json.Utf8JsonReader")]
[assembly: AssemblyFileVersion("6.0.1823.26907")]
[assembly: AssemblyInformationalVersion("6.0.18+c76ac565499f3e7c657126d46c00b67a0d74832c")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Json")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("6.0.0.8")]
[module: UnverifiableCode]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
}
namespace FxResources.System.Text.Json
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = default(Span<char>);
			if (bytes.Length > 16)
			{
				char[] array = new char[bytes.Length * 2];
				span = array.AsSpan();
			}
			else
			{
				span = stackalloc char[bytes.Length * 2];
			}
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				byte value = readOnlySpan[i];
				ToCharsBuffer(value, span, num, casing);
				num += 2;
			}
			return span.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes)
		{
			int charsProcessed;
			return TryDecodeFromUtf16(chars, bytes, out charsProcessed);
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				ulong num2 = (ulong)(-17875860044349952L << (int)num);
				ulong num3 = num - 64;
				if ((long)(num2 & num3) >= 0L)
				{
					return false;
				}
				return true;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class Obsoletions
	{
		internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}";

		internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.";

		internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001";

		internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used.";

		internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002";

		internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime.";

		internal const string CodeAccessSecurityDiagId = "SYSLIB0003";

		internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported.";

		internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004";

		internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported.";

		internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005";

		internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadAbortDiagId = "SYSLIB0006";

		internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported.";

		internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007";

		internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException.";

		internal const string CreatePdbGeneratorDiagId = "SYSLIB0008";

		internal const string AuthenticationManagerMessage = "The AuthenticationManager Authenticate and PreAuthenticate methods are not supported and throw PlatformNotSupportedException.";

		internal const string AuthenticationManagerDiagId = "SYSLIB0009";

		internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException.";

		internal const string RemotingApisDiagId = "SYSLIB0010";

		internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.";

		internal const string BinaryFormatterDiagId = "SYSLIB0011";

		internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead.";

		internal const string CodeBaseDiagId = "SYSLIB0012";

		internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead.";

		internal const string EscapeUriStringDiagId = "SYSLIB0013";

		internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.";

		internal const string WebRequestDiagId = "SYSLIB0014";

		internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+.";

		internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015";

		internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations.";

		internal const string GetContextInfoDiagId = "SYSLIB0016";

		internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException.";

		internal const string StrongNameKeyPairDiagId = "SYSLIB0017";

		internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException.";

		internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018";

		internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException.";

		internal const string RuntimeEnvironmentDiagId = "SYSLIB0019";

		internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.";

		internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020";

		internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead.";

		internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021";

		internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead.";

		internal const string RijndaelDiagId = "SYSLIB0022";

		internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.";

		internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023";

		internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception.";

		internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024";

		internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+.";

		internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025";

		internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use the appropriate constructor to create a new certificate.";

		internal const string X509CertificateImmutableDiagId = "SYSLIB0026";

		internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey.";

		internal const string PublicKeyPropertyDiagId = "SYSLIB0027";

		internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.";

		internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028";

		internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported.";

		internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029";

		internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter.";

		internal const string UseManagedSha1DiagId = "SYSLIB0030";

		internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1.";

		internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031";

		internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.";

		internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032";

		internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead.";

		internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033";

		internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead.";

		internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034";

		internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner.";

		internal const string SignerInfoCounterSigDiagId = "SYSLIB0035";
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge");

		internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss");

		internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16");

		internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16");

		internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose");

		internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty");

		internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8");

		internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64");

		internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16");

		internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16");

		internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8");

		internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray");

		internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty");

		internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose");

		internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject");

		internal static string DepthTooLarge => GetResourceString("DepthTooLarge");

		internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid");

		internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound");

		internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound");

		internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson");

		internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound");

		internal static string ExpectedFalse => GetResourceString("ExpectedFalse");

		internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens");

		internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken");

		internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound");

		internal static string ExpectedNull => GetResourceString("ExpectedNull");

		internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound");

		internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound");

		internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound");

		internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound");

		internal static string ExpectedTrue => GetResourceString("ExpectedTrue");

		internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound");

		internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan");

		internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter");

		internal static string InvalidCast => GetResourceString("InvalidCast");

		internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString");

		internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString");

		internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive");

		internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString");

		internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments");

		internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType");

		internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive");

		internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid");

		internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray");

		internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty");

		internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge");

		internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge");

		internal static string FormatDecimal => GetResourceString("FormatDecimal");

		internal static string FormatDouble => GetResourceString("FormatDouble");

		internal static string FormatInt32 => GetResourceString("FormatInt32");

		internal static string FormatInt64 => GetResourceString("FormatInt64");

		internal static string FormatSingle => GetResourceString("FormatSingle");

		internal static string FormatUInt32 => GetResourceString("FormatUInt32");

		internal static string FormatUInt64 => GetResourceString("FormatUInt64");

		internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal");

		internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign");

		internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData");

		internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported");

		internal static string ValueTooLarge => GetResourceString("ValueTooLarge");

		internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd");

		internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue");

		internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType");

		internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize");

		internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar");

		internal static string InvalidComparison => GetResourceString("InvalidComparison");

		internal static string FormatDateTime => GetResourceString("FormatDateTime");

		internal static string FormatDateTimeOffset => GetResourceString("FormatDateTimeOffset");

		internal static string FormatTimeSpan => GetResourceString("FormatTimeSpan");

		internal static string FormatGuid => GetResourceString("FormatGuid");

		internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment");

		internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd");

		internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd");

		internal static string SerializerOptionsImmutable => GetResourceString("SerializerOptionsImmutable");

		internal static string StreamNotWritable => GetResourceString("StreamNotWritable");

		internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter");

		internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict");

		internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull");

		internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid");

		internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute");

		internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType");

		internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization");

		internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment");

		internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment");

		internal static string CannotSkip => GetResourceString("CannotSkip");

		internal static string NotEnoughData => GetResourceString("NotEnoughData");

		internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator");

		internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments");

		internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor");

		internal static string DeserializePolymorphicInterface => GetResourceString("DeserializePolymorphicInterface");

		internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible");

		internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid");

		internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead");

		internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible");

		internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite");

		internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull");

		internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute");

		internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize");

		internal static string FormatByte => GetResourceString("FormatByte");

		internal static string FormatInt16 => GetResourceString("FormatInt16");

		internal static string FormatSByte => GetResourceString("FormatSByte");

		internal static string FormatUInt16 => GetResourceString("FormatUInt16");

		internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected");

		internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber");

		internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable");

		internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound");

		internal static string MetadataIdIsNotFirstProperty => GetResourceString("MetadataIdIsNotFirstProperty");

		internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType");

		internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues");

		internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed");

		internal static string MetadataPreservedArrayInvalidProperty => GetResourceString("MetadataPreservedArrayInvalidProperty");

		internal static string MetadataPreservedArrayPropertyNotFound => GetResourceString("MetadataPreservedArrayPropertyNotFound");

		internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties");

		internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound");

		internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString");

		internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign");

		internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter");

		internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding");

		internal static string ConstructorMaxOf64Parameters => GetResourceString("ConstructorMaxOf64Parameters");

		internal static string ObjectWithParameterizedCtorRefMetadataNotHonored => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotHonored");

		internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull");

		internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType");

		internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam");

		internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded");

		internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType");

		internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported");

		internal static string JsonIncludeOnNonPublicInvalid => GetResourceString("JsonIncludeOnNonPublicInvalid");

		internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember");

		internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection");

		internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified");

		internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid");

		internal static string FormatBoolean => GetResourceString("FormatBoolean");

		internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported");

		internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid");

		internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid");

		internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes");

		internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType");

		internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue");

		internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull");

		internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory");

		internal static string NodeDynamicObjectResultNotAssignable => GetResourceString("NodeDynamicObjectResultNotAssignable");

		internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType");

		internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray");

		internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent");

		internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected");

		internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert");

		internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement");

		internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed");

		internal static string NodeWrongType => GetResourceString("NodeWrongType");

		internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey");

		internal static string SerializerContextOptionsImmutable => GetResourceString("SerializerContextOptionsImmutable");

		internal static string OptionsAlreadyBoundToContext => GetResourceString("OptionsAlreadyBoundToContext");

		internal static string InitializeTypeInfoAsObjectInvalid => GetResourceString("InitializeTypeInfoAsObjectInvalid");

		internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid");

		internal static string BuiltInConvertersNotRooted => GetResourceString("BuiltInConvertersNotRooted");

		internal static string NoMetadataForType => GetResourceString("NoMetadataForType");

		internal static string NodeCollectionIsReadOnly => GetResourceString("NodeCollectionIsReadOnly");

		internal static string NodeArrayIndexNegative => GetResourceString("NodeArrayIndexNegative");

		internal static string NodeArrayTooSmall => GetResourceString("NodeArrayTooSmall");

		internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty");

		internal static string MetadataInitFuncsNull => GetResourceString("MetadataInitFuncsNull");

		internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties");

		internal static string NoDefaultOptionsForContext => GetResourceString("NoDefaultOptionsForContext");

		internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual");

		internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember");

		internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported");

		internal static string NoMetadataForTypeCtorParams => GetResourceString("NoMetadataForTypeCtorParams");

		private static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		internal static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ObsoleteAttribute : Attribute
	{
		public string Message { get; }

		public bool IsError { get; }

		public string DiagnosticId { get; set; }

		public string UrlFormat { get; set; }

		public ObsoleteAttribute()
		{
		}

		public ObsoleteAttribute(string message)
		{
			Message = message;
		}

		public ObsoleteAttribute(string message, bool error)
		{
			Message = message;
			IsError = error;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type Type { get; }

		public string TypeName { get; }

		public string AssemblyName { get; }

		public string Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string Scope { get; set; }

		public string Target { get; set; }

		public string MessageId { get; set; }

		public string Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[EditorBrowsable(EditorBrowsableState.Never)]
	internal static class IsExternalInit
	{
	}
}
namespace System.Collections.Generic
{
	internal sealed class ReferenceEqualityComparer : IEqualityComparer<object>, IEqualityComparer
	{
		public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer();


		private ReferenceEqualityComparer()
		{
		}

		public new bool Equals(object x, object y)
		{
			return x == y;
		}

		public int GetHashCode(object obj)
		{
			return RuntimeHelpers.GetHashCode(obj);
		}
	}
	internal static class StackExtensions
	{
		public static bool TryPeek<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result)
		{
			if (stack.Count > 0)
			{
				result = stack.Peek();
				return true;
			}
			result = default(T);
			return false;
		}

		public static bool TryPop<T>(this Stack<T> stack, [MaybeNullWhen(false)] out T result)
		{
			if (stack.Count > 0)
			{
				result = stack.Pop();
				return true;
			}
			result = default(T);
			return false;
		}
	}
}
namespace System.Buffers
{
	internal sealed class ArrayBufferWriter<T> : IBufferWriter<T>
	{
		private const int ArrayMaxLength = 2147483591;

		private const int DefaultInitialBufferSize = 256;

		private T[] _buffer;

		private int _index;

		public ReadOnlyMemory<T> WrittenMemory => _buffer.AsMemory(0, _index);

		public ReadOnlySpan<T> WrittenSpan => _buffer.AsSpan(0, _index);

		public int WrittenCount => _index;

		public int Capacity => _buffer.Length;

		public int FreeCapacity => _buffer.Length - _index;

		public ArrayBufferWriter()
		{
			_buffer = Array.Empty<T>();
			_index = 0;
		}

		public ArrayBufferWriter(int initialCapacity)
		{
			if (initialCapacity <= 0)
			{
				throw new ArgumentException(null, "initialCapacity");
			}
			_buffer = new T[initialCapacity];
			_index = 0;
		}

		public void Clear()
		{
			_buffer.AsSpan(0, _index).Clear();
			_index = 0;
		}

		public void Advance(int count)
		{
			if (count < 0)
			{
				throw new ArgumentException(null, "count");
			}
			if (_index > _buffer.Length - count)
			{
				ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length);
			}
			_index += count;
		}

		public Memory<T> GetMemory(int sizeHint = 0)
		{
			CheckAndResizeBuffer(sizeHint);
			return _buffer.AsMemory(_index);
		}

		public Span<T> GetSpan(int sizeHint = 0)
		{
			CheckAndResizeBuffer(sizeHint);
			return _buffer.AsSpan(_index);
		}

		private void CheckAndResizeBuffer(int sizeHint)
		{
			if (sizeHint < 0)
			{
				throw new ArgumentException("sizeHint");
			}
			if (sizeHint == 0)
			{
				sizeHint = 1;
			}
			if (sizeHint <= FreeCapacity)
			{
				return;
			}
			int num = _buffer.Length;
			int num2 = Math.Max(sizeHint, num);
			if (num == 0)
			{
				num2 = Math.Max(num2, 256);
			}
			int num3 = num + num2;
			if ((uint)num3 > 2147483647u)
			{
				uint num4 = (uint)(num - FreeCapacity + sizeHint);
				if (num4 > 2147483591)
				{
					ThrowOutOfMemoryException(num4);
				}
				num3 = 2147483591;
			}
			Array.Resize(ref _buffer, num3);
		}

		private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity));
		}

		private static void ThrowOutOfMemoryException(uint capacity)
		{
			throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity));
		}
	}
}
namespace System.Buffers.Text
{
	internal enum SequenceValidity
	{
		Empty,
		WellFormed,
		Incomplete,
		Invalid
	}
}
namespace System.Text.Json
{
	internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable
	{
		private byte[] _rentedBuffer;

		private int _index;

		private const int MinimumBufferSize = 256;

		public ReadOnlyMemory<byte> WrittenMemory => _rentedBuffer.AsMemory(0, _index);

		public int WrittenCount => _index;

		public int Capacity => _rentedBuffer.Length;

		public int FreeCapacity => _rentedBuffer.Length - _index;

		public PooledByteBufferWriter(int initialCapacity)
		{
			_rentedBuffer = ArrayPool<byte>.Shared.Rent(initialCapacity);
			_index = 0;
		}

		public void Clear()
		{
			ClearHelper();
		}

		private void ClearHelper()
		{
			_rentedBuffer.AsSpan(0, _index).Clear();
			_index = 0;
		}

		public void Dispose()
		{
			if (_rentedBuffer != null)
			{
				ClearHelper();
				byte[] rentedBuffer = _rentedBuffer;
				_rentedBuffer = null;
				ArrayPool<byte>.Shared.Return(rentedBuffer);
			}
		}

		public void Advance(int count)
		{
			_index += count;
		}

		public Memory<byte> GetMemory(int sizeHint = 0)
		{
			CheckAndResizeBuffer(sizeHint);
			return _rentedBuffer.AsMemory(_index);
		}

		public Span<byte> GetSpan(int sizeHint = 0)
		{
			CheckAndResizeBuffer(sizeHint);
			return _rentedBuffer.AsSpan(_index);
		}

		internal Task WriteToStreamAsync(Stream destination, CancellationToken cancellationToken)
		{
			return destination.WriteAsync(_rentedBuffer, 0, _index, cancellationToken);
		}

		internal void WriteToStream(Stream destination)
		{
			destination.Write(_rentedBuffer, 0, _index);
		}

		private void CheckAndResizeBuffer(int sizeHint)
		{
			if (sizeHint == 0)
			{
				sizeHint = 256;
			}
			int num = _rentedBuffer.Length - _index;
			if (sizeHint <= num)
			{
				return;
			}
			int num2 = _rentedBuffer.Length;
			int num3 = Math.Max(sizeHint, num2);
			int num4 = num2 + num3;
			if ((uint)num4 > 2147483647u)
			{
				num4 = num2 + sizeHint;
				if ((uint)num4 > 2147483647u)
				{
					ThrowHelper.ThrowOutOfMemoryException_BufferMaximumSizeExceeded((uint)num4);
				}
			}
			byte[] rentedBuffer = _rentedBuffer;
			_rentedBuffer = ArrayPool<byte>.Shared.Rent(num4);
			Span<byte> span = rentedBuffer.AsSpan(0, _index);
			span.CopyTo(_rentedBuffer);
			span.Clear();
			ArrayPool<byte>.Shared.Return(rentedBuffer);
		}
	}
	internal static class ThrowHelper
	{
		public const string ExceptionSourceValueToRethrowAsJsonException = "System.Text.Json.Rethrowable";

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowOutOfMemoryException_BufferMaximumSizeExceeded(uint capacity)
		{
			throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity));
		}

		public static ArgumentOutOfRangeException GetArgumentOutOfRangeException_MaxDepthMustBePositive(string parameterName)
		{
			return GetArgumentOutOfRangeException(parameterName, System.SR.MaxDepthMustBePositive);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(string parameterName, string message)
		{
			return new ArgumentOutOfRangeException(parameterName, message);
		}

		public static ArgumentOutOfRangeException GetArgumentOutOfRangeException_CommentEnumMustBeInRange(string parameterName)
		{
			return GetArgumentOutOfRangeException(parameterName, System.SR.CommentHandlingMustBeValid);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static ArgumentException GetArgumentException(string message)
		{
			return new ArgumentException(message);
		}

		[DoesNotReturn]
		public static void ThrowArgumentException(string message)
		{
			throw GetArgumentException(message);
		}

		public static InvalidOperationException GetInvalidOperationException_CallFlushFirst(int _buffered)
		{
			return GetInvalidOperationException(System.SR.Format(System.SR.CallFlushToAvoidDataLoss, _buffered));
		}

		[DoesNotReturn]
		public static void ThrowArgumentException_PropertyNameTooLarge(int tokenLength)
		{
			throw GetArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, tokenLength));
		}

		[DoesNotReturn]
		public static void ThrowArgumentException_ValueTooLarge(int tokenLength)
		{
			throw GetArgumentException(System.SR.Format(System.SR.ValueTooLarge, tokenLength));
		}

		[DoesNotReturn]
		public static void ThrowArgumentException_ValueNotSupported()
		{
			throw GetArgumentException(System.SR.SpecialNumberValuesNotSupported);
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NeedLargerSpan()
		{
			throw GetInvalidOperationException(System.SR.FailedToGetLargerSpan);
		}

		[DoesNotReturn]
		public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<byte> value)
		{
			if (propertyName.Length > 166666666)
			{
				ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length));
			}
			else
			{
				ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length));
			}
		}

		[DoesNotReturn]
		public static void ThrowArgumentException(ReadOnlySpan<byte> propertyName, ReadOnlySpan<char> value)
		{
			if (propertyName.Length > 166666666)
			{
				ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length));
			}
			else
			{
				ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length));
			}
		}

		[DoesNotReturn]
		public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<byte> value)
		{
			if (propertyName.Length > 166666666)
			{
				ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length));
			}
			else
			{
				ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length));
			}
		}

		[DoesNotReturn]
		public static void ThrowArgumentException(ReadOnlySpan<char> propertyName, ReadOnlySpan<char> value)
		{
			if (propertyName.Length > 166666666)
			{
				ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length));
			}
			else
			{
				ThrowArgumentException(System.SR.Format(System.SR.ValueTooLarge, value.Length));
			}
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<byte> propertyName, int currentDepth)
		{
			currentDepth &= 0x7FFFFFFF;
			if (currentDepth >= 1000)
			{
				ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, 1000));
			}
			else
			{
				ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length));
			}
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException(int currentDepth)
		{
			currentDepth &= 0x7FFFFFFF;
			ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, 1000));
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException(string message)
		{
			throw GetInvalidOperationException(message);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static InvalidOperationException GetInvalidOperationException(string message)
		{
			InvalidOperationException ex = new InvalidOperationException(message);
			ex.Source = "System.Text.Json.Rethrowable";
			return ex;
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException_DepthNonZeroOrEmptyJson(int currentDepth)
		{
			throw GetInvalidOperationException(currentDepth);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static InvalidOperationException GetInvalidOperationException(int currentDepth)
		{
			currentDepth &= 0x7FFFFFFF;
			if (currentDepth != 0)
			{
				return GetInvalidOperationException(System.SR.Format(System.SR.ZeroDepthAtEnd, currentDepth));
			}
			return GetInvalidOperationException(System.SR.EmptyJsonIsInvalid);
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationOrArgumentException(ReadOnlySpan<char> propertyName, int currentDepth)
		{
			currentDepth &= 0x7FFFFFFF;
			if (currentDepth >= 1000)
			{
				ThrowInvalidOperationException(System.SR.Format(System.SR.DepthTooLarge, currentDepth, 1000));
			}
			else
			{
				ThrowArgumentException(System.SR.Format(System.SR.PropertyNameTooLarge, propertyName.Length));
			}
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedArray(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("array", tokenType);
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedObject(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("object", tokenType);
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedNumber(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("number", tokenType);
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedBoolean(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("boolean", tokenType);
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedString(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("string", tokenType);
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedStringComparison(JsonTokenType tokenType)
		{
			return GetInvalidOperationException(tokenType);
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedComment(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("comment", tokenType);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static InvalidOperationException GetInvalidOperationException_CannotSkipOnPartial()
		{
			return GetInvalidOperationException(System.SR.CannotSkip);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static InvalidOperationException GetInvalidOperationException(string message, JsonTokenType tokenType)
		{
			return GetInvalidOperationException(System.SR.Format(System.SR.InvalidCast, tokenType, message));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static InvalidOperationException GetInvalidOperationException(JsonTokenType tokenType)
		{
			return GetInvalidOperationException(System.SR.Format(System.SR.InvalidComparison, tokenType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static InvalidOperationException GetJsonElementWrongTypeException(JsonTokenType expectedType, JsonTokenType actualType)
		{
			return GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind());
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonTokenType actualType)
		{
			return GetJsonElementWrongTypeException(expectedTypeName, actualType.ToValueKind());
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static InvalidOperationException GetJsonElementWrongTypeException(JsonValueKind expectedType, JsonValueKind actualType)
		{
			return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedType, actualType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static InvalidOperationException GetJsonElementWrongTypeException(string expectedTypeName, JsonValueKind actualType)
		{
			return GetInvalidOperationException(System.SR.Format(System.SR.JsonElementHasWrongType, expectedTypeName, actualType));
		}

		[DoesNotReturn]
		public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = 0, ReadOnlySpan<byte> bytes = default(ReadOnlySpan<byte>))
		{
			throw GetJsonReaderException(ref json, resource, nextByte, bytes);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static JsonException GetJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, ReadOnlySpan<byte> bytes)
		{
			string resourceString = GetResourceString(ref json, resource, nextByte, JsonHelpers.Utf8GetString(bytes));
			long lineNumber = json.CurrentState._lineNumber;
			long bytePositionInLine = json.CurrentState._bytePositionInLine;
			resourceString += $" LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
			return new JsonReaderException(resourceString, lineNumber, bytePositionInLine);
		}

		private static bool IsPrintable(byte value)
		{
			if (value >= 32)
			{
				return value < 127;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static string GetPrintableString(byte value)
		{
			if (!IsPrintable(value))
			{
				return $"0x{value:X2}";
			}
			char c = (char)value;
			return c.ToString();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static string GetResourceString(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte, string characters)
		{
			string printableString = GetPrintableString(nextByte);
			string result = "";
			switch (resource)
			{
			case ExceptionResource.ArrayDepthTooLarge:
				result = System.SR.Format(System.SR.ArrayDepthTooLarge, json.CurrentState.Options.MaxDepth);
				break;
			case ExceptionResource.MismatchedObjectArray:
				result = System.SR.Format(System.SR.MismatchedObjectArray, printableString);
				break;
			case ExceptionResource.TrailingCommaNotAllowedBeforeArrayEnd:
				result = System.SR.TrailingCommaNotAllowedBeforeArrayEnd;
				break;
			case ExceptionResource.TrailingCommaNotAllowedBeforeObjectEnd:
				result = System.SR.TrailingCommaNotAllowedBeforeObjectEnd;
				break;
			case ExceptionResource.EndOfStringNotFound:
				result = System.SR.EndOfStringNotFound;
				break;
			case ExceptionResource.RequiredDigitNotFoundAfterSign:
				result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterSign, printableString);
				break;
			case ExceptionResource.RequiredDigitNotFoundAfterDecimal:
				result = System.SR.Format(System.SR.RequiredDigitNotFoundAfterDecimal, printableString);
				break;
			case ExceptionResource.RequiredDigitNotFoundEndOfData:
				result = System.SR.RequiredDigitNotFoundEndOfData;
				break;
			case ExceptionResource.ExpectedEndAfterSingleJson:
				result = System.SR.Format(System.SR.ExpectedEndAfterSingleJson, printableString);
				break;
			case ExceptionResource.ExpectedEndOfDigitNotFound:
				result = System.SR.Format(System.SR.ExpectedEndOfDigitNotFound, printableString);
				break;
			case ExceptionResource.ExpectedNextDigitEValueNotFound:
				result = System.SR.Format(System.SR.ExpectedNextDigitEValueNotFound, printableString);
				break;
			case ExceptionResource.ExpectedSeparatorAfterPropertyNameNotFound:
				result = System.SR.Format(System.SR.ExpectedSeparatorAfterPropertyNameNotFound, printableString);
				break;
			case ExceptionResource.ExpectedStartOfPropertyNotFound:
				result = System.SR.Format(System.SR.ExpectedStartOfPropertyNotFound, printableString);
				break;
			case ExceptionResource.ExpectedStartOfPropertyOrValueNotFound:
				result = System.SR.ExpectedStartOfPropertyOrValueNotFound;
				break;
			case ExceptionResource.ExpectedStartOfPropertyOrValueAfterComment:
				result = System.SR.Format(System.SR.ExpectedStartOfPropertyOrValueAfterComment, printableString);
				break;
			case ExceptionResource.ExpectedStartOfValueNotFound:
				result = System.SR.Format(System.SR.ExpectedStartOfValueNotFound, printableString);
				break;
			case ExceptionResource.ExpectedValueAfterPropertyNameNotFound:
				result = System.SR.ExpectedValueAfterPropertyNameNotFound;
				break;
			case ExceptionResource.FoundInvalidCharacter:
				result = System.SR.Format(System.SR.FoundInvalidCharacter, printableString);
				break;
			case ExceptionResource.InvalidEndOfJsonNonPrimitive:
				result = System.SR.Format(System.SR.InvalidEndOfJsonNonPrimitive, json.TokenType);
				break;
			case ExceptionResource.ObjectDepthTooLarge:
				result = System.SR.Format(System.SR.ObjectDepthTooLarge, json.CurrentState.Options.MaxDepth);
				break;
			case ExceptionResource.ExpectedFalse:
				result = System.SR.Format(System.SR.ExpectedFalse, characters);
				break;
			case ExceptionResource.ExpectedNull:
				result = System.SR.Format(System.SR.ExpectedNull, characters);
				break;
			case ExceptionResource.ExpectedTrue:
				result = System.SR.Format(System.SR.ExpectedTrue, characters);
				break;
			case ExceptionResource.InvalidCharacterWithinString:
				result = System.SR.Format(System.SR.InvalidCharacterWithinString, printableString);
				break;
			case ExceptionResource.InvalidCharacterAfterEscapeWithinString:
				result = System.SR.Format(System.SR.InvalidCharacterAfterEscapeWithinString, printableString);
				break;
			case ExceptionResource.InvalidHexCharacterWithinString:
				result = System.SR.Format(System.SR.InvalidHexCharacterWithinString, printableString);
				break;
			case ExceptionResource.EndOfCommentNotFound:
				result = System.SR.EndOfCommentNotFound;
				break;
			case ExceptionResource.ZeroDepthAtEnd:
				result = System.SR.Format(System.SR.ZeroDepthAtEnd);
				break;
			case ExceptionResource.ExpectedJsonTokens:
				result = System.SR.ExpectedJsonTokens;
				break;
			case ExceptionResource.NotEnoughData:
				result = System.SR.NotEnoughData;
				break;
			case ExceptionResource.ExpectedOneCompleteToken:
				result = System.SR.ExpectedOneCompleteToken;
				break;
			case ExceptionResource.InvalidCharacterAtStartOfComment:
				result = System.SR.Format(System.SR.InvalidCharacterAtStartOfComment, printableString);
				break;
			case ExceptionResource.UnexpectedEndOfDataWhileReadingComment:
				result = System.SR.Format(System.SR.UnexpectedEndOfDataWhileReadingComment);
				break;
			case ExceptionResource.UnexpectedEndOfLineSeparator:
				result = System.SR.Format(System.SR.UnexpectedEndOfLineSeparator);
				break;
			case ExceptionResource.InvalidLeadingZeroInNumber:
				result = System.SR.Format(System.SR.InvalidLeadingZeroInNumber, printableString);
				break;
			}
			return result;
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException(ExceptionResource resource, int currentDepth, byte token, JsonTokenType tokenType)
		{
			throw GetInvalidOperationException(resource, currentDepth, token, tokenType);
		}

		[DoesNotReturn]
		public static void ThrowArgumentException_InvalidCommentValue()
		{
			throw new ArgumentException(System.SR.CannotWriteCommentWithEmbeddedDelimiter);
		}

		[DoesNotReturn]
		public static void ThrowArgumentException_InvalidUTF8(ReadOnlySpan<byte> value)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = Math.Min(value.Length, 10);
			for (int i = 0; i < num; i++)
			{
				byte b = value[i];
				if (IsPrintable(b))
				{
					stringBuilder.Append((char)b);
				}
				else
				{
					stringBuilder.Append($"0x{b:X2}");
				}
			}
			if (num < value.Length)
			{
				stringBuilder.Append("...");
			}
			throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF8, stringBuilder));
		}

		[DoesNotReturn]
		public static void ThrowArgumentException_InvalidUTF16(int charAsInt)
		{
			throw new ArgumentException(System.SR.Format(System.SR.CannotEncodeInvalidUTF16, $"0x{charAsInt:X2}"));
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException_ReadInvalidUTF16(int charAsInt)
		{
			throw GetInvalidOperationException(System.SR.Format(System.SR.CannotReadInvalidUTF16, $"0x{charAsInt:X2}"));
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException_ReadInvalidUTF16()
		{
			throw GetInvalidOperationException(System.SR.CannotReadIncompleteUTF16);
		}

		public static InvalidOperationException GetInvalidOperationException_ReadInvalidUTF8(DecoderFallbackException innerException)
		{
			return GetInvalidOperationException(System.SR.CannotTranscodeInvalidUtf8, innerException);
		}

		public static ArgumentException GetArgumentException_ReadInvalidUTF16(EncoderFallbackException innerException)
		{
			return new ArgumentException(System.SR.CannotTranscodeInvalidUtf16, innerException);
		}

		public static InvalidOperationException GetInvalidOperationException(string message, Exception innerException)
		{
			InvalidOperationException ex = new InvalidOperationException(message, innerException);
			ex.Source = "System.Text.Json.Rethrowable";
			return ex;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static InvalidOperationException GetInvalidOperationException(ExceptionResource resource, int currentDepth, byte token, JsonTokenType tokenType)
		{
			string resourceString = GetResourceString(resource, currentDepth, token, tokenType);
			InvalidOperationException invalidOperationException = GetInvalidOperationException(resourceString);
			invalidOperationException.Source = "System.Text.Json.Rethrowable";
			return invalidOperationException;
		}

		[DoesNotReturn]
		public static void ThrowOutOfMemoryException(uint capacity)
		{
			throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static string GetResourceString(ExceptionResource resource, int currentDepth, byte token, JsonTokenType tokenType)
		{
			string result = "";
			switch (resource)
			{
			case ExceptionResource.MismatchedObjectArray:
				result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWriteEndAfterProperty, (char)token) : System.SR.Format(System.SR.MismatchedObjectArray, (char)token));
				break;
			case ExceptionResource.DepthTooLarge:
				result = System.SR.Format(System.SR.DepthTooLarge, currentDepth & 0x7FFFFFFF, 1000);
				break;
			case ExceptionResource.CannotStartObjectArrayWithoutProperty:
				result = System.SR.Format(System.SR.CannotStartObjectArrayWithoutProperty, tokenType);
				break;
			case ExceptionResource.CannotStartObjectArrayAfterPrimitiveOrClose:
				result = System.SR.Format(System.SR.CannotStartObjectArrayAfterPrimitiveOrClose, tokenType);
				break;
			case ExceptionResource.CannotWriteValueWithinObject:
				result = System.SR.Format(System.SR.CannotWriteValueWithinObject, tokenType);
				break;
			case ExceptionResource.CannotWritePropertyWithinArray:
				result = ((tokenType == JsonTokenType.PropertyName) ? System.SR.Format(System.SR.CannotWritePropertyAfterProperty) : System.SR.Format(System.SR.CannotWritePropertyWithinArray, tokenType));
				break;
			case ExceptionResource.CannotWriteValueAfterPrimitiveOrClose:
				result = System.SR.Format(System.SR.CannotWriteValueAfterPrimitiveOrClose, tokenType);
				break;
			}
			return result;
		}

		public static FormatException GetFormatException()
		{
			FormatException ex = new FormatException();
			ex.Source = "System.Text.Json.Rethrowable";
			return ex;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static FormatException GetFormatException(NumericType numericType)
		{
			string message = "";
			switch (numericType)
			{
			case NumericType.Byte:
				message = System.SR.FormatByte;
				break;
			case NumericType.SByte:
				message = System.SR.FormatSByte;
				break;
			case NumericType.Int16:
				message = System.SR.FormatInt16;
				break;
			case NumericType.Int32:
				message = System.SR.FormatInt32;
				break;
			case NumericType.Int64:
				message = System.SR.FormatInt64;
				break;
			case NumericType.UInt16:
				message = System.SR.FormatUInt16;
				break;
			case NumericType.UInt32:
				message = System.SR.FormatUInt32;
				break;
			case NumericType.UInt64:
				message = System.SR.FormatUInt64;
				break;
			case NumericType.Single:
				message = System.SR.FormatSingle;
				break;
			case NumericType.Double:
				message = System.SR.FormatDouble;
				break;
			case NumericType.Decimal:
				message = System.SR.FormatDecimal;
				break;
			}
			FormatException ex = new FormatException(message);
			ex.Source = "System.Text.Json.Rethrowable";
			return ex;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static FormatException GetFormatException(DataType dateType)
		{
			string message = "";
			switch (dateType)
			{
			case DataType.Boolean:
				message = System.SR.FormatBoolean;
				break;
			case DataType.DateTime:
				message = System.SR.FormatDateTime;
				break;
			case DataType.DateTimeOffset:
				message = System.SR.FormatDateTimeOffset;
				break;
			case DataType.TimeSpan:
				message = System.SR.FormatTimeSpan;
				break;
			case DataType.Base64String:
				message = System.SR.CannotDecodeInvalidBase64;
				break;
			case DataType.Guid:
				message = System.SR.FormatGuid;
				break;
			}
			FormatException ex = new FormatException(message);
			ex.Source = "System.Text.Json.Rethrowable";
			return ex;
		}

		public static InvalidOperationException GetInvalidOperationException_ExpectedChar(JsonTokenType tokenType)
		{
			return GetInvalidOperationException("char", tokenType);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowArgumentException_NodeValueNotAllowed(string paramName)
		{
			throw new ArgumentException(System.SR.NodeValueNotAllowed, paramName);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowArgumentException_NodeArrayTooSmall(string paramName)
		{
			throw new ArgumentException(System.SR.NodeArrayTooSmall, paramName);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowArgumentOutOfRangeException_NodeArrayIndexNegative(string paramName)
		{
			throw new ArgumentOutOfRangeException(paramName, System.SR.NodeArrayIndexNegative);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowArgumentException_DuplicateKey(string propertyName)
		{
			throw new ArgumentException(System.SR.NodeDuplicateKey, propertyName);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NodeAlreadyHasParent()
		{
			throw new InvalidOperationException(System.SR.NodeAlreadyHasParent);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NodeCycleDetected()
		{
			throw new InvalidOperationException(System.SR.NodeCycleDetected);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NodeElementCannotBeObjectOrArray()
		{
			throw new InvalidOperationException(System.SR.NodeElementCannotBeObjectOrArray);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_NodeCollectionIsReadOnly()
		{
			throw NotSupportedException_NodeCollectionIsReadOnly();
		}

		public static NotSupportedException NotSupportedException_NodeCollectionIsReadOnly()
		{
			return new NotSupportedException(System.SR.NodeCollectionIsReadOnly);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowArgumentException_DeserializeWrongType(Type type, object value)
		{
			throw new ArgumentException(System.SR.Format(System.SR.DeserializeWrongType, type, value.GetType()));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_SerializationNotSupported(Type propertyType)
		{
			throw new NotSupportedException(System.SR.Format(System.SR.SerializationNotSupportedType, propertyType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_TypeRequiresAsyncSerialization(Type propertyType)
		{
			throw new NotSupportedException(System.SR.Format(System.SR.TypeRequiresAsyncSerialization, propertyType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_ConstructorMaxOf64Parameters(Type type)
		{
			throw new NotSupportedException(System.SR.Format(System.SR.ConstructorMaxOf64Parameters, type));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_DictionaryKeyTypeNotSupported(Type keyType, JsonConverter converter)
		{
			throw new NotSupportedException(System.SR.Format(System.SR.DictionaryKeyTypeNotSupported, keyType, converter.GetType()));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
		{
			throw new JsonException(System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType))
			{
				AppendPathInformation = true
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidCastException_DeserializeUnableToAssignValue(Type typeOfValue, Type declaredType)
		{
			throw new InvalidCastException(System.SR.Format(System.SR.DeserializeUnableToAssignValue, typeOfValue, declaredType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_DeserializeUnableToAssignNull(Type declaredType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.DeserializeUnableToAssignNull, declaredType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_SerializationConverterRead(JsonConverter converter)
		{
			throw new JsonException(System.SR.Format(System.SR.SerializationConverterRead, converter))
			{
				AppendPathInformation = true
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_SerializationConverterWrite(JsonConverter converter)
		{
			throw new JsonException(System.SR.Format(System.SR.SerializationConverterWrite, converter))
			{
				AppendPathInformation = true
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_SerializerCycleDetected(int maxDepth)
		{
			throw new JsonException(System.SR.Format(System.SR.SerializerCycleDetected, maxDepth))
			{
				AppendPathInformation = true
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException(string message = null)
		{
			throw new JsonException(message)
			{
				AppendPathInformation = true
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type parentClassType, MemberInfo memberInfo)
		{
			if (parentClassType == null)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidType, type));
			}
			throw new InvalidOperationException(System.SR.Format(System.SR.CannotSerializeInvalidMember, type, memberInfo.Name, parentClassType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationConverterNotCompatible(Type converterType, Type type)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterNotCompatible, converterType, type));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, MemberInfo memberInfo)
		{
			string text = classType.ToString();
			if (memberInfo != null)
			{
				text = text + "." + memberInfo.Name;
			}
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeInvalid, text));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, MemberInfo memberInfo, Type typeToConvert)
		{
			string text = classTypeAttributeIsOn.ToString();
			if (memberInfo != null)
			{
				text = text + "." + memberInfo.Name;
			}
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationConverterOnAttributeNotCompatible, text, typeToConvert));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializerOptionsImmutable(JsonSerializerContext context)
		{
			string message = ((context == null) ? System.SR.SerializerOptionsImmutable : System.SR.SerializerContextOptionsImmutable);
			throw new InvalidOperationException(message);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameConflict, type, jsonPropertyInfo.ClrName));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializerPropertyNameNull(Type parentType, JsonPropertyInfo jsonPropertyInfo)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializerPropertyNameNull, parentType, jsonPropertyInfo.MemberInfo?.Name));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NamingPolicyReturnNull(JsonNamingPolicy namingPolicy)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.NamingPolicyReturnNull, namingPolicy));
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsNull(Type converterType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsNull, converterType));
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializerConverterFactoryReturnsJsonConverterFactorty(Type converterType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializerConverterFactoryReturnsJsonConverterFactory, converterType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_MultiplePropertiesBindToConstructorParameters(Type parentType, string parameterName, string firstMatchName, string secondMatchName)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MultipleMembersBindWithConstructorParameter, firstMatchName, secondMatchName, parentType, parameterName));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_ConstructorParameterIncompleteBinding(Type parentType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.ConstructorParamIncompleteBinding, parentType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_ExtensionDataCannotBindToCtorParam(JsonPropertyInfo jsonPropertyInfo)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.ExtensionDataCannotBindToCtorParam, jsonPropertyInfo.ClrName, jsonPropertyInfo.DeclaringType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_JsonIncludeOnNonPublicInvalid(string memberName, Type declaringType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.JsonIncludeOnNonPublicInvalid, memberName, declaringType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_IgnoreConditionOnValueTypeInvalid(string clrPropertyName, Type propertyDeclaringType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.IgnoreConditionOnValueTypeInvalid, clrPropertyName, propertyDeclaringType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NumberHandlingOnPropertyInvalid(JsonPropertyInfo jsonPropertyInfo)
		{
			MemberInfo memberInfo = jsonPropertyInfo.MemberInfo;
			throw new InvalidOperationException(System.SR.Format(System.SR.NumberHandlingOnPropertyInvalid, memberInfo.Name, memberInfo.DeclaringType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_ConverterCanConvertMultipleTypes(Type runtimePropertyType, JsonConverter jsonConverter)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.ConverterCanConvertMultipleTypes, jsonConverter.GetType(), jsonConverter.TypeToConvert, runtimePropertyType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, ref ReadStack state)
		{
			state.Current.JsonPropertyName = propertyName.ToArray();
			NotSupportedException ex = new NotSupportedException(System.SR.Format(System.SR.ObjectWithParameterizedCtorRefMetadataNotHonored, state.Current.JsonTypeInfo.Type));
			ThrowNotSupportedException(ref state, in reader, ex);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ReThrowWithPath(ref ReadStack state, JsonReaderException ex)
		{
			string text = state.JsonPath();
			string message = ex.Message;
			int num = message.LastIndexOf(" LineNumber: ", StringComparison.InvariantCulture);
			message = ((num < 0) ? (message + " Path: " + text + ".") : (message.Substring(0, num) + " Path: " + text + " |" + message.Substring(num)));
			throw new JsonException(message, text, ex.LineNumber, ex.BytePositionInLine, ex);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ReThrowWithPath(ref ReadStack state, in Utf8JsonReader reader, Exception ex)
		{
			JsonException ex2 = new JsonException(null, ex);
			AddJsonExceptionInformation(ref state, in reader, ex2);
			throw ex2;
		}

		public static void AddJsonExceptionInformation(ref ReadStack state, in Utf8JsonReader reader, JsonException ex)
		{
			long lineNumber = reader.CurrentState._lineNumber;
			ex.LineNumber = lineNumber;
			long bytePositionInLine = reader.CurrentState._bytePositionInLine;
			ex.BytePositionInLine = bytePositionInLine;
			string arg = (ex.Path = state.JsonPath());
			string text2 = ex._message;
			if (string.IsNullOrEmpty(text2))
			{
				Type type = state.Current.JsonPropertyInfo?.RuntimePropertyType;
				if (type == null)
				{
					type = state.Current.JsonTypeInfo?.Type;
				}
				text2 = System.SR.Format(System.SR.DeserializeUnableToConvertValue, type);
				ex.AppendPathInformation = true;
			}
			if (ex.AppendPathInformation)
			{
				text2 += $" Path: {arg} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
				ex.SetMessage(text2);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ReThrowWithPath(ref WriteStack state, Exception ex)
		{
			JsonException ex2 = new JsonException(null, ex);
			AddJsonExceptionInformation(ref state, ex2);
			throw ex2;
		}

		public static void AddJsonExceptionInformation(ref WriteStack state, JsonException ex)
		{
			string text2 = (ex.Path = state.PropertyPath());
			string text3 = ex._message;
			if (string.IsNullOrEmpty(text3))
			{
				text3 = System.SR.Format(System.SR.SerializeUnableToSerialize);
				ex.AppendPathInformation = true;
			}
			if (ex.AppendPathInformation)
			{
				text3 = text3 + " Path: " + text2 + ".";
				ex.SetMessage(text3);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationDuplicateAttribute(Type attribute, Type classType, MemberInfo memberInfo)
		{
			string text = classType.ToString();
			if (memberInfo != null)
			{
				text = text + "." + memberInfo.Name;
			}
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateAttribute, attribute, text));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute(Type classType, Type attribute)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, attribute));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationDuplicateTypeAttribute<TAttribute>(Type classType)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDuplicateTypeAttribute, classType, typeof(TAttribute)));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_SerializationDataExtensionPropertyInvalid(Type type, JsonPropertyInfo jsonPropertyInfo)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.SerializationDataExtensionPropertyInvalid, type, jsonPropertyInfo.MemberInfo?.Name));
		}

		[DoesNotReturn]
		public static void ThrowNotSupportedException(ref ReadStack state, in Utf8JsonReader reader, NotSupportedException ex)
		{
			string text = ex.Message;
			Type type = state.Current.JsonPropertyInfo?.RuntimePropertyType;
			if (type == null)
			{
				type = state.Current.JsonTypeInfo.Type;
			}
			if (!text.Contains(type.ToString()))
			{
				if (text.Length > 0)
				{
					text += " ";
				}
				text += System.SR.Format(System.SR.SerializationNotSupportedParentType, type);
			}
			long lineNumber = reader.CurrentState._lineNumber;
			long bytePositionInLine = reader.CurrentState._bytePositionInLine;
			text += $" Path: {state.JsonPath()} | LineNumber: {lineNumber} | BytePositionInLine: {bytePositionInLine}.";
			throw new NotSupportedException(text, ex);
		}

		[DoesNotReturn]
		public static void ThrowNotSupportedException(ref WriteStack state, NotSupportedException ex)
		{
			string text = ex.Message;
			Type type = state.Current.DeclaredJsonPropertyInfo?.RuntimePropertyType;
			if (type == null)
			{
				type = state.Current.JsonTypeInfo.Type;
			}
			if (!text.Contains(type.ToString()))
			{
				if (text.Length > 0)
				{
					text += " ";
				}
				text += System.SR.Format(System.SR.SerializationNotSupportedParentType, type);
			}
			text = text + " Path: " + state.PropertyPath() + ".";
			throw new NotSupportedException(text, ex);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_DeserializeNoConstructor(Type type, ref Utf8JsonReader reader, ref ReadStack state)
		{
			string message = ((!type.IsInterface) ? System.SR.Format(System.SR.DeserializeNoConstructor, "JsonConstructorAttribute", type) : System.SR.Format(System.SR.DeserializePolymorphicInterface, type));
			ThrowNotSupportedException(ref state, in reader, new NotSupportedException(message));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_CannotPopulateCollection(Type type, ref Utf8JsonReader reader, ref ReadStack state)
		{
			ThrowNotSupportedException(ref state, in reader, new NotSupportedException(System.SR.Format(System.SR.CannotPopulateCollection, type)));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataValuesInvalidToken(JsonTokenType tokenType)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataInvalidTokenAfterValues, tokenType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataReferenceNotFound(string id)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataReferenceNotFound, id));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataValueWasNotString(JsonTokenType tokenType)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataValueWasNotString, tokenType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataValueWasNotString(JsonValueKind valueKind)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataValueWasNotString, valueKind));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(ReadOnlySpan<byte> propertyName, ref ReadStack state)
		{
			state.Current.JsonPropertyName = propertyName.ToArray();
			ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties()
		{
			ThrowJsonException(System.SR.MetadataReferenceCannotContainOtherProperties);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataIdIsNotFirstProperty(ReadOnlySpan<byte> propertyName, ref ReadStack state)
		{
			state.Current.JsonPropertyName = propertyName.ToArray();
			ThrowJsonException(System.SR.MetadataIdIsNotFirstProperty);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataMissingIdBeforeValues(ref ReadStack state, ReadOnlySpan<byte> propertyName)
		{
			state.Current.JsonPropertyName = propertyName.ToArray();
			ThrowJsonException(System.SR.MetadataPreservedArrayPropertyNotFound);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(ReadOnlySpan<byte> propertyName, ref ReadStack state, in Utf8JsonReader reader)
		{
			if (state.Current.IsProcessingDictionary())
			{
				state.Current.JsonPropertyNameAsString = reader.GetString();
			}
			else
			{
				state.Current.JsonPropertyName = propertyName.ToArray();
			}
			ThrowJsonException(System.SR.MetadataInvalidPropertyWithLeadingDollarSign);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataDuplicateIdFound(string id)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataDuplicateIdFound, id));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataInvalidReferenceToValueType(Type propertyType)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataInvalidReferenceToValueType, propertyType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataPreservedArrayInvalidProperty(ref ReadStack state, Type propertyType, in Utf8JsonReader reader)
		{
			//IL_001f: 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)
			ref ReadStackFrame current = ref state.Current;
			byte[] jsonPropertyName;
			if (!reader.HasValueSequence)
			{
				jsonPropertyName = reader.ValueSpan.ToArray();
			}
			else
			{
				ReadOnlySequence<byte> valueSequence = reader.ValueSequence;
				jsonPropertyName = BuffersExtensions.ToArray<byte>(ref valueSequence);
			}
			current.JsonPropertyName = jsonPropertyName;
			string @string = reader.GetString();
			ThrowJsonException(System.SR.Format(System.SR.MetadataPreservedArrayFailed, System.SR.Format(System.SR.MetadataPreservedArrayInvalidProperty, @string), System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataPreservedArrayValuesNotFound(ref ReadStack state, Type propertyType)
		{
			state.Current.JsonPropertyName = null;
			ThrowJsonException(System.SR.Format(System.SR.MetadataPreservedArrayFailed, System.SR.MetadataPreservedArrayPropertyNotFound, System.SR.Format(System.SR.DeserializeUnableToConvertValue, propertyType)));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowJsonException_MetadataCannotParsePreservedObjectIntoImmutable(Type propertyType)
		{
			ThrowJsonException(System.SR.Format(System.SR.MetadataCannotParsePreservedObjectToImmutable, propertyType));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_MetadataReferenceOfTypeCannotBeAssignedToType(string referenceId, Type currentType, Type typeToConvert)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MetadataReferenceOfTypeCannotBeAssignedToType, referenceId, currentType, typeToConvert));
		}

		[DoesNotReturn]
		internal static void ThrowUnexpectedMetadataException(ReadOnlySpan<byte> propertyName, ref Utf8JsonReader reader, ref ReadStack state)
		{
			if (state.Current.JsonTypeInfo.PropertyInfoForTypeInfo.ConverterBase.ConstructorIsParameterized)
			{
				ThrowNotSupportedException_ObjectWithParameterizedCtorRefMetadataNotHonored(propertyName, ref reader, ref state);
			}
			switch (JsonSerializer.GetMetadataPropertyName(propertyName))
			{
			case MetadataPropertyName.Id:
				ThrowJsonException_MetadataIdIsNotFirstProperty(propertyName, ref state);
				break;
			case MetadataPropertyName.Ref:
				ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(propertyName, ref state);
				break;
			default:
				ThrowJsonException_MetadataInvalidPropertyWithLeadingDollarSign(propertyName, ref state, in reader);
				break;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_JsonSerializerOptionsAlreadyBoundToContext()
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.OptionsAlreadyBoundToContext));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_BuiltInConvertersNotRooted(Type type)
		{
			throw new NotSupportedException(System.SR.Format(System.SR.BuiltInConvertersNotRooted, type));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowNotSupportedException_NoMetadataForType(Type type)
		{
			throw new NotSupportedException(System.SR.Format(System.SR.NoMetadataForType, type));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_NoMetadataForType(Type type)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.NoMetadataForType, type));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowInvalidOperationException_MetadatInitFuncsNull()
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MetadataInitFuncsNull));
		}

		public static void ThrowInvalidOperationException_NoMetadataForTypeProperties(JsonSerializerContext context, Type type)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.NoMetadataForTypeProperties, context.GetType(), type));
		}

		public static void ThrowInvalidOperationException_NoMetadataForTypeCtorParams(JsonSerializerContext context, Type type)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.NoMetadataForTypeCtorParams, context.GetType(), type));
		}

		public static void ThrowInvalidOperationException_NoDefaultOptionsForContext(JsonSerializerContext context, Type type)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.NoDefaultOptionsForContext, context.GetType(), type));
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[DoesNotReturn]
		public static void ThrowMissingMemberException_MissingFSharpCoreMember(string missingFsharpCoreMember)
		{
			throw new MissingMemberException(System.SR.Format(System.SR.MissingFSharpCoreMember, missingFsharpCoreMember));
		}
	}
	internal sealed class JsonCamelCaseNamingPolicy : JsonNamingPolicy
	{
		public override string ConvertName(string name)
		{
			if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0]))
			{
				return name;
			}
			char[] array = name.ToCharArray();
			FixCasing(array);
			return new string(array);
		}

		private static void FixCasing(Span<char> chars)
		{
			for (int i = 0; i < chars.Length && (i != 1 || char.IsUpper(chars[i])); i++)
			{
				bool flag = i + 1 < chars.Length;
				if (i > 0 && flag && !char.IsUpper(chars[i + 1]))
				{
					if (chars[i + 1] == ' ')
					{
						chars[i] = char.ToLowerInvariant(chars[i]);
					}
					break;
				}
				chars[i] = char.ToLowerInvariant(chars[i]);
			}
		}
	}
	public abstract class JsonNamingPolicy
	{
		public static JsonNamingPolicy CamelCase { get; } = new JsonCamelCaseNamingPolicy();


		public abstract string ConvertName(string name);
	}
	internal static class JsonConstants
	{
		public const int MaxParameterCount