From 976a3b0187da1b4df6f2fbdb912b5314d891dca3 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sun, 1 Nov 2026 02:28:06 +0000 Subject: [PATCH 01/12] remove early return in cache code --- context.cc | 1 - 1 file changed, 1 deletion(-) diff --git a/context.cc b/context.cc index 6bc0b7f..9befbda 100644 --- a/context.cc +++ b/context.cc @@ -259,7 +259,6 @@ Context::getImageInPath(const std::vector &paths, NameMap *debug << name << " has an interpreter: " << interpreter << " - opening that instead\n"; res = openImage( interpreter, -1, false ); } else { - return std::make_shared(*this, reader , isDebug); res = openImage( path, -1, isDebug ); } break; From 4aa86dcbe519c6c8477210ec068468dec1ab16b9 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sat, 31 Oct 2026 13:54:30 +0000 Subject: [PATCH 02/12] Use the term "segment", not "section" as appropriate. --- elf.cc | 8 ++++---- libpstack/elf.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/elf.cc b/elf.cc index 8f74fdf..dbadb0a 100644 --- a/elf.cc +++ b/elf.cc @@ -98,15 +98,15 @@ Notes::segment_iterator::segment_iterator(const Object *object_) if (phdrs) { phdrsi = phdrs->begin(); if (phdrsi != phdrs->end()) { - startSection(); + startSegment(); readNote(); } } } -void Notes::segment_iterator::startSection() { +void Notes::segment_iterator::startSegment() { offset = 0; - io = object->io->view("note section", Off(phdrsi->p_offset), size_t(phdrsi->p_filesz)); + io = object->io->view("note segment", Off(phdrsi->p_offset), size_t(phdrsi->p_filesz)); } Notes::segment_iterator &Notes::segment_iterator::operator++() @@ -117,7 +117,7 @@ Notes::segment_iterator &Notes::segment_iterator::operator++() offset = 0; return *this; } - startSection(); + startSegment(); } else { offset = newOff; } diff --git a/libpstack/elf.h b/libpstack/elf.h index 17dd985..89faf72 100644 --- a/libpstack/elf.h +++ b/libpstack/elf.h @@ -418,7 +418,7 @@ class Notes::segment_iterator { Note curNote; Reader::csptr io; void readNote() { io->readObj(offset, &curNote); } - void startSection(); + void startSegment(); public: segment_iterator(const Object *object_); segment_iterator(const segment_iterator &rhs) = default; From c51e364e9ea26e9d6b65b8ef42167b17557414c8 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sat, 31 Oct 2026 13:55:53 +0000 Subject: [PATCH 03/12] Refactor getBuildID We don't need to iterate notes sepaately for debug and exe objects anymore - the note iterator takes care of that. Also, refactor the code to extract build IDs from note descrs so we can reuse it later. --- elf.cc | 36 ++++++++++-------------------------- libpstack/elf.h | 1 + 2 files changed, 11 insertions(+), 26 deletions(-) diff --git a/elf.cc b/elf.cc index dbadb0a..0b8faf4 100644 --- a/elf.cc +++ b/elf.cc @@ -570,33 +570,17 @@ Object::findDebugSymbol(const string &name) return {undef(), 0}; } +BuildID getBuildIDFromNote(const NoteDesc ¬e) { + auto noteIo = note.data(); + std::vector data(noteIo->size()); + noteIo->readObj(0, data.data(), noteIo->size()); + return BuildID{ data }; +} + BuildID Object::getBuildID() const { - if (isDebug) { - // For debug objects, don't trust the notes segments are accurate - // (they're not). Only use sections to derive info in debug objects. - const auto ¬esec = getSection(".note.gnu.build-id", SHT_NOTE); - if (notesec) { - auto noteIo = notesec.io(); - if (noteIo->size() > 4 + sizeof (Note)) { - auto note = noteIo->readObj( 0 ); - if (note.n_type == GNU_BUILD_ID) { - std::vector data; - data.resize(note.n_descsz); - noteIo->readObj(sizeof note + roundup2(note.n_namesz, 4), data.data(), note.n_descsz ); - return BuildID(data); - } - } - } - } else { - // for "execuable" objects, trust the segments primarily. Find the GNU buildID note. - for (const auto ¬e : notes()) { - if (note.name() == "GNU" && note.type() == GNU_BUILD_ID) { - auto noteIo = note.data(); - std::vector data; - data.resize(noteIo->size()); - noteIo->readObj(0, data.data(), noteIo->size()); - return BuildID(data); - } + for (const auto ¬e : notes()) { + if (note.name() == "GNU" && note.type() == GNU_BUILD_ID) { + return getBuildIDFromNote(note); } } return {}; diff --git a/libpstack/elf.h b/libpstack/elf.h index 89faf72..000d312 100644 --- a/libpstack/elf.h +++ b/libpstack/elf.h @@ -409,6 +409,7 @@ class NoteDesc { Reader::csptr data() const; int type() const { return note.n_type; } }; +BuildID getBuildIDFromNote(const NoteDesc ¬ed); class Notes::segment_iterator { const Object *object; From dd5e256541735ba5a34c8d919e886a49588da5c8 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sat, 31 Oct 2026 13:57:48 +0000 Subject: [PATCH 04/12] Make addGoroutines a member of Process This is where it belongs --- golang.cc | 43 +++++++++++++++++++++++-------------------- libpstack/proc.h | 4 +--- process.cc | 2 +- 3 files changed, 25 insertions(+), 24 deletions(-) diff --git a/golang.cc b/golang.cc index 5f21425..6580889 100644 --- a/golang.cc +++ b/golang.cc @@ -17,26 +17,29 @@ namespace pstack::Procman { #endif void -addGoRoutines(Process &proc, Stacks &stacks) +Process::addGoroutines(Stacks &stacks) { Elf::Object::sptr elf; Elf::Addr loadAddress; Elf::Sym allgsSymbol; + + // If it doesn't look like a go process, and we are not forcing the issue, don't + // do the work of searching for goroutines. try { - std::tie(elf, loadAddress, allgsSymbol) = proc.resolveSymbolDetail("runtime.allgs", true); + std::tie(elf, loadAddress, allgsSymbol) = resolveSymbolDetail("runtime.allgs", true); } catch (const Exception &ex) { // Most targets are not Go programs; absence of this runtime symbol is normal. - if (proc.context.verbose > 1) - *proc.context.debug << "no go interpreter detected: " << ex.what() << "\n"; + if (context.verbose > 1) + *context.debug << "no go interpreter detected: " << ex.what() << "\n"; return; } try { - const auto &offsets = Go::getOffsets(proc.context, *elf); + const auto &offsets = Go::getOffsets(context, *elf); const Elf::Addr allgsAddress = loadAddress + allgsSymbol.st_value; - const Elf::Addr allgsData = proc.io->readObj(allgsAddress + offsets.allgsData); - const Elf::Addr count = proc.io->readObj(allgsAddress + offsets.allgsLength); + const Elf::Addr allgsData = io->readObj(allgsAddress + offsets.allgsData); + const Elf::Addr count = io->readObj(allgsAddress + offsets.allgsLength); if (!allgsData || !count) return; if (count > 1'000'000) @@ -46,20 +49,20 @@ addGoRoutines(Process &proc, Stacks &stacks) for (Elf::Addr i = 0; i < count; ++i) { try { - auto g = proc.io->readObj(allgsData + i * offsets.allgsStride); + auto g = io->readObj(allgsData + i * offsets.allgsStride); if (!g) continue; const Elf::Addr sched = g + offsets.gSched; // Running goroutines have their state in a kernel thread. A nonzero // saved SP identifies goroutines parked in the runtime scheduler. - auto sp = proc.io->readObj(sched + offsets.gobufSp); + auto sp = io->readObj(sched + offsets.gobufSp); if (!sp) continue; - auto pc = proc.io->readObj(sched + offsets.gobufPc); + auto pc = io->readObj(sched + offsets.gobufPc); if (!pc) continue; - auto goid = proc.io->readObj(g + offsets.gGoid); + auto goid = io->readObj(g + offsets.gGoid); if (!goid) continue; // g0 and gsignal are runtime scheduler stacks. @@ -67,42 +70,42 @@ addGoRoutines(Process &proc, Stacks &stacks) regs.setDwarf(SPREG, RegisterValue{gpreg(sp)}); regs.setDwarf(IPREG, RegisterValue{gpreg(pc)}); if (offsets.gobufBp) { - const Elf::Addr bp = proc.io->readObj(sched + *offsets.gobufBp); + const Elf::Addr bp = io->readObj(sched + *offsets.gobufBp); regs.setDwarf(BPREG, RegisterValue{gpreg(bp)}); } #ifdef GREG if (offsets.gobufG) { - const Elf::Addr g = proc.io->readObj(sched + *offsets.gobufG); + const Elf::Addr g = io->readObj(sched + *offsets.gobufG); regs.setDwarf(GREG, RegisterValue{gpreg(g)}); } #endif #ifdef CTXTREG if (offsets.gobufCtxt) { - const Elf::Addr ctxt = proc.io->readObj(sched + *offsets.gobufCtxt); + const Elf::Addr ctxt = io->readObj(sched + *offsets.gobufCtxt); regs.setDwarf(CTXTREG, RegisterValue{gpreg(ctxt)}); } #endif #ifdef LRREG if (offsets.gobufLr) { - const Elf::Addr lr = proc.io->readObj(sched + *offsets.gobufLr); + const Elf::Addr lr = io->readObj(sched + *offsets.gobufLr); regs.setDwarf(LRREG, RegisterValue{gpreg(lr)}); } #endif Lwp goroutine; goroutine.id = fakeLWPId--; goroutine.goroutineID = goid; - goroutine.unwind(proc, regs); + goroutine.unwind(*this, regs); stacks.emplace(goroutine.id, std::move(goroutine)); } catch (const Exception &ex) { - if (proc.context.verbose > 1) - *proc.context.debug << "failed to unwind Go goroutine " << i << ": " << ex.what() << "\n"; + if (context.verbose > 1) + *context.debug << "failed to unwind Go goroutine " << i << ": " << ex.what() << "\n"; } } } catch (const Exception &ex) { - if (proc.context.verbose > 0) - *proc.context.debug << "Go goroutine support unavailable: " << ex.what() << "\n"; + if (context.verbose > 0) + *context.debug << "Go goroutine support unavailable: " << ex.what() << "\n"; } } diff --git a/libpstack/proc.h b/libpstack/proc.h index 90310cd..dbf5d6c 100644 --- a/libpstack/proc.h +++ b/libpstack/proc.h @@ -179,9 +179,6 @@ struct Lwp { using Stacks = std::map; -// Add saved Go goroutine stacks to the process stack collection. -void addGoRoutines(Process &, Stacks &); - struct DevNode { int major = -1; int minor = -1; @@ -252,6 +249,7 @@ class Process : public ps_prochandle { void loadSharedObjects(Elf::Addr); Elf::Addr extractDtDebugFromDynamicSegment(const Elf::Phdr &phdr, Elf::Addr loadAddr, const char *); void processAUXV(const Reader &); + void addGoroutines(Stacks&); protected: td_thragent_t *agent; diff --git a/process.cc b/process.cc index 75ddfca..c54ebe4 100644 --- a/process.cc +++ b/process.cc @@ -1250,7 +1250,7 @@ Process::getStacks() { } }); - addGoRoutines(*this, stacks); + addGoroutines(stacks); /* * Use the thread db to find at least the thread ids for each lwp. We From b03e3071181aaeccf6100dffe95e3f89c571d988 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sat, 31 Oct 2026 14:00:05 +0000 Subject: [PATCH 05/12] resolveSymbolDetail's matcher func now gets the MappedObject, not its name --- libpstack/proc.h | 8 ++++---- proc_service.cc | 4 ++-- process.cc | 13 ++++--------- python.cc | 3 ++- 4 files changed, 12 insertions(+), 16 deletions(-) diff --git a/libpstack/proc.h b/libpstack/proc.h index dbf5d6c..36b6462 100644 --- a/libpstack/proc.h +++ b/libpstack/proc.h @@ -306,15 +306,15 @@ class Process : public ps_prochandle { template void listThreads(const T &invokeable); virtual void listLWPs(const std::function &) {}; + using SymMatcher = std::function; + static bool defaultMatcher(const MappedObject &) { return true; }; // find address of named symbol in the process. - Elf::Addr resolveSymbol(const char *symbolName, bool includeDebug, - std::function matcher = [](std::string_view) { return true; }); + Elf::Addr resolveSymbol(const char *symbolName, bool includeDebug, SymMatcher matcher = defaultMatcher); // find symbol data of named symbol in the process. // like resolveSymbol, but return the library and that library's load address as well as the address in the process. std::tuple - resolveSymbolDetail(const char *name, bool includeDebug, - std::function match = [](std::string_view) { return true; }); + resolveSymbolDetail(const char *name, bool includeDebug, SymMatcher matcher = defaultMatcher); virtual Stacks getStacks(); void load(); [[nodiscard]] virtual pid_t getPID() const = 0; diff --git a/proc_service.cc b/proc_service.cc index 4a4719c..26b163f 100644 --- a/proc_service.cc +++ b/proc_service.cc @@ -48,13 +48,13 @@ ps_pglobal_lookup(struct ps_prochandle *ph, const char *ld_object_name, auto p = static_cast(ph); try { *ld_symbol_addr = psaddr_t(intptr_t(p->resolveSymbol(ld_symbol_name, true, - [ld_object_name](std::string_view name) { + [ld_object_name](const Procman::MappedObject &mappedObject) { if (ld_object_name == nullptr) { // Null pointer for object name means look at all objects. // Also, avoid constructing a string_view with a nullptr. return true; } - auto bn = std::filesystem::path(name).filename(); + auto bn = std::filesystem::path(mappedObject.name()).filename(); return bn == ld_object_name || bn == "libc.so.6"; } ))); diff --git a/process.cc b/process.cc index c54ebe4..2b8dd8a 100644 --- a/process.cc +++ b/process.cc @@ -913,13 +913,10 @@ Process::findRDebugAddr() try { addElfObject(execImage->getInterpreter(), nullptr, interpBase); dt_debug = resolveSymbol("_r_debug", false, - [this](const std::string_view name) { - return execImage->getInterpreter() == name; - }); + [this](const MappedObject & mapped) { return execImage->getInterpreter() == mapped.name(); }); if (dt_debug != 0 && context.debug) { *context.debug << "found DT_DEBUG using address of _r_debug symbol\n"; } - } catch (...) { } @@ -944,11 +941,10 @@ Process::findSegment(Elf::Addr addr) } std::tuple -Process::resolveSymbolDetail(const char *name, bool includeDebug, - std::function match) +Process::resolveSymbolDetail(const char *name, bool includeDebug, SymMatcher match) { for (auto &loaded : objects) { - if (!match(loaded.second.name())) + if (!match(loaded.second)) continue; auto obj = loaded.second.object(context); if (!obj) @@ -966,8 +962,7 @@ Process::resolveSymbolDetail(const char *name, bool includeDebug, } Elf::Addr -Process::resolveSymbol(const char *name, bool includeDebug, - std::function match) +Process::resolveSymbol(const char *name, bool includeDebug, SymMatcher match) { auto [obj, addr, sym] = resolveSymbolDetail(name, includeDebug, match); return addr + sym.st_value; diff --git a/python.cc b/python.cc index e0ee11b..96c7d10 100644 --- a/python.cc +++ b/python.cc @@ -79,7 +79,8 @@ pthreadTidOffset(Procman::Process &proc, size_t *offsetp) if (status == notDone) { try { auto addr = proc.resolveSymbol("_thread_db_pthread_tid", true, - [](std::string_view name) { + [](const Procman::MappedObject &mapped) { + const auto name = mapped.name(); return name.find("libc." ) != std::string::npos || name.find("libpthread" ) != std::string::npos || From 6e71cce7125980dca38d3a264b5d94f8ee916caa Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sat, 31 Oct 2026 17:45:10 +0000 Subject: [PATCH 06/12] Record if a MappedObject has a "Go" note as well as the ELF build-id We can use this later to avoid scanning for any symbols, or mapping the ELF object, when we want to find the go runtime innards. --- golang.cc | 12 ++++++++---- libpstack/context.h | 1 + libpstack/proc.h | 12 ++++++------ process.cc | 18 +++++++++++++----- pstack.cc | 6 ++++++ python3.cc | 4 ++-- 6 files changed, 36 insertions(+), 17 deletions(-) diff --git a/golang.cc b/golang.cc index 6580889..93bad3b 100644 --- a/golang.cc +++ b/golang.cc @@ -26,7 +26,10 @@ Process::addGoroutines(Stacks &stacks) // If it doesn't look like a go process, and we are not forcing the issue, don't // do the work of searching for goroutines. try { - std::tie(elf, loadAddress, allgsSymbol) = resolveSymbolDetail("runtime.allgs", true); + std::tie(elf, loadAddress, allgsSymbol) = resolveSymbolDetail("runtime.allgs", true, + [&](const MappedObject &mo) { + return context.options.forceGo || mo.hasGoNote; + } ); } catch (const Exception &ex) { // Most targets are not Go programs; absence of this runtime symbol is normal. @@ -96,16 +99,17 @@ Process::addGoroutines(Stacks &stacks) goroutine.goroutineID = goid; goroutine.unwind(*this, regs); stacks.emplace(goroutine.id, std::move(goroutine)); + if (context.verbose > 1) + *context.debug << "added goroutine " << goid << "\n"; } catch (const Exception &ex) { - if (context.verbose > 1) - *context.debug << "failed to unwind Go goroutine " << i << ": " << ex.what() << "\n"; + *context.debug << "failed to unwind goroutine " << i << ": " << ex.what() << "\n"; } } } catch (const Exception &ex) { if (context.verbose > 0) - *context.debug << "Go goroutine support unavailable: " << ex.what() << "\n"; + *context.debug << "goroutine support unavailable: " << ex.what() << "\n"; } } diff --git a/libpstack/context.h b/libpstack/context.h index 1c501d2..30a0d36 100644 --- a/libpstack/context.h +++ b/libpstack/context.h @@ -24,6 +24,7 @@ struct Options { bool withDebuginfod = false; // use debuginfod client library. bool noBuildIds = false; bool noLocalFiles = false; + bool forceGo = false; unsigned maxdepth = std::numeric_limits::max(); unsigned maxframes = 30; unsigned maxthreads = 1024; diff --git a/libpstack/proc.h b/libpstack/proc.h index 36b6462..ef11410 100644 --- a/libpstack/proc.h +++ b/libpstack/proc.h @@ -222,22 +222,22 @@ using AddressSpace = std::vector; // on resource constrained systems. struct MappedObject { std::string name_; - Elf::BuildID bid_; - Elf::Object::sptr objptr_; public: + MappedObject(std::string_view n, Elf::Object::sptr objptr) : name_{n}, objptr_{objptr} {} + Elf::BuildID buildID{}; + bool hasGoNote{}; + Elf::Object::sptr objptr_{}; [[nodiscard]] const std::string &name() const { return name_; } bool operator < (const MappedObject &rhs) const { - return name_ < rhs.name_ || ( name_ == rhs.name_ && bid_ < rhs.bid_); // for comparing pairs. + return name_ < rhs.name_ || ( name_ == rhs.name_ && buildID < rhs.buildID); // for comparing pairs. } Elf::Object::sptr object(Context &ctx) { if (objptr_ == nullptr) - objptr_ = ctx.findImage(bid_); + objptr_ = ctx.findImage(buildID); if (objptr_ == nullptr) objptr_ = ctx.findImage(name_); return objptr_; } - MappedObject(std::string_view name, Elf::BuildID bid, Elf::Object::sptr objptr = {}) : - name_{name}, bid_{std::move(bid)}, objptr_{std::move(objptr)} {} }; class Process : public ps_prochandle { diff --git a/process.cc b/process.cc index 2b8dd8a..0acd128 100644 --- a/process.cc +++ b/process.cc @@ -803,10 +803,18 @@ Process::dumpFrameText(std::ostream &os, const StackFrame &frame, int frameNo) void Process::addElfObject(std::string_view name, const Elf::Object::sptr &obj, Elf::Addr load) { - Elf::BuildID bid; + MappedObject mo{name, obj}; try { auto bidElf = obj ? obj : std::make_shared(context, io->view( "in-memory elf object", load, 0x4000), false); - bid = bidElf->getBuildID(); + for (auto note : bidElf->notes()) { + if (note.name() == "GNU") { + if (note.type() == pstack::Elf::GNU_BUILD_ID) { + mo.buildID = getBuildIDFromNote(note); + } + } else if (note.name() == "Go") { + mo.hasGoNote = true; + } + } } catch (const Exception &ex) { // this is not a fatal problem - ELF headers may or may not be present in the core. @@ -814,14 +822,14 @@ Process::addElfObject(std::string_view name, const Elf::Object::sptr &obj, Elf:: *context.debug << "failed to read build id from memory image\n"; } - objects.emplace(std::make_pair(load, MappedObject{ name, bid, obj })); if (context.verbose >= 2) { IOFlagSave _(*context.debug); *context.debug << "object " << name; - if (bid) - *context.debug << " with in-process build ID " << bid; + if (mo.buildID) + *context.debug << " with in-process build ID " << mo.buildID; *context.debug << " loaded at address " << std::hex << load << std::dec << std::endl; } + objects.emplace(std::make_pair(load, std::move(mo))); } /* diff --git a/pstack.cc b/pstack.cc index cfcecb5..d677713 100644 --- a/pstack.cc +++ b/pstack.cc @@ -316,6 +316,12 @@ emain(int argc, char **argv, Context &context) std::clog << STR(VERSION) << "\n"; exitCode = 0; }) + .add("go", + 'G', + "attempt to find go routines, even if the process is not " + "heuristically characterised as a 'go' process", + Flags::setf(context.options.forceGo)) + #if defined(HAVE_PYTHON39) ||defined(WITH_PYRDB) .add("python-modules", 'm', diff --git a/python3.cc b/python3.cc index 813708d..9728b93 100644 --- a/python3.cc +++ b/python3.cc @@ -178,8 +178,8 @@ getInterpHead<3>(Procman::Process &proc) { std::tie(libpython, libpythonAddr, _PyRuntimeSym) = proc.resolveSymbolDetail( "_PyRuntime", false, - [&](std::string_view name) { - auto base = std::filesystem::path(name).filename(); + [&](const Procman::MappedObject &mo) { + auto base = std::filesystem::path(mo.name()).filename(); return std::string(base).find("python3") != std::string::npos; }); From 76edda294fae53dafdc8d8fca8020fbf98310a18 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sat, 31 Oct 2026 20:51:27 +0000 Subject: [PATCH 07/12] version bump --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 82c1cf5..546a851 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.10) -set(PSTACK_SOVERSION 2.18) -set(PSTACK_VERSION 2.18.9) +set(PSTACK_SOVERSION 2.19) +set(PSTACK_VERSION 2.19.0) project(pstack LANGUAGES C CXX VERSION "${PSTACK_VERSION}" ) set(Python3_DEBUG_OUTPUT ON) From bc325ac28a54d70baf2a57ad07c4ca645d8018ba Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sun, 1 Nov 2026 00:23:26 +0000 Subject: [PATCH 08/12] Use PT_DYNAMIC rather than sections for symbol hash tables Keep dynamic entries lazy so opening an image for notes or debug information does not require readable dynamic data. Bound virtual reads to the file-backed segment and size SysV hash arrays using the table header. If we can avoid looking at section tables while looking for dynamic symbols, then we can avoid loading otherwise unmapped pages of executable images into memory on systems where paging is expensive. --- elf.cc | 75 +++++++++++++++++++++++++++++-------------------- libpstack/elf.h | 43 ++++++++++++++++------------ 2 files changed, 69 insertions(+), 49 deletions(-) diff --git a/elf.cc b/elf.cc index 0b8faf4..586b257 100644 --- a/elf.cc +++ b/elf.cc @@ -274,20 +274,29 @@ const Object::SectionHeaders & Object::sectionHeaders() const { return *sectionHeaders_; } -std::map> & -Object::dynamic() const { - /* Load dynamic entries */ - if (!dynamic_) { - dynamic_ = std::make_shared>>(); - const auto §ion = getSection(".dynamic", SHT_DYNAMIC ); - if (section) { - ReaderArray content(*section.io()); - for (auto dyn : content) - (*dynamic_)[dyn.d_tag].push_back(dyn); +std::span +Object::dynamic(unsigned tag) const { + + assert (!isDebug); + if (dynamic_ == nullptr) { + auto newDynamic = std::make_unique(); + for (auto &seghdr: getSegments(PT_DYNAMIC)) { + auto segio = virtualView()->view("dynamic segment VA", seghdr.p_vaddr, seghdr.p_filesz); + for (auto &dyn : ReaderArray(*segio)) { + if (dyn.d_tag == DT_NULL) { + break; + } + (*newDynamic)[dyn.d_tag].push_back(dyn.d_un.d_ptr); + } } + dynamic_ = std::move(newDynamic); } - return *dynamic_; -}; + static const std::vector empty; + auto it = dynamic_->find(tag); + auto &vec = it == dynamic_->end() ? empty : it->second; + return {vec.begin(), vec.end()}; +} + const SymbolVersioning & Object::symbolVersions() const @@ -299,11 +308,11 @@ Object::symbolVersions() const const auto &gnu_version_r = getSection(".gnu.version_r", SHT_GNU_verneed ); if (gnu_version_r) { const auto &strings = getLinkedSection(gnu_version_r); - const auto &verneednum = dynamic().at(DT_VERNEEDNUM); + const auto &verneednum = dynamic(DT_VERNEEDNUM); if (verneednum.size() != 0) { size_t off = 0; - for (size_t cnt = verneednum[0].d_un.d_val; cnt != 0; --cnt) { + for (size_t cnt = verneednum[0]; cnt != 0; --cnt) { auto verneed = gnu_version_r.io()->readObj(off); Off auxOff = off + verneed.vn_aux; auto filename = strings.io()->readString(verneed.vn_file); @@ -323,10 +332,10 @@ Object::symbolVersions() const const auto &gnu_version_d = getSection(".gnu.version_d", SHT_GNU_verdef ); if (gnu_version_d) { const auto &strings = getLinkedSection(gnu_version_d); - const auto &verdefnum = dynamic().at(DT_VERDEFNUM); + const auto &verdefnum = dynamic(DT_VERDEFNUM); if (verdefnum.size() != 0) { size_t off = 0; - for (size_t cnt = verdefnum[0].d_un.d_val; cnt != 0; --cnt) { + for (size_t cnt = verdefnum[0]; cnt != 0; --cnt) { auto verdef = gnu_version_d.io()->readObj(off); Off auxOff = off + verdef.vd_aux; // IF there are multiple verdaux entries, the first is the @@ -658,26 +667,32 @@ struct VirtualElfReader : public Reader { csptr view(const std::string &name, Off start, Off length=std::numeric_limits::max()) const override; size_t read(Off off, size_t count, char *ptr) const override; private: - template I translate(I from) const; + std::pair translate(Off addr, Off size) const; std::shared_ptr elf; }; -template -I VirtualElfReader::translate(I from) const { - auto seg = elf->getSegmentForAddress( from ); +std::pair VirtualElfReader::translate(Off addr, Off len) const { + auto seg = elf->getSegmentForAddress( addr ); if (seg == 0) { throw Exception() << "invalid address for ELF image"; } - return from - seg->p_vaddr + seg->p_offset; + auto segoff = addr - seg->p_vaddr; + if (segoff > seg->p_filesz) + throw Exception() << "invalid address for ELF image"; + return { segoff + seg->p_offset, std::min(len, seg->p_filesz - segoff) }; } Reader::csptr VirtualElfReader::view(const std::string &name, Off start, Off length) const { - return elf->io->view(name, translate(start), length); + auto [fileoff, caplen] = translate(start, length); + return elf->io->view(name, fileoff, caplen); } size_t VirtualElfReader::read(Off off, size_t count, char *ptr) const { - return elf->io->read(translate(off), count, ptr); + if (count == 0) + return 0; + auto [fileoff, caplen] = translate(off, count); + return elf->io->read(fileoff, caplen, ptr); } Reader::csptr @@ -692,19 +707,17 @@ SymHash::SymHash(Reader::csptr hash_, , strings(std::move(strings_)) { // read the hash table into local memory. - size_t words = hash->size() / sizeof (Word); - data.resize(words); - hash->readObj(0, data.data(), words); - nbucket = data[0]; - nchain = data[1]; - buckets = data.data() + 2; - chains = buckets + nbucket; + hash->readObj(0, &header); + buckets.resize(header.nbucket); + chains.resize(header.nchain); + hash->readObj(sizeof header, buckets.data(), buckets.size()); + hash->readObj(sizeof header + sizeof buckets[0] * buckets.size(), chains.data(), chains.size()); } std::pair SymHash::findSymbol(const string &name) { - uint32_t bucket = elf_hash(name) % nbucket; + uint32_t bucket = elf_hash(name) % header.nbucket; for (Word i = buckets[bucket]; i != STN_UNDEF; i = chains[i]) { auto candidate = syms->readObj(i * sizeof (Sym)); auto candidateName = strings->readString(candidate.st_name); diff --git a/libpstack/elf.h b/libpstack/elf.h index 000d312..feda351 100644 --- a/libpstack/elf.h +++ b/libpstack/elf.h @@ -141,14 +141,16 @@ class SymHash { Reader::csptr hash; Reader::csptr syms; Reader::csptr strings; - Word nbucket; - Word nchain; - std::vector data; - const Word *chains; - const Word *buckets; + struct { + Word nbucket; + Word nchain; + } header; + std::vector chains; + std::vector buckets; public: - static const char *tablename() { return ".hash"; } - static int sectiontype() { return SHT_HASH; } + static constexpr const char *tablename() { return ".hash"; } + static constexpr int sectiontype() { return SHT_HASH; } + static constexpr int dynhash() { return DT_HASH; } SymHash(Reader::csptr hash_, Reader::csptr syms_, Reader::csptr strings_); std::pair findSymbol(const std::string &name); // fills sym, and returns index. }; @@ -174,8 +176,9 @@ class GnuHash { [[nodiscard]] uint32_t bucketoff(size_t idx) const noexcept { return bloomoff(header.bloom_size) + idx * 4; } [[nodiscard]] uint32_t chainoff(size_t idx) const noexcept { return bucketoff(header.nbuckets) + idx * 4; } public: - static const char *tablename() noexcept { return ".gnu.hash"; } - static int sectiontype() { return SHT_GNU_HASH; } + static constexpr const char *tablename() noexcept { return ".gnu.hash"; } + static constexpr int sectiontype() { return SHT_GNU_HASH; } + static constexpr int dynhash() { return DT_GNU_HASH; } GnuHash(Reader::csptr hash_, Reader::csptr syms_, Reader::csptr strings_) : hash(std::move(hash_)) @@ -289,7 +292,7 @@ class Object : public std::enable_shared_from_this { public: using sptr = std::shared_ptr; using ProgramHeaders = std::vector; - using Dynamic = std::map>; + using Dynamic = std::map>; using ProgramHeadersByType = std::map; using SectionHeaders = std::vector>; @@ -353,7 +356,7 @@ class Object : public std::enable_shared_from_this { mutable std::unique_ptr symbolVersions_; mutable std::unique_ptr sectionHeaders_; mutable std::map namedSection; - mutable std::shared_ptr dynamic_; + mutable std::unique_ptr dynamic_; mutable std::unique_ptr debugSymbols_; mutable std::unique_ptr dynamicSymbols_; mutable Object::sptr debugObject; // debug object as per .gnu_debuglink/other. @@ -370,7 +373,7 @@ class Object : public std::enable_shared_from_this { ProgramHeadersByType programHeaders_; SymbolSection &getSymtab(std::unique_ptr &table, const char *name, int type) const; - Dynamic &dynamic() const; + std::span dynamic(unsigned) const; const SectionHeaders §ionHeaders() const; @@ -378,12 +381,16 @@ class Object : public std::enable_shared_from_this { // types and section names, so share the code. template HashType *get_hash(std::unique_ptr &ptr) const { if (ptr == nullptr) { - auto §ion { getSection( HashType::tablename(), HashType::sectiontype() ) }; - if (section) { - auto &syms = getLinkedSection(section); - auto &strings = getLinkedSection(syms); - if (syms && strings) - ptr = std::make_unique(section.io(), syms.io(), strings.io()); + auto dt_strtab = dynamic(DT_STRTAB); + auto dt_strsz = dynamic(DT_STRSZ); + auto dt_hash = dynamic(HashType::dynhash()); + auto dt_symtab = dynamic(DT_SYMTAB); + if (!dt_strtab.empty() && !dt_strsz.empty() && !dt_hash.empty() && !dt_symtab.empty()) { + auto elfReader = virtualView(); + ptr = std::make_unique( + elfReader->view("hash table", dt_hash[0]), + elfReader->view("sym table", dt_symtab[0]), + elfReader->view("string table", dt_strtab[0], dt_strsz[0])); } } return ptr.get(); From c2dae07b9412739d1beb0b0bb2c6febe0820198d Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sun, 1 Nov 2026 02:00:52 +0000 Subject: [PATCH 09/12] Add AI-generated test --- tests/CMakeLists.txt | 28 +++++- tests/elf-fixture.c | 3 + tests/elf-regressions.cc | 209 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 239 insertions(+), 1 deletion(-) create mode 100644 tests/elf-fixture.c create mode 100644 tests/elf-regressions.cc diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 50400de..1bedd9c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -24,6 +24,29 @@ add_executable(noreturn noreturn.c noreturn-ext.c) add_executable(cpp cpp.cc) add_executable(procself procself.cc) add_executable(suspend suspend.cc) +add_executable(elf-regressions elf-regressions.cc) + +foreach(hash_style sysv gnu) + add_library(elf-fixture-${hash_style} SHARED elf-fixture.c) + target_link_options(elf-fixture-${hash_style} PRIVATE + -Wl,--hash-style=${hash_style} -Wl,--build-id=sha1) +endforeach() + +set(ELF_STRIPPED_FIXTURE ${CMAKE_CURRENT_BINARY_DIR}/elf-debug-fixture.so) +set(ELF_DEBUG_FIXTURE ${ELF_STRIPPED_FIXTURE}.debug) +add_custom_command( + OUTPUT ${ELF_STRIPPED_FIXTURE} ${ELF_DEBUG_FIXTURE} + COMMAND ${CMAKE_OBJCOPY} --only-keep-debug + $ ${ELF_DEBUG_FIXTURE} + COMMAND ${CMAKE_OBJCOPY} --strip-debug + $ ${ELF_STRIPPED_FIXTURE} + COMMAND ${CMAKE_OBJCOPY} --add-gnu-debuglink=${ELF_DEBUG_FIXTURE} + ${ELF_STRIPPED_FIXTURE} + DEPENDS elf-fixture-gnu + VERBATIM) +add_custom_target(elf-debug-fixture DEPENDS ${ELF_STRIPPED_FIXTURE} ${ELF_DEBUG_FIXTURE}) +add_dependencies(elf-regressions elf-fixture-sysv elf-debug-fixture) +target_link_libraries(elf-regressions dwelf) target_link_libraries(thread pthread testhelper) target_link_libraries(badfp testhelper) @@ -69,8 +92,11 @@ add_test(NAME thread COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/t add_test(NAME jsondump COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/dump-test.py) add_test(NAME procself COMMAND $) +add_test(NAME elf COMMAND elf-regressions + $ $ + ${ELF_STRIPPED_FIXTURE} ${ELF_DEBUG_FIXTURE}) -set(ALL_TESTS args badfp basic cpp noreturn segv thread jsondump) +set(ALL_TESTS args badfp basic cpp noreturn segv thread jsondump elf) if (Python3_Development_FOUND) add_test(NAME python_path_test COMMAND python_path_test) diff --git a/tests/elf-fixture.c b/tests/elf-fixture.c new file mode 100644 index 0000000..31caf9e --- /dev/null +++ b/tests/elf-fixture.c @@ -0,0 +1,3 @@ +int elf_test_symbol(void) { + return 42; +} diff --git a/tests/elf-regressions.cc b/tests/elf-regressions.cc new file mode 100644 index 0000000..c26aa4e --- /dev/null +++ b/tests/elf-regressions.cc @@ -0,0 +1,209 @@ +#include "libpstack/elf.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace fs = std::filesystem; +using namespace pstack; + +void check(bool condition, const std::string &message) { + if (!condition) + throw std::runtime_error(message); +} + +template +void expectException(Func func, const std::string &message) { + try { + func(); + } catch (const Exception &) { + return; + } + throw std::runtime_error(message); +} + +struct TempDirectory { + fs::path path; + TempDirectory() { + auto pattern = (fs::temp_directory_path() / "pstack-elf-XXXXXX").string(); + check(mkdtemp(pattern.data()) != nullptr, "cannot create test directory"); + path = pattern; + } + ~TempDirectory() { + std::error_code ec; + fs::remove_all(path, ec); + } +}; + +std::vector readFile(const fs::path &path) { + std::ifstream input(path, std::ios::binary); + check(bool(input), "cannot read " + path.string()); + return {std::istreambuf_iterator(input), std::istreambuf_iterator()}; +} + +void writeFile(const fs::path &path, const std::vector &bytes) { + std::ofstream output(path, std::ios::binary); + output.write(bytes.data(), bytes.size()); + check(bool(output), "cannot write " + path.string()); +} + +void testHash(const fs::path &fixture, const fs::path &withoutSections) { + Context context; + auto object = context.openImage(fixture); + const auto [symbol, index] = object->findDynamicSymbol("elf_test_symbol"); + check(index != 0 && symbol.st_shndx != SHN_UNDEF, "dynamic symbol lookup failed"); + check(object->findDynamicSymbol("pstack_missing_symbol").first.st_shndx == SHN_UNDEF, + "missing dynamic symbol should be undefined"); + + // Runtime symbol lookup must also work after the section table is removed. + auto bytes = readFile(fixture); + Elf::Ehdr header; + std::memcpy(&header, bytes.data(), sizeof header); + header.e_shoff = 0; + header.e_shnum = 0; + header.e_shstrndx = SHN_UNDEF; + std::memcpy(bytes.data(), &header, sizeof header); + writeFile(withoutSections, bytes); + auto sectionless = context.openImage(withoutSections); + const auto [found, foundIndex] = sectionless->findDynamicSymbol("elf_test_symbol"); + check(foundIndex == index && found.st_value == symbol.st_value && found.st_shndx != SHN_UNDEF, + "dynamic symbol lookup requires section headers"); +} + +void testDebugLink(const fs::path &stripped, const fs::path &debug, const fs::path &directory) { + Context context; + auto original = context.openImage(stripped); + auto buildID = original->getBuildID(); + check(bool(buildID), "fixture has no build ID"); + auto debugObject = context.openImage(debug, -1, true); + check(debugObject->getBuildID() == buildID, "separate debug file build ID differs"); + check(bool(debugObject->getSection(".debug_info", SHT_PROGBITS)), "debug fixture has no DWARF"); + check(!original->getSection(".debug_info", SHT_PROGBITS), "fixture was not stripped"); + + std::ostringstream id; + id << buildID; + auto link = directory / id.str().substr(0, 2) / id.str().substr(2); + fs::create_directories(link.parent_path()); + fs::create_symlink(fs::absolute(stripped), link); + context.exeBuildIdPrefixes = {directory}; + context.debugBuildIdPrefixes.clear(); + context.debugPrefixes = {""}; + auto linked = context.findImage(buildID); + check(bool(linked), "cannot load fixture through build-ID symlink"); + check(bool(linked->getDebugSection(".debug_info", SHT_PROGBITS)), + "cannot find debug link beside the build-ID symlink target"); +} + +void testPartialImage(const fs::path &fixture, const fs::path &partial) { + Context context; + auto original = context.openImage(fixture); + auto buildID = original->getBuildID(); + check(bool(buildID), "fixture has no build ID"); + const auto &dynamic = original->getSegments(PT_DYNAMIC); + check(dynamic.size() == 1, "fixture must have one dynamic segment"); + auto bytes = readFile(fixture); + check(dynamic[0].p_offset < bytes.size(), "dynamic segment is outside fixture"); + bytes.resize(dynamic[0].p_offset); + writeFile(partial, bytes); + + // Use file reads so the absent dynamic segment produces EOF, as with a + // partial core, rather than reading beyond an mmap of a truncated file. + auto reader = std::make_shared(context, partial); + auto object = std::make_shared(context, reader); + check(object->getBuildID() == buildID, "missing dynamic data prevents build-ID recovery"); + expectException([&] { object->findDynamicSymbol("elf_test_symbol"); }, + "partial fixture unexpectedly contains dynamic data"); +} + +void testReader(const fs::path &fixture) { + // Keep bytes beyond p_filesz in the file to detect reads that escape the + // segment. The segment's BSS extends beyond its file-backed contents. + Elf::Ehdr header{}; + std::memcpy(header.e_ident, ELFMAG, SELFMAG); + header.e_ident[EI_CLASS] = ELF_BITS == 64 ? ELFCLASS64 : ELFCLASS32; + header.e_ident[EI_DATA] = std::endian::native == std::endian::little ? ELFDATA2LSB : ELFDATA2MSB; + header.e_ident[EI_VERSION] = EV_CURRENT; + header.e_version = EV_CURRENT; + header.e_type = ET_DYN; + header.e_ehsize = sizeof header; + header.e_phoff = sizeof header; + header.e_phentsize = sizeof(Elf::Phdr); + header.e_phnum = 1; + Elf::Phdr segment{}; + segment.p_type = PT_LOAD; + segment.p_offset = 0x100; + segment.p_vaddr = 0x1000; + segment.p_filesz = 0x10; + segment.p_memsz = 0x30; + std::vector bytes(0x200, 'A'); + std::memcpy(bytes.data(), &header, sizeof header); + std::memcpy(bytes.data() + header.e_phoff, &segment, sizeof segment); + writeFile(fixture, bytes); + + Context context; + auto object = context.openImage(fixture); + auto reader = object->virtualView(); + check(reader->view("segment remainder", 0x100e)->size() == 2, "unlimited view escapes segment"); + auto bounded = reader->view("bounded", 0x100e, 8); + check(bounded->size() == 2, "explicit view escapes segment"); + std::array output{}; + check(bounded->read(0, output.size(), output.data()) == 2, "view read escapes segment"); + check(reader->read(0x100e, output.size(), output.data()) == 2, "direct read escapes segment"); + check(reader->read(0x100f, 1, output.data()) == 1 && output[0] == 'A', "last file-backed byte unreadable"); + check(reader->view("empty", 0x1000, 0)->size() == 0, "zero-length view expands"); + check(reader->read(0x1000, 0, output.data()) == 0, "zero-length read expands"); + check(reader->view("end", 0x1010)->size() == 0, "view at file-backed end is not empty"); + check(reader->read(0x1010, 1, output.data()) == 0, "read at file-backed end is not empty"); + expectException([&] { reader->view("bss", 0x1011); }, "view inside BSS should fail"); + expectException([&] { reader->read(0x1011, 1, output.data()); }, "read inside BSS should fail"); + expectException([&] { reader->view("unmapped", 0x2000); }, "unmapped view should fail"); + expectException([&] { reader->readObj(0x100e); }, "object read crossing segment should fail"); + + std::weak_ptr weak = object; + object.reset(); + check(!weak.expired(), "virtual reader does not retain its ELF object"); + check(reader->read(0x1000, 1, output.data()) == 1, "retained reader is unusable"); + bounded.reset(); + reader.reset(); + check(weak.expired(), "virtual reader creates an ownership cycle"); +} + +void testRemovedFile(const fs::path &fixture, const fs::path &removed) { + fs::copy_file(fixture, removed); + Context context; + auto object = context.openImage(removed); + fs::remove(removed); + check(!object->io->filename().empty(), "removed mapping has no filename"); + std::ostringstream description; + object->io->describe(description); + check(!description.str().empty(), "removed mapping has no description"); + check(object->io->readObj(0).e_ident[EI_MAG0] == ELFMAG0, + "removed mapping is unreadable"); +} +} + +int main(int argc, char **argv) { + try { + check(argc == 5, "expected SysV, GNU, stripped and debug fixture paths"); + TempDirectory directory; + testHash(argv[1], directory.path / "sysv-sectionless.so"); + testHash(argv[2], directory.path / "gnu-sectionless.so"); + testDebugLink(argv[3], argv[4], directory.path / "build-id"); + testPartialImage(argv[2], directory.path / "partial.so"); + testReader(directory.path / "segments.so"); + testRemovedFile(argv[2], directory.path / "removed.so"); + } catch (const std::exception &ex) { + std::cerr << "ELF regression: " << ex.what() << '\n'; + return 1; + } + return 0; +} From 15f0c30d38030d38ad5a4de50ecd1bc31ed3ec6e Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sun, 1 Nov 2026 02:13:55 +0000 Subject: [PATCH 10/12] Do a better job with move semantics. In a number of places, there are opportunities to move objects, rather than copy them. Do that. --- canal.cc | 7 ++-- dead.cc | 2 +- dwarf_lines.cc | 8 ++-- elf.cc | 2 +- libpstack/elf.h | 20 ++------- libpstack/exception.h | 30 ++++++++------ libpstack/proc.h | 2 +- process.cc | 5 ++- reader.cc | 2 +- tests/CMakeLists.txt | 4 +- tests/elf-regressions.cc | 44 ++++++++++++++++++++ tests/exception-regressions.cc | 76 ++++++++++++++++++++++++++++++++++ 12 files changed, 159 insertions(+), 43 deletions(-) create mode 100644 tests/exception-regressions.cc diff --git a/canal.cc b/canal.cc index eff4581..ca10aa9 100644 --- a/canal.cc +++ b/canal.cc @@ -72,9 +72,9 @@ struct ListedSymbol { ListedSymbol(const Elf::Sym &sym_, Elf::Off objbase_, string name_, string object) : sym(sym_) , objbase(objbase_) - , name(name_) + , name(std::move(name_)) , count(0) - , objname(object) + , objname(std::move(object)) {} Elf::Off memaddr() const { return sym.st_value + objbase; } }; @@ -84,7 +84,8 @@ class SymbolStore { public: void add(ListedSymbol symbol) { - store_.emplace(symbol.memaddr() + symbol.sym.st_size, symbol); + const auto end = symbol.memaddr() + symbol.sym.st_size; + store_.emplace(end, std::move(symbol)); } template diff --git a/dead.cc b/dead.cc index c093af1..de87663 100644 --- a/dead.cc +++ b/dead.cc @@ -83,7 +83,7 @@ CoreProcess::CoreProcess(Context &ctx, Elf::Object::sptr exec, Elf::Object::sptr break; } } - notes.push_back( note ); + notes.push_back( std::move(note) ); } } diff --git a/dwarf_lines.cc b/dwarf_lines.cc index dc9d457..ad963bf 100644 --- a/dwarf_lines.cc +++ b/dwarf_lines.cc @@ -93,7 +93,7 @@ LineInfo::build(DWARFReader &r, Unit &unit) if (path == "") { *unit.dwarf->elf->context.debug << "no path in directory table entry" << std::endl; } else { - directories.emplace_back(path); + directories.emplace_back(std::move(path)); } } EntryFormats fileFormat = readEntryFormats(r); @@ -113,15 +113,15 @@ LineInfo::build(DWARFReader &r, Unit &unit) break; } } - files.push_back(entry); + files.push_back(std::move(entry)); } } else { directories.emplace_back("."); for (;;) { - const auto &s = r.getstring(); + auto s = r.getstring(); if (s == "") break; - directories.push_back(s); + directories.push_back(std::move(s)); } files.emplace_back("unknown", 0U, 0U, 0U); // index 0 is special diff --git a/elf.cc b/elf.cc index 586b257..7a845fa 100644 --- a/elf.cc +++ b/elf.cc @@ -583,7 +583,7 @@ BuildID getBuildIDFromNote(const NoteDesc ¬e) { auto noteIo = note.data(); std::vector data(noteIo->size()); noteIo->readObj(0, data.data(), noteIo->size()); - return BuildID{ data }; + return BuildID{ std::move(data) }; } BuildID Object::getBuildID() const { diff --git a/libpstack/elf.h b/libpstack/elf.h index feda351..7b5eb13 100644 --- a/libpstack/elf.h +++ b/libpstack/elf.h @@ -258,7 +258,7 @@ class SymbolSection { } SymbolSection(Reader::csptr symbols_, Reader::csptr strings_) - : symbols(symbols_), strings(strings_), array(*symbols) + : symbols(std::move(symbols_)), strings(std::move(strings_)), array(*symbols) {} std::string name(const Sym &sym) const { return strings->readString(sym.st_name, std::numeric_limits::max()); } }; @@ -410,8 +410,7 @@ class NoteDesc { public: NoteDesc() = default; - NoteDesc(const NoteDesc &rhs) = default; - NoteDesc(const Note ¬e_, Reader::csptr io_) : note(note_) , io(io_) { } + NoteDesc(const Note ¬e_, Reader::csptr io_) : note(note_) , io(std::move(io_)) { } [[nodiscard]] std::string name() const; Reader::csptr data() const; int type() const { return note.n_type; } @@ -492,11 +491,6 @@ class Notes::iterator { bool operator == ( const auto & ) const { return false; } invalid & operator ++ ( ) { return *this; } invalid operator ++ ( int ) { return *this; } - invalid(const invalid &) { } - invalid(invalid &&) { } - invalid() {} - invalid &operator = (const invalid &) = default; - invalid &operator = (invalid &&) = default; using difference_type = int; NoteDesc operator *() { return NoteDesc{}; } }; @@ -504,15 +498,9 @@ class Notes::iterator { public: using difference_type = std::ptrdiff_t; - iterator(Notes::section_iterator &&it) : choice( it ) {} - iterator(Notes::segment_iterator &&it) : choice( it ) {} + iterator(Notes::section_iterator &&it) : choice( std::move(it) ) {} + iterator(Notes::segment_iterator &&it) : choice( std::move(it) ) {} iterator() : choice{invalid{}} {} - iterator(const iterator &rhs) : choice{rhs.choice} {} - - iterator & operator = (const iterator &rhs) { - std::visit([this](auto &arg) { choice = arg; }, rhs.choice); - return *this; - } bool operator == (const sentinel &rhs) const { return std::visit([&rhs](auto &lhs) { return lhs == rhs; }, choice); diff --git a/libpstack/exception.h b/libpstack/exception.h index 3db6cc3..ed527c7 100644 --- a/libpstack/exception.h +++ b/libpstack/exception.h @@ -8,25 +8,29 @@ class Exception : public std::exception { mutable std::ostringstream str; mutable std::string intermediate; public: - Exception() noexcept = default; - Exception(const Exception &rhs) noexcept : str{ rhs.str.str() } {} - Exception(Exception &&rhs) noexcept : str{ std::move(rhs.str ) } {} + Exception() = default; + // Keep the put position at the end so streaming onto a copy appends. + Exception(const Exception &rhs) : str{ rhs.str.str(), std::ios::out | std::ios::ate } {} + Exception(Exception &&rhs) = default; - Exception &operator = (const Exception &rhs) noexcept { - str.clear(); - str << rhs.str.str(); + Exception &operator = (const Exception &rhs) { + if (this != &rhs) { + str = std::ostringstream{rhs.str.str(), std::ios::out | std::ios::ate}; + intermediate.clear(); + } return *this; }; - Exception &operator = (Exception &&rhs) noexcept { - str = std::move(rhs.str); - return *this; - }; + Exception &operator = (Exception &&rhs) = default; ~Exception() noexcept = default; - const char *what() const noexcept { - intermediate = str.str(); - return intermediate.c_str(); + const char *what() const noexcept override { + try { + intermediate = str.str(); + return intermediate.c_str(); + } catch (...) { + return "pstack exception (message unavailable)"; + } } std::ostream &getStream() const { return str; } typedef void IsStreamable; diff --git a/libpstack/proc.h b/libpstack/proc.h index ef11410..d80e958 100644 --- a/libpstack/proc.h +++ b/libpstack/proc.h @@ -223,7 +223,7 @@ using AddressSpace = std::vector; struct MappedObject { std::string name_; public: - MappedObject(std::string_view n, Elf::Object::sptr objptr) : name_{n}, objptr_{objptr} {} + MappedObject(std::string_view n, Elf::Object::sptr objptr) : name_{n}, objptr_{std::move(objptr)} {} Elf::BuildID buildID{}; bool hasGoNote{}; Elf::Object::sptr objptr_{}; diff --git a/process.cc b/process.cc index 0acd128..2377e97 100644 --- a/process.cc +++ b/process.cc @@ -364,9 +364,10 @@ Process::processAUXV(const Reader &auxio) std::vector data; data.resize(n.n_descsz); io->read(noteVa + sizeof n + 4, n.n_descsz, (char *)data.data()); + Elf::BuildID buildID{std::move(data)}; if (context.verbose > 1) - *context.debug << "build ID From AT_PHDR: " << Elf::BuildID(data) << "\n"; - execImage = context.findImage(Elf::BuildID{data}); + *context.debug << "build ID From AT_PHDR: " << buildID << "\n"; + execImage = context.findImage(buildID); break; } } diff --git a/reader.cc b/reader.cc index 70b3c29..7fa714c 100644 --- a/reader.cc +++ b/reader.cc @@ -248,7 +248,7 @@ AbstractMemReader::view(const std::string &name, Off offset, Off size) const { } OffsetReader::OffsetReader(std::string name_, Reader::csptr upstream_, Off offset_, Off length_) - : upstream(upstream_) + : upstream(std::move(upstream_)) , offset(offset_) , name(std::move(name_)) { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1bedd9c..c0e03d2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -25,6 +25,7 @@ add_executable(cpp cpp.cc) add_executable(procself procself.cc) add_executable(suspend suspend.cc) add_executable(elf-regressions elf-regressions.cc) +add_executable(exception-regressions exception-regressions.cc) foreach(hash_style sysv gnu) add_library(elf-fixture-${hash_style} SHARED elf-fixture.c) @@ -92,11 +93,12 @@ add_test(NAME thread COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/t add_test(NAME jsondump COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/dump-test.py) add_test(NAME procself COMMAND $) +add_test(NAME exception COMMAND exception-regressions) add_test(NAME elf COMMAND elf-regressions $ $ ${ELF_STRIPPED_FIXTURE} ${ELF_DEBUG_FIXTURE}) -set(ALL_TESTS args badfp basic cpp noreturn segv thread jsondump elf) +set(ALL_TESTS args badfp basic cpp noreturn segv thread jsondump elf exception) if (Python3_Development_FOUND) add_test(NAME python_path_test COMMAND python_path_test) diff --git a/tests/elf-regressions.cc b/tests/elf-regressions.cc index c26aa4e..65bbd2e 100644 --- a/tests/elf-regressions.cc +++ b/tests/elf-regressions.cc @@ -10,6 +10,8 @@ #include #include #include +#include +#include #include namespace { @@ -189,6 +191,47 @@ void testRemovedFile(const fs::path &fixture, const fs::path &removed) { check(object->io->readObj(0).e_ident[EI_MAG0] == ELFMAG0, "removed mapping is unreadable"); } + +void testNoteMoves(const fs::path &fixture) { + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + + Context context; + auto reader = std::make_shared(context, fixture); + Elf::Note header{}; + header.n_type = Elf::GNU_BUILD_ID; + Elf::NoteDesc note(header, reader); + const auto owners = reader.use_count(); + Elf::NoteDesc moved(std::move(note)); + check(reader.use_count() == owners, "moving a note copied its reader"); + Elf::NoteDesc assigned; + assigned = std::move(moved); + check(reader.use_count() == owners, "move-assigning a note copied its reader"); + check(assigned.type() == Elf::GNU_BUILD_ID, "note move lost its type"); + auto copied = assigned; + check(reader.use_count() == owners + 1 && copied.type() == Elf::GNU_BUILD_ID, + "copying a note no longer shares its reader"); + + auto object = context.openImage(fixture); + const auto objectOwners = object->io.use_count(); + Elf::Notes::segment_iterator segment(object.get()); + Elf::Notes::iterator iterator(std::move(segment)); + Elf::Notes::iterator movedIterator(std::move(iterator)); + { + Elf::Notes::iterator assignedIterator; + assignedIterator = std::move(movedIterator); + check(!(assignedIterator == object->notes().end()), "moved note iterator is at end"); + check((*assignedIterator).name() == "GNU", "moved note iterator is unreadable"); + auto copy = assignedIterator; + Elf::Notes::iterator copyAssigned; + copyAssigned = copy; + check(copyAssigned == assignedIterator, "copied note iterator changed position"); + } + check(object->io.use_count() == objectOwners, + "moved-from note iterators retained the segment reader"); +} } int main(int argc, char **argv) { @@ -201,6 +244,7 @@ int main(int argc, char **argv) { testPartialImage(argv[2], directory.path / "partial.so"); testReader(directory.path / "segments.so"); testRemovedFile(argv[2], directory.path / "removed.so"); + testNoteMoves(argv[2]); } catch (const std::exception &ex) { std::cerr << "ELF regression: " << ex.what() << '\n'; return 1; diff --git a/tests/exception-regressions.cc b/tests/exception-regressions.cc new file mode 100644 index 0000000..9f2a6ec --- /dev/null +++ b/tests/exception-regressions.cc @@ -0,0 +1,76 @@ +#include "libpstack/exception.h" + +#include +#include +#include +#include +#include + +using pstack::Exception; + +static_assert(!std::is_nothrow_copy_constructible_v); +static_assert(!std::is_nothrow_copy_assignable_v); +static_assert(std::is_nothrow_move_constructible_v == + std::is_nothrow_move_constructible_v); +static_assert(std::is_nothrow_move_assignable_v == + std::is_nothrow_move_assignable_v); + +namespace { +void checkMessage(const Exception &exception, std::string_view expected) { + if (exception.what() != expected) + throw std::runtime_error("exception message mismatch: " + std::string(exception.what())); +} + +void testExceptions() { + Exception original; + checkMessage(original, ""); + original << "source " << 42; + checkMessage(original, "source 42"); + + Exception copied(original); + copied << " copied"; + checkMessage(copied, "source 42 copied"); + checkMessage(original, "source 42"); + + Exception assigned; + assigned << "old destination text"; + checkMessage(assigned, "old destination text"); + assigned.getStream().setstate(std::ios::failbit); + assigned = original; + checkMessage(assigned, "source 42"); + assigned << " assigned"; + checkMessage(assigned, "source 42 assigned"); + assigned = original; + checkMessage(assigned, "source 42"); + const Exception &self = assigned; + assigned = self; + assigned << " self"; + checkMessage(assigned, "source 42 self"); + + Exception moved(std::move(copied)); + checkMessage(moved, "source 42 copied"); + moved << " moved"; + checkMessage(moved, "source 42 copied moved"); + assigned = std::move(moved); + checkMessage(assigned, "source 42 copied moved"); + assigned << " assigned"; + checkMessage(assigned, "source 42 copied moved assigned"); + + try { + throw Exception() << "thrown " << 7; + } catch (const Exception &exception) { + checkMessage(exception, "thrown 7"); + exception << " caught"; + checkMessage(exception, "thrown 7 caught"); + } +} +} + +int main() { + try { + testExceptions(); + } catch (const std::exception &exception) { + std::cerr << "Exception regression: " << exception.what() << '\n'; + return 1; + } +} From c68a67d53e7631fd88be0acfee813dd4a1b0d5e0 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sun, 1 Nov 2026 09:45:09 +0000 Subject: [PATCH 11/12] Do less scanning over notes in a core. Rather than record every note, and still go searching for readers for things like siginfo_t, NT_FILE, etc., grab them opportunistically as we scan the notes in the ctor. We still record most notes, but now bucket them by lwp, so we don't have to use the non-obvious indexing map any more. --- dead.cc | 68 +++++++++++++++++++++--------------------------- libpstack/proc.h | 5 ++-- 2 files changed, 32 insertions(+), 41 deletions(-) diff --git a/dead.cc b/dead.cc index de87663..8af54ca 100644 --- a/dead.cc +++ b/dead.cc @@ -62,48 +62,49 @@ CoreProcess::CoreProcess(Context &ctx, Elf::Object::sptr exec, Elf::Object::sptr , prpsinfo{} , coreImage(std::move(core)) { + lwpid_t curLwp = -1; for (auto note : coreImage->notes()) { if (note.name() == "CORE") { switch (note.type() ) { case NT_PRSTATUS: { - // for NT_PRSTATUS notes, mark the index of the current note in our - // vector as the start of the notes for that LWP. When looking - // for an LWP-related note, we start at the index for that LWPs - // NT_PRSTATUS, and consider it a failure if we reach another - // NT_PRSTATUS or the end of the list. + // Notes from here to the next NT_PRSTATUS are potentially + // associated with the LWP in the prstatus_t here. Aggregate + // those notes appropriately auto task = note.data()->readObj(0); - lwpToPrStatusIdx[task.pr_pid] = notes.size(); + curLwp = task.pr_pid; break; } case NT_PRPSINFO: { note.data()->readObj(0, &prpsinfo); // hold on to a copy of this break; } - default: + case NT_SIGINFO: + siginfo_ = note.data()->readObj(0); break; + case NT_AUXV: + auxv_ = note.data(); + break; + case NT_FILE: + break; + default: + break; } } - notes.push_back( std::move(note) ); + if (curLwp != -1) + lwpNotes[curLwp].push_back(std::move(note)); } } void CoreProcess::listLWPs(const std::function &cb) { - for (auto &task : lwpToPrStatusIdx) + for (auto &task : lwpNotes) cb(task.first); } Reader::csptr CoreProcess::getAUXV() const { -#ifdef __linux__ - for (const auto ¬e : notes) { - if (note.name() == "CORE" && note.type() == NT_AUXV) { - return note.data(); - break; - } - } -#endif - return {}; + return auxv_; + } void CoreReader::describe(std::ostream &os) const @@ -191,27 +192,22 @@ CoreReader::CoreReader(Process *p_, Elf::Object::sptr core_) : p(p_), core(std:: size_t CoreProcess::getRegs(lwpid_t lwpid, int code, size_t size, void *data) { - auto idx = lwpToPrStatusIdx.find( lwpid ); - if ( idx == lwpToPrStatusIdx.end() ) { + auto lwpNotesIt = lwpNotes.find(lwpid); + if (lwpNotesIt == lwpNotes.end()) return 0; - } - for (size_t i = idx->second;;) { - if (notes[i].type() == code) { + + for (auto note : lwpNotesIt->second) { + if (note.type() == code) { if (code == NT_PRSTATUS) { - auto prstatus = notes[i].data()->readObj(0); + auto prstatus = note.data()->readObj(0); size = std::min(size, sizeof prstatus.pr_reg); memcpy(data, &prstatus.pr_reg, size); } else { - size = std::min(size, size_t(notes[i].data()->size())); - notes[i].data()->read(0, size, reinterpret_cast(data)); + size = std::min(size, size_t(note.data()->size())); + note.data()->read(0, size, reinterpret_cast(data)); } return size; } - ++i; - if (i == notes.size() || ( notes[i].type() == NT_PRSTATUS && notes[i].name() == "CORE") ) { - // We're done if that's all the notes, or the next note is the start of a new LWP. - break; - } } return 0; } @@ -332,14 +328,8 @@ CoreProcess::loadSharedObjectsFromFileNote() std::optional CoreProcess::getSignalInfo() const { -#ifdef NT_SIGINFO - for ( const auto ¬e : coreImage->notes() ) { - if ( note.name() == "CORE" && note.type() == NT_SIGINFO ) { - return note.data()->readObj(0); - } - } -#endif - return std::nullopt; + return siginfo_; + } } diff --git a/libpstack/proc.h b/libpstack/proc.h index d80e958..cff0c4a 100644 --- a/libpstack/proc.h +++ b/libpstack/proc.h @@ -416,9 +416,10 @@ class CoreReader final : public Reader { }; class CoreProcess : public Process { - std::vector notes; - std::map lwpToPrStatusIdx; prpsinfo_t prpsinfo; + std::optional siginfo_; + std::map> lwpNotes; + Reader::csptr auxv_; public: Elf::Object::sptr coreImage; CoreProcess(Context &, Elf::Object::sptr exec, Elf::Object::sptr core); From c9680be3451e07d15fc6972c1b80b52de071d646 Mon Sep 17 00:00:00 2001 From: Peter Edwards Date: Sun, 1 Nov 2026 23:14:51 +0000 Subject: [PATCH 12/12] version bump to 2.19.1 --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 546a851..e5ba605 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.10) set(PSTACK_SOVERSION 2.19) -set(PSTACK_VERSION 2.19.0) +set(PSTACK_VERSION 2.19.1) project(pstack LANGUAGES C CXX VERSION "${PSTACK_VERSION}" ) set(Python3_DEBUG_OUTPUT ON)