ELF, modules: Bound header fields before using them

- ElfReader: do the relocation segment and table bounds checks in 64 bits
  (p_offset + p_filesz wrapped, and relocations were read gigabytes past the
  file), range-check R_MIPS_32's four bytes, require section names to end
  inside the file, and check the Rel2 field widths fit the 16-bit commands.
- Pair HI16 relocations with their LO16 in linear time, and cap the total
  relocation data processed at the file size. Several sections can point at
  the same table, and a table of only HI16s was quadratic.
- PRX: reject decrypted sizes larger than the input, and check the KIRK input
  (which starts past the header) fits rather than only the output.
- Module loading: cap elf_size before allocating, zero the buffer, give gzip
  the real input length, range-check the module info, export entries and
  their NID tables and thread parameters instead of their first byte, and
  don't trust header names to be terminated.
- PBP modules need the offsets that are read, sceKernelLoadModuleByID copes
  with a seek past the end, and sceKernelLoadModuleBufferUsbWlan checks the
  buffer.
- ParamSFO: table offset math in 64 bits (wrapped on 32-bit hosts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Henrik RydgårdandClaude Opus 5.5 committed 2026-11-05 12:07:13 +01:00
1 parent 3413784d8e
commit 56cf35ac95
5 files changed
+191 -93

No files matched your search

+90 -45
View File
@@ -15,6 +15,9 @@
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#include <algorithm>
#include <cstring>
#include "Common/StringUtils.h"
#include "Common/Data/Text/Demangle.h"
#include "Common/File/DirListing.h"
@@ -42,11 +45,15 @@ const char *ElfReader::GetSectionName(int section) const {
return nullptr;
}
const char *ptr = (const char *)GetSectionDataPtr(header->e_shstrndx);
if (ptr)
return ptr + nameOffset;
else
if (!ptr)
return nullptr;
// The name has to end before the file does.
const size_t maxLen = size_ - ((size_t)nameOffset + stringsOffset);
if (strnlen(ptr + nameOffset, maxLen) == maxLen) {
ERROR_LOG(Log::Loader, "ELF: Unterminated name in section %d", section);
return nullptr;
}
return ptr + nameOffset;
}
void addrToHiLo(u32 addr, u16 &hi, s16 &lo)
@@ -63,13 +70,51 @@ void addrToHiLo(u32 addr, u16 &hi, s16 &lo)
}
}
bool ElfReader::ConsumeRelocBudget(u64 bytes) {
relocBytesProcessed_ += bytes;
if (relocBytesProcessed_ > size_) {
ERROR_LOG_REPORT(Log::Loader, "ELF: More relocation data than the file holds, ignoring the rest");
return false;
}
return true;
}
bool ElfReader::LoadRelocations(const Elf32_Rel *rels, int numRelocs) {
if (numRelocs <= 0)
return true;
if (!ConsumeRelocBudget((u64)numRelocs * sizeof(Elf32_Rel)))
return false;
std::vector<u32> relocOps;
relocOps.resize(numRelocs);
DEBUG_LOG(Log::Loader, "Loading %i relocations...", numRelocs);
int numErrors = 0;
// A HI16 pairs with the next relocation that can serve as its LO16, skipping other HI16s.
// Whether one can doesn't depend on the HI16, so find them all in one backward pass, rather
// than scanning forward from every HI16 (quadratic, with a table of only HI16s).
auto isLoCandidate = [&](int t) {
int t_type = rels[t].r_info & 0xF;
// In MotorStorm: Arctic Edge (US), these are sometimes R_MIPS_16 (instead of LO16.)
// It appears the PSP takes any relocation that is not a HI16, but let's play it safe and
// skip the others, we've only seen R_MIPS_16.
if (t_type != R_MIPS_LO16 && t_type != R_MIPS_16)
return false;
// The candidate LO16 declares its own segment - use that rather than the HI16's,
// which is what the mismatch warning further down is there to detect.
int t_readwrite = (rels[t].r_info >> 8) & 0xff;
if (!SegmentIsLoaded(t_readwrite))
return false;
return Memory::IsValidAddress(rels[t].r_offset + segmentVAddr[t_readwrite]);
};
std::vector<int> nextLo(numRelocs + 1, -1);
for (int t = numRelocs - 1; t >= 0; t--) {
nextLo[t] = isLoCandidate(t) ? t : nextLo[t + 1];
}
// Relocations up to here have already been logged as skipped by an earlier HI16.
int loggedSkipsUpTo = 0;
{
for (int r = 0; r < numRelocs; r++) {
u32 info = rels[r].r_info;
@@ -97,8 +142,8 @@ bool ElfReader::LoadRelocations(const Elf32_Rel *rels, int numRelocs) {
addr += segmentVAddr[readwrite];
// It appears that misaligned relocations are allowed.
if (((addr & 3) && type != R_MIPS_32) || !Memory::IsValidAddress(addr)) {
// It appears that misaligned relocations are allowed. We read and write 4 bytes either way.
if (((addr & 3) && type != R_MIPS_32) || !Memory::IsValidRange(addr, 4)) {
if (numErrors < 10) {
WARN_LOG_REPORT(Log::Loader, "Suspicious address %08x, skipping reloc, type = %d", addr, type);
} else if (numErrors == 10) {
@@ -128,7 +173,7 @@ bool ElfReader::LoadRelocations(const Elf32_Rel *rels, int numRelocs) {
}
addr += segmentVAddr[readwrite];
if (((addr & 3) && type != R_MIPS_32) || !Memory::IsValidAddress(addr)) {
if (((addr & 3) && type != R_MIPS_32) || !Memory::IsValidRange(addr, 4)) {
continue;
}
@@ -164,31 +209,29 @@ bool ElfReader::LoadRelocations(const Elf32_Rel *rels, int numRelocs) {
u32 cur = (op & 0xFFFF) << 16;
u16 hi = 0;
bool found = false;
for (int t = r + 1; t < numRelocs; t++) {
int t_type = rels[t].r_info & 0xF;
if (t_type == R_MIPS_HI16)
const int t = nextLo[r + 1];
const int skipEnd = t < 0 ? numRelocs : t;
for (int s = std::max(r + 1, loggedSkipsUpTo); s < skipEnd; s++) {
int s_type = rels[s].r_info & 0xF;
int s_readwrite = (rels[s].r_info >> 8) & 0xff;
if (s_type == R_MIPS_HI16 || !SegmentIsLoaded(s_readwrite))
continue;
// The candidate LO16 declares its own segment - use that rather than the HI16's,
// which is what the mismatch warning further down is there to detect.
u32 skippedAddr = rels[s].r_offset + segmentVAddr[s_readwrite];
if (s_type != R_MIPS_LO16 && s_type != R_MIPS_16) {
// These exists in some popular games like Assassin's Creed: Bloodlines and GTA: VCS: (https://report.ppsspp.org/logs/kind/1187)
ERROR_LOG_REPORT(Log::Loader, "ELF relocation HI16/%d pair (instead of LO16) at %08x / %08x", s_type, addr, skippedAddr);
} else {
ERROR_LOG(Log::Loader, "Bad corrLoAddr %08x", skippedAddr);
}
}
loggedSkipsUpTo = std::max(loggedSkipsUpTo, skipEnd);
if (t >= 0) {
int t_type = rels[t].r_info & 0xF;
int t_readwrite = (rels[t].r_info >> 8) & 0xff;
if (!SegmentIsLoaded(t_readwrite))
continue;
u32 corrLoAddr = rels[t].r_offset + segmentVAddr[t_readwrite];
// In MotorStorm: Arctic Edge (US), these are sometimes R_MIPS_16 (instead of LO16.)
// It appears the PSP takes any relocation that is not a HI16.
if (t_type != R_MIPS_LO16) {
if (t_type != R_MIPS_16) {
// Let's play it safe for now and skip. We've only seen this type.
// These exists in some popular games like Assassin's Creed: Bloodlines and GTA: VCS: (https://report.ppsspp.org/logs/kind/1187)
ERROR_LOG_REPORT(Log::Loader, "ELF relocation HI16/%d pair (instead of LO16) at %08x / %08x", t_type, addr, corrLoAddr);
continue;
} else {
WARN_LOG_REPORT(Log::Loader, "ELF relocation HI16/%d(16) pair (instead of LO16) at %08x / %08x", t_type, addr, corrLoAddr);
}
if (t_type == R_MIPS_16) {
WARN_LOG_REPORT(Log::Loader, "ELF relocation HI16/%d(16) pair (instead of LO16) at %08x / %08x", t_type, addr, corrLoAddr);
}
// Should have matching index and segment info, according to llvm, which makes sense.
if ((rels[t].r_info >> 8) != (rels[r].r_info >> 8)) {
WARN_LOG_REPORT(Log::Loader, "ELF relocation HI16/LO16 with mismatching r_info lo=%08x, hi=%08x", rels[t].r_info, rels[r].r_info);
@@ -196,16 +239,11 @@ bool ElfReader::LoadRelocations(const Elf32_Rel *rels, int numRelocs) {
if (log) {
DEBUG_LOG(Log::Loader, "Corresponding lo found at %08x", corrLoAddr);
}
if (Memory::IsValidAddress(corrLoAddr)) {
s16 lo = (s16)relocOps[t];
cur += lo;
cur += relocateTo;
addrToHiLo(cur, hi, lo);
found = true;
break;
} else {
ERROR_LOG(Log::Loader, "Bad corrLoAddr %08x", corrLoAddr);
}
s16 lo = (s16)relocOps[t];
cur += lo;
cur += relocateTo;
addrToHiLo(cur, hi, lo);
found = true;
}
if (found) {
op = (op & 0xFFFF0000) | hi;
@@ -289,6 +327,8 @@ void ElfReader::LoadRelocations2(int rel_seg)
ERROR_LOG_REPORT(Log::Loader, "Rel2 segment extends past the end of the file");
return;
}
if (!ConsumeRelocBudget(ph->p_filesz))
return;
end = buf+ph->p_filesz;
// Everything below reads forward from buf, so check there's something there each time. All of
@@ -311,6 +351,12 @@ void ElfReader::LoadRelocations2(int rel_seg)
while((1<<seg_bits)<rel_seg)
seg_bits += 1;
// The three fields are packed into 16-bit commands, and the shifts below assume they fit.
if (flag_bits + seg_bits + type_bits > 16) {
ERROR_LOG_REPORT(Log::Loader, "Rel2: bad field sizes %d/%d/%d", flag_bits, seg_bits, type_bits);
return;
}
buf += 4;
// Both tables are prefixed by their own size, and are indexed by bitfields out of the command
@@ -522,13 +568,12 @@ void ElfReader::LoadRelocations2(int rel_seg)
int ElfReader::LoadInto(u32 loadAddress, bool fromTop) {
DEBUG_LOG(Log::Loader,"String section: %i", header->e_shstrndx);
if (size_ < sizeof(Elf32_Ehdr)) {
ERROR_LOG(Log::Loader, "Truncated ELF header, %d bytes", (int)size_);
// Probably not the right error code.
return SCE_KERNEL_ERROR_MEMBLOCK_ALLOC_FAILED;
}
DEBUG_LOG(Log::Loader,"String section: %i", header->e_shstrndx);
if (header->e_ident[0] != ELFMAG0 || header->e_ident[1] != ELFMAG1
|| header->e_ident[2] != ELFMAG2 || header->e_ident[3] != ELFMAG3)
@@ -546,14 +591,14 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop) {
if (header->e_ident[EI_DATA] != ELFDATA2LSB)
return SCE_KERNEL_ERROR_MEMBLOCK_ALLOC_FAILED;
const size_t phdrEnd = header->e_phoff + sizeof(Elf32_Phdr) * GetNumSegments();
const size_t shdrEnd = header->e_shoff + sizeof(Elf32_Shdr) * GetNumSections();
const u64 phdrEnd = (u64)header->e_phoff + sizeof(Elf32_Phdr) * GetNumSegments();
const u64 shdrEnd = (u64)header->e_shoff + sizeof(Elf32_Shdr) * GetNumSections();
if (size_ < phdrEnd || size_ < shdrEnd) {
// Say which table runs off the end and by how much. "Truncated ELF" on its own sends you
// looking at the executable, when the usual cause is that we were handed fewer bytes than
// the file really has - a short read, or a size clamped somewhere upstream.
const char *which = size_ < phdrEnd ? "program header table" : "section header table";
const size_t needed = size_ < phdrEnd ? phdrEnd : shdrEnd;
const u64 needed = size_ < phdrEnd ? phdrEnd : shdrEnd;
loadError_ = StringFromFormat(
"Truncated ELF: %s ends at %d but only %d bytes are available (%d short), %d sections, %d segments",
which, (int)needed, (int)size_, (int)(needed - size_), GetNumSections(), GetNumSegments());
@@ -793,7 +838,7 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop) {
int numRelocs = s->sh_size / sizeof(Elf32_Rel);
Elf32_Rel *rels = (Elf32_Rel *)GetSectionDataPtr(i);
if (GetSectionDataOffset(i) + sizeof(Elf32_Rel) * numRelocs > size_)
if ((u64)GetSectionDataOffset(i) + sizeof(Elf32_Rel) * (u64)numRelocs > size_)
rels = nullptr;
DEBUG_LOG(Log::Loader,"%s: Performing %i relocations on %s : offset = %08x", name, numRelocs, GetSectionName(sectionToModify), sections[i].sh_offset);
@@ -845,7 +890,7 @@ int ElfReader::LoadInto(u32 loadAddress, bool fromTop) {
int numRelocs = p->p_filesz / sizeof(Elf32_Rel);
Elf32_Rel *rels = (Elf32_Rel *)GetSegmentPtr(i);
if (p->p_offset + p->p_filesz > size_)
if ((u64)p->p_offset + p->p_filesz > size_)
rels = nullptr;
if (!rels || !LoadRelocations(rels, numRelocs)) {
ERROR_LOG(Log::Loader, "LoadInto: Relocs failed, trying anyway (2)");
+4
View File
@@ -202,6 +202,10 @@ private:
// array that callers are trusted to stay inside.
std::vector<u32> segmentVAddr;
size_t size_ = 0;
// Relocation data processed so far. Several relocation sections or segments can point at the
// same table, so this is capped at the file size to keep the total work linear.
u64 relocBytesProcessed_ = 0;
bool ConsumeRelocBudget(u64 bytes);
u32 firstSegAlign = 0;
std::string loadError_;
};
+14 -13
View File
@@ -146,7 +146,7 @@ bool ParamSFOData::ReadSFO(const u8 *paramsfo, size_t size) {
// The index table itself must fit entirely within the buffer before we
// can dereference entries; otherwise indexTables[i] reads out of bounds.
if (sizeof(Header) + (size_t)header->index_table_entries * sizeof(IndexTable) > size) {
if (sizeof(Header) + (u64)header->index_table_entries * sizeof(IndexTable) > size) {
return false;
}
@@ -172,15 +172,17 @@ bool ParamSFOData::ReadSFO(const u8 *paramsfo, size_t size) {
for (u32 i = 0; i < header->index_table_entries; i++)
{
size_t key_offset = header->key_table_start + indexTables[i].key_table_offset;
if (key_offset >= size) {
const u64 key_offset64 = (u64)header->key_table_start + indexTables[i].key_table_offset;
if (key_offset64 >= size) {
return false;
}
const size_t key_offset = (size_t)key_offset64;
size_t data_offset = header->data_table_start + indexTables[i].data_table_offset;
if (data_offset >= size) {
const u64 data_offset64 = (u64)header->data_table_start + indexTables[i].data_table_offset;
if (data_offset64 >= size) {
return false;
}
const size_t data_offset = (size_t)data_offset64;
std::string key = readStringCapped(key_offset, 0);
if (key.empty())
@@ -200,7 +202,7 @@ bool ParamSFOData::ReadSFO(const u8 *paramsfo, size_t size) {
case 0x0004:
// Special format UTF-8
{
if (data_offset + indexTables[i].param_len > size)
if ((u64)data_offset + indexTables[i].param_len > size)
continue;
const u8 *utfdata = (const u8 *)(paramsfo + data_offset);
VERBOSE_LOG(Log::Loader, "%s %s", key.c_str(), utfdata);
@@ -242,7 +244,7 @@ int ParamSFOData::GetDataOffset(const u8 *paramsfo, size_t size, const char *dat
WARN_LOG(Log::Loader, "Unexpected SFO header version: %08x", header->version);
// Both the index table and the key/data tables must fit in the buffer.
if (sizeof(Header) + (size_t)header->index_table_entries * sizeof(IndexTable) > size)
if (sizeof(Header) + (u64)header->index_table_entries * sizeof(IndexTable) > size)
return -1;
if (header->key_table_start > size || header->data_table_start > size)
return -1;
@@ -254,19 +256,18 @@ int ParamSFOData::GetDataOffset(const u8 *paramsfo, size_t size, const char *dat
for (u32 i = 0; i < header->index_table_entries; i++)
{
// In size_t throughout - these are u32s from the file, and mixing them with int meant the
// bounds check below was done in whatever type the promotion landed on. ReadSFO does the
// same arithmetic this way.
size_t key_offset = header->key_table_start + indexTables[i].key_table_offset;
// In u64 - these are u32s from the file, and the sums can wrap a 32-bit size_t.
// ReadSFO does the same arithmetic this way.
const u64 key_offset = (u64)header->key_table_start + indexTables[i].key_table_offset;
if (key_offset >= size)
continue;
size_t data_offset = data_start + indexTables[i].data_table_offset;
const u64 data_offset = (u64)data_start + indexTables[i].data_table_offset;
if (data_offset >= size)
continue;
const char *key = (const char *)(key_start + indexTables[i].key_table_offset);
// Ensure the key string is NUL-terminated within the buffer before strcmp.
if (strnlen(key, size - key_offset) == size - key_offset)
if (strnlen(key, (size_t)(size - key_offset)) == size - key_offset)
continue;
if (!strcmp(key, dataName))
{
+18 -7
View File
@@ -972,7 +972,7 @@ static int pspDecryptType0(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 siz
memcpy(reinterpret_cast<u8*>(header)+sizeof(KIRK_CMD1_HEADER), type0.prxHeader, sizeof(type0.prxHeader));
decryptKirkHeaderType0(reinterpret_cast<u8*>(header), type0.kirkBlock, xorbuf, pti->code);
if (!KirkOutputFits(header, size))
if (!KirkOutputFits(header, size - offset))
{
return -5;
}
@@ -1031,7 +1031,7 @@ static int pspDecryptType1(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 siz
memcpy(reinterpret_cast<u8*>(header)+sizeof(KIRK_CMD1_HEADER), type1.prxHeader, sizeof(type1.prxHeader));
decryptKirkHeaderType0(reinterpret_cast<u8*>(header), type1.kirkBlock, xorbuf, pti->code);
if (!KirkOutputFits(header, size))
if (!KirkOutputFits(header, size - offset))
{
return -5;
}
@@ -1099,7 +1099,7 @@ static int pspDecryptType2(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 siz
decryptKirkHeader(reinterpret_cast<u8*>(header), type2.kirkHeader, xorbuf.cbegin()+0x10, pti->code);
header->mode = 1;
if (!KirkOutputFits(header, size))
if (!KirkOutputFits(header, size - offset))
{
return -5;
}
@@ -1150,7 +1150,7 @@ static int pspFinishType5(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 size
decryptKirkHeader(reinterpret_cast<u8*>(header), type5.kirkHeader, xorbuf.cbegin()+0x10, code);
header->mode = 1;
if (!KirkOutputFits(header, size))
if (!KirkOutputFits(header, size - offset))
{
return -5;
}
@@ -1275,7 +1275,7 @@ static int pspDecryptType6(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 siz
header->mode = 1;
header->ecdsa_hash = 1;
if (!KirkOutputFits(header, size))
if (!KirkOutputFits(header, size - offset))
{
return -5;
}
@@ -1352,7 +1352,7 @@ static int pspDecryptType9(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 siz
// branch only writes the mode word and zeroes the rest of that region.
header->ecdsa_hash = 0;
if (!KirkOutputFits(header, size))
if (!KirkOutputFits(header, size - offset))
{
return -5;
}
@@ -1365,7 +1365,7 @@ static int pspDecryptType9(KirkState *kirk, const u8 *inbuf, u8 *outbuf, u32 siz
return decryptSize;
}
int pspDecryptPRX(const u8 *inbuf, u8 *outbuf, u32 size, const u8 *seed, const u32 *fuseId)
static int pspDecryptPRXAnyType(const u8 *inbuf, u8 *outbuf, u32 size, const u8 *seed, const u32 *fuseId)
{
// Every type below reads the tag at 0xD0, the size at 0xB0 and key data as far as 0x150, and
// writes a KIRK header into outbuf at a fixed offset derived from sizeof(PSP_Header). Without
@@ -1423,6 +1423,17 @@ int pspDecryptPRX(const u8 *inbuf, u8 *outbuf, u32 size, const u8 *seed, const u
return pspDecryptType9(&kirk, inbuf, outbuf, size);
}
int pspDecryptPRX(const u8 *inbuf, u8 *outbuf, u32 size, const u8 *seed, const u32 *fuseId)
{
const int res = pspDecryptPRXAnyType(inbuf, outbuf, size, seed, fuseId);
// The decrypted size comes from the header, and callers size their reads of outbuf by it.
if (res > 0 && (u32)res > size) {
ERROR_LOG(Log::Loader, "PRX claims a decrypted size of %d, larger than its %d bytes", res, (int)size);
return -1;
}
return res;
}
bool pspUnwrapDNASPGD(std::vector<u8> &data, const u8 *secureId, const u32 *fuseId)
{
if (data.size() < 0x90 || memcmp(data.data(), "\0PGD", 4) != 0) {
+65 -28
View File
@@ -1256,14 +1256,14 @@ static bool KernelImportModuleFuncs(PSPModule *module, u32 *firstImportStubAddr,
return true;
}
static int gzipDecompress(u8 *OutBuffer, int OutBufferLength, u8 *InBuffer) {
static int gzipDecompress(u8 *OutBuffer, int OutBufferLength, const u8 *InBuffer, int InBufferLength) {
int err;
z_stream stream;
u8 *outBufferPtr;
outBufferPtr = OutBuffer;
stream.next_in = InBuffer;
stream.avail_in = (uInt)OutBufferLength;
stream.next_in = (Bytef *)InBuffer;
stream.avail_in = (uInt)InBufferLength;
stream.next_out = outBufferPtr;
stream.avail_out = (uInt)OutBufferLength;
stream.zalloc = (alloc_func)0;
@@ -1629,7 +1629,8 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
if (Read32(ptr) == SCE_MAGIC) { // "~SCE"
const u32 headerSize = *(const u32_le*)(ptr + 4);
if (headerSize < elfSize) {
// Leave at least the magic read below.
if (headerSize < elfSize && elfSize - headerSize >= 4) {
// Parse and print the lib info
parsePrxLibInfo(ptr, headerSize);
@@ -1646,11 +1647,13 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
DEBUG_LOG(Log::sceModule, "Decrypting ~PSP file");
head = (const PSP_Header *)ptr;
devkitVersion = head->devkitversion;
// Not necessarily terminated.
const std::string headModName(head->modname, strnlen(head->modname, sizeof(head->modname)));
bool wasDisabled;
if (ShouldHLEModuleForLoad(head->modname, &wasDisabled)) {
if (ShouldHLEModuleForLoad(headModName, &wasDisabled)) {
int ver = (head->module_ver_hi << 8) | head->module_ver_lo;
INFO_LOG(Log::sceModule, "Loading module %s with version %04x, devkit %08x, crc %x", head->modname, ver, head->devkitversion, module->crc);
INFO_LOG(Log::sceModule, "Loading module %s with version %04x, devkit %08x, crc %x", headModName.c_str(), ver, head->devkitversion, module->crc);
// TODO: Don't conflate these!
reportedModule = true;
@@ -1658,7 +1661,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
}
if (wasDisabled) {
g_OSD.Show(OSDType::MESSAGE_WARNING, StringFromFormat("HLE for '%s' has been manually disabled", head->modname));
g_OSD.Show(OSDType::MESSAGE_WARNING, StringFromFormat("HLE for '%s' has been manually disabled", headModName.c_str()));
}
const u8 *in = ptr;
const bool isCompressed = (head->comp_attribute & 1) != 0;
@@ -1673,7 +1676,17 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
return nullptr;
}
const auto maxElfSize = std::max(head->elf_size, head->psp_size);
newptr = new u8[maxElfSize];
// elf_size isn't bounded by anything else. Nothing this big fits in PSP RAM.
if (maxElfSize > 64 * 1024 * 1024) {
*error_string = StringFromFormat("ELF/PRX corrupt, unreasonable size: %u", (u32)maxElfSize);
module->Cleanup();
kernelObjects.Destroy<PSPModule>(module->GetUID());
error = SCE_KERNEL_ERROR_FILEERR;
return nullptr;
}
// Zeroed, since decryption and decompression can fill less than all of it and the ELF
// reader is handed the whole buffer.
newptr = new u8[maxElfSize]();
elfSize = maxElfSize;
ptr = newptr;
int decryptedSize = pspDecryptPRX(in, (u8*)ptr, head->psp_size, prxSeed, fuseId);
@@ -1722,13 +1735,13 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
} else {
scheme = "gzip";
_dbg_assert_(Read32(ptr + 0x150) != ELF_MAGIC);
outBytes = gzipDecompress((u8 *)ptr, maxElfSize, temp);
outBytes = gzipDecompress((u8 *)ptr, maxElfSize, temp, decryptedSize);
}
free(temp);
if (outBytes < 0) {
// Bail out cleanly rather than falling through to parse whatever's left in the
// buffer (still compressed, not a valid ELF) as if it were real code.
*error_string = StringFromFormat("Module '%s' %s decompression failed", head->modname, scheme);
*error_string = StringFromFormat("Module '%s' %s decompression failed", headModName.c_str(), scheme);
delete [] newptr;
module->Cleanup();
kernelObjects.Destroy<PSPModule>(module->GetUID());
@@ -1736,7 +1749,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
error = SCE_KERNEL_ERROR_FILEERR;
return nullptr;
}
INFO_LOG(Log::sceModule, "'%s' is %s-compressed, decompressing (%d -> %d bytes, bufmax=%d).", head->modname, scheme, decryptedSize, outBytes, maxElfSize);
INFO_LOG(Log::sceModule, "'%s' is %s-compressed, decompressing (%d -> %d bytes, bufmax=%d).", headModName.c_str(), scheme, decryptedSize, outBytes, maxElfSize);
}
if (fakeLoadedModule) {
@@ -1745,7 +1758,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
std::string elfFilename(KeepAfterLast(filename, '/'));
if (elfFilename.empty() || startsWith(elfFilename, "sce_lbn")) {
// Use the name from the header.
elfFilename = head->modname;
elfFilename = headModName;
}
DumpFileIfEnabled(ptr, (u32)elfSize, elfFilename.c_str(), DumpFileType::PRX);
@@ -1884,7 +1897,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
else
modinfoaddr = reader.GetSegmentVaddr(0) + (reader.GetSegmentPaddr(0) & 0x7FFFFFFF) - reader.GetSegmentOffset(0);
if (!Memory::IsValidAddress(modinfoaddr)) {
if (!Memory::IsValidRange(modinfoaddr, sizeof(PspModuleInfo))) {
*error_string = StringFromFormat("Bad module info address %08x", modinfoaddr);
ERROR_LOG(Log::sceModule, "Bad module info address %08x", modinfoaddr);
delete[] newptr;
@@ -1895,6 +1908,8 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
}
modinfo = (const PspModuleInfo *)Memory::GetPointerUnchecked(modinfoaddr);
// Not necessarily terminated.
const std::string modInfoName(modinfo->name, strnlen(modinfo->name, sizeof(modinfo->name)));
module->nm.nsegment = reader.GetNumSegments();
module->nm.attribute = modinfo->moduleAttrs;
@@ -1902,9 +1917,9 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
// name check is for firmware 1.50, whose vshmain.prx declares no attributes at all - Sony
// only started setting PSP_MODULE_VSH_MODE in 1.52. Without it the whole VSH bootstrap
// below was skipped and the shell ran with none of its support modules loaded.
if ((module->nm.attribute & PSP_MODULE_VSH_MODE) != 0 || equals(modinfo->name, "vsh_module")) {
if ((module->nm.attribute & PSP_MODULE_VSH_MODE) != 0 || modInfoName == "vsh_module") {
g_runningVSH = true;
INFO_LOG(Log::sceModule, "VSH mode module detected: %s", modinfo->name);
INFO_LOG(Log::sceModule, "VSH mode module detected: %s", modInfoName.c_str());
// The shell booted without a game: its drive starts out empty, for a disc to go in later.
if (!pspFileSystem.GetSystem("disc0:")) {
__UmdEject();
@@ -1913,7 +1928,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
// OK, even if it's an ELF module, it might be one we shouldn't fully load and execute!
// This is seen with mpeg.prx in Tony Hawk's Underground 2, see #20568.
if (ShouldHLEModuleForLoad(modinfo->name)) {
if (ShouldHLEModuleForLoad(modInfoName)) {
// We load it, but at least we don't run any part of it.
module->isFake = true;
}
@@ -1988,7 +2003,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
module->libstub = modinfo->libstub;
module->libstubend = modinfo->libstubend;
INFO_LOG(Log::Loader, "Module %s: %08x %08x %08x", modinfo->name, modinfo->gp, modinfo->libent, modinfo->libstub);
INFO_LOG(Log::Loader, "Module %s: %08x %08x %08x", modInfoName.c_str(), modinfo->gp, modinfo->libent, modinfo->libstub);
DEBUG_LOG(Log::Loader,"===================================================");
u32 firstImportStubAddr = 0;
@@ -2098,16 +2113,24 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
const u32_le *entPos = nullptr;
const u32_le *entEnd = nullptr;
const u32_le *entBegin = nullptr;
// A module that wasn't relocated (cut off before its relocations, see LoadInto) still has
// link-time addresses here.
if (Memory::IsValidRange(modinfo->libent, modinfo->libentend - modinfo->libent)) {
entPos = (const u32_le *)Memory::GetPointerUnchecked(modinfo->libent);
entEnd = (const u32_le *)Memory::GetPointerUnchecked(modinfo->libentend);
entBegin = entPos;
} else {
WARN_LOG(Log::Loader, "Garbage libent address %08x or end %08x, no exports", modinfo->libent, modinfo->libentend);
}
for (int m = 0; entPos < entEnd; ++m) {
const u32 entAddr = modinfo->libent + (u32)((const u8 *)entPos - (const u8 *)entBegin);
// Read as a whole struct below, even when the entry is shorter.
if (!Memory::IsValidRange(entAddr, sizeof(PspLibEntEntry))) {
WARN_LOG_REPORT(Log::Loader, "Export entry at %08x runs off the end of memory", entAddr);
break;
}
const PspLibEntEntry *ent = (const PspLibEntEntry *)entPos;
entPos += ent->size;
if (ent->size == 0) {
@@ -2118,7 +2141,7 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
const u32 variableCount = ent->size <= 4 ? ent->vcount : std::max((u32)ent->vcount , (u32)ent->vcountNew);
const char *name;
if (Memory::IsValidAddress(ent->name)) {
if (ent->name != 0 && Memory::IsValidNullTerminatedString(ent->name)) {
name = Memory::GetCharPointer(ent->name);
} else if (ent->name == 0) {
name = module->nm.name;
@@ -2128,9 +2151,11 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
INFO_LOG(Log::Loader, "Exporting ent %d named %s, %d funcs, %d vars, resident %08x", m, name, ent->fcount, ent->vcount, ent->resident);
if (!Memory::IsValidAddress(ent->resident)) {
// The NIDs, then the addresses, one word each per function and variable.
const u32 residentBytes = ((u32)ent->fcount + variableCount) * 8;
if (!Memory::IsValidAddress(ent->resident) || !Memory::IsValidRange(ent->resident, residentBytes)) {
if (ent->fcount + variableCount > 0) {
WARN_LOG_REPORT(Log::Loader, "Invalid export resident address %08x", ent->resident);
WARN_LOG_REPORT(Log::Loader, "Invalid export resident address %08x (%d funcs, %d vars)", ent->resident, ent->fcount, variableCount);
}
continue;
}
@@ -2193,6 +2218,12 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
WARN_LOG(Log::Loader, "Invalid var %d, nid %08x, export address %08x", j, nid, exportAddr);
continue;
}
// The thread parameter variables below are four words.
const bool isThreadParam = nid == NID_MODULE_START_THREAD_PARAMETER || nid == NID_MODULE_STOP_THREAD_PARAMETER || nid == NID_MODULE_REBOOT_BEFORE_THREAD_PARAMETER;
if ((isThreadParam && !Memory::IsValidRange(exportAddr, 16)) || (nid == NID_MODULE_SDK_VERSION && !Memory::IsValidRange(exportAddr, 4))) {
WARN_LOG(Log::Loader, "Var %d, nid %08x, export address %08x runs off the end of memory", j, nid, exportAddr);
continue;
}
int size;
switch (nid) {
@@ -2265,8 +2296,8 @@ static PSPModule *__KernelLoadELFFromPtr(const u8 *ptr, size_t elfSize, u32 load
delete [] newptr;
if (!reportedModule && ShouldHLEModuleForLoad(modinfo->name)) {
INFO_LOG(Log::sceModule, "Loading module %s with version %04x, devkit %08x", modinfo->name, modinfo->moduleVersion, devkitVersion);
if (!reportedModule && ShouldHLEModuleForLoad(modInfoName)) {
INFO_LOG(Log::sceModule, "Loading module %s with version %04x, devkit %08x", modInfoName.c_str(), modinfo->moduleVersion, devkitVersion);
if (!strcmp(modinfo->name, "sceMpeg_library")) {
__MpegLoadModule(modinfo->moduleVersion, module->crc);
@@ -2354,7 +2385,7 @@ SceUID KernelLoadModule(const std::string &filename, std::string *error_string,
u32 error = SCE_KERNEL_ERROR_ILLEGAL_OBJECT;
u32 magic;
PSPModule *module = __KernelLoadELFFromPtr(&buffer[0], buffer.size(), 0, fromTop, error_string, &magic, filename, error);
PSPModule *module = __KernelLoadELFFromPtr(buffer.data(), buffer.size(), 0, fromTop, error_string, &magic, filename, error);
if (module == nullptr)
return error;
@@ -2369,11 +2400,12 @@ static PSPModule *__KernelLoadModule(u8 *fileptr, size_t fileSize, SceKernelLMOp
// PBP!
u32_le version;
memcpy(&version, fileptr + 4, 4);
u32_le offset0, offsets[16];
u32_le offset0, offsets[16]{};
memcpy(&offset0, fileptr + 8, 4);
int numfiles = (offset0 - 8) / 4;
if (numfiles <= 0 || numfiles > 16) {
// offsets[5] and [6] are used below.
if (numfiles < 7 || numfiles > 16) {
*error_string = "Invalid PBP header - can't load";
return nullptr;
}
@@ -3686,11 +3718,13 @@ static u32 sceKernelLoadModuleByID(u32 id, u32 flags, u32 lmoptionPtr) {
std::string error_string;
pspFileSystem.SeekFile(handle, pos, FILEMOVE_BEGIN);
PSPModule *module = nullptr;
u8 *temp = new u8[size - pos];
pspFileSystem.ReadFile(handle, temp, size - pos);
// The game may have seeked past the end.
const size_t remaining = size > pos ? size - pos : 0;
u8 *temp = new u8[remaining]();
const size_t bytesRead = pspFileSystem.ReadFile(handle, temp, remaining);
u32 magic;
module = __KernelLoadELFFromPtr(temp, size - pos, 0, lmoption ? lmoption->position == PSP_SMEM_High : false, &error_string, &magic, "", error);
module = __KernelLoadELFFromPtr(temp, std::min(bytesRead, remaining), 0, lmoption ? lmoption->position == PSP_SMEM_High : false, &error_string, &magic, "", error);
delete [] temp;
if (!module) {
@@ -3805,6 +3839,9 @@ SceUID sceKernelLoadModuleBufferUsbWlan(u32 size, u32 bufPtr, u32 flags, u32 lmo
char fakeDebugFilename[512];
snprintf(fakeDebugFilename, sizeof(fakeDebugFilename), "moduleByPtr_%08x_%d", bufPtr, (int)size);
if (!Memory::IsValidRange(bufPtr, size)) {
return hleLogError(Log::Loader, SCE_KERNEL_ERROR_ILLEGAL_ADDR, "Bad module buffer %08x (%d bytes)", bufPtr, size);
}
module = __KernelLoadELFFromPtr(Memory::GetPointerOrException(bufPtr), size, 0, lmoption ? lmoption->position == PSP_SMEM_High : false, &error_string, &magic, fakeDebugFilename, error);
if (!module) {