本文整理汇总了C#中System.Reflection.Metadata.BlobReader类的典型用法代码示例。如果您正苦于以下问题:C# BlobReader类的具体用法?C# BlobReader怎么用?C# BlobReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BlobReader类属于System.Reflection.Metadata命名空间,在下文中一共展示了BlobReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EcmaSignatureParser
// TODO
// bool _hasModifiers;
public EcmaSignatureParser(EcmaModule module, BlobReader reader)
{
_module = module;
_reader = reader;
// _hasModifiers = false;
}
示例2: UncompressSlotMap
private unsafe static ImmutableArray<LocalSlotDebugInfo> UncompressSlotMap(ImmutableArray<byte> compressedSlotMap)
{
if (compressedSlotMap.IsDefaultOrEmpty)
{
return default(ImmutableArray<LocalSlotDebugInfo>);
}
var mapBuilder = ArrayBuilder<LocalSlotDebugInfo>.GetInstance();
int syntaxOffsetBaseline = -1;
fixed (byte* compressedSlotMapPtr = &compressedSlotMap.ToArray()[0])
{
var blobReader = new BlobReader(compressedSlotMapPtr, compressedSlotMap.Length);
while (blobReader.RemainingBytes > 0)
{
byte b = blobReader.ReadByte();
if (b == SyntaxOffsetBaseline)
{
syntaxOffsetBaseline = -blobReader.ReadCompressedInteger();
continue;
}
if (b == 0)
{
// short-lived temp, no info
mapBuilder.Add(new LocalSlotDebugInfo(SynthesizedLocalKind.LoweringTemp, default(LocalDebugId)));
continue;
}
var kind = (SynthesizedLocalKind)((b & 0x3f) - 1);
bool hasOrdinal = (b & (1 << 7)) != 0;
int syntaxOffset;
if (!blobReader.TryReadCompressedInteger(out syntaxOffset))
{
// invalid data
return default(ImmutableArray<LocalSlotDebugInfo>);
}
syntaxOffset += syntaxOffsetBaseline;
int ordinal = 0;
if (hasOrdinal && !blobReader.TryReadCompressedInteger(out ordinal))
{
// invalid data
return default(ImmutableArray<LocalSlotDebugInfo>);
}
mapBuilder.Add(new LocalSlotDebugInfo(kind, new LocalDebugId(syntaxOffset, ordinal)));
}
}
return mapBuilder.ToImmutableAndFree();
}
示例3: UncompressSlotMap
/// <exception cref="InvalidDataException">Invalid data.</exception>
private unsafe static ImmutableArray<LocalSlotDebugInfo> UncompressSlotMap(ImmutableArray<byte> compressedSlotMap)
{
if (compressedSlotMap.IsDefaultOrEmpty)
{
return default(ImmutableArray<LocalSlotDebugInfo>);
}
var mapBuilder = ArrayBuilder<LocalSlotDebugInfo>.GetInstance();
int syntaxOffsetBaseline = -1;
fixed (byte* compressedSlotMapPtr = &compressedSlotMap.ToArray()[0])
{
var blobReader = new BlobReader(compressedSlotMapPtr, compressedSlotMap.Length);
while (blobReader.RemainingBytes > 0)
{
try
{
// Note: integer operations below can't overflow since compressed integers are in range [0, 0x20000000)
byte b = blobReader.ReadByte();
if (b == SyntaxOffsetBaseline)
{
syntaxOffsetBaseline = -blobReader.ReadCompressedInteger();
continue;
}
if (b == 0)
{
// short-lived temp, no info
mapBuilder.Add(new LocalSlotDebugInfo(SynthesizedLocalKind.LoweringTemp, default(LocalDebugId)));
continue;
}
var kind = (SynthesizedLocalKind)((b & 0x3f) - 1);
bool hasOrdinal = (b & (1 << 7)) != 0;
int syntaxOffset = blobReader.ReadCompressedInteger() + syntaxOffsetBaseline;
int ordinal = hasOrdinal ? blobReader.ReadCompressedInteger() : 0;
mapBuilder.Add(new LocalSlotDebugInfo(kind, new LocalDebugId(syntaxOffset, ordinal)));
}
catch (BadImageFormatException)
{
throw CreateInvalidDataException(compressedSlotMap, blobReader.Offset);
}
}
}
return mapBuilder.ToImmutableAndFree();
}
示例4: DecodeType
// cf. MetadataDecoder<>.DecodeTypeOrThrow.
private TypeSignature DecodeType(ref BlobReader signatureReader, SignatureTypeCode typeCode)
{
switch (typeCode)
{
case SignatureTypeCode.TypeHandle:
{
int typeArgumentOffset = 0;
return DecodeType(signatureReader.ReadTypeHandle(), ImmutableArray<TypeSignature>.Empty, ref typeArgumentOffset);
}
case SignatureTypeCode.Array:
{
var elementType = DecodeModifiersAndType(ref signatureReader);
int rank;
int sizes;
signatureReader.TryReadCompressedInteger(out rank);
signatureReader.TryReadCompressedInteger(out sizes);
if (sizes != 0)
{
throw UnhandledMetadata();
}
return new ArrayTypeSignature(elementType, rank);
}
case SignatureTypeCode.SZArray:
{
var elementType = DecodeModifiersAndType(ref signatureReader);
return new ArrayTypeSignature(elementType, 1);
}
case SignatureTypeCode.GenericTypeInstance:
return DecodeGenericTypeInstance(ref signatureReader);
case SignatureTypeCode.Pointer:
{
var pointedAtType = DecodeModifiersAndType(ref signatureReader);
return new PointerTypeSignature(pointedAtType);
}
case SignatureTypeCode.GenericTypeParameter:
return DecodeGenericTypeParameter(ref signatureReader, _allTypeParameters, _containingArity);
case SignatureTypeCode.GenericMethodParameter:
return DecodeGenericTypeParameter(ref signatureReader, _methodTypeParameters, 0);
default:
{
var signature = typeCode.ToSpecialType().GetTypeSignature();
if (signature == null)
{
throw UnhandledMetadata();
}
return signature;
}
}
}
示例5: GetInstructions
public static ILResult GetInstructions(BlobReader reader)
{
var instructions = ImmutableArray.CreateBuilder<Instruction>();
List<int[]> switches = null;
while (reader.RemainingBytes > 0)
{
ushort pos = (ushort)reader.Offset;
byte op0 = reader.ReadByte();
InstrCode code = (InstrCode)(op0 == 0xFE ? unchecked(0xFE00 + reader.ReadByte()) : op0);
OperandType opType = code.GetOperandType();
ulong operand = 0;
if (code == InstrCode.Switch)
{
if (switches == null)
switches = new List<int[]>();
operand = (ulong)switches.Count;
uint branchCount = reader.ReadUInt32();
int[] branches = new int[branchCount];
for (int i = 0; i < branchCount; i++)
{
branches[i] = reader.ReadInt32();
}
switches.Add(branches);
}
else
{
byte operandSize = opType.GetOperandSize();
operand = operandSize == 8 ? reader.ReadUInt64()
: operandSize == 4 ? reader.ReadUInt32()
: operandSize == 2 ? reader.ReadUInt16()
: operandSize == 1 ? (ulong)reader.ReadByte()
: 0;
}
instructions.Add(new Instruction(pos, code, opType, operand));
}
return new ILResult
{
Instructions = instructions.ToImmutable(),
Switches = switches?.ToArray()
};
}
示例6: GetMethodBody
/// <summary>
/// Returns a body block of a method with specified Relative Virtual Address (RVA);
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="peReader"/> is null.</exception>
/// <exception cref="BadImageFormatException">The body is not found in the metadata or is invalid.</exception>
/// <exception cref="InvalidOperationException">Section where the method is stored is not available.</exception>
public static unsafe MethodBodyBlock GetMethodBody(this PEReader peReader, int relativeVirtualAddress)
{
if (peReader == null)
{
throw new ArgumentNullException(nameof(peReader));
}
var block = peReader.GetSectionData(relativeVirtualAddress);
if (block.Length == 0)
{
throw new BadImageFormatException(SR.Format(SR.InvalidMethodRva, relativeVirtualAddress));
}
// Call to validating public BlobReader constructor is by design -- we need to throw PlatformNotSupported on big-endian architecture.
var blobReader = new BlobReader(block.Pointer, block.Length);
return MethodBodyBlock.Create(blobReader);
}
示例7: GetMethodIL
public static unsafe string GetMethodIL(this ImmutableArray<byte> ilArray)
{
var result = new StringBuilder();
fixed (byte* ilPtr = ilArray.ToArray())
{
int offset = 0;
while (true)
{
// skip padding:
while (offset < ilArray.Length && ilArray[offset] == 0)
{
offset++;
}
if (offset == ilArray.Length)
{
break;
}
var reader = new BlobReader(ilPtr + offset, ilArray.Length - offset);
var methodIL = MethodBodyBlock.Create(reader);
if (methodIL == null)
{
result.AppendFormat("<invalid byte 0x{0:X2} at offset {1}>", ilArray[offset], offset);
offset++;
}
else
{
ILVisualizerAsTokens.Instance.DumpMethod(
result,
methodIL.MaxStack,
methodIL.GetILContent(),
ImmutableArray.Create<ILVisualizer.LocalInfo>(),
ImmutableArray.Create<ILVisualizer.HandlerSpan>());
offset += methodIL.Size;
}
}
}
return result.ToString();
}
示例8: BlobReader
public unsafe BlobReader(byte* buffer, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("length");
}
if (buffer == null && length != 0)
{
throw new ArgumentNullException("buffer");
}
// the reader performs little-endian specific operations
if (!BitConverter.IsLittleEndian)
{
throw new PlatformNotSupportedException(MetadataResources.LitteEndianArchitectureRequired);
}
this = new BlobReader(new MemoryBlock(buffer, length));
}
示例9: IndexOfCharacter
private static int IndexOfCharacter(BlobReader blobReader, char ch)
{
// This function is only safe for searching for ascii characters.
Debug.Assert(ch < 127);
unsafe
{
var ptr = blobReader.CurrentPointer;
for (int i = 0, n = blobReader.RemainingBytes; i < n; i++)
{
if (*ptr == ch)
{
return i;
}
ptr++;
}
return -1;
}
}
示例10: DecodeParameter
// cf. MetadataDecoder<>.DecodeParameterOrThrow.
private ParameterSignature DecodeParameter(ref BlobReader signatureReader)
{
bool isByRef = false;
while (true)
{
var typeCode = signatureReader.ReadSignatureTypeCode();
switch (typeCode)
{
case SignatureTypeCode.RequiredModifier:
case SignatureTypeCode.OptionalModifier:
// Skip modifiers.
break;
case SignatureTypeCode.ByReference:
isByRef = true;
break;
default:
var type = DecodeType(ref signatureReader, typeCode);
return new ParameterSignature(type, isByRef);
}
}
}
示例11: ReadDebugDirectoryEntries
internal static ImmutableArray<DebugDirectoryEntry> ReadDebugDirectoryEntries(BlobReader reader)
{
int entryCount = reader.Length / DebugDirectoryEntry.Size;
var builder = ImmutableArray.CreateBuilder<DebugDirectoryEntry>(entryCount);
for (int i = 0; i < entryCount; i++)
{
// Reserved, must be zero.
int characteristics = reader.ReadInt32();
if (characteristics != 0)
{
throw new BadImageFormatException(SR.InvalidDebugDirectoryEntryCharacteristics);
}
uint stamp = reader.ReadUInt32();
ushort majorVersion = reader.ReadUInt16();
ushort minorVersion = reader.ReadUInt16();
var type = (DebugDirectoryEntryType)reader.ReadInt32();
int dataSize = reader.ReadInt32();
int dataRva = reader.ReadInt32();
int dataPointer = reader.ReadInt32();
builder.Add(new DebugDirectoryEntry(stamp, majorVersion, minorVersion, type, dataSize, dataRva, dataPointer));
}
return builder.MoveToImmutable();
}
示例12: ReadDebugDirectory
/// <summary>
/// Reads all Debug Directory table entries.
/// </summary>
/// <exception cref="BadImageFormatException">Bad format of the entry.</exception>
/// <exception cref="IOException">IO error while reading from the underlying stream.</exception>
public unsafe ImmutableArray<DebugDirectoryEntry> ReadDebugDirectory()
{
var debugDirectory = PEHeaders.PEHeader.DebugTableDirectory;
if (debugDirectory.Size == 0)
{
return ImmutableArray<DebugDirectoryEntry>.Empty;
}
int position;
if (!PEHeaders.TryGetDirectoryOffset(debugDirectory, out position))
{
throw new BadImageFormatException(SR.InvalidDirectoryRVA);
}
if (debugDirectory.Size % DebugDirectoryEntry.Size != 0)
{
throw new BadImageFormatException(SR.InvalidDirectorySize);
}
using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(position, debugDirectory.Size))
{
var reader = new BlobReader(block.Pointer, block.Size);
return ReadDebugDirectoryEntries(reader);
}
}
示例13: MetadataReader
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain
/// metadata from a PE image.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is not positive.</exception>
/// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception>
/// <exception cref="ArgumentException">The encoding of <paramref name="utf8Decoder"/> is not <see cref="UTF8Encoding"/>.</exception>
/// <exception cref="PlatformNotSupportedException">The current platform is big-endian.</exception>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder)
{
// Do not throw here when length is 0. We'll throw BadImageFormatException later on, so that the caller doesn't need to
// worry about the image (stream) being empty and can handle all image errors by catching BadImageFormatException.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
if (utf8Decoder == null)
{
utf8Decoder = MetadataStringDecoder.DefaultUTF8;
}
if (!(utf8Decoder.Encoding is UTF8Encoding))
{
throw new ArgumentException(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder));
}
if (!BitConverter.IsLittleEndian)
{
Throw.LitteEndianArchitectureRequired();
}
this.Block = new MemoryBlock(metadata, length);
_options = options;
this.UTF8Decoder = utf8Decoder;
var headerReader = new BlobReader(this.Block);
this.ReadMetadataHeader(ref headerReader, out _versionString);
_metadataKind = GetMetadataKind(_versionString);
var streamHeaders = this.ReadStreamHeaders(ref headerReader);
// storage header and stream headers:
MemoryBlock metadataTableStream;
MemoryBlock standalonePdbStream;
this.InitializeStreamReaders(ref this.Block, streamHeaders, out _metadataStreamKind, out metadataTableStream, out standalonePdbStream);
int[] externalTableRowCountsOpt;
if (standalonePdbStream.Length > 0)
{
ReadStandalonePortablePdbStream(standalonePdbStream, out _debugMetadataHeader, out externalTableRowCountsOpt);
}
else
{
externalTableRowCountsOpt = null;
}
var tableReader = new BlobReader(metadataTableStream);
HeapSizes heapSizes;
int[] metadataTableRowCounts;
this.ReadMetadataTableHeader(ref tableReader, out heapSizes, out metadataTableRowCounts, out _sortedTables);
this.InitializeTableReaders(tableReader.GetMemoryBlockAt(0, tableReader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCountsOpt);
// This previously could occur in obfuscated assemblies but a check was added to prevent
// it getting to this point
Debug.Assert(this.AssemblyTable.NumberOfRows <= 1);
// Although the specification states that the module table will have exactly one row,
// the native metadata reader would successfully read files containing more than one row.
// Such files exist in the wild and may be produced by obfuscators.
if (standalonePdbStream.Length == 0 && this.ModuleTable.NumberOfRows < 1)
{
throw new BadImageFormatException(SR.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows));
}
// read
this.NamespaceCache = new NamespaceCache(this);
if (_metadataKind != MetadataKind.Ecma335)
{
this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection();
}
}
示例14: ReadStandalonePortablePdbStream
// internal for testing
internal static void ReadStandalonePortablePdbStream(MemoryBlock block, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts)
{
var reader = new BlobReader(block);
const int PdbIdSize = 20;
byte[] pdbId = reader.ReadBytes(PdbIdSize);
// ECMA-335 15.4.1.2:
// The entry point to an application shall be static.
// This entry point method can be a global method or it can appear inside a type.
// The entry point method shall either accept no arguments or a vector of strings.
// The return type of the entry point method shall be void, int32, or unsigned int32.
// The entry point method cannot be defined in a generic class.
uint entryPointToken = reader.ReadUInt32();
int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask);
if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0))
{
throw new BadImageFormatException(string.Format(SR.InvalidEntryPointToken, entryPointToken));
}
ulong externalTableMask = reader.ReadUInt64();
// EnC & Ptr tables can't be referenced from standalone PDB metadata:
const ulong validTables = (ulong)TableMask.ValidPortablePdbExternalTables;
if ((externalTableMask & ~validTables) != 0)
{
throw new BadImageFormatException(string.Format(SR.UnknownTables, (TableMask)externalTableMask));
}
externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask);
debugMetadataHeader = new DebugMetadataHeader(
ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref pdbId),
MethodDefinitionHandle.FromRowId(entryPointRowId));
}
示例15: ReadMetadataTableRowCounts
private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask)
{
ulong currentTableBit = 1;
var rowCounts = new int[MetadataTokens.TableCount];
for (int i = 0; i < rowCounts.Length; i++)
{
if ((presentTableMask & currentTableBit) != 0)
{
if (memReader.RemainingBytes < sizeof(uint))
{
throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall);
}
uint rowCount = memReader.ReadUInt32();
if (rowCount > TokenTypeIds.RIDMask)
{
throw new BadImageFormatException(SR.Format(SR.InvalidRowCount, rowCount));
}
rowCounts[i] = (int)rowCount;
}
currentTableBit <<= 1;
}
return rowCounts;
}