Skip to content

Commit

Permalink
Add support for symbol name remapping
Browse files Browse the repository at this point in the history
  • Loading branch information
brenoguim committed Feb 18, 2023
1 parent 5908e16 commit 18a8b8a
Show file tree
Hide file tree
Showing 4 changed files with 420 additions and 5 deletions.
271 changes: 268 additions & 3 deletions src/patchelf.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,18 @@
*/

#include <algorithm>
#include <fstream>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <optional>

#include <cassert>
#include <cerrno>
Expand Down Expand Up @@ -553,6 +555,27 @@ std::optional<std::reference_wrapper<Elf_Shdr>> ElfFile<ElfFileParamNames>::tryF
return {};
}

template<ElfFileParams>
template<class T>
span<T> ElfFile<ElfFileParamNames>::getSectionSpan(const Elf_Shdr & shdr) const
{
return span((T*)(fileContents->data() + rdi(shdr.sh_offset)), rdi(shdr.sh_size)/sizeof(T));
}

template<ElfFileParams>
template<class T>
span<T> ElfFile<ElfFileParamNames>::getSectionSpan(const SectionName & sectionName)
{
return getSectionSpan<T>(findSectionHeader(sectionName));
}

template<ElfFileParams>
template<class T>
span<T> ElfFile<ElfFileParamNames>::tryGetSectionSpan(const SectionName & sectionName)
{
auto shdrOpt = tryFindSectionHeader(sectionName);
return shdrOpt ? getSectionSpan<T>(*shdrOpt) : span<T>();
}

template<ElfFileParams>
unsigned int ElfFile<ElfFileParamNames>::getSectionIndex(const SectionName & sectionName)
Expand Down Expand Up @@ -1861,6 +1884,222 @@ void ElfFile<ElfFileParamNames>::addDebugTag()
changed = true;
}

static uint32_t gnuHash(std::string_view name) {
uint32_t h = 5381;
for (uint8_t c : name)
h = ((h << 5) + h) + c;
return h;
}

template<ElfFileParams>
auto ElfFile<ElfFileParamNames>::GnuHashTable::parse(span<char> sectionData) -> GnuHashTable
{
auto hdr = (Header*)sectionData.begin();
auto bloomFilters = span((BloomWord*)(hdr+1), hdr->maskwords);
auto buckets = span((uint32_t*)bloomFilters.end(), hdr->numBuckets);
auto table = span(buckets.end(), ((uint32_t*)sectionData.end()) - buckets.end());
return GnuHashTable{*hdr, bloomFilters, buckets, table};
}

