diff --git a/CMakeLists.txt b/CMakeLists.txt index 82c1cf5..e5ba605 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.1) project(pstack LANGUAGES C CXX VERSION "${PSTACK_VERSION}" ) set(Python3_DEBUG_OUTPUT ON) 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/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; diff --git a/dead.cc b/dead.cc index c093af1..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( 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/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 8f74fdf..7a845fa 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; } @@ -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 @@ -570,33 +579,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{ std::move(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 {}; @@ -674,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 @@ -708,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/golang.cc b/golang.cc index 5f21425..93bad3b 100644 --- a/golang.cc +++ b/golang.cc @@ -17,26 +17,32 @@ 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, + [&](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. - 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 +52,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 +73,43 @@ 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)); + if (context.verbose > 1) + *context.debug << "added goroutine " << goid << "\n"; } catch (const Exception &ex) { - if (proc.context.verbose > 1) - *proc.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 (proc.context.verbose > 0) - *proc.context.debug << "Go goroutine support unavailable: " << ex.what() << "\n"; + if (context.verbose > 0) + *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/elf.h b/libpstack/elf.h index 17dd985..7b5eb13 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_)) @@ -255,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()); } }; @@ -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(); @@ -403,12 +410,12 @@ 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; } }; +BuildID getBuildIDFromNote(const NoteDesc ¬ed); class Notes::segment_iterator { const Object *object; @@ -418,7 +425,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; @@ -484,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{}; } }; @@ -496,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 90310cd..cff0c4a 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; @@ -225,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_{std::move(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 { @@ -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; @@ -308,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; @@ -418,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); 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 75ddfca..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; } } @@ -803,10 +804,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 +823,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))); } /* @@ -913,13 +922,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 +950,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 +971,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; @@ -1250,7 +1254,7 @@ Process::getStacks() { } }); - addGoRoutines(*this, stacks); + addGoroutines(stacks); /* * Use the thread db to find at least the thread ids for each lwp. We 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/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 || 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; }); 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 50400de..c0e03d2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -24,6 +24,30 @@ 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) +add_executable(exception-regressions exception-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 +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) +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-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..65bbd2e --- /dev/null +++ b/tests/elf-regressions.cc @@ -0,0 +1,253 @@ +#include "libpstack/elf.h" + +#include +#include +#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"); +} + +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) { + 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"); + testNoteMoves(argv[2]); + } catch (const std::exception &ex) { + std::cerr << "ELF regression: " << ex.what() << '\n'; + return 1; + } + return 0; +} 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; + } +}