Skip to content

Commit 62dcdd2

Browse files
committed
Add support for symbol name remapping
1 parent 5908e16 commit 62dcdd2

File tree

4 files changed

+424
-5
lines changed

4 files changed

+424
-5
lines changed

src/patchelf.cc

Lines changed: 265 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,18 @@
1717
*/
1818

1919
#include <algorithm>
20+
#include <fstream>
2021
#include <limits>
2122
#include <map>
2223
#include <memory>
24+
#include <optional>
2325
#include <set>
2426
#include <sstream>
2527
#include <stdexcept>
2628
#include <string>
2729
#include <unordered_map>
30+
#include <unordered_set>
2831
#include <vector>
29-
#include <optional>
3032

3133
#include <cassert>
3234
#include <cerrno>
@@ -553,6 +555,27 @@ std::optional<std::reference_wrapper<Elf_Shdr>> ElfFile<ElfFileParamNames>::tryF
553555
return {};
554556
}
555557

558+
template<ElfFileParams>
559+
template<class T>
560+
span<T> ElfFile<ElfFileParamNames>::getSectionSpan(const Elf_Shdr & shdr) const
561+
{
562+
return span((T*)(fileContents->data() + rdi(shdr.sh_offset)), rdi(shdr.sh_size)/sizeof(T));
563+
}
564+
565+
template<ElfFileParams>
566+
template<class T>
567+
span<T> ElfFile<ElfFileParamNames>::getSectionSpan(const SectionName & sectionName)
568+
{
569+
return getSectionSpan<T>(findSectionHeader(sectionName));
570+
}
571+
572+
template<ElfFileParams>
573+
template<class T>
574+
span<T> ElfFile<ElfFileParamNames>::tryGetSectionSpan(const SectionName & sectionName)
575+
{
576+
auto shdrOpt = tryFindSectionHeader(sectionName);
577+
return shdrOpt ? getSectionSpan<T>(*shdrOpt) : span<T>();
578+
}
556579

557580
template<ElfFileParams>
558581
unsigned int ElfFile<ElfFileParamNames>::getSectionIndex(const SectionName & sectionName)
@@ -1861,6 +1884,219 @@ void ElfFile<ElfFileParamNames>::addDebugTag()
18611884
changed = true;
18621885
}
18631886