template<ElfFileParams>
void ElfFile<ElfFileParamNames>::rebuildGnuHashTable(const char* strTab, span<Elf_Sym> dynsyms)
{
auto sectionData = tryGetSectionSpan<char>(".gnu.hash");
if (!sectionData)
return;

auto ght = GnuHashTable::parse(sectionData);

// Only work with the last "m_table.size()" symbols from dynsyms which are the
// symbols that belong to the hash table
auto firstSymIdx = dynsyms.size() - ght.m_table.size();
auto symsToInsert = span(dynsyms.begin() + firstSymIdx, dynsyms.end());

// Only use the range of symbol versions that will be changed
auto versyms = tryGetSectionSpan<Elf_Versym>(".gnu.version");
if (versyms)
versyms = span(versyms.begin() + firstSymIdx, versyms.end());

struct Entry
{
Elf_Sym sym;
uint32_t hash, bucketIdx;
Elf_Versym vsym {};
uint32_t originalPos;
};

std::vector<Entry> entries;
entries.reserve(symsToInsert.size());

uint32_t pos = 0;
for (auto& sym : symsToInsert)
{
Entry e;
e.sym = sym;
e.hash = gnuHash(strTab + rdi(e.sym.st_name));
e.originalPos = pos++;
e.bucketIdx = e.hash % ght.m_hdr.numBuckets;
if (versyms)
e.vsym = versyms[e.originalPos];

entries.push_back(e);
}

// Sort the entries based on the buckets. This is a requirement for gnu hash table to work
std::sort(entries.begin(), entries.end(), [&] (auto& l, auto& r) {
return l.bucketIdx < r.bucketIdx;
});

// Update the symbol table with the new order and
// all tables that refer to symbols through indexes in the symbol table
std::vector<uint32_t> old2new(entries.size());
for (size_t i = 0; i < entries.size(); ++i)
{
auto& entry = entries[i];
old2new[entry.originalPos] = i + firstSymIdx;
symsToInsert[i] = entry.sym;
if (versyms)
versyms[i] = entry.vsym;
}

auto fixRelocationTable = [&old2new, firstSymIdx, this] <class ER> (auto& hdr)
{
auto rela = getSectionSpan<ER>(hdr);
for (auto& r : rela)
{
auto info = rdi(r.r_info);
auto oldSymIdx = rel_getSymId(info);
if (oldSymIdx >= firstSymIdx)
{
auto newSymIdx = old2new[oldSymIdx - firstSymIdx];
if (newSymIdx != oldSymIdx) {
wri(r.r_info, rel_setSymId(info, newSymIdx));
}
}
}
};

for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
{
auto& shdr = shdrs.at(i);
auto shtype = rdi(shdr.sh_type);
if (shtype == SHT_REL)
fixRelocationTable.template operator()<Elf_Rel>(shdr);
else if (shtype == SHT_RELA)
fixRelocationTable.template operator()<Elf_Rela>(shdr);
}

// Update bloom filters
std::fill(ght.m_bloomFilters.begin(), ght.m_bloomFilters.end(), 0);
for (size_t i = 0; i < entries.size(); ++i)
{
auto h = entries[i].hash;
size_t idx = (h / ElfWordSize) % ght.m_bloomFilters.size();
auto val = rdi(ght.m_bloomFilters[idx]);
val |= uint64_t(1) << (h % ElfWordSize);
val |= uint64_t(1) << ((h >> ght.m_hdr.shift2) % ElfWordSize);
wri(ght.m_bloomFilters[idx], val);
}

// Fill buckets
std::fill(ght.m_buckets.begin(), ght.m_buckets.end(), 0);
for (size_t i = 0; i < entries.size(); ++i)
{
auto symBucketIdx = entries[i].bucketIdx;
if (!ght.m_buckets[symBucketIdx])
ght.m_buckets[symBucketIdx] = i + ght.m_hdr.symndx;
}

// Fill hash table
for (size_t i = 0; i < entries.size(); ++i)
{
auto& n = entries[i];
bool isLast = (i == entries.size() - 1) || (n.bucketIdx != entries[i+1].bucketIdx);
// Add hash with first bit indicating end of chain
ght.m_table[i] = isLast ? (n.hash | 1) : (n.hash & ~1);
}
}

static uint32_t sysvHash(std::string_view name) {
uint32_t h = 0;
for (uint8_t c : name)
{
h = (h << 4) + c;
uint32_t g = h & 0xf0000000;
if (g != 0)
h ^= g >> 24;
h &= ~g;
}
return h;
}

template<ElfFileParams>
auto ElfFile<ElfFileParamNames>::HashTable::parse(span<char> sectionData) -> HashTable
{
auto hdr = (Header*)sectionData.begin();
auto buckets = span((uint32_t*)(hdr+1), hdr->numBuckets);
auto table = span(buckets.end(), ((uint32_t*)sectionData.end()) - buckets.end());
return HashTable{*hdr, buckets, table};
}

template<ElfFileParams>
void ElfFile<ElfFileParamNames>::rebuildHashTable(const char* strTab, span<Elf_Sym> dynsyms)
{
auto sectionData = tryGetSectionSpan<char>(".hash");
if (!sectionData)
return;

auto ht = HashTable::parse(sectionData);

std::fill(ht.m_buckets.begin(), ht.m_buckets.end(), 0);
std::fill(ht.m_chain.begin(), ht.m_chain.end(), 0);

auto symsToInsert = span(dynsyms.end() - ht.m_chain.size(), dynsyms.end());

for (auto& sym : symsToInsert)
{
auto name = strTab + rdi(sym.st_name);
uint32_t i = &sym - dynsyms.begin();
uint32_t hash = sysvHash(name) % ht.m_buckets.size();
ht.m_chain[i] = ht.m_buckets[hash];
ht.m_buckets[hash] = i;
}
}

template<ElfFileParams>
void ElfFile<ElfFileParamNames>::renameDynamicSymbols(const std::unordered_map<std::string_view, std::string>& remap)
{
auto dynsyms = getSectionSpan<Elf_Sym>(".dynsym");
auto strTab = getSectionSpan<char>(".dynstr");

std::vector<char> extraStrings;
extraStrings.reserve(remap.size() * 30); // Just an estimate
for (size_t i = 0; i < dynsyms.size(); i++)
{
auto& dynsym = dynsyms[i];
std::string_view name = &strTab[rdi(dynsym.st_name)];
auto it = remap.find(name);
if (it != remap.end())
{
wri(dynsym.st_name, strTab.size() + extraStrings.size());
auto& newName = it->second;
extraStrings.insert(extraStrings.end(), newName.data(), newName.data() + newName.size() + 1);
changed = true;
}
}

if (changed)
{
auto& newSec = replaceSection(".dynstr", strTab.size() + extraStrings.size());
std::copy(extraStrings.begin(), extraStrings.end(), newSec.begin() + strTab.size());

rebuildGnuHashTable(newSec.data(), dynsyms);
rebuildHashTable(newSec.data(), dynsyms);
}

this->rewriteSections();
}

