Merge pull request #1249 from Raghav314/fix/relinker-guest-hash

fix(relinker): write a bucketed hash table for Linux guest modules
This commit is contained in:
Adrià
2026-10-10 00:37:47 +02:00
committed by GitHub
2 changed files with 37 additions and 3 deletions
@@ -55,10 +55,21 @@ std::vector<std::uint8_t> GuestModuleWriter::WriteLinux(const Relinker::GuestIma
bytes.insert(bytes.end(), symbols.begin(), symbols.end());
const auto hashAddress = address();
const auto count = static_cast<std::uint32_t>(image.Symbols.size());
Io::AppendU32(bytes, 1);
const auto bucketCount = std::max<std::uint32_t>(count, 1);
std::vector<std::uint32_t> buckets(bucketCount), chains(count);
for (std::uint32_t index = count; index-- > 1;) {
std::uint32_t hash = 0;
for (auto offset = Io::ReadU32(symbols, index * 24); offset < strings.size() && strings[offset] != 0; ++offset) {
hash = (hash << 4u) + strings[offset];
hash = (hash ^ ((hash & 0xf0000000u) >> 24u)) & 0x0fffffffu;
}
chains[index] = buckets[hash % bucketCount];
buckets[hash % bucketCount] = index;
}
Io::AppendU32(bytes, bucketCount);
Io::AppendU32(bytes, count);
Io::AppendU32(bytes, count > 1 ? 1 : 0);
for (std::uint32_t index = 0; index < count; ++index) Io::AppendU32(bytes, index != 0 && index + 1 < count ? index + 1 : 0);
for (const auto bucket : buckets) Io::AppendU32(bytes, bucket);
for (const auto chain : chains) Io::AppendU32(bytes, chain);
Io::AlignBuffer(bytes, 8);
const auto relaAddress = address();
bytes.insert(bytes.end(), image.Dynamic.RelaData.begin(), image.Dynamic.RelaData.end());
@@ -85,6 +85,27 @@ def module_symbols(image):
return [symbol_name(image, tags, index) for index in range(1, count)]
def elf_hash(name):
value = 0
for byte in name.encode():
value = (value << 4) + byte
value = (value ^ ((value & 0xF0000000) >> 24)) & 0x0FFFFFFF
return value
def check_hash_table(image):
tags = dynamic_tags(image)
table = file_offset(image, tags[4])
buckets, count = struct.unpack_from("<II", image, table)
assert buckets == count, (buckets, count)
for index in range(1, count):
name = symbol_name(image, tags, index)
found, = struct.unpack_from("<I", image, table + 8 + elf_hash(name) % buckets * 4)
while found not in (0, index):
found, = struct.unpack_from("<I", image, table + 8 + (buckets + found) * 4)
assert found == index, name
def imported_symbols(image):
tags = dynamic_tags(image)
names = set()
@@ -123,6 +144,8 @@ def main():
assert libc == ["AAAAAAAAAAA#guest", "BBBBBBBBBBB#guest", "CCCCCCCCCCC", "EEEEEEEEEEE#guest"], libc
other = module_symbols((modules / "other.prx.guest.prx").read_bytes())
assert other == ["BBBBBBBBBBB#guest", "EEEEEEEEEEE#guest"], other
check_hash_table((modules / "libc.prx.guest.prx").read_bytes())
check_hash_table((modules / "other.prx.guest.prx").read_bytes())
imports = imported_symbols(output.read_bytes())
assert imports == {"AAAAAAAAAAA#guest", "DDDDDDDDDDD"}, imports
print("Guest symbol name tests passed")