1887+
static uint32_t gnuHash(std::string_view name) {
1888+
uint32_t h = 5381;
1889+
for (uint8_t c : name)
1890+
h = ((h << 5) + h) + c;
1891+
return h;
1892+
}
1893+
1894+
template<ElfFileParams>
1895+
auto ElfFile<ElfFileParamNames>::parseGnuHashTable(span<char> sectionData) -> GnuHashTable
1896+
{
1897+
auto hdr = (typename GnuHashTable::Header*)sectionData.begin();
1898+
auto bloomFilters = span((typename GnuHashTable::BloomWord*)(hdr+1), rdi(hdr->maskwords));
1899+
auto buckets = span((uint32_t*)bloomFilters.end(), rdi(hdr->numBuckets));
1900+
auto table = span(buckets.end(), ((uint32_t*)sectionData.end()) - buckets.end());
1901+
return GnuHashTable{*hdr, bloomFilters, buckets, table};
1902+
}
1903+
1904+
template<ElfFileParams>
1905+
void ElfFile<ElfFileParamNames>::rebuildGnuHashTable(const char* strTab, span<Elf_Sym> dynsyms)
1906+
{
1907+
auto sectionData = tryGetSectionSpan<char>(".gnu.hash");
1908+
if (!sectionData)
1909+
return;
1910+
1911+
auto ght = parseGnuHashTable(sectionData);
1912+
1913+
// The hash table includes only a subset of dynsyms
1914+
auto firstSymIdx = rdi(ght.m_hdr.symndx);
1915+
dynsyms = span(dynsyms.begin() + firstSymIdx, dynsyms.end());
1916+
1917+
// Only use the range of symbol versions that will be changed
1918+
auto versyms = tryGetSectionSpan<Elf_Versym>(".gnu.version");
1919+
if (versyms)
1920+
versyms = span(versyms.begin() + firstSymIdx, versyms.end());
1921+
1922+
struct Entry
1923+
{
1924+
uint32_t hash, bucketIdx, originalPos;
1925+
};
1926+
1927+
std::vector<Entry> entries;
1928+
entries.reserve(dynsyms.size());
1929+
1930+
uint32_t pos = 0; // Track the original position of the symbol in the table
1931+
for (auto& sym : dynsyms)
1932+
{
1933+
Entry e;
1934+
e.hash = gnuHash(strTab + rdi(sym.st_name));
1935+
e.bucketIdx = e.hash % ght.m_buckets.size();
1936+
e.originalPos = pos++;
1937+
entries.push_back(e);
1938+
}
1939+
1940+
// Sort the entries based on the buckets. This is a requirement for gnu hash table to work
1941+
std::sort(entries.begin(), entries.end(), [&] (auto& l, auto& r) {
1942+
return l.bucketIdx < r.bucketIdx;
1943+
});
1944+
1945+
// Create a map of old positions to new positions after sorting
1946+
std::vector<uint32_t> old2new(entries.size());
1947+
for (size_t i = 0; i < entries.size(); ++i)
1948+
old2new[entries[i].originalPos] = i;
1949+
1950+
// Update the symbol table with the new order and
1951+
// all tables that refer to symbols through indexes in the symbol table
1952+
auto reorderSpan = [] (auto dst, auto& old2new)
1953+
{
1954+
std::vector tmp(dst.begin(), dst.end());
1955+
for (size_t i = 0; i < tmp.size(); ++i)
1956+
dst[old2new[i]] = tmp[i];
1957+
};
1958+
1959+
reorderSpan(dynsyms, old2new);
1960+
if (versyms)
1961+
reorderSpan(versyms, old2new);
1962+
1963+
auto fixRelocationTable = [&old2new, firstSymIdx, this] <class ER> (auto& hdr)
1964+
{
1965+
auto rela = getSectionSpan<ER>(hdr);
1966+
for (auto& r : rela)
1967+
{
1968+
auto info = rdi(r.r_info);
1969+
auto oldSymIdx = rel_getSymId(info);
1970+
if (oldSymIdx >= firstSymIdx)
1971+
{
1972+
auto newSymIdx = old2new[oldSymIdx - firstSymIdx] + firstSymIdx;
1973+
if (newSymIdx != oldSymIdx)
1974+
wri(r.r_info, rel_setSymId(info, newSymIdx));
1975+
}
1976+
}
1977+
};
1978+
1979+
for (unsigned int i = 1; i < rdi(hdr()->e_shnum); ++i)
1980+
{
1981+
auto& shdr = shdrs.at(i);
1982+
auto shtype = rdi(shdr.sh_type);
1983+
if (shtype == SHT_REL)
1984+
fixRelocationTable.template operator()<Elf_Rel>(shdr);
1985+
else if (shtype == SHT_RELA)
1986+
fixRelocationTable.template operator()<Elf_Rela>(shdr);
1987+
}
1988+
1989+
// Update bloom filters
1990+
std::fill(ght.m_bloomFilters.begin(), ght.m_bloomFilters.end(), 0);
1991+
for (size_t i = 0; i < entries.size(); ++i)
1992+
{
1993+
auto h = entries[i].hash;
1994+
size_t idx = (h / ElfClass) % ght.m_bloomFilters.size();
1995+
auto val = rdi(ght.m_bloomFilters[idx]);
1996+
val |= uint64_t(1) << (h % ElfClass);
1997+
val |= uint64_t(1) << ((h >> rdi(ght.m_hdr.shift2)) % ElfClass);
1998+
wri(ght.m_bloomFilters[idx], val);
1999+
}
2000+
2001+
// Fill buckets
2002+
std::fill(ght.m_buckets.begin(), ght.m_buckets.end(), 0);
2003+
for (size_t i = 0; i < entries.size(); ++i)
2004+
{
2005+
auto symBucketIdx = entries[i].bucketIdx;
2006+
if (!ght.m_buckets[symBucketIdx])
2007+
wri(ght.m_buckets[symBucketIdx], i + firstSymIdx);
2008+
}
2009+
2010+
// Fill hash table
2011+
for (size_t i = 0; i < entries.size(); ++i)
2012+
{
2013+
auto& n = entries[i];
2014+
bool isLast = (i == entries.size() - 1) || (n.bucketIdx != entries[i+1].bucketIdx);
2015+
// Add hash with first bit indicating end of chain
2016+
wri(ght.m_table[i], isLast ? (n.hash | 1) : (n.hash & ~1));
2017+
}
2018+
}
2019+
2020+
static uint32_t sysvHash(std::string_view name) {
2021+
uint32_t h = 0;
2022+
for (uint8_t c : name)
2023+
{
2024+
h = (h << 4) + c;
2025+
uint32_t g = h & 0xf0000000;
2026+
if (g != 0)
2027+
h ^= g >> 24;
2028+
h &= ~g;
2029+
}
2030+
return h;
2031+
}
2032+
2033+
template<ElfFileParams>
2034+
auto ElfFile<ElfFileParamNames>::parseHashTable(span<char> sectionData) -> HashTable
2035+
{
2036+
auto hdr = (typename HashTable::Header*)sectionData.begin();
2037+
auto buckets = span((uint32_t*)(hdr+1), rdi(hdr->numBuckets));
2038+
auto table = span(buckets.end(), ((uint32_t*)sectionData.end()) - buckets.end());
2039+
return HashTable{*hdr, buckets, table};
2040+
}
2041+
2042+
template<ElfFileParams>
2043+
void ElfFile<ElfFileParamNames>::rebuildHashTable(const char* strTab, span<Elf_Sym> dynsyms)
2044+
{
2045+
auto sectionData = tryGetSectionSpan<char>(".hash");
2046+
if (!sectionData)
2047+
return;
2048+
2049+
auto ht = parseHashTable(sectionData);
2050+
2051+
std::fill(ht.m_buckets.begin(), ht.m_buckets.end(), 0);
2052+
std::fill(ht.m_chain.begin(), ht.m_chain.end(), 0);
2053+
2054+
auto symsToInsert = span(dynsyms.end() - ht.m_chain.size(), dynsyms.end());
2055+
2056+
for (auto& sym : symsToInsert)
2057+
{
2058+
auto name = strTab + rdi(sym.st_name);
2059+
uint32_t i = &sym - dynsyms.begin();
2060+
uint32_t hash = sysvHash(name) % ht.m_buckets.size();
2061+
wri(ht.m_chain[i], rdi(ht.m_buckets[hash]));
2062+
wri(ht.m_buckets[hash], i);
2063+
}
2064+
}
2065+
2066+
template<ElfFileParams>
2067+
void ElfFile<ElfFileParamNames>::renameDynamicSymbols(const std::unordered_map<std::string_view, std::string>& remap)
2068+
{
2069+
auto dynsyms = getSectionSpan<Elf_Sym>(".dynsym");
2070+
auto strTab = getSectionSpan<char>(".dynstr");
2071+
2072+
std::vector<char> extraStrings;
2073+
extraStrings.reserve(remap.size() * 30); // Just an estimate
2074+
for (size_t i = 0; i < dynsyms.size(); i++)
2075+
{
2076+
auto& dynsym = dynsyms[i];
2077+
std::string_view name = &strTab[rdi(dynsym.st_name)];
2078+
auto it = remap.find(name);
2079+
if (it != remap.end())
2080+
{
2081+
wri(dynsym.st_name, strTab.size() + extraStrings.size());
2082+
auto& newName = it->second;
2083+
extraStrings.insert(extraStrings.end(), newName.data(), newName.data() + newName.size() + 1);
2084+
changed = true;
2085+
}
2086+
}
2087+
2088+
if (changed)
2089+
{
2090+
auto& newSec = replaceSection(".dynstr", strTab.size() + extraStrings.size());
2091+
std::copy(extraStrings.begin(), extraStrings.end(), newSec.begin() + strTab.size());
2092+
2093+
rebuildGnuHashTable(newSec.data(), dynsyms);
2094+
rebuildHashTable(newSec.data(), dynsyms);
2095+
}
2096+
2097+
this->rewriteSections();
2098+
}
2099+
18642100
template<ElfFileParams>
18652101
void ElfFile<ElfFileParamNames>::clearSymbolVersions(const std::set<std::string> & syms)
18662102
{
@@ -1904,12 +2140,15 @@ static bool removeRPath = false;
19042140
static bool setRPath = false;
19052141
static bool addRPath = false;
19062142
static bool addDebugTag = false;
2143+
static bool renameDynamicSymbols = false;
19072144
static bool printRPath = false;
19082145
static std::string newRPath;
19092146
static std::set<std::string> neededLibsToRemove;
19102147
static std::map<std::string, std::string> neededLibsToReplace;
19112148
static std::set<std::string> neededLibsToAdd;
19122149
static std::set<std::string> symbolsToClearVersion;
2150+
static std::unordered_map<std::string_view, std::string> symbolsToRename;
2151+
static std::unordered_set<std::string> symbolsToRenameKeys;
19132152
static bool printNeeded = false;
19142153
static bool noDefaultLib = false;
19152154

@@ -1959,6 +2198,9 @@ static void patchElf2(ElfFile && elfFile, const FileContents & fileContents, con
19592198
if (addDebugTag)
19602199
elfFile.addDebugTag();
19612200

2201+
if (renameDynamicSymbols)
2202+
elfFile.renameDynamicSymbols(symbolsToRename);
2203+
19622204
if (elfFile.isChanged()){
19632205
writeFile(fileName, elfFile.fileContents);
19642206
} else if (alwaysWrite) {
@@ -1978,9 +2220,9 @@ static void patchElf()
19782220
const std::string & outputFileName2 = outputFileName.empty() ? fileName : outputFileName;
19792221

19802222
if (getElfType(fileContents).is32Bit)
1981-
patchElf2(ElfFile<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Addr, Elf32_Off, Elf32_Dyn, Elf32_Sym, Elf32_Verneed, Elf32_Versym>(fileContents), fileContents, outputFileName2);
2223+
patchElf2(ElfFile<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Addr, Elf32_Off, Elf32_Dyn, Elf32_Sym, Elf32_Verneed, Elf32_Versym, Elf32_Rel, Elf32_Rela, 32>(fileContents), fileContents, outputFileName2);
19822224
else
1983-
patchElf2(ElfFile<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Addr, Elf64_Off, Elf64_Dyn, Elf64_Sym, Elf64_Verneed, Elf64_Versym>(fileContents), fileContents, outputFileName2);
2225+
patchElf2(ElfFile<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Addr, Elf64_Off, Elf64_Dyn, Elf64_Sym, Elf64_Verneed, Elf64_Versym, Elf64_Rel, Elf64_Rela, 64>(fileContents), fileContents, outputFileName2);
19842226
}
19852227
}
19862228

@@ -2019,6 +2261,7 @@ void showHelp(const std::string & progName)
20192261
[--no-sort]\t\tDo not sort program+section headers; useful for debugging patchelf.\n\
20202262
[--clear-symbol-version SYMBOL]\n\
20212263
[--add-debug-tag]\n\
2264+
[--rename-dynamic-symbols NAME_MAP_FILE]\tRenames dynamic symbols. The name map file should contain two symbols (old_name new_name) per line\n\
20222265
[--output FILE]\n\
20232266
[--debug]\n\
20242267
[--version]\n\
@@ -2141,6 +2384,25 @@ int mainWrapped(int argc, char * * argv)
21412384
else if (arg == "--add-debug-tag") {
21422385
addDebugTag = true;
21432386
}
2387+
else if (arg == "--rename-dynamic-symbols") {
2388+
renameDynamicSymbols = true;
2389+
if (++i == argc) error("missing argument");
2390+
2391+
std::ifstream infile(argv[i]);
2392+
if (!infile) error(fmt("Cannot open map file ", argv[i]));
2393+
2394+
std::string from, to;
2395+
while (true)
2396+
{
2397+
if (!(infile >> from))
2398+
break;
2399+
if (!(infile >> to))
2400+
error("Odd number of symbols in map file");
2401+
if (symbolsToRenameKeys.count(from))
2402+
error(fmt("Symbol appears twice in the map file: ", from.c_str()));
2403+
symbolsToRename[*symbolsToRenameKeys.insert(from).first] = to;
2404+
}
2405+
}
21442406
else if (arg == "--help" || arg == "-h" ) {
21452407
showHelp(argv[0]);
21462408
return 0;

0 commit comments

Comments
 (0)