Skip to content

Commit 0cf91f3

Browse files
committed
Reflection: add PE/COFF magic checking for inspection
When we inspect a binary, verify that it is a PE/COFF binary before trying to interpret it as a PE/COFF binary. This prepares the code for extraction of the file inspection and will permit cross-platform builds to introspect foreign binaries.
1 parent 2f235db commit 0cf91f3

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

include/swift/Reflection/ReflectionContext.h

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ class ReflectionContext
288288
}
289289

290290
#elif defined(_WIN32)
291-
bool addImage(RemoteAddress ImageStart) {
291+
bool readPECOFFSections(RemoteAddress ImageStart) {
292292
auto DOSHdrBuf = this->getReader().readBytes(
293293
ImageStart, sizeof(llvm::object::dos_header));
294294
auto DOSHdr =
@@ -380,6 +380,29 @@ class ReflectionContext
380380
return true;
381381
}
382382

383+
bool addImage(RemoteAddress ImageStart) {
384+
auto Buf = this->getReader().readBytes(ImageStart,
385+
sizeof(llvm::object::dos_header));
386+
if (!Buf)
387+
return false;
388+
389+
auto DOSHdr = reinterpret_cast<const llvm::object::dos_header *>(Buf.get());
390+
if (!(DOSHdr->Magic[0] == 'M' && DOSHdr->Magic[1] == 'Z'))
391+
return false;
392+
393+
auto PEHeaderAddress =
394+
ImageStart.getAddressData() + DOSHdr->AddressOfNewExeHeader;
395+
396+
Buf = this->getReader().readBytes(RemoteAddress(PEHeaderAddress),
397+
sizeof(llvm::COFF::PEMagic));
398+
if (!Buf)
399+
return false;
400+
401+
if (memcmp(Buf.get(), llvm::COFF::PEMagic, sizeof(llvm::COFF::PEMagic)))
402+
return false;
403+
404+
return readPECOFFSections(ImageStart);
405+
}
383406
#else // ELF platforms.
384407
template <typename T> bool readELFSections(RemoteAddress ImageStart) {
385408
auto Buf =

0 commit comments

Comments
 (0)