| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections.Immutable; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.IO; |
| | | 7 | | using System.Reflection.Internal; |
| | | 8 | | using System.Reflection.Metadata; |
| | | 9 | | using System.Reflection.Metadata.Ecma335; |
| | | 10 | | |
| | | 11 | | namespace System.Reflection.PortableExecutable |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream. |
| | | 15 | | /// </summary> |
| | | 16 | | public sealed class PEHeaders |
| | | 17 | | { |
| | | 18 | | private readonly CoffHeader _coffHeader; |
| | | 19 | | private readonly PEHeader? _peHeader; |
| | | 20 | | private readonly ImmutableArray<SectionHeader> _sectionHeaders; |
| | | 21 | | private readonly CorHeader? _corHeader; |
| | | 22 | | private readonly bool _isLoadedImage; |
| | | 23 | | |
| | 0 | 24 | | private readonly int _metadataStartOffset = -1; |
| | | 25 | | private readonly int _metadataSize; |
| | 0 | 26 | | private readonly int _coffHeaderStartOffset = -1; |
| | 0 | 27 | | private readonly int _corHeaderStartOffset = -1; |
| | 0 | 28 | | private readonly int _peHeaderStartOffset = -1; |
| | | 29 | | |
| | | 30 | | internal const ushort DosSignature = 0x5A4D; // 'M' 'Z' |
| | | 31 | | internal const int PESignatureOffsetLocation = 0x3C; |
| | | 32 | | internal const uint PESignature = 0x00004550; // PE00 |
| | | 33 | | internal const int PESignatureSize = sizeof(uint); |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Reads PE headers from the current location in the stream. |
| | | 37 | | /// </summary> |
| | | 38 | | /// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at th |
| | | 39 | | /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> |
| | | 40 | | /// <exception cref="IOException">Error reading from the stream.</exception> |
| | | 41 | | /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> |
| | | 42 | | /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> |
| | | 43 | | public PEHeaders(Stream peStream) |
| | 0 | 44 | | : this(peStream, 0) |
| | 0 | 45 | | { |
| | 0 | 46 | | } |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Reads PE headers from the current location in the stream. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param |
| | | 52 | | /// <param name="size">Size of the PE image.</param> |
| | | 53 | | /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> |
| | | 54 | | /// <exception cref="IOException">Error reading from the stream.</exception> |
| | | 55 | | /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> |
| | | 56 | | /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> |
| | | 57 | | /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</excep |
| | | 58 | | public PEHeaders(Stream peStream, int size) |
| | 0 | 59 | | : this(peStream, size, isLoadedImage: false) |
| | 0 | 60 | | { |
| | 0 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Reads PE headers from the current location in the stream. |
| | | 65 | | /// </summary> |
| | | 66 | | /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param |
| | | 67 | | /// <param name="size">Size of the PE image.</param> |
| | | 68 | | /// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param> |
| | | 69 | | /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> |
| | | 70 | | /// <exception cref="IOException">Error reading from the stream.</exception> |
| | | 71 | | /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> |
| | | 72 | | /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> |
| | | 73 | | /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</excep |
| | 0 | 74 | | public PEHeaders(Stream peStream, int size, bool isLoadedImage) |
| | 0 | 75 | | { |
| | 0 | 76 | | if (peStream is null) |
| | 0 | 77 | | { |
| | 0 | 78 | | Throw.ArgumentNull(nameof(peStream)); |
| | | 79 | | } |
| | | 80 | | |
| | 0 | 81 | | if (!peStream.CanRead || !peStream.CanSeek) |
| | 0 | 82 | | { |
| | 0 | 83 | | throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); |
| | | 84 | | } |
| | | 85 | | |
| | 0 | 86 | | _isLoadedImage = isLoadedImage; |
| | | 87 | | |
| | 0 | 88 | | int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream)); |
| | 0 | 89 | | var reader = new PEBinaryReader(peStream, actualSize); |
| | | 90 | | |
| | 0 | 91 | | SkipDosHeader(ref reader, out bool isCoffOnly); |
| | | 92 | | |
| | 0 | 93 | | if (isCoffOnly && isLoadedImage) |
| | 0 | 94 | | { |
| | | 95 | | // Only images can be loaded. |
| | 0 | 96 | | throw new BadImageFormatException(SR.InvalidPESignature); |
| | | 97 | | } |
| | | 98 | | |
| | 0 | 99 | | _coffHeaderStartOffset = reader.Offset; |
| | 0 | 100 | | _coffHeader = new CoffHeader(ref reader); |
| | | 101 | | |
| | 0 | 102 | | if (isCoffOnly) |
| | 0 | 103 | | { |
| | | 104 | | // In COFF files the size of the optional header must be zero. |
| | 0 | 105 | | if (_coffHeader.SizeOfOptionalHeader != 0) |
| | 0 | 106 | | { |
| | 0 | 107 | | throw new BadImageFormatException(SR.UnknownFileFormat); |
| | | 108 | | } |
| | 0 | 109 | | } |
| | | 110 | | else |
| | 0 | 111 | | { |
| | 0 | 112 | | _peHeaderStartOffset = reader.Offset; |
| | 0 | 113 | | _peHeader = new PEHeader(ref reader); |
| | 0 | 114 | | } |
| | | 115 | | |
| | 0 | 116 | | _sectionHeaders = ReadSectionHeaders(ref reader, actualSize); |
| | | 117 | | |
| | 0 | 118 | | if (!isCoffOnly) |
| | 0 | 119 | | { |
| | 0 | 120 | | if (TryCalculateCorHeaderOffset(out int offset)) |
| | 0 | 121 | | { |
| | 0 | 122 | | _corHeaderStartOffset = offset; |
| | 0 | 123 | | reader.Offset = offset; |
| | 0 | 124 | | _corHeader = new CorHeader(ref reader); |
| | 0 | 125 | | } |
| | 0 | 126 | | } |
| | | 127 | | |
| | 0 | 128 | | CalculateMetadataLocation(actualSize, out _metadataStartOffset, out _metadataSize); |
| | 0 | 129 | | } |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata. |
| | | 133 | | /// or -1 if the image does not contain metadata. |
| | | 134 | | /// </summary> |
| | | 135 | | public int MetadataStartOffset |
| | | 136 | | { |
| | 0 | 137 | | get { return _metadataStartOffset; } |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | /// <summary> |
| | | 141 | | /// Gets the size of the CLI metadata 0 if the image does not contain metadata.) |
| | | 142 | | /// </summary> |
| | | 143 | | public int MetadataSize |
| | | 144 | | { |
| | 0 | 145 | | get { return _metadataSize; } |
| | | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Gets the COFF header of the image. |
| | | 150 | | /// </summary> |
| | | 151 | | public CoffHeader CoffHeader |
| | | 152 | | { |
| | 0 | 153 | | get { return _coffHeader; } |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Gets the byte offset from the start of the PE image to the start of the COFF header. |
| | | 158 | | /// </summary> |
| | | 159 | | public int CoffHeaderStartOffset |
| | | 160 | | { |
| | 0 | 161 | | get { return _coffHeaderStartOffset; } |
| | | 162 | | } |
| | | 163 | | |
| | | 164 | | /// <summary> |
| | | 165 | | /// Determines if the image is Coff only. |
| | | 166 | | /// </summary> |
| | | 167 | | public bool IsCoffOnly |
| | | 168 | | { |
| | 0 | 169 | | get { return _peHeader == null; } |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary> |
| | | 173 | | /// Gets the PE header of the image or null if the image is COFF only. |
| | | 174 | | /// </summary> |
| | | 175 | | public PEHeader? PEHeader |
| | | 176 | | { |
| | 0 | 177 | | get { return _peHeader; } |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Gets the byte offset from the start of the image to |
| | | 182 | | /// </summary> |
| | | 183 | | public int PEHeaderStartOffset |
| | | 184 | | { |
| | 0 | 185 | | get { return _peHeaderStartOffset; } |
| | | 186 | | } |
| | | 187 | | |
| | | 188 | | /// <summary> |
| | | 189 | | /// Gets the PE section headers. |
| | | 190 | | /// </summary> |
| | | 191 | | public ImmutableArray<SectionHeader> SectionHeaders |
| | | 192 | | { |
| | 0 | 193 | | get { return _sectionHeaders; } |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | /// <summary> |
| | | 197 | | /// Gets the CLI header or null if the image does not have one. |
| | | 198 | | /// </summary> |
| | | 199 | | public CorHeader? CorHeader |
| | | 200 | | { |
| | 0 | 201 | | get { return _corHeader; } |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | /// <summary> |
| | | 205 | | /// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one. |
| | | 206 | | /// </summary> |
| | | 207 | | public int CorHeaderStartOffset |
| | | 208 | | { |
| | 0 | 209 | | get { return _corHeaderStartOffset; } |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | /// <summary> |
| | | 213 | | /// Determines if the image represents a Windows console application. |
| | | 214 | | /// </summary> |
| | | 215 | | public bool IsConsoleApplication |
| | | 216 | | { |
| | | 217 | | get |
| | 0 | 218 | | { |
| | 0 | 219 | | return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui; |
| | 0 | 220 | | } |
| | | 221 | | } |
| | | 222 | | |
| | | 223 | | /// <summary> |
| | | 224 | | /// Determines if the image represents a dynamically linked library. |
| | | 225 | | /// </summary> |
| | | 226 | | public bool IsDll |
| | | 227 | | { |
| | | 228 | | get |
| | 0 | 229 | | { |
| | 0 | 230 | | return (_coffHeader.Characteristics & Characteristics.Dll) != 0; |
| | 0 | 231 | | } |
| | | 232 | | } |
| | | 233 | | |
| | | 234 | | /// <summary> |
| | | 235 | | /// Determines if the image represents an executable. |
| | | 236 | | /// </summary> |
| | | 237 | | public bool IsExe |
| | | 238 | | { |
| | | 239 | | get |
| | 0 | 240 | | { |
| | 0 | 241 | | return (_coffHeader.Characteristics & Characteristics.Dll) == 0; |
| | 0 | 242 | | } |
| | | 243 | | } |
| | | 244 | | |
| | | 245 | | private bool TryCalculateCorHeaderOffset(out int startOffset) |
| | 0 | 246 | | { |
| | 0 | 247 | | if (!TryGetDirectoryOffset(_peHeader!.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: fal |
| | 0 | 248 | | { |
| | 0 | 249 | | startOffset = -1; |
| | 0 | 250 | | return false; |
| | | 251 | | } |
| | | 252 | | |
| | 0 | 253 | | int length = _peHeader.CorHeaderTableDirectory.Size; |
| | 0 | 254 | | if (length < COR20Constants.SizeOfCorHeader) |
| | 0 | 255 | | { |
| | 0 | 256 | | throw new BadImageFormatException(SR.InvalidCorHeaderSize); |
| | | 257 | | } |
| | | 258 | | |
| | 0 | 259 | | return true; |
| | 0 | 260 | | } |
| | | 261 | | |
| | | 262 | | private static void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) |
| | 0 | 263 | | { |
| | | 264 | | // Look for DOS Signature "MZ" |
| | 0 | 265 | | ushort dosSig = reader.ReadUInt16(); |
| | | 266 | | |
| | 0 | 267 | | if (dosSig != DosSignature) |
| | 0 | 268 | | { |
| | | 269 | | // If image doesn't start with DOS signature, let's assume it is a |
| | | 270 | | // COFF (Common Object File Format), aka .OBJ file. |
| | | 271 | | // See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp |
| | | 272 | | |
| | 0 | 273 | | if (dosSig != 0 || reader.ReadUInt16() != 0xffff) |
| | 0 | 274 | | { |
| | 0 | 275 | | isCOFFOnly = true; |
| | 0 | 276 | | reader.Offset = 0; |
| | 0 | 277 | | } |
| | | 278 | | else |
| | 0 | 279 | | { |
| | | 280 | | // Might need to handle other formats. Anonymous or LTCG objects, for example. |
| | 0 | 281 | | throw new BadImageFormatException(SR.UnknownFileFormat); |
| | | 282 | | } |
| | 0 | 283 | | } |
| | | 284 | | else |
| | 0 | 285 | | { |
| | 0 | 286 | | isCOFFOnly = false; |
| | 0 | 287 | | } |
| | | 288 | | |
| | 0 | 289 | | if (!isCOFFOnly) |
| | 0 | 290 | | { |
| | | 291 | | // Skip the DOS Header |
| | 0 | 292 | | reader.Offset = PESignatureOffsetLocation; |
| | | 293 | | |
| | 0 | 294 | | int ntHeaderOffset = reader.ReadInt32(); |
| | 0 | 295 | | reader.Offset = ntHeaderOffset; |
| | | 296 | | |
| | | 297 | | // Look for PESignature "PE\0\0" |
| | 0 | 298 | | uint ntSignature = reader.ReadUInt32(); |
| | 0 | 299 | | if (ntSignature != PESignature) |
| | 0 | 300 | | { |
| | 0 | 301 | | throw new BadImageFormatException(SR.InvalidPESignature); |
| | | 302 | | } |
| | 0 | 303 | | } |
| | 0 | 304 | | } |
| | | 305 | | |
| | | 306 | | private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader, int size) |
| | 0 | 307 | | { |
| | 0 | 308 | | int numberOfSections = _coffHeader.NumberOfSections; |
| | 0 | 309 | | if (numberOfSections < 0 || numberOfSections * SectionHeader.Size > size - reader.Offset) |
| | 0 | 310 | | { |
| | 0 | 311 | | throw new BadImageFormatException(SR.InvalidNumberOfSections); |
| | | 312 | | } |
| | | 313 | | |
| | 0 | 314 | | var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections); |
| | | 315 | | |
| | 0 | 316 | | for (int i = 0; i < numberOfSections; i++) |
| | 0 | 317 | | { |
| | 0 | 318 | | builder.Add(new SectionHeader(ref reader)); |
| | 0 | 319 | | } |
| | | 320 | | |
| | 0 | 321 | | return builder.MoveToImmutable(); |
| | 0 | 322 | | } |
| | | 323 | | |
| | | 324 | | /// <summary> |
| | | 325 | | /// Gets the offset (in bytes) from the start of the image to the given directory data. |
| | | 326 | | /// </summary> |
| | | 327 | | /// <param name="directory">PE directory entry</param> |
| | | 328 | | /// <param name="offset">Offset from the start of the image to the given directory data</param> |
| | | 329 | | /// <returns>True if the directory data is found, false otherwise.</returns> |
| | | 330 | | public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) |
| | 0 | 331 | | { |
| | 0 | 332 | | return TryGetDirectoryOffset(directory, out offset, canCrossSectionBoundary: true); |
| | 0 | 333 | | } |
| | | 334 | | |
| | | 335 | | internal bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset, bool canCrossSectionBoundary) |
| | 0 | 336 | | { |
| | 0 | 337 | | int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); |
| | 0 | 338 | | if (sectionIndex < 0) |
| | 0 | 339 | | { |
| | 0 | 340 | | offset = -1; |
| | 0 | 341 | | return false; |
| | | 342 | | } |
| | | 343 | | |
| | 0 | 344 | | int relativeOffset = directory.RelativeVirtualAddress - _sectionHeaders[sectionIndex].VirtualAddress; |
| | 0 | 345 | | if (!canCrossSectionBoundary && directory.Size > _sectionHeaders[sectionIndex].VirtualSize - relativeOffset) |
| | 0 | 346 | | { |
| | 0 | 347 | | throw new BadImageFormatException(SR.SectionTooSmall); |
| | | 348 | | } |
| | | 349 | | |
| | 0 | 350 | | offset = _isLoadedImage ? directory.RelativeVirtualAddress : _sectionHeaders[sectionIndex].PointerToRawData |
| | 0 | 351 | | return true; |
| | 0 | 352 | | } |
| | | 353 | | |
| | | 354 | | /// <summary> |
| | | 355 | | /// Searches sections of the PE image for the one that contains specified Relative Virtual Address. |
| | | 356 | | /// </summary> |
| | | 357 | | /// <param name="relativeVirtualAddress">Address.</param> |
| | | 358 | | /// <returns> |
| | | 359 | | /// Index of the section that contains <paramref name="relativeVirtualAddress"/>, |
| | | 360 | | /// or -1 if there is none. |
| | | 361 | | /// </returns> |
| | | 362 | | public int GetContainingSectionIndex(int relativeVirtualAddress) |
| | 0 | 363 | | { |
| | 0 | 364 | | for (int i = 0; i < _sectionHeaders.Length; i++) |
| | 0 | 365 | | { |
| | 0 | 366 | | if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && |
| | 0 | 367 | | relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize) |
| | 0 | 368 | | { |
| | 0 | 369 | | return i; |
| | | 370 | | } |
| | 0 | 371 | | } |
| | | 372 | | |
| | 0 | 373 | | return -1; |
| | 0 | 374 | | } |
| | | 375 | | |
| | | 376 | | internal int IndexOfSection(string name) |
| | 0 | 377 | | { |
| | 0 | 378 | | for (int i = 0; i < SectionHeaders.Length; i++) |
| | 0 | 379 | | { |
| | 0 | 380 | | if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) |
| | 0 | 381 | | { |
| | 0 | 382 | | return i; |
| | | 383 | | } |
| | 0 | 384 | | } |
| | | 385 | | |
| | 0 | 386 | | return -1; |
| | 0 | 387 | | } |
| | | 388 | | |
| | | 389 | | private void CalculateMetadataLocation(long peImageSize, out int start, out int size) |
| | 0 | 390 | | { |
| | 0 | 391 | | if (IsCoffOnly) |
| | 0 | 392 | | { |
| | 0 | 393 | | int cormeta = IndexOfSection(".cormeta"); |
| | 0 | 394 | | if (cormeta == -1) |
| | 0 | 395 | | { |
| | 0 | 396 | | start = -1; |
| | 0 | 397 | | size = 0; |
| | 0 | 398 | | return; |
| | | 399 | | } |
| | | 400 | | |
| | 0 | 401 | | start = SectionHeaders[cormeta].PointerToRawData; |
| | 0 | 402 | | size = SectionHeaders[cormeta].SizeOfRawData; |
| | 0 | 403 | | } |
| | 0 | 404 | | else if (_corHeader == null) |
| | 0 | 405 | | { |
| | 0 | 406 | | start = 0; |
| | 0 | 407 | | size = 0; |
| | 0 | 408 | | return; |
| | | 409 | | } |
| | | 410 | | else |
| | 0 | 411 | | { |
| | 0 | 412 | | if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start, canCrossSectionBoundary: false)) |
| | 0 | 413 | | { |
| | 0 | 414 | | throw new BadImageFormatException(SR.MissingDataDirectory); |
| | | 415 | | } |
| | | 416 | | |
| | 0 | 417 | | size = _corHeader.MetadataDirectory.Size; |
| | 0 | 418 | | } |
| | | 419 | | |
| | 0 | 420 | | if (start < 0 || |
| | 0 | 421 | | start >= peImageSize || |
| | 0 | 422 | | size <= 0 || |
| | 0 | 423 | | start > peImageSize - size) |
| | 0 | 424 | | { |
| | 0 | 425 | | throw new BadImageFormatException(SR.InvalidMetadataSectionSpan); |
| | | 426 | | } |
| | 0 | 427 | | } |
| | | 428 | | } |
| | | 429 | | } |
| | | 430 | | |