template<ElfFileParams>
void ElfFile<ElfFileParamNames>::clearSymbolVersions(const std::set<std::string> & syms)
{
Expand Down Expand Up @@ -1904,12 +2143,15 @@ static bool removeRPath = false;
static bool setRPath = false;
static bool addRPath = false;
static bool addDebugTag = false;
static bool renameDynamicSymbols = false;
static bool printRPath = false;
static std::string newRPath;
static std::set<std::string> neededLibsToRemove;
static std::map<std::string, std::string> neededLibsToReplace;
static std::set<std::string> neededLibsToAdd;
static std::set<std::string> symbolsToClearVersion;
static std::unordered_map<std::string_view, std::string> symbolsToRename;
static std::unordered_set<std::string> symbolsToRenameKeys;
static bool printNeeded = false;
static bool noDefaultLib = false;

Expand Down Expand Up @@ -1959,6 +2201,9 @@ static void patchElf2(ElfFile && elfFile, const FileContents & fileContents, con
if (addDebugTag)
elfFile.addDebugTag();

if (renameDynamicSymbols)
elfFile.renameDynamicSymbols(symbolsToRename);

if (elfFile.isChanged()){
writeFile(fileName, elfFile.fileContents);
} else if (alwaysWrite) {
Expand All @@ -1978,9 +2223,9 @@ static void patchElf()
const std::string & outputFileName2 = outputFileName.empty() ? fileName : outputFileName;

if (getElfType(fileContents).is32Bit)
patchElf2(ElfFile<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Addr, Elf32_Off, Elf32_Dyn, Elf32_Sym, Elf32_Verneed, Elf32_Versym>(fileContents), fileContents, outputFileName2);
patchElf2(ElfFile<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Addr, Elf32_Off, Elf32_Dyn, Elf32_Sym, Elf32_Verneed, Elf32_Versym, Elf32_Rel, Elf32_Rela>(fileContents), fileContents, outputFileName2);
else
patchElf2(ElfFile<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Addr, Elf64_Off, Elf64_Dyn, Elf64_Sym, Elf64_Verneed, Elf64_Versym>(fileContents), fileContents, outputFileName2);
patchElf2(ElfFile<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Addr, Elf64_Off, Elf64_Dyn, Elf64_Sym, Elf64_Verneed, Elf64_Versym, Elf64_Rel, Elf64_Rela>(fileContents), fileContents, outputFileName2);
}
}

Expand Down Expand Up @@ -2019,6 +2264,7 @@ void showHelp(const std::string & progName)
[--no-sort]\t\tDo not sort program+section headers; useful for debugging patchelf.\n\
[--clear-symbol-version SYMBOL]\n\
[--add-debug-tag]\n\
[--rename-dynamic-symbols NAME_MAP_FILE]\tRenames dynamic symbols. The name map file should contain two symbols (old_name new_name) per line\n\
[--output FILE]\n\
[--debug]\n\
[--version]\n\
Expand Down Expand Up @@ -2141,6 +2387,25 @@ int mainWrapped(int argc, char * * argv)
else if (arg == "--add-debug-tag") {
addDebugTag = true;
}
else if (arg == "--rename-dynamic-symbols") {
renameDynamicSymbols = true;
if (++i == argc) error("missing argument");

std::ifstream infile(argv[i]);
if (!infile) error(fmt("Cannot open map file ", argv[i]));

std::string from, to;
while (true)
{
if (!(infile >> from))
break;
if (!(infile >> to))
error("Odd number of symbols in map file");
if (symbolsToRenameKeys.count(from))
error(fmt("Symbol appears twice in the map file: ", from.c_str()));
symbolsToRename[*symbolsToRenameKeys.insert(from).first] = to;
}
}
else if (arg == "--help" || arg == "-h" ) {
showHelp(argv[0]);
return 0;
Expand Down
Loading

0 comments on commit 18a8b8a

Please sign in to comment.