From 91f8ce8782422b0b53c89ac86db76ff70d36485d Mon Sep 17 00:00:00 2001 From: Bradley Fernandez Date: Thu, 5 Nov 2026 13:16:05 -0500 Subject: [PATCH 1/6] Introduce the Linux ptrace engine with launch, registers and memory Register the native PTRACE adapter on Linux. Introduce tracer, event and terminal I/O threads, marshal ptrace requests to the tracer, and support launch, continue, interrupt and termination. Describe x86/x86-64 register layouts, access register sets through ptrace, and read/write target memory through /proc//mem. --- core/CMakeLists.txt | 10 + core/adapters/ptrace/ptraceadapter.cpp | 759 +++++++++++++++++++++++ core/adapters/ptrace/ptraceadapter.h | 174 ++++++ core/adapters/ptrace/ptracearch.cpp | 125 ++++ core/adapters/ptrace/ptracearch.h | 51 ++ core/adapters/ptrace/ptraceengine.cpp | 827 +++++++++++++++++++++++++ core/adapters/ptrace/ptraceengine.h | 177 ++++++ core/debugger.cpp | 6 + 8 files changed, 2129 insertions(+) create mode 100644 core/adapters/ptrace/ptraceadapter.cpp create mode 100644 core/adapters/ptrace/ptraceadapter.h create mode 100644 core/adapters/ptrace/ptracearch.cpp create mode 100644 core/adapters/ptrace/ptracearch.h create mode 100644 core/adapters/ptrace/ptraceengine.cpp create mode 100644 core/adapters/ptrace/ptraceengine.h diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 158b988f..0889988c 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -59,6 +59,16 @@ if(WIN32) ) else() set(SOURCES ${COMMON_SOURCES} ${ADAPTER_SOURCES}) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + list(APPEND SOURCES + adapters/ptrace/ptraceadapter.cpp + adapters/ptrace/ptraceadapter.h + adapters/ptrace/ptracearch.cpp + adapters/ptrace/ptracearch.h + adapters/ptrace/ptraceengine.cpp + adapters/ptrace/ptraceengine.h + ) + endif() endif() if(DEMO) diff --git a/core/adapters/ptrace/ptraceadapter.cpp b/core/adapters/ptrace/ptraceadapter.cpp new file mode 100644 index 00000000..4cf51bc4 --- /dev/null +++ b/core/adapters/ptrace/ptraceadapter.cpp @@ -0,0 +1,759 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include +#include +#include +#include "ptraceadapter.h" + +namespace BinaryNinjaDebugger { + + static std::optional> ParseCommandLineArguments(const std::string& commandLine) + { + enum class Quote { None, Single, Double }; + Quote quote = Quote::None; + bool escaped = false; + bool argumentStarted = false; + std::string argument; + std::vector arguments; + + for (char ch : commandLine) + { + if (escaped) + { + argument += ch; + argumentStarted = true; + escaped = false; + continue; + } + + if (ch == '\\' && quote != Quote::Single) + { + escaped = true; + argumentStarted = true; + continue; + } + if (ch == '\'' && quote != Quote::Double) + { + quote = quote == Quote::Single ? Quote::None : Quote::Single; + argumentStarted = true; + continue; + } + if (ch == '"' && quote != Quote::Single) + { + quote = quote == Quote::Double ? Quote::None : Quote::Double; + argumentStarted = true; + continue; + } + if (std::isspace(static_cast(ch)) && quote == Quote::None) + { + if (argumentStarted) + { + arguments.push_back(argument); + argument.clear(); + argumentStarted = false; + } + continue; + } + + argument += ch; + argumentStarted = true; + } + + if (escaped || quote != Quote::None) + return std::nullopt; + if (argumentStarted) + arguments.push_back(argument); + return arguments; + } + + + static DebugRegister RegisterFromBytes(const PtraceRegister& reg, const std::vector& data, size_t index) + { + uint8_t buffer[64] = {}; + memcpy(buffer, data.data() + reg.offset, std::min(reg.size, sizeof(buffer))); + return DebugRegister(reg.name, intx::le::load(buffer), reg.size * 8, index); + } + + + static bool RegisterInBounds(const PtraceRegister& reg, const std::vector& data) + { + return reg.offset + reg.size <= data.size(); + } + + + static DebugStopReason StopReasonFromEvent(const PtraceEngine::Event& event) + { + if (event.interrupted) + return UnknownReason; + if (event.signal == SIGTRAP) + return event.singleStep ? SingleStep : Breakpoint; + return SignalToDebugStopReason(event.signal); + } + + + static bool IsSupportedArchitecture(BinaryView* data) + { + if (!data) + return false; + + auto arch = data->GetDefaultArchitecture(); + if (!arch) + return false; + + auto name = arch->GetName(); + return name == "x86" || name == "x86_64"; + } + + + bool PtraceAdapter::ResolveModuleAddress(const ModuleNameAndOffset& location, uint64_t& address) + { + return false; + } + + + PtraceAdapter::PtraceAdapter(BinaryView* data) : DebugAdapter(data) + { + m_targetActive = false; + GenerateDefaultAdapterSettings(data); + } + + + PtraceAdapter::~PtraceAdapter() + { + m_engine.reset(); + } + + + bool PtraceAdapter::Execute(const std::string& path, const LaunchConfigurations& configs) + { + return ExecuteWithArgs(path, "", "", configs); + } + + + bool PtraceAdapter::ExecuteWithArgs(const std::string& path, const std::string& args, + const std::string& workingDir, const LaunchConfigurations& configs) + { + auto adapterSettings = GetAdapterSettings(); + auto data = GetData(); + BNSettingsScope scope = SettingsResourceScope; + auto executablePath = adapterSettings->Get("launch.executablePath", data, &scope); + scope = SettingsResourceScope; + auto workingDirectory = adapterSettings->Get("launch.workingDirectory", data, &scope); + scope = SettingsResourceScope; + auto commandLineArgs = adapterSettings->Get("launch.commandLineArguments", data, &scope); + scope = SettingsResourceScope; + auto disableAslr = adapterSettings->Get("launch.disableAslr", data, &scope); + + if (executablePath.empty()) + executablePath = path; + if (workingDirectory.empty()) + workingDirectory = workingDir; + if (commandLineArgs.empty()) + commandLineArgs = args; + + auto launchFailure = [this](const std::string& error) { + DebuggerEvent event; + event.type = LaunchFailureEventType; + event.data.errorData.shortError = "Failed to launch target"; + event.data.errorData.error = fmt::format("PTRACE: {}", error); + PostDebuggerEvent(event); + return false; + }; + + if (executablePath.empty()) + return launchFailure("no executable path specified"); + + auto parsedArguments = ParseCommandLineArguments(commandLineArgs); + if (!parsedArguments) + return launchFailure("invalid command line arguments"); + + PtraceEngine::LaunchOptions options; + options.path = executablePath; + options.args = *parsedArguments; + options.workingDir = workingDirectory; + options.disableAslr = disableAslr; + + m_engine.reset(); + m_stopAtSystemEntry = Settings::Instance()->Get("debugger.stopAtSystemEntryPoint"); + m_firstStop = true; + m_targetActive = true; + m_engine = std::make_unique([this](const PtraceEngine::Event& event) { HandleEngineEvent(event); }); + + std::string error; + if (!m_engine->Launch(options, error)) + { + m_targetActive = false; + return launchFailure(error); + } + return true; + } + + + void PtraceAdapter::HandleEngineEvent(const PtraceEngine::Event& event) + { + DebuggerEvent dbgevt; + switch (event.type) + { + case PtraceEngine::StoppedEvent: + m_activeThreadId = event.tid; + m_lastStopReason = StopReasonFromEvent(event); + if (m_firstStop) + { + m_firstStop = false; + m_arch = DetectPtraceArch(m_engine->GetPid()); + if (!m_arch) + LogWarn("PtraceAdapter: unsupported target architecture"); + if (!m_stopAtSystemEntry) + { + m_engine->Resume(false, 0); + break; + } + } + dbgevt.type = AdapterStoppedEventType; + dbgevt.data.targetStoppedData.reason = m_lastStopReason; + dbgevt.data.targetStoppedData.lastActiveThread = event.tid; + PostDebuggerEvent(dbgevt); + break; + case PtraceEngine::ExitedEvent: + m_targetActive = false; + m_lastStopReason = ProcessExited; + m_exitCode = event.signal ? 128 + event.signal : event.exitCode; + dbgevt.type = TargetExitedEventType; + dbgevt.data.exitData.exitCode = m_exitCode; + PostDebuggerEvent(dbgevt); + break; + case PtraceEngine::DetachedEvent: + m_targetActive = false; + dbgevt.type = DetachedEventType; + PostDebuggerEvent(dbgevt); + break; + case PtraceEngine::OutputEvent: + dbgevt.type = StdoutMessageEventType; + dbgevt.data.messageData.message = event.data; + PostDebuggerEvent(dbgevt); + break; + } + } + + + bool PtraceAdapter::Attach(std::uint32_t pid) + { + LogWarn("PtraceAdapter::Attach not implemented"); + return false; + } + + + bool PtraceAdapter::Connect(const std::string& server, std::uint32_t port) + { + return false; + } + + + bool PtraceAdapter::Detach() + { + return m_engine && m_engine->Detach(); + } + + + bool PtraceAdapter::Quit() + { + return m_engine && m_engine->Kill(); + } + + + std::vector PtraceAdapter::GetProcessList() + { + return {}; + } + + + std::uint32_t PtraceAdapter::GetActivePID() + { + return m_engine ? m_engine->GetPid() : 0; + } + + + std::vector PtraceAdapter::GetThreadList() + { + std::vector threads; + if (!m_engine) + return threads; + + auto arch = m_arch.load(); + for (uint32_t tid : m_engine->GetThreads()) + { + DebugThread thread(tid); + if (arch && !m_engine->IsRunning()) + { + auto pc = arch->Find(arch->pc); + std::vector data; + if (pc && m_engine->GetRegisterSet(tid, pc->regset, data) && RegisterInBounds(*pc, data)) + thread.m_rip = (uintptr_t)RegisterFromBytes(*pc, data, 0).m_value; + } + threads.push_back(thread); + } + return threads; + } + + + DebugThread PtraceAdapter::GetActiveThread() const + { + return DebugThread(m_activeThreadId); + } + + + uint32_t PtraceAdapter::GetActiveThreadId() const + { + return m_activeThreadId; + } + + + bool PtraceAdapter::SetActiveThread(const DebugThread& thread) + { + return SetActiveThreadId(thread.m_tid); + } + + + bool PtraceAdapter::SetActiveThreadId(std::uint32_t tid) + { + if (!m_engine) + return false; + + auto threads = m_engine->GetThreads(); + if (std::find(threads.begin(), threads.end(), tid) == threads.end()) + return false; + + m_activeThreadId = tid; + return true; + } + + + bool PtraceAdapter::SuspendThread(std::uint32_t tid) + { + return false; + } + + + bool PtraceAdapter::ResumeThread(std::uint32_t tid) + { + return false; + } + + + std::vector PtraceAdapter::GetFramesOfThread(uint32_t tid) + { + return {}; + } + + + DebugBreakpoint PtraceAdapter::AddBreakpoint(const std::uintptr_t address, unsigned long breakpoint_type) + { + return DebugBreakpoint(); + } + + + DebugBreakpoint PtraceAdapter::AddBreakpoint(const ModuleNameAndOffset& address, unsigned long breakpoint_type) + { + return DebugBreakpoint(); + } + + + bool PtraceAdapter::RemoveBreakpoint(const DebugBreakpoint& breakpoint) + { + return false; + } + + + bool PtraceAdapter::RemoveBreakpoint(const ModuleNameAndOffset& address) + { + return false; + } + + + std::vector PtraceAdapter::GetBreakpointList() const + { + return {}; + } + + + // Hardware breakpoint and watchpoint support + bool PtraceAdapter::AddHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size) + { + return false; + } + + + bool PtraceAdapter::RemoveHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size) + { + return false; + } + + + bool PtraceAdapter::AddHardwareBreakpoint( + const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size) + { + return false; + } + + + bool PtraceAdapter::RemoveHardwareBreakpoint( + const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size) + { + return false; + } + + + std::unordered_map PtraceAdapter::ReadAllRegisters() + { + std::unordered_map result; + auto arch = m_arch.load(); + if (!m_engine || !arch) + return result; + + std::unordered_map> regsets; + for (int regset : arch->regsets) + { + std::vector data; + if (m_engine->GetRegisterSet(m_activeThreadId, regset, data)) + regsets[regset] = std::move(data); + } + + for (size_t i = 0; i < arch->registers.size(); i++) + { + const auto& reg = arch->registers[i]; + auto it = regsets.find(reg.regset); + if (it != regsets.end() && RegisterInBounds(reg, it->second)) + result[reg.name] = RegisterFromBytes(reg, it->second, i); + } + return result; + } + + + DebugRegister PtraceAdapter::ReadRegister(const std::string& reg) + { + auto arch = m_arch.load(); + if (!m_engine || !arch) + return DebugRegister(); + + auto info = arch->Find(reg); + std::vector data; + if (!info || !m_engine->GetRegisterSet(m_activeThreadId, info->regset, data) || !RegisterInBounds(*info, data)) + return DebugRegister(); + + return RegisterFromBytes(*info, data, info - arch->registers.data()); + } + + + bool PtraceAdapter::WriteRegister(const std::string& reg, intx::uint512 value) + { + auto arch = m_arch.load(); + if (!m_engine || !arch) + return false; + + auto info = arch->Find(reg); + std::vector data; + if (!info || !m_engine->GetRegisterSet(m_activeThreadId, info->regset, data) || !RegisterInBounds(*info, data)) + return false; + + uint8_t buffer[64]; + intx::le::store(buffer, value); + memcpy(data.data() + info->offset, buffer, std::min(info->size, sizeof(buffer))); + return m_engine->SetRegisterSet(m_activeThreadId, info->regset, data); + } + + + uint64_t PtraceAdapter::ReadArchRegister(const std::string& name) + { + return (uint64_t)ReadRegister(name).m_value; + } + + + DataBuffer PtraceAdapter::ReadMemory(std::uintptr_t address, std::size_t size) + { + DataBuffer result; + if (!m_engine || size == 0) + return result; + + std::vector buffer(size); + if (m_engine->ReadMemory(address, buffer.data(), size)) + result.Append(buffer.data(), size); + return result; + } + + + bool PtraceAdapter::WriteMemory(std::uintptr_t address, const DataBuffer& buffer) + { + return m_engine && m_engine->WriteMemory(address, buffer.GetData(), buffer.GetLength()); + } + + + std::vector PtraceAdapter::GetModuleList() + { + return {}; + } + + + std::vector PtraceAdapter::GetMemoryMap() + { + return {}; + } + + + std::vector PtraceAdapter::GetSymbolsForModule(const DebugModule& module) + { + return {}; + } + + + std::string PtraceAdapter::GetTargetArchitecture() + { + auto arch = m_arch.load(); + return arch ? arch->name : ""; + } + + + DebugStopReason PtraceAdapter::StopReason() + { + return m_lastStopReason; + } + + + uint64_t PtraceAdapter::ExitCode() + { + return m_exitCode; + } + + + bool PtraceAdapter::BreakInto() + { + return m_engine && m_engine->Interrupt(); + } + + + bool PtraceAdapter::Go() + { + if (!m_engine || !m_engine->Resume(false, 0)) + return false; + + DebuggerEvent event; + event.type = ResumeEventType; + PostDebuggerEvent(event); + return true; + } + + + bool PtraceAdapter::StepInto() + { + if (!m_engine || !m_engine->Resume(true, m_activeThreadId)) + return false; + + DebuggerEvent event; + event.type = StepIntoEventType; + PostDebuggerEvent(event); + return true; + } + + + bool PtraceAdapter::StepOver() + { + return false; + } + + + bool PtraceAdapter::StepReturn() + { + return false; + } + + + std::string PtraceAdapter::InvokeBackendCommand(const std::string& command) + { + return ""; + } + + + uint64_t PtraceAdapter::GetInstructionOffset() + { + auto arch = m_arch.load(); + return arch ? ReadArchRegister(arch->pc) : 0; + } + + + uint64_t PtraceAdapter::GetStackPointer() + { + auto arch = m_arch.load(); + return arch ? ReadArchRegister(arch->sp) : 0; + } + + + bool PtraceAdapter::SupportFeature(DebugAdapterCapacity feature) + { + switch (feature) + { + case DebugAdapterSupportThreads: + return true; + default: + return false; + } + } + + + void PtraceAdapter::EventListener() {} + + + void PtraceAdapter::WriteStdin(const std::string& msg) + { + if (m_engine) + m_engine->WriteInput(msg); + } + + + void PtraceAdapter::FixActiveThread() {} + + + Ref PtraceAdapter::GetProperty(const std::string& name) + { + return nullptr; + } + + + bool PtraceAdapter::SetProperty(const std::string& name, const Ref& value) + { + return false; + } + + + void PtraceAdapter::ApplyBreakpoints() {} + + + void PtraceAdapter::GenerateDefaultAdapterSettings(BinaryView* data) + { + auto adapterSettings = GetAdapterSettings(); + BNSettingsScope scope = SettingsResourceScope; + adapterSettings->Get("common.inputFile", data, &scope); + if (scope != SettingsResourceScope) + adapterSettings->Set("common.inputFile", data->GetFile()->GetOriginalFilename(), data, SettingsResourceScope); + + scope = SettingsResourceScope; + adapterSettings->Get("launch.executablePath", data, &scope); + if (scope != SettingsResourceScope) + adapterSettings->Set( + "launch.executablePath", data->GetFile()->GetOriginalFilename(), data, SettingsResourceScope); + } + + + Ref PtraceAdapter::GetAdapterSettings() + { + return PtraceAdapterType::GetAdapterSettings(); + } + + + PtraceAdapterType::PtraceAdapterType() : DebugAdapterType("PTRACE") {} + + + DebugAdapter* PtraceAdapterType::Create(BinaryNinja::BinaryView* data) + { + return new PtraceAdapter(data); + } + + + bool PtraceAdapterType::IsValidForData(BinaryNinja::BinaryView* data) + { + return IsSupportedArchitecture(data); + } + + + bool PtraceAdapterType::CanConnect(BinaryNinja::BinaryView* data) + { + return false; + } + + + bool PtraceAdapterType::CanExecute(BinaryNinja::BinaryView* data) + { + return data && data->GetTypeName() == "ELF"; + } + + + Ref PtraceAdapterType::RegisterAdapterSettings() + { + Ref settings = Settings::Instance("PtraceAdapterSettings"); + settings->SetResourceId("ptrace_adapter_settings"); + settings->RegisterSetting("common.inputFile", + R"({ + "title" : "Input File", + "type" : "string", + "default" : "", + "description" : "Input file to use to find the base address of the binary view", + "readOnly" : false, + "uiSelectionAction" : "file" + })"); + settings->RegisterSetting("launch.executablePath", + R"({ + "title" : "Executable Path", + "type" : "string", + "default" : "", + "description" : "Path of the executable to launch for local debugging.", + "readOnly" : false, + "uiSelectionAction" : "file" + })"); + settings->RegisterSetting("launch.workingDirectory", + R"({ + "title" : "Working Directory", + "type" : "string", + "default" : "", + "description" : "Working directory to launch the target in.", + "readOnly" : false, + "uiSelectionAction" : "directory" + })"); + settings->RegisterSetting("launch.commandLineArguments", + R"({ + "title" : "Command Line Arguments", + "type" : "string", + "default" : "", + "description" : "Command line arguments to pass to the target.", + "readOnly" : false + })"); + settings->RegisterSetting("launch.disableAslr", + R"({ + "title" : "Disable ASLR", + "type" : "boolean", + "default" : true, + "description" : "Disable address space layout randomization for the target.", + "readOnly" : false + })"); + + return settings; + } + + + Ref PtraceAdapterType::GetAdapterSettings() + { + static Ref settings = PtraceAdapterType::RegisterAdapterSettings(); + return settings; + } + + + void InitPtraceAdapterType() + { + static PtraceAdapterType ptraceType; + DebugAdapterType::Register(&ptraceType); + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceadapter.h b/core/adapters/ptrace/ptraceadapter.h new file mode 100644 index 00000000..4f5bce6e --- /dev/null +++ b/core/adapters/ptrace/ptraceadapter.h @@ -0,0 +1,174 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include "../../debugadapter.h" +#include "../../debugadaptertype.h" +#include "ptracearch.h" +#include "ptraceengine.h" + +namespace BinaryNinjaDebugger { + class PtraceAdapter : public DebugAdapter + { + private: + std::unique_ptr m_engine; + std::atomic m_targetActive; + std::atomic m_activeThreadId {0}; + std::atomic m_lastStopReason {UnknownReason}; + std::atomic m_exitCode {0}; + std::atomic m_arch {nullptr}; + bool m_firstStop = false; + bool m_stopAtSystemEntry = false; + + std::vector m_pendingBreakpoints {}; + std::vector m_pendingHardwareBreakpoints {}; + + void HandleEngineEvent(const PtraceEngine::Event& event); + uint64_t ReadArchRegister(const std::string& name); + + // Helper to resolve module+offset to absolute address + // Returns true if the module was found in the loaded module list and address was resolved + // Returns false if the module was not found (caller should fall back to module+offset handling) + bool ResolveModuleAddress(const ModuleNameAndOffset& location, uint64_t& address); + + public: + PtraceAdapter(BinaryView* data); + virtual ~PtraceAdapter(); + + bool Execute(const std::string& path, const LaunchConfigurations& configs) override; + + bool ExecuteWithArgs(const std::string& path, const std::string& args, const std::string& workingDir, + const LaunchConfigurations& configs) override; + + bool Attach(std::uint32_t pid) override; + + bool Connect(const std::string& server, std::uint32_t port) override; + + bool Detach() override; + + bool Quit() override; + + std::vector GetProcessList() override; + + std::uint32_t GetActivePID() override; + + std::vector GetThreadList() override; + + DebugThread GetActiveThread() const override; + + uint32_t GetActiveThreadId() const override; + + bool SetActiveThread(const DebugThread& thread) override; + + bool SetActiveThreadId(std::uint32_t tid) override; + + bool SuspendThread(std::uint32_t tid) override; + bool ResumeThread(std::uint32_t tid) override; + + std::vector GetFramesOfThread(uint32_t tid) override; + + DebugBreakpoint AddBreakpoint(const std::uintptr_t address, unsigned long breakpoint_type) override; + + virtual DebugBreakpoint AddBreakpoint( + const ModuleNameAndOffset& address, unsigned long breakpoint_type = 0) override; + + bool RemoveBreakpoint(const DebugBreakpoint& breakpoint) override; + + virtual bool RemoveBreakpoint(const ModuleNameAndOffset& address) override; + + std::vector GetBreakpointList() const override; + + // Hardware breakpoint and watchpoint support + bool AddHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size = 1) override; + bool RemoveHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size = 1) override; + bool AddHardwareBreakpoint(const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size = 1) override; + bool RemoveHardwareBreakpoint(const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size = 1) override; + + std::unordered_map ReadAllRegisters() override; + + DebugRegister ReadRegister(const std::string& reg) override; + + bool WriteRegister(const std::string& reg, intx::uint512 value) override; + + DataBuffer ReadMemory(std::uintptr_t address, std::size_t size) override; + + bool WriteMemory(std::uintptr_t address, const DataBuffer& buffer) override; + + std::vector GetModuleList() override; + + std::vector GetMemoryMap() override; + + std::vector GetSymbolsForModule(const DebugModule& module) override; + + std::string GetTargetArchitecture() override; + + DebugStopReason StopReason() override; + + uint64_t ExitCode() override; + + bool BreakInto() override; + + bool Go() override; + + bool StepInto() override; + + bool StepOver() override; + + bool StepReturn() override; + + std::string InvokeBackendCommand(const std::string& command) override; + + uint64_t GetInstructionOffset() override; + + uint64_t GetStackPointer() override; + + bool SupportFeature(DebugAdapterCapacity feature) override; + + void EventListener(); + + void WriteStdin(const std::string& msg) override; + + void FixActiveThread(); + + Ref GetProperty(const std::string& name) override; + + bool SetProperty(const std::string& name, const Ref& value) override; + + void ApplyBreakpoints(); + + void GenerateDefaultAdapterSettings(BinaryView* data); + Ref GetAdapterSettings() override; + }; + + class PtraceAdapterType : public DebugAdapterType + { + static Ref RegisterAdapterSettings(); + + public: + PtraceAdapterType(); + virtual DebugAdapter* Create(BinaryNinja::BinaryView* data); + virtual bool IsValidForData(BinaryNinja::BinaryView* data); + virtual bool CanExecute(BinaryNinja::BinaryView* data); + virtual bool CanConnect(BinaryNinja::BinaryView* data); + static Ref GetAdapterSettings(); + }; + + + void InitPtraceAdapterType(); + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracearch.cpp b/core/adapters/ptrace/ptracearch.cpp new file mode 100644 index 00000000..01df80d7 --- /dev/null +++ b/core/adapters/ptrace/ptracearch.cpp @@ -0,0 +1,125 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptracearch.h" +#include +#include + +namespace BinaryNinjaDebugger { + + const PtraceRegister* PtraceArch::Find(const std::string& registerName) const + { + for (const auto& reg : registers) + { + if (reg.name == registerName) + return ® + } + return nullptr; + } + + + static void AddRegisters(PtraceArch& arch, int regset, size_t size, const std::vector& names, + const std::vector& indices) + { + for (size_t i = 0; i < names.size(); i++) + arch.registers.push_back({names[i], regset, indices[i] * size, size}); + } + + + static PtraceArch BuildX86_64() + { + PtraceArch arch; + arch.name = "x86_64"; + arch.pc = "rip"; + arch.sp = "rsp"; + arch.regsets = {NT_PRSTATUS, NT_PRFPREG}; + + // The order of user_regs_struct: r15 r14 r13 r12 rbp rbx r11 r10 r9 r8 rax rcx rdx rsi rdi orig_rax rip cs + // eflags rsp ss fs_base gs_base ds es fs gs. The registers are listed in the order GDB uses. + AddRegisters(arch, NT_PRSTATUS, 8, + {"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "r8", "r9", "r10", "r11", "r12", "r13", "r14", + "r15", "rip", "eflags", "cs", "ss", "ds", "es", "fs", "gs", "fs_base", "gs_base", "orig_rax"}, + {10, 5, 11, 12, 13, 14, 4, 19, 9, 8, 7, 6, 3, 2, 1, 0, 16, 18, 17, 20, 23, 24, 25, 26, 21, 22, 15}); + + // user_fpregs_struct, which is the FXSAVE area + arch.registers.push_back({"fctrl", NT_PRFPREG, 0, 2}); + arch.registers.push_back({"fstat", NT_PRFPREG, 2, 2}); + arch.registers.push_back({"fop", NT_PRFPREG, 6, 2}); + arch.registers.push_back({"mxcsr", NT_PRFPREG, 24, 4}); + for (size_t i = 0; i < 8; i++) + arch.registers.push_back({"st" + std::to_string(i), NT_PRFPREG, 32 + i * 16, 10}); + for (size_t i = 0; i < 16; i++) + arch.registers.push_back({"xmm" + std::to_string(i), NT_PRFPREG, 160 + i * 16, 16}); + return arch; + } + + + static PtraceArch BuildX86() + { + PtraceArch arch; + arch.name = "x86"; + arch.pc = "eip"; + arch.sp = "esp"; + arch.regsets = {NT_PRSTATUS}; + + // The order of the 32-bit user_regs_struct: ebx ecx edx esi edi ebp eax xds xes xfs xgs orig_eax eip xcs + // eflags esp xss + AddRegisters(arch, NT_PRSTATUS, 4, + {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "eip", "eflags", "cs", "ss", "ds", "es", "fs", + "gs", "orig_eax"}, + {6, 1, 2, 0, 15, 5, 3, 4, 12, 14, 13, 16, 7, 8, 9, 10, 11}); + return arch; + } + + + const PtraceArch& PtraceArchX86_64() + { + static const PtraceArch arch = BuildX86_64(); + return arch; + } + + + const PtraceArch& PtraceArchX86() + { + static const PtraceArch arch = BuildX86(); + return arch; + } + + + const PtraceArch* DetectPtraceArch(pid_t pid) + { + std::ifstream file("/proc/" + std::to_string(pid) + "/exe", std::ios::binary); + unsigned char header[20] = {}; + if (!file.read(reinterpret_cast(header), sizeof(header))) + return nullptr; + if (header[EI_MAG0] != ELFMAG0 || header[EI_MAG1] != ELFMAG1 || header[EI_MAG2] != ELFMAG2 + || header[EI_MAG3] != ELFMAG3 || header[EI_DATA] != ELFDATA2LSB) + return nullptr; + + // e_machine follows e_type, and both are 16 bits + unsigned int machine = header[18] | (header[19] << 8); + switch (machine) + { + case EM_X86_64: + return &PtraceArchX86_64(); + case EM_386: + return &PtraceArchX86(); + default: + return nullptr; + } + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracearch.h b/core/adapters/ptrace/ptracearch.h new file mode 100644 index 00000000..105804f7 --- /dev/null +++ b/core/adapters/ptrace/ptracearch.h @@ -0,0 +1,51 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include +#include + +namespace BinaryNinjaDebugger { + // Where a register lives inside one of the register sets that PTRACE_GETREGSET returns + struct PtraceRegister + { + std::string name; + int regset; + size_t offset; + size_t size; + }; + + // Describes the registers of one target architecture. Nothing outside of this table and DetectPtraceArch needs to + // know how a particular architecture lays its registers out. + struct PtraceArch + { + std::string name; + std::string pc; + std::string sp; + std::vector registers; + std::vector regsets; + + const PtraceRegister* Find(const std::string& registerName) const; + }; + + const PtraceArch& PtraceArchX86_64(); + const PtraceArch& PtraceArchX86(); + + // Returns nullptr if the architecture of the process is not supported + const PtraceArch* DetectPtraceArch(pid_t pid); +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceengine.cpp b/core/adapters/ptrace/ptraceengine.cpp new file mode 100644 index 00000000..5987d880 --- /dev/null +++ b/core/adapters/ptrace/ptraceengine.cpp @@ -0,0 +1,827 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptraceengine.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace BinaryNinjaDebugger { + + static bool IsSilentSignal(int signal) + { + switch (signal) + { + case SIGCHLD: + case SIGALRM: + case SIGURG: + case SIGVTALRM: + case SIGPROF: + case SIGWINCH: + case SIGIO: + return true; + default: + return false; + } + } + + + [[noreturn]] static void ChildFail(int fd) + { + int error = errno; + [[maybe_unused]] auto ignored = write(fd, &error, sizeof(error)); + _exit(127); + } + + + PtraceEngine::PtraceEngine(EventHandler handler) : m_handler(std::move(handler)) {} + + + PtraceEngine::~PtraceEngine() + { + if (m_tracerThread.joinable()) + { + RunOnTracer([this] { return DoKill(); }); + { + std::lock_guard lock(m_taskMutex); + m_shutdown = true; + } + m_taskCv.notify_all(); + m_tracerThread.join(); + } + + if (m_ioThread.joinable()) + { + m_ioStop = true; + m_ioThread.join(); + } + + if (m_eventThread.joinable()) + { + { + std::lock_guard lock(m_eventMutex); + m_eventStop = true; + } + m_eventCv.notify_all(); + m_eventThread.join(); + } + + if (m_masterFd >= 0) + close(m_masterFd); + if (m_memFd >= 0) + close(m_memFd); + } + + + bool PtraceEngine::Launch(const LaunchOptions& options, std::string& error) + { + m_options = options; + auto result = m_launchResult.get_future(); + m_eventThread = std::thread(&PtraceEngine::EventMain, this); + m_tracerThread = std::thread(&PtraceEngine::TracerMain, this); + error = result.get(); + return error.empty(); + } + + + bool PtraceEngine::RunOnTracer(std::function function) + { + auto task = std::make_shared>(std::move(function)); + auto result = task->get_future(); + { + std::lock_guard lock(m_taskMutex); + if (m_tracerStop) + return false; + m_tasks.push_back([task] { (*task)(); }); + } + m_taskCv.notify_all(); + + // Only the queue may keep the task alive, so that discarding it breaks the promise + task.reset(); + try + { + return result.get(); + } + catch (const std::future_error&) + { + return false; + } + } + + + bool PtraceEngine::Resume(bool step, uint32_t tid) + { + return RunOnTracer([this, step, tid] { return DoResume(step, tid); }); + } + + + bool PtraceEngine::Kill() + { + return RunOnTracer([this] { return DoKill(); }); + } + + + bool PtraceEngine::Detach() + { + return RunOnTracer([this] { return DoDetach(); }); + } + + + bool PtraceEngine::Interrupt() + { + if (!m_publishedRunning) + return false; + + m_interruptRequested = true; + return kill(m_pid, SIGSTOP) == 0; + } + + + bool PtraceEngine::WriteInput(const std::string& data) + { + if (m_masterFd < 0) + return false; + + size_t written = 0; + while (written < data.size()) + { + auto count = write(m_masterFd, data.data() + written, data.size() - written); + if (count < 0) + { + if (errno == EINTR || errno == EAGAIN) + continue; + return false; + } + written += count; + } + return true; + } + + + bool PtraceEngine::GetRegisterSet(uint32_t tid, int regset, std::vector& data) + { + return RunOnTracer([this, tid, regset, &data] { + auto it = m_threads.find(tid); + if (m_done || m_running || it == m_threads.end() || !it->second.stopped) + return false; + + // The largest register set, the extended state, can be a few kilobytes + std::vector buffer(16384); + iovec vec {buffer.data(), buffer.size()}; + if (ptrace(PTRACE_GETREGSET, tid, (void*)(uintptr_t)regset, &vec) != 0) + return false; + + buffer.resize(vec.iov_len); + data = std::move(buffer); + return true; + }); + } + + + bool PtraceEngine::SetRegisterSet(uint32_t tid, int regset, const std::vector& data) + { + return RunOnTracer([this, tid, regset, &data] { + auto it = m_threads.find(tid); + if (m_done || m_running || it == m_threads.end() || !it->second.stopped) + return false; + + iovec vec {const_cast(data.data()), data.size()}; + return ptrace(PTRACE_SETREGSET, tid, (void*)(uintptr_t)regset, &vec) == 0; + }); + } + + + bool PtraceEngine::ReadMemory(uint64_t address, void* buffer, size_t size) + { + if (m_memFd < 0 || m_finished || address > INT64_MAX || size > INT64_MAX - address) + return false; + + size_t done = 0; + while (done < size) + { + auto count = pread(m_memFd, (char*)buffer + done, size - done, address + done); + if (count < 0 && errno == EINTR) + continue; + if (count <= 0) + return false; + done += count; + } + return true; + } + + + bool PtraceEngine::WriteMemory(uint64_t address, const void* buffer, size_t size) + { + if (m_memFd < 0 || m_finished || address > INT64_MAX || size > INT64_MAX - address) + return false; + + size_t done = 0; + while (done < size) + { + auto count = pwrite(m_memFd, (const char*)buffer + done, size - done, address + done); + if (count < 0 && errno == EINTR) + continue; + if (count <= 0) + return false; + done += count; + } + return true; + } + + + std::vector PtraceEngine::GetThreads() const + { + std::lock_guard lock(m_infoMutex); + return m_publishedThreads; + } + + + void PtraceEngine::PushEvent(const Event& event) + { + { + std::lock_guard lock(m_eventMutex); + m_events.push_back(event); + } + m_eventCv.notify_one(); + } + + + void PtraceEngine::Publish() + { + std::lock_guard lock(m_infoMutex); + m_publishedThreads.clear(); + for (const auto& [tid, info] : m_threads) + m_publishedThreads.push_back(tid); + m_publishedRunning = m_running; + } + + + void PtraceEngine::StopIo() + { + if (!m_ioThread.joinable()) + return; + + m_ioStop = true; + m_ioThread.join(); + } + + + void PtraceEngine::EventMain() + { + while (true) + { + Event event; + { + std::unique_lock lock(m_eventMutex); + m_eventCv.wait(lock, [this] { return m_eventStop || !m_events.empty(); }); + if (m_eventStop) + return; + + event = std::move(m_events.front()); + m_events.pop_front(); + } + m_handler(event); + } + } + + + void PtraceEngine::IoMain() + { + char buffer[4096]; + while (true) + { + pollfd fd {m_masterFd, POLLIN, 0}; + int ready = poll(&fd, 1, 50); + if (ready == 0) + { + if (m_ioStop) + return; + continue; + } + if (ready < 0) + { + if (errno == EINTR) + continue; + return; + } + + auto count = read(m_masterFd, buffer, sizeof(buffer)); + if (count > 0) + { + Event event; + event.type = OutputEvent; + event.data.assign(buffer, count); + PushEvent(event); + } + else if (count == 0 || (errno != EINTR && errno != EAGAIN)) + { + return; + } + } + } + + + std::string PtraceEngine::Spawn() + { + std::vector argStorage; + argStorage.push_back(m_options.path); + argStorage.insert(argStorage.end(), m_options.args.begin(), m_options.args.end()); + std::vector argv; + for (auto& arg : argStorage) + argv.push_back(arg.data()); + argv.push_back(nullptr); + + const char* path = m_options.path.c_str(); + const char* workingDir = m_options.workingDir.empty() ? nullptr : m_options.workingDir.c_str(); + + char slaveName[256] = {}; + if (m_options.usePty) + { + m_masterFd = posix_openpt(O_RDWR | O_NOCTTY | O_CLOEXEC); + if (m_masterFd < 0 || grantpt(m_masterFd) != 0 || unlockpt(m_masterFd) != 0 + || ptsname_r(m_masterFd, slaveName, sizeof(slaveName)) != 0) + return std::string("failed to open a pseudo terminal: ") + strerror(errno); + } + + int errorPipe[2]; + if (pipe2(errorPipe, O_CLOEXEC) != 0) + return std::string("failed to create a pipe: ") + strerror(errno); + + pid_t pid = fork(); + if (pid < 0) + { + int error = errno; + close(errorPipe[0]); + close(errorPipe[1]); + return std::string("failed to fork: ") + strerror(error); + } + + if (pid == 0) + { + sigset_t noSignals; + sigemptyset(&noSignals); + sigprocmask(SIG_SETMASK, &noSignals, nullptr); + + if (slaveName[0]) + { + setsid(); + int slave = open(slaveName, O_RDWR); + if (slave < 0) + ChildFail(errorPipe[1]); + ioctl(slave, TIOCSCTTY, 0); + dup2(slave, 0); + dup2(slave, 1); + dup2(slave, 2); + if (slave > 2) + close(slave); + } + + if (workingDir && chdir(workingDir) != 0) + ChildFail(errorPipe[1]); + if (m_options.disableAslr) + personality(personality(0xffffffff) | ADDR_NO_RANDOMIZE); + if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) != 0) + ChildFail(errorPipe[1]); + + execv(path, argv.data()); + ChildFail(errorPipe[1]); + } + + close(errorPipe[1]); + int childError = 0; + ssize_t count; + do + { + count = read(errorPipe[0], &childError, sizeof(childError)); + } while (count < 0 && errno == EINTR); + close(errorPipe[0]); + + if (count == (ssize_t)sizeof(childError)) + { + waitpid(pid, nullptr, __WALL); + return std::string("failed to execute ") + m_options.path + ": " + strerror(childError); + } + + int status = 0; + if (waitpid(pid, &status, __WALL) < 0 || !WIFSTOPPED(status)) + return "the target exited before it could be traced"; + + ptrace(PTRACE_SETOPTIONS, pid, nullptr, (void*)(uintptr_t)(PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE)); + + m_pid = pid; + m_memFd = open(("/proc/" + std::to_string(pid) + "/mem").c_str(), O_RDWR | O_CLOEXEC); + ThreadInfo info; + info.stopped = true; + m_threads[pid] = info; + Publish(); + + if (m_masterFd >= 0) + { + fcntl(m_masterFd, F_SETFL, fcntl(m_masterFd, F_GETFL) | O_NONBLOCK); + m_ioThread = std::thread(&PtraceEngine::IoMain, this); + } + + Event event; + event.type = StoppedEvent; + event.tid = pid; + event.signal = WSTOPSIG(status); + PushEvent(event); + return ""; + } + + + void PtraceEngine::TracerMain() + { + std::string error = Spawn(); + m_launchResult.set_value(error); + + int idle = 0; + while (error.empty() && !m_done) + { + std::deque> tasks; + { + std::unique_lock lock(m_taskMutex); + if (!m_running) + { + m_taskCv.wait(lock, [this] { return m_shutdown || !m_tasks.empty(); }); + } + else if (m_tasks.empty() && idle >= 20) + { + auto delay = std::chrono::microseconds(50 << std::min(idle - 20, 6)); + m_taskCv.wait_for(lock, delay, [this] { return m_shutdown || !m_tasks.empty(); }); + } + if (m_shutdown) + break; + tasks.swap(m_tasks); + } + + for (auto& task : tasks) + task(); + if (m_done) + break; + + if (m_running) + { + if (PollThreads()) + idle = 0; + else if (++idle < 20) + sched_yield(); + } + } + + std::lock_guard lock(m_taskMutex); + m_tracerStop = true; + m_tasks.clear(); + } + + + bool PtraceEngine::PollThreads() + { + std::vector tids; + for (const auto& [tid, info] : m_threads) + { + if (!info.stopped) + tids.push_back(tid); + } + + bool progressed = false; + for (pid_t tid : tids) + { + if (!m_running || m_done) + break; + if (m_threads.find(tid) == m_threads.end()) + continue; + + int status = 0; + pid_t result = waitpid(tid, &status, __WALL | WNOHANG); + if (result == 0) + continue; + + progressed = true; + if (result < 0) + { + if (errno == EINTR) + continue; + // The thread is gone without a status we can read + status = 0; + } + HandleStatus(tid, status); + } + return progressed; + } + + + PtraceEngine::Classified PtraceEngine::Classify(pid_t tid, int status) + { + Classified result; + if (!WIFSTOPPED(status)) + { + m_threads.erase(tid); + Publish(); + result.kind = StopKind::Gone; + if (tid == m_pid) + FinishExit(status); + return result; + } + + auto& info = m_threads[tid]; + info.stopped = true; + int signal = WSTOPSIG(status); + int event = status >> 16; + + if (event == PTRACE_EVENT_CLONE) + { + unsigned long newTid = 0; + ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &newTid); + ThreadInfo created; + created.awaitingInitialStop = true; + m_threads[(pid_t)newTid] = created; + Publish(); + return result; + } + if (event != 0) + return result; + + if (signal == SIGSTOP) + { + if (info.awaitingInitialStop) + { + info.awaitingInitialStop = false; + return result; + } + if (info.expectedStops > 0) + { + info.expectedStops--; + return result; + } + if (m_interruptRequested.exchange(false)) + { + result.kind = StopKind::Report; + result.interrupted = true; + return result; + } + } + + if (IsSilentSignal(signal)) + { + info.pendingSignal = signal; + return result; + } + + if (signal != SIGTRAP) + info.pendingSignal = signal; + result.kind = StopKind::Report; + result.signal = signal; + return result; + } + + + bool PtraceEngine::ResumeThread(pid_t tid) + { + auto& info = m_threads[tid]; + int signal = info.pendingSignal; + info.pendingSignal = 0; + info.stopped = false; + auto request = info.stepping ? PTRACE_SINGLESTEP : PTRACE_CONT; + return ptrace(request, tid, nullptr, (void*)(intptr_t)signal) == 0 || errno == ESRCH; + } + + + void PtraceEngine::HandleStatus(pid_t tid, int status) + { + auto stop = Classify(tid, status); + switch (stop.kind) + { + case StopKind::Gone: + break; + case StopKind::Internal: + { + auto it = m_threads.find(tid); + if (it != m_threads.end() && it->second.stopped && (m_continueMode || it->second.stepping)) + ResumeThread(tid); + break; + } + case StopKind::Report: + StopAll(); + if (!m_done) + FinishStop(tid, stop); + break; + } + } + + + // Stops every thread that is still running, and waits for the new threads that have not reported yet. + void PtraceEngine::StopAll() + { + while (!m_done) + { + pid_t next = -1; + for (const auto& [tid, info] : m_threads) + { + if (!info.stopped) + { + next = tid; + break; + } + } + if (next < 0) + return; + + auto& info = m_threads[next]; + if (!info.awaitingInitialStop && info.expectedStops == 0) + { + syscall(SYS_tgkill, m_pid, next, SIGSTOP); + info.expectedStops++; + } + + int status = 0; + if (waitpid(next, &status, __WALL) < 0) + { + if (errno == EINTR) + continue; + status = 0; + } + Classify(next, status); + } + } + + + void PtraceEngine::FinishStop(pid_t tid, const Classified& stop) + { + Event event; + event.type = StoppedEvent; + event.tid = tid; + event.signal = stop.signal; + event.interrupted = stop.interrupted; + event.singleStep = m_threads[tid].stepping; + + for (auto& [id, info] : m_threads) + info.stepping = false; + m_running = false; + Publish(); + PushEvent(event); + } + + + void PtraceEngine::FinishExit(int status) + { + m_done = true; + m_finished = true; + m_running = false; + Publish(); + StopIo(); + + Event event; + event.type = ExitedEvent; + event.tid = m_pid; + if (WIFEXITED(status)) + event.exitCode = WEXITSTATUS(status); + else if (WIFSIGNALED(status)) + event.signal = WTERMSIG(status); + PushEvent(event); + } + + + bool PtraceEngine::DoResume(bool step, pid_t tid) + { + if (m_done || m_running) + return false; + if (step && m_threads.find(tid) == m_threads.end()) + return false; + + m_continueMode = !step; + bool resumed = false; + for (auto& [id, info] : m_threads) + { + if (!info.stopped || (step && id != tid)) + continue; + + info.stepping = step; + resumed |= ResumeThread(id); + } + + m_running = resumed; + Publish(); + return resumed; + } + + + bool PtraceEngine::DoKill() + { + if (m_done) + return false; + + kill(m_pid, SIGKILL); + + std::vector tids; + for (const auto& [tid, info] : m_threads) + { + if (tid != m_pid) + tids.push_back(tid); + } + tids.push_back(m_pid); + + int status = SIGKILL; + for (pid_t tid : tids) + { + while (true) + { + int threadStatus = 0; + if (waitpid(tid, &threadStatus, __WALL) < 0) + { + if (errno == EINTR) + continue; + break; + } + if (WIFEXITED(threadStatus) || WIFSIGNALED(threadStatus)) + { + if (tid == m_pid) + status = threadStatus; + break; + } + } + } + + m_threads.clear(); + FinishExit(status); + return true; + } + + + bool PtraceEngine::DoDetach() + { + if (m_done) + return false; + + StopAll(); + if (m_done) + return false; + + // A SIGSTOP we sent that was never consumed would stop the target for good once we let go of it + for (int attempt = 0; attempt < 8; attempt++) + { + pid_t pending = -1; + for (const auto& [tid, info] : m_threads) + { + if (info.expectedStops > 0) + { + pending = tid; + break; + } + } + if (pending < 0) + break; + + m_threads[pending].stepping = false; + ResumeThread(pending); + int status = 0; + if (waitpid(pending, &status, __WALL) < 0) + break; + Classify(pending, status); + if (m_done) + return false; + } + + for (const auto& [tid, info] : m_threads) + ptrace(PTRACE_DETACH, tid, nullptr, (void*)(intptr_t)info.pendingSignal); + + m_threads.clear(); + m_done = true; + m_finished = true; + m_running = false; + Publish(); + StopIo(); + + Event event; + event.type = DetachedEvent; + PushEvent(event); + return true; + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceengine.h b/core/adapters/ptrace/ptraceengine.h new file mode 100644 index 00000000..65422c78 --- /dev/null +++ b/core/adapters/ptrace/ptraceengine.h @@ -0,0 +1,177 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace BinaryNinjaDebugger { + // Owns a single ptrace session. Linux only requires that every ptrace request and wait comes from the thread that + // started tracing, so all of them run on one tracer thread and the public methods only marshal onto it. + // Events are delivered from a separate thread, so a handler is free to call back into the engine. + class PtraceEngine + { + public: + enum EventType + { + StoppedEvent, + ExitedEvent, + DetachedEvent, + OutputEvent + }; + + struct Event + { + EventType type {}; + uint32_t tid = 0; + // StoppedEvent: the signal that stopped the thread. ExitedEvent: the terminating signal, if any. + int signal = 0; + int exitCode = 0; + bool singleStep = false; + bool interrupted = false; + std::string data; + }; + + struct LaunchOptions + { + std::string path; + std::vector args; + std::string workingDir; + bool disableAslr = true; + bool usePty = true; + }; + + using EventHandler = std::function; + + private: + struct ThreadInfo + { + bool stopped = false; + bool stepping = false; + bool awaitingInitialStop = false; + // SIGSTOPs we sent that have not been consumed yet + int expectedStops = 0; + int pendingSignal = 0; + }; + + enum class StopKind + { + Gone, + Internal, + Report + }; + + struct Classified + { + StopKind kind = StopKind::Internal; + int signal = 0; + bool interrupted = false; + }; + + EventHandler m_handler; + LaunchOptions m_options; + std::promise m_launchResult; + + std::thread m_tracerThread; + std::thread m_eventThread; + std::thread m_ioThread; + + std::mutex m_taskMutex; + std::condition_variable m_taskCv; + std::deque> m_tasks; + bool m_tracerStop = false; + bool m_shutdown = false; + + std::mutex m_eventMutex; + std::condition_variable m_eventCv; + std::deque m_events; + bool m_eventStop = false; + + // Only touched by the tracer thread + std::map m_threads; + bool m_running = false; + bool m_continueMode = false; + bool m_done = false; + + mutable std::mutex m_infoMutex; + std::vector m_publishedThreads; + std::atomic m_publishedRunning {false}; + std::atomic m_interruptRequested {false}; + + pid_t m_pid = -1; + int m_masterFd = -1; + int m_memFd = -1; + std::atomic m_finished {false}; + std::atomic m_ioStop {false}; + + void TracerMain(); + void EventMain(); + void IoMain(); + + std::string Spawn(); + bool RunOnTracer(std::function function); + void PushEvent(const Event& event); + void Publish(); + void StopIo(); + + bool PollThreads(); + void HandleStatus(pid_t tid, int status); + Classified Classify(pid_t tid, int status); + bool ResumeThread(pid_t tid); + void StopAll(); + void FinishStop(pid_t tid, const Classified& stop); + void FinishExit(int status); + + bool DoResume(bool step, pid_t tid); + bool DoKill(); + bool DoDetach(); + + public: + explicit PtraceEngine(EventHandler handler); + ~PtraceEngine(); + + bool Launch(const LaunchOptions& options, std::string& error); + + // With step set, only `tid` runs, for one instruction. Otherwise every thread runs. + bool Resume(bool step, uint32_t tid); + bool Interrupt(); + bool Kill(); + bool Detach(); + bool WriteInput(const std::string& data); + + // Raw register sets, as PTRACE_GETREGSET and PTRACE_SETREGSET see them. The thread must be stopped. + bool GetRegisterSet(uint32_t tid, int regset, std::vector& data); + bool SetRegisterSet(uint32_t tid, int regset, const std::vector& data); + + // All or nothing + bool ReadMemory(uint64_t address, void* buffer, size_t size); + bool WriteMemory(uint64_t address, const void* buffer, size_t size); + + uint32_t GetPid() const { return m_pid > 0 ? m_pid : 0; } + std::vector GetThreads() const; + bool IsRunning() const { return m_publishedRunning; } + }; +} // namespace BinaryNinjaDebugger diff --git a/core/debugger.cpp b/core/debugger.cpp index 2064e249..02e6f4fb 100644 --- a/core/debugger.cpp +++ b/core/debugger.cpp @@ -22,6 +22,9 @@ limitations under the License. #include "adapters/lldbcoredumpadapter.h" #include "adapters/esrevenadapter.h" #include "adapters/x2winrpcadapter.h" +#ifdef __linux__ + #include "adapters/ptrace/ptraceadapter.h" +#endif #ifdef WIN32 #include "adapters/dbgengadapter.h" #include "adapters/dbgengttdadapter.h" @@ -59,6 +62,9 @@ void InitDebugAdapterTypes() InitEsrevenAdapterType(); InitLldbCoreDumpAdapterType(); InitX2WinRpcAdapterType(); +#ifdef __linux__ + InitPtraceAdapterType(); +#endif } From 9496a260fce08bb944b8ed973adb50e36cee349f Mon Sep 17 00:00:00 2001 From: Bradley Fernandez Date: Thu, 5 Nov 2026 13:16:05 -0500 Subject: [PATCH 2/6] Add breakpoints, module inspection and structured stepping Install software traps while preserving original bytes, and program x86 hardware breakpoints/watchpoints. Keep module-relative breakpoints pending until their modules load. Read process maps, ELF metadata and symbols, expose frame-pointer backtraces, and track the dynamic loader. Implement step-over and step-return with temporary breakpoints matched to the initiating thread and frame. --- core/CMakeLists.txt | 6 + core/adapters/ptrace/ptraceadapter.cpp | 636 ++++++++++++++++++++++++- core/adapters/ptrace/ptraceadapter.h | 43 +- core/adapters/ptrace/ptracearch.cpp | 83 ++++ core/adapters/ptrace/ptracearch.h | 33 ++ core/adapters/ptrace/ptraceelf.cpp | 200 ++++++++ core/adapters/ptrace/ptraceelf.h | 50 ++ core/adapters/ptrace/ptraceengine.cpp | 594 ++++++++++++++++++++++- core/adapters/ptrace/ptraceengine.h | 89 +++- core/adapters/ptrace/ptracemodule.cpp | 168 +++++++ core/adapters/ptrace/ptracemodule.h | 61 +++ core/adapters/ptrace/ptracestep.cpp | 172 +++++++ core/adapters/ptrace/ptracestep.h | 89 ++++ 13 files changed, 2178 insertions(+), 46 deletions(-) create mode 100644 core/adapters/ptrace/ptraceelf.cpp create mode 100644 core/adapters/ptrace/ptraceelf.h create mode 100644 core/adapters/ptrace/ptracemodule.cpp create mode 100644 core/adapters/ptrace/ptracemodule.h create mode 100644 core/adapters/ptrace/ptracestep.cpp create mode 100644 core/adapters/ptrace/ptracestep.h diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 0889988c..8fcc41e0 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -65,8 +65,14 @@ else() adapters/ptrace/ptraceadapter.h adapters/ptrace/ptracearch.cpp adapters/ptrace/ptracearch.h + adapters/ptrace/ptraceelf.cpp + adapters/ptrace/ptraceelf.h adapters/ptrace/ptraceengine.cpp adapters/ptrace/ptraceengine.h + adapters/ptrace/ptracemodule.cpp + adapters/ptrace/ptracemodule.h + adapters/ptrace/ptracestep.cpp + adapters/ptrace/ptracestep.h ) endif() endif() diff --git a/core/adapters/ptrace/ptraceadapter.cpp b/core/adapters/ptrace/ptraceadapter.cpp index 4cf51bc4..56f8432a 100644 --- a/core/adapters/ptrace/ptraceadapter.cpp +++ b/core/adapters/ptrace/ptraceadapter.cpp @@ -16,16 +16,24 @@ limitations under the License. #include #include +#include +#include #include #include #include #include "ptraceadapter.h" +#include "lowlevelilinstruction.h" namespace BinaryNinjaDebugger { static std::optional> ParseCommandLineArguments(const std::string& commandLine) { - enum class Quote { None, Single, Double }; + enum class Quote + { + None, + Single, + Double + }; Quote quote = Quote::None; bool escaped = false; bool argumentStarted = false; @@ -97,10 +105,34 @@ namespace BinaryNinjaDebugger { } + static bool HwTypeFromBreakpointType(DebugBreakpointType type, PtraceHwType& result) + { + switch (type) + { + case HardwareExecuteBreakpoint: + result = PtraceHwType::Execute; + return true; + case HardwareReadBreakpoint: + result = PtraceHwType::Read; + return true; + case HardwareWriteBreakpoint: + result = PtraceHwType::Write; + return true; + case HardwareAccessBreakpoint: + result = PtraceHwType::Access; + return true; + default: + return false; + } + } + + static DebugStopReason StopReasonFromEvent(const PtraceEngine::Event& event) { if (event.interrupted) return UnknownReason; + if (event.breakpoint || event.hardware) + return Breakpoint; if (event.signal == SIGTRAP) return event.singleStep ? SingleStep : Breakpoint; return SignalToDebugStopReason(event.signal); @@ -123,7 +155,26 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::ResolveModuleAddress(const ModuleNameAndOffset& location, uint64_t& address) { - return false; + if (location.module.empty()) + { + address = location.offset; + return true; + } + if (!m_engine) + return false; + + // The base of a module is where its first mapping starts + uint64_t base = UINT64_MAX; + for (const auto& map : m_engine->GetMaps()) + { + if (!map.path.empty() && DebugModule::IsSameBaseModule(map.path, location.module)) + base = std::min(base, map.start); + } + if (base == UINT64_MAX) + return false; + + address = base + location.offset; + return true; } @@ -136,6 +187,7 @@ namespace BinaryNinjaDebugger { PtraceAdapter::~PtraceAdapter() { + m_stepper.reset(); m_engine.reset(); } @@ -146,14 +198,16 @@ namespace BinaryNinjaDebugger { } - bool PtraceAdapter::ExecuteWithArgs(const std::string& path, const std::string& args, - const std::string& workingDir, const LaunchConfigurations& configs) + bool PtraceAdapter::ExecuteWithArgs(const std::string& path, const std::string& args, const std::string& workingDir, + const LaunchConfigurations& configs) { auto adapterSettings = GetAdapterSettings(); auto data = GetData(); BNSettingsScope scope = SettingsResourceScope; auto executablePath = adapterSettings->Get("launch.executablePath", data, &scope); scope = SettingsResourceScope; + m_inputFile = adapterSettings->Get("common.inputFile", data, &scope); + scope = SettingsResourceScope; auto workingDirectory = adapterSettings->Get("launch.workingDirectory", data, &scope); scope = SettingsResourceScope; auto commandLineArgs = adapterSettings->Get("launch.commandLineArguments", data, &scope); @@ -166,6 +220,8 @@ namespace BinaryNinjaDebugger { workingDirectory = workingDir; if (commandLineArgs.empty()) commandLineArgs = args; + if (m_inputFile.empty()) + m_inputFile = executablePath; auto launchFailure = [this](const std::string& error) { DebuggerEvent event; @@ -189,11 +245,18 @@ namespace BinaryNinjaDebugger { options.workingDir = workingDirectory; options.disableAslr = disableAslr; + m_stepper.reset(); m_engine.reset(); + ResetTargetState(); m_stopAtSystemEntry = Settings::Instance()->Get("debugger.stopAtSystemEntryPoint"); m_firstStop = true; m_targetActive = true; - m_engine = std::make_unique([this](const PtraceEngine::Event& event) { HandleEngineEvent(event); }); + m_engine = std::make_unique([this](const PtraceEngine::Event& event) { + HandleEngineEvent(event); + }); + m_stepper = std::make_unique( + *m_engine, [this](uint64_t address) { return AcquireBreakpoint(address); }, + [this](uint64_t address) { return ReleaseBreakpoint(address); }); std::string error; if (!m_engine->Launch(options, error)) @@ -211,27 +274,59 @@ namespace BinaryNinjaDebugger { switch (event.type) { case PtraceEngine::StoppedEvent: + m_stopGeneration++; m_activeThreadId = event.tid; m_lastStopReason = StopReasonFromEvent(event); if (m_firstStop) { m_firstStop = false; - m_arch = DetectPtraceArch(m_engine->GetPid()); + m_arch = m_engine->GetArch(); if (!m_arch) LogWarn("PtraceAdapter: unsupported target architecture"); + + if (Settings::Instance()->Get("debugger.stopAtEntryPoint") && m_hasEntryFunction) + AddBreakpoint(ModuleNameAndOffset(m_inputFile, m_entryPoint - m_start), 0); + SetUpLoaderBreakpoint(); if (!m_stopAtSystemEntry) { + ApplyBreakpoints(); m_engine->Resume(false, 0); break; } } + // A library was loaded or unloaded, which may be where a pending breakpoint goes + if (event.breakpoint && m_loaderBreakpoint && m_arch.load() + && ReadArchRegister(m_arch.load()->pc) == m_loaderBreakpoint) + { + ApplyBreakpoints(); + m_engine->Resume(false, 0); + break; + } + + if (m_stepper && m_stepper->IsActive()) + { + auto arch = m_arch.load(); + uint64_t pc = arch ? ReadArchRegister(arch->pc) : 0; + uint64_t sp = arch ? ReadArchRegister(arch->sp) : 0; + auto result = m_stepper->OnStop(event, pc, sp, IsUserBreakpoint(pc)); + if (result == PtraceStepper::Result::Consumed) + break; + if (result == PtraceStepper::Result::Finished) + m_lastStopReason = SingleStep; + } + + ApplyBreakpoints(); dbgevt.type = AdapterStoppedEventType; dbgevt.data.targetStoppedData.reason = m_lastStopReason; dbgevt.data.targetStoppedData.lastActiveThread = event.tid; PostDebuggerEvent(dbgevt); break; case PtraceEngine::ExitedEvent: + m_stopGeneration++; m_targetActive = false; + if (m_stepper) + m_stepper->Cancel(); + ClearBreakpoints(); m_lastStopReason = ProcessExited; m_exitCode = event.signal ? 128 + event.signal : event.exitCode; dbgevt.type = TargetExitedEventType; @@ -240,9 +335,15 @@ namespace BinaryNinjaDebugger { break; case PtraceEngine::DetachedEvent: m_targetActive = false; + if (m_stepper) + m_stepper->Cancel(); + ClearBreakpoints(); dbgevt.type = DetachedEventType; PostDebuggerEvent(dbgevt); break; + case PtraceEngine::TaskEvent: + // The engine runs these itself + break; case PtraceEngine::OutputEvent: dbgevt.type = StdoutMessageEventType; dbgevt.data.messageData.message = event.data; @@ -279,7 +380,10 @@ namespace BinaryNinjaDebugger { std::vector PtraceAdapter::GetProcessList() { - return {}; + std::vector processes; + for (const auto& process : ListProcesses()) + processes.push_back(DebugProcess(process.pid, process.name, process.commandLine)); + return processes; } @@ -356,66 +460,205 @@ namespace BinaryNinjaDebugger { } + bool PtraceAdapter::ReadRegisterOf(uint32_t tid, const std::string& name, uint64_t& value) + { + auto arch = m_arch.load(); + auto info = arch ? arch->Find(name) : nullptr; + std::vector data; + if (!m_engine || !info || !m_engine->GetRegisterSet(tid, info->regset, data) || !RegisterInBounds(*info, data)) + return false; + + value = (uint64_t)RegisterFromBytes(*info, data, 0).m_value; + return true; + } + + std::vector PtraceAdapter::GetFramesOfThread(uint32_t tid) { - return {}; + std::vector frames; + auto arch = m_arch.load(); + auto pcInfo = arch ? arch->Find(arch->pc) : nullptr; + uint64_t pc, sp, fp = 0; + if (!m_engine || !pcInfo || m_engine->IsRunning() || !ReadRegisterOf(tid, arch->pc, pc) + || !ReadRegisterOf(tid, arch->sp, sp)) + return frames; + // Without a frame pointer register there is only the one frame + if (!arch->fp.empty()) + ReadRegisterOf(tid, arch->fp, fp); + + std::vector> executable; + for (const auto& map : m_engine->GetMaps()) + { + if (map.execute) + executable.emplace_back(map.start, map.end); + } + std::sort(executable.begin(), executable.end()); + + size_t wordSize = pcInfo->size; + auto isExecutable = [&executable](uint64_t address) { + auto it = std::upper_bound(executable.begin(), executable.end(), std::make_pair(address, UINT64_MAX)); + return it != executable.begin() && address < std::prev(it)->second; + }; + auto readWord = [this, wordSize](uint64_t address, uint64_t& value) { + value = 0; + return m_engine->ReadMemory(address, &value, wordSize); + }; + + auto modules = GetModules(); + size_t index = 0; + for (const auto& record : UnwindFramePointers(pc, sp, fp, wordSize, readWord, isExecutable)) + { + std::string functionName; + uint64_t functionStart = 0; + std::string moduleName = ""; + for (const auto& module : modules) + { + if (record.pc < module.base || record.pc >= module.base + module.size) + continue; + + moduleName = module.shortName; + auto elf = GetElf(module.path); + uint64_t bias = module.base - (elf ? elf->linkBase : 0); + if (auto symbol = elf ? FindElfSymbol(*elf, record.pc - bias) : nullptr) + { + functionName = symbol->name; + functionStart = symbol->address + bias; + } + break; + } + + frames.push_back( + DebugFrame(index++, record.pc, record.sp, record.fp, functionName, functionStart, moduleName)); + } + return frames; } DebugBreakpoint PtraceAdapter::AddBreakpoint(const std::uintptr_t address, unsigned long breakpoint_type) { - return DebugBreakpoint(); + if (!m_engine || !m_targetActive) + return DebugBreakpoint(); + + std::lock_guard lock(m_breakpointMutex); + auto it = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [address](const DebugBreakpoint& bp) { + return bp.m_address == address; + }); + if (it != m_breakpoints.end()) + return *it; + + if (!AcquireBreakpoint(address)) + { + LogWarn("PtraceAdapter: failed to set a breakpoint at 0x%" PRIx64, (uint64_t)address); + return DebugBreakpoint(); + } + + m_breakpoints.emplace_back(address, m_nextBreakpointId++, true); + return m_breakpoints.back(); } DebugBreakpoint PtraceAdapter::AddBreakpoint(const ModuleNameAndOffset& address, unsigned long breakpoint_type) { + std::lock_guard lock(m_breakpointMutex); + uint64_t resolved; + if (m_targetActive && ResolveModuleAddress(address, resolved)) + return AddBreakpoint(resolved, breakpoint_type); + + // The module is not loaded yet, so this waits for it + if (std::find(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address) == m_pendingBreakpoints.end()) + m_pendingBreakpoints.push_back(address); return DebugBreakpoint(); } bool PtraceAdapter::RemoveBreakpoint(const DebugBreakpoint& breakpoint) { - return false; + std::lock_guard lock(m_breakpointMutex); + auto it = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [&breakpoint](const DebugBreakpoint& bp) { + return bp.m_address == breakpoint.m_address; + }); + if (!m_engine || it == m_breakpoints.end() || !ReleaseBreakpoint(breakpoint.m_address)) + return false; + + m_breakpoints.erase(it); + return true; } bool PtraceAdapter::RemoveBreakpoint(const ModuleNameAndOffset& address) { - return false; + std::lock_guard lock(m_breakpointMutex); + auto pending = std::find(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address); + if (pending != m_pendingBreakpoints.end()) + { + m_pendingBreakpoints.erase(pending); + return true; + } + + uint64_t resolved; + return m_targetActive && ResolveModuleAddress(address, resolved) && RemoveBreakpoint(DebugBreakpoint(resolved)); } std::vector PtraceAdapter::GetBreakpointList() const { - return {}; + std::lock_guard lock(m_breakpointMutex); + return m_breakpoints; } // Hardware breakpoint and watchpoint support bool PtraceAdapter::AddHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size) { - return false; + PtraceHwType hwType; + if (!m_engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) + return false; + + return m_engine->AddHardwareBreakpoint(address, hwType, size); } bool PtraceAdapter::RemoveHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size) { - return false; + PtraceHwType hwType; + if (!m_engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) + return false; + + return m_engine->RemoveHardwareBreakpoint(address, hwType, size); } bool PtraceAdapter::AddHardwareBreakpoint( const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size) { - return false; + std::lock_guard lock(m_breakpointMutex); + uint64_t resolved; + if (m_targetActive && ResolveModuleAddress(location, resolved)) + return AddHardwareBreakpoint(resolved, type, size); + + PendingHardwareBreakpoint pending(location, type, size); + if (std::find(m_pendingHardwareBreakpoints.begin(), m_pendingHardwareBreakpoints.end(), pending) + == m_pendingHardwareBreakpoints.end()) + m_pendingHardwareBreakpoints.push_back(pending); + return true; } bool PtraceAdapter::RemoveHardwareBreakpoint( const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size) { - return false; + std::lock_guard lock(m_breakpointMutex); + PendingHardwareBreakpoint pending(location, type, size); + auto it = std::find(m_pendingHardwareBreakpoints.begin(), m_pendingHardwareBreakpoints.end(), pending); + if (it != m_pendingHardwareBreakpoints.end()) + { + m_pendingHardwareBreakpoints.erase(it); + return true; + } + + uint64_t resolved; + return m_targetActive && ResolveModuleAddress(location, resolved) + && RemoveHardwareBreakpoint(resolved, type, size); } @@ -503,21 +746,147 @@ namespace BinaryNinjaDebugger { } + std::vector PtraceAdapter::GetModules() + { + if (!m_engine) + return {}; + + std::lock_guard lock(m_moduleMutex); + uint64_t generation = m_stopGeneration; + if (m_moduleGeneration != generation) + { + m_modules = BuildModules(m_engine->GetMaps(), [this](uint64_t address) { + uint8_t magic[4]; + return m_engine->ReadMemory(address, magic, sizeof(magic)) + && memcmp(magic, + "\x7f" + "ELF", + 4) + == 0; + }); + m_moduleGeneration = generation; + } + return m_modules; + } + + + std::shared_ptr PtraceAdapter::GetElf(const std::string& path) + { + std::lock_guard lock(m_moduleMutex); + auto it = m_elfCache.find(path); + if (it != m_elfCache.end()) + return it->second; + + // A file that cannot be read is remembered as well, so that it is not tried for every frame + auto elf = std::make_shared(); + if (!ReadElfFile(path, *elf)) + elf = nullptr; + m_elfCache[path] = elf; + return elf; + } + + + void PtraceAdapter::ResetTargetState() + { + std::lock_guard lock(m_moduleMutex); + m_elfCache.clear(); + m_modules.clear(); + m_moduleGeneration = UINT64_MAX; + m_loaderBreakpoint = 0; + } + + + // The dynamic loader calls _dl_debug_state every time it changes the list of libraries. Stopping there is how + // a breakpoint in a library gets placed before the library runs, and how libraries that are loaded later are found. + void PtraceAdapter::SetUpLoaderBreakpoint() + { + if (!m_engine) + return; + + std::error_code error; + auto exe = std::filesystem::read_symlink("/proc/" + std::to_string(m_engine->GetPid()) + "/exe", error); + auto elf = error ? nullptr : GetElf(exe.string()); + if (!elf || elf->interpreter.empty()) + return; + + for (const auto& module : GetModules()) + { + if (!DebugModule::IsSameBaseModule(module.path, elf->interpreter)) + continue; + + auto loader = GetElf(module.path); + if (!loader) + return; + + for (const auto& symbol : loader->symbols) + { + if (symbol.name != "_dl_debug_state") + continue; + + uint64_t address = symbol.address + module.base - loader->linkBase; + if (AcquireBreakpoint(address)) + m_loaderBreakpoint = address; + return; + } + return; + } + } + + std::vector PtraceAdapter::GetModuleList() { - return {}; + std::vector modules; + for (const auto& module : GetModules()) + modules.push_back(DebugModule(module.path, module.shortName, module.base, module.size, true)); + return modules; } std::vector PtraceAdapter::GetMemoryMap() { - return {}; + std::vector regions; + if (!m_engine) + return regions; + + for (const auto& map : m_engine->GetMaps()) + { + if (map.end > map.start) + regions.push_back(DebugMemoryRegion( + map.start, map.end - map.start, map.path, map.read, map.write, map.execute, map.shared)); + } + return regions; } std::vector PtraceAdapter::GetSymbolsForModule(const DebugModule& module) { - return {}; + std::vector symbols; + const PtraceModuleInfo* match = nullptr; + auto modules = GetModules(); + for (const auto& candidate : modules) + { + // Prefer the module at the same address, since two modules can have the same name + if (candidate.base == module.m_address) + { + match = &candidate; + break; + } + if (!match && module.IsSameBaseModule(candidate.path)) + match = &candidate; + } + + auto elf = match ? GetElf(match->path) : nullptr; + if (!elf) + return symbols; + + uint64_t bias = match->base - elf->linkBase; + symbols.reserve(elf->symbols.size()); + for (const auto& symbol : elf->symbols) + { + symbols.push_back(DebugSymbol(symbol.name, match->shortName + "!" + symbol.name, symbol.name, + symbol.address + bias, symbol.size, symbol.isFunction)); + } + return symbols; } @@ -548,6 +917,9 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::Go() { + if (m_stepper) + m_stepper->Cancel(); + m_stopGeneration++; if (!m_engine || !m_engine->Resume(false, 0)) return false; @@ -560,6 +932,9 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::StepInto() { + if (m_stepper) + m_stepper->Cancel(); + m_stopGeneration++; if (!m_engine || !m_engine->Resume(true, m_activeThreadId)) return false; @@ -570,15 +945,151 @@ namespace BinaryNinjaDebugger { } + // The controller calls these with the adapter lock held, and working out what to do needs the analysis of + // Binary Ninja, which must not be called under that lock. So the work is done on the thread of the events, and the + // controller waits for the stop as it does for any other step. bool PtraceAdapter::StepOver() { - return false; + if (!m_engine || !m_stepper || m_engine->IsRunning()) + return false; + + m_stepper->Cancel(); + m_stopGeneration++; + uint32_t tid = m_activeThreadId; + m_engine->PostTask([this, tid] { DoStepOver(tid); }); + + DebuggerEvent event; + event.type = StepOverEventType; + PostDebuggerEvent(event); + return true; } bool PtraceAdapter::StepReturn() { - return false; + if (!m_engine || !m_stepper || m_engine->IsRunning()) + return false; + + m_stepper->Cancel(); + m_stopGeneration++; + uint32_t tid = m_activeThreadId; + m_engine->PostTask([this, tid] { DoStepReturn(tid); }); + + DebuggerEvent event; + event.type = StepOverEventType; + PostDebuggerEvent(event); + return true; + } + + + // The controller is waiting for a stop, so a step that cannot be done still has to end in one + void PtraceAdapter::FailStep(const std::string& message) + { + DebuggerEvent event; + event.type = ErrorEventType; + event.data.errorData.shortError = "Step failed"; + event.data.errorData.error = fmt::format("PTRACE: {}", message); + PostDebuggerEvent(event); + + m_lastStopReason = UnknownReason; + DebuggerEvent stopped; + stopped.type = AdapterStoppedEventType; + stopped.data.targetStoppedData.reason = UnknownReason; + stopped.data.targetStoppedData.lastActiveThread = m_activeThreadId; + PostDebuggerEvent(stopped); + } + + + size_t PtraceAdapter::GetCallLength(uint64_t pc) + { + auto data = GetData(); + auto arch = data ? data->GetDefaultArchitecture() : nullptr; + if (!arch) + return 0; + + DataBuffer buffer = ReadMemory(pc, arch->GetMaxInstructionLength()); + size_t bytesRead = buffer.GetLength(); + if (bytesRead == 0) + return 0; + + Ref il = new LowLevelILFunction(arch, nullptr); + il->SetCurrentAddress(arch, pc); + arch->GetInstructionLowLevelIL((const uint8_t*)buffer.GetData(), pc, bytesRead, *il); + if (il->GetInstructionCount() == 0 || (*il)[0].operation != LLIL_CALL) + return 0; + + InstructionInfo info; + if (!arch->GetInstructionInfo((const uint8_t*)buffer.GetData(), pc, bytesRead, info)) + return 0; + return info.length; + } + + + std::vector PtraceAdapter::GetReturnSites(uint64_t pc) + { + std::vector sites; + auto data = GetData(); + auto functions = data ? data->GetAnalysisFunctionsContainingAddress(pc) : std::vector>(); + if (functions.empty() || !functions[0]) + return sites; + + auto il = functions[0]->GetLowLevelIL(); + if (!il) + return sites; + + for (size_t i = 0; i < il->GetInstructionCount(); i++) + { + auto instruction = il->GetInstruction(i); + if (instruction.operation == LLIL_RET || instruction.operation == LLIL_TAILCALL) + sites.push_back(instruction.address); + } + return sites; + } + + + void PtraceAdapter::DoStepOver(uint32_t tid) + { + auto arch = m_arch.load(); + auto pcInfo = arch ? arch->Find(arch->pc) : nullptr; + uint64_t pc, sp; + if (!pcInfo || !ReadRegisterOf(tid, arch->pc, pc) || !ReadRegisterOf(tid, arch->sp, sp)) + { + FailStep("could not read the registers of the thread"); + return; + } + + if (!m_stepper->StepOver(tid, pc, sp, GetCallLength(pc), pcInfo->size)) + FailStep("could not step over the instruction"); + } + + + void PtraceAdapter::DoStepReturn(uint32_t tid) + { + auto arch = m_arch.load(); + uint64_t pc, sp; + if (!arch || !ReadRegisterOf(tid, arch->pc, pc) || !ReadRegisterOf(tid, arch->sp, sp)) + { + FailStep("could not read the registers of the thread"); + return; + } + + // Without an analysis of the function, its caller is found from the frame pointers + auto sites = GetReturnSites(pc); + uint64_t returnAddress = 0, returnSp = 0; + if (sites.empty()) + { + auto frames = GetFramesOfThread(tid); + if (frames.size() >= 2) + { + returnAddress = frames[1].m_pc; + returnSp = frames[1].m_sp; + } + } + + // A return instruction has the stack pointer of the function or above it, on every ABI that keeps the return + // address on the stack, as well as on those that do not once the epilogue has run + if (!m_stepper->StepReturn(tid, pc, sp, sites, returnAddress, returnSp)) + FailStep("could not find where the function returns"); } @@ -606,7 +1117,11 @@ namespace BinaryNinjaDebugger { { switch (feature) { + case DebugAdapterSupportStepOver: + case DebugAdapterSupportStepReturn: case DebugAdapterSupportThreads: + case DebugAdapterSupportModules: + case DebugAdapterSupportSymbols: return true; default: return false; @@ -639,7 +1154,81 @@ namespace BinaryNinjaDebugger { } - void PtraceAdapter::ApplyBreakpoints() {} + void PtraceAdapter::ApplyBreakpoints() + { + std::lock_guard lock(m_breakpointMutex); + if (!m_engine || !m_targetActive) + return; + + // Only what has been applied leaves the list, so the rest waits for a module that is not loaded yet + for (auto it = m_pendingBreakpoints.begin(); it != m_pendingBreakpoints.end();) + { + uint64_t address; + if (ResolveModuleAddress(*it, address) && AddBreakpoint(address, 0).m_address != 0) + it = m_pendingBreakpoints.erase(it); + else + it++; + } + + for (auto it = m_pendingHardwareBreakpoints.begin(); it != m_pendingHardwareBreakpoints.end();) + { + uint64_t address = it->address; + bool resolved = !it->isRelative || ResolveModuleAddress(it->location, address); + if (resolved && AddHardwareBreakpoint(address, it->type, it->size)) + it = m_pendingHardwareBreakpoints.erase(it); + else + it++; + } + } + + + void PtraceAdapter::ClearBreakpoints() + { + std::lock_guard lock(m_breakpointMutex); + m_breakpoints.clear(); + m_engineBreakpointRefs.clear(); + } + + + bool PtraceAdapter::AcquireBreakpoint(uint64_t address) + { + std::lock_guard lock(m_breakpointMutex); + if (!m_engine) + return false; + + int& count = m_engineBreakpointRefs[address]; + if (count == 0 && !m_engine->AddBreakpoint(address)) + { + m_engineBreakpointRefs.erase(address); + return false; + } + count++; + return true; + } + + + bool PtraceAdapter::ReleaseBreakpoint(uint64_t address) + { + std::lock_guard lock(m_breakpointMutex); + auto it = m_engineBreakpointRefs.find(address); + if (!m_engine || it == m_engineBreakpointRefs.end()) + return false; + + if (--it->second > 0) + return true; + + m_engineBreakpointRefs.erase(it); + return m_engine->RemoveBreakpoint(address); + } + + + bool PtraceAdapter::IsUserBreakpoint(uint64_t address) + { + std::lock_guard lock(m_breakpointMutex); + return std::any_of(m_breakpoints.begin(), m_breakpoints.end(), [address](const DebugBreakpoint& bp) { + return bp.m_address == address; + }); + } void PtraceAdapter::GenerateDefaultAdapterSettings(BinaryView* data) @@ -648,7 +1237,8 @@ namespace BinaryNinjaDebugger { BNSettingsScope scope = SettingsResourceScope; adapterSettings->Get("common.inputFile", data, &scope); if (scope != SettingsResourceScope) - adapterSettings->Set("common.inputFile", data->GetFile()->GetOriginalFilename(), data, SettingsResourceScope); + adapterSettings->Set( + "common.inputFile", data->GetFile()->GetOriginalFilename(), data, SettingsResourceScope); scope = SettingsResourceScope; adapterSettings->Get("launch.executablePath", data, &scope); diff --git a/core/adapters/ptrace/ptraceadapter.h b/core/adapters/ptrace/ptraceadapter.h index 4f5bce6e..d44d9ccd 100644 --- a/core/adapters/ptrace/ptraceadapter.h +++ b/core/adapters/ptrace/ptraceadapter.h @@ -16,10 +16,15 @@ limitations under the License. #pragma once #include +#include #include +#include #include "../../debugadapter.h" #include "../../debugadaptertype.h" #include "ptracearch.h" +#include "ptraceelf.h" +#include "ptracemodule.h" +#include "ptracestep.h" #include "ptraceengine.h" namespace BinaryNinjaDebugger { @@ -27,6 +32,7 @@ namespace BinaryNinjaDebugger { { private: std::unique_ptr m_engine; + std::unique_ptr m_stepper; std::atomic m_targetActive; std::atomic m_activeThreadId {0}; std::atomic m_lastStopReason {UnknownReason}; @@ -35,11 +41,42 @@ namespace BinaryNinjaDebugger { bool m_firstStop = false; bool m_stopAtSystemEntry = false; + std::string m_inputFile; + + // Bumped whenever the target may have changed, which is when the cached modules go stale + std::atomic m_stopGeneration {0}; + std::mutex m_moduleMutex; + uint64_t m_moduleGeneration = UINT64_MAX; + std::vector m_modules; + std::map> m_elfCache; + // The dynamic loader calls this every time the libraries of the target change + uint64_t m_loaderBreakpoint = 0; + + // Guards the breakpoint lists. It is recursive because adding one by module and offset adds it by address. + mutable std::recursive_mutex m_breakpointMutex; + std::vector m_breakpoints; + // How many users the breakpoint of the engine at an address has: the user, a step, the dynamic loader + std::map m_engineBreakpointRefs; + unsigned long m_nextBreakpointId = 1; std::vector m_pendingBreakpoints {}; std::vector m_pendingHardwareBreakpoints {}; void HandleEngineEvent(const PtraceEngine::Event& event); + void ClearBreakpoints(); uint64_t ReadArchRegister(const std::string& name); + bool ReadRegisterOf(uint32_t tid, const std::string& name, uint64_t& value); + std::vector GetModules(); + std::shared_ptr GetElf(const std::string& path); + void SetUpLoaderBreakpoint(); + bool AcquireBreakpoint(uint64_t address); + bool ReleaseBreakpoint(uint64_t address); + bool IsUserBreakpoint(uint64_t address); + void DoStepOver(uint32_t tid); + void DoStepReturn(uint32_t tid); + void FailStep(const std::string& message); + size_t GetCallLength(uint64_t pc); + std::vector GetReturnSites(uint64_t pc); + void ResetTargetState(); // Helper to resolve module+offset to absolute address // Returns true if the module was found in the loaded module list and address was resolved @@ -96,8 +133,10 @@ namespace BinaryNinjaDebugger { // Hardware breakpoint and watchpoint support bool AddHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size = 1) override; bool RemoveHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size = 1) override; - bool AddHardwareBreakpoint(const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size = 1) override; - bool RemoveHardwareBreakpoint(const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size = 1) override; + bool AddHardwareBreakpoint( + const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size = 1) override; + bool RemoveHardwareBreakpoint( + const ModuleNameAndOffset& location, DebugBreakpointType type, size_t size = 1) override; std::unordered_map ReadAllRegisters() override; diff --git a/core/adapters/ptrace/ptracearch.cpp b/core/adapters/ptrace/ptracearch.cpp index 01df80d7..fb7ed704 100644 --- a/core/adapters/ptrace/ptracearch.cpp +++ b/core/adapters/ptrace/ptracearch.cpp @@ -16,7 +16,9 @@ limitations under the License. #include "ptracearch.h" #include +#include #include +#include namespace BinaryNinjaDebugger { @@ -31,6 +33,77 @@ namespace BinaryNinjaDebugger { } + // The debug registers are read and written through PTRACE_PEEKUSER and PTRACE_POKEUSER, at the offset of u_debugreg + // in struct user. The offset differs between 32-bit and 64-bit targets. + class X86HwDebug : public PtraceHwDebug + { + size_t m_offset; + + bool ReadDr(pid_t tid, size_t index, unsigned long& value) + { + errno = 0; + value = ptrace(PTRACE_PEEKUSER, tid, (void*)(m_offset + index * sizeof(long)), nullptr); + return errno == 0; + } + + bool WriteDr(pid_t tid, size_t index, unsigned long value) + { + return ptrace(PTRACE_POKEUSER, tid, (void*)(m_offset + index * sizeof(long)), (void*)value) == 0; + } + + public: + X86HwDebug(size_t offset) : m_offset(offset) {} + + size_t SlotCount() const override { return 4; } + + bool SlotSupports(size_t slot, PtraceHwType type) const override { return slot < 4; } + + bool Set(pid_t tid, size_t slot, uint64_t address, PtraceHwType type, size_t size) override + { + // x86 has no read-only watchpoint, so a read watches for any access + unsigned long rw = type == PtraceHwType::Execute ? 0 : (type == PtraceHwType::Write ? 1 : 3); + unsigned long len; + switch (type == PtraceHwType::Execute ? 1 : size) + { + case 1: + len = 0; + break; + case 2: + len = 1; + break; + case 4: + len = 3; + break; + case 8: + len = 2; + break; + default: + return false; + } + + unsigned long control; + if (!ReadDr(tid, 7, control) || !WriteDr(tid, slot, address)) + return false; + + control &= ~((3ul << (16 + slot * 4)) | (3ul << (18 + slot * 4)) | (1ul << (slot * 2))); + control |= (1ul << (slot * 2)) | (rw << (16 + slot * 4)) | (len << (18 + slot * 4)); + return WriteDr(tid, 7, control); + } + + bool Clear(pid_t tid, size_t slot) override + { + unsigned long control; + if (!ReadDr(tid, 7, control)) + return false; + + control &= ~((3ul << (16 + slot * 4)) | (3ul << (18 + slot * 4)) | (1ul << (slot * 2))); + return WriteDr(tid, 7, control) && WriteDr(tid, slot, 0); + } + + void OnTrap(pid_t tid) override { WriteDr(tid, 6, 0); } + }; + + static void AddRegisters(PtraceArch& arch, int regset, size_t size, const std::vector& names, const std::vector& indices) { @@ -45,7 +118,12 @@ namespace BinaryNinjaDebugger { arch.name = "x86_64"; arch.pc = "rip"; arch.sp = "rsp"; + arch.fp = "rbp"; arch.regsets = {NT_PRSTATUS, NT_PRFPREG}; + arch.breakpointInstruction = {0xcc}; + arch.breakpointPcAdjust = 1; + static X86HwDebug hwDebug(848); + arch.hwDebug = &hwDebug; // The order of user_regs_struct: r15 r14 r13 r12 rbp rbx r11 r10 r9 r8 rax rcx rdx rsi rdi orig_rax rip cs // eflags rsp ss fs_base gs_base ds es fs gs. The registers are listed in the order GDB uses. @@ -73,7 +151,12 @@ namespace BinaryNinjaDebugger { arch.name = "x86"; arch.pc = "eip"; arch.sp = "esp"; + arch.fp = "ebp"; arch.regsets = {NT_PRSTATUS}; + arch.breakpointInstruction = {0xcc}; + arch.breakpointPcAdjust = 1; + static X86HwDebug hwDebug(252); + arch.hwDebug = &hwDebug; // The order of the 32-bit user_regs_struct: ebx ecx edx esi edi ebp eax xds xes xfs xgs orig_eax eip xcs // eflags esp xss diff --git a/core/adapters/ptrace/ptracearch.h b/core/adapters/ptrace/ptracearch.h index 105804f7..28e11e2f 100644 --- a/core/adapters/ptrace/ptracearch.h +++ b/core/adapters/ptrace/ptracearch.h @@ -17,6 +17,7 @@ limitations under the License. #pragma once #include #include +#include #include #include @@ -30,6 +31,31 @@ namespace BinaryNinjaDebugger { size_t size; }; + enum class PtraceHwType + { + Execute, + Write, + Read, + Access + }; + + // The debug registers of one architecture. The thread must be stopped for all of these. + class PtraceHwDebug + { + public: + virtual ~PtraceHwDebug() = default; + + virtual size_t SlotCount() const = 0; + virtual bool SlotSupports(size_t slot, PtraceHwType type) const = 0; + virtual bool Set(pid_t tid, size_t slot, uint64_t address, PtraceHwType type, size_t size) = 0; + virtual bool Clear(pid_t tid, size_t slot) = 0; + // Called after a thread trapped on one of the slots + virtual void OnTrap(pid_t tid) {} + // Whether a watchpoint reports before its access has happened, so that the access has to be stepped over. + // Execute breakpoints always report first. + virtual bool DataTrapsBeforeAccess() const { return false; } + }; + // Describes the registers of one target architecture. Nothing outside of this table and DetectPtraceArch needs to // know how a particular architecture lays its registers out. struct PtraceArch @@ -37,9 +63,16 @@ namespace BinaryNinjaDebugger { std::string name; std::string pc; std::string sp; + // The register that points at the frame of the running function + std::string fp; std::vector registers; std::vector regsets; + // The bytes of a software breakpoint. After it traps, the PC is this many bytes past its address. + std::vector breakpointInstruction; + size_t breakpointPcAdjust = 0; + PtraceHwDebug* hwDebug = nullptr; + const PtraceRegister* Find(const std::string& registerName) const; }; diff --git a/core/adapters/ptrace/ptraceelf.cpp b/core/adapters/ptrace/ptraceelf.cpp new file mode 100644 index 00000000..df9f9e44 --- /dev/null +++ b/core/adapters/ptrace/ptraceelf.cpp @@ -0,0 +1,200 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptraceelf.h" +#include +#include +#include +#include + +namespace BinaryNinjaDebugger { + + struct Elf32Types + { + using Ehdr = Elf32_Ehdr; + using Phdr = Elf32_Phdr; + using Shdr = Elf32_Shdr; + using Sym = Elf32_Sym; + }; + + struct Elf64Types + { + using Ehdr = Elf64_Ehdr; + using Phdr = Elf64_Phdr; + using Shdr = Elf64_Shdr; + using Sym = Elf64_Sym; + }; + + + static bool ReadAt(std::ifstream& file, uint64_t offset, void* buffer, size_t size) + { + file.clear(); + file.seekg(offset); + return file.read(reinterpret_cast(buffer), size).gcount() == (std::streamsize)size; + } + + + template + static void ReadSymbols(std::ifstream& file, uint64_t fileSize, const typename T::Shdr& table, + const typename T::Shdr& strings, std::vector& symbols) + { + if (table.sh_offset > fileSize || table.sh_size > fileSize - table.sh_offset || strings.sh_offset > fileSize + || strings.sh_size > fileSize - strings.sh_offset) + return; + + std::vector tableData(table.sh_size); + std::vector stringData(strings.sh_size); + if (!ReadAt(file, table.sh_offset, tableData.data(), tableData.size()) + || !ReadAt(file, strings.sh_offset, stringData.data(), stringData.size())) + return; + + size_t entrySize = table.sh_entsize ? table.sh_entsize : sizeof(typename T::Sym); + if (entrySize < sizeof(typename T::Sym)) + return; + + for (size_t offset = 0; offset + sizeof(typename T::Sym) <= tableData.size(); offset += entrySize) + { + typename T::Sym symbol; + memcpy(&symbol, tableData.data() + offset, sizeof(symbol)); + + unsigned type = ELF32_ST_TYPE(symbol.st_info); + bool isFunction = type == STT_FUNC || type == STT_GNU_IFUNC; + if (!isFunction && type != STT_OBJECT) + continue; + if (symbol.st_shndx == SHN_UNDEF || symbol.st_shndx >= SHN_LORESERVE || symbol.st_value == 0) + continue; + if (symbol.st_name == 0 || symbol.st_name >= stringData.size()) + continue; + + // The string table is terminated, but the file may not be + size_t length = strnlen(stringData.data() + symbol.st_name, stringData.size() - symbol.st_name); + ElfSymbol result; + result.name.assign(stringData.data() + symbol.st_name, length); + result.address = symbol.st_value; + result.size = symbol.st_size; + result.isFunction = isFunction; + symbols.push_back(std::move(result)); + } + } + + + template + static bool ParseElf(std::ifstream& file, uint64_t fileSize, ElfInfo& info) + { + typename T::Ehdr header; + if (!ReadAt(file, 0, &header, sizeof(header))) + return false; + + info.type = header.e_type; + info.entry = header.e_entry; + + bool haveLoad = false; + uint64_t lowest = 0; + for (unsigned i = 0; i < header.e_phnum && header.e_phentsize >= sizeof(typename T::Phdr); i++) + { + typename T::Phdr segment; + if (!ReadAt(file, header.e_phoff + (uint64_t)i * header.e_phentsize, &segment, sizeof(segment))) + break; + + if (segment.p_type == PT_LOAD && (!haveLoad || segment.p_vaddr < lowest)) + { + lowest = segment.p_vaddr; + haveLoad = true; + } + else if (segment.p_type == PT_INTERP && segment.p_filesz > 0 && segment.p_filesz < 4096) + { + std::string path(segment.p_filesz, '\0'); + if (ReadAt(file, segment.p_offset, path.data(), path.size())) + info.interpreter = path.c_str(); + } + } + info.linkBase = lowest & ~0xfffull; + + if (header.e_shoff == 0 || header.e_shnum == 0 || header.e_shentsize < sizeof(typename T::Shdr)) + return true; + + std::vector sections; + for (unsigned i = 0; i < header.e_shnum; i++) + { + typename T::Shdr section; + if (!ReadAt(file, header.e_shoff + (uint64_t)i * header.e_shentsize, §ion, sizeof(section))) + break; + sections.push_back(section); + } + + for (const auto& section : sections) + { + if ((section.sh_type == SHT_SYMTAB || section.sh_type == SHT_DYNSYM) && section.sh_link < sections.size()) + ReadSymbols(file, fileSize, section, sections[section.sh_link], info.symbols); + } + + std::stable_sort(info.symbols.begin(), info.symbols.end(), [](const ElfSymbol& a, const ElfSymbol& b) { + return a.address < b.address; + }); + // The dynamic symbols repeat in the full table + info.symbols.erase( + std::unique(info.symbols.begin(), info.symbols.end(), + [](const ElfSymbol& a, const ElfSymbol& b) { return a.address == b.address && a.name == b.name; }), + info.symbols.end()); + return true; + } + + + bool ReadElfFile(const std::string& path, ElfInfo& info) + { + std::ifstream file(path, std::ios::binary); + unsigned char ident[EI_NIDENT] = {}; + if (!file || !file.read(reinterpret_cast(ident), sizeof(ident))) + return false; + if (memcmp(ident, ELFMAG, SELFMAG) != 0 || ident[EI_DATA] != ELFDATA2LSB) + return false; + + file.seekg(0, std::ios::end); + uint64_t fileSize = file.tellg(); + + info = ElfInfo(); + if (ident[EI_CLASS] == ELFCLASS64) + { + info.is64 = true; + return ParseElf(file, fileSize, info); + } + if (ident[EI_CLASS] == ELFCLASS32) + return ParseElf(file, fileSize, info); + return false; + } + + + const ElfSymbol* FindElfSymbol(const ElfInfo& info, uint64_t address) + { + // The last symbols that start at or before the address are the candidates + auto end = std::upper_bound(info.symbols.begin(), info.symbols.end(), address, + [](uint64_t value, const ElfSymbol& symbol) { return value < symbol.address; }); + + const ElfSymbol* fallback = nullptr; + size_t checked = 0; + while (end != info.symbols.begin() && checked++ < 32) + { + --end; + if (address - end->address < end->size) + return &*end; + // A symbol without a size is only a guess, and a function is a better one than data + if (!fallback && end->size == 0 && end->isFunction) + fallback = &*end; + } + return fallback; + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceelf.h b/core/adapters/ptrace/ptraceelf.h new file mode 100644 index 00000000..5202cbf3 --- /dev/null +++ b/core/adapters/ptrace/ptraceelf.h @@ -0,0 +1,50 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include + +namespace BinaryNinjaDebugger { + struct ElfSymbol + { + std::string name; + // As it is in the file. Add the load bias of the module to get the address in the target. + uint64_t address = 0; + uint64_t size = 0; + bool isFunction = false; + }; + + struct ElfInfo + { + uint16_t type = 0; + bool is64 = false; + uint64_t entry = 0; + // The address the first loadable segment is linked at, rounded down to a page. The load bias of a module + // is where that segment is mapped minus this. + uint64_t linkBase = 0; + std::string interpreter; + // Sorted by address + std::vector symbols; + }; + + // Reads the headers and the symbol tables (.symtab and .dynsym) of a little-endian ELF file + bool ReadElfFile(const std::string& path, ElfInfo& info); + + // The symbol that contains an address of the file, or nullptr + const ElfSymbol* FindElfSymbol(const ElfInfo& info, uint64_t address); +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceengine.cpp b/core/adapters/ptrace/ptraceengine.cpp index 5987d880..283a8300 100644 --- a/core/adapters/ptrace/ptraceengine.cpp +++ b/core/adapters/ptrace/ptraceengine.cpp @@ -22,9 +22,12 @@ limitations under the License. #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -191,15 +194,7 @@ namespace BinaryNinjaDebugger { if (m_done || m_running || it == m_threads.end() || !it->second.stopped) return false; - // The largest register set, the extended state, can be a few kilobytes - std::vector buffer(16384); - iovec vec {buffer.data(), buffer.size()}; - if (ptrace(PTRACE_GETREGSET, tid, (void*)(uintptr_t)regset, &vec) != 0) - return false; - - buffer.resize(vec.iov_len); - data = std::move(buffer); - return true; + return RawGetRegisterSet(tid, regset, data); }); } @@ -211,13 +206,12 @@ namespace BinaryNinjaDebugger { if (m_done || m_running || it == m_threads.end() || !it->second.stopped) return false; - iovec vec {const_cast(data.data()), data.size()}; - return ptrace(PTRACE_SETREGSET, tid, (void*)(uintptr_t)regset, &vec) == 0; + return RawSetRegisterSet(tid, regset, data); }); } - bool PtraceEngine::ReadMemory(uint64_t address, void* buffer, size_t size) + bool PtraceEngine::RawReadMemory(uint64_t address, void* buffer, size_t size) { if (m_memFd < 0 || m_finished || address > INT64_MAX || size > INT64_MAX - address) return false; @@ -236,7 +230,7 @@ namespace BinaryNinjaDebugger { } - bool PtraceEngine::WriteMemory(uint64_t address, const void* buffer, size_t size) + bool PtraceEngine::RawWriteMemory(uint64_t address, const void* buffer, size_t size) { if (m_memFd < 0 || m_finished || address > INT64_MAX || size > INT64_MAX - address) return false; @@ -255,6 +249,154 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::ReadMemory(uint64_t address, void* buffer, size_t size) + { + std::lock_guard lock(m_breakpointMutex); + if (!RawReadMemory(address, buffer, size)) + return false; + + for (const auto& [breakpointAddress, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + + // Show the original bytes wherever the read overlaps a breakpoint + for (size_t i = 0; i < breakpoint.original.size(); i++) + { + uint64_t byteAddress = breakpointAddress + i; + if (byteAddress >= address && byteAddress - address < size) + ((uint8_t*)buffer)[byteAddress - address] = breakpoint.original[i]; + } + } + return true; + } + + + bool PtraceEngine::WriteMemory(uint64_t address, const void* buffer, size_t size) + { + std::lock_guard lock(m_breakpointMutex); + std::vector data((const uint8_t*)buffer, (const uint8_t*)buffer + size); + + // The breakpoint bytes stay in place, and what was written becomes the bytes underneath them + for (auto& [breakpointAddress, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + + for (size_t i = 0; i < breakpoint.original.size(); i++) + { + uint64_t byteAddress = breakpointAddress + i; + if (byteAddress >= address && byteAddress - address < size) + { + breakpoint.original[i] = data[byteAddress - address]; + data[byteAddress - address] = m_arch->breakpointInstruction[i]; + } + } + } + return RawWriteMemory(address, data.data(), size); + } + + + std::vector PtraceEngine::GetMaps() const + { + std::vector maps; + std::ifstream file("/proc/" + std::to_string(m_pid) + "/maps"); + std::string line; + while (std::getline(file, line)) + { + unsigned long long start, end, offset; + char permissions[8] = {}; + int consumed = 0; + if (sscanf(line.c_str(), "%llx-%llx %7s %llx %*s %*s %n", &start, &end, permissions, &offset, &consumed) + < 4) + continue; + + MapEntry entry; + entry.start = start; + entry.end = end; + entry.offset = offset; + entry.read = permissions[0] == 'r'; + entry.write = permissions[1] == 'w'; + entry.execute = permissions[2] == 'x'; + entry.shared = permissions[3] == 's'; + if (consumed > 0 && (size_t)consumed < line.size()) + entry.path = line.substr(consumed); + maps.push_back(entry); + } + return maps; + } + + + bool PtraceEngine::RawGetRegisterSet(pid_t tid, int regset, std::vector& data) + { + // The largest register set, the extended state, can be a few kilobytes + std::vector buffer(16384); + iovec vec {buffer.data(), buffer.size()}; + if (ptrace(PTRACE_GETREGSET, tid, (void*)(uintptr_t)regset, &vec) != 0) + return false; + + buffer.resize(vec.iov_len); + data = std::move(buffer); + return true; + } + + + bool PtraceEngine::RawSetRegisterSet(pid_t tid, int regset, const std::vector& data) + { + iovec vec {const_cast(data.data()), data.size()}; + return ptrace(PTRACE_SETREGSET, tid, (void*)(uintptr_t)regset, &vec) == 0; + } + + + bool PtraceEngine::ReadPc(pid_t tid, uint64_t& pc) + { + auto reg = m_arch ? m_arch->Find(m_arch->pc) : nullptr; + std::vector data; + if (!reg || !RawGetRegisterSet(tid, reg->regset, data) || reg->offset + reg->size > data.size()) + return false; + + pc = 0; + memcpy(&pc, data.data() + reg->offset, std::min(reg->size, sizeof(pc))); + return true; + } + + + bool PtraceEngine::WritePc(pid_t tid, uint64_t pc) + { + auto reg = m_arch ? m_arch->Find(m_arch->pc) : nullptr; + std::vector data; + if (!reg || !RawGetRegisterSet(tid, reg->regset, data) || reg->offset + reg->size > data.size()) + return false; + + memcpy(data.data() + reg->offset, &pc, std::min(reg->size, sizeof(pc))); + return RawSetRegisterSet(tid, reg->regset, data); + } + + + bool PtraceEngine::AddBreakpoint(uint64_t address) + { + return RunOnTracer([this, address] { return DoAddBreakpoint(address); }); + } + + + bool PtraceEngine::RemoveBreakpoint(uint64_t address) + { + return RunOnTracer([this, address] { return DoRemoveBreakpoint(address); }); + } + + + bool PtraceEngine::AddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size) + { + return RunOnTracer([this, address, type, size] { return DoAddHardwareBreakpoint(address, type, size); }); + } + + + bool PtraceEngine::RemoveHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size) + { + return RunOnTracer([this, address, type, size] { return DoRemoveHardwareBreakpoint(address, type, size); }); + } + + std::vector PtraceEngine::GetThreads() const { std::lock_guard lock(m_infoMutex); @@ -272,6 +414,15 @@ namespace BinaryNinjaDebugger { } + void PtraceEngine::PostTask(std::function task) + { + Event event; + event.type = TaskEvent; + event.task = std::move(task); + PushEvent(event); + } + + void PtraceEngine::Publish() { std::lock_guard lock(m_infoMutex); @@ -306,7 +457,10 @@ namespace BinaryNinjaDebugger { event = std::move(m_events.front()); m_events.pop_front(); } - m_handler(event); + if (event.type == TaskEvent) + event.task(); + else + m_handler(event); } } @@ -436,6 +590,9 @@ namespace BinaryNinjaDebugger { m_pid = pid; m_memFd = open(("/proc/" + std::to_string(pid) + "/mem").c_str(), O_RDWR | O_CLOEXEC); + m_arch = m_options.arch ? m_options.arch : DetectPtraceArch(pid); + if (m_arch && m_arch->hwDebug) + m_hardwareSlots.resize(m_arch->hwDebug->SlotCount()); ThreadInfo info; info.stopped = true; m_threads[pid] = info; @@ -537,11 +694,92 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::HasBreakpointAt(uint64_t address) + { + { + std::lock_guard lock(m_breakpointMutex); + auto it = m_breakpoints.find(address); + if (it != m_breakpoints.end() && it->second.inserted) + return true; + } + + for (const auto& slot : m_hardwareSlots) + { + if (slot.used && slot.type == PtraceHwType::Execute && slot.address == address) + return true; + } + return false; + } + + + // Works out why a thread stopped with SIGTRAP. Returns false if the stop is not worth reporting. + bool PtraceEngine::ClassifyTrap(pid_t tid, ThreadInfo& info, Classified& result) + { + siginfo_t signalInfo {}; + bool haveInfo = ptrace(PTRACE_GETSIGINFO, tid, nullptr, &signalInfo) == 0; + int code = haveInfo ? signalInfo.si_code : 0; + + if (code == TRAP_HWBKPT) + { + if (m_arch && m_arch->hwDebug) + m_arch->hwDebug->OnTrap(tid); + result.hardware = true; + return true; + } + + if (code == TRAP_TRACE) + { + result.stepTrap = true; + return true; + } + + uint64_t pc = 0; + if (m_arch && !m_arch->breakpointInstruction.empty() && ReadPc(tid, pc)) + { + uint64_t address = pc - m_arch->breakpointPcAdjust; + bool ours; + { + std::lock_guard lock(m_breakpointMutex); + auto it = m_breakpoints.find(address); + ours = it != m_breakpoints.end() && it->second.inserted; + } + bool removed = !ours && m_recentlyRemoved.count(address); + + if (ours || removed) + { + if (m_arch->breakpointPcAdjust) + WritePc(tid, address); + // A thread that trapped on a breakpoint that has just been removed only needs to run again + if (removed) + return false; + + result.breakpoint = true; + return true; + } + } + + // Stepping over a system call traps like a breakpoint on x86, so this is a step if we asked for one + if (info.stepping) + result.stepTrap = true; + return true; + } + + PtraceEngine::Classified PtraceEngine::Classify(pid_t tid, int status) { Classified result; + + // The breakpoint that a thread is stepping over goes back once the thread reports a stop, but not while it is + // only passing through an internal one + auto endGuard = [this, tid](bool threadAlive) { + auto it = m_threads.find(tid); + if (it != m_threads.end() && (it->second.guardSoftware || !it->second.guardSlots.empty())) + EndGuard(tid, threadAlive); + }; + if (!WIFSTOPPED(status)) { + endGuard(false); m_threads.erase(tid); Publish(); result.kind = StopKind::Gone; @@ -573,6 +811,7 @@ namespace BinaryNinjaDebugger { if (info.awaitingInitialStop) { info.awaitingInitialStop = false; + ApplyHardwareToThread(tid); return result; } if (info.expectedStops > 0) @@ -582,6 +821,7 @@ namespace BinaryNinjaDebugger { } if (m_interruptRequested.exchange(false)) { + endGuard(true); result.kind = StopKind::Report; result.interrupted = true; return result; @@ -594,8 +834,17 @@ namespace BinaryNinjaDebugger { return result; } - if (signal != SIGTRAP) + if (signal == SIGTRAP) + { + if (!ClassifyTrap(tid, info, result)) + return result; + } + else + { info.pendingSignal = signal; + } + + endGuard(true); result.kind = StopKind::Report; result.signal = signal; return result; @@ -613,21 +862,158 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::NeedsStepOver(pid_t tid, const ThreadInfo& info) + { + uint64_t pc; + return info.atReportedStop && ReadPc(tid, pc) && pc == info.reportedPc + && (info.hardwareBeforeAccess || HasBreakpointAt(pc)); + } + + + // Lifts the breakpoints at an address, so that a thread can execute the instruction there + void PtraceEngine::BeginGuard(pid_t tid, uint64_t address) + { + auto& info = m_threads[tid]; + info.guardAddress = address; + + { + std::lock_guard lock(m_breakpointMutex); + auto it = m_breakpoints.find(address); + if (it != m_breakpoints.end() && it->second.inserted) + { + RawWriteMemory(address, it->second.original.data(), it->second.original.size()); + it->second.inserted = false; + info.guardSoftware = true; + } + } + + // A watchpoint that reports before the access has to be lifted altogether, since we do not know which one it + // was + for (size_t i = 0; i < m_hardwareSlots.size(); i++) + { + const auto& slot = m_hardwareSlots[i]; + if (slot.used + && (info.hardwareBeforeAccess || (slot.type == PtraceHwType::Execute && slot.address == address))) + { + m_arch->hwDebug->Clear(tid, i); + info.guardSlots.push_back(i); + } + } + } + + + void PtraceEngine::EndGuard(pid_t tid, bool threadAlive) + { + auto& info = m_threads[tid]; + if (info.guardSoftware) + { + info.guardSoftware = false; + std::lock_guard lock(m_breakpointMutex); + auto it = m_breakpoints.find(info.guardAddress); + if (it != m_breakpoints.end() && !it->second.inserted) + { + RawWriteMemory( + info.guardAddress, m_arch->breakpointInstruction.data(), m_arch->breakpointInstruction.size()); + it->second.inserted = true; + } + } + + info.hardwareBeforeAccess = false; + auto slots = std::move(info.guardSlots); + info.guardSlots.clear(); + for (size_t index : slots) + { + const auto& slot = m_hardwareSlots[index]; + if (threadAlive && slot.used) + m_arch->hwDebug->Set(tid, index, slot.address, slot.type, slot.size); + } + } + + + bool PtraceEngine::ResumeAll() + { + bool resumed = false; + for (auto& [id, info] : m_threads) + { + if (!info.stopped) + continue; + + info.stepping = false; + resumed |= ResumeThread(id); + } + return resumed; + } + + + // Runs one thread past a breakpoint while all the others stay stopped, and then lets everything run + bool PtraceEngine::StartNextStepOver() + { + while (!m_stepOverQueue.empty()) + { + pid_t tid = m_stepOverQueue.front(); + m_stepOverQueue.erase(m_stepOverQueue.begin()); + + auto it = m_threads.find(tid); + uint64_t pc; + if (it == m_threads.end() || !it->second.stopped || !ReadPc(tid, pc)) + continue; + + BeginGuard(tid, pc); + it->second.stepping = true; + m_stepOverTid = tid; + return ResumeThread(tid); + } + + m_stepOverTid = -1; + return ResumeAll(); + } + + + void PtraceEngine::ApplyHardwareToThread(pid_t tid) + { + for (size_t i = 0; i < m_hardwareSlots.size(); i++) + { + const auto& slot = m_hardwareSlots[i]; + if (slot.used) + m_arch->hwDebug->Set(tid, i, slot.address, slot.type, slot.size); + } + } + + void PtraceEngine::HandleStatus(pid_t tid, int status) { auto stop = Classify(tid, status); + bool steppingOver = tid == m_stepOverTid; switch (stop.kind) { case StopKind::Gone: + if (steppingOver && !m_done) + { + m_stepOverTid = -1; + StartNextStepOver(); + } break; case StopKind::Internal: { auto it = m_threads.find(tid); - if (it != m_threads.end() && it->second.stopped && (m_continueMode || it->second.stepping)) + if (it != m_threads.end() && it->second.stopped + && ((m_continueMode && m_stepOverTid < 0) || it->second.stepping)) ResumeThread(tid); break; } case StopKind::Report: + if (steppingOver && stop.stepTrap) + { + m_threads[tid].stepping = false; + m_stepOverTid = -1; + StartNextStepOver(); + break; + } + if (steppingOver) + { + m_stepOverTid = -1; + m_stepOverQueue.clear(); + } StopAll(); if (!m_done) FinishStop(tid, stop); @@ -679,10 +1065,21 @@ namespace BinaryNinjaDebugger { event.tid = tid; event.signal = stop.signal; event.interrupted = stop.interrupted; + event.breakpoint = stop.breakpoint; + event.hardware = stop.hardware; event.singleStep = m_threads[tid].stepping; for (auto& [id, info] : m_threads) info.stepping = false; + + // Once everything is stopped, no thread can still trap on a breakpoint that was removed + m_recentlyRemoved.clear(); + + auto& info = m_threads[tid]; + info.atReportedStop = ReadPc(tid, info.reportedPc); + info.hardwareBeforeAccess = + stop.hardware && m_arch && m_arch->hwDebug && m_arch->hwDebug->DataTrapsBeforeAccess(); + m_running = false; Publish(); PushEvent(event); @@ -712,18 +1109,41 @@ namespace BinaryNinjaDebugger { { if (m_done || m_running) return false; - if (step && m_threads.find(tid) == m_threads.end()) + + auto stepping = m_threads.find(tid); + if (step && (stepping == m_threads.end() || !stepping->second.stopped)) return false; m_continueMode = !step; - bool resumed = false; + std::vector stepOver; for (auto& [id, info] : m_threads) { if (!info.stopped || (step && id != tid)) continue; - info.stepping = step; - resumed |= ResumeThread(id); + if (NeedsStepOver(id, info)) + stepOver.push_back(id); + info.atReportedStop = false; + } + + bool resumed; + if (step) + { + uint64_t pc; + if (!stepOver.empty() && ReadPc(tid, pc)) + BeginGuard(tid, pc); + + stepping->second.stepping = true; + resumed = ResumeThread(tid); + } + else if (!stepOver.empty()) + { + m_stepOverQueue = stepOver; + resumed = StartNextStepOver(); + } + else + { + resumed = ResumeAll(); } m_running = resumed; @@ -732,6 +1152,139 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::DoAddBreakpoint(uint64_t address) + { + if (m_done || !m_arch || m_arch->breakpointInstruction.empty()) + return false; + + std::lock_guard lock(m_breakpointMutex); + if (m_breakpoints.count(address)) + return true; + + const auto& instruction = m_arch->breakpointInstruction; + Breakpoint breakpoint; + breakpoint.original.resize(instruction.size()); + if (!RawReadMemory(address, breakpoint.original.data(), instruction.size()) + || !RawWriteMemory(address, instruction.data(), instruction.size())) + return false; + + breakpoint.inserted = true; + m_breakpoints[address] = std::move(breakpoint); + return true; + } + + + bool PtraceEngine::DoRemoveBreakpoint(uint64_t address) + { + std::lock_guard lock(m_breakpointMutex); + auto it = m_breakpoints.find(address); + if (it == m_breakpoints.end()) + return false; + + if (it->second.inserted && !m_done) + RawWriteMemory(address, it->second.original.data(), it->second.original.size()); + m_breakpoints.erase(it); + + // A thread that is running may just have trapped on it + if (m_running) + m_recentlyRemoved.insert(address); + return true; + } + + + bool PtraceEngine::DoAddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size) + { + if (m_done || m_running || !m_arch || !m_arch->hwDebug) + return false; + + for (const auto& slot : m_hardwareSlots) + { + if (slot.used && slot.address == address && slot.type == type && slot.size == size) + return true; + } + + size_t index = 0; + while (index < m_hardwareSlots.size() + && (m_hardwareSlots[index].used || !m_arch->hwDebug->SlotSupports(index, type))) + index++; + if (index == m_hardwareSlots.size()) + return false; + + std::vector programmed; + for (const auto& [tid, info] : m_threads) + { + if (!info.stopped) + continue; + if (!m_arch->hwDebug->Set(tid, index, address, type, size)) + { + for (pid_t done : programmed) + m_arch->hwDebug->Clear(done, index); + return false; + } + programmed.push_back(tid); + } + + m_hardwareSlots[index] = {true, address, type, size}; + return true; + } + + + bool PtraceEngine::DoRemoveHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size) + { + if (m_done || m_running || !m_arch || !m_arch->hwDebug) + return false; + + for (size_t index = 0; index < m_hardwareSlots.size(); index++) + { + auto& slot = m_hardwareSlots[index]; + if (!slot.used || slot.address != address || slot.type != type || slot.size != size) + continue; + + for (const auto& [tid, info] : m_threads) + { + if (info.stopped) + m_arch->hwDebug->Clear(tid, index); + } + slot.used = false; + return true; + } + return false; + } + + + // Puts the target back the way it was before we let go of it + void PtraceEngine::RemoveAllBreakpoints() + { + for (auto& [tid, info] : m_threads) + { + if (info.guardSoftware || !info.guardSlots.empty()) + EndGuard(tid, true); + } + + { + std::lock_guard lock(m_breakpointMutex); + for (auto& [address, breakpoint] : m_breakpoints) + { + if (breakpoint.inserted) + RawWriteMemory(address, breakpoint.original.data(), breakpoint.original.size()); + } + m_breakpoints.clear(); + } + + for (size_t index = 0; index < m_hardwareSlots.size(); index++) + { + if (!m_hardwareSlots[index].used) + continue; + + for (const auto& [tid, info] : m_threads) + m_arch->hwDebug->Clear(tid, index); + m_hardwareSlots[index].used = false; + } + m_stepOverQueue.clear(); + m_stepOverTid = -1; + } + + bool PtraceEngine::DoKill() { if (m_done) @@ -808,6 +1361,7 @@ namespace BinaryNinjaDebugger { return false; } + RemoveAllBreakpoints(); for (const auto& [tid, info] : m_threads) ptrace(PTRACE_DETACH, tid, nullptr, (void*)(intptr_t)info.pendingSignal); diff --git a/core/adapters/ptrace/ptraceengine.h b/core/adapters/ptrace/ptraceengine.h index 65422c78..68615ead 100644 --- a/core/adapters/ptrace/ptraceengine.h +++ b/core/adapters/ptrace/ptraceengine.h @@ -24,9 +24,11 @@ limitations under the License. #include #include #include +#include #include #include #include +#include "ptracearch.h" namespace BinaryNinjaDebugger { // Owns a single ptrace session. Linux only requires that every ptrace request and wait comes from the thread that @@ -40,7 +42,9 @@ namespace BinaryNinjaDebugger { StoppedEvent, ExitedEvent, DetachedEvent, - OutputEvent + OutputEvent, + // Not from the target. See PostTask. + TaskEvent }; struct Event @@ -52,7 +56,22 @@ namespace BinaryNinjaDebugger { int exitCode = 0; bool singleStep = false; bool interrupted = false; + bool breakpoint = false; + bool hardware = false; std::string data; + std::function task; + }; + + struct MapEntry + { + uint64_t start = 0; + uint64_t end = 0; + bool read = false; + bool write = false; + bool execute = false; + bool shared = false; + uint64_t offset = 0; + std::string path; }; struct LaunchOptions @@ -62,6 +81,8 @@ namespace BinaryNinjaDebugger { std::string workingDir; bool disableAslr = true; bool usePty = true; + // Overrides the architecture that is detected from the target + const PtraceArch* arch = nullptr; }; using EventHandler = std::function; @@ -75,6 +96,28 @@ namespace BinaryNinjaDebugger { // SIGSTOPs we sent that have not been consumed yet int expectedStops = 0; int pendingSignal = 0; + // Set for the thread whose stop was reported, so that resuming it steps over a breakpoint at its PC + bool atReportedStop = false; + uint64_t reportedPc = 0; + // The breakpoint that is lifted while the thread steps over it + bool guardSoftware = false; + std::vector guardSlots; + uint64_t guardAddress = 0; + bool hardwareBeforeAccess = false; + }; + + struct Breakpoint + { + std::vector original; + bool inserted = false; + }; + + struct HardwareSlot + { + bool used = false; + uint64_t address = 0; + PtraceHwType type = PtraceHwType::Execute; + size_t size = 0; }; enum class StopKind @@ -89,6 +132,9 @@ namespace BinaryNinjaDebugger { StopKind kind = StopKind::Internal; int signal = 0; bool interrupted = false; + bool breakpoint = false; + bool hardware = false; + bool stepTrap = false; }; EventHandler m_handler; @@ -115,6 +161,14 @@ namespace BinaryNinjaDebugger { bool m_running = false; bool m_continueMode = false; bool m_done = false; + std::vector m_hardwareSlots; + std::set m_recentlyRemoved; + std::vector m_stepOverQueue; + pid_t m_stepOverTid = -1; + + const PtraceArch* m_arch = nullptr; + std::mutex m_breakpointMutex; + std::map m_breakpoints; mutable std::mutex m_infoMutex; std::vector m_publishedThreads; @@ -141,6 +195,21 @@ namespace BinaryNinjaDebugger { void HandleStatus(pid_t tid, int status); Classified Classify(pid_t tid, int status); bool ResumeThread(pid_t tid); + bool ClassifyTrap(pid_t tid, ThreadInfo& info, Classified& result); + bool RawGetRegisterSet(pid_t tid, int regset, std::vector& data); + bool RawSetRegisterSet(pid_t tid, int regset, const std::vector& data); + bool ReadPc(pid_t tid, uint64_t& pc); + bool WritePc(pid_t tid, uint64_t pc); + bool RawReadMemory(uint64_t address, void* buffer, size_t size); + bool RawWriteMemory(uint64_t address, const void* buffer, size_t size); + bool HasBreakpointAt(uint64_t address); + bool NeedsStepOver(pid_t tid, const ThreadInfo& info); + void BeginGuard(pid_t tid, uint64_t address); + void EndGuard(pid_t tid, bool threadAlive); + bool StartNextStepOver(); + bool ResumeAll(); + void ApplyHardwareToThread(pid_t tid); + void RemoveAllBreakpoints(); void StopAll(); void FinishStop(pid_t tid, const Classified& stop); void FinishExit(int status); @@ -148,6 +217,10 @@ namespace BinaryNinjaDebugger { bool DoResume(bool step, pid_t tid); bool DoKill(); bool DoDetach(); + bool DoAddBreakpoint(uint64_t address); + bool DoRemoveBreakpoint(uint64_t address); + bool DoAddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); + bool DoRemoveHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); public: explicit PtraceEngine(EventHandler handler); @@ -162,10 +235,24 @@ namespace BinaryNinjaDebugger { bool Detach(); bool WriteInput(const std::string& data); + // Runs a function on the thread that delivers the events, after everything that was posted before it. That + // thread is not tied up by the caller, so it is the place for work that must not run under the caller's locks. + void PostTask(std::function task); + // Raw register sets, as PTRACE_GETREGSET and PTRACE_SETREGSET see them. The thread must be stopped. bool GetRegisterSet(uint32_t tid, int regset, std::vector& data); bool SetRegisterSet(uint32_t tid, int regset, const std::vector& data); + // Software breakpoints are inserted straight into the target. ReadMemory and WriteMemory hide them. + bool AddBreakpoint(uint64_t address); + bool RemoveBreakpoint(uint64_t address); + // The target must be stopped + bool AddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); + bool RemoveHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); + + const PtraceArch* GetArch() const { return m_arch; } + std::vector GetMaps() const; + // All or nothing bool ReadMemory(uint64_t address, void* buffer, size_t size); bool WriteMemory(uint64_t address, const void* buffer, size_t size); diff --git a/core/adapters/ptrace/ptracemodule.cpp b/core/adapters/ptrace/ptracemodule.cpp new file mode 100644 index 00000000..e89315fe --- /dev/null +++ b/core/adapters/ptrace/ptracemodule.cpp @@ -0,0 +1,168 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptracemodule.h" +#include +#include +#include +#include + +namespace BinaryNinjaDebugger { + + // The segments of a module sit right next to each other, apart from the gaps that the loader leaves in between + static constexpr uint64_t ModuleSegmentGapLimit = 0x4000000; + + + std::vector BuildModules( + const std::vector& maps, const std::function& isElf) + { + auto sorted = maps; + std::sort(sorted.begin(), sorted.end(), [](const PtraceEngine::MapEntry& a, const PtraceEngine::MapEntry& b) { + return a.start < b.start; + }); + + std::vector modules; + // The module of each path that is still being extended + std::map open; + + for (size_t i = 0; i < sorted.size(); i++) + { + const auto& map = sorted[i]; + if (map.path.empty() || map.path[0] != '/') + continue; + + auto it = open.find(map.path); + if (it != open.end()) + { + auto& module = modules[it->second]; + uint64_t moduleEnd = module.base + module.size; + if (map.start >= moduleEnd && map.start - moduleEnd <= ModuleSegmentGapLimit) + { + module.size = map.end - module.base; + continue; + } + } + + // A module begins where its file is mapped from the start + if (map.offset != 0 || !isElf(map.start)) + continue; + + PtraceModuleInfo module; + module.path = map.path; + module.base = map.start; + module.size = map.end - map.start; + open[map.path] = modules.size(); + modules.push_back(module); + } + + // The zero-filled memory that follows the last segment belongs to the module as well + for (auto& module : modules) + { + for (const auto& map : sorted) + { + if (map.start == module.base + module.size && map.path.empty()) + { + module.size = map.end - module.base; + break; + } + } + } + + std::map seen; + for (auto& module : modules) + { + module.shortName = std::filesystem::path(module.path).filename().string(); + int count = seen[module.shortName]++; + if (count > 0) + module.shortName += "-" + std::to_string(count); + } + return modules; + } + + + std::vector UnwindFramePointers(uint64_t pc, uint64_t sp, uint64_t fp, size_t wordSize, + const std::function& readWord, const std::function& isExecutable, + size_t maxFrames) + { + std::vector frames; + frames.push_back({pc, sp, fp}); + + while (frames.size() < maxFrames) + { + const auto current = frames.back(); + // The stack grows down, so a frame pointer is never below the stack pointer + if (current.fp == 0 || current.fp % wordSize != 0 || current.fp < current.sp) + break; + + uint64_t callerFp, returnAddress; + if (!readWord(current.fp, callerFp) || !readWord(current.fp + wordSize, returnAddress)) + break; + if (returnAddress == 0 || !isExecutable(returnAddress)) + break; + // The caller's frame is further up the stack + if (callerFp != 0 && callerFp <= current.fp) + break; + + frames.push_back({returnAddress, current.fp + 2 * wordSize, callerFp}); + } + return frames; + } + + + static std::string ReadSmallFile(const std::filesystem::path& path) + { + std::ifstream file(path, std::ios::binary); + std::string contents((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + return contents; + } + + + std::vector ListProcesses() + { + std::vector processes; + std::error_code error; + for (const auto& entry : std::filesystem::directory_iterator("/proc", error)) + { + std::string name = entry.path().filename().string(); + if (name.empty() || !std::all_of(name.begin(), name.end(), [](char c) { return c >= '0' && c <= '9'; })) + continue; + + PtraceProcessInfo process; + process.pid = std::stoul(name); + process.name = ReadSmallFile(entry.path() / "comm"); + while (!process.name.empty() && process.name.back() == '\n') + process.name.pop_back(); + + // The arguments are separated by null characters + std::string commandLine = ReadSmallFile(entry.path() / "cmdline"); + std::replace(commandLine.begin(), commandLine.end(), '\0', ' '); + while (!commandLine.empty() && commandLine.back() == ' ') + commandLine.pop_back(); + process.commandLine = commandLine; + + // The process may have gone away since it was listed + if (process.name.empty()) + continue; + processes.push_back(std::move(process)); + } + + std::sort(processes.begin(), processes.end(), [](const PtraceProcessInfo& a, const PtraceProcessInfo& b) { + return a.pid < b.pid; + }); + return processes; + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracemodule.h b/core/adapters/ptrace/ptracemodule.h new file mode 100644 index 00000000..62408214 --- /dev/null +++ b/core/adapters/ptrace/ptracemodule.h @@ -0,0 +1,61 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include +#include +#include "ptraceengine.h" + +namespace BinaryNinjaDebugger { + struct PtraceModuleInfo + { + std::string path; + // The base name, made unique if two modules have the same one + std::string shortName; + uint64_t base = 0; + uint64_t size = 0; + }; + + // Groups the file mappings of a process into the modules that they belong to. `isElf` tells whether the file + // mapped at an address is an ELF object, which leaves out the data files that are mapped too. + std::vector BuildModules( + const std::vector& maps, const std::function& isElf); + + struct PtraceFrameRecord + { + uint64_t pc = 0; + uint64_t sp = 0; + uint64_t fp = 0; + }; + + // Follows the chain of saved frame pointers. Every frame is expected to keep the caller's frame pointer and its + // return address next to each other, where its own frame pointer points. It stops at the first frame that does not + // look right, so code that does not keep frame pointers ends the trace early. + std::vector UnwindFramePointers(uint64_t pc, uint64_t sp, uint64_t fp, size_t wordSize, + const std::function& readWord, const std::function& isExecutable, + size_t maxFrames = 256); + + struct PtraceProcessInfo + { + uint32_t pid = 0; + std::string name; + std::string commandLine; + }; + + std::vector ListProcesses(); +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracestep.cpp b/core/adapters/ptrace/ptracestep.cpp new file mode 100644 index 00000000..7de0fc3d --- /dev/null +++ b/core/adapters/ptrace/ptracestep.cpp @@ -0,0 +1,172 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptracestep.h" +#include + +namespace BinaryNinjaDebugger { + + PtraceStepper::PtraceStepper(PtraceEngine& engine, BreakpointFunction acquire, BreakpointFunction release) : + m_engine(engine), m_acquire(std::move(acquire)), m_release(std::move(release)) + {} + + + void PtraceStepper::ReleaseAll() + { + for (uint64_t address : m_addresses) + m_release(address); + m_addresses.clear(); + m_mode = Mode::None; + } + + + bool PtraceStepper::IsActive() + { + std::lock_guard lock(m_mutex); + return m_mode != Mode::None; + } + + + void PtraceStepper::Cancel() + { + std::lock_guard lock(m_mutex); + ReleaseAll(); + } + + + bool PtraceStepper::StepOver(uint32_t tid, uint64_t pc, uint64_t sp, size_t callLength, size_t wordSize) + { + std::lock_guard lock(m_mutex); + ReleaseAll(); + if (callLength == 0) + return m_engine.Resume(true, tid); + + uint64_t address = pc + callLength; + if (!m_acquire(address)) + return false; + + m_addresses.insert(address); + m_mode = Mode::ReturnAddress; + m_tid = tid; + // A call that goes to the next instruction leaves its return address on the stack, so allow for it + m_minSp = sp - wordSize; + if (m_engine.Resume(false, 0)) + return true; + + ReleaseAll(); + return false; + } + + + bool PtraceStepper::StepReturn(uint32_t tid, uint64_t pc, uint64_t minSp, const std::vector& returnSites, + uint64_t returnAddress, uint64_t returnSp) + { + std::lock_guard lock(m_mutex); + ReleaseAll(); + + // Already at the instruction that returns, so the return is the next step + if (std::find(returnSites.begin(), returnSites.end(), pc) != returnSites.end()) + { + m_mode = Mode::FinalStep; + m_tid = tid; + if (m_engine.Resume(true, tid)) + return true; + + m_mode = Mode::None; + return false; + } + + for (uint64_t site : returnSites) + { + if (!m_addresses.count(site) && m_acquire(site)) + m_addresses.insert(site); + } + + if (!m_addresses.empty()) + { + m_mode = Mode::ReturnSites; + m_minSp = minSp; + } + else if (returnAddress != 0 && m_acquire(returnAddress)) + { + m_addresses.insert(returnAddress); + m_mode = Mode::ReturnAddress; + m_minSp = returnSp; + } + else + { + return false; + } + + m_tid = tid; + if (m_engine.Resume(false, 0)) + return true; + + ReleaseAll(); + return false; + } + + + PtraceStepper::Result PtraceStepper::OnStop( + const PtraceEngine::Event& event, uint64_t pc, uint64_t sp, bool userBreakpoint) + { + std::lock_guard lock(m_mutex); + if (m_mode == Mode::None) + return Result::Ignored; + + if (m_mode == Mode::FinalStep) + { + bool stepped = event.tid == m_tid && event.singleStep && !event.breakpoint; + m_mode = Mode::None; + return stepped ? Result::Finished : Result::Ignored; + } + + // Whatever else stops the target ends the step. That includes a breakpoint of the user, even at one of our + // addresses. + bool atOurs = event.breakpoint && m_addresses.count(pc); + if (!atOurs || userBreakpoint) + { + ReleaseAll(); + return Result::Ignored; + } + + if (event.tid != m_tid || sp < m_minSp) + { + // Another thread, or a deeper frame. It is not ours, so it goes on. + if (m_engine.Resume(false, 0)) + return Result::Consumed; + + ReleaseAll(); + return Result::Ignored; + } + + if (m_mode == Mode::ReturnAddress) + { + ReleaseAll(); + return Result::Finished; + } + + // At an instruction that returns: it takes one step to be out + ReleaseAll(); + m_mode = Mode::FinalStep; + if (m_engine.Resume(true, m_tid)) + return Result::Consumed; + + m_mode = Mode::None; + return Result::Ignored; + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracestep.h b/core/adapters/ptrace/ptracestep.h new file mode 100644 index 00000000..f9413e93 --- /dev/null +++ b/core/adapters/ptrace/ptracestep.h @@ -0,0 +1,89 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include +#include +#include +#include "ptraceengine.h" + +namespace BinaryNinjaDebugger { + // Steps over a call and out of a function. Both let the target run until it reaches an address of ours, and a stop + // there only counts if it is the same thread in the same frame: other threads run through the same code, and a + // recursive function comes back to the same address from deeper frames. Any other stop ends the step and is + // left to the caller to report. + class PtraceStepper + { + enum class Mode + { + None, + // Run to an address that the function returns to + ReturnAddress, + // Run to the instructions that return from the function, and then step once more to do the return + ReturnSites, + FinalStep + }; + + using BreakpointFunction = std::function; + + PtraceEngine& m_engine; + BreakpointFunction m_acquire; + BreakpointFunction m_release; + + std::mutex m_mutex; + Mode m_mode = Mode::None; + uint32_t m_tid = 0; + uint64_t m_minSp = 0; + std::set m_addresses; + + void ReleaseAll(); + + public: + enum class Result + { + // No step is going on, or it has been called off. The stop is for the caller to deal with. + Ignored, + // The stop was part of the step, which goes on + Consumed, + // The step is done, and this stop is where it ended + Finished + }; + + // `acquire` and `release` place and remove the breakpoints of a step. They may be shared with other users of + // the same address, and are called once per address. + PtraceStepper(PtraceEngine& engine, BreakpointFunction acquire, BreakpointFunction release); + + // Runs the call at `pc` to its end. `callLength` is zero if the instruction is not a call, and that is + // only a single step. + bool StepOver(uint32_t tid, uint64_t pc, uint64_t sp, size_t callLength, size_t wordSize); + + // Runs until the function that the thread is in returns. `returnSites` are the instructions that do it, and a + // stop at one only counts if the stack pointer is at least `minSp`, which is what tells the function apart from + // the calls that it makes to itself. What a return leaves the stack pointer at depends on the ABI, so the + // caller works it out. If there are no return sites, `returnAddress` is where the function returns to, and + // `returnSp` the stack pointer that the caller has once it is back. + bool StepReturn(uint32_t tid, uint64_t pc, uint64_t minSp, const std::vector& returnSites, + uint64_t returnAddress, uint64_t returnSp); + + // Call for every stop of the target. `userBreakpoint` tells whether there is a breakpoint of the user at `pc`. + Result OnStop(const PtraceEngine::Event& event, uint64_t pc, uint64_t sp, bool userBreakpoint); + + bool IsActive(); + void Cancel(); + }; +} // namespace BinaryNinjaDebugger From 9a36fc9c4cba68092debbe1d4b857bca9d718829 Mon Sep 17 00:00:00 2001 From: Bradley Fernandez Date: Thu, 5 Nov 2026 13:16:05 -0500 Subject: [PATCH 3/6] Support attach, fork/exec, Linux signals and syscall tracing Attach to running processes, apply ordered descriptor redirects, initialize the terminal and reap detached launch targets. Release fork/vfork children safely and reconcile target state, symbols and breakpoints across exec. Handle Linux signal stops and target-generated traps, optionally stop at signal handlers, and preserve stopped state on failed operations. Expose syscall tracing/emulation, console commands and adapter properties; derive register aliases from the Binary Ninja architecture. --- core/CMakeLists.txt | 4 + core/adapters/ptrace/ptraceadapter.cpp | 983 +++++++++++++++++-- core/adapters/ptrace/ptraceadapter.h | 43 +- core/adapters/ptrace/ptracearch.cpp | 78 +- core/adapters/ptrace/ptracearch.h | 28 + core/adapters/ptrace/ptraceelf.cpp | 26 + core/adapters/ptrace/ptraceelf.h | 4 + core/adapters/ptrace/ptraceengine.cpp | 1226 ++++++++++++++++++++++-- core/adapters/ptrace/ptraceengine.h | 172 +++- core/adapters/ptrace/ptracesignal.cpp | 92 ++ core/adapters/ptrace/ptracesignal.h | 25 + core/adapters/ptrace/ptracesyscall.cpp | 320 +++++++ core/adapters/ptrace/ptracesyscall.h | 36 + 13 files changed, 2878 insertions(+), 159 deletions(-) create mode 100644 core/adapters/ptrace/ptracesignal.cpp create mode 100644 core/adapters/ptrace/ptracesignal.h create mode 100644 core/adapters/ptrace/ptracesyscall.cpp create mode 100644 core/adapters/ptrace/ptracesyscall.h diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 8fcc41e0..e05b1ac6 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -71,8 +71,12 @@ else() adapters/ptrace/ptraceengine.h adapters/ptrace/ptracemodule.cpp adapters/ptrace/ptracemodule.h + adapters/ptrace/ptracesignal.cpp + adapters/ptrace/ptracesignal.h adapters/ptrace/ptracestep.cpp adapters/ptrace/ptracestep.h + adapters/ptrace/ptracesyscall.cpp + adapters/ptrace/ptracesyscall.h ) endif() endif() diff --git a/core/adapters/ptrace/ptraceadapter.cpp b/core/adapters/ptrace/ptraceadapter.cpp index 56f8432a..4eff0ebb 100644 --- a/core/adapters/ptrace/ptraceadapter.cpp +++ b/core/adapters/ptrace/ptraceadapter.cpp @@ -21,8 +21,11 @@ limitations under the License. #include #include #include +#include #include "ptraceadapter.h" +#include "ptracesignal.h" #include "lowlevelilinstruction.h" +#include "../../debuggercontroller.h" namespace BinaryNinjaDebugger { @@ -131,11 +134,19 @@ namespace BinaryNinjaDebugger { { if (event.interrupted) return UnknownReason; + // ExcSyscall is the closest reason there is. It is the one of the Mach exception for a system call. + if (event.syscall) + return ExcSyscall; + // Stopped at the handler of a signal, so it is the signal that is the reason + if (event.signalHandler) + return StopReasonFromLinuxSignal(event.signalHandler); + if (event.trapOrigin == PtraceEngine::TrapOrigin::Target) + return StopReasonFromLinuxSignal(event.signal); if (event.breakpoint || event.hardware) return Breakpoint; if (event.signal == SIGTRAP) return event.singleStep ? SingleStep : Breakpoint; - return SignalToDebugStopReason(event.signal); + return StopReasonFromLinuxSignal(event.signal); } @@ -245,26 +256,46 @@ namespace BinaryNinjaDebugger { options.workingDir = workingDirectory; options.disableAslr = disableAslr; + scope = SettingsResourceScope; + for (const auto& text : adapterSettings->Get>("launch.redirectFileDescriptors", data, &scope)) + { + if (text.empty()) + continue; + + PtraceEngine::FdRedirect redirect; + std::string parseError; + if (!ParseFdRedirect(text, redirect, parseError)) + return launchFailure(parseError); + options.redirects.push_back(std::move(redirect)); + } + + CreateEngine(false); + std::string error; + if (!m_engine->Launch(options, error)) + { + m_targetActive = false; + return launchFailure(error); + } + return true; + } + + + void PtraceAdapter::CreateEngine(bool attached) + { m_stepper.reset(); m_engine.reset(); ResetTargetState(); + m_attached = attached; m_stopAtSystemEntry = Settings::Instance()->Get("debugger.stopAtSystemEntryPoint"); m_firstStop = true; m_targetActive = true; m_engine = std::make_unique([this](const PtraceEngine::Event& event) { HandleEngineEvent(event); }); + SyncEngineSettings(); m_stepper = std::make_unique( *m_engine, [this](uint64_t address) { return AcquireBreakpoint(address); }, [this](uint64_t address) { return ReleaseBreakpoint(address); }); - - std::string error; - if (!m_engine->Launch(options, error)) - { - m_targetActive = false; - return launchFailure(error); - } - return true; } @@ -277,17 +308,26 @@ namespace BinaryNinjaDebugger { m_stopGeneration++; m_activeThreadId = event.tid; m_lastStopReason = StopReasonFromEvent(event); + if (event.exec) + { + HandleExec(event); + break; + } if (m_firstStop) { m_firstStop = false; m_arch = m_engine->GetArch(); + BuildRegisterList(); if (!m_arch) LogWarn("PtraceAdapter: unsupported target architecture"); - if (Settings::Instance()->Get("debugger.stopAtEntryPoint") && m_hasEntryFunction) + // An attached target is long past its entry point, and it stops where it is + if (!m_attached && Settings::Instance()->Get("debugger.stopAtEntryPoint") && m_hasEntryFunction) AddBreakpoint(ModuleNameAndOffset(m_inputFile, m_entryPoint - m_start), 0); SetUpLoaderBreakpoint(); - if (!m_stopAtSystemEntry) + if (m_attached) + m_lastStopReason = InitialBreakpoint; + else if (!m_stopAtSystemEntry) { ApplyBreakpoints(); m_engine->Resume(false, 0); @@ -316,6 +356,32 @@ namespace BinaryNinjaDebugger { } ApplyBreakpoints(); + if (event.signalHandler) + { + auto arch = m_arch.load(); + DebuggerEvent message; + message.type = BackendMessageEventType; + message.data.messageData.message = fmt::format( + "PTRACE: signal {} ({}) was delivered to thread {}, which is stopped at the start of its handler, " + "0x{:x}\n", + event.signalHandler, strsignal(event.signalHandler), event.tid, + arch ? ReadArchRegister(arch->pc) : 0); + PostDebuggerEvent(message); + } + if (event.syscall) + { + PtraceEngine::SyscallInfo info; + DebuggerEvent message; + message.type = BackendMessageEventType; + if (m_engine->GetSyscallInfo(event.tid, info)) + message.data.messageData.message = "PTRACE: " + DescribeSyscallStop(event.tid, info) + "\n"; + else + message.data.messageData.message = fmt::format( + "PTRACE: thread {} is stopped at a system call, but its details could not be read, which needs " + "Linux 5.3\n", + event.tid); + PostDebuggerEvent(message); + } dbgevt.type = AdapterStoppedEventType; dbgevt.data.targetStoppedData.reason = m_lastStopReason; dbgevt.data.targetStoppedData.lastActiveThread = event.tid; @@ -324,6 +390,7 @@ namespace BinaryNinjaDebugger { case PtraceEngine::ExitedEvent: m_stopGeneration++; m_targetActive = false; + ForgetKnownBreakpoints(); if (m_stepper) m_stepper->Cancel(); ClearBreakpoints(); @@ -335,6 +402,7 @@ namespace BinaryNinjaDebugger { break; case PtraceEngine::DetachedEvent: m_targetActive = false; + ForgetKnownBreakpoints(); if (m_stepper) m_stepper->Cancel(); ClearBreakpoints(); @@ -355,8 +423,41 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::Attach(std::uint32_t pid) { - LogWarn("PtraceAdapter::Attach not implemented"); - return false; + if (pid == 0) + { + DebuggerEvent event; + event.type = LaunchFailureEventType; + event.data.errorData.shortError = "Failed to attach to target"; + event.data.errorData.error = "PTRACE: no process id to attach to"; + PostDebuggerEvent(event); + return false; + } + + auto adapterSettings = GetAdapterSettings(); + auto data = GetData(); + BNSettingsScope scope = SettingsResourceScope; + m_inputFile = adapterSettings->Get("common.inputFile", data, &scope); + if (m_inputFile.empty()) + { + std::error_code error; + auto exe = std::filesystem::read_symlink("/proc/" + std::to_string(pid) + "/exe", error); + if (!error) + m_inputFile = exe.string(); + } + + CreateEngine(true); + std::string error; + if (!m_engine->Attach(pid, error)) + { + m_targetActive = false; + DebuggerEvent event; + event.type = LaunchFailureEventType; + event.data.errorData.shortError = "Failed to attach to target"; + event.data.errorData.error = fmt::format("PTRACE: {}", error); + PostDebuggerEvent(event); + return false; + } + return true; } @@ -553,6 +654,8 @@ namespace BinaryNinjaDebugger { } m_breakpoints.emplace_back(address, m_nextBreakpointId++, true); + + RememberBreakpoint(address); return m_breakpoints.back(); } @@ -567,6 +670,9 @@ namespace BinaryNinjaDebugger { // The module is not loaded yet, so this waits for it if (std::find(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address) == m_pendingBreakpoints.end()) m_pendingBreakpoints.push_back(address); + if (std::none_of(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&address](const KnownBreakpoint& known) { return known.location == address; })) + m_knownBreakpoints.push_back({address, "", 0}); return DebugBreakpoint(); } @@ -577,10 +683,18 @@ namespace BinaryNinjaDebugger { auto it = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [&breakpoint](const DebugBreakpoint& bp) { return bp.m_address == breakpoint.m_address; }); - if (!m_engine || it == m_breakpoints.end() || !ReleaseBreakpoint(breakpoint.m_address)) + if (!m_engine || it == m_breakpoints.end()) + return false; + + ModuleNameAndOffset location; + bool known = ToModuleOffset(breakpoint.m_address, location); + if (!ReleaseBreakpoint(breakpoint.m_address)) return false; m_breakpoints.erase(it); + std::erase_if(m_knownBreakpoints, [&](const KnownBreakpoint& k) { + return k.appliedAddress == breakpoint.m_address || (known && k.location == location); + }); return true; } @@ -588,15 +702,27 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::RemoveBreakpoint(const ModuleNameAndOffset& address) { std::lock_guard lock(m_breakpointMutex); - auto pending = std::find(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address); - if (pending != m_pendingBreakpoints.end()) + auto known = std::find_if(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&address](const KnownBreakpoint& k) { return k.location == address; }); + if (known != m_knownBreakpoints.end() && known->appliedAddress) { - m_pendingBreakpoints.erase(pending); - return true; + uint64_t appliedAddress = known->appliedAddress; + auto breakpoint = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), + [appliedAddress](const DebugBreakpoint& bp) { return bp.m_address == appliedAddress; }); + if (breakpoint != m_breakpoints.end()) + { + if (!ReleaseBreakpoint(appliedAddress)) + return false; + m_breakpoints.erase(breakpoint); + } } - uint64_t resolved; - return m_targetActive && ResolveModuleAddress(address, resolved) && RemoveBreakpoint(DebugBreakpoint(resolved)); + if (known == m_knownBreakpoints.end()) + return false; + m_knownBreakpoints.erase(known); + m_pendingBreakpoints.erase(std::remove(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address), + m_pendingBreakpoints.end()); + return true; } @@ -614,7 +740,22 @@ namespace BinaryNinjaDebugger { if (!m_engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) return false; - return m_engine->AddHardwareBreakpoint(address, hwType, size); + if (!m_engine->AddHardwareBreakpoint(address, hwType, size)) + return false; + + std::lock_guard lock(m_breakpointMutex); + ModuleNameAndOffset location; + if (ToModuleOffset(address, location)) + { + PendingHardwareBreakpoint known(location, type, size); + known.address = address; + auto existing = std::find(m_knownHardwareBreakpoints.begin(), m_knownHardwareBreakpoints.end(), known); + if (existing == m_knownHardwareBreakpoints.end()) + m_knownHardwareBreakpoints.push_back(known); + else + existing->address = address; + } + return true; } @@ -624,7 +765,17 @@ namespace BinaryNinjaDebugger { if (!m_engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) return false; - return m_engine->RemoveHardwareBreakpoint(address, hwType, size); + std::lock_guard lock(m_breakpointMutex); + ModuleNameAndOffset location; + bool known = ToModuleOffset(address, location); + if (!m_engine->RemoveHardwareBreakpoint(address, hwType, size)) + return false; + + std::erase_if(m_knownHardwareBreakpoints, [&](const PendingHardwareBreakpoint& entry) { + return entry.address == address + || (known && entry.isRelative && entry.location == location && entry.type == type && entry.size == size); + }); + return true; } @@ -640,6 +791,9 @@ namespace BinaryNinjaDebugger { if (std::find(m_pendingHardwareBreakpoints.begin(), m_pendingHardwareBreakpoints.end(), pending) == m_pendingHardwareBreakpoints.end()) m_pendingHardwareBreakpoints.push_back(pending); + if (std::find(m_knownHardwareBreakpoints.begin(), m_knownHardwareBreakpoints.end(), pending) + == m_knownHardwareBreakpoints.end()) + m_knownHardwareBreakpoints.push_back(pending); return true; } @@ -649,16 +803,18 @@ namespace BinaryNinjaDebugger { { std::lock_guard lock(m_breakpointMutex); PendingHardwareBreakpoint pending(location, type, size); - auto it = std::find(m_pendingHardwareBreakpoints.begin(), m_pendingHardwareBreakpoints.end(), pending); - if (it != m_pendingHardwareBreakpoints.end()) - { - m_pendingHardwareBreakpoints.erase(it); - return true; - } - - uint64_t resolved; - return m_targetActive && ResolveModuleAddress(location, resolved) - && RemoveHardwareBreakpoint(resolved, type, size); + auto known = std::find(m_knownHardwareBreakpoints.begin(), m_knownHardwareBreakpoints.end(), pending); + if (known == m_knownHardwareBreakpoints.end()) + return false; + if (known->address && !RemoveHardwareBreakpoint(known->address, type, size)) + return false; + m_knownHardwareBreakpoints.erase( + std::remove(m_knownHardwareBreakpoints.begin(), m_knownHardwareBreakpoints.end(), pending), + m_knownHardwareBreakpoints.end()); + m_pendingHardwareBreakpoints.erase( + std::remove(m_pendingHardwareBreakpoints.begin(), m_pendingHardwareBreakpoints.end(), pending), + m_pendingHardwareBreakpoints.end()); + return true; } @@ -677,9 +833,10 @@ namespace BinaryNinjaDebugger { regsets[regset] = std::move(data); } - for (size_t i = 0; i < arch->registers.size(); i++) + auto registers = GetRegisterList(); + for (size_t i = 0; i < registers->size(); i++) { - const auto& reg = arch->registers[i]; + const auto& reg = (*registers)[i]; auto it = regsets.find(reg.regset); if (it != regsets.end() && RegisterInBounds(reg, it->second)) result[reg.name] = RegisterFromBytes(reg, it->second, i); @@ -694,12 +851,17 @@ namespace BinaryNinjaDebugger { if (!m_engine || !arch) return DebugRegister(); - auto info = arch->Find(reg); + auto registers = GetRegisterList(); + auto found = std::find_if(registers->begin(), registers->end(), + [®](const PtraceRegister& candidate) { return candidate.name == reg; }); + if (found == registers->end()) + return DebugRegister(); + std::vector data; - if (!info || !m_engine->GetRegisterSet(m_activeThreadId, info->regset, data) || !RegisterInBounds(*info, data)) + if (!m_engine->GetRegisterSet(m_activeThreadId, found->regset, data) || !RegisterInBounds(*found, data)) return DebugRegister(); - return RegisterFromBytes(*info, data, info - arch->registers.data()); + return RegisterFromBytes(*found, data, found - registers->begin()); } @@ -709,9 +871,12 @@ namespace BinaryNinjaDebugger { if (!m_engine || !arch) return false; - auto info = arch->Find(reg); + auto registers = GetRegisterList(); + auto info = std::find_if(registers->begin(), registers->end(), + [®](const PtraceRegister& candidate) { return candidate.name == reg; }); std::vector data; - if (!info || !m_engine->GetRegisterSet(m_activeThreadId, info->regset, data) || !RegisterInBounds(*info, data)) + if (info == registers->end() || !m_engine->GetRegisterSet(m_activeThreadId, info->regset, data) + || !RegisterInBounds(*info, data)) return false; uint8_t buffer[64]; @@ -721,6 +886,54 @@ namespace BinaryNinjaDebugger { } + // The table has the registers that are in the target. The architecture of the view knows the names of the others, which + // are parts of them, and those are what the controller asks for when the IL reads `edi` and not `rdi`. The controller + // finds a register by its exact name, and an unknown name reads as 0. + void PtraceAdapter::BuildRegisterList() + { + auto list = std::make_shared>(); + auto arch = m_arch.load(); + if (arch) + { + *list = arch->registers; + + // The view describes the program that was analyzed, which is not always the one that is running + auto viewArch = GetData() ? GetData()->GetDefaultArchitecture() : nullptr; + if (viewArch && viewArch->GetName() == arch->name) + { + std::vector described; + for (uint32_t reg : viewArch->GetAllRegisters()) + { + auto info = viewArch->GetRegisterInfo(reg); + PtraceRegisterDescription description; + description.name = viewArch->GetRegisterName(reg); + description.parent = viewArch->GetRegisterName(info.fullWidthRegister); + description.offset = info.offset; + description.size = info.size; + described.push_back(std::move(description)); + } + + for (const auto& message : CheckRegisterSizes(*arch, described)) + LogDebug("PtraceAdapter: %s", message.c_str()); + auto derived = DeriveSubRegisters(*arch, described); + list->insert(list->end(), derived.begin(), derived.end()); + } + } + + std::lock_guard lock(m_registerMutex); + m_registers = list; + } + + + std::shared_ptr> PtraceAdapter::GetRegisterList() + { + std::lock_guard lock(m_registerMutex); + if (!m_registers) + m_registers = std::make_shared>(); + return m_registers; + } + + uint64_t PtraceAdapter::ReadArchRegister(const std::string& name) { return (uint64_t)ReadRegister(name).m_value; @@ -793,6 +1006,9 @@ namespace BinaryNinjaDebugger { m_modules.clear(); m_moduleGeneration = UINT64_MAX; m_loaderBreakpoint = 0; + + std::lock_guard syscallLock(m_syscallMutex); + m_syscallEntries.clear(); } @@ -917,6 +1133,7 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::Go() { + SyncEngineSettings(); if (m_stepper) m_stepper->Cancel(); m_stopGeneration++; @@ -932,6 +1149,7 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::StepInto() { + SyncEngineSettings(); if (m_stepper) m_stepper->Cancel(); m_stopGeneration++; @@ -953,6 +1171,7 @@ namespace BinaryNinjaDebugger { if (!m_engine || !m_stepper || m_engine->IsRunning()) return false; + SyncEngineSettings(); m_stepper->Cancel(); m_stopGeneration++; uint32_t tid = m_activeThreadId; @@ -970,6 +1189,7 @@ namespace BinaryNinjaDebugger { if (!m_engine || !m_stepper || m_engine->IsRunning()) return false; + SyncEngineSettings(); m_stepper->Cancel(); m_stopGeneration++; uint32_t tid = m_activeThreadId; @@ -1025,9 +1245,37 @@ namespace BinaryNinjaDebugger { } + // The view analyzes one module, the input file. Its functions are only where that module is, so what the analysis + // knows says nothing about an address outside of it, such as in another program after an exec. + bool PtraceAdapter::IsInAnalyzedModule(uint64_t address) + { + for (const auto& module : GetModules()) + { + if (DebugModule::IsSameBaseModule(module.path, m_inputFile) && address >= module.base + && address < module.base + module.size) + return true; + } + return false; + } + + + bool PtraceAdapter::AnalyzedModuleLoaded() + { + for (const auto& module : GetModules()) + { + if (DebugModule::IsSameBaseModule(module.path, m_inputFile)) + return true; + } + return false; + } + + std::vector PtraceAdapter::GetReturnSites(uint64_t pc) { std::vector sites; + if (!IsInAnalyzedModule(pc)) + return sites; + auto data = GetData(); auto functions = data ? data->GetAnalysisFunctionsContainingAddress(pc) : std::vector>(); if (functions.empty() || !functions[0]) @@ -1093,9 +1341,158 @@ namespace BinaryNinjaDebugger { } + static const char* BackendCommandHelp = + "PTRACE backend commands:\n" + " syscall continue until a thread is at the entry or the exit of a system call. The call is made.\n" + " sysemu continue until a thread is at the entry of a system call, which is not made. Put the result\n" + " in the return register of the target, and resume it with the usual buttons.\n" + " syscall-info describe the system call that the active thread is stopped at\n" + " syscall-set F V change the stop, on Linux 6.16 or newer: F is nr or arg0 to arg5 at an entry, or ret at an\n" + " exit, and V is a number\n"; + + std::string PtraceAdapter::InvokeBackendCommand(const std::string& command) { - return ""; + std::istringstream stream(command); + std::vector words; + for (std::string word; stream >> word;) + words.push_back(word); + + if (words.empty() || words[0] == "help" || words[0] == "?") + return BackendCommandHelp; + if (words[0] == "syscall" && words.size() == 1) + return ContinueToSyscall(PtraceEngine::SyscallMode::Trace); + if (words[0] == "sysemu" && words.size() == 1) + return ContinueToSyscall(PtraceEngine::SyscallMode::Emulate); + if (words[0] == "syscall-info" && words.size() == 1) + return DescribeCurrentSyscall(); + if (words[0] == "syscall-set" && words.size() == 3) + return SetSyscallField(words[1], words[2]); + + return fmt::format("PTRACE: unknown command \"{}\"\n{}", command, BackendCommandHelp); + } + + + std::string PtraceAdapter::DescribeSyscallStop(uint32_t tid, const PtraceEngine::SyscallInfo& info) + { + std::lock_guard lock(m_syscallMutex); + switch (info.op) + { + case PtraceEngine::SyscallInfo::Entry: + case PtraceEngine::SyscallInfo::Seccomp: + m_syscallEntries[tid] = info; + return fmt::format("thread {} is entering {}", tid, DescribeSyscall(info)); + case PtraceEngine::SyscallInfo::Exit: + { + // The exit only has the result, so the call comes from the entry + auto entry = m_syscallEntries.find(tid); + std::string call = entry != m_syscallEntries.end() ? DescribeSyscall(entry->second) + " " : ""; + m_syscallEntries.erase(tid); + return fmt::format("thread {} left {}{}", tid, call, DescribeSyscall(info)); + } + default: + return fmt::format("thread {}: {}", tid, DescribeSyscall(info)); + } + } + + + std::string PtraceAdapter::ContinueToSyscall(PtraceEngine::SyscallMode mode) + { + if (!m_engine || !m_targetActive) + return "PTRACE: there is no target\n"; + if (m_engine->IsRunning()) + return "PTRACE: the target is running\n"; + auto arch = m_arch.load(); + if (mode == PtraceEngine::SyscallMode::Emulate && (!arch || !arch->sysemu)) + return "PTRACE: this architecture has no PTRACE_SYSEMU\n"; + + SyncEngineSettings(); + if (m_stepper) + m_stepper->Cancel(); + m_stopGeneration++; + + // The controller did not ask for this, so it has to be told that the target runs. That comes before the resume, + // because a stop that comes quickly must not be the first of the two that the controller hears of. + DebuggerEvent resumed; + resumed.type = ResumeEventType; + PostDebuggerEvent(resumed); + + if (m_engine->ResumeToSyscall(mode)) + return mode == PtraceEngine::SyscallMode::Trace + ? "PTRACE: running to the entry or the exit of the next system call\n" + : "PTRACE: running to the entry of the next system call, which will not be made\n"; + + DebuggerEvent stopped; + stopped.type = AdapterStoppedEventType; + stopped.data.targetStoppedData.reason = m_lastStopReason; + stopped.data.targetStoppedData.lastActiveThread = m_activeThreadId; + PostDebuggerEvent(stopped); + return "PTRACE: the target could not be resumed\n"; + } + + + std::string PtraceAdapter::DescribeCurrentSyscall() + { + if (!m_engine || !m_targetActive) + return "PTRACE: there is no target\n"; + + PtraceEngine::SyscallInfo info; + if (m_engine->IsRunning() || !m_engine->GetSyscallInfo(m_activeThreadId, info)) + return "PTRACE: the system call information could not be read. The target has to be stopped, on Linux 5.3 or " + "newer.\n"; + + std::string text = DescribeSyscall(info, true); + if (info.op == PtraceEngine::SyscallInfo::Exit) + { + std::lock_guard lock(m_syscallMutex); + auto entry = m_syscallEntries.find(m_activeThreadId); + if (entry != m_syscallEntries.end()) + text += "\nentered as " + DescribeSyscall(entry->second); + } + return "PTRACE: " + text + "\n"; + } + + + std::string PtraceAdapter::SetSyscallField(const std::string& field, const std::string& value) + { + if (!m_engine || !m_targetActive || m_engine->IsRunning()) + return "PTRACE: the target has to be stopped\n"; + + PtraceEngine::SyscallInfo info; + if (!m_engine->GetSyscallInfo(m_activeThreadId, info) + || (info.op == PtraceEngine::SyscallInfo::None)) + return "PTRACE: the active thread is not stopped at a system call\n"; + + char* end = nullptr; + bool isEntry = info.op != PtraceEngine::SyscallInfo::Exit; + if (field == "ret") + { + if (isEntry) + return "PTRACE: ret can only be set at an exit\n"; + info.returnValue = strtoll(value.c_str(), &end, 0); + // The kernel puts a value from -4095 to -1 in the register for an error + info.isError = info.returnValue < 0 && info.returnValue >= -4095; + } + else if (field == "nr" || (field.size() == 4 && field.rfind("arg", 0) == 0 && field[3] >= '0' && field[3] <= '5')) + { + if (!isEntry) + return fmt::format("PTRACE: {} can only be set at an entry\n", field); + uint64_t number = strtoull(value.c_str(), &end, 0); + if (field == "nr") + info.number = number; + else + info.args[field[3] - '0'] = number; + } + else + { + return fmt::format("PTRACE: unknown field \"{}\", the fields are nr, arg0 to arg5 and ret\n", field); + } + + if (value.empty() || !end || *end != '\0') + return fmt::format("PTRACE: \"{}\" is not a number\n", value); + if (!m_engine->SetSyscallInfo(m_activeThreadId, info)) + return "PTRACE: the kernel did not take the change. It needs Linux 6.16.\n"; + return "PTRACE: changed. " + DescribeCurrentSyscall(); } @@ -1144,7 +1541,33 @@ namespace BinaryNinjaDebugger { Ref PtraceAdapter::GetProperty(const std::string& name) { - return nullptr; + // The system call that the active thread is stopped at, for scripts + if (name != "syscall" || !m_engine || !m_targetActive || m_engine->IsRunning()) + return nullptr; + + PtraceEngine::SyscallInfo info; + if (!m_engine->GetSyscallInfo(m_activeThreadId, info)) + return nullptr; + + static const char* const ops[] = {"none", "entry", "exit", "seccomp"}; + std::map> values; + values["op"] = new Metadata(std::string(ops[info.op])); + values["arch"] = new Metadata((uint64_t)info.arch); + values["pc"] = new Metadata(info.instructionPointer); + values["sp"] = new Metadata(info.stackPointer); + if (info.op == PtraceEngine::SyscallInfo::Entry || info.op == PtraceEngine::SyscallInfo::Seccomp) + { + const char* syscallName = SyscallName(info.arch, info.number); + values["number"] = new Metadata(info.number); + values["name"] = new Metadata(std::string(syscallName ? syscallName : "")); + values["args"] = new Metadata(std::vector(info.args, info.args + 6)); + } + if (info.op == PtraceEngine::SyscallInfo::Exit) + { + values["return"] = new Metadata(info.returnValue); + values["is_error"] = new Metadata(info.isError); + } + return new Metadata(values); } @@ -1160,28 +1583,414 @@ namespace BinaryNinjaDebugger { if (!m_engine || !m_targetActive) return; - // Only what has been applied leaves the list, so the rest waits for a module that is not loaded yet - for (auto it = m_pendingBreakpoints.begin(); it != m_pendingBreakpoints.end();) + // The logical module-relative breakpoint remains authoritative after it has been applied. A loader rendezvous + // may mean that its mapping disappeared, was replaced at the same address, or moved to another base. + for (size_t index = 0; index < m_knownBreakpoints.size(); index++) { - uint64_t address; - if (ResolveModuleAddress(*it, address) && AddBreakpoint(address, 0).m_address != 0) - it = m_pendingBreakpoints.erase(it); - else - it++; + auto location = m_knownBreakpoints[index].location; + uint64_t oldAddress = m_knownBreakpoints[index].appliedAddress; + uint64_t address = 0; + bool resolved = ResolveModuleAddress(location, address); + + if (oldAddress && (!resolved || oldAddress != address)) + { + auto applied = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [oldAddress](const DebugBreakpoint& bp) { + return bp.m_address == oldAddress; + }); + if (applied != m_breakpoints.end()) + { + if (!ReleaseBreakpoint(oldAddress, false)) + continue; + m_breakpoints.erase(applied); + } + m_knownBreakpoints[index].appliedAddress = 0; + } + + if (!resolved) + continue; + + auto applied = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [address](const DebugBreakpoint& bp) { + return bp.m_address == address; + }); + if (applied != m_breakpoints.end()) + { + if (m_engine->AddBreakpoint(address)) + m_knownBreakpoints[index].appliedAddress = address; + } + else if (AddBreakpoint(address, 0).m_address != 0) + { + // RememberBreakpoint, called by AddBreakpoint, records this address on the same logical entry. + m_knownBreakpoints[index].appliedAddress = address; + } } - for (auto it = m_pendingHardwareBreakpoints.begin(); it != m_pendingHardwareBreakpoints.end();) + m_pendingBreakpoints.clear(); + for (const auto& known : m_knownBreakpoints) { - uint64_t address = it->address; - bool resolved = !it->isRelative || ResolveModuleAddress(it->location, address); - if (resolved && AddHardwareBreakpoint(address, it->type, it->size)) - it = m_pendingHardwareBreakpoints.erase(it); - else - it++; + if (!known.appliedAddress) + m_pendingBreakpoints.push_back(known.location); + } + + // Breakpoints outside a module have no logical location to reconcile, but an idempotent add still repairs a + // replacement mapping at the same absolute address. + for (const auto& breakpoint : m_breakpoints) + { + bool logical = std::any_of(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&breakpoint](const KnownBreakpoint& known) { return known.appliedAddress == breakpoint.m_address; }); + if (!logical) + m_engine->AddBreakpoint(breakpoint.m_address); + } + + for (auto& known : m_knownHardwareBreakpoints) + { + uint64_t address = 0; + bool resolved = ResolveModuleAddress(known.location, address); + PtraceHwType hwType; + if (!HwTypeFromBreakpointType(known.type, hwType)) + continue; + + if (known.address && (!resolved || known.address != address)) + { + if (!m_engine->RemoveHardwareBreakpoint(known.address, hwType, known.size)) + continue; + known.address = 0; + } + if (resolved && !known.address && m_engine->AddHardwareBreakpoint(address, hwType, known.size)) + known.address = address; + } + m_pendingHardwareBreakpoints.clear(); + for (const auto& known : m_knownHardwareBreakpoints) + { + if (!known.address) + m_pendingHardwareBreakpoints.push_back(known); } } + // The target has started another program. The engine has already thrown away everything that belonged to the old + // one, so this does the same for what the adapter keeps, and sets the new program up the way the first stop set up + // the first. + void PtraceAdapter::HandleExec(const PtraceEngine::Event& event) + { + // A step that the exec cut short is over, and the stop is the end of it + bool wasStepping = event.singleStep || (m_stepper && m_stepper->IsActive()); + if (m_stepper) + m_stepper->Cancel(); + ClearBreakpoints(); + ResetTargetState(); + + m_arch = m_engine->GetArch(); + BuildRegisterList(); + if (!m_arch) + LogWarn("PtraceAdapter: unsupported target architecture"); + + { + std::lock_guard lock(m_breakpointMutex); + m_pendingBreakpoints.clear(); + for (auto& known : m_knownBreakpoints) + { + known.appliedAddress = 0; + m_pendingBreakpoints.push_back(known.location); + } + for (auto& known : m_knownHardwareBreakpoints) + known.address = 0; + m_pendingHardwareBreakpoints = m_knownHardwareBreakpoints; + } + + std::error_code error; + auto program = std::filesystem::read_symlink("/proc/" + std::to_string(m_engine->GetPid()) + "/exe", error); + DebuggerEvent message; + message.type = BackendMessageEventType; + message.data.messageData.message = fmt::format("PTRACE: the process started {}\n", program.string()); + PostDebuggerEvent(message); + + SetUpLoaderBreakpoint(); + ApplyBreakpoints(); + std::string resolved = ResolveBreakpointsByName(program.string()); + resolved += RefreshSymbolsAfterExec(program.string()); + m_lastStopReason = UnknownReason; + ReportAfterExec(resolved); + + BNSettingsScope scope = SettingsResourceScope; + bool stopOnExec = GetAdapterSettings()->Get("common.stopOnExec", GetData(), &scope); + if (!stopOnExec && !wasStepping) + { + m_engine->Resume(false, 0); + return; + } + + DebuggerEvent stopped; + stopped.type = AdapterStoppedEventType; + stopped.data.targetStoppedData.reason = UnknownReason; + stopped.data.targetStoppedData.lastActiveThread = event.tid; + PostDebuggerEvent(stopped); + } + + + // Says what the exec has left as it was, since the view still analyzes the program that the target started with + void PtraceAdapter::ReportAfterExec(const std::string& resolved) + { + std::string text = resolved; + if (!AnalyzedModuleLoaded()) + text += fmt::format( + "PTRACE: this view analyzes {}, which the target is no longer running. Its analysis does not " + "apply to the new program, and stepping out of a function follows the frame pointers " + "instead.\n", + DebugModule::GetPathBaseName(m_inputFile)); + + { + std::lock_guard lock(m_breakpointMutex); + if (!m_pendingBreakpoints.empty()) + { + text += fmt::format("PTRACE: {} breakpoint(s) are inactive, because their module is not loaded:", + m_pendingBreakpoints.size()); + size_t shown = 0; + for (const auto& location : m_pendingBreakpoints) + { + if (shown++ == 5) + { + text += fmt::format(" and {} more", m_pendingBreakpoints.size() - 5); + break; + } + text += fmt::format(" {}+0x{:x}", DebugModule::GetPathBaseName(location.module), location.offset); + } + text += "\n"; + + // Say how the ones at the start of a function can be found in the new program + bool namedOnes = std::any_of(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), + [this](const ModuleNameAndOffset& location) { + return std::any_of(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&location](const KnownBreakpoint& k) { + return k.location == location && !k.function.empty(); + }); + }); + if (namedOnes && !ResolveByNameEnabled()) + text += + "PTRACE: the ones at the start of a function can be found by its name in the new program, with " + "the " + "common.resolveBreakpointsByNameOnExec setting.\n"; + } + } + + if (text.empty()) + return; + + DebuggerEvent message; + message.type = BackendMessageEventType; + message.data.messageData.message = text; + PostDebuggerEvent(message); + } + + + // A breakpoint is known by the module that it is in, and its offset there, which stays true when the address does + // not + bool PtraceAdapter::FindModule(uint64_t address, PtraceModuleInfo& module) + { + for (const auto& candidate : GetModules()) + { + if (address >= candidate.base && address < candidate.base + candidate.size) + { + module = candidate; + return true; + } + } + return false; + } + + + bool PtraceAdapter::ToModuleOffset(uint64_t address, ModuleNameAndOffset& location) + { + PtraceModuleInfo module; + if (!FindModule(address, module)) + return false; + + location = ModuleNameAndOffset(module.path, address - module.base); + return true; + } + + + // Keeps a breakpoint by its module and offset, and by the function that it is at the start of + void PtraceAdapter::RememberBreakpoint(uint64_t address) + { + PtraceModuleInfo module; + if (!FindModule(address, module)) + return; + + std::string function; + if (auto elf = GetElf(module.path)) + { + uint64_t bias = module.base - elf->linkBase; + auto symbol = FindElfSymbol(*elf, address - bias); + if (symbol && symbol->isFunction && symbol->address + bias == address) + function = symbol->name; + } + + ModuleNameAndOffset location(module.path, address - module.base); + auto it = std::find_if(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&location](const KnownBreakpoint& known) { return known.location == location; }); + if (it == m_knownBreakpoints.end()) + m_knownBreakpoints.push_back({location, function, address}); + else if (it->function.empty()) + it->function = function; + it = std::find_if(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&location](const KnownBreakpoint& known) { return known.location == location; }); + if (it != m_knownBreakpoints.end()) + it->appliedAddress = address; + } + + + bool PtraceAdapter::ResolveByNameEnabled() + { + BNSettingsScope scope = SettingsResourceScope; + return GetAdapterSettings()->Get("common.resolveBreakpointsByNameOnExec", GetData(), &scope); + } + + + // The symbols that were loaded into the view are at the addresses of the old program. A module that is still there + // is loaded again, since it may have moved, and one that is gone is taken out. The controller is used through what + // it offers for this, with modules made from what the adapter sees now, because its own list of modules is only + // brought up to date at the next stop. This runs with none of the adapter's locks held, since it reaches into + // Binary Ninja. + std::string PtraceAdapter::RefreshSymbolsAfterExec(const std::string& program) + { + auto controller = GetController(); + if (!controller) + return ""; + + auto modules = GetModules(); + auto toDebugModule = [](const PtraceModuleInfo& module) { + return DebugModule(module.path, module.shortName, module.base, module.size, true); + }; + + size_t reloaded = 0, removed = 0; + bool programDone = false; + for (const auto& name : controller->GetModulesWithLoadedSymbols()) + { + auto it = std::find_if(modules.begin(), modules.end(), [&name](const PtraceModuleInfo& module) { + return DebugModule::IsSameBaseModule(module.path, name); + }); + if (it == modules.end()) + { + controller->RemoveSymbolsForModule(name); + removed++; + continue; + } + + controller->LoadSymbolsForModule(toDebugModule(*it)); + reloaded++; + programDone = programDone || it->path == program; + } + + bool loadedProgram = false; + BNSettingsScope scope = SettingsResourceScope; + if (!programDone && GetAdapterSettings()->Get("common.loadSymbolsAfterExec", GetData(), &scope)) + { + for (const auto& module : modules) + { + if (module.path == program) + { + loadedProgram = controller->LoadSymbolsForModule(toDebugModule(module)) > 0; + break; + } + } + } + + if (!reloaded && !removed && !loadedProgram) + return ""; + + std::string text = "PTRACE: symbols in the view:"; + if (removed) + text += fmt::format(" {} module(s) that are gone were taken out;", removed); + if (reloaded) + text += fmt::format(" {} that are still there were loaded again;", reloaded); + if (loadedProgram) + text += fmt::format(" the symbols of {} were loaded;", DebugModule::GetPathBaseName(program)); + text.back() = '\n'; + return text; + } + + + // GDB looks a breakpoint up again by its name when the target starts another program. A breakpoint here is a module + // and an offset, which mean nothing in another program, so the ones at the start of a function are looked up by + // that function's name in the main executable of the new program, when that is asked for. + std::string PtraceAdapter::ResolveBreakpointsByName(const std::string& program) + { + if (!ResolveByNameEnabled()) + return ""; + + PtraceModuleInfo main; + bool found = false; + for (const auto& module : GetModules()) + { + if (module.path == program) + { + main = module; + found = true; + break; + } + } + auto elf = found ? GetElf(program) : nullptr; + if (!elf) + return ""; + + uint64_t bias = main.base - elf->linkBase; + std::string text; + std::lock_guard lock(m_breakpointMutex); + // Adding a breakpoint changes these lists, so it is done from a copy + for (const auto& location : std::vector(m_pendingBreakpoints)) + { + auto known = std::find_if(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), + [&location](const KnownBreakpoint& k) { return k.location == location; }); + if (known == m_knownBreakpoints.end() || known->function.empty()) + continue; + + std::string function = known->function; + bool ambiguous; + auto symbol = FindElfFunctionByName(*elf, function, &ambiguous); + if (!symbol) + { + if (ambiguous) + text += fmt::format("PTRACE: {} is more than one function in {}, so its breakpoint is not moved\n", + function, DebugModule::GetPathBaseName(program)); + continue; + } + + uint64_t address = symbol->address + bias; + if (!AddBreakpoint(address, 0).m_address) + continue; + + // It belongs to the new program now, and the old place is forgotten + text += fmt::format("PTRACE: the breakpoint at {}+0x{:x} ({}) is now at {}+0x{:x}\n", + DebugModule::GetPathBaseName(location.module), location.offset, function, + DebugModule::GetPathBaseName(program), address - main.base); + std::erase_if(m_knownBreakpoints, [&location](const KnownBreakpoint& k) { return k.location == location; }); + m_pendingBreakpoints.erase(std::remove(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), location), + m_pendingBreakpoints.end()); + } + return text; + } + + + // The setting can be changed while the target is stopped, so the engine is told again before every resume + void PtraceAdapter::SyncEngineSettings() + { + if (!m_engine) + return; + + BNSettingsScope scope = SettingsResourceScope; + m_engine->SetDebugSignalHandlers( + GetAdapterSettings()->Get("common.debugSignalHandlers", GetData(), &scope)); + } + + + void PtraceAdapter::ForgetKnownBreakpoints() + { + std::lock_guard lock(m_breakpointMutex); + m_knownBreakpoints.clear(); + m_knownHardwareBreakpoints.clear(); + } + + void PtraceAdapter::ClearBreakpoints() { std::lock_guard lock(m_breakpointMutex); @@ -1207,18 +2016,23 @@ namespace BinaryNinjaDebugger { } - bool PtraceAdapter::ReleaseBreakpoint(uint64_t address) + bool PtraceAdapter::ReleaseBreakpoint(uint64_t address, bool restore) { std::lock_guard lock(m_breakpointMutex); auto it = m_engineBreakpointRefs.find(address); if (!m_engine || it == m_engineBreakpointRefs.end()) return false; - if (--it->second > 0) + if (it->second > 1) + { + it->second--; return true; + } - m_engineBreakpointRefs.erase(it); - return m_engine->RemoveBreakpoint(address); + bool removed = restore ? m_engine->RemoveBreakpoint(address) : m_engine->DiscardBreakpoint(address); + if (removed) + m_engineBreakpointRefs.erase(it); + return removed; } @@ -1320,6 +2134,57 @@ namespace BinaryNinjaDebugger { "description" : "Command line arguments to pass to the target.", "readOnly" : false })"); + settings->RegisterSetting("attach.pid", + R"({ + "title" : "PID to attach to", + "type" : "number", + "default" : 0, + "minValue" : 0, + "maxValue" : 4294967295, + "description" : "PID of the process to attach to", + "readOnly" : false + })"); + settings->RegisterSetting("common.debugSignalHandlers", + R"({ + "title" : "Debug Signal Handlers", + "type" : "boolean", + "default" : false, + "description" : "When the target is sent a signal that it has a handler for, stop at the first instruction of the handler. This includes the signals that would not stop the target otherwise, such as SIGCHLD, SIGALRM and SIGWINCH. Signals without a handler are not affected, and neither is stepping. A change takes effect the next time the target is resumed.", + "readOnly" : false + })"); + settings->RegisterSetting("common.loadSymbolsAfterExec", + R"({ + "title" : "Load Symbols After Exec", + "type" : "boolean", + "default" : false, + "description" : "When the target starts another program, load the symbols of that program into the view. The symbols that were already loaded into the view are always brought up to date after an exec: the ones for modules that are gone are removed, and the others are loaded again.", + "readOnly" : false + })"); + settings->RegisterSetting("common.resolveBreakpointsByNameOnExec", + R"({ + "title" : "Find Breakpoints By Function Name After Exec", + "type" : "boolean", + "default" : false, + "description" : "When the target starts another program, look up the breakpoints that are at the start of a function by the name of that function in the main executable of the new program, the way GDB does. Otherwise a breakpoint belongs to its module, and stays inactive while that module is not loaded. Only a name that is exactly one function in the new program is used, and only breakpoints at the very start of a function.", + "readOnly" : false + })"); + settings->RegisterSetting("common.stopOnExec", + R"({ + "title" : "Stop On Exec", + "type" : "boolean", + "default" : false, + "description" : "Stop the target when it starts another program with exec. Otherwise the target carries on with the new program, and the debugger says so in its messages.", + "readOnly" : false + })"); + settings->RegisterSetting("launch.redirectFileDescriptors", + R"({ + "title" : "Redirect File Descriptors", + "type" : "array", + "sorted" : false, + "default" : [], + "description" : "Sets file descriptors of the target before it starts, written the way a shell writes them, and applied in order. The forms are: [\"0out.txt\"] to write it to a file, [\"1>>out.txt\"] to append to it, [\"3<>data.bin\"] to open it for reading and writing, [\"2>&1\"] to make descriptor 2 a copy of descriptor 1, and [\"4>&-\"] to close it. Without a number it is 0 for < and 1 for the others. Files are created when they do not exist, and a relative path is relative to the working directory. Without a redirect, descriptors 0, 1 and 2 are the terminal of the debugger. A descriptor that is redirected to a file no longer reaches the terminal, and input written to the target no longer reaches it if descriptor 0 is redirected. This has no effect when attaching to a process.", + "readOnly" : false + })"); settings->RegisterSetting("launch.disableAslr", R"({ "title" : "Disable ASLR", diff --git a/core/adapters/ptrace/ptraceadapter.h b/core/adapters/ptrace/ptraceadapter.h index d44d9ccd..62e3f816 100644 --- a/core/adapters/ptrace/ptraceadapter.h +++ b/core/adapters/ptrace/ptraceadapter.h @@ -25,6 +25,7 @@ limitations under the License. #include "ptraceelf.h" #include "ptracemodule.h" #include "ptracestep.h" +#include "ptracesyscall.h" #include "ptraceengine.h" namespace BinaryNinjaDebugger { @@ -38,7 +39,11 @@ namespace BinaryNinjaDebugger { std::atomic m_lastStopReason {UnknownReason}; std::atomic m_exitCode {0}; std::atomic m_arch {nullptr}; + // The registers of the table, and the ones that the architecture of the view adds to them. It is replaced whole. + std::mutex m_registerMutex; + std::shared_ptr> m_registers; bool m_firstStop = false; + bool m_attached = false; bool m_stopAtSystemEntry = false; std::string m_inputFile; @@ -60,22 +65,58 @@ namespace BinaryNinjaDebugger { unsigned long m_nextBreakpointId = 1; std::vector m_pendingBreakpoints {}; std::vector m_pendingHardwareBreakpoints {}; + // The breakpoints of the user by module and offset, applied or not. An exec throws the addresses away, and + // these are what the breakpoints are put back from. + struct KnownBreakpoint + { + ModuleNameAndOffset location; + // The function that the breakpoint is at the very start of, if it is. That is what it can be found by in + // another program. + std::string function; + // The physical installation for this logical breakpoint. Loader rendezvous stops reconcile it with location. + uint64_t appliedAddress = 0; + }; + std::vector m_knownBreakpoints; + std::vector m_knownHardwareBreakpoints; + + // The last entry of a system call of each thread, which is what the exit that follows is the exit of + std::mutex m_syscallMutex; + std::map m_syscallEntries; void HandleEngineEvent(const PtraceEngine::Event& event); + std::string DescribeSyscallStop(uint32_t tid, const PtraceEngine::SyscallInfo& info); + std::string ContinueToSyscall(PtraceEngine::SyscallMode mode); + std::string DescribeCurrentSyscall(); + std::string SetSyscallField(const std::string& field, const std::string& value); void ClearBreakpoints(); + void ForgetKnownBreakpoints(); + void SyncEngineSettings(); + void HandleExec(const PtraceEngine::Event& event); + void ReportAfterExec(const std::string& resolved); + bool ToModuleOffset(uint64_t address, ModuleNameAndOffset& location); + bool FindModule(uint64_t address, PtraceModuleInfo& module); + void RememberBreakpoint(uint64_t address); + bool ResolveByNameEnabled(); + std::string ResolveBreakpointsByName(const std::string& program); + std::string RefreshSymbolsAfterExec(const std::string& program); + void BuildRegisterList(); + std::shared_ptr> GetRegisterList(); uint64_t ReadArchRegister(const std::string& name); bool ReadRegisterOf(uint32_t tid, const std::string& name, uint64_t& value); std::vector GetModules(); std::shared_ptr GetElf(const std::string& path); + void CreateEngine(bool attached); void SetUpLoaderBreakpoint(); bool AcquireBreakpoint(uint64_t address); - bool ReleaseBreakpoint(uint64_t address); + bool ReleaseBreakpoint(uint64_t address, bool restore = true); bool IsUserBreakpoint(uint64_t address); void DoStepOver(uint32_t tid); void DoStepReturn(uint32_t tid); void FailStep(const std::string& message); size_t GetCallLength(uint64_t pc); std::vector GetReturnSites(uint64_t pc); + bool IsInAnalyzedModule(uint64_t address); + bool AnalyzedModuleLoaded(); void ResetTargetState(); // Helper to resolve module+offset to absolute address diff --git a/core/adapters/ptrace/ptracearch.cpp b/core/adapters/ptrace/ptracearch.cpp index fb7ed704..014442c0 100644 --- a/core/adapters/ptrace/ptracearch.cpp +++ b/core/adapters/ptrace/ptracearch.cpp @@ -18,7 +18,11 @@ limitations under the License. #include #include #include +#include #include +#if defined(__i386__) || defined(__x86_64__) +#include +#endif namespace BinaryNinjaDebugger { @@ -33,26 +37,27 @@ namespace BinaryNinjaDebugger { } - // The debug registers are read and written through PTRACE_PEEKUSER and PTRACE_POKEUSER, at the offset of u_debugreg - // in struct user. The offset differs between 32-bit and 64-bit targets. + // PTRACE_PEEKUSER and PTRACE_POKEUSER use the ptracer's syscall ABI. A 64-bit debugger therefore uses its native + // struct user layout even when the tracee is a 32-bit process. class X86HwDebug : public PtraceHwDebug { size_t m_offset; + size_t m_stride; bool ReadDr(pid_t tid, size_t index, unsigned long& value) { errno = 0; - value = ptrace(PTRACE_PEEKUSER, tid, (void*)(m_offset + index * sizeof(long)), nullptr); + value = ptrace(PTRACE_PEEKUSER, tid, (void*)(m_offset + index * m_stride), nullptr); return errno == 0; } bool WriteDr(pid_t tid, size_t index, unsigned long value) { - return ptrace(PTRACE_POKEUSER, tid, (void*)(m_offset + index * sizeof(long)), (void*)value) == 0; + return ptrace(PTRACE_POKEUSER, tid, (void*)(m_offset + index * m_stride), (void*)value) == 0; } public: - X86HwDebug(size_t offset) : m_offset(offset) {} + X86HwDebug(size_t offset, size_t stride) : m_offset(offset), m_stride(stride) {} size_t SlotCount() const override { return 4; } @@ -104,6 +109,61 @@ namespace BinaryNinjaDebugger { }; + std::vector DeriveSubRegisters( + const PtraceArch& arch, const std::vector& described) + { + std::vector result; + // What is at the low end of a register is at its first byte only on a little-endian one + if (!arch.littleEndian) + return result; + + std::set seen; + for (const auto& description : described) + { + if (description.name.empty() || description.parent.empty() || description.parent == description.name + || description.size == 0 || arch.Find(description.name) || !seen.insert(description.name).second) + continue; + + auto parent = arch.Find(description.parent); + if (!parent || description.offset + description.size > parent->size) + continue; + + result.push_back({description.name, parent->regset, parent->offset + description.offset, description.size}); + } + return result; + } + + + std::vector CheckRegisterSizes( + const PtraceArch& arch, const std::vector& described) + { + std::vector result; + for (const auto& description : described) + { + if (description.name.empty() || description.parent != description.name) + continue; + + auto reg = arch.Find(description.name); + if (reg && reg->size != description.size) + result.push_back(description.name + " is " + std::to_string(reg->size) + " bytes in the table, and " + + std::to_string(description.size) + " for the architecture"); + } + return result; + } + + + static PtraceHwDebug* NativeX86HwDebug() + { +#if defined(__i386__) || defined(__x86_64__) + static X86HwDebug hwDebug( + offsetof(struct user, u_debugreg), sizeof(((struct user*)nullptr)->u_debugreg[0])); + return &hwDebug; +#else + return nullptr; +#endif + } + + static void AddRegisters(PtraceArch& arch, int regset, size_t size, const std::vector& names, const std::vector& indices) { @@ -122,8 +182,8 @@ namespace BinaryNinjaDebugger { arch.regsets = {NT_PRSTATUS, NT_PRFPREG}; arch.breakpointInstruction = {0xcc}; arch.breakpointPcAdjust = 1; - static X86HwDebug hwDebug(848); - arch.hwDebug = &hwDebug; + arch.hwDebug = NativeX86HwDebug(); + arch.sysemu = true; // The order of user_regs_struct: r15 r14 r13 r12 rbp rbx r11 r10 r9 r8 rax rcx rdx rsi rdi orig_rax rip cs // eflags rsp ss fs_base gs_base ds es fs gs. The registers are listed in the order GDB uses. @@ -155,8 +215,8 @@ namespace BinaryNinjaDebugger { arch.regsets = {NT_PRSTATUS}; arch.breakpointInstruction = {0xcc}; arch.breakpointPcAdjust = 1; - static X86HwDebug hwDebug(252); - arch.hwDebug = &hwDebug; + arch.hwDebug = NativeX86HwDebug(); + arch.sysemu = true; // The order of the 32-bit user_regs_struct: ebx ecx edx esi edi ebp eax xds xes xfs xgs orig_eax eip xcs // eflags esp xss diff --git a/core/adapters/ptrace/ptracearch.h b/core/adapters/ptrace/ptracearch.h index 28e11e2f..7fb9d706 100644 --- a/core/adapters/ptrace/ptracearch.h +++ b/core/adapters/ptrace/ptracearch.h @@ -72,10 +72,38 @@ namespace BinaryNinjaDebugger { std::vector breakpointInstruction; size_t breakpointPcAdjust = 0; PtraceHwDebug* hwDebug = nullptr; + // Whether PTRACE_SYSEMU works. It began on x86. + bool sysemu = false; + // Whether a register that is part of another one is at the low or the high end of it, which is what the sub-registers + // that are derived rely on + bool littleEndian = true; const PtraceRegister* Find(const std::string& registerName) const; }; + // What an architecture says about one of its registers. Only the registers of the table have a place in the target, so + // this is where the rest of them come from: a register that is part of another one is found in the same bytes. + struct PtraceRegisterDescription + { + std::string name; + // The register that this one is part of. It is the register itself for one that is not part of another. + std::string parent; + // Where in the parent, in bytes from its low end + size_t offset = 0; + size_t size = 0; + }; + + // The registers that the description has and the table does not, and that are inside a register of the table: `eax`, + // `al` and `ah` for `rax`. They are located as the parent is. Anything else is left out, which is the registers + // that are not in the table, and the ones that would reach outside of their parent. + std::vector DeriveSubRegisters( + const PtraceArch& arch, const std::vector& described); + + // Where the description and the table disagree about a register that both have, one message for each. It is only + // for the log: a register of the table is always read as the table says. + std::vector CheckRegisterSizes( + const PtraceArch& arch, const std::vector& described); + const PtraceArch& PtraceArchX86_64(); const PtraceArch& PtraceArchX86(); diff --git a/core/adapters/ptrace/ptraceelf.cpp b/core/adapters/ptrace/ptraceelf.cpp index df9f9e44..caaffade 100644 --- a/core/adapters/ptrace/ptraceelf.cpp +++ b/core/adapters/ptrace/ptraceelf.cpp @@ -83,6 +83,10 @@ namespace BinaryNinjaDebugger { size_t length = strnlen(stringData.data() + symbol.st_name, stringData.size() - symbol.st_name); ElfSymbol result; result.name.assign(stringData.data() + symbol.st_name, length); + // The linker writes the version into the name of some symbols of .symtab, `stdin@@GLIBC_2.2.5` + auto version = result.name.find('@'); + if (version != std::string::npos && version > 0) + result.name.resize(version); result.address = symbol.st_value; result.size = symbol.st_size; result.isFunction = isFunction; @@ -197,4 +201,26 @@ namespace BinaryNinjaDebugger { return fallback; } + const ElfSymbol* FindElfFunctionByName(const ElfInfo& info, const std::string& name, bool* ambiguous) + { + if (ambiguous) + *ambiguous = false; + + const ElfSymbol* found = nullptr; + for (const auto& symbol : info.symbols) + { + if (!symbol.isFunction || symbol.name != name) + continue; + + if (found && found->address != symbol.address) + { + if (ambiguous) + *ambiguous = true; + return nullptr; + } + found = &symbol; + } + return found; + } + } // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceelf.h b/core/adapters/ptrace/ptraceelf.h index 5202cbf3..e2cec6a5 100644 --- a/core/adapters/ptrace/ptraceelf.h +++ b/core/adapters/ptrace/ptraceelf.h @@ -47,4 +47,8 @@ namespace BinaryNinjaDebugger { // The symbol that contains an address of the file, or nullptr const ElfSymbol* FindElfSymbol(const ElfInfo& info, uint64_t address); + + // The function with this name, if there is exactly one. `ambiguous` says that there are several, at different + // addresses. + const ElfSymbol* FindElfFunctionByName(const ElfInfo& info, const std::string& name, bool* ambiguous = nullptr); } // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceengine.cpp b/core/adapters/ptrace/ptraceengine.cpp index 283a8300..8c768370 100644 --- a/core/adapters/ptrace/ptraceengine.cpp +++ b/core/adapters/ptrace/ptraceengine.cpp @@ -16,16 +16,19 @@ limitations under the License. #include "ptraceengine.h" #include +#include #include #include #include #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -35,8 +38,62 @@ limitations under the License. #include #include +// Older headers do not have these +#ifndef PTRACE_SYSEMU +#define PTRACE_SYSEMU 31 +#endif +#ifndef PTRACE_GET_SYSCALL_INFO +#define PTRACE_GET_SYSCALL_INFO 0x420e +#endif +#ifndef PTRACE_SET_SYSCALL_INFO +#define PTRACE_SET_SYSCALL_INFO 0x4212 +#endif +#ifndef PTRACE_O_TRACESYSGOOD +#define PTRACE_O_TRACESYSGOOD 1 +#endif + namespace BinaryNinjaDebugger { + // struct ptrace_syscall_info of the kernel + struct KernelSyscallInfo + { + uint8_t op; + uint8_t reserved; + uint16_t flags; + uint32_t arch; + uint64_t instructionPointer; + uint64_t stackPointer; + union + { + struct + { + uint64_t number; + uint64_t args[6]; + } entry; + struct + { + int64_t returnValue; + uint8_t isError; + } exit; + struct + { + uint64_t number; + uint64_t args[6]; + uint32_t data; + } seccomp; + }; + }; + + static_assert(sizeof(KernelSyscallInfo) == 88, "struct ptrace_syscall_info"); + + enum : uint8_t + { + KernelSyscallInfoNone = 0, + KernelSyscallInfoEntry = 1, + KernelSyscallInfoExit = 2, + KernelSyscallInfoSeccomp = 3 + }; + static bool IsSilentSignal(int signal) { switch (signal) @@ -70,7 +127,7 @@ namespace BinaryNinjaDebugger { { if (m_tracerThread.joinable()) { - RunOnTracer([this] { return DoKill(); }); + RunOnTracer([this] { return m_attached ? DoDetach() : DoKill(); }); { std::lock_guard lock(m_taskMutex); m_shutdown = true; @@ -113,6 +170,19 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::Attach(uint32_t pid, std::string& error, const PtraceArch* arch) + { + m_options.arch = arch; + m_attachPid = pid; + m_attached = true; + auto result = m_launchResult.get_future(); + m_eventThread = std::thread(&PtraceEngine::EventMain, this); + m_tracerThread = std::thread(&PtraceEngine::TracerMain, this); + error = result.get(); + return error.empty(); + } + + bool PtraceEngine::RunOnTracer(std::function function) { auto task = std::make_shared>(std::move(function)); @@ -144,6 +214,26 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::ResumeToSyscall(SyscallMode mode) + { + if (mode == SyscallMode::None) + return false; + return RunOnTracer([this, mode] { return DoResume(false, 0, mode); }); + } + + + bool PtraceEngine::GetSyscallInfo(uint32_t tid, SyscallInfo& info) + { + return RunOnTracer([this, tid, &info] { return DoGetSyscallInfo(tid, info); }); + } + + + bool PtraceEngine::SetSyscallInfo(uint32_t tid, const SyscallInfo& info) + { + return RunOnTracer([this, tid, &info] { return DoSetSyscallInfo(tid, info); }); + } + + bool PtraceEngine::Kill() { return RunOnTracer([this] { return DoKill(); }); @@ -161,27 +251,39 @@ namespace BinaryNinjaDebugger { if (!m_publishedRunning) return false; - m_interruptRequested = true; - return kill(m_pid, SIGSTOP) == 0; + m_interruptWanted = true; + + // One signal on its way is enough, because the stop that it causes is the one that is wanted + if (m_interruptInFlight++ > 0) + { + m_interruptInFlight--; + return true; + } + if (kill(m_pid, SIGSTOP) != 0) + { + m_interruptInFlight--; + return false; + } + return true; } bool PtraceEngine::WriteInput(const std::string& data) { - if (m_masterFd < 0) + if (m_masterFd < 0 || m_ioStop) return false; - size_t written = 0; - while (written < data.size()) + // Input is drained by the I/O thread. Writing synchronously to the nonblocking PTY would either spin on EAGAIN + // or block a debugger thread while the target is stopped. Keep the queue bounded so an unresponsive target + // cannot make the debugger consume memory without limit. + constexpr size_t maxPendingInput = 8 << 20; + std::lock_guard lock(m_inputMutex); + if (data.size() > maxPendingInput - m_pendingInputBytes) + return false; + if (!data.empty()) { - auto count = write(m_masterFd, data.data() + written, data.size() - written); - if (count < 0) - { - if (errno == EINTR || errno == EAGAIN) - continue; - return false; - } - written += count; + m_pendingInputBytes += data.size(); + m_inputQueue.push_back(data); } return true; } @@ -385,6 +487,12 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::DiscardBreakpoint(uint64_t address) + { + return RunOnTracer([this, address] { return DoDiscardBreakpoint(address); }); + } + + bool PtraceEngine::AddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size) { return RunOnTracer([this, address, type, size] { return DoAddHardwareBreakpoint(address, type, size); }); @@ -397,6 +505,24 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::WaitForDetachedExit(int& status, std::chrono::milliseconds timeout) + { + std::shared_ptr exit; + { + std::lock_guard lock(m_infoMutex); + exit = m_detachedExit; + } + if (!exit) + return false; + + std::unique_lock lock(exit->mutex); + if (!exit->cv.wait_for(lock, timeout, [&exit] { return exit->done; })) + return false; + status = exit->status; + return true; + } + + std::vector PtraceEngine::GetThreads() const { std::lock_guard lock(m_infoMutex); @@ -470,7 +596,16 @@ namespace BinaryNinjaDebugger { char buffer[4096]; while (true) { - pollfd fd {m_masterFd, POLLIN, 0}; + if (m_ioStop) + return; + + short events = POLLIN; + { + std::lock_guard lock(m_inputMutex); + if (!m_inputQueue.empty()) + events |= POLLOUT; + } + pollfd fd {m_masterFd, events, 0}; int ready = poll(&fd, 1, 50); if (ready == 0) { @@ -485,18 +620,48 @@ namespace BinaryNinjaDebugger { return; } - auto count = read(m_masterFd, buffer, sizeof(buffer)); - if (count > 0) + if (fd.revents & POLLOUT) { - Event event; - event.type = OutputEvent; - event.data.assign(buffer, count); - PushEvent(event); + bool writeFailed = false; + std::lock_guard lock(m_inputMutex); + if (!m_inputQueue.empty()) + { + const auto& input = m_inputQueue.front(); + auto count = write(m_masterFd, input.data() + m_inputOffset, input.size() - m_inputOffset); + if (count > 0) + { + m_inputOffset += count; + m_pendingInputBytes -= count; + if (m_inputOffset == input.size()) + { + m_inputQueue.pop_front(); + m_inputOffset = 0; + } + } + else if (count < 0 && errno != EINTR && errno != EAGAIN) + writeFailed = true; + } + if (writeFailed) + return; } - else if (count == 0 || (errno != EINTR && errno != EAGAIN)) + + if (fd.revents & POLLIN) { - return; + auto count = read(m_masterFd, buffer, sizeof(buffer)); + if (count > 0) + { + Event event; + event.type = OutputEvent; + event.data.assign(buffer, count); + PushEvent(event); + } + else if (count == 0 || (errno != EINTR && errno != EAGAIN)) + { + return; + } } + else if (fd.revents & (POLLERR | POLLHUP | POLLNVAL)) + return; } } @@ -521,11 +686,73 @@ namespace BinaryNinjaDebugger { if (m_masterFd < 0 || grantpt(m_masterFd) != 0 || unlockpt(m_masterFd) != 0 || ptsname_r(m_masterFd, slaveName, sizeof(slaveName)) != 0) return std::string("failed to open a pseudo terminal: ") + strerror(errno); + + winsize size = {}; + size.ws_row = m_options.rows; + size.ws_col = m_options.columns; + ioctl(m_masterFd, TIOCSWINSZ, &size); + } + + // The descriptors that we keep for ourselves are kept above every one that the redirects name, so that setting + // those up cannot get in their way + int firstFreeFd = 10; + for (const auto& redirect : m_options.redirects) + { + firstFreeFd = std::max(firstFreeFd, redirect.fd + 1); + if (redirect.kind == FdRedirect::Duplicate) + firstFreeFd = std::max(firstFreeFd, redirect.source + 1); + } + + std::vector redirectFds(m_options.redirects.size(), -1); + auto closeRedirectFds = [&redirectFds]() { + for (int fd : redirectFds) + { + if (fd >= 0) + close(fd); + } + }; + + for (size_t i = 0; i < m_options.redirects.size(); i++) + { + const auto& redirect = m_options.redirects[i]; + if (redirect.kind != FdRedirect::OpenFile) + continue; + + std::string redirectPath = redirect.path; + if (workingDir && !redirectPath.empty() && redirectPath[0] != '/') + redirectPath = std::string(workingDir) + "/" + redirectPath; + + int fd = open(redirectPath.c_str(), redirect.flags | O_CLOEXEC, 0666); + int moved = fd >= 0 ? fcntl(fd, F_DUPFD_CLOEXEC, firstFreeFd) : -1; + int error = errno; + if (fd >= 0) + close(fd); + if (moved < 0) + { + closeRedirectFds(); + return "failed to open " + redirectPath + " for file descriptor " + std::to_string(redirect.fd) + ": " + + strerror(error); + } + redirectFds[i] = moved; } int errorPipe[2]; if (pipe2(errorPipe, O_CLOEXEC) != 0) + { + closeRedirectFds(); return std::string("failed to create a pipe: ") + strerror(errno); + } + int movedPipe = fcntl(errorPipe[1], F_DUPFD_CLOEXEC, firstFreeFd); + if (movedPipe < 0) + { + int error = errno; + close(errorPipe[0]); + close(errorPipe[1]); + closeRedirectFds(); + return std::string("failed to create a pipe: ") + strerror(error); + } + close(errorPipe[1]); + errorPipe[1] = movedPipe; pid_t pid = fork(); if (pid < 0) @@ -533,6 +760,7 @@ namespace BinaryNinjaDebugger { int error = errno; close(errorPipe[0]); close(errorPipe[1]); + closeRedirectFds(); return std::string("failed to fork: ") + strerror(error); } @@ -556,6 +784,25 @@ namespace BinaryNinjaDebugger { close(slave); } + for (size_t i = 0; i < m_options.redirects.size(); i++) + { + const auto& redirect = m_options.redirects[i]; + switch (redirect.kind) + { + case FdRedirect::OpenFile: + if (dup2(redirectFds[i], redirect.fd) < 0) + ChildFail(errorPipe[1]); + break; + case FdRedirect::Duplicate: + if (dup2(redirect.source, redirect.fd) < 0) + ChildFail(errorPipe[1]); + break; + case FdRedirect::Close: + close(redirect.fd); + break; + } + } + if (workingDir && chdir(workingDir) != 0) ChildFail(errorPipe[1]); if (m_options.disableAslr) @@ -568,6 +815,7 @@ namespace BinaryNinjaDebugger { } close(errorPipe[1]); + closeRedirectFds(); int childError = 0; ssize_t count; do @@ -586,13 +834,27 @@ namespace BinaryNinjaDebugger { if (waitpid(pid, &status, __WALL) < 0 || !WIFSTOPPED(status)) return "the target exited before it could be traced"; - ptrace(PTRACE_SETOPTIONS, pid, nullptr, (void*)(uintptr_t)(PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE)); + if (ptrace(PTRACE_SETOPTIONS, pid, nullptr, + (void*)(uintptr_t)(PTRACE_O_EXITKILL | PTRACE_O_TRACECLONE | PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK + | PTRACE_O_TRACEVFORKDONE | PTRACE_O_TRACEEXEC | PTRACE_O_TRACESYSGOOD)) != 0) + { + int error = errno; + kill(pid, SIGKILL); + while (waitpid(pid, nullptr, __WALL) < 0 && errno == EINTR) + {} + return std::string("failed to configure ptrace options: ") + strerror(error); + } m_pid = pid; - m_memFd = open(("/proc/" + std::to_string(pid) + "/mem").c_str(), O_RDWR | O_CLOEXEC); - m_arch = m_options.arch ? m_options.arch : DetectPtraceArch(pid); - if (m_arch && m_arch->hwDebug) - m_hardwareSlots.resize(m_arch->hwDebug->SlotCount()); + auto adoptError = AdoptTarget(); + if (!adoptError.empty()) + { + kill(pid, SIGKILL); + while (waitpid(pid, nullptr, __WALL) < 0 && errno == EINTR) + {} + m_pid = -1; + return adoptError; + } ThreadInfo info; info.stopped = true; m_threads[pid] = info; @@ -613,9 +875,185 @@ namespace BinaryNinjaDebugger { } + std::string PtraceEngine::AdoptTarget() + { + m_memFd = open(("/proc/" + std::to_string(m_pid) + "/mem").c_str(), O_RDWR | O_CLOEXEC); + if (m_memFd < 0) + return "failed to open target memory: " + std::string(strerror(errno)); + + m_arch = m_options.arch ? m_options.arch : DetectPtraceArch(m_pid); + if (!m_arch) + { + close(m_memFd); + m_memFd = -1; + return "unsupported target architecture"; + } + if (m_arch && m_arch->hwDebug) + m_hardwareSlots.resize(m_arch->hwDebug->SlotCount()); + return ""; + } + + + static std::string AttachErrorMessage(pid_t pid, int error) + { + std::string message = "failed to attach to process " + std::to_string(pid) + ": " + strerror(error); + if (error == ESRCH) + return message; + + std::string line; + std::ifstream status("/proc/" + std::to_string(pid) + "/status"); + while (std::getline(status, line)) + { + if (line.rfind("TracerPid:", 0) == 0 && atoi(line.c_str() + 10) > 0) + return message + " (it is already being traced by process " + std::to_string(atoi(line.c_str() + 10)) + ")"; + } + + if (error == EPERM || error == EACCES) + { + std::ifstream yama("/proc/sys/kernel/yama/ptrace_scope"); + int scope = 0; + if (yama >> scope && scope > 0) + message += " (kernel.yama.ptrace_scope is " + std::to_string(scope) + + ", so only descendants of the debugger can be traced without extra privileges)"; + } + return message; + } + + + std::string PtraceEngine::AttachToProcess() + { + pid_t pid = m_attachPid; + auto listThreads = [pid]() { + std::vector tids; + std::error_code error; + for (const auto& entry : std::filesystem::directory_iterator("/proc/" + std::to_string(pid) + "/task", error)) + { + pid_t tid = atoi(entry.path().filename().c_str()); + if (tid > 0) + tids.push_back(tid); + } + return tids; + }; + + if (listThreads().empty()) + return "failed to attach to process " + std::to_string(pid) + ": there is no such process"; + + std::vector attached; + auto detachAll = [&attached]() { + for (pid_t tid : attached) + ptrace(PTRACE_DETACH, tid, nullptr, nullptr); + }; + + // A thread can be created while the others are being stopped, so go over the list until nothing is new + bool foundNew = true; + for (int round = 0; foundNew && round < 32; round++) + { + foundNew = false; + for (pid_t tid : listThreads()) + { + if (std::find(attached.begin(), attached.end(), tid) != attached.end()) + continue; + foundNew = true; + + if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr) != 0) + { + int error = errno; + if (tid != pid && error == ESRCH) + continue; + detachAll(); + return AttachErrorMessage(pid, error); + } + + // A signal can reach the thread before the SIGSTOP that attaching sends. It is passed on, and the + // SIGSTOP comes after it. + bool stopped = false; + bool gone = false; + for (int attempt = 0; attempt < 16 && !stopped && !gone; attempt++) + { + int status = 0; + if (waitpid(tid, &status, __WALL) < 0) + { + if (errno == EINTR) + continue; + gone = true; + } + else if (WIFEXITED(status) || WIFSIGNALED(status)) + { + gone = true; + } + else if (WIFSTOPPED(status)) + { + int signal = WSTOPSIG(status); + if (signal == SIGSTOP) + stopped = true; + else + ptrace(PTRACE_CONT, tid, nullptr, (void*)(intptr_t)signal); + } + } + + if (!stopped) + { + if (!gone) + { + attached.push_back(tid); + detachAll(); + return "failed to attach to process " + std::to_string(pid) + ": thread " + std::to_string(tid) + + " did not stop"; + } + if (tid == pid) + { + detachAll(); + return "failed to attach to process " + std::to_string(pid) + ": it exited"; + } + continue; + } + attached.push_back(tid); + } + } + + for (pid_t tid : attached) + { + if (ptrace(PTRACE_SETOPTIONS, tid, nullptr, + (void*)(uintptr_t)(PTRACE_O_TRACECLONE | PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK + | PTRACE_O_TRACEVFORKDONE | PTRACE_O_TRACEEXEC | PTRACE_O_TRACESYSGOOD)) != 0) + { + int error = errno; + detachAll(); + return "failed to configure ptrace options for thread " + std::to_string(tid) + ": " + + strerror(error); + } + } + + m_pid = pid; + auto adoptError = AdoptTarget(); + if (!adoptError.empty()) + { + detachAll(); + m_pid = -1; + return adoptError; + } + for (pid_t tid : attached) + { + ThreadInfo info; + info.stopped = true; + m_threads[tid] = info; + } + auto& leader = m_threads[pid]; + leader.atReportedStop = ReadPc(pid, leader.reportedPc); + Publish(); + + Event event; + event.type = StoppedEvent; + event.tid = pid; + event.signal = SIGSTOP; + PushEvent(event); + return ""; + } + + void PtraceEngine::TracerMain() { - std::string error = Spawn(); + std::string error = m_attached ? AttachToProcess() : Spawn(); m_launchResult.set_value(error); int idle = 0; @@ -712,29 +1150,82 @@ namespace BinaryNinjaDebugger { } - // Works out why a thread stopped with SIGTRAP. Returns false if the stop is not worth reporting. + // Works out who owns a SIGTRAP. Returns false if an internal trap is not worth reporting. bool PtraceEngine::ClassifyTrap(pid_t tid, ThreadInfo& info, Classified& result) { siginfo_t signalInfo {}; bool haveInfo = ptrace(PTRACE_GETSIGINFO, tid, nullptr, &signalInfo) == 0; int code = haveInfo ? signalInfo.si_code : 0; + // Delivering a caught signal with PTRACE_SINGLESTEP stops after the kernel has entered its handler. Ordinarily + // that is TRAP_TRACE. When the delivered signal is SIGTRAP, Linux can retain its original non-positive si_code; + // in that case the changed PC proves that signal delivery entered the handler. + bool handlerEntry = info.handlerSignal && haveInfo && code == TRAP_TRACE; + if (info.handlerSignal && info.handlerResumePcValid) + { + uint64_t pc = 0; + handlerEntry |= ReadPc(tid, pc) && pc != info.handlerResumePc; + } + if (handlerEntry) + { + result.signalHandler = info.handlerSignal; + info.handlerSignal = 0; + info.handlerResumePcValid = false; + result.trapOrigin = TrapOrigin::SignalHandler; + return true; + } + + // Signals explicitly sent by the target are never debugger breakpoints, even if the interrupted PC happens to be + // next to one. AArch64 also produces code-zero, pid-zero traps for some requested single steps, so SI_USER only + // identifies a sender when the kernel supplied one. + bool sentSignal = haveInfo && (code < 0 || (code == SI_USER && signalInfo.si_pid != 0)); + if (sentSignal) + { + info.pendingSignal = SIGTRAP; + result.trapOrigin = TrapOrigin::Target; + return true; + } + if (code == TRAP_HWBKPT) { - if (m_arch && m_arch->hwDebug) + bool ours = std::any_of(m_hardwareSlots.begin(), m_hardwareSlots.end(), + [](const HardwareSlot& slot) { return slot.used; }); + if (ours && m_arch && m_arch->hwDebug) + { m_arch->hwDebug->OnTrap(tid); - result.hardware = true; + result.hardware = true; + result.trapOrigin = TrapOrigin::HardwareBreakpoint; + } + else + { + info.pendingSignal = SIGTRAP; + result.trapOrigin = TrapOrigin::Target; + } return true; } if (code == TRAP_TRACE) { - result.stepTrap = true; + if (info.stepping) + { + result.stepTrap = true; + result.trapOrigin = TrapOrigin::SingleStep; + } + else + { + info.pendingSignal = SIGTRAP; + result.trapOrigin = TrapOrigin::Target; + } return true; } + // Architectures report a CPU breakpoint as TRAP_BRKPT or, notably for x86 int3, SI_KERNEL. Only those codes may + // be matched by PC: a user-generated SIGTRAP can stop at the same PC by coincidence. + bool breakpointCode = !haveInfo || code == TRAP_BRKPT || code == SI_KERNEL; + bool unownedTrapInstruction = haveInfo && code == TRAP_BRKPT; uint64_t pc = 0; - if (m_arch && !m_arch->breakpointInstruction.empty() && ReadPc(tid, pc)) + if (breakpointCode && m_arch && !m_arch->breakpointInstruction.empty() && ReadPc(tid, pc) + && pc >= m_arch->breakpointPcAdjust) { uint64_t address = pc - m_arch->breakpointPcAdjust; bool ours; @@ -751,16 +1242,35 @@ namespace BinaryNinjaDebugger { WritePc(tid, address); // A thread that trapped on a breakpoint that has just been removed only needs to run again if (removed) + { + result.trapOrigin = TrapOrigin::Internal; return false; + } result.breakpoint = true; + result.trapOrigin = TrapOrigin::SoftwareBreakpoint; return true; } + + // SI_KERNEL is also used for some debugger-requested traps. It is target-owned when the instruction at the + // adjusted PC is the architecture's trap opcode. TRAP_BRKPT itself is already definitive. + std::vector instruction(m_arch->breakpointInstruction.size()); + unownedTrapInstruction |= code == SI_KERNEL && RawReadMemory(address, instruction.data(), instruction.size()) + && instruction == m_arch->breakpointInstruction; } - // Stepping over a system call traps like a breakpoint on x86, so this is a step if we asked for one - if (info.stepping) + // Some kernels report a requested step around a syscall with a generic kernel trap rather than TRAP_TRACE. Preserve + // that compatibility fallback, but never let it consume a trap instruction or an explicitly sent signal. + if (info.stepping && !unownedTrapInstruction) + { result.stepTrap = true; + result.trapOrigin = TrapOrigin::SingleStep; + } + else + { + info.pendingSignal = SIGTRAP; + result.trapOrigin = TrapOrigin::Target; + } return true; } @@ -803,9 +1313,35 @@ namespace BinaryNinjaDebugger { Publish(); return result; } + if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK) + { + unsigned long child = 0; + ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &child); + HandleFork((pid_t)child, event == PTRACE_EVENT_VFORK); + return result; + } + if (event == PTRACE_EVENT_EXEC) + return HandleExec(tid); + if (event == PTRACE_EVENT_VFORK_DONE) + { + if (m_vforkPending > 0 && --m_vforkPending == 0) + ResumeBreakpointsAfterVfork(); + return result; + } if (event != 0) return result; + // A stop at a system call, which only happens to a thread that was resumed to one + if (signal == (SIGTRAP | 0x80)) + { + endGuard(true); + result.kind = StopKind::Report; + result.signal = SIGTRAP; + result.syscall = true; + result.trapOrigin = TrapOrigin::Syscall; + return result; + } + if (signal == SIGSTOP) { if (info.awaitingInitialStop) @@ -819,11 +1355,16 @@ namespace BinaryNinjaDebugger { info.expectedStops--; return result; } - if (m_interruptRequested.exchange(false)) + if (m_interruptInFlight > 0) { - endGuard(true); - result.kind = StopKind::Report; - result.interrupted = true; + m_interruptInFlight--; + // The pause may have been given by another stop since, and then this signal is only left over + if (m_interruptWanted.exchange(false)) + { + endGuard(true); + result.kind = StopKind::Report; + result.interrupted = true; + } return result; } } @@ -841,6 +1382,9 @@ namespace BinaryNinjaDebugger { } else { + // A different signal interrupted any outstanding single-step-to-handler operation. + info.handlerSignal = 0; + info.handlerResumePcValid = false; info.pendingSignal = signal; } @@ -855,10 +1399,56 @@ namespace BinaryNinjaDebugger { { auto& info = m_threads[tid]; int signal = info.pendingSignal; + bool step = info.stepping; + + // Resuming with a single step and a signal delivers the signal and stops at the first instruction of its + // handler + int handlerSignal = 0; + uint64_t handlerResumePc = 0; + bool handlerResumePcValid = false; + if (signal && !step && m_debugSignalHandlers && HasSignalHandler(signal)) + { + step = true; + handlerSignal = signal; + handlerResumePcValid = ReadPc(tid, handlerResumePc); + } + + int request = PTRACE_CONT; + if (step) + request = PTRACE_SINGLESTEP; + else if (m_syscallMode == SyscallMode::Trace) + request = PTRACE_SYSCALL; + else if (m_syscallMode == SyscallMode::Emulate) + request = PTRACE_SYSEMU; + if (ptrace((__ptrace_request)request, tid, nullptr, (void*)(intptr_t)signal) != 0 && errno != ESRCH) + return false; + + // Only commit the transition after the kernel accepted it. Otherwise a stopped thread would disappear from + // future resume attempts, and a pending signal could be lost. info.pendingSignal = 0; info.stopped = false; - auto request = info.stepping ? PTRACE_SINGLESTEP : PTRACE_CONT; - return ptrace(request, tid, nullptr, (void*)(intptr_t)signal) == 0 || errno == ESRCH; + info.handlerSignal = handlerSignal; + info.handlerResumePc = handlerResumePc; + info.handlerResumePcValid = handlerResumePcValid; + info.atReportedStop = false; + return true; + } + + + // The signals that the target has a handler for are the ones that /proc lists as caught + bool PtraceEngine::HasSignalHandler(int signal) + { + std::ifstream file("/proc/" + std::to_string(m_pid) + "/status"); + std::string line; + while (std::getline(file, line)) + { + if (line.rfind("SigCgt:", 0) != 0) + continue; + + uint64_t caught = strtoull(line.c_str() + strlen("SigCgt:"), nullptr, 16); + return signal >= 1 && signal <= 64 && (caught >> (signal - 1)) & 1; + } + return false; } @@ -871,19 +1461,26 @@ namespace BinaryNinjaDebugger { // Lifts the breakpoints at an address, so that a thread can execute the instruction there - void PtraceEngine::BeginGuard(pid_t tid, uint64_t address) + bool PtraceEngine::BeginGuard(pid_t tid, uint64_t address) { auto& info = m_threads[tid]; info.guardAddress = address; + bool success = true; { std::lock_guard lock(m_breakpointMutex); auto it = m_breakpoints.find(address); if (it != m_breakpoints.end() && it->second.inserted) { - RawWriteMemory(address, it->second.original.data(), it->second.original.size()); - it->second.inserted = false; - info.guardSoftware = true; + if (RawWriteMemory(address, it->second.original.data(), it->second.original.size())) + { + it->second.inserted = false; + info.guardSoftware = true; + } + else + { + success = false; + } } } @@ -895,26 +1492,40 @@ namespace BinaryNinjaDebugger { if (slot.used && (info.hardwareBeforeAccess || (slot.type == PtraceHwType::Execute && slot.address == address))) { - m_arch->hwDebug->Clear(tid, i); - info.guardSlots.push_back(i); + if (m_arch->hwDebug->Clear(tid, i)) + info.guardSlots.push_back(i); + else + success = false; } } + return success; } - void PtraceEngine::EndGuard(pid_t tid, bool threadAlive) + bool PtraceEngine::EndGuard(pid_t tid, bool threadAlive) { auto& info = m_threads[tid]; + bool success = true; if (info.guardSoftware) { - info.guardSoftware = false; std::lock_guard lock(m_breakpointMutex); auto it = m_breakpoints.find(info.guardAddress); - if (it != m_breakpoints.end() && !it->second.inserted) + if (it != m_breakpoints.end() && !it->second.inserted && !it->second.suspended) { - RawWriteMemory( - info.guardAddress, m_arch->breakpointInstruction.data(), m_arch->breakpointInstruction.size()); - it->second.inserted = true; + if (threadAlive && !RawWriteMemory( + info.guardAddress, m_arch->breakpointInstruction.data(), m_arch->breakpointInstruction.size())) + { + success = false; + } + else + { + it->second.inserted = threadAlive; + info.guardSoftware = false; + } + } + else + { + info.guardSoftware = false; } } @@ -924,9 +1535,13 @@ namespace BinaryNinjaDebugger { for (size_t index : slots) { const auto& slot = m_hardwareSlots[index]; - if (threadAlive && slot.used) - m_arch->hwDebug->Set(tid, index, slot.address, slot.type, slot.size); + if (threadAlive && slot.used && !m_arch->hwDebug->Set(tid, index, slot.address, slot.type, slot.size)) + { + info.guardSlots.push_back(index); + success = false; + } } + return success; } @@ -958,10 +1573,18 @@ namespace BinaryNinjaDebugger { if (it == m_threads.end() || !it->second.stopped || !ReadPc(tid, pc)) continue; - BeginGuard(tid, pc); + if (!BeginGuard(tid, pc)) + { + EndGuard(tid, true); + return false; + } it->second.stepping = true; m_stepOverTid = tid; - return ResumeThread(tid); + if (ResumeThread(tid)) + return true; + it->second.stepping = false; + EndGuard(tid, true); + return false; } m_stepOverTid = -1; @@ -969,6 +1592,138 @@ namespace BinaryNinjaDebugger { } + // A child of the target starts out as a copy of it, breakpoints included, and it is not ours to debug. So the + // breakpoints come out of it, and it is let go. + void PtraceEngine::HandleFork(pid_t child, bool sharedMemory) + { + // It is stopped from the start, and has to be seen to before it can be let go + int status = 0; + pid_t result; + do + { + result = waitpid(child, &status, __WALL); + } while (result < 0 && errno == EINTR); + if (result < 0 || !WIFSTOPPED(status)) + return; + + { + std::lock_guard lock(m_breakpointMutex); + if (sharedMemory) + { + // There is only one memory, so the breakpoints are out of the target for as long as the child uses it + for (auto& [address, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + + RawWriteMemory(address, breakpoint.original.data(), breakpoint.original.size()); + breakpoint.inserted = false; + breakpoint.suspended = true; + } + m_vforkPending++; + } + else + { + int fd = open(("/proc/" + std::to_string(child) + "/mem").c_str(), O_RDWR | O_CLOEXEC); + if (fd >= 0) + { + for (const auto& [address, breakpoint] : m_breakpoints) + { + { + if (!breakpoint.inserted) + continue; + + // Best effort: a child that cannot be written to is simply let go + [[maybe_unused]] auto written = + pwrite(fd, breakpoint.original.data(), breakpoint.original.size(), address); + } + } + close(fd); + } + } + } + + ptrace(PTRACE_DETACH, child, nullptr, nullptr); + } + + + // The target has started another program. Nothing of the old one is left: not its threads, its memory, its + // breakpoints or its debug registers. So this starts over, and the stop is reported so that the owner can set the + // new program up before it runs. + PtraceEngine::Classified PtraceEngine::HandleExec(pid_t tid) + { + // Every thread but one is gone, and that one is the leader from now on, whichever thread it was before + std::vector gone; + bool stepping = false; + int expectedStops = 0; + for (const auto& [id, info] : m_threads) + { + if (id != m_pid) + gone.push_back(id); + if (id == tid) + stepping = info.stepping; + if (id == m_pid) + expectedStops = info.expectedStops; + } + + ThreadInfo leader; + leader.stopped = true; + leader.stepping = stepping; + leader.expectedStops = expectedStops; + m_threads.clear(); + m_threads[m_pid] = leader; + + // Whatever is left of the threads that were killed + for (pid_t id : gone) + { + int status; + waitpid(id, &status, __WALL | WNOHANG); + } + + { + std::lock_guard lock(m_breakpointMutex); + int fd = open(("/proc/" + std::to_string(m_pid) + "/mem").c_str(), O_RDWR | O_CLOEXEC); + if (m_memFd >= 0) + close(m_memFd); + m_memFd = fd; + m_breakpoints.clear(); + m_arch = m_options.arch ? m_options.arch : DetectPtraceArch(m_pid); + } + + m_recentlyRemoved.clear(); + m_stepOverQueue.clear(); + m_stepOverTid = -1; + m_vforkPending = 0; + m_hardwareSlots.assign(m_arch && m_arch->hwDebug ? m_arch->hwDebug->SlotCount() : 0, HardwareSlot()); + Publish(); + + Classified result; + result.kind = StopKind::Report; + result.signal = SIGTRAP; + result.exec = true; + result.tid = m_pid; + return result; + } + + + void PtraceEngine::ResumeBreakpointsAfterVfork() + { + std::lock_guard lock(m_breakpointMutex); + const auto& instruction = m_arch->breakpointInstruction; + for (auto& [address, breakpoint] : m_breakpoints) + { + if (!breakpoint.suspended) + continue; + + // The child may have changed what is there + breakpoint.suspended = false; + if (RawReadMemory(address, breakpoint.original.data(), instruction.size()) + && RawWriteMemory(address, instruction.data(), instruction.size())) + breakpoint.inserted = true; + } + } + + void PtraceEngine::ApplyHardwareToThread(pid_t tid) { for (size_t i = 0; i < m_hardwareSlots.size(); i++) @@ -1016,7 +1771,7 @@ namespace BinaryNinjaDebugger { } StopAll(); if (!m_done) - FinishStop(tid, stop); + FinishStop(stop.tid ? stop.tid : tid, stop); break; } } @@ -1067,18 +1822,28 @@ namespace BinaryNinjaDebugger { event.interrupted = stop.interrupted; event.breakpoint = stop.breakpoint; event.hardware = stop.hardware; - event.singleStep = m_threads[tid].stepping; + event.trapOrigin = stop.trapOrigin; + event.exec = stop.exec; + event.signalHandler = stop.signalHandler; + event.syscall = stop.syscall; + event.singleStep = stop.stepTrap; for (auto& [id, info] : m_threads) info.stepping = false; // Once everything is stopped, no thread can still trap on a breakpoint that was removed m_recentlyRemoved.clear(); + // Any stop is a pause, so a request for one that has not been seen yet is answered + m_interruptWanted = false; auto& info = m_threads[tid]; info.atReportedStop = ReadPc(tid, info.reportedPc); info.hardwareBeforeAccess = stop.hardware && m_arch && m_arch->hwDebug && m_arch->hwDebug->DataTrapsBeforeAccess(); + // The first instruction of a program is where a breakpoint of the new program may be, and it has not run yet. At + // the entry of a system call the instruction after it has not run either. + if (stop.exec || stop.syscall) + info.atReportedStop = false; m_running = false; Publish(); @@ -1105,7 +1870,7 @@ namespace BinaryNinjaDebugger { } - bool PtraceEngine::DoResume(bool step, pid_t tid) + bool PtraceEngine::DoResume(bool step, pid_t tid, SyscallMode mode) { if (m_done || m_running) return false; @@ -1113,7 +1878,10 @@ namespace BinaryNinjaDebugger { auto stepping = m_threads.find(tid); if (step && (stepping == m_threads.end() || !stepping->second.stopped)) return false; + if (mode == SyscallMode::Emulate && (!m_arch || !m_arch->sysemu)) + return false; + m_syscallMode = step ? SyscallMode::None : mode; m_continueMode = !step; std::vector stepOver; for (auto& [id, info] : m_threads) @@ -1123,18 +1891,26 @@ namespace BinaryNinjaDebugger { if (NeedsStepOver(id, info)) stepOver.push_back(id); - info.atReportedStop = false; } bool resumed; if (step) { uint64_t pc; - if (!stepOver.empty() && ReadPc(tid, pc)) - BeginGuard(tid, pc); + if (!stepOver.empty() && ReadPc(tid, pc) && !BeginGuard(tid, pc)) + { + EndGuard(tid, true); + return false; + } stepping->second.stepping = true; resumed = ResumeThread(tid); + if (!resumed) + { + stepping->second.stepping = false; + if (stepping->second.guardSoftware || !stepping->second.guardSlots.empty()) + EndGuard(tid, true); + } } else if (!stepOver.empty()) { @@ -1152,23 +1928,127 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::DoGetSyscallInfo(pid_t tid, SyscallInfo& info) + { + auto it = m_threads.find(tid); + if (m_done || m_running || it == m_threads.end() || !it->second.stopped) + return false; + + KernelSyscallInfo raw = {}; + long size = ptrace((__ptrace_request)PTRACE_GET_SYSCALL_INFO, tid, (void*)sizeof(raw), &raw); + // The header comes before the union, so that is the least that there can be + if (size < (long)offsetof(KernelSyscallInfo, entry)) + return false; + + info = SyscallInfo(); + info.arch = raw.arch; + info.instructionPointer = raw.instructionPointer; + info.stackPointer = raw.stackPointer; + switch (raw.op) + { + case KernelSyscallInfoEntry: + info.op = SyscallInfo::Entry; + info.number = raw.entry.number; + memcpy(info.args, raw.entry.args, sizeof(info.args)); + break; + case KernelSyscallInfoExit: + info.op = SyscallInfo::Exit; + info.returnValue = raw.exit.returnValue; + info.isError = raw.exit.isError != 0; + break; + case KernelSyscallInfoSeccomp: + info.op = SyscallInfo::Seccomp; + info.number = raw.seccomp.number; + memcpy(info.args, raw.seccomp.args, sizeof(info.args)); + info.seccompData = raw.seccomp.data; + break; + default: + break; + } + return true; + } + + + bool PtraceEngine::DoSetSyscallInfo(pid_t tid, const SyscallInfo& info) + { + // Only what the stop has is changed, so the rest is taken from the stop + SyscallInfo current; + if (!DoGetSyscallInfo(tid, current) || current.op != info.op) + return false; + + KernelSyscallInfo raw = {}; + raw.arch = current.arch; + raw.instructionPointer = current.instructionPointer; + raw.stackPointer = current.stackPointer; + switch (info.op) + { + case SyscallInfo::Entry: + raw.op = KernelSyscallInfoEntry; + raw.entry.number = info.number; + memcpy(raw.entry.args, info.args, sizeof(raw.entry.args)); + break; + case SyscallInfo::Exit: + raw.op = KernelSyscallInfoExit; + raw.exit.returnValue = info.returnValue; + raw.exit.isError = info.isError; + break; + case SyscallInfo::Seccomp: + raw.op = KernelSyscallInfoSeccomp; + raw.seccomp.number = info.number; + memcpy(raw.seccomp.args, info.args, sizeof(raw.seccomp.args)); + raw.seccomp.data = current.seccompData; + break; + default: + return false; + } + return ptrace((__ptrace_request)PTRACE_SET_SYSCALL_INFO, tid, (void*)sizeof(raw), &raw) == 0; + } + + bool PtraceEngine::DoAddBreakpoint(uint64_t address) { if (m_done || !m_arch || m_arch->breakpointInstruction.empty()) return false; std::lock_guard lock(m_breakpointMutex); - if (m_breakpoints.count(address)) + auto existing = m_breakpoints.find(address); + if (existing != m_breakpoints.end()) + { + // A mapping can disappear and later be replaced at the same address. The saved record then says that the + // breakpoint is inserted even though the new mapping contains its original instruction. Revalidate an + // idempotent add so a loader rendezvous can repair that state. + if (!existing->second.inserted || existing->second.suspended) + return true; + + std::vector current(m_arch->breakpointInstruction.size()); + if (!RawReadMemory(address, current.data(), current.size())) + return false; + if (current == m_arch->breakpointInstruction) + return true; + + if (!RawWriteMemory(address, m_arch->breakpointInstruction.data(), m_arch->breakpointInstruction.size())) + return false; + existing->second.original = std::move(current); return true; + } const auto& instruction = m_arch->breakpointInstruction; Breakpoint breakpoint; breakpoint.original.resize(instruction.size()); - if (!RawReadMemory(address, breakpoint.original.data(), instruction.size()) - || !RawWriteMemory(address, instruction.data(), instruction.size())) + if (!RawReadMemory(address, breakpoint.original.data(), instruction.size())) return false; - breakpoint.inserted = true; + // While a child shares the memory it must not run into a new breakpoint either + if (m_vforkPending > 0) + { + breakpoint.suspended = true; + } + else + { + if (!RawWriteMemory(address, instruction.data(), instruction.size())) + return false; + breakpoint.inserted = true; + } m_breakpoints[address] = std::move(breakpoint); return true; } @@ -1181,8 +2061,9 @@ namespace BinaryNinjaDebugger { if (it == m_breakpoints.end()) return false; - if (it->second.inserted && !m_done) - RawWriteMemory(address, it->second.original.data(), it->second.original.size()); + if (it->second.inserted && !m_done + && !RawWriteMemory(address, it->second.original.data(), it->second.original.size())) + return false; m_breakpoints.erase(it); // A thread that is running may just have trapped on it @@ -1192,6 +2073,16 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::DoDiscardBreakpoint(uint64_t address) + { + if (m_running) + return false; + + std::lock_guard lock(m_breakpointMutex); + return m_breakpoints.erase(address) != 0; + } + + bool PtraceEngine::DoAddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size) { if (m_done || m_running || !m_arch || !m_arch->hwDebug) @@ -1240,11 +2131,14 @@ namespace BinaryNinjaDebugger { if (!slot.used || slot.address != address || slot.type != type || slot.size != size) continue; + bool cleared = true; for (const auto& [tid, info] : m_threads) { - if (info.stopped) - m_arch->hwDebug->Clear(tid, index); + if (info.stopped && !m_arch->hwDebug->Clear(tid, index)) + cleared = false; } + if (!cleared) + return false; slot.used = false; return true; } @@ -1253,22 +2147,31 @@ namespace BinaryNinjaDebugger { // Puts the target back the way it was before we let go of it - void PtraceEngine::RemoveAllBreakpoints() + bool PtraceEngine::RemoveAllBreakpoints() { + bool success = true; for (auto& [tid, info] : m_threads) { if (info.guardSoftware || !info.guardSlots.empty()) - EndGuard(tid, true); + success &= EndGuard(tid, true); } { std::lock_guard lock(m_breakpointMutex); - for (auto& [address, breakpoint] : m_breakpoints) + for (auto it = m_breakpoints.begin(); it != m_breakpoints.end();) { - if (breakpoint.inserted) - RawWriteMemory(address, breakpoint.original.data(), breakpoint.original.size()); + auto& [address, breakpoint] = *it; + if (breakpoint.inserted + && !RawWriteMemory(address, breakpoint.original.data(), breakpoint.original.size())) + { + success = false; + it++; + } + else + { + it = m_breakpoints.erase(it); + } } - m_breakpoints.clear(); } for (size_t index = 0; index < m_hardwareSlots.size(); index++) @@ -1276,12 +2179,20 @@ namespace BinaryNinjaDebugger { if (!m_hardwareSlots[index].used) continue; + bool cleared = true; for (const auto& [tid, info] : m_threads) - m_arch->hwDebug->Clear(tid, index); - m_hardwareSlots[index].used = false; + cleared &= m_arch->hwDebug->Clear(tid, index); + if (cleared) + m_hardwareSlots[index].used = false; + else + success = false; } - m_stepOverQueue.clear(); - m_stepOverTid = -1; + if (success) + { + m_stepOverQueue.clear(); + m_stepOverTid = -1; + } + return success; } @@ -1361,21 +2272,166 @@ namespace BinaryNinjaDebugger { return false; } - RemoveAllBreakpoints(); + if (!RemoveAllBreakpoints()) + return false; + + bool detached = true; + std::vector tids; for (const auto& [tid, info] : m_threads) - ptrace(PTRACE_DETACH, tid, nullptr, (void*)(intptr_t)info.pendingSignal); + tids.push_back(tid); + for (pid_t tid : tids) + { + auto it = m_threads.find(tid); + if (it == m_threads.end()) + continue; + if (ptrace(PTRACE_DETACH, tid, nullptr, (void*)(intptr_t)it->second.pendingSignal) == 0 || errno == ESRCH) + m_threads.erase(it); + else + detached = false; + } + if (!detached) + { + Publish(); + return false; + } - m_threads.clear(); m_done = true; m_finished = true; m_running = false; Publish(); StopIo(); + if (!m_attached) + { + auto exit = std::make_shared(); + { + std::lock_guard lock(m_infoMutex); + m_detachedExit = exit; + } + std::thread([exit, pid = m_pid]() { + int status = 0; + pid_t result; + do + { + result = waitpid(pid, &status, __WALL); + } while (result < 0 && errno == EINTR); + + std::lock_guard lock(exit->mutex); + exit->status = result < 0 ? 0 : status; + exit->done = true; + exit->cv.notify_all(); + }).detach(); + } + Event event; event.type = DetachedEvent; PushEvent(event); return true; } + + bool ParseFdRedirect(const std::string& text, PtraceEngine::FdRedirect& redirect, std::string& error) + { + using Redirect = PtraceEngine::FdRedirect; + redirect = Redirect(); + + size_t i = 0; + auto skipSpace = [&]() { + while (i < text.size() && isspace((unsigned char)text[i])) + i++; + }; + auto readNumber = [&](int& value) { + size_t start = i; + long result = 0; + while (i < text.size() && isdigit((unsigned char)text[i])) + { + result = result * 10 + (text[i] - '0'); + if (result > 1000000) + return false; + i++; + } + value = (int)result; + return i > start; + }; + + skipSpace(); + int fd = -1; + if (i < text.size() && isdigit((unsigned char)text[i]) && !readNumber(fd)) + { + error = "the file descriptor is too large: " + text; + return false; + } + if (i >= text.size() || (text[i] != '<' && text[i] != '>')) + { + error = "expected < or > after the file descriptor: " + text; + return false; + } + + bool input = text[i++] == '<'; + if (fd < 0) + fd = input ? 0 : 1; + redirect.fd = fd; + + if (i < text.size() && text[i] == '&') + { + i++; + skipSpace(); + if (i < text.size() && text[i] == '-') + { + i++; + redirect.kind = Redirect::Close; + } + else + { + redirect.kind = Redirect::Duplicate; + if (!readNumber(redirect.source)) + { + error = "expected a file descriptor or - after &: " + text; + return false; + } + } + skipSpace(); + if (i != text.size()) + { + error = "unexpected text after the file descriptor: " + text; + return false; + } + return true; + } + + if (input) + { + if (i < text.size() && text[i] == '>') + { + i++; + redirect.flags = O_RDWR | O_CREAT; + } + else + { + redirect.flags = O_RDONLY; + } + } + else if (i < text.size() && text[i] == '>') + { + i++; + redirect.flags = O_WRONLY | O_CREAT | O_APPEND; + } + else + { + redirect.flags = O_WRONLY | O_CREAT | O_TRUNC; + } + + skipSpace(); + redirect.kind = Redirect::OpenFile; + redirect.path = text.substr(i); + while (!redirect.path.empty() && isspace((unsigned char)redirect.path.back())) + redirect.path.pop_back(); + if (redirect.path.empty()) + { + error = "expected a path: " + text; + return false; + } + return true; + } + } // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceengine.h b/core/adapters/ptrace/ptraceengine.h index 68615ead..1f7de717 100644 --- a/core/adapters/ptrace/ptraceengine.h +++ b/core/adapters/ptrace/ptraceengine.h @@ -17,12 +17,14 @@ limitations under the License. #pragma once #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -37,6 +39,18 @@ namespace BinaryNinjaDebugger { class PtraceEngine { public: + enum class TrapOrigin + { + None, + SoftwareBreakpoint, + HardwareBreakpoint, + SingleStep, + SignalHandler, + Target, + Internal, + Syscall + }; + enum EventType { StoppedEvent, @@ -58,6 +72,15 @@ namespace BinaryNinjaDebugger { bool interrupted = false; bool breakpoint = false; bool hardware = false; + // SIGTRAP is shared by ptrace, debugger breakpoints and the target. This records which of those produced it. + TrapOrigin trapOrigin = TrapOrigin::None; + // The target has started another program. The engine has started over with it: the breakpoints, the memory + // and the threads are all new. + bool exec = false; + // The signal that was delivered to the thread, whose handler the thread is now stopped at the start of + int signalHandler = 0; + // The thread is stopped at a system call, because it was resumed to one. See ResumeToSyscall. + bool syscall = false; std::string data; std::function task; }; @@ -74,6 +97,62 @@ namespace BinaryNinjaDebugger { std::string path; }; + // A stop at a system call, as PTRACE_GET_SYSCALL_INFO tells it + struct SyscallInfo + { + enum Op + { + None, + Entry, + Exit, + Seccomp + }; + + Op op = None; + // The AUDIT_ARCH_* value, which tells the table that the number belongs to + uint32_t arch = 0; + uint64_t instructionPointer = 0; + uint64_t stackPointer = 0; + // Entry and Seccomp + uint64_t number = 0; + uint64_t args[6] = {}; + // Exit + int64_t returnValue = 0; + // The return value is -errno + bool isError = false; + // Seccomp: the SECCOMP_RET_DATA of the filter + uint32_t seccompData = 0; + }; + + // Which stops at system calls a resume asks for + enum class SyscallMode + { + None, + // Stop at the entry and at the exit of the next system call, which is executed + Trace, + // Stop at the entry of the next system call, which is not executed: the debugger stands in for the kernel + Emulate + }; + + // What the target's file descriptor `fd` is set to before the target starts + struct FdRedirect + { + enum Kind + { + OpenFile, + Duplicate, + Close + }; + + Kind kind = OpenFile; + int fd = 0; + // OpenFile + std::string path; + int flags = 0; + // Duplicate: the descriptor of the target that `fd` becomes a copy of + int source = 0; + }; + struct LaunchOptions { std::string path; @@ -81,12 +160,27 @@ namespace BinaryNinjaDebugger { std::string workingDir; bool disableAslr = true; bool usePty = true; + // The size of the terminal + unsigned short rows = 24; + unsigned short columns = 80; + // Applied in order, after the terminal is set up, so 1 and 2 can be sent elsewhere and later ones can refer + // to earlier ones. A relative path is relative to the working directory. + std::vector redirects; // Overrides the architecture that is detected from the target const PtraceArch* arch = nullptr; }; using EventHandler = std::function; + // Where the exit of a target that was let go of is picked up, since it is still our child + struct DetachedExit + { + std::mutex mutex; + std::condition_variable cv; + bool done = false; + int status = 0; + }; + private: struct ThreadInfo { @@ -96,6 +190,12 @@ namespace BinaryNinjaDebugger { // SIGSTOPs we sent that have not been consumed yet int expectedStops = 0; int pendingSignal = 0; + // The signal that the thread was resumed with in order to stop at its handler + int handlerSignal = 0; + // SIGTRAP delivered into a SIGTRAP handler can retain its original si_code. A changed PC distinguishes that + // handler-entry stop from the original signal-delivery stop. + uint64_t handlerResumePc = 0; + bool handlerResumePcValid = false; // Set for the thread whose stop was reported, so that resuming it steps over a breakpoint at its PC bool atReportedStop = false; uint64_t reportedPc = 0; @@ -110,6 +210,8 @@ namespace BinaryNinjaDebugger { { std::vector original; bool inserted = false; + // Taken out while a child that shares the memory of the target runs, and put back after it + bool suspended = false; }; struct HardwareSlot @@ -135,6 +237,12 @@ namespace BinaryNinjaDebugger { bool breakpoint = false; bool hardware = false; bool stepTrap = false; + bool exec = false; + int signalHandler = 0; + TrapOrigin trapOrigin = TrapOrigin::None; + bool syscall = false; + // The thread that the stop is for, if it is not the one that it was found on + pid_t tid = 0; }; EventHandler m_handler; @@ -165,27 +273,43 @@ namespace BinaryNinjaDebugger { std::set m_recentlyRemoved; std::vector m_stepOverQueue; pid_t m_stepOverTid = -1; + int m_vforkPending = 0; + SyscallMode m_syscallMode = SyscallMode::None; const PtraceArch* m_arch = nullptr; std::mutex m_breakpointMutex; std::map m_breakpoints; mutable std::mutex m_infoMutex; + std::shared_ptr m_detachedExit; std::vector m_publishedThreads; std::atomic m_publishedRunning {false}; - std::atomic m_interruptRequested {false}; + // An interrupt is a SIGSTOP that we send. It can be asked for again before the first one has been seen, so the + // signals that are on their way are counted, and whether a pause is still wanted is kept apart from that. + std::atomic m_interruptWanted {false}; + std::atomic m_interruptInFlight {0}; + std::atomic m_debugSignalHandlers {false}; pid_t m_pid = -1; + pid_t m_attachPid = -1; + // The target was running before we came to it, so we let go of it rather than kill it when we are done + bool m_attached = false; int m_masterFd = -1; int m_memFd = -1; std::atomic m_finished {false}; std::atomic m_ioStop {false}; + std::mutex m_inputMutex; + std::deque m_inputQueue; + size_t m_inputOffset = 0; + size_t m_pendingInputBytes = 0; void TracerMain(); void EventMain(); void IoMain(); std::string Spawn(); + std::string AttachToProcess(); + std::string AdoptTarget(); bool RunOnTracer(std::function function); void PushEvent(const Event& event); void Publish(); @@ -195,6 +319,7 @@ namespace BinaryNinjaDebugger { void HandleStatus(pid_t tid, int status); Classified Classify(pid_t tid, int status); bool ResumeThread(pid_t tid); + bool HasSignalHandler(int signal); bool ClassifyTrap(pid_t tid, ThreadInfo& info, Classified& result); bool RawGetRegisterSet(pid_t tid, int regset, std::vector& data); bool RawSetRegisterSet(pid_t tid, int regset, const std::vector& data); @@ -204,21 +329,27 @@ namespace BinaryNinjaDebugger { bool RawWriteMemory(uint64_t address, const void* buffer, size_t size); bool HasBreakpointAt(uint64_t address); bool NeedsStepOver(pid_t tid, const ThreadInfo& info); - void BeginGuard(pid_t tid, uint64_t address); - void EndGuard(pid_t tid, bool threadAlive); + bool BeginGuard(pid_t tid, uint64_t address); + bool EndGuard(pid_t tid, bool threadAlive); bool StartNextStepOver(); bool ResumeAll(); void ApplyHardwareToThread(pid_t tid); - void RemoveAllBreakpoints(); + void HandleFork(pid_t child, bool sharedMemory); + Classified HandleExec(pid_t tid); + void ResumeBreakpointsAfterVfork(); + bool RemoveAllBreakpoints(); void StopAll(); void FinishStop(pid_t tid, const Classified& stop); void FinishExit(int status); - bool DoResume(bool step, pid_t tid); + bool DoResume(bool step, pid_t tid, SyscallMode mode = SyscallMode::None); + bool DoGetSyscallInfo(pid_t tid, SyscallInfo& info); + bool DoSetSyscallInfo(pid_t tid, const SyscallInfo& info); bool DoKill(); bool DoDetach(); bool DoAddBreakpoint(uint64_t address); bool DoRemoveBreakpoint(uint64_t address); + bool DoDiscardBreakpoint(uint64_t address); bool DoAddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); bool DoRemoveHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); @@ -227,9 +358,19 @@ namespace BinaryNinjaDebugger { ~PtraceEngine(); bool Launch(const LaunchOptions& options, std::string& error); + // Starts tracing a process that is already running, and stops all of its threads. The target keeps its own + // terminal, so there is no output and no input. + // `arch` overrides the architecture that is detected from the target. + bool Attach(uint32_t pid, std::string& error, const PtraceArch* arch = nullptr); // With step set, only `tid` runs, for one instruction. Otherwise every thread runs. bool Resume(bool step, uint32_t tid); + // Resumes every thread, and stops when one of them is at a system call. The other threads are stopped where they + // are, so they may be at one too. Emulate needs an architecture with PTRACE_SYSEMU (see PtraceArch::sysemu). + // A thread that is resumed after an Emulate stop does not execute the system call that it stopped at, whatever + // it is resumed with, so it goes on with the registers as they are: the return value is what the debugger left + // in the register for it. + bool ResumeToSyscall(SyscallMode mode); bool Interrupt(); bool Kill(); bool Detach(); @@ -239,6 +380,10 @@ namespace BinaryNinjaDebugger { // thread is not tied up by the caller, so it is the place for work that must not run under the caller's locks. void PostTask(std::function task); + // A signal that the target has a handler for is normally delivered and the handler runs on its own. With this + // set, the thread stops at the first instruction of the handler instead. + void SetDebugSignalHandlers(bool enable) { m_debugSignalHandlers = enable; } + // Raw register sets, as PTRACE_GETREGSET and PTRACE_SETREGSET see them. The thread must be stopped. bool GetRegisterSet(uint32_t tid, int regset, std::vector& data); bool SetRegisterSet(uint32_t tid, int regset, const std::vector& data); @@ -246,10 +391,18 @@ namespace BinaryNinjaDebugger { // Software breakpoints are inserted straight into the target. ReadMemory and WriteMemory hide them. bool AddBreakpoint(uint64_t address); bool RemoveBreakpoint(uint64_t address); + // For a mapping that has been removed or replaced. Drops bookkeeping without writing the saved bytes into a + // different mapping that now occupies the address. + bool DiscardBreakpoint(uint64_t address); // The target must be stopped bool AddHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); bool RemoveHardwareBreakpoint(uint64_t address, PtraceHwType type, size_t size); + // PTRACE_GET_SYSCALL_INFO and PTRACE_SET_SYSCALL_INFO for a thread that is stopped. They need Linux 5.3 and 6.16. + // Setting takes the number and the arguments at an entry, and the return value at an exit. + bool GetSyscallInfo(uint32_t tid, SyscallInfo& info); + bool SetSyscallInfo(uint32_t tid, const SyscallInfo& info); + const PtraceArch* GetArch() const { return m_arch; } std::vector GetMaps() const; @@ -260,5 +413,14 @@ namespace BinaryNinjaDebugger { uint32_t GetPid() const { return m_pid > 0 ? m_pid : 0; } std::vector GetThreads() const; bool IsRunning() const { return m_publishedRunning; } + + // After Detach, waits for the target to exit and gives its wait status. A launched target is our child, so a + // thread reaps it when it exits, and this is the only way to see its status. + bool WaitForDetachedExit(int& status, std::chrono::milliseconds timeout); }; + + // Reads a redirect the way a shell writes one: `Npath` (write, truncating), `N>>path` (append), + // `N<>path` (read and write), `N>&M` (a copy of the descriptor M of the target) and `N>&-` (close). Without N it is + // 0 for `<` and 1 for the others. + bool ParseFdRedirect(const std::string& text, PtraceEngine::FdRedirect& redirect, std::string& error); } // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracesignal.cpp b/core/adapters/ptrace/ptracesignal.cpp new file mode 100644 index 00000000..407460d8 --- /dev/null +++ b/core/adapters/ptrace/ptracesignal.cpp @@ -0,0 +1,92 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptracesignal.h" +#include + +namespace BinaryNinjaDebugger { + + BNDebugStopReason StopReasonFromLinuxSignal(int signal) + { + // The constants are used instead of numbers, because the numbers of some signals differ between architectures + switch (signal) + { + case SIGHUP: + return SignalHup; + case SIGINT: + return SignalInt; + case SIGQUIT: + return SignalQuit; + case SIGILL: + return IllegalInstruction; + case SIGABRT: + return SignalAbrt; + case SIGFPE: + return SignalFpe; + case SIGKILL: + return SignalKill; + case SIGBUS: + return SignalBus; + case SIGSEGV: + return SignalSegv; + case SIGSYS: + return SignalSys; + case SIGPIPE: + return SignalPipe; + case SIGALRM: + return SignalAlrm; + case SIGTERM: + return SignalTerm; + case SIGURG: + return SignalUrg; + case SIGSTOP: + return SignalStop; + case SIGTSTP: + return SignalTstp; + case SIGCONT: + return SignalCont; + case SIGCHLD: + return SignalChld; + case SIGTTIN: + return SignalTtin; + case SIGTTOU: + return SignalTtou; + case SIGIO: + return SignalIo; + case SIGXCPU: + return SignalXcpu; + case SIGXFSZ: + return SignalXfsz; + case SIGVTALRM: + return SignalVtalrm; + case SIGPROF: + return SignalProf; + case SIGWINCH: + return SignalWinch; + case SIGUSR1: + return SignalUsr1; + case SIGUSR2: + return SignalUsr2; +#ifdef SIGSTKFLT + case SIGSTKFLT: + return SignalStkflt; +#endif + default: + return UnknownReason; + } + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracesignal.h b/core/adapters/ptrace/ptracesignal.h new file mode 100644 index 00000000..de669125 --- /dev/null +++ b/core/adapters/ptrace/ptracesignal.h @@ -0,0 +1,25 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include "../../../api/ffi.h" + +namespace BinaryNinjaDebugger { + // The stop reason for a signal of Linux. Not the table of the shared code, which uses the numbers of macOS and + // gives SIGSEGV and SIGFPE their macOS names. + BNDebugStopReason StopReasonFromLinuxSignal(int signal); +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracesyscall.cpp b/core/adapters/ptrace/ptracesyscall.cpp new file mode 100644 index 00000000..de4c1d57 --- /dev/null +++ b/core/adapters/ptrace/ptracesyscall.cpp @@ -0,0 +1,320 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ptracesyscall.h" +#include +#include +#include +#include + +namespace BinaryNinjaDebugger { + namespace { + struct SyscallEntry + { + uint16_t number; + const char* name; + }; + + // Generated from asm/unistd_64.h and asm/unistd_32.h of Linux 6.8, sorted by number + const SyscallEntry g_x86_64[] = { + {0, "read"}, {1, "write"}, {2, "open"}, {3, "close"}, + {4, "stat"}, {5, "fstat"}, {6, "lstat"}, {7, "poll"}, + {8, "lseek"}, {9, "mmap"}, {10, "mprotect"}, {11, "munmap"}, + {12, "brk"}, {13, "rt_sigaction"}, {14, "rt_sigprocmask"}, {15, "rt_sigreturn"}, + {16, "ioctl"}, {17, "pread64"}, {18, "pwrite64"}, {19, "readv"}, + {20, "writev"}, {21, "access"}, {22, "pipe"}, {23, "select"}, + {24, "sched_yield"}, {25, "mremap"}, {26, "msync"}, {27, "mincore"}, + {28, "madvise"}, {29, "shmget"}, {30, "shmat"}, {31, "shmctl"}, + {32, "dup"}, {33, "dup2"}, {34, "pause"}, {35, "nanosleep"}, + {36, "getitimer"}, {37, "alarm"}, {38, "setitimer"}, {39, "getpid"}, + {40, "sendfile"}, {41, "socket"}, {42, "connect"}, {43, "accept"}, + {44, "sendto"}, {45, "recvfrom"}, {46, "sendmsg"}, {47, "recvmsg"}, + {48, "shutdown"}, {49, "bind"}, {50, "listen"}, {51, "getsockname"}, + {52, "getpeername"}, {53, "socketpair"}, {54, "setsockopt"}, {55, "getsockopt"}, + {56, "clone"}, {57, "fork"}, {58, "vfork"}, {59, "execve"}, + {60, "exit"}, {61, "wait4"}, {62, "kill"}, {63, "uname"}, + {64, "semget"}, {65, "semop"}, {66, "semctl"}, {67, "shmdt"}, + {68, "msgget"}, {69, "msgsnd"}, {70, "msgrcv"}, {71, "msgctl"}, + {72, "fcntl"}, {73, "flock"}, {74, "fsync"}, {75, "fdatasync"}, + {76, "truncate"}, {77, "ftruncate"}, {78, "getdents"}, {79, "getcwd"}, + {80, "chdir"}, {81, "fchdir"}, {82, "rename"}, {83, "mkdir"}, + {84, "rmdir"}, {85, "creat"}, {86, "link"}, {87, "unlink"}, + {88, "symlink"}, {89, "readlink"}, {90, "chmod"}, {91, "fchmod"}, + {92, "chown"}, {93, "fchown"}, {94, "lchown"}, {95, "umask"}, + {96, "gettimeofday"}, {97, "getrlimit"}, {98, "getrusage"}, {99, "sysinfo"}, + {100, "times"}, {101, "ptrace"}, {102, "getuid"}, {103, "syslog"}, + {104, "getgid"}, {105, "setuid"}, {106, "setgid"}, {107, "geteuid"}, + {108, "getegid"}, {109, "setpgid"}, {110, "getppid"}, {111, "getpgrp"}, + {112, "setsid"}, {113, "setreuid"}, {114, "setregid"}, {115, "getgroups"}, + {116, "setgroups"}, {117, "setresuid"}, {118, "getresuid"}, {119, "setresgid"}, + {120, "getresgid"}, {121, "getpgid"}, {122, "setfsuid"}, {123, "setfsgid"}, + {124, "getsid"}, {125, "capget"}, {126, "capset"}, {127, "rt_sigpending"}, + {128, "rt_sigtimedwait"}, {129, "rt_sigqueueinfo"}, {130, "rt_sigsuspend"}, {131, "sigaltstack"}, + {132, "utime"}, {133, "mknod"}, {134, "uselib"}, {135, "personality"}, + {136, "ustat"}, {137, "statfs"}, {138, "fstatfs"}, {139, "sysfs"}, + {140, "getpriority"}, {141, "setpriority"}, {142, "sched_setparam"}, {143, "sched_getparam"}, + {144, "sched_setscheduler"}, {145, "sched_getscheduler"}, {146, "sched_get_priority_max"}, {147, "sched_get_priority_min"}, + {148, "sched_rr_get_interval"}, {149, "mlock"}, {150, "munlock"}, {151, "mlockall"}, + {152, "munlockall"}, {153, "vhangup"}, {154, "modify_ldt"}, {155, "pivot_root"}, + {156, "_sysctl"}, {157, "prctl"}, {158, "arch_prctl"}, {159, "adjtimex"}, + {160, "setrlimit"}, {161, "chroot"}, {162, "sync"}, {163, "acct"}, + {164, "settimeofday"}, {165, "mount"}, {166, "umount2"}, {167, "swapon"}, + {168, "swapoff"}, {169, "reboot"}, {170, "sethostname"}, {171, "setdomainname"}, + {172, "iopl"}, {173, "ioperm"}, {174, "create_module"}, {175, "init_module"}, + {176, "delete_module"}, {177, "get_kernel_syms"}, {178, "query_module"}, {179, "quotactl"}, + {180, "nfsservctl"}, {181, "getpmsg"}, {182, "putpmsg"}, {183, "afs_syscall"}, + {184, "tuxcall"}, {185, "security"}, {186, "gettid"}, {187, "readahead"}, + {188, "setxattr"}, {189, "lsetxattr"}, {190, "fsetxattr"}, {191, "getxattr"}, + {192, "lgetxattr"}, {193, "fgetxattr"}, {194, "listxattr"}, {195, "llistxattr"}, + {196, "flistxattr"}, {197, "removexattr"}, {198, "lremovexattr"}, {199, "fremovexattr"}, + {200, "tkill"}, {201, "time"}, {202, "futex"}, {203, "sched_setaffinity"}, + {204, "sched_getaffinity"}, {205, "set_thread_area"}, {206, "io_setup"}, {207, "io_destroy"}, + {208, "io_getevents"}, {209, "io_submit"}, {210, "io_cancel"}, {211, "get_thread_area"}, + {212, "lookup_dcookie"}, {213, "epoll_create"}, {214, "epoll_ctl_old"}, {215, "epoll_wait_old"}, + {216, "remap_file_pages"}, {217, "getdents64"}, {218, "set_tid_address"}, {219, "restart_syscall"}, + {220, "semtimedop"}, {221, "fadvise64"}, {222, "timer_create"}, {223, "timer_settime"}, + {224, "timer_gettime"}, {225, "timer_getoverrun"}, {226, "timer_delete"}, {227, "clock_settime"}, + {228, "clock_gettime"}, {229, "clock_getres"}, {230, "clock_nanosleep"}, {231, "exit_group"}, + {232, "epoll_wait"}, {233, "epoll_ctl"}, {234, "tgkill"}, {235, "utimes"}, + {236, "vserver"}, {237, "mbind"}, {238, "set_mempolicy"}, {239, "get_mempolicy"}, + {240, "mq_open"}, {241, "mq_unlink"}, {242, "mq_timedsend"}, {243, "mq_timedreceive"}, + {244, "mq_notify"}, {245, "mq_getsetattr"}, {246, "kexec_load"}, {247, "waitid"}, + {248, "add_key"}, {249, "request_key"}, {250, "keyctl"}, {251, "ioprio_set"}, + {252, "ioprio_get"}, {253, "inotify_init"}, {254, "inotify_add_watch"}, {255, "inotify_rm_watch"}, + {256, "migrate_pages"}, {257, "openat"}, {258, "mkdirat"}, {259, "mknodat"}, + {260, "fchownat"}, {261, "futimesat"}, {262, "newfstatat"}, {263, "unlinkat"}, + {264, "renameat"}, {265, "linkat"}, {266, "symlinkat"}, {267, "readlinkat"}, + {268, "fchmodat"}, {269, "faccessat"}, {270, "pselect6"}, {271, "ppoll"}, + {272, "unshare"}, {273, "set_robust_list"}, {274, "get_robust_list"}, {275, "splice"}, + {276, "tee"}, {277, "sync_file_range"}, {278, "vmsplice"}, {279, "move_pages"}, + {280, "utimensat"}, {281, "epoll_pwait"}, {282, "signalfd"}, {283, "timerfd_create"}, + {284, "eventfd"}, {285, "fallocate"}, {286, "timerfd_settime"}, {287, "timerfd_gettime"}, + {288, "accept4"}, {289, "signalfd4"}, {290, "eventfd2"}, {291, "epoll_create1"}, + {292, "dup3"}, {293, "pipe2"}, {294, "inotify_init1"}, {295, "preadv"}, + {296, "pwritev"}, {297, "rt_tgsigqueueinfo"}, {298, "perf_event_open"}, {299, "recvmmsg"}, + {300, "fanotify_init"}, {301, "fanotify_mark"}, {302, "prlimit64"}, {303, "name_to_handle_at"}, + {304, "open_by_handle_at"}, {305, "clock_adjtime"}, {306, "syncfs"}, {307, "sendmmsg"}, + {308, "setns"}, {309, "getcpu"}, {310, "process_vm_readv"}, {311, "process_vm_writev"}, + {312, "kcmp"}, {313, "finit_module"}, {314, "sched_setattr"}, {315, "sched_getattr"}, + {316, "renameat2"}, {317, "seccomp"}, {318, "getrandom"}, {319, "memfd_create"}, + {320, "kexec_file_load"}, {321, "bpf"}, {322, "execveat"}, {323, "userfaultfd"}, + {324, "membarrier"}, {325, "mlock2"}, {326, "copy_file_range"}, {327, "preadv2"}, + {328, "pwritev2"}, {329, "pkey_mprotect"}, {330, "pkey_alloc"}, {331, "pkey_free"}, + {332, "statx"}, {333, "io_pgetevents"}, {334, "rseq"}, {424, "pidfd_send_signal"}, + {425, "io_uring_setup"}, {426, "io_uring_enter"}, {427, "io_uring_register"}, {428, "open_tree"}, + {429, "move_mount"}, {430, "fsopen"}, {431, "fsconfig"}, {432, "fsmount"}, + {433, "fspick"}, {434, "pidfd_open"}, {435, "clone3"}, {436, "close_range"}, + {437, "openat2"}, {438, "pidfd_getfd"}, {439, "faccessat2"}, {440, "process_madvise"}, + {441, "epoll_pwait2"}, {442, "mount_setattr"}, {443, "quotactl_fd"}, {444, "landlock_create_ruleset"}, + {445, "landlock_add_rule"}, {446, "landlock_restrict_self"}, {447, "memfd_secret"}, {448, "process_mrelease"}, + {449, "futex_waitv"}, {450, "set_mempolicy_home_node"}, {451, "cachestat"}, {452, "fchmodat2"}, + {453, "map_shadow_stack"}, {454, "futex_wake"}, {455, "futex_wait"}, {456, "futex_requeue"}, + {457, "statmount"}, {458, "listmount"}, {459, "lsm_get_self_attr"}, {460, "lsm_set_self_attr"}, + {461, "lsm_list_modules"}, + }; + + const SyscallEntry g_i386[] = { + {0, "restart_syscall"}, {1, "exit"}, {2, "fork"}, {3, "read"}, + {4, "write"}, {5, "open"}, {6, "close"}, {7, "waitpid"}, + {8, "creat"}, {9, "link"}, {10, "unlink"}, {11, "execve"}, + {12, "chdir"}, {13, "time"}, {14, "mknod"}, {15, "chmod"}, + {16, "lchown"}, {17, "break"}, {18, "oldstat"}, {19, "lseek"}, + {20, "getpid"}, {21, "mount"}, {22, "umount"}, {23, "setuid"}, + {24, "getuid"}, {25, "stime"}, {26, "ptrace"}, {27, "alarm"}, + {28, "oldfstat"}, {29, "pause"}, {30, "utime"}, {31, "stty"}, + {32, "gtty"}, {33, "access"}, {34, "nice"}, {35, "ftime"}, + {36, "sync"}, {37, "kill"}, {38, "rename"}, {39, "mkdir"}, + {40, "rmdir"}, {41, "dup"}, {42, "pipe"}, {43, "times"}, + {44, "prof"}, {45, "brk"}, {46, "setgid"}, {47, "getgid"}, + {48, "signal"}, {49, "geteuid"}, {50, "getegid"}, {51, "acct"}, + {52, "umount2"}, {53, "lock"}, {54, "ioctl"}, {55, "fcntl"}, + {56, "mpx"}, {57, "setpgid"}, {58, "ulimit"}, {59, "oldolduname"}, + {60, "umask"}, {61, "chroot"}, {62, "ustat"}, {63, "dup2"}, + {64, "getppid"}, {65, "getpgrp"}, {66, "setsid"}, {67, "sigaction"}, + {68, "sgetmask"}, {69, "ssetmask"}, {70, "setreuid"}, {71, "setregid"}, + {72, "sigsuspend"}, {73, "sigpending"}, {74, "sethostname"}, {75, "setrlimit"}, + {76, "getrlimit"}, {77, "getrusage"}, {78, "gettimeofday"}, {79, "settimeofday"}, + {80, "getgroups"}, {81, "setgroups"}, {82, "select"}, {83, "symlink"}, + {84, "oldlstat"}, {85, "readlink"}, {86, "uselib"}, {87, "swapon"}, + {88, "reboot"}, {89, "readdir"}, {90, "mmap"}, {91, "munmap"}, + {92, "truncate"}, {93, "ftruncate"}, {94, "fchmod"}, {95, "fchown"}, + {96, "getpriority"}, {97, "setpriority"}, {98, "profil"}, {99, "statfs"}, + {100, "fstatfs"}, {101, "ioperm"}, {102, "socketcall"}, {103, "syslog"}, + {104, "setitimer"}, {105, "getitimer"}, {106, "stat"}, {107, "lstat"}, + {108, "fstat"}, {109, "olduname"}, {110, "iopl"}, {111, "vhangup"}, + {112, "idle"}, {113, "vm86old"}, {114, "wait4"}, {115, "swapoff"}, + {116, "sysinfo"}, {117, "ipc"}, {118, "fsync"}, {119, "sigreturn"}, + {120, "clone"}, {121, "setdomainname"}, {122, "uname"}, {123, "modify_ldt"}, + {124, "adjtimex"}, {125, "mprotect"}, {126, "sigprocmask"}, {127, "create_module"}, + {128, "init_module"}, {129, "delete_module"}, {130, "get_kernel_syms"}, {131, "quotactl"}, + {132, "getpgid"}, {133, "fchdir"}, {134, "bdflush"}, {135, "sysfs"}, + {136, "personality"}, {137, "afs_syscall"}, {138, "setfsuid"}, {139, "setfsgid"}, + {140, "_llseek"}, {141, "getdents"}, {142, "_newselect"}, {143, "flock"}, + {144, "msync"}, {145, "readv"}, {146, "writev"}, {147, "getsid"}, + {148, "fdatasync"}, {149, "_sysctl"}, {150, "mlock"}, {151, "munlock"}, + {152, "mlockall"}, {153, "munlockall"}, {154, "sched_setparam"}, {155, "sched_getparam"}, + {156, "sched_setscheduler"}, {157, "sched_getscheduler"}, {158, "sched_yield"}, {159, "sched_get_priority_max"}, + {160, "sched_get_priority_min"}, {161, "sched_rr_get_interval"}, {162, "nanosleep"}, {163, "mremap"}, + {164, "setresuid"}, {165, "getresuid"}, {166, "vm86"}, {167, "query_module"}, + {168, "poll"}, {169, "nfsservctl"}, {170, "setresgid"}, {171, "getresgid"}, + {172, "prctl"}, {173, "rt_sigreturn"}, {174, "rt_sigaction"}, {175, "rt_sigprocmask"}, + {176, "rt_sigpending"}, {177, "rt_sigtimedwait"}, {178, "rt_sigqueueinfo"}, {179, "rt_sigsuspend"}, + {180, "pread64"}, {181, "pwrite64"}, {182, "chown"}, {183, "getcwd"}, + {184, "capget"}, {185, "capset"}, {186, "sigaltstack"}, {187, "sendfile"}, + {188, "getpmsg"}, {189, "putpmsg"}, {190, "vfork"}, {191, "ugetrlimit"}, + {192, "mmap2"}, {193, "truncate64"}, {194, "ftruncate64"}, {195, "stat64"}, + {196, "lstat64"}, {197, "fstat64"}, {198, "lchown32"}, {199, "getuid32"}, + {200, "getgid32"}, {201, "geteuid32"}, {202, "getegid32"}, {203, "setreuid32"}, + {204, "setregid32"}, {205, "getgroups32"}, {206, "setgroups32"}, {207, "fchown32"}, + {208, "setresuid32"}, {209, "getresuid32"}, {210, "setresgid32"}, {211, "getresgid32"}, + {212, "chown32"}, {213, "setuid32"}, {214, "setgid32"}, {215, "setfsuid32"}, + {216, "setfsgid32"}, {217, "pivot_root"}, {218, "mincore"}, {219, "madvise"}, + {220, "getdents64"}, {221, "fcntl64"}, {224, "gettid"}, {225, "readahead"}, + {226, "setxattr"}, {227, "lsetxattr"}, {228, "fsetxattr"}, {229, "getxattr"}, + {230, "lgetxattr"}, {231, "fgetxattr"}, {232, "listxattr"}, {233, "llistxattr"}, + {234, "flistxattr"}, {235, "removexattr"}, {236, "lremovexattr"}, {237, "fremovexattr"}, + {238, "tkill"}, {239, "sendfile64"}, {240, "futex"}, {241, "sched_setaffinity"}, + {242, "sched_getaffinity"}, {243, "set_thread_area"}, {244, "get_thread_area"}, {245, "io_setup"}, + {246, "io_destroy"}, {247, "io_getevents"}, {248, "io_submit"}, {249, "io_cancel"}, + {250, "fadvise64"}, {252, "exit_group"}, {253, "lookup_dcookie"}, {254, "epoll_create"}, + {255, "epoll_ctl"}, {256, "epoll_wait"}, {257, "remap_file_pages"}, {258, "set_tid_address"}, + {259, "timer_create"}, {260, "timer_settime"}, {261, "timer_gettime"}, {262, "timer_getoverrun"}, + {263, "timer_delete"}, {264, "clock_settime"}, {265, "clock_gettime"}, {266, "clock_getres"}, + {267, "clock_nanosleep"}, {268, "statfs64"}, {269, "fstatfs64"}, {270, "tgkill"}, + {271, "utimes"}, {272, "fadvise64_64"}, {273, "vserver"}, {274, "mbind"}, + {275, "get_mempolicy"}, {276, "set_mempolicy"}, {277, "mq_open"}, {278, "mq_unlink"}, + {279, "mq_timedsend"}, {280, "mq_timedreceive"}, {281, "mq_notify"}, {282, "mq_getsetattr"}, + {283, "kexec_load"}, {284, "waitid"}, {286, "add_key"}, {287, "request_key"}, + {288, "keyctl"}, {289, "ioprio_set"}, {290, "ioprio_get"}, {291, "inotify_init"}, + {292, "inotify_add_watch"}, {293, "inotify_rm_watch"}, {294, "migrate_pages"}, {295, "openat"}, + {296, "mkdirat"}, {297, "mknodat"}, {298, "fchownat"}, {299, "futimesat"}, + {300, "fstatat64"}, {301, "unlinkat"}, {302, "renameat"}, {303, "linkat"}, + {304, "symlinkat"}, {305, "readlinkat"}, {306, "fchmodat"}, {307, "faccessat"}, + {308, "pselect6"}, {309, "ppoll"}, {310, "unshare"}, {311, "set_robust_list"}, + {312, "get_robust_list"}, {313, "splice"}, {314, "sync_file_range"}, {315, "tee"}, + {316, "vmsplice"}, {317, "move_pages"}, {318, "getcpu"}, {319, "epoll_pwait"}, + {320, "utimensat"}, {321, "signalfd"}, {322, "timerfd_create"}, {323, "eventfd"}, + {324, "fallocate"}, {325, "timerfd_settime"}, {326, "timerfd_gettime"}, {327, "signalfd4"}, + {328, "eventfd2"}, {329, "epoll_create1"}, {330, "dup3"}, {331, "pipe2"}, + {332, "inotify_init1"}, {333, "preadv"}, {334, "pwritev"}, {335, "rt_tgsigqueueinfo"}, + {336, "perf_event_open"}, {337, "recvmmsg"}, {338, "fanotify_init"}, {339, "fanotify_mark"}, + {340, "prlimit64"}, {341, "name_to_handle_at"}, {342, "open_by_handle_at"}, {343, "clock_adjtime"}, + {344, "syncfs"}, {345, "sendmmsg"}, {346, "setns"}, {347, "process_vm_readv"}, + {348, "process_vm_writev"}, {349, "kcmp"}, {350, "finit_module"}, {351, "sched_setattr"}, + {352, "sched_getattr"}, {353, "renameat2"}, {354, "seccomp"}, {355, "getrandom"}, + {356, "memfd_create"}, {357, "bpf"}, {358, "execveat"}, {359, "socket"}, + {360, "socketpair"}, {361, "bind"}, {362, "connect"}, {363, "listen"}, + {364, "accept4"}, {365, "getsockopt"}, {366, "setsockopt"}, {367, "getsockname"}, + {368, "getpeername"}, {369, "sendto"}, {370, "sendmsg"}, {371, "recvfrom"}, + {372, "recvmsg"}, {373, "shutdown"}, {374, "userfaultfd"}, {375, "membarrier"}, + {376, "mlock2"}, {377, "copy_file_range"}, {378, "preadv2"}, {379, "pwritev2"}, + {380, "pkey_mprotect"}, {381, "pkey_alloc"}, {382, "pkey_free"}, {383, "statx"}, + {384, "arch_prctl"}, {385, "io_pgetevents"}, {386, "rseq"}, {393, "semget"}, + {394, "semctl"}, {395, "shmget"}, {396, "shmctl"}, {397, "shmat"}, + {398, "shmdt"}, {399, "msgget"}, {400, "msgsnd"}, {401, "msgrcv"}, + {402, "msgctl"}, {403, "clock_gettime64"}, {404, "clock_settime64"}, {405, "clock_adjtime64"}, + {406, "clock_getres_time64"}, {407, "clock_nanosleep_time64"}, {408, "timer_gettime64"}, {409, "timer_settime64"}, + {410, "timerfd_gettime64"}, {411, "timerfd_settime64"}, {412, "utimensat_time64"}, {413, "pselect6_time64"}, + {414, "ppoll_time64"}, {416, "io_pgetevents_time64"}, {417, "recvmmsg_time64"}, {418, "mq_timedsend_time64"}, + {419, "mq_timedreceive_time64"}, {420, "semtimedop_time64"}, {421, "rt_sigtimedwait_time64"}, {422, "futex_time64"}, + {423, "sched_rr_get_interval_time64"}, {424, "pidfd_send_signal"}, {425, "io_uring_setup"}, {426, "io_uring_enter"}, + {427, "io_uring_register"}, {428, "open_tree"}, {429, "move_mount"}, {430, "fsopen"}, + {431, "fsconfig"}, {432, "fsmount"}, {433, "fspick"}, {434, "pidfd_open"}, + {435, "clone3"}, {436, "close_range"}, {437, "openat2"}, {438, "pidfd_getfd"}, + {439, "faccessat2"}, {440, "process_madvise"}, {441, "epoll_pwait2"}, {442, "mount_setattr"}, + {443, "quotactl_fd"}, {444, "landlock_create_ruleset"}, {445, "landlock_add_rule"}, {446, "landlock_restrict_self"}, + {447, "memfd_secret"}, {448, "process_mrelease"}, {449, "futex_waitv"}, {450, "set_mempolicy_home_node"}, + {451, "cachestat"}, {452, "fchmodat2"}, {453, "map_shadow_stack"}, {454, "futex_wake"}, + {455, "futex_wait"}, {456, "futex_requeue"}, {457, "statmount"}, {458, "listmount"}, + {459, "lsm_get_self_attr"}, {460, "lsm_set_self_attr"}, {461, "lsm_list_modules"}, + }; + + template + const char* Find(const SyscallEntry (&table)[N], uint64_t number) + { + auto end = table + N; + auto it = std::lower_bound(table, end, number, [](const SyscallEntry& entry, uint64_t value) { return entry.number < value; }); + return it != end && it->number == number ? it->name : nullptr; + } + } // namespace + + + const char* SyscallName(uint32_t auditArch, uint64_t number) + { + switch (auditArch) + { + case AuditArchX86_64: + return Find(g_x86_64, number); + case AuditArchI386: + return Find(g_i386, number); + default: + return nullptr; + } + } + + + static std::string Call(const PtraceEngine::SyscallInfo& info) + { + const char* name = SyscallName(info.arch, info.number); + std::string text = name ? name : "syscall_" + std::to_string(info.number); + text += "("; + for (size_t i = 0; i < 6; i++) + { + char buffer[32]; + snprintf(buffer, sizeof(buffer), "%s0x%" PRIx64, i ? ", " : "", info.args[i]); + text += buffer; + } + return text + ")"; + } + + + std::string DescribeSyscall(const PtraceEngine::SyscallInfo& info, bool verbose) + { + std::string text; + switch (info.op) + { + case PtraceEngine::SyscallInfo::Entry: + text = (verbose ? "system call entry: " : "") + Call(info); + break; + case PtraceEngine::SyscallInfo::Seccomp: + { + char buffer[48]; + snprintf(buffer, sizeof(buffer), " (seccomp data 0x%x)", info.seccompData); + text = (verbose ? "seccomp stop: " : "") + Call(info) + buffer; + break; + } + case PtraceEngine::SyscallInfo::Exit: + { + text = verbose ? "system call exit: = " : "= "; + if (info.isError) + text += std::to_string(info.returnValue) + " (" + strerror((int)-info.returnValue) + ")"; + else + text += std::to_string(info.returnValue); + break; + } + default: + return "not stopped at a system call"; + } + + if (verbose) + { + char buffer[96]; + snprintf(buffer, sizeof(buffer), "\npc 0x%" PRIx64 ", sp 0x%" PRIx64, info.instructionPointer, info.stackPointer); + text += buffer; + } + return text; + } +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracesyscall.h b/core/adapters/ptrace/ptracesyscall.h new file mode 100644 index 00000000..78b23e3c --- /dev/null +++ b/core/adapters/ptrace/ptracesyscall.h @@ -0,0 +1,36 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include "ptraceengine.h" + +namespace BinaryNinjaDebugger { + // The AUDIT_ARCH_* values that PTRACE_GET_SYSCALL_INFO reports. They say which system call table a number belongs + // to, which is not always the architecture of the debugger's table: a 32-bit program on a 64-bit kernel makes the + // system calls of i386. + constexpr uint32_t AuditArchX86_64 = 0xC000003E; + constexpr uint32_t AuditArchI386 = 0x40000003; + + // The name of a system call, or nullptr if there is no table for the architecture, or no such number in it + const char* SyscallName(uint32_t auditArch, uint64_t number); + + // One line that tells what the stop was: `openat(0xffffff9c, 0x7ffc1000, 0x0, 0x0, 0x0, 0x0)` at an entry, and + // `= 3` or `= -2 (No such file or directory)` at an exit. With `verbose` the line has the registers and the kind of + // the stop in front. The arguments are all six registers, because the number of them is not in the table. + std::string DescribeSyscall(const PtraceEngine::SyscallInfo& info, bool verbose = false); +} // namespace BinaryNinjaDebugger From 360f89b1140f1b4ab5396b26aa1e515eaa7edd27 Mon Sep 17 00:00:00 2001 From: Bradley Fernandez Date: Thu, 5 Nov 2026 13:16:05 -0500 Subject: [PATCH 4/6] Bound engine waits, output and breakpoint cleanup Put deadlines on waits and report unresponsive threads. Bound and batch terminal output, drain shutdown output, and handle teardown from an event handler or while a handler is blocked. Check ptrace operations that maintain thread/breakpoint invariants. Centralize breakpoint suspension/restoration, retain failed restores for retry, and abort detach when cleanup fails. Release non-thread clones and only claim hardware traps from active slots. --- core/adapters/ptrace/ptraceadapter.cpp | 63 ++- core/adapters/ptrace/ptraceadapter.h | 6 +- core/adapters/ptrace/ptracearch.cpp | 10 + core/adapters/ptrace/ptracearch.h | 12 + core/adapters/ptrace/ptraceengine.cpp | 609 +++++++++++++++++++------ core/adapters/ptrace/ptraceengine.h | 125 ++++- core/adapters/ptrace/ptracemodule.cpp | 6 +- core/adapters/ptrace/ptracestep.cpp | 20 +- core/adapters/ptrace/ptracestep.h | 2 +- core/adapters/ptrace/ptracesyscall.cpp | 6 +- 10 files changed, 679 insertions(+), 180 deletions(-) diff --git a/core/adapters/ptrace/ptraceadapter.cpp b/core/adapters/ptrace/ptraceadapter.cpp index 4eff0ebb..a18faef0 100644 --- a/core/adapters/ptrace/ptraceadapter.cpp +++ b/core/adapters/ptrace/ptraceadapter.cpp @@ -198,6 +198,7 @@ namespace BinaryNinjaDebugger { PtraceAdapter::~PtraceAdapter() { + m_destroying = true; m_stepper.reset(); m_engine.reset(); } @@ -301,6 +302,46 @@ namespace BinaryNinjaDebugger { void PtraceAdapter::HandleEngineEvent(const PtraceEngine::Event& event) { + if (m_destroying) + return; + + if (!event.errors.empty()) + { + std::string text; + for (const auto& error : event.errors) + text += (text.empty() ? "" : "\n") + error; + + DebuggerEvent failure; + failure.type = ErrorEventType; + failure.data.errorData.shortError = "PTRACE engine error"; + failure.data.errorData.error = "PTRACE: " + text + + "\nThe debugger's picture of the target may be wrong from here on."; + PostDebuggerEvent(failure); + } + + for (const auto& note : event.notes) + { + DebuggerEvent message; + message.type = BackendMessageEventType; + message.data.messageData.message = "PTRACE: " + note + "\n"; + PostDebuggerEvent(message); + } + + if (!event.unresponsive.empty()) + { + std::string threads; + for (uint32_t tid : event.unresponsive) + threads += (threads.empty() ? "" : ", ") + std::to_string(tid); + + DebuggerEvent message; + message.type = BackendMessageEventType; + message.data.messageData.message = fmt::format( + "PTRACE: thread(s) {} did not answer in time, and the debugger went on without {}. A thread in " + "uninterruptible sleep, on NFS or FUSE for example, neither stops nor dies until its I/O is done.\n", + threads, event.unresponsive.size() == 1 ? "it" : "them"); + PostDebuggerEvent(message); + } + DebuggerEvent dbgevt; switch (event.type) { @@ -336,7 +377,7 @@ namespace BinaryNinjaDebugger { } // A library was loaded or unloaded, which may be where a pending breakpoint goes if (event.breakpoint && m_loaderBreakpoint && m_arch.load() - && ReadArchRegister(m_arch.load()->pc) == m_loaderBreakpoint) + && ReadRegister64(m_arch.load()->pc) == m_loaderBreakpoint) { ApplyBreakpoints(); m_engine->Resume(false, 0); @@ -346,8 +387,8 @@ namespace BinaryNinjaDebugger { if (m_stepper && m_stepper->IsActive()) { auto arch = m_arch.load(); - uint64_t pc = arch ? ReadArchRegister(arch->pc) : 0; - uint64_t sp = arch ? ReadArchRegister(arch->sp) : 0; + uint64_t pc = arch ? ReadRegister64(arch->pc) : 0; + uint64_t sp = arch ? ReadRegister64(arch->sp) : 0; auto result = m_stepper->OnStop(event, pc, sp, IsUserBreakpoint(pc)); if (result == PtraceStepper::Result::Consumed) break; @@ -365,7 +406,7 @@ namespace BinaryNinjaDebugger { "PTRACE: signal {} ({}) was delivered to thread {}, which is stopped at the start of its handler, " "0x{:x}\n", event.signalHandler, strsignal(event.signalHandler), event.tid, - arch ? ReadArchRegister(arch->pc) : 0); + arch ? ReadRegister64(arch->pc) : 0); PostDebuggerEvent(message); } if (event.syscall) @@ -393,7 +434,7 @@ namespace BinaryNinjaDebugger { ForgetKnownBreakpoints(); if (m_stepper) m_stepper->Cancel(); - ClearBreakpoints(); + ClearAppliedBreakpointState(); m_lastStopReason = ProcessExited; m_exitCode = event.signal ? 128 + event.signal : event.exitCode; dbgevt.type = TargetExitedEventType; @@ -405,7 +446,7 @@ namespace BinaryNinjaDebugger { ForgetKnownBreakpoints(); if (m_stepper) m_stepper->Cancel(); - ClearBreakpoints(); + ClearAppliedBreakpointState(); dbgevt.type = DetachedEventType; PostDebuggerEvent(dbgevt); break; @@ -934,7 +975,7 @@ namespace BinaryNinjaDebugger { } - uint64_t PtraceAdapter::ReadArchRegister(const std::string& name) + uint64_t PtraceAdapter::ReadRegister64(const std::string& name) { return (uint64_t)ReadRegister(name).m_value; } @@ -1499,14 +1540,14 @@ namespace BinaryNinjaDebugger { uint64_t PtraceAdapter::GetInstructionOffset() { auto arch = m_arch.load(); - return arch ? ReadArchRegister(arch->pc) : 0; + return arch ? ReadRegister64(arch->pc) : 0; } uint64_t PtraceAdapter::GetStackPointer() { auto arch = m_arch.load(); - return arch ? ReadArchRegister(arch->sp) : 0; + return arch ? ReadRegister64(arch->sp) : 0; } @@ -1676,7 +1717,7 @@ namespace BinaryNinjaDebugger { bool wasStepping = event.singleStep || (m_stepper && m_stepper->IsActive()); if (m_stepper) m_stepper->Cancel(); - ClearBreakpoints(); + ClearAppliedBreakpointState(); ResetTargetState(); m_arch = m_engine->GetArch(); @@ -1991,7 +2032,7 @@ namespace BinaryNinjaDebugger { } - void PtraceAdapter::ClearBreakpoints() + void PtraceAdapter::ClearAppliedBreakpointState() { std::lock_guard lock(m_breakpointMutex); m_breakpoints.clear(); diff --git a/core/adapters/ptrace/ptraceadapter.h b/core/adapters/ptrace/ptraceadapter.h index 62e3f816..1ad33b07 100644 --- a/core/adapters/ptrace/ptraceadapter.h +++ b/core/adapters/ptrace/ptraceadapter.h @@ -43,6 +43,8 @@ namespace BinaryNinjaDebugger { std::mutex m_registerMutex; std::shared_ptr> m_registers; bool m_firstStop = false; + // Set when the adapter is being destroyed. A handler that has not started does nothing then. + std::atomic m_destroying {false}; bool m_attached = false; bool m_stopAtSystemEntry = false; @@ -88,7 +90,7 @@ namespace BinaryNinjaDebugger { std::string ContinueToSyscall(PtraceEngine::SyscallMode mode); std::string DescribeCurrentSyscall(); std::string SetSyscallField(const std::string& field, const std::string& value); - void ClearBreakpoints(); + void ClearAppliedBreakpointState(); void ForgetKnownBreakpoints(); void SyncEngineSettings(); void HandleExec(const PtraceEngine::Event& event); @@ -101,7 +103,7 @@ namespace BinaryNinjaDebugger { std::string RefreshSymbolsAfterExec(const std::string& program); void BuildRegisterList(); std::shared_ptr> GetRegisterList(); - uint64_t ReadArchRegister(const std::string& name); + uint64_t ReadRegister64(const std::string& name); bool ReadRegisterOf(uint32_t tid, const std::string& name, uint64_t& value); std::vector GetModules(); std::shared_ptr GetElf(const std::string& path); diff --git a/core/adapters/ptrace/ptracearch.cpp b/core/adapters/ptrace/ptracearch.cpp index 014442c0..31429601 100644 --- a/core/adapters/ptrace/ptracearch.cpp +++ b/core/adapters/ptrace/ptracearch.cpp @@ -106,6 +106,14 @@ namespace BinaryNinjaDebugger { } void OnTrap(pid_t tid) override { WriteDr(tid, 6, 0); } + + // DR6 has a bit for each of the four breakpoints that were met. Linux keeps a virtual DR6 for the tracer. + uint64_t TriggeredSlots(pid_t tid, bool& known) override + { + unsigned long dr6 = 0; + known = ReadDr(tid, 6, dr6); + return known ? (dr6 & 0xf) : 0; + } }; @@ -184,6 +192,7 @@ namespace BinaryNinjaDebugger { arch.breakpointPcAdjust = 1; arch.hwDebug = NativeX86HwDebug(); arch.sysemu = true; + arch.trapInstructions = {{0xcd, 0x03}}; // The order of user_regs_struct: r15 r14 r13 r12 rbp rbx r11 r10 r9 r8 rax rcx rdx rsi rdi orig_rax rip cs // eflags rsp ss fs_base gs_base ds es fs gs. The registers are listed in the order GDB uses. @@ -217,6 +226,7 @@ namespace BinaryNinjaDebugger { arch.breakpointPcAdjust = 1; arch.hwDebug = NativeX86HwDebug(); arch.sysemu = true; + arch.trapInstructions = {{0xcd, 0x03}}; // The order of the 32-bit user_regs_struct: ebx ecx edx esi edi ebp eax xds xes xfs xgs orig_eax eip xcs // eflags esp xss diff --git a/core/adapters/ptrace/ptracearch.h b/core/adapters/ptrace/ptracearch.h index 7fb9d706..11ac2764 100644 --- a/core/adapters/ptrace/ptracearch.h +++ b/core/adapters/ptrace/ptracearch.h @@ -51,6 +51,14 @@ namespace BinaryNinjaDebugger { virtual bool Clear(pid_t tid, size_t slot) = 0; // Called after a thread trapped on one of the slots virtual void OnTrap(pid_t tid) {} + // Which slots the trap of a thread that is stopped is for, as bits from slot 0 up. `known` says whether the + // architecture can tell. If it cannot, any trap of the debug registers counts as one of a slot that is in use. Called + // before OnTrap. + virtual uint64_t TriggeredSlots(pid_t tid, bool& known) + { + known = false; + return 0; + } // Whether a watchpoint reports before its access has happened, so that the access has to be stepped over. // Execute breakpoints always report first. virtual bool DataTrapsBeforeAccess() const { return false; } @@ -74,6 +82,10 @@ namespace BinaryNinjaDebugger { PtraceHwDebug* hwDebug = nullptr; // Whether PTRACE_SYSEMU works. It began on x86. bool sysemu = false; + // Other encodings of an instruction that traps like the breakpoint but is not one of the debugger's, each ending where + // the PC is after the trap: on x86 the two-byte `int $3`. They are how a trap of the target is told from the end of + // a single step. + std::vector> trapInstructions; // Whether a register that is part of another one is at the low or the high end of it, which is what the sub-registers // that are derived rely on bool littleEndian = true; diff --git a/core/adapters/ptrace/ptraceengine.cpp b/core/adapters/ptrace/ptraceengine.cpp index 8c768370..2333d687 100644 --- a/core/adapters/ptrace/ptraceengine.cpp +++ b/core/adapters/ptrace/ptraceengine.cpp @@ -25,11 +25,11 @@ limitations under the License. #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -94,7 +94,7 @@ namespace BinaryNinjaDebugger { KernelSyscallInfoSeccomp = 3 }; - static bool IsSilentSignal(int signal) + static bool ShouldAutoContinueSignal(int signal) { switch (signal) { @@ -120,7 +120,10 @@ namespace BinaryNinjaDebugger { } - PtraceEngine::PtraceEngine(EventHandler handler) : m_handler(std::move(handler)) {} + PtraceEngine::PtraceEngine(EventHandler handler) : m_core(std::make_shared()) + { + m_core->handler = std::make_shared(std::move(handler)); + } PtraceEngine::~PtraceEngine() @@ -144,12 +147,31 @@ namespace BinaryNinjaDebugger { if (m_eventThread.joinable()) { + // Nothing is called after this, and what was queued is dropped + { + std::lock_guard lock(m_core->mutex); + m_core->stop = true; + m_core->handler.reset(); + m_core->events.clear(); + } + m_core->cv.notify_all(); + + if (m_eventThread.get_id() == std::this_thread::get_id()) { - std::lock_guard lock(m_eventMutex); - m_eventStop = true; + // Destroyed by its own handler, which cannot wait for itself + m_eventThread.detach(); + } + else + { + std::unique_lock lock(m_core->mutex); + bool finished = m_core->doneCv.wait_for( + lock, std::chrono::milliseconds(m_teardownWaitMs.load()), [this] { return m_core->done; }); + lock.unlock(); + if (finished) + m_eventThread.join(); + else + m_eventThread.detach(); } - m_eventCv.notify_all(); - m_eventThread.join(); } if (m_masterFd >= 0) @@ -159,11 +181,82 @@ namespace BinaryNinjaDebugger { } + PtraceEngine::WaitResult PtraceEngine::WaitForThread(pid_t tid, int& status, std::chrono::milliseconds timeout) + { + auto deadline = std::chrono::steady_clock::now() + timeout; + int idle = 0; + while (true) + { + pid_t result = waitpid(tid, &status, __WALL | WNOHANG); + if (result == tid) + return WaitResult::Status; + if (result < 0) + { + if (errno == EINTR) + continue; + return WaitResult::Gone; + } + if (std::chrono::steady_clock::now() >= deadline) + return WaitResult::Timeout; + + // A thread that was asked to stop usually has by the time it is looked at again, so yield first + if (++idle < 50) + sched_yield(); + else + std::this_thread::sleep_for(std::chrono::microseconds(50 << std::min((idle - 50) / 20, 5))); + } + } + + + // Kills a task that is ours and waits a while for it to be gone + void PtraceEngine::KillAndReap(pid_t pid) + { + kill(pid, SIGKILL); + auto deadline = std::chrono::steady_clock::now() + WaitTimeout(); + while (true) + { + int status = 0; + auto remaining = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); + auto result = WaitForThread(pid, status, std::max(remaining, std::chrono::milliseconds(0))); + if (result != WaitResult::Status || WIFEXITED(status) || WIFSIGNALED(status)) + return; + } + } + + + // The thread group that a task belongs to, or -1 if there is no such task + pid_t PtraceEngine::ThreadGroupOf(pid_t tid) + { + std::ifstream status("/proc/" + std::to_string(tid) + "/status"); + std::string line; + while (std::getline(status, line)) + { + if (line.rfind("Tgid:", 0) == 0) + return atoi(line.c_str() + 5); + } + return -1; + } + + + // The threads that were given up on, for an event. The ones that are not in m_threads are only told once. + std::vector PtraceEngine::TakeUnresponsive() + { + std::vector result = std::move(m_lingering); + m_lingering.clear(); + for (const auto& [tid, info] : m_threads) + { + if (info.unresponsive && !info.stopped) + result.push_back(tid); + } + return result; + } + + bool PtraceEngine::Launch(const LaunchOptions& options, std::string& error) { m_options = options; auto result = m_launchResult.get_future(); - m_eventThread = std::thread(&PtraceEngine::EventMain, this); + m_eventThread = std::thread(&PtraceEngine::EventLoop, m_core); m_tracerThread = std::thread(&PtraceEngine::TracerMain, this); error = result.get(); return error.empty(); @@ -176,7 +269,7 @@ namespace BinaryNinjaDebugger { m_attachPid = pid; m_attached = true; auto result = m_launchResult.get_future(); - m_eventThread = std::thread(&PtraceEngine::EventMain, this); + m_eventThread = std::thread(&PtraceEngine::EventLoop, m_core); m_tracerThread = std::thread(&PtraceEngine::TracerMain, this); error = result.get(); return error.empty(); @@ -533,10 +626,23 @@ namespace BinaryNinjaDebugger { void PtraceEngine::PushEvent(const Event& event) { { - std::lock_guard lock(m_eventMutex); - m_events.push_back(event); + std::lock_guard lock(m_core->mutex); + if (event.type == OutputEvent) + { + m_core->pendingOutput += event.data.size(); + // Output that has not been taken up yet is joined with what comes after it, which keeps the order, and + // which is one round trip to the handler instead of many when it is slow + static constexpr size_t maxChunk = 64 * 1024; + if (!m_core->events.empty() && m_core->events.back().type == OutputEvent + && m_core->events.back().data.size() + event.data.size() <= maxChunk) + { + m_core->events.back().data += event.data; + return; + } + } + m_core->events.push_back(event); } - m_eventCv.notify_one(); + m_core->cv.notify_one(); } @@ -549,7 +655,7 @@ namespace BinaryNinjaDebugger { } - void PtraceEngine::Publish() + void PtraceEngine::PublishThreadSnapshot() { std::lock_guard lock(m_infoMutex); m_publishedThreads.clear(); @@ -569,24 +675,61 @@ namespace BinaryNinjaDebugger { } - void PtraceEngine::EventMain() + void PtraceEngine::EventLoop(std::shared_ptr core) { while (true) { Event event; + std::shared_ptr handler; { - std::unique_lock lock(m_eventMutex); - m_eventCv.wait(lock, [this] { return m_eventStop || !m_events.empty(); }); - if (m_eventStop) - return; + std::unique_lock lock(core->mutex); + core->cv.wait(lock, [&core] { return core->stop || !core->events.empty(); }); + if (core->stop) + break; - event = std::move(m_events.front()); - m_events.pop_front(); + event = std::move(core->events.front()); + core->events.pop_front(); + // This call is made with a share of the handler, so that the engine letting go of it does not end it + handler = core->handler; + } + if (event.type == OutputEvent) + { + core->pendingOutput -= event.data.size(); + std::lock_guard lock(core->outputMutex); + core->outputCv.notify_all(); } if (event.type == TaskEvent) event.task(); - else - m_handler(event); + else if (handler && *handler) + (*handler)(event); + } + + { + std::lock_guard lock(core->mutex); + core->done = true; + } + core->doneCv.notify_all(); + } + + + // What is in the terminal when the reading is asked to stop. The amount is capped, because a target that goes on writing + // never runs out of it. + void PtraceEngine::DrainOutput(char* buffer, size_t size) + { + for (int chunk = 0; chunk < 64; chunk++) + { + auto count = read(m_masterFd, buffer, size); + if (count <= 0) + { + if (count < 0 && errno == EINTR) + continue; + return; + } + + Event event; + event.type = OutputEvent; + event.data.assign(buffer, count); + PushEvent(event); } } @@ -597,13 +740,29 @@ namespace BinaryNinjaDebugger { while (true) { if (m_ioStop) + { + DrainOutput(buffer, sizeof(buffer)); return; + } - short events = POLLIN; + short events = 0; + bool wantInput = false; { std::lock_guard lock(m_inputMutex); - if (!m_inputQueue.empty()) - events |= POLLOUT; + wantInput = !m_inputQueue.empty(); + } + if (m_core->pendingOutput < m_outputLimit) + events |= POLLIN; + if (wantInput) + events |= POLLOUT; + if (!events) + { + // Too much output is waiting for the handler, and there is nothing to write. Not reading is what makes the + // target wait when its terminal is full. + std::unique_lock lock(m_core->outputMutex); + m_core->outputCv.wait_for(lock, std::chrono::milliseconds(50), + [this] { return m_ioStop || m_core->pendingOutput < m_outputLimit; }); + continue; } pollfd fd {m_masterFd, events, 0}; int ready = poll(&fd, 1, 50); @@ -661,7 +820,16 @@ namespace BinaryNinjaDebugger { } } else if (fd.revents & (POLLERR | POLLHUP | POLLNVAL)) - return; + { + if (events & POLLIN) + return; + + // The terminal is closed, but there is output that has not been read, and it is not read while the handler is + // behind. It is read when the handler has caught up. + std::unique_lock lock(m_core->outputMutex); + m_core->outputCv.wait_for(lock, std::chrono::milliseconds(50), + [this] { return m_ioStop || m_core->pendingOutput < m_outputLimit; }); + } } } @@ -772,14 +940,15 @@ namespace BinaryNinjaDebugger { if (slaveName[0]) { - setsid(); + if (setsid() < 0) + ChildFail(errorPipe[1]); int slave = open(slaveName, O_RDWR); if (slave < 0) ChildFail(errorPipe[1]); + // A terminal that cannot be the controlling one still works for input and output ioctl(slave, TIOCSCTTY, 0); - dup2(slave, 0); - dup2(slave, 1); - dup2(slave, 2); + if (dup2(slave, 0) < 0 || dup2(slave, 1) < 0 || dup2(slave, 2) < 0) + ChildFail(errorPipe[1]); if (slave > 2) close(slave); } @@ -826,12 +995,19 @@ namespace BinaryNinjaDebugger { if (count == (ssize_t)sizeof(childError)) { - waitpid(pid, nullptr, __WALL); + int ignored = 0; + WaitForThread(pid, ignored, WaitTimeout()); return std::string("failed to execute ") + m_options.path + ": " + strerror(childError); } int status = 0; - if (waitpid(pid, &status, __WALL) < 0 || !WIFSTOPPED(status)) + auto waited = WaitForThread(pid, status, WaitTimeout()); + if (waited == WaitResult::Timeout) + { + KillAndReap(pid); + return "the target did not stop within " + std::to_string(WaitTimeout().count()) + " ms of being started"; + } + if (waited == WaitResult::Gone || !WIFSTOPPED(status)) return "the target exited before it could be traced"; if (ptrace(PTRACE_SETOPTIONS, pid, nullptr, @@ -839,26 +1015,22 @@ namespace BinaryNinjaDebugger { | PTRACE_O_TRACEVFORKDONE | PTRACE_O_TRACEEXEC | PTRACE_O_TRACESYSGOOD)) != 0) { int error = errno; - kill(pid, SIGKILL); - while (waitpid(pid, nullptr, __WALL) < 0 && errno == EINTR) - {} + KillAndReap(pid); return std::string("failed to configure ptrace options: ") + strerror(error); } m_pid = pid; - auto adoptError = AdoptTarget(); + auto adoptError = InitializeTargetAccess(); if (!adoptError.empty()) { - kill(pid, SIGKILL); - while (waitpid(pid, nullptr, __WALL) < 0 && errno == EINTR) - {} + KillAndReap(pid); m_pid = -1; return adoptError; } ThreadInfo info; info.stopped = true; m_threads[pid] = info; - Publish(); + PublishThreadSnapshot(); if (m_masterFd >= 0) { @@ -866,16 +1038,28 @@ namespace BinaryNinjaDebugger { m_ioThread = std::thread(&PtraceEngine::IoMain, this); } + // A container can forbid personality(), and then the target runs with ASLR on, which is not what was asked + if (m_options.disableAslr) + { + std::ifstream file("/proc/" + std::to_string(pid) + "/personality"); + unsigned long personalityBits = 0; + file >> std::hex >> personalityBits; + if (file && !(personalityBits & ADDR_NO_RANDOMIZE)) + QueueNote("ASLR could not be turned off for the target. The system does not allow personality(), which is how " + "a container with the default seccomp profile is set up. The addresses of the target change on every run."); + } + Event event; event.type = StoppedEvent; event.tid = pid; event.signal = WSTOPSIG(status); + event.notes = TakeNotes(); PushEvent(event); return ""; } - std::string PtraceEngine::AdoptTarget() + std::string PtraceEngine::InitializeTargetAccess() { m_memFd = open(("/proc/" + std::to_string(m_pid) + "/mem").c_str(), O_RDWR | O_CLOEXEC); if (m_memFd < 0) @@ -938,6 +1122,31 @@ namespace BinaryNinjaDebugger { if (listThreads().empty()) return "failed to attach to process " + std::to_string(pid) + ": there is no such process"; + // Whether a thread has gone, or is going: it is not in the list any more, or it is a zombie. It can take a moment + // for the state to show, so it is looked at a few times. + auto threadIsGoing = [pid](pid_t tid) { + for (int attempt = 0; attempt < 5; attempt++) + { + std::ifstream status("/proc/" + std::to_string(pid) + "/task/" + std::to_string(tid) + "/status"); + if (!status) + return true; + + std::string line; + while (std::getline(status, line)) + { + if (line.rfind("State:", 0) == 0) + { + auto at = line.find_first_not_of(" \t", 6); + if (at != std::string::npos && (line[at] == 'Z' || line[at] == 'X')) + return true; + break; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + return false; + }; + std::vector attached; auto detachAll = [&attached]() { for (pid_t tid : attached) @@ -958,7 +1167,9 @@ namespace BinaryNinjaDebugger { if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr) != 0) { int error = errno; - if (tid != pid && error == ESRCH) + // A thread that is exiting can still be listed, and refuses with ESRCH, or with EPERM once its memory + // is gone. That is not a refusal to trace the process. + if (tid != pid && (error == ESRCH || error == EPERM) && threadIsGoing(tid)) continue; detachAll(); return AttachErrorMessage(pid, error); @@ -968,13 +1179,20 @@ namespace BinaryNinjaDebugger { // SIGSTOP comes after it. bool stopped = false; bool gone = false; + auto stopDeadline = std::chrono::steady_clock::now() + WaitTimeout(); for (int attempt = 0; attempt < 16 && !stopped && !gone; attempt++) { int status = 0; - if (waitpid(tid, &status, __WALL) < 0) + auto remaining = std::chrono::duration_cast( + stopDeadline - std::chrono::steady_clock::now()); + auto waited = WaitForThread(tid, status, std::max(remaining, std::chrono::milliseconds(0))); + if (waited == WaitResult::Timeout) + { + // Not stopped, and not gone: the message below says so + break; + } + if (waited == WaitResult::Gone) { - if (errno == EINTR) - continue; gone = true; } else if (WIFEXITED(status) || WIFSIGNALED(status)) @@ -1025,7 +1243,7 @@ namespace BinaryNinjaDebugger { } m_pid = pid; - auto adoptError = AdoptTarget(); + auto adoptError = InitializeTargetAccess(); if (!adoptError.empty()) { detachAll(); @@ -1040,12 +1258,14 @@ namespace BinaryNinjaDebugger { } auto& leader = m_threads[pid]; leader.atReportedStop = ReadPc(pid, leader.reportedPc); - Publish(); + PublishThreadSnapshot(); Event event; event.type = StoppedEvent; event.tid = pid; event.signal = SIGSTOP; + event.notes = TakeNotes(); + event.errors = TakeErrors(); PushEvent(event); return ""; } @@ -1151,7 +1371,7 @@ namespace BinaryNinjaDebugger { // Works out who owns a SIGTRAP. Returns false if an internal trap is not worth reporting. - bool PtraceEngine::ClassifyTrap(pid_t tid, ThreadInfo& info, Classified& result) + bool PtraceEngine::ProcessTrap(pid_t tid, ThreadInfo& info, ThreadStatusResult& result) { siginfo_t signalInfo {}; bool haveInfo = ptrace(PTRACE_GETSIGINFO, tid, nullptr, &signalInfo) == 0; @@ -1188,8 +1408,13 @@ namespace BinaryNinjaDebugger { if (code == TRAP_HWBKPT) { - bool ours = std::any_of(m_hardwareSlots.begin(), m_hardwareSlots.end(), - [](const HardwareSlot& slot) { return slot.used; }); + // A slot that is in use is not enough to make the trap ours: when the architecture can say which slots the trap + // is for, one of them has to be it + bool known = false; + uint64_t triggered = m_arch && m_arch->hwDebug ? m_arch->hwDebug->TriggeredSlots(tid, known) : 0; + bool ours = false; + for (size_t i = 0; i < m_hardwareSlots.size(); i++) + ours |= m_hardwareSlots[i].used && (!known || ((triggered >> i) & 1)); if (ours && m_arch && m_arch->hwDebug) { m_arch->hwDebug->OnTrap(tid); @@ -1238,8 +1463,9 @@ namespace BinaryNinjaDebugger { if (ours || removed) { - if (m_arch->breakpointPcAdjust) - WritePc(tid, address); + if (m_arch->breakpointPcAdjust && !WritePc(tid, address)) + QueueError(fmt::format("thread {} stopped at the breakpoint at 0x{:x}, and its PC could not be moved back to it. " + "The PC that is reported is 0x{:x}, which is after the breakpoint.", tid, address, pc)); // A thread that trapped on a breakpoint that has just been removed only needs to run again if (removed) { @@ -1257,6 +1483,21 @@ namespace BinaryNinjaDebugger { std::vector instruction(m_arch->breakpointInstruction.size()); unownedTrapInstruction |= code == SI_KERNEL && RawReadMemory(address, instruction.data(), instruction.size()) && instruction == m_arch->breakpointInstruction; + + // The same trap can come from another encoding, which ends at the PC and not one byte before it + if (code == SI_KERNEL && !unownedTrapInstruction) + { + for (const auto& encoding : m_arch->trapInstructions) + { + std::vector found(encoding.size()); + if (pc >= encoding.size() && RawReadMemory(pc - encoding.size(), found.data(), found.size()) + && found == encoding) + { + unownedTrapInstruction = true; + break; + } + } + } } // Some kernels report a requested step around a syscall with a generic kernel trap rather than TRAP_TRACE. Preserve @@ -1275,48 +1516,62 @@ namespace BinaryNinjaDebugger { } - PtraceEngine::Classified PtraceEngine::Classify(pid_t tid, int status) + PtraceEngine::ThreadStatusResult PtraceEngine::ProcessThreadStatus(pid_t tid, int status) { - Classified result; - - // The breakpoint that a thread is stepping over goes back once the thread reports a stop, but not while it is - // only passing through an internal one - auto endGuard = [this, tid](bool threadAlive) { - auto it = m_threads.find(tid); - if (it != m_threads.end() && (it->second.guardSoftware || !it->second.guardSlots.empty())) - EndGuard(tid, threadAlive); - }; + ThreadStatusResult result; + // Restore suspended breakpoints at a reportable stop or thread exit, leaving them suspended across internal stops. if (!WIFSTOPPED(status)) { - endGuard(false); + RestoreBreakpoints(tid, false); m_threads.erase(tid); - Publish(); + PublishThreadSnapshot(); result.kind = StopKind::Gone; if (tid == m_pid) - FinishExit(status); + ReportExited(status); return result; } auto& info = m_threads[tid]; info.stopped = true; + info.unresponsive = false; int signal = WSTOPSIG(status); int event = status >> 16; if (event == PTRACE_EVENT_CLONE) { unsigned long newTid = 0; - ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &newTid); + if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &newTid) != 0 || newTid == 0) + { + QueueError("thread " + std::to_string(tid) + " made a new task, and its id could not be read, so the new task is " + "not managed and stays stopped"); + return result; + } + + // Any clone that is not a fork or a vfork is reported like this, and not all of them make a thread. One that does + // not is a process of its own, which is dealt with like the child of a fork. + if (ThreadGroupOf((pid_t)newTid) != m_pid) + { + QueueNote("thread " + std::to_string(tid) + " made a process with clone, and it was let go of"); + HandleFork((pid_t)newTid, false); + return result; + } + ThreadInfo created; created.awaitingInitialStop = true; m_threads[(pid_t)newTid] = created; - Publish(); + PublishThreadSnapshot(); return result; } if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK) { unsigned long child = 0; - ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &child); + if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &child) != 0 || child == 0) + { + QueueError("thread " + std::to_string(tid) + " made a child process, and its id could not be read, so the child is " + "not let go of and stays stopped"); + return result; + } HandleFork((pid_t)child, event == PTRACE_EVENT_VFORK); return result; } @@ -1334,7 +1589,7 @@ namespace BinaryNinjaDebugger { // A stop at a system call, which only happens to a thread that was resumed to one if (signal == (SIGTRAP | 0x80)) { - endGuard(true); + RestoreBreakpoints(tid, true); result.kind = StopKind::Report; result.signal = SIGTRAP; result.syscall = true; @@ -1347,7 +1602,9 @@ namespace BinaryNinjaDebugger { if (info.awaitingInitialStop) { info.awaitingInitialStop = false; - ApplyHardwareToThread(tid); + if (!ApplyHardwareToThread(tid)) + QueueError("the hardware breakpoints could not be set for the new thread " + std::to_string(tid) + + ", which will not stop at them"); return result; } if (info.expectedStops > 0) @@ -1361,7 +1618,7 @@ namespace BinaryNinjaDebugger { // The pause may have been given by another stop since, and then this signal is only left over if (m_interruptWanted.exchange(false)) { - endGuard(true); + RestoreBreakpoints(tid, true); result.kind = StopKind::Report; result.interrupted = true; } @@ -1369,7 +1626,7 @@ namespace BinaryNinjaDebugger { } } - if (IsSilentSignal(signal)) + if (ShouldAutoContinueSignal(signal)) { info.pendingSignal = signal; return result; @@ -1377,7 +1634,7 @@ namespace BinaryNinjaDebugger { if (signal == SIGTRAP) { - if (!ClassifyTrap(tid, info, result)) + if (!ProcessTrap(tid, info, result)) return result; } else @@ -1388,7 +1645,7 @@ namespace BinaryNinjaDebugger { info.pendingSignal = signal; } - endGuard(true); + RestoreBreakpoints(tid, true); result.kind = StopKind::Report; result.signal = signal; return result; @@ -1461,10 +1718,10 @@ namespace BinaryNinjaDebugger { // Lifts the breakpoints at an address, so that a thread can execute the instruction there - bool PtraceEngine::BeginGuard(pid_t tid, uint64_t address) + bool PtraceEngine::SuspendBreakpoints(pid_t tid, uint64_t address) { auto& info = m_threads[tid]; - info.guardAddress = address; + info.suspendedBreakpointAddress = address; bool success = true; { @@ -1475,7 +1732,7 @@ namespace BinaryNinjaDebugger { if (RawWriteMemory(address, it->second.original.data(), it->second.original.size())) { it->second.inserted = false; - info.guardSoftware = true; + info.suspendedSoftwareBreakpoint = true; } else { @@ -1493,7 +1750,7 @@ namespace BinaryNinjaDebugger { && (info.hardwareBeforeAccess || (slot.type == PtraceHwType::Execute && slot.address == address))) { if (m_arch->hwDebug->Clear(tid, i)) - info.guardSlots.push_back(i); + info.suspendedHardwareSlots.push_back(i); else success = false; } @@ -1502,45 +1759,58 @@ namespace BinaryNinjaDebugger { } - bool PtraceEngine::EndGuard(pid_t tid, bool threadAlive) + // Failed restorations stay recorded for retry. Only failures queue an error for the next event. + bool PtraceEngine::RestoreBreakpoints(pid_t tid, bool threadAlive) { - auto& info = m_threads[tid]; + auto thread = m_threads.find(tid); + if (thread == m_threads.end()) + return true; + auto& info = thread->second; + if (!info.suspendedSoftwareBreakpoint && info.suspendedHardwareSlots.empty()) + return true; + uint64_t address = info.suspendedBreakpointAddress; bool success = true; - if (info.guardSoftware) + if (info.suspendedSoftwareBreakpoint) { std::lock_guard lock(m_breakpointMutex); - auto it = m_breakpoints.find(info.guardAddress); + auto it = m_breakpoints.find(info.suspendedBreakpointAddress); if (it != m_breakpoints.end() && !it->second.inserted && !it->second.suspended) { if (threadAlive && !RawWriteMemory( - info.guardAddress, m_arch->breakpointInstruction.data(), m_arch->breakpointInstruction.size())) + info.suspendedBreakpointAddress, m_arch->breakpointInstruction.data(), m_arch->breakpointInstruction.size())) { success = false; + QueueError(fmt::format("could not put back the breakpoint at 0x{:x} for thread {}. " + "It is not in the target, and restoration will be retried.", address, tid)); } else { it->second.inserted = threadAlive; - info.guardSoftware = false; + info.suspendedSoftwareBreakpoint = false; } } else { - info.guardSoftware = false; + info.suspendedSoftwareBreakpoint = false; } } info.hardwareBeforeAccess = false; - auto slots = std::move(info.guardSlots); - info.guardSlots.clear(); + auto slots = std::move(info.suspendedHardwareSlots); + info.suspendedHardwareSlots.clear(); + bool hardwareRestored = true; for (size_t index : slots) { const auto& slot = m_hardwareSlots[index]; if (threadAlive && slot.used && !m_arch->hwDebug->Set(tid, index, slot.address, slot.type, slot.size)) { - info.guardSlots.push_back(index); + info.suspendedHardwareSlots.push_back(index); success = false; + hardwareRestored = false; } } + if (!hardwareRestored) + QueueError(fmt::format("could not put back the hardware breakpoints of thread {}. Restoration will be retried.", tid)); return success; } @@ -1573,9 +1843,9 @@ namespace BinaryNinjaDebugger { if (it == m_threads.end() || !it->second.stopped || !ReadPc(tid, pc)) continue; - if (!BeginGuard(tid, pc)) + if (!SuspendBreakpoints(tid, pc)) { - EndGuard(tid, true); + RestoreBreakpoints(tid, true); return false; } it->second.stepping = true; @@ -1583,7 +1853,7 @@ namespace BinaryNinjaDebugger { if (ResumeThread(tid)) return true; it->second.stepping = false; - EndGuard(tid, true); + RestoreBreakpoints(tid, true); return false; } @@ -1598,12 +1868,14 @@ namespace BinaryNinjaDebugger { { // It is stopped from the start, and has to be seen to before it can be let go int status = 0; - pid_t result; - do + auto waited = WaitForThread(child, status, WaitTimeout()); + if (waited == WaitResult::Timeout) { - result = waitpid(child, &status, __WALL); - } while (result < 0 && errno == EINTR); - if (result < 0 || !WIFSTOPPED(status)) + // It stays as it is, stopped and traced, because nothing here can let go of it before it has stopped + m_lingering.push_back(child); + return; + } + if (waited == WaitResult::Gone || !WIFSTOPPED(status)) return; { @@ -1639,6 +1911,29 @@ namespace BinaryNinjaDebugger { } } close(fd); + + // A clone with CLONE_VM that is not a thread shares the memory of the target, and is not told by a + // vfork event when it is done with it. What was written to the child is then what is in the target now, + // and the breakpoints are put back. + for (const auto& [address, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + + std::vector now(breakpoint.original.size()); + if (RawReadMemory(address, now.data(), now.size()) && now == breakpoint.original) + { + for (auto& [otherAddress, other] : m_breakpoints) + { + if (other.inserted) + RawWriteMemory(otherAddress, m_arch->breakpointInstruction.data(), + m_arch->breakpointInstruction.size()); + } + QueueNote("a process made with clone shares the memory of the target, so it can run into the " + "breakpoints, which stay where they are"); + } + break; + } } } } @@ -1650,7 +1945,7 @@ namespace BinaryNinjaDebugger { // The target has started another program. Nothing of the old one is left: not its threads, its memory, its // breakpoints or its debug registers. So this starts over, and the stop is reported so that the owner can set the // new program up before it runs. - PtraceEngine::Classified PtraceEngine::HandleExec(pid_t tid) + PtraceEngine::ThreadStatusResult PtraceEngine::HandleExec(pid_t tid) { // Every thread but one is gone, and that one is the leader from now on, whichever thread it was before std::vector gone; @@ -1695,9 +1990,9 @@ namespace BinaryNinjaDebugger { m_stepOverTid = -1; m_vforkPending = 0; m_hardwareSlots.assign(m_arch && m_arch->hwDebug ? m_arch->hwDebug->SlotCount() : 0, HardwareSlot()); - Publish(); + PublishThreadSnapshot(); - Classified result; + ThreadStatusResult result; result.kind = StopKind::Report; result.signal = SIGTRAP; result.exec = true; @@ -1724,20 +2019,22 @@ namespace BinaryNinjaDebugger { } - void PtraceEngine::ApplyHardwareToThread(pid_t tid) + bool PtraceEngine::ApplyHardwareToThread(pid_t tid) { + bool all = true; for (size_t i = 0; i < m_hardwareSlots.size(); i++) { const auto& slot = m_hardwareSlots[i]; if (slot.used) - m_arch->hwDebug->Set(tid, i, slot.address, slot.type, slot.size); + all &= m_arch->hwDebug->Set(tid, i, slot.address, slot.type, slot.size); } + return all; } void PtraceEngine::HandleStatus(pid_t tid, int status) { - auto stop = Classify(tid, status); + auto stop = ProcessThreadStatus(tid, status); bool steppingOver = tid == m_stepOverTid; switch (stop.kind) { @@ -1771,7 +2068,7 @@ namespace BinaryNinjaDebugger { } StopAll(); if (!m_done) - FinishStop(stop.tid ? stop.tid : tid, stop); + ReportStopped(stop.tid ? stop.tid : tid, stop); break; } } @@ -1780,12 +2077,29 @@ namespace BinaryNinjaDebugger { // Stops every thread that is still running, and waits for the new threads that have not reported yet. void PtraceEngine::StopAll() { + // A thread that was given up on may have stopped since. It is looked at, and not waited for. + std::vector given; + for (const auto& [tid, info] : m_threads) + { + if (info.unresponsive && !info.stopped) + given.push_back(tid); + } + for (pid_t tid : given) + { + int status = 0; + pid_t result = waitpid(tid, &status, __WALL | WNOHANG); + if (result == tid) + ProcessThreadStatus(tid, status); + if (m_done) + return; + } + while (!m_done) { pid_t next = -1; for (const auto& [tid, info] : m_threads) { - if (!info.stopped) + if (!info.stopped && !info.unresponsive) { next = tid; break; @@ -1802,18 +2116,20 @@ namespace BinaryNinjaDebugger { } int status = 0; - if (waitpid(next, &status, __WALL) < 0) + auto waited = WaitForThread(next, status, WaitTimeout()); + if (waited == WaitResult::Timeout) { - if (errno == EINTR) - continue; - status = 0; + m_threads[next].unresponsive = true; + continue; } - Classify(next, status); + if (waited == WaitResult::Gone) + status = 0; + ProcessThreadStatus(next, status); } } - void PtraceEngine::FinishStop(pid_t tid, const Classified& stop) + void PtraceEngine::ReportStopped(pid_t tid, const ThreadStatusResult& stop) { Event event; event.type = StoppedEvent; @@ -1827,12 +2143,20 @@ namespace BinaryNinjaDebugger { event.signalHandler = stop.signalHandler; event.syscall = stop.syscall; event.singleStep = stop.stepTrap; + event.unresponsive = TakeUnresponsive(); + event.notes = TakeNotes(); + event.errors = TakeErrors(); for (auto& [id, info] : m_threads) info.stepping = false; - // Once everything is stopped, no thread can still trap on a breakpoint that was removed - m_recentlyRemoved.clear(); + // Once everything is stopped, no thread can still trap on a breakpoint that was removed. A thread that was given + // up on may still be running, and can. + bool allStopped = true; + for (const auto& [id, info] : m_threads) + allStopped &= info.stopped; + if (allStopped) + m_recentlyRemoved.clear(); // Any stop is a pause, so a request for one that has not been seen yet is answered m_interruptWanted = false; @@ -1846,22 +2170,25 @@ namespace BinaryNinjaDebugger { info.atReportedStop = false; m_running = false; - Publish(); + PublishThreadSnapshot(); PushEvent(event); } - void PtraceEngine::FinishExit(int status) + void PtraceEngine::ReportExited(int status) { m_done = true; m_finished = true; m_running = false; - Publish(); + PublishThreadSnapshot(); StopIo(); Event event; event.type = ExitedEvent; event.tid = m_pid; + event.unresponsive = TakeUnresponsive(); + event.notes = TakeNotes(); + event.errors = TakeErrors(); if (WIFEXITED(status)) event.exitCode = WEXITSTATUS(status); else if (WIFSIGNALED(status)) @@ -1897,9 +2224,9 @@ namespace BinaryNinjaDebugger { if (step) { uint64_t pc; - if (!stepOver.empty() && ReadPc(tid, pc) && !BeginGuard(tid, pc)) + if (!stepOver.empty() && ReadPc(tid, pc) && !SuspendBreakpoints(tid, pc)) { - EndGuard(tid, true); + RestoreBreakpoints(tid, true); return false; } @@ -1908,8 +2235,8 @@ namespace BinaryNinjaDebugger { if (!resumed) { stepping->second.stepping = false; - if (stepping->second.guardSoftware || !stepping->second.guardSlots.empty()) - EndGuard(tid, true); + if (stepping->second.suspendedSoftwareBreakpoint || !stepping->second.suspendedHardwareSlots.empty()) + RestoreBreakpoints(tid, true); } } else if (!stepOver.empty()) @@ -1923,7 +2250,7 @@ namespace BinaryNinjaDebugger { } m_running = resumed; - Publish(); + PublishThreadSnapshot(); return resumed; } @@ -2152,8 +2479,8 @@ namespace BinaryNinjaDebugger { bool success = true; for (auto& [tid, info] : m_threads) { - if (info.guardSoftware || !info.guardSlots.empty()) - success &= EndGuard(tid, true); + if (info.suspendedSoftwareBreakpoint || !info.suspendedHardwareSlots.empty()) + success &= RestoreBreakpoints(tid, true); } { @@ -2211,16 +2538,22 @@ namespace BinaryNinjaDebugger { } tids.push_back(m_pid); + // One deadline for all of them, so that a number of threads that do not die is not a number of timeouts int status = SIGKILL; + auto deadline = std::chrono::steady_clock::now() + WaitTimeout(); for (pid_t tid : tids) { while (true) { int threadStatus = 0; - if (waitpid(tid, &threadStatus, __WALL) < 0) + auto remaining = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()); + auto waited = WaitForThread(tid, threadStatus, std::max(remaining, std::chrono::milliseconds(0))); + if (waited == WaitResult::Gone) + break; + if (waited == WaitResult::Timeout) { - if (errno == EINTR) - continue; + m_lingering.push_back(tid); break; } if (WIFEXITED(threadStatus) || WIFSIGNALED(threadStatus)) @@ -2233,7 +2566,7 @@ namespace BinaryNinjaDebugger { } m_threads.clear(); - FinishExit(status); + ReportExited(status); return true; } @@ -2265,15 +2598,27 @@ namespace BinaryNinjaDebugger { m_threads[pending].stepping = false; ResumeThread(pending); int status = 0; - if (waitpid(pending, &status, __WALL) < 0) + auto waited = WaitForThread(pending, status, WaitTimeout()); + if (waited == WaitResult::Timeout) + { + m_threads[pending].unresponsive = true; + m_threads[pending].expectedStops = 0; + break; + } + if (waited == WaitResult::Gone) break; - Classify(pending, status); + ProcessThreadStatus(pending, status); if (m_done) return false; } + // The threads that were given up on are not in the map any more once they are let go of, so they are noted now + auto givenUp = TakeUnresponsive(); if (!RemoveAllBreakpoints()) + { + m_lingering = givenUp; return false; + } bool detached = true; std::vector tids; @@ -2291,14 +2636,15 @@ namespace BinaryNinjaDebugger { } if (!detached) { - Publish(); + m_lingering = givenUp; + PublishThreadSnapshot(); return false; } m_done = true; m_finished = true; m_running = false; - Publish(); + PublishThreadSnapshot(); StopIo(); if (!m_attached) @@ -2325,6 +2671,9 @@ namespace BinaryNinjaDebugger { Event event; event.type = DetachedEvent; + event.unresponsive = givenUp; + event.notes = TakeNotes(); + event.errors = TakeErrors(); PushEvent(event); return true; } diff --git a/core/adapters/ptrace/ptraceengine.h b/core/adapters/ptrace/ptraceengine.h index 1f7de717..df18b2b7 100644 --- a/core/adapters/ptrace/ptraceengine.h +++ b/core/adapters/ptrace/ptraceengine.h @@ -81,6 +81,15 @@ namespace BinaryNinjaDebugger { int signalHandler = 0; // The thread is stopped at a system call, because it was resumed to one. See ResumeToSyscall. bool syscall = false; + // Threads that did not answer within the wait timeout, and that the engine went on without: they did not stop + // when they were asked to, or they did not die when they were killed. See SetWaitTimeout. + std::vector unresponsive; + // Things that the engine handled that the owner should know of, one line each. They come with the next stop, exit + // or detach. + std::vector notes; + // Things that went wrong that the engine cannot put right, and that leave what it says about the target in doubt: + // a breakpoint that could not be put back, a PC that could not be moved. The engine goes on, and says so. + std::vector errors; std::string data; std::function task; }; @@ -185,6 +194,9 @@ namespace BinaryNinjaDebugger { struct ThreadInfo { bool stopped = false; + // It did not stop within the wait timeout. It is not waited for again, and is looked at when it may have + // stopped, until it does. + bool unresponsive = false; bool stepping = false; bool awaitingInitialStop = false; // SIGSTOPs we sent that have not been consumed yet @@ -200,9 +212,9 @@ namespace BinaryNinjaDebugger { bool atReportedStop = false; uint64_t reportedPc = 0; // The breakpoint that is lifted while the thread steps over it - bool guardSoftware = false; - std::vector guardSlots; - uint64_t guardAddress = 0; + bool suspendedSoftwareBreakpoint = false; + std::vector suspendedHardwareSlots; + uint64_t suspendedBreakpointAddress = 0; bool hardwareBeforeAccess = false; }; @@ -229,7 +241,7 @@ namespace BinaryNinjaDebugger { Report }; - struct Classified + struct ThreadStatusResult { StopKind kind = StopKind::Internal; int signal = 0; @@ -245,7 +257,26 @@ namespace BinaryNinjaDebugger { pid_t tid = 0; }; - EventHandler m_handler; + // What the event thread works on. The thread owns a share of it, and touches nothing else of the engine, so that it + // can outlive the engine: a handler that is still running when the engine is destroyed (because it destroyed the + // engine itself, or because it waits for whoever destroys it) is left to finish on its own. + struct EventCore + { + std::mutex mutex; + std::condition_variable cv; + std::deque events; + bool stop = false; + bool done = false; + std::condition_variable doneCv; + std::shared_ptr handler; + // The bytes of output that are queued for the handler. The pty is not read while there are too many, so a target + // that writes faster than the handler takes it up is slowed down by its terminal filling, and memory stays bounded. + std::atomic pendingOutput {0}; + std::mutex outputMutex; + std::condition_variable outputCv; + }; + + std::shared_ptr m_core; LaunchOptions m_options; std::promise m_launchResult; @@ -259,10 +290,9 @@ namespace BinaryNinjaDebugger { bool m_tracerStop = false; bool m_shutdown = false; - std::mutex m_eventMutex; - std::condition_variable m_eventCv; - std::deque m_events; - bool m_eventStop = false; + std::atomic m_outputLimit {1024 * 1024}; + // How long the destructor waits for a handler that is still running + std::atomic m_teardownWaitMs {2000}; // Only touched by the tracer thread std::map m_threads; @@ -289,6 +319,13 @@ namespace BinaryNinjaDebugger { std::atomic m_interruptWanted {false}; std::atomic m_interruptInFlight {0}; std::atomic m_debugSignalHandlers {false}; + // How long a wait for a thread lasts before it is given up on, in milliseconds + std::atomic m_waitTimeoutMs {5000}; + // Tasks that were given up on and are not in m_threads: a child of a fork that did not stop, and the threads that + // did not die when the target was killed + std::vector m_lingering; + std::vector m_notes; + std::vector m_errors; pid_t m_pid = -1; pid_t m_attachPid = -1; @@ -304,23 +341,25 @@ namespace BinaryNinjaDebugger { size_t m_pendingInputBytes = 0; void TracerMain(); - void EventMain(); + static void EventLoop(std::shared_ptr core); void IoMain(); std::string Spawn(); std::string AttachToProcess(); - std::string AdoptTarget(); + std::string InitializeTargetAccess(); bool RunOnTracer(std::function function); void PushEvent(const Event& event); - void Publish(); + void PublishThreadSnapshot(); void StopIo(); + void DrainOutput(char* buffer, size_t size); bool PollThreads(); void HandleStatus(pid_t tid, int status); - Classified Classify(pid_t tid, int status); + // Consumes a waitpid status, updates thread and breakpoint state, and decides whether to report a stop. + ThreadStatusResult ProcessThreadStatus(pid_t tid, int status); bool ResumeThread(pid_t tid); bool HasSignalHandler(int signal); - bool ClassifyTrap(pid_t tid, ThreadInfo& info, Classified& result); + bool ProcessTrap(pid_t tid, ThreadInfo& info, ThreadStatusResult& result); bool RawGetRegisterSet(pid_t tid, int regset, std::vector& data); bool RawSetRegisterSet(pid_t tid, int regset, const std::vector& data); bool ReadPc(pid_t tid, uint64_t& pc); @@ -329,18 +368,47 @@ namespace BinaryNinjaDebugger { bool RawWriteMemory(uint64_t address, const void* buffer, size_t size); bool HasBreakpointAt(uint64_t address); bool NeedsStepOver(pid_t tid, const ThreadInfo& info); - bool BeginGuard(pid_t tid, uint64_t address); - bool EndGuard(pid_t tid, bool threadAlive); + bool SuspendBreakpoints(pid_t tid, uint64_t address); + bool RestoreBreakpoints(pid_t tid, bool threadAlive); bool StartNextStepOver(); bool ResumeAll(); - void ApplyHardwareToThread(pid_t tid); + bool ApplyHardwareToThread(pid_t tid); void HandleFork(pid_t child, bool sharedMemory); - Classified HandleExec(pid_t tid); + ThreadStatusResult HandleExec(pid_t tid); void ResumeBreakpointsAfterVfork(); bool RemoveAllBreakpoints(); void StopAll(); - void FinishStop(pid_t tid, const Classified& stop); - void FinishExit(int status); + enum class WaitResult + { + Status, + Timeout, + Gone + }; + + // Waits for a status of `tid` for at most `timeout`. A wait that has no deadline hangs the tracer thread, and + // with it everything that calls into the engine, for as long as a thread is stuck in uninterruptible sleep. + WaitResult WaitForThread(pid_t tid, int& status, std::chrono::milliseconds timeout); + std::chrono::milliseconds WaitTimeout() const { return std::chrono::milliseconds(m_waitTimeoutMs.load()); } + void KillAndReap(pid_t pid); + std::vector TakeUnresponsive(); + void QueueNote(const std::string& note) { m_notes.push_back(note); } + void QueueError(const std::string& error) { m_errors.push_back(error); } + std::vector TakeErrors() + { + std::vector result; + result.swap(m_errors); + return result; + } + std::vector TakeNotes() + { + std::vector result; + result.swap(m_notes); + return result; + } + pid_t ThreadGroupOf(pid_t tid); + // Finalizes the debugger state and emits the stopped event after StopAll has collected the other threads. + void ReportStopped(pid_t tid, const ThreadStatusResult& stop); + void ReportExited(int status); bool DoResume(bool step, pid_t tid, SyscallMode mode = SyscallMode::None); bool DoGetSyscallInfo(pid_t tid, SyscallInfo& info); @@ -380,6 +448,23 @@ namespace BinaryNinjaDebugger { // thread is not tied up by the caller, so it is the place for work that must not run under the caller's locks. void PostTask(std::function task); + // How long the engine waits for a thread to stop after it was asked to, to die after it was killed, and so on, + // before it goes on without it. A thread in uninterruptible sleep, on NFS or FUSE for example, does neither until + // its I/O is done. The events that follow tell which threads were given up on. + void SetWaitTimeout(std::chrono::milliseconds timeout) { m_waitTimeoutMs = (int)timeout.count(); } + + // How much output can be queued for the handler before the target's terminal is left to fill up. The output that is + // queued is joined into events of up to 64 KB, so a handler that is slow sees fewer and larger ones. + void SetOutputLimit(size_t bytes) { m_outputLimit = bytes; } + size_t PendingOutputBytes() const { return m_core->pendingOutput; } + + // The engine can be destroyed from its own handler: nothing waits for the handler that is running. It can be + // destroyed while a handler waits for the caller (an event that is posted to the controller is waited for, and the + // controller may be what destroys the engine): the destructor waits this long for the handler, and then goes on. In + // both cases the handler is not called again, and it finishes without the engine. What it does to whatever else it + // captured is its own matter. + void SetTeardownWait(std::chrono::milliseconds wait) { m_teardownWaitMs = (int)wait.count(); } + // A signal that the target has a handler for is normally delivered and the handler runs on its own. With this // set, the thread stops at the first instruction of the handler instead. void SetDebugSignalHandlers(bool enable) { m_debugSignalHandlers = enable; } diff --git a/core/adapters/ptrace/ptracemodule.cpp b/core/adapters/ptrace/ptracemodule.cpp index e89315fe..259d2923 100644 --- a/core/adapters/ptrace/ptracemodule.cpp +++ b/core/adapters/ptrace/ptracemodule.cpp @@ -122,7 +122,7 @@ namespace BinaryNinjaDebugger { } - static std::string ReadSmallFile(const std::filesystem::path& path) + static std::string ReadFileContents(const std::filesystem::path& path) { std::ifstream file(path, std::ios::binary); std::string contents((std::istreambuf_iterator(file)), std::istreambuf_iterator()); @@ -142,12 +142,12 @@ namespace BinaryNinjaDebugger { PtraceProcessInfo process; process.pid = std::stoul(name); - process.name = ReadSmallFile(entry.path() / "comm"); + process.name = ReadFileContents(entry.path() / "comm"); while (!process.name.empty() && process.name.back() == '\n') process.name.pop_back(); // The arguments are separated by null characters - std::string commandLine = ReadSmallFile(entry.path() / "cmdline"); + std::string commandLine = ReadFileContents(entry.path() / "cmdline"); std::replace(commandLine.begin(), commandLine.end(), '\0', ' '); while (!commandLine.empty() && commandLine.back() == ' ') commandLine.pop_back(); diff --git a/core/adapters/ptrace/ptracestep.cpp b/core/adapters/ptrace/ptracestep.cpp index 7de0fc3d..ba24f90d 100644 --- a/core/adapters/ptrace/ptracestep.cpp +++ b/core/adapters/ptrace/ptracestep.cpp @@ -24,7 +24,7 @@ namespace BinaryNinjaDebugger { {} - void PtraceStepper::ReleaseAll() + void PtraceStepper::EndStep() { for (uint64_t address : m_addresses) m_release(address); @@ -43,14 +43,14 @@ namespace BinaryNinjaDebugger { void PtraceStepper::Cancel() { std::lock_guard lock(m_mutex); - ReleaseAll(); + EndStep(); } bool PtraceStepper::StepOver(uint32_t tid, uint64_t pc, uint64_t sp, size_t callLength, size_t wordSize) { std::lock_guard lock(m_mutex); - ReleaseAll(); + EndStep(); if (callLength == 0) return m_engine.Resume(true, tid); @@ -66,7 +66,7 @@ namespace BinaryNinjaDebugger { if (m_engine.Resume(false, 0)) return true; - ReleaseAll(); + EndStep(); return false; } @@ -75,7 +75,7 @@ namespace BinaryNinjaDebugger { uint64_t returnAddress, uint64_t returnSp) { std::lock_guard lock(m_mutex); - ReleaseAll(); + EndStep(); // Already at the instruction that returns, so the return is the next step if (std::find(returnSites.begin(), returnSites.end(), pc) != returnSites.end()) @@ -115,7 +115,7 @@ namespace BinaryNinjaDebugger { if (m_engine.Resume(false, 0)) return true; - ReleaseAll(); + EndStep(); return false; } @@ -139,7 +139,7 @@ namespace BinaryNinjaDebugger { bool atOurs = event.breakpoint && m_addresses.count(pc); if (!atOurs || userBreakpoint) { - ReleaseAll(); + EndStep(); return Result::Ignored; } @@ -149,18 +149,18 @@ namespace BinaryNinjaDebugger { if (m_engine.Resume(false, 0)) return Result::Consumed; - ReleaseAll(); + EndStep(); return Result::Ignored; } if (m_mode == Mode::ReturnAddress) { - ReleaseAll(); + EndStep(); return Result::Finished; } // At an instruction that returns: it takes one step to be out - ReleaseAll(); + EndStep(); m_mode = Mode::FinalStep; if (m_engine.Resume(true, m_tid)) return Result::Consumed; diff --git a/core/adapters/ptrace/ptracestep.h b/core/adapters/ptrace/ptracestep.h index f9413e93..48c75a92 100644 --- a/core/adapters/ptrace/ptracestep.h +++ b/core/adapters/ptrace/ptracestep.h @@ -51,7 +51,7 @@ namespace BinaryNinjaDebugger { uint64_t m_minSp = 0; std::set m_addresses; - void ReleaseAll(); + void EndStep(); public: enum class Result diff --git a/core/adapters/ptrace/ptracesyscall.cpp b/core/adapters/ptrace/ptracesyscall.cpp index de4c1d57..90c26ee7 100644 --- a/core/adapters/ptrace/ptracesyscall.cpp +++ b/core/adapters/ptrace/ptracesyscall.cpp @@ -266,7 +266,7 @@ namespace BinaryNinjaDebugger { } - static std::string Call(const PtraceEngine::SyscallInfo& info) + static std::string FormatSyscallCall(const PtraceEngine::SyscallInfo& info) { const char* name = SyscallName(info.arch, info.number); std::string text = name ? name : "syscall_" + std::to_string(info.number); @@ -287,13 +287,13 @@ namespace BinaryNinjaDebugger { switch (info.op) { case PtraceEngine::SyscallInfo::Entry: - text = (verbose ? "system call entry: " : "") + Call(info); + text = (verbose ? "system call entry: " : "") + FormatSyscallCall(info); break; case PtraceEngine::SyscallInfo::Seccomp: { char buffer[48]; snprintf(buffer, sizeof(buffer), " (seccomp data 0x%x)", info.seccompData); - text = (verbose ? "seccomp stop: " : "") + Call(info) + buffer; + text = (verbose ? "seccomp stop: " : "") + FormatSyscallCall(info) + buffer; break; } case PtraceEngine::SyscallInfo::Exit: From 4ccc0367bbdc9b9ba303213790c9a2ca03a0b731 Mon Sep 17 00:00:00 2001 From: Bradley Fernandez Date: Thu, 5 Nov 2026 13:16:05 -0500 Subject: [PATCH 5/6] Add ELFIO metadata parsing and the Linux regression suite Replace manual ELF decoding with pinned, header-only ELFIO, preserving symbol semantics and validating malformed metadata. Wire production and test builds to its submodule and package its MIT notice. Build standalone engine/fault drivers and fixtures with CMake. Run isolated pytest scenarios with deadlines and descendant cleanup, including readelf comparisons, malformed ELF, register layouts and adapter integration. Add sanitizer/stress options, Linux CI integration and Python adapter settings. --- .gitmodules | 3 + api/python/debuggercontroller.py | 9 + core/CMakeLists.txt | 18 + core/adapters/ptrace/ptraceelf.cpp | 194 +-- core/adapters/ptrace/ptraceelf.h | 3 +- scripts/build.py | 5 + test/debugger_test.py | 193 ++- test/ptrace_engine/CMakeLists.txt | 103 ++ test/ptrace_engine/Dockerfile | 3 + test/ptrace_engine/driver.cpp | 2235 ++++++++++++++++++++++++++++ test/ptrace_engine/elfcmp.cpp | 8 + test/ptrace_engine/libtest.c | 2 + test/ptrace_engine/progs.c | 143 ++ test/ptrace_engine_test.py | 309 ++++ vendor/elfio | 1 + 15 files changed, 3105 insertions(+), 124 deletions(-) create mode 100644 test/ptrace_engine/CMakeLists.txt create mode 100644 test/ptrace_engine/Dockerfile create mode 100644 test/ptrace_engine/driver.cpp create mode 100644 test/ptrace_engine/elfcmp.cpp create mode 100644 test/ptrace_engine/libtest.c create mode 100644 test/ptrace_engine/progs.c create mode 100644 test/ptrace_engine_test.py create mode 160000 vendor/elfio diff --git a/.gitmodules b/.gitmodules index 10b902db..a42e18c6 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "vendor/flatbuffers"] path = vendor/flatbuffers url = https://github.com/google/flatbuffers.git +[submodule "vendor/elfio"] + path = vendor/elfio + url = https://github.com/serge1/ELFIO.git diff --git a/api/python/debuggercontroller.py b/api/python/debuggercontroller.py index a27137e5..446197a1 100644 --- a/api/python/debuggercontroller.py +++ b/api/python/debuggercontroller.py @@ -2307,6 +2307,15 @@ def adapter_type(self) -> str: def adapter_type(self, adapter: Union[str, bytes]) -> None: dbgcore.BNDebuggerSetAdapterType(self.handle, adapter) + @property + def adapter_settings(self) -> Optional[binaryninja.Settings]: + """Get the settings for the current debug adapter (read-only).""" + result = dbgcore.BNDebuggerGetAdapterSettings(self.handle) + if result is None: + return None + result = ctypes.cast(result, ctypes.POINTER(binaryninja.core.BNSettings)) + return binaryninja.Settings(handle=result) + @property def connection_status(self) -> DebugAdapterConnectionStatus: """ diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index e05b1ac6..f2f9f54c 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -89,6 +89,13 @@ endif() target_link_libraries(debuggercore binaryninjaapi) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + if(NOT TARGET elfio::elfio) + add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../vendor/elfio ${CMAKE_CURRENT_BINARY_DIR}/elfio EXCLUDE_FROM_ALL) + endif() + target_link_libraries(debuggercore elfio::elfio) +endif() + if(WIN32) target_link_libraries(debuggercore Msi.lib delayimp.lib wsock32 ws2_32 dbghelp.lib) target_link_libraries(debuggercore dbgengengine) @@ -110,6 +117,11 @@ else() set(LIBRARY_OUTPUT_DIRECTORY_PATH "${CMAKE_BINARY_DIR}/out/plugins") endif() +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/../vendor/elfio/LICENSE.txt + ${LIBRARY_OUTPUT_DIRECTORY_PATH}/licenses/ELFIO.txt COPYONLY) +endif() + set_target_properties(debuggercore PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_DIRECTORY_PATH} RUNTIME_OUTPUT_DIRECTORY ${LIBRARY_OUTPUT_DIRECTORY_PATH} @@ -303,3 +315,9 @@ option(BUILD_CORE_TESTS "Build core unit tests" OFF) if(BUILD_CORE_TESTS) add_subdirectory(tests) endif() + +# The ptrace engine can be tested without linking or loading Binary Ninja. +option(BUILD_PTRACE_TESTS "Build the standalone ptrace engine regression tests" OFF) +if(BUILD_PTRACE_TESTS AND CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_subdirectory(../test/ptrace_engine ${CMAKE_BINARY_DIR}/test/ptrace_engine) +endif() diff --git a/core/adapters/ptrace/ptraceelf.cpp b/core/adapters/ptrace/ptraceelf.cpp index caaffade..47f988a1 100644 --- a/core/adapters/ptrace/ptraceelf.cpp +++ b/core/adapters/ptrace/ptraceelf.cpp @@ -15,172 +15,124 @@ limitations under the License. */ #include "ptraceelf.h" -#include #include #include +#include #include namespace BinaryNinjaDebugger { - struct Elf32Types + static bool ReadSymbols(const ELFIO::elfio& file, const ELFIO::section* section, std::vector& symbols) { - using Ehdr = Elf32_Ehdr; - using Phdr = Elf32_Phdr; - using Shdr = Elf32_Shdr; - using Sym = Elf32_Sym; - }; - - struct Elf64Types - { - using Ehdr = Elf64_Ehdr; - using Phdr = Elf64_Phdr; - using Shdr = Elf64_Shdr; - using Sym = Elf64_Sym; - }; - - - static bool ReadAt(std::ifstream& file, uint64_t offset, void* buffer, size_t size) - { - file.clear(); - file.seekg(offset); - return file.read(reinterpret_cast(buffer), size).gcount() == (std::streamsize)size; - } - - - template - static void ReadSymbols(std::ifstream& file, uint64_t fileSize, const typename T::Shdr& table, - const typename T::Shdr& strings, std::vector& symbols) - { - if (table.sh_offset > fileSize || table.sh_size > fileSize - table.sh_offset || strings.sh_offset > fileSize - || strings.sh_size > fileSize - strings.sh_offset) - return; - - std::vector tableData(table.sh_size); - std::vector stringData(strings.sh_size); - if (!ReadAt(file, table.sh_offset, tableData.data(), tableData.size()) - || !ReadAt(file, strings.sh_offset, stringData.data(), stringData.size())) - return; + if (section->get_size() == 0) + return true; - size_t entrySize = table.sh_entsize ? table.sh_entsize : sizeof(typename T::Sym); - if (entrySize < sizeof(typename T::Sym)) - return; + size_t entrySize = file.get_class() == ELFIO::ELFCLASS64 ? sizeof(ELFIO::Elf64_Sym) : sizeof(ELFIO::Elf32_Sym); + if (section->get_entry_size() != entrySize || section->get_size() % entrySize != 0 + || section->get_link() >= file.sections.size()) + return false; + auto strings = file.sections[section->get_link()]; + const char* data = section->get_data(); + if (!data || !strings || strings->get_type() != ELFIO::SHT_STRTAB || !strings->get_data()) + return false; - for (size_t offset = 0; offset + sizeof(typename T::Sym) <= tableData.size(); offset += entrySize) + ELFIO::const_symbol_section_accessor table(file, section); + ELFIO::const_string_section_accessor names(strings); + if (table.get_symbols_num() != section->get_size() / entrySize) + return false; + for (ELFIO::Elf_Xword index = 0; index < table.get_symbols_num(); index++) { - typename T::Sym symbol; - memcpy(&symbol, tableData.data() + offset, sizeof(symbol)); - - unsigned type = ELF32_ST_TYPE(symbol.st_info); - bool isFunction = type == STT_FUNC || type == STT_GNU_IFUNC; - if (!isFunction && type != STT_OBJECT) - continue; - if (symbol.st_shndx == SHN_UNDEF || symbol.st_shndx >= SHN_LORESERVE || symbol.st_value == 0) + ElfSymbol result; + ELFIO::Elf64_Addr value; + ELFIO::Elf_Xword size; + unsigned char binding, type, other; + ELFIO::Elf_Half sectionIndex; + if (!table.get_symbol(index, result.name, value, size, binding, type, sectionIndex, other)) + return false; + // GNU IFUNC uses the first OS-specific symbol type; ELFIO does not name this extension. + constexpr unsigned char SttGnuIfunc = ELFIO::STT_LOOS; + bool isFunction = type == ELFIO::STT_FUNC || type == SttGnuIfunc; + if ((!isFunction && type != ELFIO::STT_OBJECT) || sectionIndex == ELFIO::SHN_UNDEF + || sectionIndex >= ELFIO::SHN_LORESERVE || value == 0) continue; - if (symbol.st_name == 0 || symbol.st_name >= stringData.size()) + + // ELFIO can report success without a valid name. st_name is the first Elf_Word in both ELF classes. + ELFIO::Elf_Word nameOffset; + memcpy(&nameOffset, data + index * entrySize, sizeof(nameOffset)); + nameOffset = file.get_convertor()(nameOffset); + if (nameOffset == 0) continue; + if (!names.get_string(nameOffset)) + return false; - // The string table is terminated, but the file may not be - size_t length = strnlen(stringData.data() + symbol.st_name, stringData.size() - symbol.st_name); - ElfSymbol result; - result.name.assign(stringData.data() + symbol.st_name, length); - // The linker writes the version into the name of some symbols of .symtab, `stdin@@GLIBC_2.2.5` + // The linker writes the version into some .symtab names, e.g. stdin@@GLIBC_2.2.5. auto version = result.name.find('@'); if (version != std::string::npos && version > 0) result.name.resize(version); - result.address = symbol.st_value; - result.size = symbol.st_size; + result.address = value; + result.size = size; result.isFunction = isFunction; symbols.push_back(std::move(result)); } + return true; } - template - static bool ParseElf(std::ifstream& file, uint64_t fileSize, ElfInfo& info) + bool ReadElfFile(const std::string& path, ElfInfo& info) { - typename T::Ehdr header; - if (!ReadAt(file, 0, &header, sizeof(header))) + std::ifstream stream(path, std::ios::binary); + ELFIO::elfio file; + // Keep the stream alive while reading lazy section/segment data; avoid loading entire PT_LOAD segments. + if (!file.load(stream, true) || !stream || file.get_encoding() != ELFIO::ELFDATA2LSB) return false; - info.type = header.e_type; - info.entry = header.e_entry; + ElfInfo result; + result.type = file.get_type(); + result.is64 = file.get_class() == ELFIO::ELFCLASS64; + result.entry = file.get_entry(); bool haveLoad = false; uint64_t lowest = 0; - for (unsigned i = 0; i < header.e_phnum && header.e_phentsize >= sizeof(typename T::Phdr); i++) + for (const auto& segment : file.segments) { - typename T::Phdr segment; - if (!ReadAt(file, header.e_phoff + (uint64_t)i * header.e_phentsize, &segment, sizeof(segment))) - break; - - if (segment.p_type == PT_LOAD && (!haveLoad || segment.p_vaddr < lowest)) + if (segment->get_type() == ELFIO::PT_LOAD && (!haveLoad || segment->get_virtual_address() < lowest)) { - lowest = segment.p_vaddr; + lowest = segment->get_virtual_address(); haveLoad = true; } - else if (segment.p_type == PT_INTERP && segment.p_filesz > 0 && segment.p_filesz < 4096) + else if (segment->get_type() == ELFIO::PT_INTERP && segment->get_file_size() > 0 + && segment->get_file_size() < 4096) { - std::string path(segment.p_filesz, '\0'); - if (ReadAt(file, segment.p_offset, path.data(), path.size())) - info.interpreter = path.c_str(); + const char* interpreter = segment->get_data(); + if (!interpreter) + return false; + const char* end = static_cast(memchr(interpreter, 0, segment->get_file_size())); + if (!end) + return false; + result.interpreter.assign(interpreter, end); } } - info.linkBase = lowest & ~0xfffull; - - if (header.e_shoff == 0 || header.e_shnum == 0 || header.e_shentsize < sizeof(typename T::Shdr)) - return true; - - std::vector sections; - for (unsigned i = 0; i < header.e_shnum; i++) - { - typename T::Shdr section; - if (!ReadAt(file, header.e_shoff + (uint64_t)i * header.e_shentsize, §ion, sizeof(section))) - break; - sections.push_back(section); - } + result.linkBase = lowest & ~0xfffull; - for (const auto& section : sections) + for (const auto& section : file.sections) { - if ((section.sh_type == SHT_SYMTAB || section.sh_type == SHT_DYNSYM) && section.sh_link < sections.size()) - ReadSymbols(file, fileSize, section, sections[section.sh_link], info.symbols); + if ((section->get_type() == ELFIO::SHT_SYMTAB || section->get_type() == ELFIO::SHT_DYNSYM) + && !ReadSymbols(file, section.get(), result.symbols)) + return false; } - std::stable_sort(info.symbols.begin(), info.symbols.end(), [](const ElfSymbol& a, const ElfSymbol& b) { + std::stable_sort(result.symbols.begin(), result.symbols.end(), [](const ElfSymbol& a, const ElfSymbol& b) { return a.address < b.address; }); - // The dynamic symbols repeat in the full table - info.symbols.erase( - std::unique(info.symbols.begin(), info.symbols.end(), + // The dynamic symbols repeat in the full table. + result.symbols.erase( + std::unique(result.symbols.begin(), result.symbols.end(), [](const ElfSymbol& a, const ElfSymbol& b) { return a.address == b.address && a.name == b.name; }), - info.symbols.end()); + result.symbols.end()); + info = std::move(result); return true; } - - bool ReadElfFile(const std::string& path, ElfInfo& info) - { - std::ifstream file(path, std::ios::binary); - unsigned char ident[EI_NIDENT] = {}; - if (!file || !file.read(reinterpret_cast(ident), sizeof(ident))) - return false; - if (memcmp(ident, ELFMAG, SELFMAG) != 0 || ident[EI_DATA] != ELFDATA2LSB) - return false; - - file.seekg(0, std::ios::end); - uint64_t fileSize = file.tellg(); - - info = ElfInfo(); - if (ident[EI_CLASS] == ELFCLASS64) - { - info.is64 = true; - return ParseElf(file, fileSize, info); - } - if (ident[EI_CLASS] == ELFCLASS32) - return ParseElf(file, fileSize, info); - return false; - } - - const ElfSymbol* FindElfSymbol(const ElfInfo& info, uint64_t address) { // The last symbols that start at or before the address are the candidates diff --git a/core/adapters/ptrace/ptraceelf.h b/core/adapters/ptrace/ptraceelf.h index e2cec6a5..642e159a 100644 --- a/core/adapters/ptrace/ptraceelf.h +++ b/core/adapters/ptrace/ptraceelf.h @@ -42,7 +42,8 @@ namespace BinaryNinjaDebugger { std::vector symbols; }; - // Reads the headers and the symbol tables (.symtab and .dynsym) of a little-endian ELF file + // Reads little-endian ELF headers and symbol tables (.symtab and .dynsym) through ELFIO. + // Returns false if the required metadata cannot be read; info is only replaced on success. bool ReadElfFile(const std::string& path, ElfInfo& info); // The symbol that contains an address of the file, or nullptr diff --git a/scripts/build.py b/scripts/build.py index 453fd98e..157fdc0f 100755 --- a/scripts/build.py +++ b/scripts/build.py @@ -264,6 +264,8 @@ def extract_zip(bundle, target): cmake_params.append(('BN_API_PATH', api_path)) cmake_params.append(('BN_INSTALL_DIR', bn_core_path)) cmake_params.append(('CMAKE_PREFIX_PATH', qt_cmake_path)) +if platform.system() == 'Linux': + cmake_params.append(('BUILD_PTRACE_TESTS', 'ON')) if sys.platform == 'darwin': if sysroot is not None: @@ -349,6 +351,9 @@ def extract_zip(bundle, target): str(base_dir / "test" / "debugger_test.py"), str(base_dir / "test" / "attach_timeout_test.py"), ] +if platform.system() == 'Linux': + env['PTRACE_TEST_BUILD_DIR'] = str(build_path / 'test' / 'ptrace_engine') + pytest_sources.append(str(base_dir / 'test' / 'ptrace_engine_test.py')) if platform.system() == "Windows": # Exercise the just-built Windows Remote server locally on the Windows worker. # An explicit path prevents accidentally testing an installed/stale server. diff --git a/test/debugger_test.py b/test/debugger_test.py index edf3f86c..f3520a4c 100644 --- a/test/debugger_test.py +++ b/test/debugger_test.py @@ -13,6 +13,7 @@ import unittest from binaryninja import load, Settings +from binaryninja.enums import SettingsScope try: from debugger import DebuggerController, DebugStopReason, DebugBreakpointType except: @@ -56,6 +57,19 @@ def is_wow64(fpath): return a == '64bit' and b.startswith('Windows') +def can_attach_to_unrelated_process(): + """Attaching to a process that is not a descendant needs root, or a Yama scope of 0 (or no Yama)""" + if os.name != 'posix': + return False + if os.geteuid() == 0: + return True + try: + with open('/proc/sys/kernel/yama/ptrace_scope') as f: + return f.read().strip() == '0' + except OSError: + return True + + def sleep_and_go(dbg): return dbg.go_and_wait() @@ -463,9 +477,10 @@ def test_breakpoints_list_and_repr(self): dbg.quit_and_wait() - @unittest.skipIf(platform.system() == 'Linux', 'Hardware breakpoints not yet supported on Linux') def test_hardware_breakpoint(self): """Test hardware breakpoint add and delete""" + if platform.system() == 'Linux' and self.adapter_type != 'PTRACE': + self.skipTest('Hardware breakpoints not yet supported on Linux') fpath = name_to_fpath('helloworld', self.arch) bv = load(fpath) dbg = self.create_debugger(bv) @@ -628,8 +643,9 @@ def test_assembly_code(self): reason = sleep_and_go(dbg) self.assertEqual(reason, DebugStopReason.ProcessExited) - @unittest.skipIf(platform.system() == 'Linux', 'Cannot attach to pid unless running as root') def test_attach(self): + if platform.system() == 'Linux' and not (self.adapter_type == 'PTRACE' and can_attach_to_unrelated_process()): + self.skipTest('Cannot attach to pid unless running as root') from attach_test_runner import run_attach_test fpath = name_to_fpath('helloworld_loop', self.arch) worker = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'attach_test_runner.py') @@ -717,6 +733,179 @@ def test_local_launch_stops_at_stripped_pie_entry_point(self): dbg.quit_and_wait() +class PtraceAdapterTests: + """The tests for what only the PTRACE adapter does. They come on top of the ones of DebuggerAPI.""" + + def create_debugger(self, bv): + dbg = super().create_debugger(bv) + + # Debugger settings are registered lazily when the first controller is constructed + if not hasattr(self, '_entry_settings_configured'): + settings = Settings() + previous_system_entry = settings.get_bool('debugger.stopAtSystemEntryPoint') + previous_program_entry = settings.get_bool('debugger.stopAtEntryPoint') + self.assertTrue(settings.set_bool('debugger.stopAtSystemEntryPoint', False)) + self.assertTrue(settings.set_bool('debugger.stopAtEntryPoint', True)) + self.addCleanup(settings.set_bool, 'debugger.stopAtEntryPoint', previous_program_entry) + self.addCleanup(settings.set_bool, 'debugger.stopAtSystemEntryPoint', previous_system_entry) + self._entry_settings_configured = True + + return dbg + + def set_redirects(self, dbg, bv, redirects): + settings = dbg.adapter_settings + self.assertIsNotNone(settings) + self.assertTrue(settings.contains('launch.redirectFileDescriptors')) + self.assertTrue(settings.set_string_list('launch.redirectFileDescriptors', redirects, bv, + SettingsScope.SettingsResourceScope)) + + def test_redirect_stdout(self): + fpath = name_to_fpath('helloworld', self.arch) + expected = subprocess.run([fpath], capture_output=True, timeout=30).stdout + self.assertTrue(expected) + + bv = load(fpath) + dbg = self.create_debugger(bv) + dbg.executable_path = fpath + with tempfile.TemporaryDirectory() as temp_dir: + out_path = os.path.join(temp_dir, 'out.txt') + self.set_redirects(dbg, bv, ['1>' + out_path]) + self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + self.assertEqual(sleep_and_go(dbg), DebugStopReason.ProcessExited) + with open(out_path, 'rb') as f: + self.assertEqual(f.read(), expected) + + def test_redirect_stdin(self): + fpath = name_to_fpath('cat', self.arch) + bv = load(fpath) + dbg = self.create_debugger(bv) + dbg.executable_path = fpath + with tempfile.TemporaryDirectory() as temp_dir: + in_path = os.path.join(temp_dir, 'in.txt') + out_path = os.path.join(temp_dir, 'out.txt') + with open(in_path, 'w') as f: + f.write('read from a file\n') + self.set_redirects(dbg, bv, ['0<' + in_path, '1>' + out_path]) + self.assertNotIn(dbg.launch_and_wait(), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + self.assertEqual(sleep_and_go(dbg), DebugStopReason.ProcessExited) + with open(out_path) as f: + self.assertEqual(f.read(), 'read from a file\n') + + def test_redirect_bad_file(self): + fpath = name_to_fpath('helloworld', self.arch) + bv = load(fpath) + dbg = self.create_debugger(bv) + dbg.executable_path = fpath + self.set_redirects(dbg, bv, ['0 None: + self.arch = 'x86_64' + self.adapter_type = 'PTRACE' + + +@unittest.skipUnless(platform.system() == 'Linux', 'The PTRACE adapter only works on Linux') +@unittest.skipIf(platform.machine() in ['arm64', 'aarch64'], 'The PTRACE adapter only supports x86 and x86_64') +class PtraceLinuxx86Test(PtraceAdapterTests, DebuggerAPI): + def setUp(self) -> None: + self.arch = 'x86' + self.adapter_type = 'PTRACE' + + @unittest.skipIf(platform.machine() not in ['arm64', 'aarch64'], "Only run arm64 tests on arm Mac or Linux") class DebuggerArm64Test(DebuggerAPI): def setUp(self) -> None: diff --git a/test/ptrace_engine/CMakeLists.txt b/test/ptrace_engine/CMakeLists.txt new file mode 100644 index 00000000..50d463cf --- /dev/null +++ b/test/ptrace_engine/CMakeLists.txt @@ -0,0 +1,103 @@ +cmake_minimum_required(VERSION 3.15) + +# Also usable on its own: no Binary Ninja runtime, license, Qt or LLDB required. +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + project(ptrace-engine-tests LANGUAGES C CXX) +endif() +if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "The ptrace engine tests require Linux") +endif() + +find_package(Threads REQUIRED) +get_filename_component(DEBUGGER_TEST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE) +set(PTRACE_ENGINE_SRC "${DEBUGGER_TEST_ROOT}/core/adapters/ptrace") +if(NOT TARGET elfio::elfio) + add_subdirectory("${DEBUGGER_TEST_ROOT}/vendor/elfio" "${CMAKE_CURRENT_BINARY_DIR}/elfio" EXCLUDE_FROM_ALL) +endif() +if(NOT BN_API_PATH) + if(BN_INTERNAL_BUILD) + set(BN_API_PATH "${CMAKE_SOURCE_DIR}/api") + else() + set(BN_API_PATH "$ENV{BN_API_PATH}" CACHE PATH "Binary Ninja API headers") + endif() +endif() +if(NOT EXISTS "${BN_API_PATH}/binaryninjacore.h") + message(FATAL_ERROR "Set BN_API_PATH to the Binary Ninja API headers") +endif() +if(NOT TARGET fmt::fmt) + add_subdirectory("${BN_API_PATH}/vendor/fmt" "${CMAKE_CURRENT_BINARY_DIR}/fmt" EXCLUDE_FROM_ALL) +endif() + +if(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64|arm64|ARM64") + set(PTRACE_TEST_ARCH arm64) +elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64|amd64") + set(PTRACE_TEST_ARCH x86_64) +else() + message(FATAL_ERROR "Unsupported ptrace test host: ${CMAKE_SYSTEM_PROCESSOR}") +endif() +set(PTRACE_TEST_CORPUS_DIR "${DEBUGGER_TEST_ROOT}/test/binaries/Linux-${PTRACE_TEST_ARCH}" + CACHE PATH "Existing debugger test binaries for this host architecture") +set(PTRACE_TEST_SANITIZER "" CACHE STRING "Optional ptrace test instrumentation: address or thread") +set_property(CACHE PTRACE_TEST_SANITIZER PROPERTY STRINGS "" address thread) +if(NOT PTRACE_TEST_SANITIZER MATCHES "^(|address|thread)$") + message(FATAL_ERROR "PTRACE_TEST_SANITIZER must be empty, address or thread") +endif() + +add_library(ptrace_test_options INTERFACE) +target_compile_features(ptrace_test_options INTERFACE cxx_std_20) +target_include_directories(ptrace_test_options INTERFACE "${PTRACE_ENGINE_SRC}" "${BN_API_PATH}") +target_compile_definitions(ptrace_test_options INTERFACE + PTRACE_TEST_DIRECTORY="${CMAKE_CURRENT_BINARY_DIR}" + PTRACE_TEST_CORPUS_DIRECTORY="${PTRACE_TEST_CORPUS_DIR}") + +add_library(ptrace_test_instrumentation INTERFACE) +if(PTRACE_TEST_SANITIZER) + if(PTRACE_TEST_SANITIZER STREQUAL "address") + set(PTRACE_SANITIZERS address,undefined) + else() + set(PTRACE_SANITIZERS thread) + endif() + target_compile_options(ptrace_test_instrumentation INTERFACE + -O1 -g -fno-omit-frame-pointer "-fsanitize=${PTRACE_SANITIZERS}") + target_link_options(ptrace_test_instrumentation INTERFACE "-fsanitize=${PTRACE_SANITIZERS}") +endif() + +# Instrument the debugger, not its inferiors: sanitizer startup would change the +# instruction sequences and process lifecycle that these fixtures exercise. +add_library(ptrace_test_arch STATIC "${PTRACE_ENGINE_SRC}/ptracearch.cpp") +target_link_libraries(ptrace_test_arch PUBLIC ptrace_test_options ptrace_test_instrumentation) +add_library(ptrace_test_engine STATIC + "${PTRACE_ENGINE_SRC}/ptraceengine.cpp" + "${PTRACE_ENGINE_SRC}/ptracestep.cpp" + "${PTRACE_ENGINE_SRC}/ptraceelf.cpp" + "${PTRACE_ENGINE_SRC}/ptracemodule.cpp" + "${PTRACE_ENGINE_SRC}/ptracesignal.cpp" + "${PTRACE_ENGINE_SRC}/ptracesyscall.cpp") +target_link_libraries(ptrace_test_engine PUBLIC ptrace_test_arch Threads::Threads PRIVATE elfio::elfio fmt::fmt) + +foreach(program progs progs_pad) + add_executable(ptrace_${program} progs.c) + target_compile_options(ptrace_${program} PRIVATE -O0 -fno-omit-frame-pointer -fno-pie) + target_link_options(ptrace_${program} PRIVATE -no-pie) + target_link_libraries(ptrace_${program} PRIVATE ptrace_test_options Threads::Threads ${CMAKE_DL_LIBS}) + set_target_properties(ptrace_${program} PROPERTIES OUTPUT_NAME ${program} + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") +endforeach() +target_compile_definitions(ptrace_progs_pad PRIVATE PAD) +add_library(ptrace_libtest SHARED libtest.c) +set_target_properties(ptrace_libtest PROPERTIES OUTPUT_NAME test + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") + +set(PTRACE_TEST_PROGRAMS driver elfcmp) +foreach(program IN LISTS PTRACE_TEST_PROGRAMS) + add_executable(ptrace_${program} ${program}.cpp) + set_target_properties(ptrace_${program} PROPERTIES OUTPUT_NAME ${program} + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") + target_link_libraries(ptrace_${program} PRIVATE ptrace_test_engine) + add_dependencies(ptrace_${program} ptrace_progs ptrace_progs_pad ptrace_libtest) +endforeach() + +add_custom_target(ptrace_tests DEPENDS + ptrace_driver ptrace_elfcmp) +file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/ptrace_test_config.json" CONTENT + "{\"corpus\":\"${PTRACE_TEST_CORPUS_DIR}\",\"sanitizer\":\"${PTRACE_TEST_SANITIZER}\"}\n") diff --git a/test/ptrace_engine/Dockerfile b/test/ptrace_engine/Dockerfile new file mode 100644 index 00000000..555c7f62 --- /dev/null +++ b/test/ptrace_engine/Dockerfile @@ -0,0 +1,3 @@ +FROM ubuntu:24.04 +RUN apt-get update -qq && apt-get install -y --no-install-recommends \ + g++ clang cmake ninja-build python3-pytest binutils && rm -rf /var/lib/apt/lists/* diff --git a/test/ptrace_engine/driver.cpp b/test/ptrace_engine/driver.cpp new file mode 100644 index 00000000..32a20a4f --- /dev/null +++ b/test/ptrace_engine/driver.cpp @@ -0,0 +1,2235 @@ +#include +#include "ptracesignal.h" +#include "ptraceengine.h" +#include "ptracearch.h" +#include "ptraceelf.h" +#include "ptracemodule.h" +#include "ptracestep.h" +#include "ptracesyscall.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace BinaryNinjaDebugger; +using namespace std::chrono_literals; + +struct Log +{ + std::mutex m; std::condition_variable cv; std::deque q; std::string output; + void push(const PtraceEngine::Event& e) { std::lock_guard l(m); if (e.type == PtraceEngine::OutputEvent) output += e.data; q.push_back(e); cv.notify_all(); } + bool wait(PtraceEngine::EventType t, PtraceEngine::Event& out, std::chrono::milliseconds to = 5000ms) + { + std::unique_lock l(m); + auto deadline = std::chrono::steady_clock::now() + to; + while (true) + { + for (auto it = q.begin(); it != q.end(); ++it) if (it->type == t) { out = *it; q.erase(it); return true; } + if (cv.wait_until(l, deadline) == std::cv_status::timeout) return false; + } + } +}; + +static int failures = 0; +#define CHECK(c) do { if (!(c)) { printf(" FAIL line %d: %s\n", __LINE__, #c); failures++; } } while (0) + +static std::string scratchDirectory() { return std::filesystem::canonical(std::filesystem::temp_directory_path()).string(); } +static std::string prog = PTRACE_TEST_DIRECTORY "/progs"; + +#if defined(__x86_64__) +// The layout of user_regs_struct, which is what NT_PRSTATUS holds +constexpr size_t kFpOff = 4 * 8, kArg0Off = 14 * 8, kPcOff = 16 * 8, kSpOff = 19 * 8, kPrstatusSize = 27 * 8, kRetOff = 10 * 8; +// x86 has PTRACE_SYSEMU, so it not working there is a failure +constexpr bool kSysemuMayBeMissing = false; +constexpr size_t kCallLength = 5; +// A ret in a deeper call has a lower sp than the one of this frame, so no adjustment is needed +constexpr size_t kMinSpExtra = 0; +constexpr bool kDataTrapsBeforeAccess = false; +constexpr bool kHostSupported = true; +static const char* kScratchRegister = "rbx"; +static const char* kLoaderName = "ld-linux-x86-64.so.2"; +static const std::vector kBreakInsn = {0xCC}; +// Detected from the target, like the adapter does +static const PtraceArch* TestArch() { return nullptr; } +static const PtraceArch& RegisterTable() { return PtraceArchX86_64(); } +// Where a thread that stepped off the first instruction of a function is. That instruction is 4 bytes long on arm64, and +// on x86 it is a `push %rbp` or an `endbr64`. +static bool SteppedOffFirstInstruction(uint64_t pc, uint64_t start) { return pc > start && pc <= start + 15; } +#elif defined(__aarch64__) +constexpr size_t kFpOff = 29 * 8, kArg0Off = 0, kPcOff = 32 * 8, kSpOff = 31 * 8, kPrstatusSize = 272, kRetOff = 0; +constexpr bool kSysemuMayBeMissing = true; +constexpr size_t kCallLength = 4; +constexpr size_t kMinSpExtra = 1; +constexpr bool kDataTrapsBeforeAccess = true; +constexpr bool kHostSupported = false; +static const char* kScratchRegister = "x28"; +static const char* kLoaderName = "ld-linux-aarch64.so.1"; +static const std::vector kBreakInsn = {0x00, 0x00, 0x20, 0xd4}; +#ifndef NT_ARM_HW_BREAK +#define NT_ARM_HW_BREAK 0x402 +#define NT_ARM_HW_WATCH 0x403 +#endif +// What a test wants TriggeredSlots to answer, when it is not the address of the access: -1 is no override, 0 is no slot +static std::atomic g_hwTrigger {-1}; +struct ArmHw : PtraceHwDebug +{ + struct State { uint32_t info; uint32_t pad; struct { uint64_t addr; uint32_t ctrl; uint32_t pad; } regs[16]; }; + size_t SlotCount() const override { return 8; } + bool SlotSupports(size_t slot, PtraceHwType type) const override { return (slot < 4) == (type == PtraceHwType::Execute); } + bool Program(pid_t tid, size_t slot, uint64_t addr, uint32_t ctrl) + { + int note = slot < 4 ? NT_ARM_HW_BREAK : NT_ARM_HW_WATCH; size_t index = slot % 4; + State st; memset(&st, 0, sizeof st); iovec iov = {&st, sizeof st}; + if (ptrace(PTRACE_GETREGSET, tid, (void*)(uintptr_t)note, &iov) != 0) return false; + st.regs[index].addr = addr; st.regs[index].ctrl = ctrl; + iov.iov_len = offsetof(State, regs) + (index + 1) * sizeof(st.regs[0]); + return ptrace(PTRACE_SETREGSET, tid, (void*)(uintptr_t)note, &iov) == 0; + } + bool Set(pid_t tid, size_t slot, uint64_t address, PtraceHwType type, size_t size) override + { + if (type == PtraceHwType::Execute) return Program(tid, slot, address, (0xf << 5) | (2 << 1) | 1); + uint32_t lsc = type == PtraceHwType::Write ? 2 : (type == PtraceHwType::Read ? 1 : 3); + return Program(tid, slot, address, (((1u << size) - 1) << 5) | (lsc << 3) | (2 << 1) | 1); + } + bool Clear(pid_t tid, size_t slot) override { return Program(tid, slot, 0, 0); } + bool DataTrapsBeforeAccess() const override { return true; } + // The slots whose address is the one that the trap is for. arm64 says that in si_addr, and has no register like DR6. + uint64_t TriggeredSlots(pid_t tid, bool& known) override + { + known = true; + if (g_hwTrigger >= 0) return (uint64_t)g_hwTrigger; + siginfo_t si {}; + if (ptrace(PTRACE_GETSIGINFO, tid, nullptr, &si) != 0) { known = false; return 0; } + uint64_t mask = 0; + for (int note : {NT_ARM_HW_BREAK, NT_ARM_HW_WATCH}) + { + State st; memset(&st, 0, sizeof st); iovec iov = {&st, sizeof st}; + if (ptrace(PTRACE_GETREGSET, tid, (void*)(uintptr_t)note, &iov) != 0) { known = false; return 0; } + for (size_t index = 0; index < 4; index++) + { + uint64_t at = (uint64_t)si.si_addr, address = st.regs[index].addr; + if ((st.regs[index].ctrl & 1) && at >= address && at < address + 8) mask |= 1ull << ((note == NT_ARM_HW_BREAK ? 0 : 4) + index); + } + } + return mask; + } +}; +static ArmHw g_armHw; + +static PtraceArch TestArm64() +{ + PtraceArch a; a.name = "aarch64"; a.pc = "pc"; a.sp = "sp"; a.regsets = {NT_PRSTATUS}; + a.breakpointInstruction = {0x00, 0x00, 0x20, 0xd4}; a.breakpointPcAdjust = 0; a.hwDebug = &g_armHw; a.sysemu = true; + for (size_t i = 0; i < 31; i++) a.registers.push_back({"x" + std::to_string(i), NT_PRSTATUS, i * 8, 8}); + a.registers.push_back({"sp", NT_PRSTATUS, 31 * 8, 8}); a.registers.push_back({"pc", NT_PRSTATUS, 32 * 8, 8}); + return a; +} + +static PtraceArch g_arm = TestArm64(); +static const PtraceArch* TestArch() { return &g_arm; } +static const PtraceArch& RegisterTable() { return g_arm; } +static bool SteppedOffFirstInstruction(uint64_t pc, uint64_t start) { return pc == start + 4; } +#else +#error "the harness knows x86_64 and aarch64" +#endif + +static std::unique_ptr start(Log& log, const std::string& mode, std::vector extra = {}, const std::string& cwd = "", bool pty = true) +{ + auto e = std::make_unique([&log](const PtraceEngine::Event& ev) { log.push(ev); }); + PtraceEngine::LaunchOptions o; o.path = prog; o.args = {mode}; o.args.insert(o.args.end(), extra.begin(), extra.end()); o.workingDir = cwd; o.usePty = pty; o.arch = TestArch(); + std::string err; + if (!e->Launch(o, err)) { printf(" launch failed: %s\n", err.c_str()); failures++; return nullptr; } + return e; +} + +static std::string procState(uint32_t pid) +{ + std::ifstream f("/proc/" + std::to_string(pid) + "/status"); std::string l; + while (std::getline(f, l)) if (l.rfind("State:", 0) == 0) return l; + return "gone"; +} + +static void t_hello() +{ + Log log; auto e = start(log, "hello"); if (!e) return; + PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGTRAP); CHECK(e->GetThreads().size() == 1); + CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); CHECK(ev.signal == 0); + CHECK(log.output.find("hello from target") != std::string::npos); + CHECK(!e->Resume(false, 0)); +} + +static void t_step() +{ + Log log; auto e = start(log, "hello"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint32_t tid = ev.tid; + for (int i = 0; i < 2000; i++) + { + if (!e->Resume(true, tid)) { printf(" step %d failed\n", i); failures++; return; } + if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" step %d no stop\n", i); failures++; return; } + if (!(ev.singleStep && ev.signal == SIGTRAP && ev.tid == tid)) { printf(" step %d bad event sig=%d step=%d\n", i, ev.signal, ev.singleStep); failures++; return; } + } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); +} + +static void t_interrupt() +{ + Log log; auto e = start(log, "loop"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(!e->Interrupt()); + for (int i = 0; i < 100; i++) + { + CHECK(e->Resume(false, 0)); if (failures) return; + std::this_thread::sleep_for(std::chrono::microseconds(i * 300)); + if (!e->Interrupt()) { printf(" interrupt %d refused\n", i); failures++; return; } + if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" interrupt %d no stop\n", i); failures++; return; } + if (!ev.interrupted) { printf(" interrupt %d not flagged (sig %d)\n", i, ev.signal); failures++; return; } + } + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGKILL); +} + +static void t_threads() +{ + Log log; auto e = start(log, "threads"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->Resume(false, 0)); + std::this_thread::sleep_for(300ms); + CHECK(e->GetThreads().size() == 5 - 0 - 0 + 0 - 0 || e->GetThreads().size() == 4); + for (int i = 0; i < 20; i++) + { + CHECK(e->Interrupt()); if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no stop %d\n", i); failures++; return; } + auto threads = e->GetThreads(); + if (i == 0) printf(" threads=%zu\n", threads.size()); + CHECK(threads.size() == 4); + // step one thread that isn't the reporter + uint32_t other = threads.back() == ev.tid ? threads.front() : threads.back(); + CHECK(e->Resume(true, other)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.tid == other); CHECK(ev.singleStep); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(5ms); + } + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); +} + +static void t_churn() +{ + Log log; auto e = start(log, "churn"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->Resume(false, 0)); + // interrupt repeatedly while threads come and go + int stops = 0; + while (true) + { + if (log.wait(PtraceEngine::ExitedEvent, ev, 20ms)) break; + if (e->Interrupt()) { if (log.wait(PtraceEngine::StoppedEvent, ev, 2000ms)) { stops++; CHECK(e->Resume(false, 0)); } } + } + CHECK(ev.exitCode == 0); printf(" churn interrupted %d times\n", stops); + CHECK(log.output.find("churn done") != std::string::npos); +} + +static void t_signal() +{ + Log log; auto e = start(log, "sig"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); + CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGUSR1); + CHECK(log.output.find("survived") == std::string::npos); + + Log log2; auto e2 = start(log2, "abort"); if (!e2) return; + CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e2->Resume(false, 0)); + CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGABRT); + CHECK(e2->Resume(false, 0)); CHECK(log2.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGABRT); +} + +static void t_silent() +{ + Log log; auto e = start(log, "sigchld"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 8000ms)); CHECK(ev.exitCode == 5); + CHECK(log.output.find("after child") != std::string::npos); +} + +static void t_detach() +{ + Log log; auto e = start(log, "sleeper"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint32_t pid = e->GetPid(); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(200ms); + CHECK(e->Detach()); + CHECK(log.wait(PtraceEngine::DetachedEvent, ev)); + std::this_thread::sleep_for(300ms); + std::string st = procState(pid); printf(" after detach: %s\n", st.c_str()); + CHECK(st.find("(sleeping)") != std::string::npos || st.find("(running)") != std::string::npos); + // it must finish on its own, and be reaped + int status = 0; CHECK(e->WaitForDetachedExit(status, 4s)); std::this_thread::sleep_for(50ms); CHECK(procState(pid) == "gone"); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 3); +} + +static void t_kill_running() +{ + Log log; auto e = start(log, "threads"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + std::this_thread::sleep_for(100ms); + uint32_t pid = e->GetPid(); + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGKILL); + CHECK(procState(pid) == "gone"); + CHECK(!e->Kill()); + e.reset(); +} + +static void t_dtor_kills() +{ + Log log; uint32_t pid; + { + auto e = start(log, "loop"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + pid = e->GetPid(); + } + CHECK(procState(pid) == "gone"); +} + +static void t_launch_errors() +{ + Log log; + auto e = std::make_unique([&log](const PtraceEngine::Event& ev) { log.push(ev); }); + PtraceEngine::LaunchOptions o; o.path = "/nonexistent/bin"; std::string err; + CHECK(!e->Launch(o, err)); printf(" err: %s\n", err.c_str()); CHECK(!err.empty()); + CHECK(!e->Resume(false, 0)); CHECK(!e->Kill()); CHECK(!e->Detach()); CHECK(!e->Interrupt()); + e.reset(); + Log log2; auto e2 = std::make_unique([&log2](const PtraceEngine::Event& ev) { log2.push(ev); }); + o.path = prog; o.workingDir = "/nonexistent"; CHECK(!e2->Launch(o, err)); printf(" err: %s\n", err.c_str()); +} + +static void t_args_cwd() +{ + Log log; auto e = start(log, "args", {"a b", "c"}, scratchDirectory()); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); + printf(" out: %s", log.output.c_str()); + CHECK(log.output.find("cwd=" + scratchDirectory() + " argc=4 [a b] [c]") != std::string::npos); +} + +static void t_stdin() +{ + Log log; auto e = start(log, "cat"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(e->WriteInput("ping\n")); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); + CHECK(log.output.find("got: ping") != std::string::npos); +} + +static void t_nopty() +{ + Log log; auto e = start(log, "hello", {}, "", false); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); CHECK(!e->WriteInput("x")); +} + +static void t_relaunch() +{ + for (int i = 0; i < 20; i++) + { + Log log; auto e = start(log, "hello"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); + } +} + +static uint64_t le64(const std::vector& v, size_t off) { uint64_t x = 0; memcpy(&x, v.data() + off, 8); return x; } + + +static bool waitOutput(Log& log, const std::string& s, int ms = 3000) +{ + for (int i = 0; i < ms / 10; i++) { { std::lock_guard l(log.m); if (log.output.find(s) != std::string::npos) return true; } std::this_thread::sleep_for(10ms); } + return false; +} + +static void t_regs_step() +{ + const PtraceArch& arch = RegisterTable(); auto pcReg = arch.Find(arch.pc); CHECK(pcReg && arch.Find("nope") == nullptr); + CHECK((DetectPtraceArch(getpid()) != nullptr) == kHostSupported); // the arm64 host is not a supported architecture + Log log; auto e = start(log, "hello"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); uint32_t tid = ev.tid; + CHECK((DetectPtraceArch(e->GetPid()) != nullptr) == kHostSupported); + std::vector regs; CHECK(e->GetRegisterSet(tid, pcReg->regset, regs)); CHECK(regs.size() == kPrstatusSize); + uint64_t pc1 = le64(regs, pcReg->offset), sp = le64(regs, arch.Find(arch.sp)->offset); + CHECK(pc1 != 0 && sp != 0); +#if defined(__aarch64__) + CHECK(pc1 % 4 == 0); +#endif + std::vector fp; CHECK(e->GetRegisterSet(tid, NT_PRFPREG, fp)); CHECK(fp.size() >= 512); + CHECK(e->Resume(true, tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + std::vector regs2; CHECK(e->GetRegisterSet(tid, NT_PRSTATUS, regs2)); + printf(" pc %llx -> %llx\n", (unsigned long long)pc1, (unsigned long long)le64(regs2, pcReg->offset)); +#if defined(__aarch64__) + CHECK(le64(regs2, pcReg->offset) == pc1 + 4); +#else + CHECK(le64(regs2, pcReg->offset) != pc1); +#endif + // write a register, read it back, restore it + const auto x28 = arch.Find(kScratchRegister)->offset; uint64_t orig = le64(regs2, x28); + auto mod = regs2; uint64_t magic = 0x1122334455667788ull; memcpy(mod.data() + x28, &magic, 8); + CHECK(e->SetRegisterSet(tid, NT_PRSTATUS, mod)); std::vector back; CHECK(e->GetRegisterSet(tid, NT_PRSTATUS, back)); CHECK(le64(back, x28) == magic); + memcpy(mod.data() + x28, &orig, 8); CHECK(e->SetRegisterSet(tid, NT_PRSTATUS, mod)); + // writing the pc redirects the step +#if defined(__aarch64__) + auto jump = regs2; uint64_t target = pc1 + 8; memcpy(jump.data() + pcReg->offset, &target, 8); + CHECK(e->SetRegisterSet(tid, NT_PRSTATUS, jump)); CHECK(e->Resume(true, tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->GetRegisterSet(tid, NT_PRSTATUS, back)); CHECK(le64(back, pcReg->offset) == target + 4); +#else + // going back to the first pc, the step has the same result again + uint64_t pc2 = le64(regs2, pcReg->offset); + CHECK(e->SetRegisterSet(tid, NT_PRSTATUS, regs)); CHECK(e->Resume(true, tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->GetRegisterSet(tid, NT_PRSTATUS, back)); CHECK(le64(back, pcReg->offset) == pc2); +#endif + // invalid requests + CHECK(!e->GetRegisterSet(tid + 1000, NT_PRSTATUS, back)); CHECK(!e->GetRegisterSet(tid, 0x7777, back)); + CHECK(e->Kill()); + CHECK(!e->GetRegisterSet(tid, NT_PRSTATUS, back)); +} + +static void t_regs_running() +{ + Log log; auto e = start(log, "loop"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); uint32_t tid = ev.tid; + CHECK(e->Resume(false, 0)); std::vector regs; + CHECK(!e->GetRegisterSet(tid, NT_PRSTATUS, regs)); CHECK(!e->SetRegisterSet(tid, NT_PRSTATUS, regs)); + CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->GetRegisterSet(ev.tid, NT_PRSTATUS, regs)); CHECK(regs.size() == kPrstatusSize); + CHECK(e->Kill()); +} + +static void t_memory() +{ + Log log; auto e = start(log, "mem"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); + CHECK(waitOutput(log, "main=")); + unsigned long long bufAddr = 0, mainAddr = 0; sscanf(log.output.c_str(), "buf=%llx main=%llx", &bufAddr, &mainAddr); + CHECK(bufAddr != 0 && mainAddr != 0); + char rd[13] = {}; CHECK(e->ReadMemory(bufAddr, rd, 12)); CHECK(!strcmp(rd, "hello memory")); + CHECK(e->WriteMemory(bufAddr, "HELLO", 5)); CHECK(e->ReadMemory(bufAddr, rd, 12)); CHECK(!strcmp(rd, "HELLO memory")); + // text pages are read-only, but a debugger must still be able to patch them + uint8_t code[4]; CHECK(e->ReadMemory(mainAddr, code, 4)); uint8_t patched[4] = {code[0], code[1], code[2], code[3]}; + CHECK(e->WriteMemory(mainAddr, patched, 4)); + // large and unaligned reads + std::vector big(3 * 4096 + 17); CHECK(e->ReadMemory(mainAddr & ~0xfffull, big.data(), 4096)); + uint8_t byte; CHECK(!e->ReadMemory(0, &byte, 1)); CHECK(!e->WriteMemory(0, &byte, 1)); CHECK(!e->ReadMemory(~0ull, &byte, 1)); CHECK(!e->ReadMemory(1ull << 52, &byte, 1)); { uint8_t two[2]; CHECK(!e->ReadMemory(0x1000000000000ull - 1, two, 2)); } + CHECK(e->ReadMemory(bufAddr, &byte, 0)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 0); + CHECK(log.output.find("HELLO memory") != std::string::npos); + CHECK(!e->ReadMemory(bufAddr, rd, 4)); +} + +static std::string readAddr(Log& log, const char* key) +{ + if (!waitOutput(log, key)) return ""; + return log.output.substr(log.output.find(key) + strlen(key)); +} + +static uint64_t addrOf(Log& log, const char* key) { auto s = readAddr(log, key); return strtoull(s.c_str(), nullptr, 16); } + +static std::vector rawRead(uint32_t pid, uint64_t addr, size_t n) +{ + std::vector v(n); int fd = open(("/proc/" + std::to_string(pid) + "/mem").c_str(), O_RDONLY); + if (fd < 0 || pread(fd, v.data(), n, addr) != (ssize_t)n) v.clear(); + if (fd >= 0) close(fd); + return v; +} + +static uint64_t pcOf(PtraceEngine& e, uint32_t tid) +{ + std::vector r; if (!e.GetRegisterSet(tid, NT_PRSTATUS, r)) return 0; return le64(r, kPcOff); +} + +// Starts the target, runs it to the SIGUSR1 stop that every breakpoint target raises once it has printed an address +static std::unique_ptr startAtSignal(Log& log, const std::string& mode, uint32_t& tid, PtraceEngine::Event& ev) +{ + auto e = start(log, mode); if (!e) return e; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); tid = ev.tid; + return e; +} + +static void t_bp_basic() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); CHECK(marker != 0); + uint32_t pid = e->GetPid(); + auto before = rawRead(pid, marker, 8); CHECK(before.size() == 8); + CHECK(e->AddBreakpoint(marker)); CHECK(e->AddBreakpoint(marker)); + auto raw = rawRead(pid, marker, kBreakInsn.size()); CHECK((raw == kBreakInsn)); + std::vector seen(8); CHECK(e->ReadMemory(marker, seen.data(), 8)); CHECK(seen == before); // the breakpoint is hidden + std::vector mid(2); CHECK(e->ReadMemory(marker + 1, mid.data(), 2)); CHECK(mid[0] == before[1] && mid[1] == before[2]); + for (int i = 1; i <= 5; i++) + { + CHECK(e->Resume(false, 0)); + if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no stop %d\n", i); failures++; return; } + if (!(ev.breakpoint && ev.signal == SIGTRAP && !ev.singleStep && pcOf(*e, ev.tid) == marker)) { printf(" hit %d wrong: bp=%d sig=%d pc=%llx\n", i, ev.breakpoint, ev.signal, (unsigned long long)pcOf(*e, ev.tid)); failures++; return; } + } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +static void t_bp_step_remove() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); uint32_t pid = e->GetPid(); + auto before = rawRead(pid, marker, 4); + CHECK(e->AddBreakpoint(marker)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.breakpoint); + // stepping off a breakpoint moves one instruction, and the breakpoint is still there afterwards + CHECK(e->Resume(true, ev.tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.singleStep && !ev.breakpoint); + CHECK(SteppedOffFirstInstruction(pcOf(*e, ev.tid), marker)); + CHECK((rawRead(pid, marker, kBreakInsn.size()) == kBreakInsn)); + CHECK(e->RemoveBreakpoint(marker)); CHECK(!e->RemoveBreakpoint(marker)); + CHECK(rawRead(pid, marker, 4) == before); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +static void t_bp_write() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); uint32_t pid = e->GetPid(); + auto before = rawRead(pid, marker, 8); + CHECK(e->AddBreakpoint(marker)); + std::vector patch = {1, 2, 3, 4, 5, 6, 7, 8}; + CHECK(e->WriteMemory(marker, patch.data(), 8)); + std::vector seen(8); CHECK(e->ReadMemory(marker, seen.data(), 8)); CHECK(seen == patch); + auto raw = rawRead(pid, marker, 8); auto wantRaw = patch; for (size_t i = 0; i < kBreakInsn.size(); i++) wantRaw[i] = kBreakInsn[i]; CHECK((raw == wantRaw)); + CHECK(e->RemoveBreakpoint(marker)); CHECK(rawRead(pid, marker, 8) == patch); + CHECK(e->WriteMemory(marker, before.data(), 8)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +static void t_bp_threads() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bpthreads", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); CHECK(e->AddBreakpoint(marker)); + int hits = 0; CHECK(e->Resume(false, 0)); + while (true) + { + { std::unique_lock l(log.m); bool got = log.cv.wait_for(l, 8s, [&] { for (auto& q : log.q) if (q.type == PtraceEngine::StoppedEvent || q.type == PtraceEngine::ExitedEvent) return true; return false; }); if (!got) { printf(" timeout after %d hits\n", hits); failures++; return; } } + if (log.wait(PtraceEngine::ExitedEvent, ev, 1ms)) break; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); if (!(ev.breakpoint && pcOf(*e, ev.tid) == marker)) { printf(" stray stop sig=%d\n", ev.signal); failures++; return; } + hits++; if (!e->Resume(false, 0)) { printf(" resume failed\n"); failures++; return; } + } + printf(" hits=%d exit=%d\n", hits, ev.exitCode); CHECK(hits == 12); CHECK(ev.exitCode == 12); +} + +// Interrupts race with breakpoint hits, so the number of reports can vary, but the target must never be damaged +static void t_bp_interrupts() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bpthreads", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); CHECK(e->AddBreakpoint(marker)); + std::atomic stop{false}; std::thread poker([&] { while (!stop) { e->Interrupt(); std::this_thread::sleep_for(700us); } }); + CHECK(e->Resume(false, 0)); + while (true) + { + std::unique_lock l(log.m); + if (!log.cv.wait_for(l, 8s, [&] { return !log.q.empty(); })) { printf(" timeout\n"); failures++; break; } + bool exited = false; PtraceEngine::Event last; bool stopped = false; + for (auto it = log.q.begin(); it != log.q.end();) { if (it->type == PtraceEngine::ExitedEvent) { exited = true; ev = *it; it = log.q.erase(it); } else if (it->type == PtraceEngine::StoppedEvent) { stopped = true; last = *it; it = log.q.erase(it); } else it = log.q.erase(it); } + l.unlock(); + if (exited) break; + if (stopped) + { + if (!(last.interrupted || (last.breakpoint && pcOf(*e, last.tid) == marker))) { printf(" stray stop sig=%d\n", last.signal); failures++; break; } + if (!e->Resume(false, 0)) { printf(" resume failed\n"); failures++; break; } + } + } + stop = true; poker.join(); + CHECK(ev.exitCode == 12); CHECK(ev.signal == 0); +} + +static void t_bp_remove_running() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bploop", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); auto before = rawRead(e->GetPid(), marker, 4); + CHECK(e->AddBreakpoint(marker)); + for (int i = 0; i < 60; i++) + { + CHECK(e->Resume(false, 0)); if (failures) return; + std::this_thread::sleep_for(std::chrono::microseconds(200 + (i * 37) % 900)); + CHECK(e->RemoveBreakpoint(marker)); + std::this_thread::sleep_for(std::chrono::microseconds(300 + (i * 91) % 700)); + CHECK(e->AddBreakpoint(marker)); + if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no stop at %d\n", i); failures++; return; } + if (!(ev.breakpoint && pcOf(*e, ev.tid) == marker)) { printf(" iteration %d stray stop sig=%d bp=%d pc=%llx\n", i, ev.signal, ev.breakpoint, (unsigned long long)pcOf(*e, ev.tid)); failures++; return; } + } + CHECK(e->RemoveBreakpoint(marker)); CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(50ms); + CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.interrupted); + CHECK(rawRead(e->GetPid(), marker, 4) == before); + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGKILL); +} + +static void t_bp_detach() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "detachbp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); uint32_t pid = e->GetPid(); + CHECK(e->AddBreakpoint(marker)); CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(200ms); + CHECK(e->Detach()); CHECK(log.wait(PtraceEngine::DetachedEvent, ev)); + int status = 0; CHECK(e->WaitForDetachedExit(status, 4s)); std::this_thread::sleep_for(50ms); CHECK(procState(pid) == "gone"); + printf(" status=%x\n", status); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 1); // it would have died of SIGTRAP if the breakpoint had stayed +} + +static void t_hw_watch() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "watch", tid, ev); if (!e) return; + uint64_t wvar = addrOf(log, "wvar="); CHECK(wvar != 0); + if (!e->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)) { printf(" SKIP: no hardware watchpoints\n"); e->Kill(); return; } + CHECK(e->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)); + for (int i = 1; i <= 3; i++) + { + CHECK(e->Resume(false, 0)); if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no hit %d\n", i); failures++; return; } + CHECK(ev.hardware && !ev.breakpoint); CHECK(ev.signal == SIGTRAP); + uint32_t value = 0; CHECK(e->ReadMemory(wvar, &value, 4)); CHECK(value == (uint32_t)(kDataTrapsBeforeAccess ? i - 1 : i)); // arm64 traps before the write is done, x86 after + } + CHECK(e->RemoveHardwareBreakpoint(wvar, PtraceHwType::Write, 4)); CHECK(!e->RemoveHardwareBreakpoint(wvar, PtraceHwType::Write, 4)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 3); + + Log log2; auto e2 = startAtSignal(log2, "watch", tid, ev); if (!e2) return; + wvar = addrOf(log2, "wvar="); CHECK(e2->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)); CHECK(e2->RemoveHardwareBreakpoint(wvar, PtraceHwType::Write, 4)); + CHECK(e2->Resume(false, 0)); CHECK(log2.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 3); // no stops + // the watchpoint slots run out, and a watchpoint cannot use an execute slot + Log log3; auto e3 = startAtSignal(log3, "watch", tid, ev); if (!e3) return; + wvar = addrOf(log3, "wvar="); + size_t watchpoints = 0; while (e3->AddHardwareBreakpoint(wvar + 4 * (watchpoints + 1), PtraceHwType::Write, 4)) watchpoints++; + CHECK(watchpoints >= 1 && watchpoints <= 4); // virtual machines can expose fewer than the four that arm64 allows + CHECK(e3->Resume(false, 0)); CHECK(!e3->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)); // not while running + CHECK(e3->Kill()); +} + +static void t_hw_thread() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "watchthread", tid, ev); if (!e) return; + uint64_t wvar = addrOf(log, "wvar="); + if (!e->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)) { printf(" SKIP: no hardware watchpoints\n"); e->Kill(); return; } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.hardware); + CHECK(ev.tid != e->GetPid()); // it was the new thread, so it inherited the watchpoint + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); +} + +static void t_hw_exec() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); + if (!e->AddHardwareBreakpoint(marker, PtraceHwType::Execute, 4)) { printf(" SKIP: no hardware breakpoints\n"); e->Kill(); return; } + for (int i = 1; i <= 5; i++) + { + CHECK(e->Resume(false, 0)); if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no hit %d\n", i); failures++; return; } + if (!(ev.hardware && pcOf(*e, ev.tid) == marker)) { printf(" hit %d wrong hw=%d pc=%llx\n", i, ev.hardware, (unsigned long long)pcOf(*e, ev.tid)); failures++; return; } + } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +static void t_hw_detach() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "watch", tid, ev); if (!e) return; + uint64_t wvar = addrOf(log, "wvar="); uint32_t pid = e->GetPid(); + if (!e->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)) { printf(" SKIP\n"); e->Kill(); return; } + CHECK(e->Detach()); CHECK(log.wait(PtraceEngine::DetachedEvent, ev)); + int status = 0; CHECK(e->WaitForDetachedExit(status, 4s)); std::this_thread::sleep_for(50ms); CHECK(procState(pid) == "gone"); + CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 3); // it would have been killed by SIGTRAP if the watchpoint had stayed +} + +static std::vector modulesOf(PtraceEngine& e) +{ + return BuildModules(e.GetMaps(), [&e](uint64_t a) { uint8_t m[4]; return e.ReadMemory(a, m, 4) && !memcmp(m, "\x7f" "ELF", 4); }); +} + +static const PtraceModuleInfo* findModule(const std::vector& mods, const std::string& base) +{ + for (auto& m : mods) if (m.path.size() >= base.size() && m.path.compare(m.path.size() - base.size(), base.size(), base) == 0) return &m; + return nullptr; +} + +static void t_modules() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "bp", tid, ev); if (!e) return; + auto mods = modulesOf(*e); auto maps = e->GetMaps(); + for (auto& m : mods) printf(" %-40s %llx +%llx (%s)\n", m.path.c_str(), (unsigned long long)m.base, (unsigned long long)m.size, m.shortName.c_str()); + auto exe = findModule(mods, "/progs"); auto libc = findModule(mods, "libc.so.6"); auto ld = findModule(mods, kLoaderName); + CHECK(exe && libc && ld); if (!exe || !libc || !ld) return; + CHECK(exe->shortName == "progs"); CHECK(exe->base == 0x400000); + // no module overlaps another, and every mapping of a module's file is inside it + for (auto& a : mods) for (auto& b : mods) if (&a != &b) CHECK(a.base + a.size <= b.base || b.base + b.size <= a.base); + for (auto& m : maps) if (m.path == libc->path) CHECK(m.start >= libc->base && m.end <= libc->base + libc->size); + for (auto& m : mods) CHECK(m.base % 0x1000 == 0 && m.size % 0x1000 == 0); + // everything reported is an ELF object, so the files that are only mapped for their data are left out + for (auto& m : mods) CHECK(m.path.find("locale") == std::string::npos); + // short names are unique + std::set names; for (auto& m : mods) CHECK(names.insert(m.shortName).second); + auto regions = e->GetMaps(); CHECK(!regions.empty()); + bool sawStack = false; for (auto& r : regions) { CHECK(r.end > r.start); if (r.path == "[stack]") { sawStack = true; CHECK(r.read && r.write && !r.execute); } } CHECK(sawStack); + e->Kill(); +} + +static void t_symbols() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "syms", tid, ev); if (!e) return; + waitOutput(log, "puts="); unsigned long long marker = 0, puts = 0; sscanf(log.output.c_str(), "marker=%llx puts=%llx", &marker, &puts); + auto mods = modulesOf(*e); auto exe = findModule(mods, "/progs"); auto libc = findModule(mods, "libc.so.6"); CHECK(exe && libc); if (!exe || !libc) return; + ElfInfo elf, libcElf; CHECK(ReadElfFile(exe->path, elf)); CHECK(ReadElfFile(libc->path, libcElf)); + CHECK(elf.is64 && elf.type == ET_EXEC && elf.linkBase == 0x400000 && elf.interpreter.find("ld-linux") != std::string::npos); + CHECK(libcElf.type == ET_DYN && libcElf.linkBase == 0); + printf(" progs: %zu symbols, libc: %zu symbols, interpreter %s\n", elf.symbols.size(), libcElf.symbols.size(), elf.interpreter.c_str()); + // symbols are found where the running program says they are + uint64_t found = 0; for (auto& s : elf.symbols) if (s.name == "marker") { found = s.address + exe->base - elf.linkBase; CHECK(s.isFunction && s.size > 0); } + CHECK(found == marker && marker != 0); + uint64_t foundPuts = 0; for (auto& s : libcElf.symbols) if (s.name == "puts") foundPuts = s.address + libc->base - libcElf.linkBase; + CHECK(foundPuts == puts && puts != 0); + // lookups by address + auto sym = FindElfSymbol(elf, marker - exe->base + elf.linkBase + 4); CHECK(sym && sym->name == "marker"); + CHECK(FindElfSymbol(elf, 0) == nullptr); + for (size_t i = 1; i < libcElf.symbols.size(); i++) CHECK(libcElf.symbols[i - 1].address <= libcElf.symbols[i].address); + ElfInfo bad; CHECK(!ReadElfFile("/etc/passwd", bad)); CHECK(!ReadElfFile("/nonexistent", bad)); + e->Kill(); +} + +static void t_frames() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "frames", tid, ev); if (!e) return; + uint64_t label = addrOf(log, "label="); CHECK(label != 0); + CHECK(e->AddBreakpoint(label)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.breakpoint); + std::vector regs; CHECK(e->GetRegisterSet(ev.tid, NT_PRSTATUS, regs)); + uint64_t pc = le64(regs, kPcOff), sp = le64(regs, kSpOff), fp = le64(regs, kFpOff); CHECK(pc == label); + auto maps = e->GetMaps(); + auto isExec = [&](uint64_t a) { for (auto& m : maps) if (m.execute && a >= m.start && a < m.end) return true; return false; }; + auto readWord = [&](uint64_t a, uint64_t& v) { v = 0; return e->ReadMemory(a, &v, 8); }; + auto frames = UnwindFramePointers(pc, sp, fp, 8, readWord, isExec); + auto mods = modulesOf(*e); auto exe = findModule(mods, "/progs"); ElfInfo elf; CHECK(ReadElfFile(exe->path, elf)); + printf(" %zu frames:", frames.size()); + std::vector names; + for (auto& f : frames) { auto s = FindElfSymbol(elf, f.pc); names.push_back(s ? s->name : "?"); printf(" %s", names.back().c_str()); } printf("\n"); + CHECK(frames.size() >= 4); if (frames.size() < 4) return; + CHECK(names[0] == "level3" && names[1] == "level2" && names[2] == "level1" && names[3] == "main"); + for (size_t i = 1; i < frames.size(); i++) CHECK(frames[i].sp > frames[i - 1].sp); + // a bad frame pointer stops the walk instead of misbehaving + CHECK(UnwindFramePointers(pc, sp, 0, 8, readWord, isExec).size() == 1); + CHECK(UnwindFramePointers(pc, sp, fp + 1, 8, readWord, isExec).size() == 1); + CHECK(UnwindFramePointers(pc, sp, sp - 16, 8, readWord, isExec).size() == 1); + CHECK(UnwindFramePointers(pc, sp, fp, 8, [](uint64_t, uint64_t& v) { v = 0; return false; }, isExec).size() == 1); + CHECK(UnwindFramePointers(pc, sp, fp, 8, readWord, isExec, 2).size() == 2); + e->Kill(); +} + +static void t_loader() +{ + Log log; PtraceEngine::Event ev; auto e = start(log, "dl"); if (!e) return; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + // what the adapter does: find _dl_debug_state in the dynamic loader + auto mods = modulesOf(*e); auto exe = findModule(mods, "/progs"); auto ld = findModule(mods, kLoaderName); CHECK(exe && ld); if (!exe || !ld) return; + ElfInfo exeElf, ldElf; CHECK(ReadElfFile(exe->path, exeElf)); CHECK(ReadElfFile(ld->path, ldElf)); + CHECK(!exeElf.interpreter.empty() && exeElf.interpreter.find(kLoaderName) != std::string::npos); + uint64_t state = 0; for (auto& s : ldElf.symbols) if (s.name == "_dl_debug_state") state = s.address + ld->base - ldElf.linkBase; + CHECK(state != 0); if (!state) return; + CHECK(e->AddBreakpoint(state)); + int hits = 0; bool sawLib = false; bool libBeforeDlopen = false; bool atSignal = false; uint64_t libfuncAddr = 0; + CHECK(e->Resume(false, 0)); + for (int i = 0; i < 200; i++) + { + if (!log.wait(PtraceEngine::StoppedEvent, ev, 4000ms)) { printf(" timeout\n"); failures++; break; } + bool haveLib = findModule(modulesOf(*e), "libtest.so") != nullptr; + if (ev.breakpoint) + { + std::vector r; e->GetRegisterSet(ev.tid, NT_PRSTATUS, r); uint64_t at = le64(r, kPcOff); + if (libfuncAddr && at == libfuncAddr) { printf(" hit the breakpoint in the library\n"); break; } + hits++; CHECK(at == state); if (haveLib) sawLib = true; if (haveLib && !atSignal) libBeforeDlopen = true; + } + else if (ev.signal == SIGUSR1) + { + if (!atSignal) { atSignal = true; CHECK(!haveLib); } + else + { + // the library is loaded now: a breakpoint by module and offset resolves and is hit + auto libMods = modulesOf(*e); auto lib = findModule(libMods, "libtest.so"); CHECK(lib != nullptr); if (!lib) break; + ElfInfo libElf; CHECK(ReadElfFile(lib->path, libElf)); + for (auto& s : libElf.symbols) if (s.name == "libfunc") libfuncAddr = s.address + lib->base - libElf.linkBase; + CHECK(libfuncAddr != 0); CHECK(e->AddBreakpoint(libfuncAddr)); + CHECK(e->RemoveBreakpoint(state)); + } + } + else if (ev.breakpoint == false && ev.signal == SIGTRAP) { std::vector r; e->GetRegisterSet(ev.tid, NT_PRSTATUS, r); if (libfuncAddr && le64(r, kPcOff) == libfuncAddr) break; } + CHECK(e->Resume(false, 0)); + } + printf(" loader hits: %d, library seen after load: %d\n", hits, sawLib); + CHECK(hits >= 3); CHECK(sawLib); CHECK(!libBeforeDlopen); CHECK(libfuncAddr != 0); + e->Kill(); +} + +static void t_library_reload_breakpoint() +{ + Log log; auto e = start(log, "dlcycle"); if (!e) return; PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); + uint64_t first = addrOf(log, "cycle1="); CHECK(first != 0); CHECK(e->AddBreakpoint(first)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.breakpoint && pcOf(*e, ev.tid) == first); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); + uint64_t second = addrOf(log, "cycle2="); CHECK(second != 0); + if (second != first) + { + printf(" SKIP: loader chose a different address (%llx -> %llx)\n", (unsigned long long)first, (unsigned long long)second); + e->Kill(); return; + } + // The old record survived dlclose. Even asking to add the same breakpoint again reports success without + // reinstalling it into the replacement mapping. + CHECK(e->AddBreakpoint(second)); + auto raw = rawRead(e->GetPid(), second, kBreakInsn.size()); + printf(" reloaded at the same address; physical breakpoint present=%d\n", raw == kBreakInsn); + CHECK(raw == kBreakInsn); + CHECK(e->RemoveBreakpoint(second)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 0); +} + +static void t_library_rebase_breakpoint() +{ + Log log; auto e = start(log, "dlrebase"); if (!e) return; PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint64_t first = addrOf(log, "cycle1="); CHECK(first != 0); CHECK(e->AddBreakpoint(first)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.breakpoint); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint64_t second = addrOf(log, "cycle2="); CHECK(second != 0); CHECK(second != first); + // The adapter must discard the physical record without restoring stale bytes into the replacement mapping, then + // resolve the logical module-relative breakpoint at its new address. + CHECK(e->DiscardBreakpoint(first)); CHECK(e->AddBreakpoint(second)); + auto raw = rawRead(e->GetPid(), second, kBreakInsn.size()); + printf(" rebased %llx -> %llx; physical breakpoint at replacement=%d\n", (unsigned long long)first, + (unsigned long long)second, raw == kBreakInsn); + CHECK(raw == kBreakInsn); + CHECK(e->RemoveBreakpoint(second)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); +} + +static void t_library_rebase_hardware() +{ + Log log; auto e = start(log, "dlrebase"); if (!e) return; PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint64_t first = addrOf(log, "cycle1="); CHECK(first != 0); + if (!e->AddHardwareBreakpoint(first, PtraceHwType::Execute, 4)) { printf(" SKIP: no hardware breakpoints\n"); e->Kill(); return; } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.hardware); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint64_t second = addrOf(log, "cycle2="); CHECK(second != 0); CHECK(second != first); + // A module-relative hardware breakpoint must move with the mapping rather than remaining armed at the old address. + CHECK(e->RemoveHardwareBreakpoint(first, PtraceHwType::Execute, 4)); + CHECK(e->AddHardwareBreakpoint(second, PtraceHwType::Execute, 4)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.hardware && pcOf(*e, ev.tid) == second); + CHECK(e->RemoveHardwareBreakpoint(second, PtraceHwType::Execute, 4)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 0); +} + +static void t_processes() +{ + Log log; auto e = start(log, "sleeper"); if (!e) return; + auto list = ListProcesses(); bool self = false, target = false; + // the sanitizer builds are called something else than driver + std::string me; { std::ifstream comm("/proc/self/comm"); std::getline(comm, me); } + for (auto& p : list) { if (p.pid == (uint32_t)getpid()) { self = true; CHECK(p.name == me); CHECK(p.commandLine.find(me) != std::string::npos); } if (p.pid == e->GetPid()) { target = true; CHECK(p.name == "progs"); CHECK(p.commandLine.find("sleeper") != std::string::npos); } } + CHECK(self && target); for (size_t i = 1; i < list.size(); i++) CHECK(list[i - 1].pid < list[i].pid); + e->Kill(); +} + +// ---- stepping +struct StepEnv +{ + Log log; // first, so that it outlives the engine that posts to it + PtraceEngine::Event ev; uint32_t tid = 0; + std::map refs; std::set user; + std::unique_ptr e; + std::unique_ptr stepper; + bool acquire(uint64_t a) { if (refs[a] == 0 && !e->AddBreakpoint(a)) { refs.erase(a); return false; } refs[a]++; return true; } + bool release(uint64_t a) { auto it = refs.find(a); if (it == refs.end()) return false; if (--it->second > 0) return true; refs.erase(it); return e->RemoveBreakpoint(a); } + bool begin(const std::string& mode) + { + e = startAtSignal(log, mode, tid, ev); if (!e) return false; + stepper = std::make_unique(*e, [this](uint64_t a) { return acquire(a); }, [this](uint64_t a) { return release(a); }); + return true; + } + uint64_t reg(size_t offset) { std::vector r; if (!e->GetRegisterSet(tid, NT_PRSTATUS, r)) return 0; return le64(r, offset); } + uint64_t pc() { return reg(kPcOff); } + uint64_t sp() { return reg(kSpOff); } + // Runs to a label that the target printed, by a temporary breakpoint of the engine + bool runTo(uint64_t address) + { + CHECK(e->AddBreakpoint(address)); CHECK(e->Resume(false, 0)); + if (!log.wait(PtraceEngine::StoppedEvent, ev, 5s)) { printf(" runTo: no stop\n"); failures++; return false; } + tid = ev.tid; CHECK(pc() == address); CHECK(e->RemoveBreakpoint(address)); return pc() == address; + } + uint32_t insnAt(uint64_t a) { uint32_t v = 0; e->ReadMemory(a, &v, 4); return v; } +#if defined(__x86_64__) + static bool isCall(uint32_t i) { return (i & 0xFF) == 0xE8; } // call rel32, which is what a direct call compiles to +#else + static bool isCall(uint32_t i) { return (i & 0xFC000000) == 0x94000000 || (i & 0xFFFFFC1F) == 0xD63F0000; } +#endif + // single-steps until the instruction at the pc is a call + bool stepToCall() + { + for (int i = 0; i < 40; i++) + { + if (isCall(insnAt(pc()))) return true; + if (!e->Resume(true, tid) || !log.wait(PtraceEngine::StoppedEvent, ev, 5s)) { failures++; return false; } + } + printf(" no call found\n"); failures++; return false; + } + // feeds the stops to the stepper until it is finished with them + PtraceStepper::Result follow(std::chrono::milliseconds timeout = 8000ms) + { + while (true) + { + if (!log.wait(PtraceEngine::StoppedEvent, ev, timeout)) { printf(" follow: no stop\n"); failures++; return PtraceStepper::Result::Ignored; } + uint64_t p = 0, s = 0; { std::vector r; if (e->GetRegisterSet(ev.tid, NT_PRSTATUS, r)) { p = le64(r, kPcOff); s = le64(r, kSpOff); } } + auto res = stepper->OnStop(ev, p, s, user.count(p) > 0); + if (res != PtraceStepper::Result::Consumed) { tid = ev.tid; return res; } + } + } + bool exitsWith(int code) { if (!e->Resume(false, 0)) { failures++; return false; } bool got = false; for (int i = 0; i < 300 && !got; i++) { std::unique_lock l(log.m); log.cv.wait_for(l, 30ms); for (auto it = log.q.begin(); it != log.q.end(); ++it) if (it->type == PtraceEngine::ExitedEvent) { ev = *it; got = true; break; } } if (!got) { printf(" no exit\n"); failures++; return false; } CHECK(ev.exitCode == code); return ev.exitCode == code; } +}; + +static std::vector retSitesOf(const ElfInfo& elf, const std::string& name) +{ + std::vector sites; +#if defined(__x86_64__) + // the program has frame pointers, so the epilogue is `leave; ret` or `pop %rbp; ret` + for (auto& s : elf.symbols) if (s.name == name) + { + std::vector code(s.size); std::ifstream f(PTRACE_TEST_DIRECTORY "/progs", std::ios::binary); f.seekg(s.address - 0x400000); f.read((char*)code.data(), code.size()); + for (size_t i = 1; i < code.size(); i++) if (code[i] == 0xC3 && (code[i - 1] == 0xC9 || code[i - 1] == 0x5D)) sites.push_back(s.address + i); + } +#else + for (auto& s : elf.symbols) if (s.name == name) for (uint64_t a = s.address; a < s.address + s.size; a += 4) { uint32_t insn; std::ifstream f(PTRACE_TEST_DIRECTORY "/progs", std::ios::binary); f.seekg(a - 0x400000); f.read((char*)&insn, 4); if (insn == 0xd65f03c0) sites.push_back(a); } +#endif + return sites; +} + +static uint64_t symbolAddr(const ElfInfo& elf, const std::string& name) { for (auto& s : elf.symbols) if (s.name == name) return s.address; return 0; } + +static void t_stepover_basic() +{ + StepEnv t; if (!t.begin("stepover")) return; + uint64_t here = addrOf(t.log, "here="); CHECK(t.runTo(here)); + CHECK(t.stepToCall()); uint64_t callPc = t.pc(), spBefore = t.sp(); + // a plain instruction is a single step + CHECK(t.stepper->StepOver(t.tid, callPc - 4, spBefore, 0, 8) == true); CHECK(t.follow() == PtraceStepper::Result::Ignored); CHECK(t.ev.singleStep); + // the call runs to its end + StepEnv u; if (!u.begin("stepover")) return; + uint64_t here2 = addrOf(u.log, "here="); CHECK(u.runTo(here2)); CHECK(u.stepToCall()); callPc = u.pc(); spBefore = u.sp(); + CHECK(u.stepper->StepOver(u.tid, callPc, spBefore, kCallLength, 8)); + CHECK(u.follow() == PtraceStepper::Result::Finished); + CHECK(u.pc() == callPc + kCallLength); CHECK(u.sp() == spBefore); CHECK(!u.stepper->IsActive()); + CHECK(u.refs.empty()); // the temporary breakpoint is gone + { auto raw = rawRead(u.e->GetPid(), callPc + kCallLength, 4); uint32_t seen = 0; u.e->ReadMemory(callPc + kCallLength, &seen, 4); CHECK(raw.size() == 4 && !memcmp(raw.data(), &seen, 4)); } // no breakpoint bytes left behind + CHECK(u.exitsWith(11)); +} + +static void t_stepover_user_breakpoint() +{ + StepEnv t; if (!t.begin("stepover")) return; + uint64_t here = addrOf(t.log, "here="); CHECK(t.runTo(here)); CHECK(t.stepToCall()); + uint64_t callPc = t.pc(), spBefore = t.sp(); + ElfInfo elf; auto mods = modulesOf(*t.e); auto exe = findModule(mods, "/progs"); CHECK(exe != nullptr); CHECK(ReadElfFile(exe->path, elf)); + uint64_t marker = symbolAddr(elf, "marker"); CHECK(marker != 0); + CHECK(t.acquire(marker)); t.user.insert(marker); + CHECK(t.stepper->StepOver(t.tid, callPc, spBefore, kCallLength, 8)); + auto res = t.follow(); CHECK(res == PtraceStepper::Result::Ignored); CHECK(t.ev.breakpoint); CHECK(t.pc() == marker); + CHECK(!t.stepper->IsActive()); CHECK(t.refs.size() == 1 && t.refs.count(marker)); // only the user's breakpoint is left + CHECK(t.exitsWith(11)); +} + +static void t_stepover_interrupt() +{ + StepEnv t; if (!t.begin("stepslow")) return; + uint64_t here = addrOf(t.log, "here="); CHECK(t.runTo(here)); CHECK(t.stepToCall()); + uint64_t callPc = t.pc(), spBefore = t.sp(); + CHECK(t.stepper->StepOver(t.tid, callPc, spBefore, kCallLength, 8)); CHECK(t.stepper->IsActive()); + std::this_thread::sleep_for(100ms); CHECK(t.e->Interrupt()); + auto res = t.follow(); CHECK(res == PtraceStepper::Result::Ignored); CHECK(t.ev.interrupted); + CHECK(!t.stepper->IsActive()); CHECK(t.refs.empty()); + // stepping over again works from wherever it stopped, and cancelling releases the breakpoint + CHECK(t.stepper->StepReturn(t.tid, t.pc(), t.sp(), {}, callPc + kCallLength, spBefore)); CHECK(t.stepper->IsActive() && !t.refs.empty()); + t.stepper->Cancel(); CHECK(t.refs.empty()); CHECK(!t.stepper->IsActive()); + CHECK(t.e->Kill()); +} + +static void t_stepover_recursion() +{ + StepEnv t; if (!t.begin("recurse")) return; + uint64_t site = addrOf(t.log, "site="); CHECK(t.runTo(site)); CHECK(t.stepToCall()); + uint64_t callPc = t.pc(), spBefore = t.sp(); + ElfInfo elf; auto mods = modulesOf(*t.e); auto exe = findModule(mods, "/progs"); CHECK(ReadElfFile(exe->path, elf)); + uint64_t counterAddr = symbolAddr(elf, "counter"); CHECK(counterAddr != 0); + CHECK(t.stepper->StepOver(t.tid, callPc, spBefore, kCallLength, 8)); + CHECK(t.follow() == PtraceStepper::Result::Finished); + // it stopped in the frame that made the call, after all the calls beneath it had returned + CHECK(t.pc() == callPc + kCallLength); CHECK(t.sp() == spBefore); + int counter = 0; CHECK(t.e->ReadMemory(counterAddr, &counter, 4)); CHECK(counter == 2); + CHECK(t.exitsWith(3)); +} + +static void t_stepreturn_sites() +{ + StepEnv t; if (!t.begin("stepret")) return; + uint64_t there = addrOf(t.log, "there="); CHECK(t.runTo(there)); + ElfInfo elf; auto mods = modulesOf(*t.e); auto exe = findModule(mods, "/progs"); CHECK(ReadElfFile(exe->path, elf)); + auto sites = retSitesOf(elf, "inner"); CHECK(sites.size() >= 1); + // where the function returns to, from the frame pointers + auto maps = t.e->GetMaps(); auto isExec = [&](uint64_t a) { for (auto& m : maps) if (m.execute && a >= m.start && a < m.end) return true; return false; }; + auto readWord = [&](uint64_t a, uint64_t& v) { v = 0; return t.e->ReadMemory(a, &v, 8); }; + auto frames = UnwindFramePointers(t.pc(), t.sp(), t.reg(kFpOff), 8, readWord, isExec); CHECK(frames.size() >= 2); + CHECK(t.stepper->StepReturn(t.tid, t.pc(), t.sp() + kMinSpExtra, sites, 0, 0)); + CHECK(t.follow() == PtraceStepper::Result::Finished); + CHECK(t.pc() == frames[1].pc); CHECK(t.sp() >= frames[1].sp); CHECK(t.refs.empty()); // on arm64 the frame size is not known, so the unwound sp is a lower bound + CHECK(t.exitsWith(102 - 1)); // inner adds 1 and outer adds 100 +} + +static void t_stepreturn_address() +{ + StepEnv t; if (!t.begin("stepret")) return; + uint64_t there = addrOf(t.log, "there="); CHECK(t.runTo(there)); + auto maps = t.e->GetMaps(); auto isExec = [&](uint64_t a) { for (auto& m : maps) if (m.execute && a >= m.start && a < m.end) return true; return false; }; + auto readWord = [&](uint64_t a, uint64_t& v) { v = 0; return t.e->ReadMemory(a, &v, 8); }; + auto frames = UnwindFramePointers(t.pc(), t.sp(), t.reg(kFpOff), 8, readWord, isExec); CHECK(frames.size() >= 2); + CHECK(!t.stepper->StepReturn(t.tid, t.pc(), t.sp(), {}, 0, 0)); // nothing to run to + CHECK(t.stepper->StepReturn(t.tid, t.pc(), t.sp(), {}, frames[1].pc, frames[1].sp)); + CHECK(t.follow() == PtraceStepper::Result::Finished); + CHECK(t.pc() == frames[1].pc); CHECK(t.sp() >= frames[1].sp); CHECK(t.refs.empty()); + CHECK(t.exitsWith(101)); +} + +static void t_stepreturn_recursion() +{ + StepEnv t; if (!t.begin("recurse")) return; + uint64_t site = addrOf(t.log, "site="); CHECK(t.runTo(site)); + ElfInfo elf; auto mods = modulesOf(*t.e); auto exe = findModule(mods, "/progs"); CHECK(ReadElfFile(exe->path, elf)); + auto sites = retSitesOf(elf, "recurse"); CHECK(sites.size() >= 1); + auto maps = t.e->GetMaps(); auto isExec = [&](uint64_t a) { for (auto& m : maps) if (m.execute && a >= m.start && a < m.end) return true; return false; }; + auto readWord = [&](uint64_t a, uint64_t& v) { v = 0; return t.e->ReadMemory(a, &v, 8); }; + auto frames = UnwindFramePointers(t.pc(), t.sp(), t.reg(kFpOff), 8, readWord, isExec); CHECK(frames.size() >= 2); + // the deeper calls return through the same instructions first, and none of them is the end of this one + CHECK(t.stepper->StepReturn(t.tid, t.pc(), t.sp() + kMinSpExtra, sites, 0, 0)); + CHECK(t.follow() == PtraceStepper::Result::Finished); + CHECK(t.pc() == frames[1].pc); CHECK(t.sp() >= frames[1].sp); + int counter = 0; CHECK(t.e->ReadMemory(symbolAddr(elf, "counter"), &counter, 4)); CHECK(counter == 3); // the frame has finished, including its own increment + CHECK(t.exitsWith(3)); +} + +static void t_stepover_threads() +{ + StepEnv t; if (!t.begin("stepthreads")) return; + uint64_t sync = addrOf(t.log, "sync="); CHECK(t.runTo(sync)); + CHECK(t.stepToCall()); uint64_t callPc = t.pc(), spBefore = t.sp(); uint32_t stepper = t.tid; + CHECK(t.stepper->StepOver(t.tid, callPc, spBefore, kCallLength, 8)); + // the other threads run through the same call and return address all the while + CHECK(t.follow() == PtraceStepper::Result::Finished); + CHECK(t.ev.tid == stepper); CHECK(t.pc() == callPc + kCallLength); CHECK(t.sp() == spBefore); CHECK(t.refs.empty()); + CHECK(t.e->Kill()); +} + +// Runs a target that forks or spawns with a breakpoint set, and counts the hits of the parent +static void forkTest(const char* mode, int expectedHits, int expectedExit) +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, mode, tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); CHECK(e->AddBreakpoint(marker)); + int hits = 0; CHECK(e->Resume(false, 0)); + while (true) + { + { std::unique_lock l(log.m); bool got = log.cv.wait_for(l, 10s, [&] { for (auto& q : log.q) if (q.type == PtraceEngine::StoppedEvent || q.type == PtraceEngine::ExitedEvent) return true; return false; }); if (!got) { printf(" timeout after %d hits\n", hits); failures++; return; } } + if (log.wait(PtraceEngine::ExitedEvent, ev, 1ms)) break; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); if (!(ev.breakpoint && pcOf(*e, ev.tid) == marker)) { printf(" stray stop sig=%d\n", ev.signal); failures++; return; } + CHECK((rawRead(e->GetPid(), marker, kBreakInsn.size()) == kBreakInsn)); // our own breakpoint is back + hits++; if (!e->Resume(false, 0)) { printf(" resume failed\n"); failures++; return; } + } + printf(" hits=%d exit=%d signal=%d\n", hits, ev.exitCode, ev.signal); CHECK(hits == expectedHits); CHECK(ev.exitCode == expectedExit); +} + +static void t_fork_child() { forkTest("forkbp", 0, 0); forkTest("forkbp2", 1, 0); } +static void t_vfork() { forkTest("vforkbp", 1, 0); } +static void t_spawn() { forkTest("spawnbp", 1, 7); } +static void t_fork_threads() { forkTest("forkthreads", 60, 0); } + +static void t_exec_basic() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "execbp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); uint32_t pid = e->GetPid(); + CHECK(e->AddBreakpoint(marker)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.exec); CHECK(ev.tid == pid); CHECK(!ev.breakpoint); CHECK(e->GetThreads().size() == 1); + // the memory is the new program's, and the breakpoint of the old one is gone from it and from what we know + uint32_t seen = 0; CHECK(e->ReadMemory(marker, &seen, 4)); auto raw = rawRead(pid, marker, 4); CHECK(raw.size() == 4 && !memcmp(raw.data(), &seen, 4)); + CHECK(!std::equal(kBreakInsn.begin(), kBreakInsn.end(), raw.begin())); + CHECK(pcOf(*e, pid) != 0); + CHECK(!e->RemoveBreakpoint(marker)); // nothing is left of it + // the new program runs its five calls without a stop, because there is no breakpoint any more + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1 && !ev.exec); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +static void t_exec_rebreak() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "execbp", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.exec); + // breakpoints work in the new program, in the same way as in the first one + CHECK(e->AddBreakpoint(marker)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); + for (int i = 1; i <= 5; i++) { CHECK(e->Resume(false, 0)); if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no hit %d\n", i); failures++; return; } CHECK(ev.breakpoint && pcOf(*e, ev.tid) == marker); } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +static void t_exec_thread() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "execthread", tid, ev); if (!e) return; + uint32_t pid = e->GetPid(); CHECK(e->GetThreads().size() == 2); + CHECK(e->Resume(false, 0)); + // the thread that runs exec is not the main thread, and the main thread is gone + CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(ev.exec); CHECK(ev.tid == pid); CHECK(e->GetThreads() == std::vector{pid}); + CHECK(pcOf(*e, pid) != 0); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); +} + +static void t_exec_continue() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "execloop", tid, ev); if (!e) return; + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.exec); + // everything still works afterwards: running, interrupting, stepping, registers + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(100ms); CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.interrupted && !ev.exec); + uint64_t pc = pcOf(*e, ev.tid); CHECK(pc != 0); + CHECK(e->Resume(true, ev.tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.singleStep); + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGKILL); +} + +static void t_winsize() +{ + Log log; auto e = start(log, "winsize"); if (!e) return; PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); + CHECK(log.output.find("tty=1 ioctl=0 rows=24 cols=80") != std::string::npos); + + Log log2; auto e2 = std::make_unique([&log2](const PtraceEngine::Event& x) { log2.push(x); }); + PtraceEngine::LaunchOptions o; o.path = prog; o.args = {"winsize"}; o.arch = TestArch(); o.rows = 50; o.columns = 132; std::string err; + CHECK(e2->Launch(o, err)); CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e2->Resume(false, 0)); CHECK(log2.wait(PtraceEngine::ExitedEvent, ev)); + CHECK(log2.output.find("tty=1 ioctl=0 rows=50 cols=132") != std::string::npos); +} + +static double cpuSeconds(); + +static void t_stdin_backpressure() +{ + Log log; auto e = start(log, "cat"); if (!e) return; PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + std::string input(8 << 20, 'x'); + double c0 = cpuSeconds(); + auto writer = std::async(std::launch::async, [&] { return e->WriteInput(input); }); + std::this_thread::sleep_for(300ms); + double cpu = cpuSeconds() - c0; + printf(" debugger used %.0f ms of CPU during 300 ms of stopped-target backpressure\n", cpu * 1000); + CHECK(writer.wait_for(0s) == std::future_status::ready); + // Release the writer even on the buggy path. The target reads one line and exits, closing the PTY. + CHECK(e->Resume(false, 0)); + CHECK(writer.wait_for(5s) == std::future_status::ready); + if (writer.wait_for(0s) == std::future_status::ready) + writer.get(); +} + +static double cpuSeconds() { rusage u; getrusage(RUSAGE_SELF, &u); return u.ru_utime.tv_sec + u.ru_stime.tv_sec + (u.ru_utime.tv_usec + u.ru_stime.tv_usec) / 1e6; } + +static void t_detach_reaped() +{ + Log log; auto e = start(log, "sleeper"); if (!e) return; PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); uint32_t pid = e->GetPid(); + int status = 0; CHECK(!e->WaitForDetachedExit(status, 10ms)); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(100ms); CHECK(e->Detach()); CHECK(log.wait(PtraceEngine::DetachedEvent, ev)); + CHECK(!e->WaitForDetachedExit(status, 200ms)); + CHECK(e->WaitForDetachedExit(status, 4s)); CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 3); + std::this_thread::sleep_for(50ms); CHECK(procState(pid) == "gone"); + // and the engine can go away while the target is still running + Log log2; auto e2 = start(log2, "sleeper"); if (!e2) return; CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); uint32_t pid2 = e2->GetPid(); + CHECK(e2->Resume(false, 0)); std::this_thread::sleep_for(50ms); CHECK(e2->Detach()); CHECK(log2.wait(PtraceEngine::DetachedEvent, ev)); e2.reset(); + std::this_thread::sleep_for(2500ms); CHECK(procState(pid2) == "gone"); +} + +static bool twoAddrs(Log& log, uint64_t& a, uint64_t& b) +{ + if (!waitOutput(log, "handler=")) return false; + unsigned long long x = 0, y = 0; sscanf(log.output.c_str(), "info=%llx handler=%llx", &x, &y); a = x; b = y; return x && y; +} + +static uint64_t x0Of(PtraceEngine& e, uint32_t tid) { std::vector r; return e.GetRegisterSet(tid, NT_PRSTATUS, r) ? le64(r, kArg0Off) : ~0ull; } + +static void t_handlers_off() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sighandler", tid, ev); if (!e) return; + uint64_t info, handler; CHECK(twoAddrs(log, info, handler)); + // by default the signal stops the target where it is delivered, and the handler then runs on its own + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR2 && ev.signalHandler == 0); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 11); // both handlers ran, with no stop + + // a breakpoint in a handler works with or without the setting + Log log2; auto e2 = startAtSignal(log2, "sighandler", tid, ev); if (!e2) return; twoAddrs(log2, info, handler); + CHECK(e2->AddBreakpoint(handler)); CHECK(e2->Resume(false, 0)); CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR2); + CHECK(e2->Resume(false, 0)); CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.breakpoint && pcOf(*e2, ev.tid) == handler && ev.signalHandler == 0); + CHECK(e2->Resume(false, 0)); CHECK(log2.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 11); +} + +static void t_handlers_on() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sighandler", tid, ev); if (!e) return; + uint64_t info, handler; CHECK(twoAddrs(log, info, handler)); e->SetDebugSignalHandlers(true); + // the signal still stops where it is delivered + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR2 && ev.signalHandler == 0); + // and then the target stops at the first instruction of the handler, with the signal number as its argument + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signalHandler == SIGUSR2 && !ev.breakpoint && !ev.singleStep && ev.signal == SIGTRAP); CHECK(pcOf(*e, ev.tid) == info); CHECK(x0Of(*e, ev.tid) == SIGUSR2); + // a signal that does not stop the target has its handler stopped at, without a stop for the signal itself + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signalHandler == SIGWINCH); CHECK(pcOf(*e, ev.tid) == handler); CHECK(x0Of(*e, ev.tid) == SIGWINCH); + // stepping from there goes through the handler like through any function + CHECK(e->Resume(true, ev.tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.singleStep && ev.signalHandler == 0); + // a signal that has no handler goes by, and the program finishes + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 11); +} + +static void t_handlers_toggle() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sighandler", tid, ev); if (!e) return; + uint64_t info, handler; twoAddrs(log, info, handler); e->SetDebugSignalHandlers(true); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR2); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signalHandler == SIGUSR2); + // turned off in the middle of it, the next handler runs on its own + e->SetDebugSignalHandlers(false); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 11); +} + +static void t_handlers_thread() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigthread", tid, ev); if (!e) return; + waitOutput(log, "handler="); unsigned long long handler = 0; sscanf(log.output.c_str(), "handler=%llx", &handler); + e->SetDebugSignalHandlers(true); uint32_t pid = e->GetPid(); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); + // the handler runs in the thread that the signal was sent to + CHECK(ev.signalHandler == SIGWINCH); CHECK(ev.tid != pid); CHECK(pcOf(*e, ev.tid) == handler); CHECK(e->GetThreads().size() == 2); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_raise() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_raise", tid, ev); if (!e) return; + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(!ev.breakpoint && !ev.hardware && !ev.singleStep && ev.signalHandler == 0); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_kill() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_kill", tid, ev); if (!e) return; + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(!ev.breakpoint && !ev.singleStep); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_handler_debug() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_raise", tid, ev); if (!e) return; + e->SetDebugSignalHandlers(true); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signalHandler == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::SignalHandler); + CHECK(!ev.breakpoint && !ev.hardware && !ev.singleStep); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_instruction() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_instruction", tid, ev); if (!e) return; + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(!ev.breakpoint && !ev.singleStep); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_instruction_handler_debug() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_instruction", tid, ev); if (!e) return; + e->SetDebugSignalHandlers(true); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signalHandler == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::SignalHandler); + CHECK(!ev.breakpoint && !ev.singleStep); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_unhandled() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_unhandled", tid, ev); if (!e) return; + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGTRAP); +} + +static void t_sigtrap_after_breakpoint() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_raise", tid, ev); if (!e) return; + uint64_t raiser = addrOf(log, "raiser="); CHECK(raiser != 0); CHECK(e->AddBreakpoint(raiser)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.breakpoint && ev.trapOrigin == PtraceEngine::TrapOrigin::SoftwareBreakpoint); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target && !ev.breakpoint); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +static void t_sigtrap_while_stepping() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "sigtrap_instruction", tid, ev); if (!e) return; + uint64_t before = addrOf(log, "before="); uint64_t trap = addrOf(log, "trap="); + CHECK(before != 0 && trap != 0); CHECK(e->AddBreakpoint(before)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.breakpoint); + CHECK(e->Resume(true, ev.tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.singleStep && ev.trapOrigin == PtraceEngine::TrapOrigin::SingleStep); CHECK(pcOf(*e, ev.tid) == trap); + CHECK(e->Resume(true, ev.tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.signal == SIGTRAP && ev.trapOrigin == PtraceEngine::TrapOrigin::Target); + CHECK(!ev.singleStep && !ev.breakpoint); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 1); +} + +// Many interrupts at once must make one pause, and leave nothing behind that stops the target again later or gets passed on to it +static void t_interrupt_burst() +{ + Log log; PtraceEngine::Event ev; auto e = start(log, "loop"); if (!e) return; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); uint32_t pid = e->GetPid(); + for (int round = 0; round < 40; round++) + { + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(std::chrono::microseconds(200 + round * 50)); + std::vector pokers; for (int i = 0; i < 4; i++) pokers.emplace_back([&] { for (int k = 0; k < 25; k++) e->Interrupt(); }); + for (auto& t : pokers) t.join(); + if (!log.wait(PtraceEngine::StoppedEvent, ev, 3000ms)) { printf(" round %d: no stop\n", round); failures++; break; } + if (!ev.interrupted) { printf(" round %d: stop was not the interrupt (signal %d)\n", round, ev.signal); failures++; break; } + // nothing else is waiting to stop it + if (log.wait(PtraceEngine::StoppedEvent, ev, 20ms)) { printf(" round %d: a second stop for the same interrupt\n", round); failures++; break; } + } + // and resuming does not stop it again, nor pass a stop on to it + CHECK(e->Resume(false, 0)); CHECK(!log.wait(PtraceEngine::StoppedEvent, ev, 150ms)); + CHECK(procState(pid).find("(stopped)") == std::string::npos); + CHECK(e->Kill()); +} + +static void t_elf_names() +{ + auto mods = std::vector(); ElfInfo elf; CHECK(ReadElfFile(PTRACE_TEST_DIRECTORY "/progs", elf)); + bool amb = true; auto m = FindElfFunctionByName(elf, "marker", &amb); CHECK(m != nullptr && !amb && m->isFunction); + // a data symbol is not a function, and a name that is not there is nothing + amb = true; CHECK(FindElfFunctionByName(elf, "counter", &amb) == nullptr && !amb); + CHECK(FindElfFunctionByName(elf, "no_such_function", &amb) == nullptr && !amb); CHECK(FindElfFunctionByName(elf, "marker") == m); + // the start of a function and a place inside it are told apart by the offset + auto at = FindElfSymbol(elf, m->address); CHECK(at && at->name == "marker" && at->address == m->address); + auto inside = FindElfSymbol(elf, m->address + 4); CHECK(inside && inside->name == "marker" && inside->address != m->address + 4); + // one function at two addresses is not a name to go by, but the same one twice is + ElfInfo fake; fake.symbols = {{"dup", 0x100, 8, true}, {"dup", 0x200, 8, true}, {"same", 0x300, 8, true}, {"same", 0x300, 8, true}, {"mixed", 0x400, 8, true}, {"mixed", 0x500, 8, false}}; + amb = false; CHECK(FindElfFunctionByName(fake, "dup", &amb) == nullptr && amb); + amb = true; auto same = FindElfFunctionByName(fake, "same", &amb); CHECK(same && same->address == 0x300 && !amb); + amb = true; auto mixed = FindElfFunctionByName(fake, "mixed", &amb); CHECK(mixed && mixed->address == 0x400 && !amb); // the data symbol does not count +} + +// What the adapter does after an exec, on the real engine: the breakpoint that was at the start of a function is put at the start of +// the function with the same name in the new program, which is not at the same address +static void t_exec_by_name() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "execpad", tid, ev); if (!e) return; + uint64_t oldMarker = addrOf(log, "marker="); CHECK(e->AddBreakpoint(oldMarker)); + auto oldMods = modulesOf(*e); auto oldExe = findModule(oldMods, "/progs"); ElfInfo oldElf; CHECK(oldExe && ReadElfFile(oldExe->path, oldElf)); + auto atStart = FindElfSymbol(oldElf, oldMarker - oldExe->base + oldElf.linkBase); CHECK(atStart && atStart->isFunction && atStart->address == oldMarker - oldExe->base + oldElf.linkBase); + std::string function = atStart ? atStart->name : ""; CHECK(function == "marker"); + + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.exec); + auto mods = modulesOf(*e); auto exe = findModule(mods, "/progs_pad"); CHECK(exe != nullptr); if (!exe) return; + CHECK(findModule(mods, "/progs") == nullptr || findModule(mods, "/progs")->path != exe->path); + ElfInfo elf; CHECK(ReadElfFile(exe->path, elf)); bool amb = false; auto found = FindElfFunctionByName(elf, function, &amb); CHECK(found && !amb); if (!found) return; + uint64_t newMarker = found->address + exe->base - elf.linkBase; + printf(" marker moved from %llx to %llx\n", (unsigned long long)oldMarker, (unsigned long long)newMarker); CHECK(newMarker != oldMarker); + CHECK(e->AddBreakpoint(newMarker)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGUSR1); + for (int i = 1; i <= 5; i++) { CHECK(e->Resume(false, 0)); if (!log.wait(PtraceEngine::StoppedEvent, ev)) { printf(" no hit %d\n", i); failures++; return; } CHECK(ev.breakpoint && pcOf(*e, ev.tid) == newMarker); } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 5); +} + +// ---- the scenarios of the unit tests of the repository (test/debugger_test.py), on its own test binaries +static const std::string bins = PTRACE_TEST_CORPUS_DIRECTORY "/"; + +static std::unique_ptr startBin(Log& log, const std::string& name, std::vector args = {}) +{ + auto e = std::make_unique([&log](const PtraceEngine::Event& ev) { log.push(ev); }); + PtraceEngine::LaunchOptions o; o.path = bins + name; o.args = args; o.arch = TestArch(); std::string err; + if (!e->Launch(o, err)) { printf(" launch of %s failed: %s\n", name.c_str(), err.c_str()); failures++; return nullptr; } + return e; +} + +// What the adapter does at the first stop: the breakpoint at the entry point of the program, by module and offset +static bool entryBreakpoint(PtraceEngine& e, Log& log, PtraceEngine::Event& ev, const std::string& name, uint64_t& entry) +{ + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); auto mods = modulesOf(e); auto exe = findModule(mods, "/" + name); CHECK(exe != nullptr); if (!exe) return false; + ElfInfo elf; CHECK(ReadElfFile(exe->path, elf)); entry = elf.entry - elf.linkBase + exe->base; CHECK(e.AddBreakpoint(entry)); + CHECK(e.Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); return true; +} + +static void t_signal_reasons() +{ + CHECK(StopReasonFromLinuxSignal(SIGSEGV) == SignalSegv); CHECK(StopReasonFromLinuxSignal(SIGFPE) == SignalFpe); + CHECK(StopReasonFromLinuxSignal(SIGBUS) == SignalBus); CHECK(StopReasonFromLinuxSignal(SIGABRT) == SignalAbrt); + CHECK(StopReasonFromLinuxSignal(SIGILL) == IllegalInstruction); CHECK(StopReasonFromLinuxSignal(SIGSYS) == SignalSys); + CHECK(StopReasonFromLinuxSignal(SIGUSR1) == SignalUsr1); CHECK(StopReasonFromLinuxSignal(SIGUSR2) == SignalUsr2); + CHECK(StopReasonFromLinuxSignal(SIGCHLD) == SignalChld); CHECK(StopReasonFromLinuxSignal(SIGTERM) == SignalTerm); + CHECK(StopReasonFromLinuxSignal(SIGKILL) == SignalKill); CHECK(StopReasonFromLinuxSignal(SIGPIPE) == SignalPipe); + CHECK(StopReasonFromLinuxSignal(SIGALRM) == SignalAlrm); CHECK(StopReasonFromLinuxSignal(SIGWINCH) == SignalWinch); + CHECK(StopReasonFromLinuxSignal(0) == UnknownReason); CHECK(StopReasonFromLinuxSignal(64) == UnknownReason); CHECK(StopReasonFromLinuxSignal(-1) == UnknownReason); + for (int s = 1; s < 65; s++) (void)StopReasonFromLinuxSignal(s); +} + +static void t_conf_exitcode() +{ + // test_return_code: some systems give the low byte and others the whole code + struct { const char* arg; int low; } cases[] = {{"-11", 245}, {"-1", 255}, {"-3", 253}, {"0", 0}, {"3", 3}, {"7", 7}, {"123", 123}}; + for (auto& c : cases) + { + Log log; PtraceEngine::Event ev; auto e = startBin(log, "exitcode", {c.arg}); if (!e) return; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); + if (ev.exitCode != c.low) { printf(" exit code for %s: %d, wanted %d\n", c.arg, ev.exitCode, c.low); failures++; } + } +} + +static void t_conf_exceptions() +{ + Log log; PtraceEngine::Event ev; auto e = startBin(log, "do_exception", {"segfault"}); if (!e) return; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); + CHECK(ev.signal == SIGSEGV); CHECK(StopReasonFromLinuxSignal(ev.signal) == SignalSegv); + // going on delivers the signal, which ends the program + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); CHECK(ev.signal == SIGSEGV); + // a division by zero only faults on x86, so the arm64 tests skip it too +} + +static void t_conf_entry_step_exit() +{ + // test_repeated_use, test_step_into, test_breakpoint: stop at the entry point, step three times, and run to the end, ten times over + for (int round = 0; round < 10; round++) + { + Log log; PtraceEngine::Event ev; auto e = startBin(log, "helloworld", {"foobar"}); if (!e) return; uint64_t entry = 0; + if (!entryBreakpoint(*e, log, ev, "helloworld", entry)) return; + CHECK(ev.breakpoint); CHECK(pcOf(*e, ev.tid) == entry); uint32_t tid = ev.tid; + for (int i = 0; i < 3; i++) { CHECK(e->Resume(true, tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.singleStep && !ev.breakpoint); } + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); CHECK(ev.exitCode == 10); // helloworld returns 10 + } +} + +static void t_conf_memory_registers() +{ + Log log; PtraceEngine::Event ev; auto e = startBin(log, "helloworld"); if (!e) return; uint64_t entry = 0; if (!entryBreakpoint(*e, log, ev, "helloworld", entry)) return; + // test_memory_read_write + uint64_t addr = pcOf(*e, ev.tid) + 10; std::vector orig(256), back(256), aa(256, 0xAA), none(16); + CHECK(e->ReadMemory(addr, orig.data(), 256)); CHECK(!e->WriteMemory(0, "heheHAHAherherHARHAR", 20)); CHECK(!e->ReadMemory(0, none.data(), 16)); + CHECK(e->WriteMemory(addr, aa.data(), 256)); CHECK(e->ReadMemory(addr, back.data(), 256)); CHECK(back == aa); + CHECK(e->WriteMemory(addr, orig.data(), 256)); CHECK(e->ReadMemory(addr, back.data(), 256)); CHECK(back == orig); + // test_register_read_write, with the first two argument registers + std::vector regs; CHECK(e->GetRegisterSet(ev.tid, NT_PRSTATUS, regs)); auto saved = regs; uint64_t a = 0xAAAAAAAADEADBEEFull, b = 0xBBBBBBBBCAFEBABEull; + memcpy(regs.data(), &a, 8); memcpy(regs.data() + 8, &b, 8); CHECK(e->SetRegisterSet(ev.tid, NT_PRSTATUS, regs)); + std::vector read; CHECK(e->GetRegisterSet(ev.tid, NT_PRSTATUS, read)); CHECK(le64(read, 0) == a && le64(read, 8) == b); + CHECK(e->SetRegisterSet(ev.tid, NT_PRSTATUS, saved)); CHECK(e->GetRegisterSet(ev.tid, NT_PRSTATUS, read)); CHECK(read == saved); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); +} + +static void t_conf_threads_restart() +{ + // test_thread and test_restart: run, pause, see more than one thread, and start over + for (int round = 0; round < 3; round++) + { + Log log; PtraceEngine::Event ev; auto e = startBin(log, "helloworld_thread"); if (!e) return; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(500ms); + CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(ev.interrupted); CHECK(e->GetThreads().size() > 1); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(500ms); + CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(e->GetThreads().size() > 1); + // a restart while it runs: the target is killed, and a new one is started + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(100ms); CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); + } +} + +static void t_conf_symbols_modules() +{ + // test_load_module_symbols: a module other than the main one has symbols to load + Log log; PtraceEngine::Event ev; auto e = startBin(log, "helloworld"); if (!e) return; uint64_t entry = 0; if (!entryBreakpoint(*e, log, ev, "helloworld", entry)) return; + auto mods = modulesOf(*e); CHECK(mods.size() >= 3); // the program, the C library and the loader + size_t withSymbols = 0; for (auto& m : mods) { if (m.path.find("/helloworld") != std::string::npos) continue; ElfInfo elf; if (ReadElfFile(m.path, elf) && !elf.symbols.empty()) withSymbols++; } + CHECK(withSymbols >= 1); CHECK(e->Kill()); +} + + +// ---- attach + +// Starts a program that is not a child of ours, the way an attach usually finds one +static pid_t spawnDetached(const std::string& mode, std::vector extra = {}) +{ + int fds[2]; if (pipe(fds) != 0) return -1; + pid_t mid = fork(); + if (mid == 0) + { + setsid(); + pid_t grand = fork(); + if (grand == 0) + { + prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY); + int n = open("/dev/null", O_RDWR); dup2(n, 0); dup2(n, 1); dup2(n, 2); + std::vector a = {prog, mode}; a.insert(a.end(), extra.begin(), extra.end()); + std::vector av; for (auto& x : a) av.push_back(x.data()); av.push_back(nullptr); + execv(prog.c_str(), av.data()); _exit(127); + } + [[maybe_unused]] auto w = write(fds[1], &grand, sizeof(grand)); _exit(0); + } + close(fds[1]); + pid_t grand = -1; [[maybe_unused]] auto r = read(fds[0], &grand, sizeof(grand)); close(fds[0]); + waitpid(mid, nullptr, 0); + std::this_thread::sleep_for(100ms); + return grand; +} + +static std::unique_ptr attachTo(Log& log, pid_t pid, std::string* error = nullptr) +{ + auto e = std::make_unique([&log](const PtraceEngine::Event& ev) { log.push(ev); }); + std::string err; + bool ok = e->Attach(pid, err, TestArch()); + if (error) *error = err; + if (!ok) { if (!error) { printf(" attach failed: %s\n", err.c_str()); failures++; } return nullptr; } + return e; +} + +static bool processAlive(pid_t pid) { std::string s = procState(pid); return s != "gone" && s.find("zombie") == std::string::npos; } + +static void t_attach_threads() +{ + pid_t pid = spawnDetached("threads"); CHECK(pid > 0); + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.signal == SIGSTOP); CHECK((pid_t)ev.tid == pid); + CHECK(e->GetPid() == (uint32_t)pid); CHECK(e->GetThreads().size() == 4); CHECK(!e->IsRunning()); + for (uint32_t tid : e->GetThreads()) { std::string st = procState(tid); CHECK(st.find("tracing stop") != std::string::npos); } + std::vector regs; CHECK(e->GetRegisterSet(pid, NT_PRSTATUS, regs)); + // the target keeps running after a resume, and can be stopped again + for (int i = 0; i < 3; i++) + { + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(50ms); + CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.interrupted); + CHECK(e->GetThreads().size() == 4); + } + CHECK(e->Detach()); CHECK(log.wait(PtraceEngine::DetachedEvent, ev)); + std::this_thread::sleep_for(100ms); + CHECK(processAlive(pid)); CHECK(procState(pid).find("tracing stop") == std::string::npos); + kill(pid, SIGKILL); +} + +static void t_attach_breakpoint() +{ + ElfInfo elf; CHECK(ReadElfFile(prog, elf)); uint64_t marker = symbolAddr(elf, "marker"); CHECK(marker != 0); + pid_t pid = spawnDetached("bploop"); CHECK(pid > 0); + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->AddBreakpoint(marker)); + for (int i = 0; i < 5; i++) + { + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(ev.breakpoint); CHECK(pcOf(*e, ev.tid) == marker); + } + // at a breakpoint, the memory that we read is the original one + auto bytes = rawRead(pid, marker, 4); std::vector seen(4); CHECK(e->ReadMemory(marker, seen.data(), 4)); CHECK(bytes != seen); + CHECK(e->RemoveBreakpoint(marker)); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(100ms); CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.interrupted); + CHECK(e->Detach()); CHECK(log.wait(PtraceEngine::DetachedEvent, ev)); + std::this_thread::sleep_for(100ms); CHECK(processAlive(pid)); kill(pid, SIGKILL); +} + +static void t_attach_step_at_breakpoint() +{ + // A breakpoint where the target stopped is stepped over when it is resumed, not hit again right away + ElfInfo elf; CHECK(ReadElfFile(prog, elf)); uint64_t marker = symbolAddr(elf, "marker"); + pid_t pid = spawnDetached("bploop"); + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + uint64_t pc = pcOf(*e, ev.tid); CHECK(pc != 0); + CHECK(e->AddBreakpoint(pc)); + CHECK(e->Resume(true, ev.tid)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(ev.singleStep); CHECK(pcOf(*e, ev.tid) != pc); + (void)marker; + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGKILL); +} + +static void t_attach_exit() +{ + pid_t pid = spawnDetached("sleeper"); + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 6000ms)); CHECK(ev.exitCode == 3); CHECK(ev.signal == 0); + CHECK(!e->Resume(false, 0)); +} + +static void t_attach_kill() +{ + pid_t pid = spawnDetached("threads"); + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(50ms); + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.signal == SIGKILL); + std::this_thread::sleep_for(100ms); CHECK(!processAlive(pid)); +} + +static void t_attach_dtor_detaches() +{ + pid_t pid = spawnDetached("threads"); + { + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(50ms); + } + std::this_thread::sleep_for(100ms); + CHECK(processAlive(pid)); CHECK(procState(pid).find("tracing stop") == std::string::npos); + kill(pid, SIGKILL); +} + +static void t_attach_errors() +{ + Log log; std::string err; + CHECK(!attachTo(log, 999999, &err)); printf(" %s\n", err.c_str()); CHECK(err.find("no such process") != std::string::npos); + + pid_t pid = spawnDetached("threads"); + auto first = attachTo(log, pid); CHECK(first != nullptr); + Log log2; auto second = attachTo(log2, pid, &err); CHECK(!second); printf(" %s\n", err.c_str()); CHECK(err.find("already being traced") != std::string::npos); + // the first is undisturbed + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(first->GetThreads().size() == 4); + first.reset(); std::this_thread::sleep_for(100ms); + CHECK(processAlive(pid)); kill(pid, SIGKILL); +} + +static void t_attach_churn() +{ + // Threads that come and go while the others are being stopped + for (int i = 0; i < 12; i++) + { + pid_t pid = spawnDetached("churnloop"); + std::this_thread::sleep_for(std::chrono::milliseconds(i * 3)); + Log log; std::string err; auto e = attachTo(log, pid, &err); + if (!e) { printf(" attach %d failed: %s\n", i, err.c_str()); failures++; kill(pid, SIGKILL); continue; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + for (uint32_t tid : e->GetThreads()) { if (procState(tid).find("tracing stop") == std::string::npos) { printf(" thread %u is not stopped: %s\n", tid, procState(tid).c_str()); failures++; } } + for (int r = 0; r < 3; r++) + { + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(10ms); + CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + } + CHECK(e->Kill()); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); + } +} + +static void t_attach_syscall() +{ + // A target that is blocked in a system call carries on after it + pid_t pid = spawnDetached("sleeper"); + Log log; auto e = attachTo(log, pid); if (!e) { kill(pid, SIGKILL); return; } + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + auto start = std::chrono::steady_clock::now(); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 6000ms)); CHECK(ev.exitCode == 3); + auto took = std::chrono::steady_clock::now() - start; CHECK(took < 3500ms); +} + +// ---- redirects + +static std::string tmpPath(const std::string& name) { return scratchDirectory() + "/rd_" + std::to_string(getpid()) + "_" + name; } +static std::string slurp(const std::string& path) { std::ifstream f(path); std::stringstream s; s << f.rdbuf(); return s.str(); } +static void spit(const std::string& path, const std::string& text) { std::ofstream f(path); f << text; } + +static std::unique_ptr startRedirected(Log& log, const std::string& mode, std::vector extra, std::vector redirects, const std::string& cwd = "", std::string* error = nullptr) +{ + auto e = std::make_unique([&log](const PtraceEngine::Event& ev) { log.push(ev); }); + PtraceEngine::LaunchOptions o; o.path = prog; o.args = {mode}; o.args.insert(o.args.end(), extra.begin(), extra.end()); o.workingDir = cwd; o.arch = TestArch(); + for (auto& text : redirects) + { + PtraceEngine::FdRedirect r; std::string perr; + if (!ParseFdRedirect(text, r, perr)) { printf(" parse failed: %s\n", perr.c_str()); failures++; return nullptr; } + o.redirects.push_back(r); + } + std::string err; + bool ok = e->Launch(o, err); + if (error) *error = err; + if (!ok) { if (!error) { printf(" launch failed: %s\n", err.c_str()); failures++; } return nullptr; } + return e; +} + +static int runRedirected(Log& log, PtraceEngine& e) +{ + PtraceEngine::Event ev; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e.Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); return ev.exitCode; +} + +static void t_redirect_parse() +{ + using R = PtraceEngine::FdRedirect; + struct Case { const char* text; bool ok; int kind; int fd; int flags; const char* path; int source; }; + Case cases[] = { + {"0out.txt", true, R::OpenFile, 1, O_WRONLY | O_CREAT | O_TRUNC, "out.txt", 0}, + {">out.txt", true, R::OpenFile, 1, O_WRONLY | O_CREAT | O_TRUNC, "out.txt", 0}, + {"2>>log", true, R::OpenFile, 2, O_WRONLY | O_CREAT | O_APPEND, "log", 0}, + {">>log", true, R::OpenFile, 1, O_WRONLY | O_CREAT | O_APPEND, "log", 0}, + {"3<>data.bin", true, R::OpenFile, 3, O_RDWR | O_CREAT, "data.bin", 0}, + {"12> dir/a b ", true, R::OpenFile, 12, O_WRONLY | O_CREAT | O_TRUNC, "dir/a b", 0}, + {"2>&1", true, R::Duplicate, 2, 0, "", 1}, + {"5<&3", true, R::Duplicate, 5, 0, "", 3}, + {">&2", true, R::Duplicate, 1, 0, "", 2}, + {"4>&-", true, R::Close, 4, 0, "", 0}, + {"", false, 0, 0, 0, "", 0}, + {"1", false, 0, 0, 0, "", 0}, + {"a>b", false, 0, 0, 0, "", 0}, + {"1>", false, 0, 0, 0, "", 0}, + {"1> ", false, 0, 0, 0, "", 0}, + {"1>&", false, 0, 0, 0, "", 0}, + {"1>&x", false, 0, 0, 0, "", 0}, + {"1>&2 extra", false, 0, 0, 0, "", 0}, + {"99999999999>x", false, 0, 0, 0, "", 0}, + }; + for (auto& c : cases) + { + R r; std::string err; bool ok = ParseFdRedirect(c.text, r, err); + if (ok != c.ok) { printf(" '%s': parse %s\n", c.text, ok ? "succeeded" : ("failed: " + err).c_str()); failures++; continue; } + if (!ok) { CHECK(!err.empty()); continue; } + if (r.kind != c.kind || r.fd != c.fd || r.flags != c.flags || r.path != c.path || r.source != c.source) { printf(" '%s': wrong result\n", c.text); failures++; } + } +} + +static void t_redirect_stdout() +{ + auto out = tmpPath("out"); unlink(out.c_str()); + Log log; auto e = startRedirected(log, "hello", {}, {"1>" + out}); if (!e) return; + CHECK(runRedirected(log, *e) == 7); + CHECK(slurp(out) == "hello from target\n"); CHECK(log.output.empty()); + unlink(out.c_str()); +} + +static void t_redirect_stdin() +{ + auto in = tmpPath("in"); spit(in, "from a file\n"); + Log log; auto e = startRedirected(log, "cat", {}, {"0<" + in}); if (!e) return; + CHECK(runRedirected(log, *e) == 0); + CHECK(log.output.find("got: from a file") != std::string::npos); + unlink(in.c_str()); +} + +static void t_redirect_stderr_merge() +{ + auto out = tmpPath("both"); unlink(out.c_str()); + Log log; auto e = startRedirected(log, "both", {}, {"1>" + out, "2>&1"}); if (!e) return; + CHECK(runRedirected(log, *e) == 0); + auto text = slurp(out); CHECK(text.find("to stdout") != std::string::npos); CHECK(text.find("to stderr") != std::string::npos); CHECK(log.output.empty()); + unlink(out.c_str()); + + // Only descriptor 2 goes to the file, and 1 stays on the terminal + auto err = tmpPath("err"); unlink(err.c_str()); + Log log2; auto e2 = startRedirected(log2, "both", {}, {"2>" + err}); if (!e2) return; + CHECK(runRedirected(log2, *e2) == 0); + CHECK(slurp(err) == "to stderr\n"); CHECK(log2.output.find("to stdout") != std::string::npos); CHECK(log2.output.find("to stderr") == std::string::npos); + unlink(err.c_str()); + + // The order matters: 2 copies what 1 is at that moment + Log log3; auto e3 = startRedirected(log3, "both", {}, {"2>&1", "1>" + out}); if (!e3) return; + CHECK(runRedirected(log3, *e3) == 0); + CHECK(slurp(out) == "to stdout\n"); CHECK(log3.output.find("to stderr") != std::string::npos); + unlink(out.c_str()); +} + +static void t_redirect_other_fds() +{ + auto in = tmpPath("in6"); spit(in, "six\n"); + auto o5 = tmpPath("o5"), o9 = tmpPath("o9"); unlink(o5.c_str()); unlink(o9.c_str()); + Log log; auto e = startRedirected(log, "fdwrite", {"5", "9", "17"}, {"5>" + o5, "9>" + o9, "17>&9"}); if (!e) return; + CHECK(runRedirected(log, *e) == 0); + CHECK(slurp(o5) == "fd5\n"); CHECK(slurp(o9) == "fd9\nfd17\n"); CHECK(log.output.find("failed") == std::string::npos); + + Log log2; auto e2 = startRedirected(log2, "fdread", {"6"}, {"6<" + in}); if (!e2) return; + CHECK(runRedirected(log2, *e2) == 0); CHECK(log2.output.find("read: six") != std::string::npos); + + // Without a redirect the descriptors are not there, with one they are, and 3 can be closed again + Log log3; auto e3 = startRedirected(log3, "fdopen", {"3", "4", "5", "6"}, {"3>" + o5, "4>" + o5, "4>&-", "5<" + in}); if (!e3) return; + CHECK(runRedirected(log3, *e3) == 0); + CHECK(log3.output.find("fd3=open fd4=closed fd5=open fd6=closed") != std::string::npos); + unlink(in.c_str()); unlink(o5.c_str()); unlink(o9.c_str()); +} + +static void t_redirect_append_readwrite() +{ + auto out = tmpPath("app"); spit(out, "first\n"); + Log log; auto e = startRedirected(log, "hello", {}, {"1>>" + out}); if (!e) return; + CHECK(runRedirected(log, *e) == 7); CHECK(slurp(out) == "first\nhello from target\n"); + + auto rw = tmpPath("rw"); unlink(rw.c_str()); + Log log2; auto e2 = startRedirected(log2, "fdwrite", {"3"}, {"3<>" + rw}); if (!e2) return; + CHECK(runRedirected(log2, *e2) == 0); CHECK(slurp(rw) == "fd3\n"); + unlink(out.c_str()); unlink(rw.c_str()); +} + +static void t_redirect_relative() +{ + auto dir = tmpPath("dir"); mkdir(dir.c_str(), 0777); + Log log; auto e = startRedirected(log, "hello", {}, {"1>rel.txt"}, dir); if (!e) return; + CHECK(runRedirected(log, *e) == 7); CHECK(slurp(dir + "/rel.txt") == "hello from target\n"); + unlink((dir + "/rel.txt").c_str()); rmdir(dir.c_str()); +} + +static void t_redirect_errors() +{ + std::string err; + Log log; auto e = startRedirected(log, "hello", {}, {"0&77"}, "", &err); + CHECK(!e2); printf(" %s\n", err.c_str()); CHECK(!err.empty()); + + // A failure after the redirects were set up is still reported: the pipe that tells about it is out of their way + auto out = tmpPath("high"); + auto bad = std::make_unique([&log](const PtraceEngine::Event& ev) { log.push(ev); }); + PtraceEngine::LaunchOptions o; o.path = "/nonexistent/program"; o.arch = TestArch(); + for (int fd : {3, 4, 10, 11, 12, 13, 20}) { PtraceEngine::FdRedirect r; ParseFdRedirect(std::to_string(fd) + ">" + out, r, err); o.redirects.push_back(r); } + CHECK(!bad->Launch(o, err)); printf(" %s\n", err.c_str()); CHECK(err.find("failed to execute") != std::string::npos); + + // Descriptors that are in the way of the ones we keep for ourselves are all set + Log log3; auto e3 = startRedirected(log3, "fdwrite", {"10", "11", "12", "13", "20"}, {"10>" + out, "11>&10", "12>&10", "13>&10", "20>&10"}); if (!e3) return; + CHECK(runRedirected(log3, *e3) == 0); CHECK(slurp(out) == "fd10\nfd11\nfd12\nfd13\nfd20\n"); + unlink(out.c_str()); + + // Nothing is left open in the debugger + int open = 0; for (int fd = 3; fd < 64; fd++) if (fcntl(fd, F_GETFD) >= 0) open++; + printf(" descriptors open in the debugger: %d\n", open); +} + +static void t_redirect_leaks() +{ + auto out = tmpPath("leak"); unlink(out.c_str()); + auto count = []() { int n = 0; for (int fd = 3; fd < 256; fd++) if (fcntl(fd, F_GETFD) >= 0) n++; return n; }; + int before = count(); + for (int i = 0; i < 20; i++) + { + Log log; auto e = startRedirected(log, "hello", {}, {"1>" + out, "7>" + out}); if (!e) return; + CHECK(runRedirected(log, *e) == 7); + } + // A failed launch too + for (int i = 0; i < 5; i++) { Log log; std::string err; startRedirected(log, "hello", {}, {"1>" + out, "0GetPid()); + CHECK(info.instructionPointer == pcOf(*e, ev.tid)); CHECK(e->GetThreads().size() == 1); + printf(" %s\n", DescribeSyscall(info, true).c_str()); + // and its exit, with the result + if (!syscallStop(*e, log, ev, info, SysMode::Trace, SysInfo::Exit)) return; + CHECK(info.returnValue == (int64_t)self); CHECK(!info.isError); + CHECK(DescribeSyscall(info) == "= " + std::to_string(self)); + // a call that fails + if (!syscallStop(*e, log, ev, info, SysMode::Trace, SysInfo::Entry)) return; + CHECK(info.number == (uint64_t)SYS_close); CHECK(info.args[0] == 9999); + CHECK(DescribeSyscall(info).find("(0x270f, ") != std::string::npos); + if (!syscallStop(*e, log, ev, info, SysMode::Trace, SysInfo::Exit)) return; + CHECK(info.isError); CHECK(info.returnValue == -EBADF); CHECK(DescribeSyscall(info) == "= -9 (Bad file descriptor)"); + // an ordinary resume runs to the end, and the stops that it makes are not system calls + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); CHECK(ev.exitCode == (int)(self & 0xff)); +} + +static void t_syscall_breakpoint() +{ + // The instruction after the system call has not run at its entry, so a breakpoint there is hit and not stepped over + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "syscalls", tid, ev); if (!e) return; + SysInfo info; if (!syscallStop(*e, log, ev, info, SysMode::Trace, SysInfo::Entry)) return; + uint64_t pc = pcOf(*e, ev.tid); CHECK(e->AddBreakpoint(pc)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); + CHECK(ev.breakpoint && !ev.syscall); CHECK(pcOf(*e, ev.tid) == pc); + CHECK(e->Kill()); +} + +static void t_syscall_emulate() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "syscalls", tid, ev); if (!e) return; + SysInfo info; + if (!e->ResumeToSyscall(SysMode::Emulate)) + { + if (!kSysemuMayBeMissing) { printf(" PTRACE_SYSEMU failed\n"); failures++; } + else printf(" SKIP: this kernel has no PTRACE_SYSEMU here\n"); + e->Kill(); return; + } + CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(ev.syscall); + CHECK(e->GetSyscallInfo(ev.tid, info)); CHECK(info.op == SysInfo::Entry); CHECK(info.number == (uint64_t)SYS_getppid); + // the call is not made, and the return value is what the debugger puts in the register + std::vector regs; CHECK(e->GetRegisterSet(ev.tid, NT_PRSTATUS, regs)); + uint64_t answer = 77; memcpy(regs.data() + kRetOff, &answer, 8); CHECK(e->SetRegisterSet(ev.tid, NT_PRSTATUS, regs)); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); CHECK(ev.exitCode == 77); // getppid would have given the pid of this program + + // it works on a target that has other threads too + Log log2; auto e2 = start(log2, "threads"); if (!e2) return; + CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); if (!settleThreads(*e2, log2, ev)) return; CHECK(e2->ResumeToSyscall(SysMode::Emulate)); CHECK(log2.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(ev.syscall); + CHECK(e2->GetThreads().size() == 4); CHECK(e2->Kill()); +} + +static void t_syscall_set_info() +{ + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "syscalls", tid, ev); if (!e) return; + SysInfo info; if (!syscallStop(*e, log, ev, info, SysMode::Trace, SysInfo::Entry)) return; + // the call is changed into getpid, which needs Linux 6.16 + SysInfo changed = info; changed.number = (uint64_t)SYS_getpid; + if (!e->SetSyscallInfo(ev.tid, changed)) { printf(" SKIP: PTRACE_SET_SYSCALL_INFO needs Linux 6.16\n"); e->Kill(); return; } + SysInfo now; CHECK(e->GetSyscallInfo(ev.tid, now)); CHECK(now.number == (uint64_t)SYS_getpid); + // the kind of the stop has to match + SysInfo wrong = info; wrong.op = SysInfo::Exit; CHECK(!e->SetSyscallInfo(ev.tid, wrong)); + if (!syscallStop(*e, log, ev, info, SysMode::Trace, SysInfo::Exit)) return; + CHECK(info.returnValue == (int64_t)e->GetPid()); + CHECK(e->Kill()); +} + +static void t_syscall_threads() +{ + Log log; PtraceEngine::Event ev; auto e = start(log, "threads"); if (!e) return; + CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); if (!settleThreads(*e, log, ev)) return; + for (int i = 0; i < 5; i++) + { + CHECK(e->ResumeToSyscall(SysMode::Trace)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(ev.syscall); + SysInfo info; CHECK(e->GetSyscallInfo(ev.tid, info)); CHECK(info.op != SysInfo::None); + auto threads = e->GetThreads(); CHECK(threads.size() == 4); + for (uint32_t t : threads) if (procState(t).find("tracing stop") == std::string::npos) { printf(" thread %u not stopped: %s\n", t, procState(t).c_str()); failures++; } + } + // back to ordinary running, which stops for an interrupt and for nothing else + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(100ms); CHECK(e->Interrupt()); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); CHECK(ev.interrupted && !ev.syscall); + CHECK(e->Kill()); +} + +static void t_syscall_unsupported() +{ + // an architecture without PTRACE_SYSEMU: it is refused, and the target can still be run + PtraceArch noSysemu = RegisterTable(); noSysemu.sysemu = false; + Log log; auto e = std::make_unique([&log](const PtraceEngine::Event& x) { log.push(x); }); + PtraceEngine::LaunchOptions o; o.path = prog; o.args = {"hello"}; o.arch = &noSysemu; std::string err; PtraceEngine::Event ev; + CHECK(e->Launch(o, err)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + CHECK(!e->ResumeToSyscall(SysMode::Emulate)); CHECK(!e->ResumeToSyscall(SysMode::None)); CHECK(!e->IsRunning()); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev)); CHECK(ev.exitCode == 7); + // there is no syscall info when the thread is not stopped at anything, or is running + Log log2; auto e2 = start(log2, "loop"); if (!e2) return; SysInfo info; + CHECK(log2.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e2->GetSyscallInfo(ev.tid, info)); CHECK(info.op == SysInfo::None); + CHECK(e2->Resume(false, 0)); CHECK(!e2->GetSyscallInfo(ev.tid, info)); CHECK(!e2->GetSyscallInfo(99999, info)); CHECK(e2->Kill()); +} + +static void t_syscall_names() +{ + CHECK(std::string(SyscallName(AuditArchX86_64, 0)) == "read"); CHECK(std::string(SyscallName(AuditArchX86_64, 1)) == "write"); + CHECK(std::string(SyscallName(AuditArchX86_64, 39)) == "getpid"); CHECK(std::string(SyscallName(AuditArchX86_64, 59)) == "execve"); + CHECK(std::string(SyscallName(AuditArchX86_64, 231)) == "exit_group"); CHECK(std::string(SyscallName(AuditArchX86_64, 257)) == "openat"); + CHECK(std::string(SyscallName(AuditArchI386, 1)) == "exit"); CHECK(std::string(SyscallName(AuditArchI386, 4)) == "write"); + CHECK(std::string(SyscallName(AuditArchI386, 11)) == "execve"); CHECK(std::string(SyscallName(AuditArchI386, 20)) == "getpid"); + // 32-bit programs and 64-bit programs number the same call differently + CHECK(std::string(SyscallName(AuditArchI386, 1)) != SyscallName(AuditArchX86_64, 1)); + CHECK(SyscallName(AuditArchX86_64, 100000) == nullptr); CHECK(SyscallName(AuditArchX86_64, ~0ull) == nullptr); CHECK(SyscallName(0xC00000B7, 64) == nullptr); CHECK(SyscallName(0, 0) == nullptr); + for (uint64_t n = 0; n < 470; n++) { auto a = SyscallName(AuditArchX86_64, n); auto b = SyscallName(AuditArchI386, n); if (a) CHECK(*a); if (b) CHECK(*b); } + + SysInfo info; info.op = SysInfo::Entry; info.arch = AuditArchX86_64; info.number = 1; info.args[0] = 1; info.args[1] = 0x7ffc1000; info.args[2] = 5; + CHECK(DescribeSyscall(info) == "write(0x1, 0x7ffc1000, 0x5, 0x0, 0x0, 0x0)"); + info.number = 9999; CHECK(DescribeSyscall(info).rfind("syscall_9999(", 0) == 0); + info.op = SysInfo::Exit; info.returnValue = 5; CHECK(DescribeSyscall(info) == "= 5"); + info.isError = true; info.returnValue = -2; CHECK(DescribeSyscall(info) == "= -2 (No such file or directory)"); + info.op = SysInfo::None; CHECK(DescribeSyscall(info) == "not stopped at a system call"); + info.op = SysInfo::Entry; info.number = 1; info.instructionPointer = 0x401000; info.stackPointer = 0x7ffe0000; + CHECK(DescribeSyscall(info, true) == "system call entry: write(0x1, 0x7ffc1000, 0x5, 0x0, 0x0, 0x0)\npc 0x401000, sp 0x7ffe0000"); + info.op = SysInfo::Seccomp; info.seccompData = 0x1234; CHECK(DescribeSyscall(info).find("(seccomp data 0x1234)") != std::string::npos); +} + + +// ---- registers that are part of others + +static void t_register_aliases() +{ + // what the architecture of the view says about x86_64, as far as the derivation is concerned + using D = PtraceRegisterDescription; + std::vector described = { + {"rax", "rax", 0, 8}, {"eax", "rax", 0, 4}, {"ax", "rax", 0, 2}, {"al", "rax", 0, 1}, {"ah", "rax", 1, 1}, + {"rsi", "rsi", 0, 8}, {"esi", "rsi", 0, 4}, {"si", "rsi", 0, 2}, {"sil", "rsi", 0, 1}, + {"r8", "r8", 0, 8}, {"r8d", "r8", 0, 4}, {"r8w", "r8", 0, 2}, {"r8b", "r8", 0, 1}, + {"xmm0", "ymm0", 0, 16}, // in the table already + {"ymm0", "ymm0", 0, 32}, // not in the table, and not part of one that is + {"ymm0_hi", "ymm0", 16, 16}, {"orphan", "nosuchregister", 0, 4}, {"toolarge", "rax", 6, 4}, {"empty", "rax", 0, 0}, + {"eax", "rax", 0, 4}, // said twice + {"", "rax", 0, 1}, {"rip", "rip", 0, 8}, {"eflags", "eflags", 0, 4}}; + auto derived = DeriveSubRegisters(PtraceArchX86_64(), described); + std::map byName; for (auto& r : derived) byName[r.name] = r; + CHECK(derived.size() == byName.size()); // once each + auto& x64 = PtraceArchX86_64(); auto rax = x64.Find("rax"); auto rsi = x64.Find("rsi"); auto r8 = x64.Find("r8"); CHECK(rax && rsi && r8); + CHECK(byName.count("eax") && byName["eax"].regset == rax->regset && byName["eax"].offset == rax->offset && byName["eax"].size == 4); + CHECK(byName["ax"].offset == rax->offset && byName["ax"].size == 2); CHECK(byName["al"].offset == rax->offset && byName["al"].size == 1); + CHECK(byName["ah"].offset == rax->offset + 1 && byName["ah"].size == 1); + CHECK(byName["esi"].offset == rsi->offset && byName["sil"].size == 1); CHECK(byName["r8d"].offset == r8->offset && byName["r8w"].size == 2 && byName["r8b"].size == 1); + for (const char* left_out : {"rax", "xmm0", "ymm0", "ymm0_hi", "orphan", "toolarge", "empty", "", "rip", "eflags"}) CHECK(!byName.count(left_out)); + CHECK(derived.size() == 10); // 4 of rax, 3 of rsi, 3 of r8 + // a big-endian register has its low part somewhere else + PtraceArch big = x64; big.littleEndian = false; CHECK(DeriveSubRegisters(big, described).empty()); + CHECK(DeriveSubRegisters(x64, {}).empty()); + + // the disagreements that are worth a line in the log + auto messages = CheckRegisterSizes(x64, described); + CHECK(messages.size() == 1); if (!messages.empty()) { printf(" %s\n", messages[0].c_str()); CHECK(messages[0].find("eflags") == 0); } + + // the locations are right in the registers of a real process: for the register that holds the pc, its low half, and the byte above that + const PtraceArch& arch = RegisterTable(); auto pcReg = arch.Find(arch.pc); CHECK(pcReg); + auto pieces = DeriveSubRegisters(arch, {{"pc_low", arch.pc, 0, 4}, {"pc_byte1", arch.pc, 1, 1}, {"pc_high", arch.pc, 4, 4}}); + CHECK(pieces.size() == 3); if (pieces.size() != 3) return; + Log log; auto e = start(log, "hello"); if (!e) return; + PtraceEngine::Event ev; CHECK(log.wait(PtraceEngine::StoppedEvent, ev)); + std::vector regs; CHECK(e->GetRegisterSet(ev.tid, pcReg->regset, regs)); if (regs.size() < pcReg->offset + 8) { failures++; return; } + uint64_t pc = le64(regs, pcReg->offset); CHECK(pc != 0); + uint32_t low = 0, high = 0; memcpy(&low, regs.data() + pieces[0].offset, 4); memcpy(&high, regs.data() + pieces[2].offset, 4); + CHECK(low == (uint32_t)pc); CHECK(high == (uint32_t)(pc >> 32)); CHECK(regs[pieces[1].offset] == (uint8_t)(pc >> 8)); + CHECK(e->Kill()); +} + +// ---- output that the handler is slow to take up + +struct SlowLog +{ + Log log; + std::atomic delivered {0}; + std::atomic events {0}; + std::chrono::milliseconds delay {20ms}; + std::string tail; + std::mutex tailMutex; + void push(const PtraceEngine::Event& e) + { + if (e.type == PtraceEngine::OutputEvent) + { + delivered += e.data.size(); events++; + { std::lock_guard l(tailMutex); tail += e.data; if (tail.size() > 64) tail.erase(0, tail.size() - 64); } + std::this_thread::sleep_for(delay); + } + else log.push(e); + } +}; + +static std::unique_ptr startSlow(SlowLog& s, const std::string& mode) +{ + auto e = std::make_unique([&s](const PtraceEngine::Event& ev) { s.push(ev); }); + PtraceEngine::LaunchOptions o; o.path = prog; o.args = {mode}; o.arch = TestArch(); std::string err; + if (!e->Launch(o, err)) { printf(" launch failed: %s\n", err.c_str()); failures++; return nullptr; } + return e; +} + +static void t_output_backpressure() +{ + // a target that writes as fast as it can, and a handler that takes 20 ms for each piece + SlowLog s; auto e = startSlow(s, "flood"); if (!e) return; + PtraceEngine::Event ev; CHECK(s.log.wait(PtraceEngine::StoppedEvent, ev)); + const size_t limit = 256 * 1024; e->SetOutputLimit(limit); + CHECK(e->Resume(false, 0)); + size_t most = 0; + for (int i = 0; i < 60; i++) { most = std::max(most, e->PendingOutputBytes()); std::this_thread::sleep_for(50ms); } + printf(" the most that was queued: %zu bytes (limit %zu), delivered %zu bytes in %zu events\n", most, limit, s.delivered.load(), s.events.load()); + CHECK(most <= limit + 64 * 1024 + 4096); // what is over the limit is what was read before the limit was seen, and one more piece + CHECK(s.delivered > 0); + // the pieces are joined, so the handler gets fewer and larger ones than the terminal gives + CHECK(s.delivered / std::max(s.events, 1) > 8192); + // a stop is still answered, behind the output that was queued + CHECK(e->Interrupt()); CHECK(s.log.wait(PtraceEngine::StoppedEvent, ev, 10s)); CHECK(ev.interrupted); + CHECK(e->Kill()); CHECK(s.log.wait(PtraceEngine::ExitedEvent, ev, 10s)); +} + +static void t_output_flood_detach() +{ + // letting go of a target that is writing all the time must not wait for it to stop writing + SlowLog s; s.delay = 0ms; auto e = startSlow(s, "flood"); if (!e) return; + PtraceEngine::Event ev; CHECK(s.log.wait(PtraceEngine::StoppedEvent, ev)); uint32_t pid = e->GetPid(); + CHECK(e->Resume(false, 0)); std::this_thread::sleep_for(300ms); + auto start = std::chrono::steady_clock::now(); + CHECK(e->Detach()); + double took = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + printf(" the detach took %.2f s\n", took); CHECK(took < 3.0); + CHECK(s.log.wait(PtraceEngine::DetachedEvent, ev, 5s)); + kill(pid, SIGKILL); int status = 0; CHECK(e->WaitForDetachedExit(status, 5s)); +} + +static void t_output_last_words() +{ + // what the target wrote just before it ended is not lost, however slowly the handler goes, and however much of it there is + for (int round = 0; round < 10; round++) + { + SlowLog s; s.delay = 1ms; auto e = startSlow(s, "lastwords"); if (!e) return; + PtraceEngine::Event ev; CHECK(s.log.wait(PtraceEngine::StoppedEvent, ev)); CHECK(e->Resume(false, 0)); + CHECK(s.log.wait(PtraceEngine::ExitedEvent, ev, 5s)); CHECK(ev.exitCode == 4); + for (int i = 0; i < 100 && s.delivered < 8192 + 9; i++) std::this_thread::sleep_for(10ms); + std::string tail; { std::lock_guard l(s.tailMutex); tail = s.tail; } + // the terminal makes the newline \r\n, which is the 9th byte + if (s.delivered != 8192 + 9 || tail.find("THE END\r\n") == std::string::npos) { printf(" round %d: delivered %zu, tail [%s]\n", round, s.delivered.load(), tail.c_str()); failures++; } + } +} + +// ---- destroying the engine from, or while waiting for, its handler + +static PtraceEngine::LaunchOptions helloOptions() { PtraceEngine::LaunchOptions o; o.path = prog; o.args = {"hello"}; o.arch = TestArch(); return o; } + +static void t_clone_process() +{ + // a clone that is not a thread is a process of its own: the breakpoints come out of its memory like a fork child's, and it is let go + forkTest("cloneproc", 1, 0); +} + +static void t_clone_shared() +{ + // one that shares the memory of the target cannot have its own breakpoints taken out, and the target keeps its own + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "cloneshared", tid, ev); if (!e) return; + uint64_t marker = addrOf(log, "marker="); CHECK(e->AddBreakpoint(marker)); CHECK(e->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 10s)); CHECK(ev.breakpoint && pcOf(*e, ev.tid) == marker); + CHECK((rawRead(e->GetPid(), marker, kBreakInsn.size()) == kBreakInsn)); + bool told = false; for (auto& n : ev.notes) told |= n.find("shares the memory") != std::string::npos; CHECK(told); + CHECK(e->GetThreads().size() == 1); + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 10s)); CHECK(ev.exitCode == 0); +} + +static void t_dtor_from_handler() +{ + // the engine is destroyed by its own handler, on its own event thread, which cannot wait for itself + for (int round = 0; round < 20; round++) + { + struct Shared { std::unique_ptr engine; std::atomic ready {false}, destroyed {false}; }; + auto sh = std::make_shared(); + sh->engine = std::make_unique([sh](const PtraceEngine::Event& ev) { + if (ev.type == PtraceEngine::ExitedEvent && sh->ready) { sh->destroyed = true; sh->engine.reset(); } + }); + std::string err; CHECK(sh->engine->Launch(helloOptions(), err)); if (!err.empty()) return; + sh->ready = true; + CHECK(sh->engine->Resume(false, 0)); // and the engine is not touched again from here + for (int i = 0; i < 500 && !sh->destroyed; i++) std::this_thread::sleep_for(10ms); + CHECK(sh->destroyed); + std::this_thread::sleep_for(50ms); // the thread that was left goes on to its end without the engine + } +} + +static void t_dtor_blocked_handler() +{ + // the handler waits for whoever destroys the engine, as a post to the controller does when the controller is destroying it + struct Blocker { std::atomic entered {false}, release {false}, left {false}; }; + auto sh = std::make_shared(); + auto engine = std::make_unique([sh](const PtraceEngine::Event& ev) { + if (ev.type != PtraceEngine::ExitedEvent) return; + sh->entered = true; + while (!sh->release) std::this_thread::sleep_for(10ms); + sh->left = true; + }); + engine->SetTeardownWait(300ms); + std::string err; CHECK(engine->Launch(helloOptions(), err)); if (!err.empty()) return; + CHECK(engine->Resume(false, 0)); + for (int i = 0; i < 500 && !sh->entered; i++) std::this_thread::sleep_for(10ms); + CHECK(sh->entered); + auto start = std::chrono::steady_clock::now(); + engine.reset(); + double took = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + printf(" the destruction took %.2f s with the handler still waiting\n", took); + CHECK(took < 2.0); CHECK(!sh->left); + sh->release = true; + for (int i = 0; i < 100 && !sh->left; i++) std::this_thread::sleep_for(10ms); + CHECK(sh->left); // it finished on its own + std::this_thread::sleep_for(50ms); +} + +static void t_hw_not_ours() +{ +#if defined(__aarch64__) + // a trap of the debug registers that is not for a slot that is in use is the target's: when the architecture can say which + Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "watch", tid, ev); if (!e) return; + uint64_t wvar = addrOf(log, "wvar="); CHECK(wvar != 0); + if (!e->AddHardwareBreakpoint(wvar, PtraceHwType::Write, 4)) { printf(" SKIP: no hardware watchpoints\n"); e->Kill(); return; } + g_hwTrigger = 0; + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::StoppedEvent, ev, 5s)); + g_hwTrigger = -1; + CHECK(!ev.hardware); CHECK(ev.trapOrigin == PtraceEngine::TrapOrigin::Target); CHECK(ev.signal == SIGTRAP); + // and it is delivered, which the target does not survive + CHECK(e->Resume(false, 0)); CHECK(log.wait(PtraceEngine::ExitedEvent, ev, 5s)); CHECK(ev.signal == SIGTRAP); +#else + printf(" SKIP: the answer of the debug registers cannot be made up on x86, where DR6 has it\n"); +#endif +} + +int main(int argc, char** argv) +{ + struct { const char* n; void (*f)(); } tests[] = { + {"hello", t_hello}, {"step", t_step}, {"interrupt", t_interrupt}, {"threads", t_threads}, {"churn", t_churn}, + {"signal", t_signal}, {"silent", t_silent}, {"detach", t_detach}, {"kill_running", t_kill_running}, + {"dtor_kills", t_dtor_kills}, {"launch_errors", t_launch_errors}, {"args_cwd", t_args_cwd}, {"stdin", t_stdin}, {"stdin_backpressure", t_stdin_backpressure}, + {"nopty", t_nopty}, {"relaunch", t_relaunch}, {"regs_step", t_regs_step}, {"regs_running", t_regs_running}, {"memory", t_memory}, {"bp_basic", t_bp_basic}, {"bp_step_remove", t_bp_step_remove}, {"bp_write", t_bp_write}, {"bp_threads", t_bp_threads}, {"bp_interrupts", t_bp_interrupts}, {"bp_remove_running", t_bp_remove_running}, {"bp_detach", t_bp_detach}, {"hw_watch", t_hw_watch}, {"hw_thread", t_hw_thread}, {"hw_exec", t_hw_exec}, {"hw_detach", t_hw_detach}, {"modules", t_modules}, {"symbols", t_symbols}, {"frames", t_frames}, {"loader", t_loader}, {"library_reload_breakpoint", t_library_reload_breakpoint}, {"library_rebase_breakpoint", t_library_rebase_breakpoint}, {"library_rebase_hardware", t_library_rebase_hardware}, {"processes", t_processes}, {"stepover_basic", t_stepover_basic}, {"stepover_user_breakpoint", t_stepover_user_breakpoint}, {"stepover_interrupt", t_stepover_interrupt}, {"stepover_recursion", t_stepover_recursion}, {"stepreturn_sites", t_stepreturn_sites}, {"stepreturn_address", t_stepreturn_address}, {"stepreturn_recursion", t_stepreturn_recursion}, {"stepover_threads", t_stepover_threads}, {"detach_reaped", t_detach_reaped}, {"fork_child", t_fork_child}, {"vfork", t_vfork}, {"spawn", t_spawn}, {"fork_threads", t_fork_threads}, {"interrupt_burst", t_interrupt_burst}, {"handlers_off", t_handlers_off}, {"handlers_on", t_handlers_on}, {"handlers_toggle", t_handlers_toggle}, {"handlers_thread", t_handlers_thread}, {"sigtrap_raise", t_sigtrap_raise}, {"sigtrap_kill", t_sigtrap_kill}, {"sigtrap_handler_debug", t_sigtrap_handler_debug}, {"sigtrap_instruction", t_sigtrap_instruction}, {"sigtrap_instruction_handler_debug", t_sigtrap_instruction_handler_debug}, {"sigtrap_unhandled", t_sigtrap_unhandled}, {"sigtrap_after_breakpoint", t_sigtrap_after_breakpoint}, {"sigtrap_while_stepping", t_sigtrap_while_stepping}, {"signal_reasons", t_signal_reasons}, {"conf_exitcode", t_conf_exitcode}, {"conf_exceptions", t_conf_exceptions}, {"conf_entry_step_exit", t_conf_entry_step_exit}, {"conf_memory_registers", t_conf_memory_registers}, {"conf_threads_restart", t_conf_threads_restart}, {"conf_symbols_modules", t_conf_symbols_modules}, {"elf_names", t_elf_names}, {"exec_by_name", t_exec_by_name}, {"exec_basic", t_exec_basic}, {"exec_rebreak", t_exec_rebreak}, {"exec_thread", t_exec_thread}, {"exec_continue", t_exec_continue}, {"winsize", t_winsize}, {"attach_threads", t_attach_threads}, {"attach_breakpoint", t_attach_breakpoint}, {"attach_step_at_breakpoint", t_attach_step_at_breakpoint}, {"attach_exit", t_attach_exit}, {"attach_kill", t_attach_kill}, {"attach_dtor_detaches", t_attach_dtor_detaches}, {"attach_errors", t_attach_errors}, {"attach_churn", t_attach_churn}, {"attach_syscall", t_attach_syscall}, {"redirect_parse", t_redirect_parse}, {"redirect_stdout", t_redirect_stdout}, {"redirect_stdin", t_redirect_stdin}, {"redirect_stderr_merge", t_redirect_stderr_merge}, {"redirect_other_fds", t_redirect_other_fds}, {"redirect_append_readwrite", t_redirect_append_readwrite}, {"redirect_relative", t_redirect_relative}, {"redirect_errors", t_redirect_errors}, {"redirect_leaks", t_redirect_leaks}, {"syscall_trace", t_syscall_trace}, {"syscall_breakpoint", t_syscall_breakpoint}, {"syscall_emulate", t_syscall_emulate}, {"syscall_set_info", t_syscall_set_info}, {"syscall_threads", t_syscall_threads}, {"syscall_unsupported", t_syscall_unsupported}, {"syscall_names", t_syscall_names}, {"register_aliases", t_register_aliases}, {"output_backpressure", t_output_backpressure}, {"output_flood_detach", t_output_flood_detach}, {"output_last_words", t_output_last_words}, {"hw_not_ours", t_hw_not_ours}, {"clone_process", t_clone_process}, {"clone_shared", t_clone_shared}, {"dtor_from_handler", t_dtor_from_handler}, {"dtor_blocked_handler", t_dtor_blocked_handler}}; + if (argc > 2) + { + fprintf(stderr, "usage: %s [--list|test-name]\n", argv[0]); + return 2; + } + if (argc == 2 && strcmp(argv[1], "--list") == 0) + { + for (const auto& test : tests) + printf("%s\n", test.n); + return 0; + } + bool matched = false; + for (auto& t : tests) + { + if (argc > 1 && strcmp(argv[1], t.n)) continue; + matched = true; + int before = failures; printf("[%s]\n", t.n); fflush(stdout); + t.f(); + printf(" %s\n", failures == before ? "ok" : "FAILED"); fflush(stdout); + } + if (!matched) + { + fprintf(stderr, "Unknown test: %s\n", argv[1]); + return 2; + } + printf("%d failure(s)\n", failures); + return failures != 0; +} diff --git a/test/ptrace_engine/elfcmp.cpp b/test/ptrace_engine/elfcmp.cpp new file mode 100644 index 00000000..f8bd9ef7 --- /dev/null +++ b/test/ptrace_engine/elfcmp.cpp @@ -0,0 +1,8 @@ +#include "ptraceelf.h" +#include +#include +#include +using namespace BinaryNinjaDebugger; +int main(int c, char** v){ ElfInfo i; if (!ReadElfFile(v[1], i)) { printf("read failed\n"); return 1; } + std::set> s; for (auto& x : i.symbols) s.insert({x.name, (unsigned long long)x.address, (unsigned long long)x.size, (int)x.isFunction}); + for (auto& t : s) printf("%s %llx %llu %d\n", std::get<0>(t).c_str(), std::get<1>(t), std::get<2>(t), std::get<3>(t)); } diff --git a/test/ptrace_engine/libtest.c b/test/ptrace_engine/libtest.c new file mode 100644 index 00000000..45b0d0be --- /dev/null +++ b/test/ptrace_engine/libtest.c @@ -0,0 +1,2 @@ +#include +void libfunc(void) { puts("in libfunc"); } diff --git a/test/ptrace_engine/progs.c b/test/ptrace_engine/progs.c new file mode 100644 index 00000000..0bab4158 --- /dev/null +++ b/test/ptrace_engine/progs.c @@ -0,0 +1,143 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +extern char** environ; +#include +#ifdef PAD +__attribute__((noinline)) int pad1(int a) { volatile int x = a; for (int i = 0; i < 3; i++) x += i * a; return x; } +__attribute__((noinline)) int pad2(int a) { return pad1(a) + pad1(a + 1) + pad1(a + 2); } +#endif +static int counter; +__attribute__((noinline)) void level3(void) { void* p = &&here; printf("label=%p\n", p); raise(SIGUSR1); here: asm volatile("nop"); counter++; } +__attribute__((noinline)) void level2(void) { level3(); counter++; } +__attribute__((noinline)) void level1(void) { level2(); counter++; } +__attribute__((noinline)) void marker(void) { __sync_fetch_and_add(&counter, 1); } +static volatile int wvar; +__attribute__((noinline)) void callee(void) { volatile int x = 0; for (int i = 0; i < 3; i++) x += i; marker(); } +__attribute__((noinline)) void slowcallee(void) { for (int i = 0; i < 100; i++) usleep(10000); marker(); } +__attribute__((noinline)) void caller(int slow) { void* p = &&here; printf("here=%p\n", p); raise(SIGUSR1); here: asm volatile("nop"); if (slow) slowcallee(); else callee(); counter += 10; } +__attribute__((noinline)) int recurse(int n) { if (n == 0) return 0; if (n == 3) { void* p = &&site; printf("site=%p\n", p); raise(SIGUSR1); site: asm volatile("nop"); } int r = recurse(n - 1); counter++; return r + 1; } +__attribute__((noinline)) void inner(void) { void* p = &&there; printf("there=%p\n", p); raise(SIGUSR1); there: asm volatile("nop"); counter++; } +__attribute__((noinline)) void outer(void) { inner(); counter += 100; } +__attribute__((noinline)) void work_item(void) { __sync_fetch_and_add(&counter, 1); } +static void* stepWorker(void* a) { for (int i = 0; i < 300; i++) { if (a == (void*)0 && i == 5) { void* p = &&sync; printf("sync=%p\n", p); raise(SIGUSR1); sync: asm volatile("nop"); } work_item(); usleep(100); } return 0; } +static volatile int handled; +__attribute__((noinline)) void sigHandler(int s) { handled++; } +__attribute__((noinline)) void infoHandler(int s, siginfo_t* i, void* c) { handled += 10; } +__attribute__((noinline)) void trapHandler(int s, siginfo_t* i, void* context) +{ + handled++; +#if defined(__aarch64__) + // AArch64 reports BRK at the trapping instruction, so returning without advancing would execute it forever. Signals + // sent with raise/tgkill have a non-positive si_code and already have the correct return PC. + if (i && i->si_code > 0) + ((ucontext_t*)context)->uc_mcontext.pc += 4; +#endif +} +__attribute__((noinline)) void raiseTrap(void) { raise(SIGTRAP); } +extern char before_trap_instruction[]; +extern char target_trap_instruction[]; +__attribute__((noinline)) void instructionTrap(void) +{ +#if defined(__x86_64__) + asm volatile(".global before_trap_instruction\n before_trap_instruction:\n nop\n" + ".global target_trap_instruction\n target_trap_instruction:\n int3"); +#elif defined(__aarch64__) + asm volatile(".global before_trap_instruction\n before_trap_instruction:\n nop\n" + ".global target_trap_instruction\n target_trap_instruction:\n brk #0"); +#endif +} +static void* handlerWaiter(void* a) { while (!handled) usleep(1000); return 0; } +static int bad; +static void* execWorker(void* a) { usleep(100000); execl(PTRACE_TEST_DIRECTORY "/progs", "progs", "hello", (char*)0); return 0; } +static void* forker(void* a) { for (int i = 0; i < 20; i++) { pid_t c = fork(); if (c == 0) { marker(); _exit(0); } int st = 0; waitpid(c, &st, 0); if (WIFSIGNALED(st)) __sync_fetch_and_add(&bad, 1); marker(); } return 0; } +static void* markerThread(void* a) { for (int i = 0; i < 3; i++) { marker(); usleep(2000); } return 0; } +// Threads that never stop running into a breakpoint, so that the debugger has to stop them all over and over +static void* markerSpinner(void* a) { while (1) { marker(); usleep(200); } return 0; } +// The thread group leader leaves while this one is still running, so the group lives on without it +static void* outliveLeader(void* a) { for (int i = 0; i < 40; i++) { marker(); usleep(25000); } printf("worker done\n"); _exit(7); return 0; } +static void* writer(void* a) { usleep(20000); wvar = 7; return 0; } +static int cloneChild(void* a) { return 0; } +static void* spin(void* a) { volatile unsigned long x = 0; while (1) x++; return 0; } +static void* shortlived(void* a) { usleep(1000); return 0; } +static int libraryRange(uintptr_t* first, uintptr_t* last) { FILE* f = fopen("/proc/self/maps", "r"); char line[512]; *first = UINTPTR_MAX; *last = 0; if (!f) return 0; while (fgets(line, sizeof(line), f)) { unsigned long a, b; if (strstr(line, PTRACE_TEST_DIRECTORY "/libtest.so") && sscanf(line, "%lx-%lx", &a, &b) == 2) { if (a < *first) *first = a; if (b > *last) *last = b; } } fclose(f); return *last > *first; } +int main(int argc, char** argv) +{ + const char* mode = argc > 1 ? argv[1] : "hello"; + setvbuf(stdout, NULL, _IONBF, 0); + if (!strcmp(mode, "hello")) { printf("hello from target\n"); return 7; } + if (!strcmp(mode, "loop")) { volatile unsigned long x = 0; while (1) x++; } + if (!strcmp(mode, "threads")) { pthread_t t[3]; for (int i = 0; i < 3; i++) pthread_create(&t[i], 0, spin, 0); while (1) usleep(1000); } + if (!strcmp(mode, "markerthreads")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pthread_t t[4]; for (int i = 0; i < 4; i++) pthread_create(&t[i], 0, markerSpinner, 0); for (int i = 0; i < 4; i++) pthread_join(t[i], 0); return 0; } + if (!strcmp(mode, "leaderexit")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); pthread_t t; pthread_create(&t, 0, outliveLeader, 0); raise(SIGUSR1); pthread_exit(0); } + if (!strcmp(mode, "churn")) { for (int i = 0; i < 50; i++) { pthread_t t; pthread_create(&t, 0, shortlived, 0); pthread_join(t, 0); } printf("churn done\n"); return 0; } + if (!strcmp(mode, "churnloop")) { while (1) { pthread_t t; pthread_create(&t, 0, shortlived, 0); pthread_join(t, 0); } } + if (!strcmp(mode, "sig")) { printf("raising\n"); raise(SIGUSR1); printf("survived\n"); return 0; } + if (!strcmp(mode, "sigchld")) { signal(SIGUSR2, SIG_IGN); if (fork() == 0) _exit(0); sleep(1); printf("after child\n"); return 5; } + if (!strcmp(mode, "sleeper")) { sleep(2); printf("done sleeping\n"); return 3; } + if (!strcmp(mode, "args")) { char c[256]; getcwd(c, 256); printf("cwd=%s argc=%d", c, argc); for (int i = 2; i < argc; i++) printf(" [%s]", argv[i]); printf("\n"); return 0; } + if (!strcmp(mode, "cat")) { char b[256]; if (fgets(b, 256, stdin)) printf("got: %s", b); return 0; } + if (!strcmp(mode, "mem")) { static char buf[32] = "hello memory"; signal(SIGUSR1, SIG_IGN); printf("buf=%p main=%p\n", (void*)buf, (void*)main); raise(SIGUSR1); printf("%s\n", buf); return 0; } + if (!strcmp(mode, "bp")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); for (int i = 0; i < 5; i++) marker(); return counter; } + if (!strcmp(mode, "bpthreads")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pthread_t t[4]; for (int i = 0; i < 4; i++) pthread_create(&t[i], 0, markerThread, 0); for (int i = 0; i < 4; i++) pthread_join(t[i], 0); return counter; } + if (!strcmp(mode, "bploop")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); while (1) marker(); } + if (!strcmp(mode, "detachbp")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); sleep(1); marker(); return counter; } + if (!strcmp(mode, "watch")) { signal(SIGUSR1, SIG_IGN); printf("wvar=%p\n", (void*)&wvar); raise(SIGUSR1); for (int i = 0; i < 3; i++) { wvar = i + 1; usleep(1000); } return wvar; } + if (!strcmp(mode, "watchthread")) { signal(SIGUSR1, SIG_IGN); printf("wvar=%p\n", (void*)&wvar); raise(SIGUSR1); pthread_t t; pthread_create(&t, 0, writer, 0); pthread_join(t, 0); return wvar; } + if (!strcmp(mode, "frames")) { signal(SIGUSR1, SIG_IGN); level1(); return counter; } + if (!strcmp(mode, "syms")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p puts=%p\n", (void*)marker, dlsym(RTLD_DEFAULT, "puts")); raise(SIGUSR1); return 0; } + if (!strcmp(mode, "dl")) { signal(SIGUSR1, SIG_IGN); printf("ready\n"); raise(SIGUSR1); void* h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); printf("loaded=%p\n", h); void (*f)(void) = (void (*)(void))dlsym(h, "libfunc"); printf("libfunc=%p\n", (void*)f); raise(SIGUSR1); f(); return 0; } + if (!strcmp(mode, "dlcycle")) { signal(SIGUSR1, SIG_IGN); for (int i = 1; i <= 2; i++) { void* h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); void (*f)(void) = (void (*)(void))dlsym(h, "libfunc"); printf("cycle%d=%p\n", i, (void*)f); raise(SIGUSR1); f(); dlclose(h); } return 0; } + if (!strcmp(mode, "dlrebase")) { signal(SIGUSR1, SIG_IGN); void* h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); void (*f)(void) = (void (*)(void))dlsym(h, "libfunc"); uintptr_t lo, hi; int range = libraryRange(&lo, &hi); printf("cycle1=%p\n", (void*)f); raise(SIGUSR1); f(); dlclose(h); void* held = range ? mmap((void*)lo, hi - lo, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0) : MAP_FAILED; h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); f = (void (*)(void))dlsym(h, "libfunc"); printf("reserved=%p cycle2=%p\n", held, (void*)f); raise(SIGUSR1); f(); dlclose(h); return held == MAP_FAILED; } + if (!strcmp(mode, "stepover")) { signal(SIGUSR1, SIG_IGN); caller(0); return counter; } + if (!strcmp(mode, "stepslow")) { signal(SIGUSR1, SIG_IGN); caller(1); return counter; } + if (!strcmp(mode, "recurse")) { signal(SIGUSR1, SIG_IGN); recurse(3); return counter; } + if (!strcmp(mode, "stepret")) { signal(SIGUSR1, SIG_IGN); outer(); return counter; } + if (!strcmp(mode, "stepthreads")) { signal(SIGUSR1, SIG_IGN); pthread_t t[3]; for (long i = 0; i < 3; i++) pthread_create(&t[i], 0, stepWorker, (void*)i); for (int i = 0; i < 3; i++) pthread_join(t[i], 0); return counter > 255 ? 255 : counter; } + if (!strcmp(mode, "forkbp")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pid_t c = fork(); if (c == 0) { marker(); _exit(0); } int st = 0; waitpid(c, &st, 0); return WIFSIGNALED(st) ? 100 + WTERMSIG(st) : WEXITSTATUS(st); } + if (!strcmp(mode, "execer")) { signal(SIGUSR1, SIG_IGN); raise(SIGUSR1); execl(PTRACE_TEST_DIRECTORY "/progs", "progs", "hello", (char*)0); return 99; } + if (!strcmp(mode, "winsize")) { struct winsize w = {0}; int r = ioctl(0, TIOCGWINSZ, &w); printf("tty=%d ioctl=%d rows=%d cols=%d\n", isatty(0), r, w.ws_row, w.ws_col); return 0; } + if (!strcmp(mode, "forkbp2")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pid_t c = fork(); if (c == 0) { marker(); _exit(0); } int st = 0; waitpid(c, &st, 0); marker(); return WIFSIGNALED(st) ? 100 + WTERMSIG(st) : WEXITSTATUS(st); } + if (!strcmp(mode, "vforkbp")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pid_t c = vfork(); if (c == 0) { marker(); _exit(0); } int st = 0; waitpid(c, &st, 0); marker(); return WIFSIGNALED(st) ? 100 + WTERMSIG(st) : WEXITSTATUS(st); } + if (!strcmp(mode, "spawnbp")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pid_t c; char* av[] = {"progs", "hello", 0}; posix_spawn(&c, PTRACE_TEST_DIRECTORY "/progs", 0, 0, av, environ); int st = 0; waitpid(c, &st, 0); marker(); return WIFSIGNALED(st) ? 100 + WTERMSIG(st) : WEXITSTATUS(st); } + if (!strcmp(mode, "forkthreads")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pthread_t t[3]; for (int i = 0; i < 3; i++) pthread_create(&t[i], 0, forker, 0); for (int i = 0; i < 3; i++) pthread_join(t[i], 0); return bad; } + if (!strcmp(mode, "execbp")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); execl(PTRACE_TEST_DIRECTORY "/progs", "progs", "bp", (char*)0); return 99; } + if (!strcmp(mode, "execloop")) { signal(SIGUSR1, SIG_IGN); raise(SIGUSR1); execl(PTRACE_TEST_DIRECTORY "/progs", "progs", "loop", (char*)0); return 99; } + if (!strcmp(mode, "execthread")) { signal(SIGUSR1, SIG_IGN); pthread_t t; pthread_create(&t, 0, execWorker, 0); raise(SIGUSR1); pthread_join(t, 0); return 99; } + if (!strcmp(mode, "sighandler")) { signal(SIGUSR1, SIG_IGN); struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_sigaction = infoHandler; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigaction(SIGUSR2, &sa, 0); signal(SIGWINCH, sigHandler); printf("info=%p handler=%p\n", (void*)infoHandler, (void*)sigHandler); raise(SIGUSR1); raise(SIGUSR2); raise(SIGWINCH); raise(SIGCHLD); return handled; } + if (!strcmp(mode, "sigthread")) { signal(SIGUSR1, SIG_IGN); signal(SIGWINCH, sigHandler); printf("handler=%p\n", (void*)sigHandler); pthread_t t; pthread_create(&t, 0, handlerWaiter, 0); raise(SIGUSR1); usleep(50000); pthread_kill(t, SIGWINCH); pthread_join(t, 0); return handled; } + if (!strcmp(mode, "sigtrap_raise")) { signal(SIGUSR1, SIG_IGN); struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_sigaction = trapHandler; sa.sa_flags = SA_SIGINFO; sigaction(SIGTRAP, &sa, 0); printf("raiser=%p handler=%p\n", (void*)raiseTrap, (void*)trapHandler); raise(SIGUSR1); raiseTrap(); return handled; } + if (!strcmp(mode, "sigtrap_kill")) { signal(SIGUSR1, SIG_IGN); struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_sigaction = trapHandler; sa.sa_flags = SA_SIGINFO; sigaction(SIGTRAP, &sa, 0); raise(SIGUSR1); kill(getpid(), SIGTRAP); return handled; } + if (!strcmp(mode, "sigtrap_instruction")) { signal(SIGUSR1, SIG_IGN); struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_sigaction = trapHandler; sa.sa_flags = SA_SIGINFO; sigaction(SIGTRAP, &sa, 0); printf("before=%p trap=%p handler=%p\n", (void*)before_trap_instruction, (void*)target_trap_instruction, (void*)trapHandler); raise(SIGUSR1); instructionTrap(); return handled; } + if (!strcmp(mode, "sigtrap_unhandled")) { signal(SIGUSR1, SIG_IGN); raise(SIGUSR1); raise(SIGTRAP); return 99; } + if (!strcmp(mode, "execpad")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); execl(PTRACE_TEST_DIRECTORY "/progs_pad", "progs_pad", "bp", (char*)0); return 99; } + if (!strcmp(mode, "abort")) { abort(); } + // A clone that is not a thread. Its exit signal is not SIGCHLD, so the kernel reports it as a clone and not as a fork. SIGURG + // is one that the engine does not stop for. + if (!strcmp(mode, "cloneproc")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pid_t c = syscall(SYS_clone, SIGURG, 0, 0, 0, 0); if (c == 0) { marker(); _exit(0); } int st = 0; waitpid(c, &st, __WALL); marker(); return WIFSIGNALED(st) ? 100 + WTERMSIG(st) : WEXITSTATUS(st); } + if (!strcmp(mode, "cloneshared")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); char* stack = malloc(65536); pid_t c = clone(cloneChild, stack + 65536, SIGURG | CLONE_VM, 0); int st = 0; waitpid(c, &st, __WALL); marker(); return WIFSIGNALED(st) ? 100 + WTERMSIG(st) : WEXITSTATUS(st); } + if (!strcmp(mode, "flood")) { char b[4096]; memset(b, 'x', sizeof b); while (1) if (write(1, b, sizeof b) < 0) break; return 0; } + if (!strcmp(mode, "lastwords")) { char b[8192]; memset(b, 'y', sizeof b); write(1, b, sizeof b); write(1, "THE END\n", 8); return 4; } + // Raw system calls only, so that the first ones after the SIGUSR1 stop are the two that the tests look for + if (!strcmp(mode, "syscalls")) { signal(SIGUSR1, SIG_IGN); long p = getpid(), t = syscall(SYS_gettid); syscall(SYS_tgkill, p, t, SIGUSR1); long r = syscall(SYS_getppid); syscall(SYS_close, 9999); return (int)(r & 0xff); } + if (!strcmp(mode, "fdwrite")) { for (int i = 2; i < argc; i++) { int fd = atoi(argv[i]); char b[32]; int n = snprintf(b, 32, "fd%d\n", fd); if (write(fd, b, n) != n) printf("write to %d failed\n", fd); } return 0; } + if (!strcmp(mode, "fdread")) { char b[64]; ssize_t n = read(atoi(argv[2]), b, 63); if (n < 0) n = 0; b[n] = 0; printf("read: %s", b); return 0; } + if (!strcmp(mode, "fdopen")) { for (int i = 2; i < argc; i++) { int fd = atoi(argv[i]); printf("fd%d=%s ", fd, fcntl(fd, F_GETFD) >= 0 ? "open" : "closed"); } printf("\n"); return 0; } + if (!strcmp(mode, "both")) { printf("to stdout\n"); fprintf(stderr, "to stderr\n"); return 0; } + return 99; +} diff --git a/test/ptrace_engine_test.py b/test/ptrace_engine_test.py new file mode 100644 index 00000000..8b6a1603 --- /dev/null +++ b/test/ptrace_engine_test.py @@ -0,0 +1,309 @@ +"""Run the standalone C++ ptrace scenarios through the debugger's pytest runner. + +CMake builds the fixtures. Each case runs in a separate supervised process, so a +native hang, signal-handler change or crash cannot take down the rest of pytest. +This module also serves as that supervisor; it does not load Binary Ninja. +""" + +import ctypes +import json +import os +from pathlib import Path +import re +import shutil +import signal +import struct +import subprocess +import sys +import tempfile +import time + + +def _children(pid): + """Include children forked by any thread, and children in new sessions.""" + result = set() + for task in Path(f'/proc/{pid}/task').glob('*/children'): + try: + result.update(int(child) for child in task.read_text().split()) + except FileNotFoundError: + pass + return result + + +def _descendants(pid): + found = set() + pending = [pid] + while pending: + for child in _children(pending.pop()) - found: + found.add(child) + pending.append(child) + return found + + +def _kill(pids): + for pid in pids: + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def _worker(timeout, command): + import resource + + # Inferiors can create sessions or become detached. A subreaper adopts those + # orphans so even a crashing driver cannot leave them behind or leave zombies. + libc = ctypes.CDLL(None, use_errno=True) + if libc.prctl(36, 1, 0, 0, 0) != 0: # PR_SET_CHILD_SUBREAPER + raise OSError(ctypes.get_errno(), 'PR_SET_CHILD_SUBREAPER failed') + resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) + timed_out = False + with tempfile.TemporaryFile() as output: + proc = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT) + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + timed_out = True + finally: + _kill(_descendants(os.getpid())) + proc.wait(timeout=5) + deadline = time.monotonic() + 5 + while True: + _kill(_descendants(os.getpid())) + try: + while os.waitpid(-1, os.WNOHANG)[0]: + pass + except ChildProcessError: + break + if time.monotonic() >= deadline: + raise RuntimeError('Could not reap all ptrace test descendants') + time.sleep(0.01) + output.seek(0) + return {'returncode': proc.returncode, 'timed_out': timed_out, + 'output': output.read().decode('utf-8', errors='replace')} + + +if __name__ == '__main__': + print(json.dumps(_worker(float(sys.argv[1]), sys.argv[2:]))) + sys.exit(0) + + +import pytest + +pytestmark = pytest.mark.skipif(sys.platform != 'linux', reason='ptrace requires Linux') +ROOT = Path(__file__).resolve().parent.parent +SOURCES = ROOT / 'test' / 'ptrace_engine' +SANITIZER_ERROR = re.compile(r'ERROR: (?:AddressSanitizer|LeakSanitizer)|WARNING: ThreadSanitizer|runtime error:') + + +def _case_names(driver): + source = (SOURCES / f'{driver}.cpp').read_text().split('int main(', 1)[1] + names = re.findall(r'\{"([a-z0-9_]+)",\s*\w+\}', source) + if not names: + raise ValueError(f'No scenarios found in {driver}.cpp') + return names + + +CASES = [('driver', name) for name in _case_names('driver')] + + +def _run(command, directory, timeout=120, env=None): + worker = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), str(timeout), *map(str, command)], + cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + start_new_session=True) + try: + output, _ = worker.communicate(timeout=timeout + 15) + except subprocess.TimeoutExpired: + os.killpg(worker.pid, signal.SIGKILL) + output, _ = worker.communicate(timeout=5) + pytest.fail(f'Test supervisor exceeded its deadline: {command}\n{output.decode(errors="replace")}') + finally: + try: + os.killpg(worker.pid, signal.SIGKILL) + except ProcessLookupError: + pass + worker.wait(timeout=5) + assert worker.returncode == 0, output.decode(errors='replace') + result = json.loads(output) + assert not result['timed_out'], f'Native test exceeded {timeout}s: {command}\n{result["output"]}' + return result + + +@pytest.fixture(scope='module') +def native(): + directory = Path(os.environ.get('PTRACE_TEST_BUILD_DIR', ROOT / 'build' / 'test' / 'ptrace_engine')).resolve() + config_file = directory / 'ptrace_test_config.json' + if not config_file.is_file(): + message = f'Build ptrace_tests and set PTRACE_TEST_BUILD_DIR to its output directory: {directory}' + if 'PTRACE_TEST_BUILD_DIR' in os.environ: + pytest.fail(message) + pytest.skip(message) + config = json.loads(config_file.read_text()) + for name in ('driver', 'elfcmp', 'progs', 'progs_pad', 'libtest.so'): + assert (directory / name).is_file(), f'Missing built ptrace fixture: {directory / name}' + env = os.environ.copy() + env['LC_ALL'] = 'C' + # A caller can still provide runtime-specific options; diagnostics below also + # catch recoverable sanitizer reports whose process happened to exit zero. + env.setdefault('ASAN_OPTIONS', 'detect_leaks=1:halt_on_error=1') + env.setdefault('UBSAN_OPTIONS', 'halt_on_error=1:print_stacktrace=1') + env.setdefault('TSAN_OPTIONS', 'halt_on_error=1:report_signal_unsafe=0:second_deadlock_stack=1') + env['PTRACE_TEST_DIR'] = str(directory) + prefix = [] + if cpus := env.get('PTRACE_TEST_CPUS'): + selected = {int(cpu) for cpu in cpus.split(',')} + assert selected and selected <= os.sched_getaffinity(0), f'Unavailable CPUs: {cpus}' + taskset = shutil.which('taskset') + assert taskset, 'PTRACE_TEST_CPUS requires taskset' + prefix = [taskset, '--cpu-list', cpus] + timeout = float(env.get('PTRACE_TEST_TIMEOUT', '120')) + repeat = int(env.get('PTRACE_TEST_REPEAT', '1')) + assert timeout > 0 and repeat > 0, 'PTRACE_TEST_TIMEOUT and PTRACE_TEST_REPEAT must be positive' + + def run(program, *arguments): + return _run([*prefix, directory / program, *arguments], directory, timeout, env) + + return directory, config, repeat, run + + +def _assert_success(result): + assert result['returncode'] == 0, result['output'] + assert not SANITIZER_ERROR.search(result['output']), result['output'] + # The C++ harness prints skips for unavailable kernel/architecture features. + # Do not turn a failing test into a skip just because it also printed SKIP. + if re.search(r'^\s*SKIP\b', result['output'], re.MULTILINE): + pytest.skip(result['output']) + + +@pytest.mark.parametrize('driver,name', CASES, ids=[f'{driver}-{name}' for driver, name in CASES]) +def test_native_scenario(native, driver, name): + _, _, repeat, run = native + for iteration in range(repeat): + result = run(driver, name) + print(f'{driver}/{name} iteration {iteration + 1}/{repeat}\n{result["output"]}', end='') + _assert_success(result) + + +def test_driver_selection(native): + driver = 'driver' + *_, run = native + result = run(driver, '--list') + _assert_success(result) + assert result['output'].splitlines() == _case_names(driver) + result = run(driver, 'not-a-real-test') + assert result['returncode'] == 2, result['output'] + assert 'Unknown test:' in result['output'] + + +@pytest.mark.parametrize('name', ['progs', 'progs_pad', 'libtest.so', + 'Linux-x86/helloworld', 'Linux-x86_64/helloworld']) +def test_elf_symbols(native, name): + directory, _, _, run = native + binary = ROOT / 'test' / 'binaries' / name if name.startswith('Linux-') else directory / name + _compare_elf_symbols(binary, run) + + +def _compare_elf_symbols(binary, run): + readelf = shutil.which('readelf') + assert readelf, 'ELF comparison requires binutils/readelf' + result = run('elfcmp', str(binary)) + _assert_success(result) + actual = set() + for line in result['output'].splitlines(): + symbol, address, size, function = line.split() + actual.add((symbol, int(address, 16), int(size), int(function))) + reference = subprocess.run([readelf, '-sW', str(binary)], check=True, + capture_output=True, text=True, timeout=10, env={**os.environ, 'LC_ALL': 'C'}) + expected = set() + for line in reference.stdout.splitlines(): + fields = line.split() + if len(fields) < 8 or not re.fullmatch(r'\d+:', fields[0]): + continue + _, address, size, kind, _, _, section, symbol = fields[:8] + if kind not in ('FUNC', 'OBJECT', 'IFUNC') or section in ('UND', 'ABS', 'COM') or int(address, 16) == 0: + continue + expected.add((symbol.split('@', 1)[0], int(address, 16), int(size, 0), int(kind != 'OBJECT'))) + assert actual == expected, f'Only in engine: {actual - expected}\nOnly in readelf: {expected - actual}' + + +@pytest.mark.parametrize('damage', ['not-elf', 'short-header', 'short-program-table', 'bad-program-offset', + 'bad-symbol-entry-size', 'bad-symbol-name', + 'bad-interpreter-offset', 'unterminated-interpreter']) +def test_elf_rejects_malformed_metadata(native, tmp_path, damage): + directory, _, _, run = native + data = bytearray((directory / 'progs').read_bytes()) + assert data[:6] == b'\x7fELF\x02\x01', 'Fixture must be ELF64 little-endian' + if damage == 'not-elf': + data[:4] = b'nope' + elif damage == 'short-header': + data = data[:24] + elif damage == 'short-program-table': + data = data[:64] + elif damage == 'bad-program-offset': + struct.pack_into(' Date: Thu, 5 Nov 2026 13:16:05 -0500 Subject: [PATCH 6/6] Finalize adapter integration, failure recovery and documentation The adapter offers StopEventDelivery and WaitForEventCallbacks so the controller can drain its events and not block its tracer thread. They take effect once the controller calls them. Keep breakpoint bytes consistent after partial writes, close pause races, tag debugger interrupts, reset inherited launch signals, check automatic resumes and retain failed temporary-breakpoint cleanup. Resolve module instances by unique short name. Add regressions to the required suite. Document architecture, guarantees, limitations and the build/test workflow. Report process exit when a thread's death or an external kill takes the group down, and do not deliver a SIGTRAP that the target never raised. Do not count a refused resume as one, leave a forked child frozen or carrying the debugger's breakpoints, or let a dead target look alive. Fix the data races found by ThreadSanitizer, split command lines like a shell, and add the fault-injection and differential fuzzing tooling. --- build.md | 7 +- core/CMakeLists.txt | 2 + core/adapters/ptrace/ptraceadapter.cpp | 456 +++++++++++-------- core/adapters/ptrace/ptraceadapter.h | 7 +- core/adapters/ptrace/ptracecmdline.cpp | 90 ++++ core/adapters/ptrace/ptracecmdline.h | 26 ++ core/adapters/ptrace/ptraceengine.cpp | 607 ++++++++++++++++++++----- core/adapters/ptrace/ptraceengine.h | 48 +- core/adapters/ptrace/ptracemodule.cpp | 15 +- core/adapters/ptrace/ptracestep.cpp | 48 +- core/adapters/ptrace/ptracestep.h | 12 +- core/debuggerstate.cpp | 10 +- test/debugger_test.py | 264 ++++++++++- test/ptrace_engine/CMakeLists.txt | 5 +- test/ptrace_engine/README.md | 73 +++ test/ptrace_engine/cmdline.cpp | 14 + test/ptrace_engine/driver.cpp | 85 +++- test/ptrace_engine/progs.c | 19 + test/ptrace_engine_test.py | 36 +- 19 files changed, 1464 insertions(+), 360 deletions(-) create mode 100644 core/adapters/ptrace/ptracecmdline.cpp create mode 100644 core/adapters/ptrace/ptracecmdline.h create mode 100644 test/ptrace_engine/README.md create mode 100644 test/ptrace_engine/cmdline.cpp diff --git a/build.md b/build.md index 7f9209b9..d6a83bde 100644 --- a/build.md +++ b/build.md @@ -22,9 +22,10 @@ git checkout dev - Build the debugger - FlatBuffers (needed for `X2WinRpcAdapter`'s wire protocol) is vendored as a git submodule - under `vendor/` and built as part of this project's own CMake configure/build -- no separate - install step needed, just make sure submodules are cloned (`--recurse-submodules` below, or + FlatBuffers (needed for `X2WinRpcAdapter`'s wire protocol) and ELFIO (used by the Linux + ptrace adapter) are Git submodules under `vendor/`. FlatBuffers is built as part of + this project's CMake build; ELFIO is header-only and adds no separate runtime library. + Make sure submodules are cloned (`--recurse-submodules` below, or `git submodule update --init --recursive` after the fact). ```bash diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index f2f9f54c..98438ded 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -65,6 +65,8 @@ else() adapters/ptrace/ptraceadapter.h adapters/ptrace/ptracearch.cpp adapters/ptrace/ptracearch.h + adapters/ptrace/ptracecmdline.cpp + adapters/ptrace/ptracecmdline.h adapters/ptrace/ptraceelf.cpp adapters/ptrace/ptraceelf.h adapters/ptrace/ptraceengine.cpp diff --git a/core/adapters/ptrace/ptraceadapter.cpp b/core/adapters/ptrace/ptraceadapter.cpp index a18faef0..080d93a3 100644 --- a/core/adapters/ptrace/ptraceadapter.cpp +++ b/core/adapters/ptrace/ptraceadapter.cpp @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +#include #include #include #include @@ -23,77 +24,13 @@ limitations under the License. #include #include #include "ptraceadapter.h" +#include "ptracecmdline.h" #include "ptracesignal.h" #include "lowlevelilinstruction.h" #include "../../debuggercontroller.h" namespace BinaryNinjaDebugger { - static std::optional> ParseCommandLineArguments(const std::string& commandLine) - { - enum class Quote - { - None, - Single, - Double - }; - Quote quote = Quote::None; - bool escaped = false; - bool argumentStarted = false; - std::string argument; - std::vector arguments; - - for (char ch : commandLine) - { - if (escaped) - { - argument += ch; - argumentStarted = true; - escaped = false; - continue; - } - - if (ch == '\\' && quote != Quote::Single) - { - escaped = true; - argumentStarted = true; - continue; - } - if (ch == '\'' && quote != Quote::Double) - { - quote = quote == Quote::Single ? Quote::None : Quote::Single; - argumentStarted = true; - continue; - } - if (ch == '"' && quote != Quote::Single) - { - quote = quote == Quote::Double ? Quote::None : Quote::Double; - argumentStarted = true; - continue; - } - if (std::isspace(static_cast(ch)) && quote == Quote::None) - { - if (argumentStarted) - { - arguments.push_back(argument); - argument.clear(); - argumentStarted = false; - } - continue; - } - - argument += ch; - argumentStarted = true; - } - - if (escaped || quote != Quote::None) - return std::nullopt; - if (argumentStarted) - arguments.push_back(argument); - return arguments; - } - - static DebugRegister RegisterFromBytes(const PtraceRegister& reg, const std::vector& data, size_t index) { uint8_t buffer[64] = {}; @@ -166,25 +103,40 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::ResolveModuleAddress(const ModuleNameAndOffset& location, uint64_t& address) { + auto engine = Engine(); if (location.module.empty()) { address = location.offset; return true; } - if (!m_engine) + if (!engine) return false; - // The base of a module is where its first mapping starts - uint64_t base = UINT64_MAX; - for (const auto& map : m_engine->GetMaps()) + // Unique short names select an individual load instance. A shared path selects + // the lowest-address instance, matching the existing module-relative API policy. + auto modules = GetModules(); + const PtraceModuleInfo* match = nullptr; + for (const auto& module : modules) + { + if (module.shortName == location.module) + { + match = &module; + break; + } + } + if (!match) { - if (!map.path.empty() && DebugModule::IsSameBaseModule(map.path, location.module)) - base = std::min(base, map.start); + for (const auto& module : modules) + { + if (!DebugModule::IsSameBaseModule(module.path, location.module)) + continue; + if (!match || module.base < match->base) + match = &module; + } } - if (base == UINT64_MAX) + if (!match || location.offset > UINT64_MAX - match->base) return false; - - address = base + location.offset; + address = match->base + location.offset; return true; } @@ -199,8 +151,17 @@ namespace BinaryNinjaDebugger { PtraceAdapter::~PtraceAdapter() { m_destroying = true; + StopEventDelivery(); m_stepper.reset(); - m_engine.reset(); + m_engine.store(nullptr); + } + + + void PtraceAdapter::StopEventDelivery() + { + auto engine = Engine(); + if (engine) + engine->StopEventDelivery(); } @@ -213,6 +174,7 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::ExecuteWithArgs(const std::string& path, const std::string& args, const std::string& workingDir, const LaunchConfigurations& configs) { + auto engine = Engine(); auto adapterSettings = GetAdapterSettings(); auto data = GetData(); BNSettingsScope scope = SettingsResourceScope; @@ -271,8 +233,9 @@ namespace BinaryNinjaDebugger { } CreateEngine(false); + engine = Engine(); // the one just created std::string error; - if (!m_engine->Launch(options, error)) + if (!engine->Launch(options, error)) { m_targetActive = false; return launchFailure(error); @@ -283,25 +246,29 @@ namespace BinaryNinjaDebugger { void PtraceAdapter::CreateEngine(bool attached) { + // The controller drains callbacks before taking AdapterAccessMutex. This is + // idempotent there, and also protects direct adapter users that replace a session. + StopEventDelivery(); m_stepper.reset(); - m_engine.reset(); + m_engine.store(nullptr); ResetTargetState(); m_attached = attached; m_stopAtSystemEntry = Settings::Instance()->Get("debugger.stopAtSystemEntryPoint"); m_firstStop = true; m_targetActive = true; - m_engine = std::make_unique([this](const PtraceEngine::Event& event) { + m_engine.store(std::make_shared([this](const PtraceEngine::Event& event) { HandleEngineEvent(event); - }); + })); SyncEngineSettings(); m_stepper = std::make_unique( - *m_engine, [this](uint64_t address) { return AcquireBreakpoint(address); }, + *Engine(), [this](uint64_t address) { return AcquireBreakpoint(address); }, [this](uint64_t address) { return ReleaseBreakpoint(address); }); } void PtraceAdapter::HandleEngineEvent(const PtraceEngine::Event& event) { + auto engine = Engine(); if (m_destroying) return; @@ -357,7 +324,7 @@ namespace BinaryNinjaDebugger { if (m_firstStop) { m_firstStop = false; - m_arch = m_engine->GetArch(); + m_arch = engine->GetArch(); BuildRegisterList(); if (!m_arch) LogWarn("PtraceAdapter: unsupported target architecture"); @@ -371,7 +338,8 @@ namespace BinaryNinjaDebugger { else if (!m_stopAtSystemEntry) { ApplyBreakpoints(); - m_engine->Resume(false, 0); + if (!engine->Resume(false, 0)) + ReportOperationFailure("could not resume after the initial stop"); break; } } @@ -380,7 +348,8 @@ namespace BinaryNinjaDebugger { && ReadRegister64(m_arch.load()->pc) == m_loaderBreakpoint) { ApplyBreakpoints(); - m_engine->Resume(false, 0); + if (!engine->Resume(false, 0)) + ReportOperationFailure("could not resume after the loader stop"); break; } @@ -390,6 +359,11 @@ namespace BinaryNinjaDebugger { uint64_t pc = arch ? ReadRegister64(arch->pc) : 0; uint64_t sp = arch ? ReadRegister64(arch->sp) : 0; auto result = m_stepper->OnStop(event, pc, sp, IsUserBreakpoint(pc)); + if (result == PtraceStepper::Result::Failed) + { + ReportOperationFailure("could not remove temporary step breakpoints; retry cleanup before resuming"); + break; + } if (result == PtraceStepper::Result::Consumed) break; if (result == PtraceStepper::Result::Finished) @@ -414,7 +388,7 @@ namespace BinaryNinjaDebugger { PtraceEngine::SyscallInfo info; DebuggerEvent message; message.type = BackendMessageEventType; - if (m_engine->GetSyscallInfo(event.tid, info)) + if (engine->GetSyscallInfo(event.tid, info)) message.data.messageData.message = "PTRACE: " + DescribeSyscallStop(event.tid, info) + "\n"; else message.data.messageData.message = fmt::format( @@ -433,7 +407,7 @@ namespace BinaryNinjaDebugger { m_targetActive = false; ForgetKnownBreakpoints(); if (m_stepper) - m_stepper->Cancel(); + m_stepper->Discard(); ClearAppliedBreakpointState(); m_lastStopReason = ProcessExited; m_exitCode = event.signal ? 128 + event.signal : event.exitCode; @@ -445,7 +419,7 @@ namespace BinaryNinjaDebugger { m_targetActive = false; ForgetKnownBreakpoints(); if (m_stepper) - m_stepper->Cancel(); + m_stepper->Discard(); ClearAppliedBreakpointState(); dbgevt.type = DetachedEventType; PostDebuggerEvent(dbgevt); @@ -464,6 +438,7 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::Attach(std::uint32_t pid) { + auto engine = Engine(); if (pid == 0) { DebuggerEvent event; @@ -487,8 +462,9 @@ namespace BinaryNinjaDebugger { } CreateEngine(true); + engine = Engine(); // the one just created std::string error; - if (!m_engine->Attach(pid, error)) + if (!engine->Attach(pid, error)) { m_targetActive = false; DebuggerEvent event; @@ -510,13 +486,15 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::Detach() { - return m_engine && m_engine->Detach(); + auto engine = Engine(); + return engine && engine->Detach(); } bool PtraceAdapter::Quit() { - return m_engine && m_engine->Kill(); + auto engine = Engine(); + return engine && engine->Kill(); } @@ -531,25 +509,27 @@ namespace BinaryNinjaDebugger { std::uint32_t PtraceAdapter::GetActivePID() { - return m_engine ? m_engine->GetPid() : 0; + auto engine = Engine(); + return engine ? engine->GetPid() : 0; } std::vector PtraceAdapter::GetThreadList() { + auto engine = Engine(); std::vector threads; - if (!m_engine) + if (!engine) return threads; auto arch = m_arch.load(); - for (uint32_t tid : m_engine->GetThreads()) + for (uint32_t tid : engine->GetThreads()) { DebugThread thread(tid); - if (arch && !m_engine->IsRunning()) + if (arch && !engine->IsRunning()) { auto pc = arch->Find(arch->pc); std::vector data; - if (pc && m_engine->GetRegisterSet(tid, pc->regset, data) && RegisterInBounds(*pc, data)) + if (pc && engine->GetRegisterSet(tid, pc->regset, data) && RegisterInBounds(*pc, data)) thread.m_rip = (uintptr_t)RegisterFromBytes(*pc, data, 0).m_value; } threads.push_back(thread); @@ -578,10 +558,11 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::SetActiveThreadId(std::uint32_t tid) { - if (!m_engine) + auto engine = Engine(); + if (!engine) return false; - auto threads = m_engine->GetThreads(); + auto threads = engine->GetThreads(); if (std::find(threads.begin(), threads.end(), tid) == threads.end()) return false; @@ -604,10 +585,11 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::ReadRegisterOf(uint32_t tid, const std::string& name, uint64_t& value) { + auto engine = Engine(); auto arch = m_arch.load(); auto info = arch ? arch->Find(name) : nullptr; std::vector data; - if (!m_engine || !info || !m_engine->GetRegisterSet(tid, info->regset, data) || !RegisterInBounds(*info, data)) + if (!engine || !info || !engine->GetRegisterSet(tid, info->regset, data) || !RegisterInBounds(*info, data)) return false; value = (uint64_t)RegisterFromBytes(*info, data, 0).m_value; @@ -617,11 +599,12 @@ namespace BinaryNinjaDebugger { std::vector PtraceAdapter::GetFramesOfThread(uint32_t tid) { + auto engine = Engine(); std::vector frames; auto arch = m_arch.load(); auto pcInfo = arch ? arch->Find(arch->pc) : nullptr; uint64_t pc, sp, fp = 0; - if (!m_engine || !pcInfo || m_engine->IsRunning() || !ReadRegisterOf(tid, arch->pc, pc) + if (!engine || !pcInfo || engine->IsRunning() || !ReadRegisterOf(tid, arch->pc, pc) || !ReadRegisterOf(tid, arch->sp, sp)) return frames; // Without a frame pointer register there is only the one frame @@ -629,7 +612,7 @@ namespace BinaryNinjaDebugger { ReadRegisterOf(tid, arch->fp, fp); std::vector> executable; - for (const auto& map : m_engine->GetMaps()) + for (const auto& map : engine->GetMaps()) { if (map.execute) executable.emplace_back(map.start, map.end); @@ -641,9 +624,9 @@ namespace BinaryNinjaDebugger { auto it = std::upper_bound(executable.begin(), executable.end(), std::make_pair(address, UINT64_MAX)); return it != executable.begin() && address < std::prev(it)->second; }; - auto readWord = [this, wordSize](uint64_t address, uint64_t& value) { + auto readWord = [engine, wordSize](uint64_t address, uint64_t& value) { value = 0; - return m_engine->ReadMemory(address, &value, wordSize); + return engine->ReadMemory(address, &value, wordSize); }; auto modules = GetModules(); @@ -678,7 +661,8 @@ namespace BinaryNinjaDebugger { DebugBreakpoint PtraceAdapter::AddBreakpoint(const std::uintptr_t address, unsigned long breakpoint_type) { - if (!m_engine || !m_targetActive) + auto engine = Engine(); + if (!engine || !m_targetActive) return DebugBreakpoint(); std::lock_guard lock(m_breakpointMutex); @@ -720,21 +704,24 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::RemoveBreakpoint(const DebugBreakpoint& breakpoint) { + auto engine = Engine(); std::lock_guard lock(m_breakpointMutex); - auto it = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [&breakpoint](const DebugBreakpoint& bp) { - return bp.m_address == breakpoint.m_address; + // Callers may pass an element of m_breakpoints. Save its address before erasing that element. + uint64_t address = breakpoint.m_address; + auto it = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [address](const DebugBreakpoint& bp) { + return bp.m_address == address; }); - if (!m_engine || it == m_breakpoints.end()) + if (!engine || it == m_breakpoints.end()) return false; ModuleNameAndOffset location; - bool known = ToModuleOffset(breakpoint.m_address, location); - if (!ReleaseBreakpoint(breakpoint.m_address)) + bool known = ToModuleOffset(address, location); + if (!ReleaseBreakpoint(address)) return false; m_breakpoints.erase(it); std::erase_if(m_knownBreakpoints, [&](const KnownBreakpoint& k) { - return k.appliedAddress == breakpoint.m_address || (known && k.location == location); + return k.appliedAddress == address || (known && k.location == location); }); return true; } @@ -759,7 +746,15 @@ namespace BinaryNinjaDebugger { } if (known == m_knownBreakpoints.end()) - return false; + { + uint64_t resolved; + if (!ResolveModuleAddress(address, resolved)) + return false; + auto applied = std::find_if(m_breakpoints.begin(), m_breakpoints.end(), [resolved](const DebugBreakpoint& bp) { + return bp.m_address == resolved; + }); + return applied != m_breakpoints.end() && RemoveBreakpoint(*applied); + } m_knownBreakpoints.erase(known); m_pendingBreakpoints.erase(std::remove(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address), m_pendingBreakpoints.end()); @@ -777,11 +772,12 @@ namespace BinaryNinjaDebugger { // Hardware breakpoint and watchpoint support bool PtraceAdapter::AddHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size) { + auto engine = Engine(); PtraceHwType hwType; - if (!m_engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) + if (!engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) return false; - if (!m_engine->AddHardwareBreakpoint(address, hwType, size)) + if (!engine->AddHardwareBreakpoint(address, hwType, size)) return false; std::lock_guard lock(m_breakpointMutex); @@ -802,19 +798,20 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::RemoveHardwareBreakpoint(uint64_t address, DebugBreakpointType type, size_t size) { + auto engine = Engine(); PtraceHwType hwType; - if (!m_engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) + if (!engine || !m_targetActive || !HwTypeFromBreakpointType(type, hwType)) return false; std::lock_guard lock(m_breakpointMutex); ModuleNameAndOffset location; bool known = ToModuleOffset(address, location); - if (!m_engine->RemoveHardwareBreakpoint(address, hwType, size)) + if (!engine->RemoveHardwareBreakpoint(address, hwType, size)) return false; std::erase_if(m_knownHardwareBreakpoints, [&](const PendingHardwareBreakpoint& entry) { - return entry.address == address - || (known && entry.isRelative && entry.location == location && entry.type == type && entry.size == size); + return entry.type == type && entry.size == size + && (entry.address == address || (known && entry.isRelative && entry.location == location)); }); return true; } @@ -846,7 +843,10 @@ namespace BinaryNinjaDebugger { PendingHardwareBreakpoint pending(location, type, size); auto known = std::find(m_knownHardwareBreakpoints.begin(), m_knownHardwareBreakpoints.end(), pending); if (known == m_knownHardwareBreakpoints.end()) - return false; + { + uint64_t resolved; + return ResolveModuleAddress(location, resolved) && RemoveHardwareBreakpoint(resolved, type, size); + } if (known->address && !RemoveHardwareBreakpoint(known->address, type, size)) return false; m_knownHardwareBreakpoints.erase( @@ -861,16 +861,17 @@ namespace BinaryNinjaDebugger { std::unordered_map PtraceAdapter::ReadAllRegisters() { + auto engine = Engine(); std::unordered_map result; auto arch = m_arch.load(); - if (!m_engine || !arch) + if (!engine || !arch) return result; std::unordered_map> regsets; for (int regset : arch->regsets) { std::vector data; - if (m_engine->GetRegisterSet(m_activeThreadId, regset, data)) + if (engine->GetRegisterSet(m_activeThreadId, regset, data)) regsets[regset] = std::move(data); } @@ -888,8 +889,9 @@ namespace BinaryNinjaDebugger { DebugRegister PtraceAdapter::ReadRegister(const std::string& reg) { + auto engine = Engine(); auto arch = m_arch.load(); - if (!m_engine || !arch) + if (!engine || !arch) return DebugRegister(); auto registers = GetRegisterList(); @@ -899,7 +901,7 @@ namespace BinaryNinjaDebugger { return DebugRegister(); std::vector data; - if (!m_engine->GetRegisterSet(m_activeThreadId, found->regset, data) || !RegisterInBounds(*found, data)) + if (!engine->GetRegisterSet(m_activeThreadId, found->regset, data) || !RegisterInBounds(*found, data)) return DebugRegister(); return RegisterFromBytes(*found, data, found - registers->begin()); @@ -908,22 +910,23 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::WriteRegister(const std::string& reg, intx::uint512 value) { + auto engine = Engine(); auto arch = m_arch.load(); - if (!m_engine || !arch) + if (!engine || !arch) return false; auto registers = GetRegisterList(); auto info = std::find_if(registers->begin(), registers->end(), [®](const PtraceRegister& candidate) { return candidate.name == reg; }); std::vector data; - if (info == registers->end() || !m_engine->GetRegisterSet(m_activeThreadId, info->regset, data) + if (info == registers->end() || !engine->GetRegisterSet(m_activeThreadId, info->regset, data) || !RegisterInBounds(*info, data)) return false; uint8_t buffer[64]; intx::le::store(buffer, value); memcpy(data.data() + info->offset, buffer, std::min(info->size, sizeof(buffer))); - return m_engine->SetRegisterSet(m_activeThreadId, info->regset, data); + return engine->SetRegisterSet(m_activeThreadId, info->regset, data); } @@ -983,12 +986,13 @@ namespace BinaryNinjaDebugger { DataBuffer PtraceAdapter::ReadMemory(std::uintptr_t address, std::size_t size) { + auto engine = Engine(); DataBuffer result; - if (!m_engine || size == 0) + if (!engine || size == 0) return result; std::vector buffer(size); - if (m_engine->ReadMemory(address, buffer.data(), size)) + if (engine->ReadMemory(address, buffer.data(), size)) result.Append(buffer.data(), size); return result; } @@ -996,28 +1000,56 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::WriteMemory(std::uintptr_t address, const DataBuffer& buffer) { - return m_engine && m_engine->WriteMemory(address, buffer.GetData(), buffer.GetLength()); + auto engine = Engine(); + return engine && engine->WriteMemory(address, buffer.GetData(), buffer.GetLength()); } std::vector PtraceAdapter::GetModules() { - if (!m_engine) + auto engine = Engine(); + if (!engine) return {}; std::lock_guard lock(m_moduleMutex); uint64_t generation = m_stopGeneration; if (m_moduleGeneration != generation) { - m_modules = BuildModules(m_engine->GetMaps(), [this](uint64_t address) { + auto modules = BuildModules(engine->GetMaps(), [engine](uint64_t address) { uint8_t magic[4]; - return m_engine->ReadMemory(address, magic, sizeof(magic)) + return engine->ReadMemory(address, magic, sizeof(magic)) && memcmp(magic, "\x7f" "ELF", 4) == 0; }); + // Keep the name of each surviving load instance stable when another instance unloads. + std::set usedNames; + for (auto& module : modules) + { + auto previous = std::find_if(m_modules.begin(), m_modules.end(), [&module](const PtraceModuleInfo& old) { + return old.path == module.path && old.base == module.base; + }); + if (previous != m_modules.end()) + { + module.shortName = previous->shortName; + usedNames.insert(module.shortName); + } + else + module.shortName.clear(); + } + for (auto& module : modules) + { + if (!module.shortName.empty()) + continue; + std::string base = std::filesystem::path(module.path).filename().string(); + module.shortName = base; + for (size_t suffix = 1; usedNames.count(module.shortName); suffix++) + module.shortName = base + "-" + std::to_string(suffix); + usedNames.insert(module.shortName); + } + m_modules = std::move(modules); m_moduleGeneration = generation; } return m_modules; @@ -1057,11 +1089,12 @@ namespace BinaryNinjaDebugger { // a breakpoint in a library gets placed before the library runs, and how libraries that are loaded later are found. void PtraceAdapter::SetUpLoaderBreakpoint() { - if (!m_engine) + auto engine = Engine(); + if (!engine) return; std::error_code error; - auto exe = std::filesystem::read_symlink("/proc/" + std::to_string(m_engine->GetPid()) + "/exe", error); + auto exe = std::filesystem::read_symlink("/proc/" + std::to_string(engine->GetPid()) + "/exe", error); auto elf = error ? nullptr : GetElf(exe.string()); if (!elf || elf->interpreter.empty()) return; @@ -1101,11 +1134,12 @@ namespace BinaryNinjaDebugger { std::vector PtraceAdapter::GetMemoryMap() { + auto engine = Engine(); std::vector regions; - if (!m_engine) + if (!engine) return regions; - for (const auto& map : m_engine->GetMaps()) + for (const auto& map : engine->GetMaps()) { if (map.end > map.start) regions.push_back(DebugMemoryRegion( @@ -1168,17 +1202,22 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::BreakInto() { - return m_engine && m_engine->Interrupt(); + auto engine = Engine(); + return engine && engine->Interrupt(); } bool PtraceAdapter::Go() { + auto engine = Engine(); SyncEngineSettings(); - if (m_stepper) - m_stepper->Cancel(); + if (m_stepper && !m_stepper->Cancel()) + { + ReportOperationFailure("could not remove temporary step breakpoints; retry cleanup before resuming"); + return false; + } m_stopGeneration++; - if (!m_engine || !m_engine->Resume(false, 0)) + if (!engine || !engine->Resume(false, 0)) return false; DebuggerEvent event; @@ -1190,11 +1229,15 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::StepInto() { + auto engine = Engine(); SyncEngineSettings(); - if (m_stepper) - m_stepper->Cancel(); + if (m_stepper && !m_stepper->Cancel()) + { + ReportOperationFailure("could not remove temporary step breakpoints; retry cleanup before resuming"); + return false; + } m_stopGeneration++; - if (!m_engine || !m_engine->Resume(true, m_activeThreadId)) + if (!engine || !engine->Resume(true, m_activeThreadId)) return false; DebuggerEvent event; @@ -1209,14 +1252,19 @@ namespace BinaryNinjaDebugger { // controller waits for the stop as it does for any other step. bool PtraceAdapter::StepOver() { - if (!m_engine || !m_stepper || m_engine->IsRunning()) + auto engine = Engine(); + if (!engine || !m_stepper || engine->IsRunning()) return false; SyncEngineSettings(); - m_stepper->Cancel(); + if (!m_stepper->Cancel()) + { + ReportOperationFailure("could not remove temporary step breakpoints; retry cleanup before resuming"); + return false; + } m_stopGeneration++; uint32_t tid = m_activeThreadId; - m_engine->PostTask([this, tid] { DoStepOver(tid); }); + engine->PostTask([this, tid] { DoStepOver(tid); }); DebuggerEvent event; event.type = StepOverEventType; @@ -1227,14 +1275,19 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::StepReturn() { - if (!m_engine || !m_stepper || m_engine->IsRunning()) + auto engine = Engine(); + if (!engine || !m_stepper || engine->IsRunning()) return false; SyncEngineSettings(); - m_stepper->Cancel(); + if (!m_stepper->Cancel()) + { + ReportOperationFailure("could not remove temporary step breakpoints; retry cleanup before resuming"); + return false; + } m_stopGeneration++; uint32_t tid = m_activeThreadId; - m_engine->PostTask([this, tid] { DoStepReturn(tid); }); + engine->PostTask([this, tid] { DoStepReturn(tid); }); DebuggerEvent event; event.type = StepOverEventType; @@ -1244,11 +1297,11 @@ namespace BinaryNinjaDebugger { // The controller is waiting for a stop, so a step that cannot be done still has to end in one - void PtraceAdapter::FailStep(const std::string& message) + void PtraceAdapter::ReportOperationFailure(const std::string& message) { DebuggerEvent event; event.type = ErrorEventType; - event.data.errorData.shortError = "Step failed"; + event.data.errorData.shortError = "Debugger operation failed"; event.data.errorData.error = fmt::format("PTRACE: {}", message); PostDebuggerEvent(event); @@ -1343,12 +1396,12 @@ namespace BinaryNinjaDebugger { uint64_t pc, sp; if (!pcInfo || !ReadRegisterOf(tid, arch->pc, pc) || !ReadRegisterOf(tid, arch->sp, sp)) { - FailStep("could not read the registers of the thread"); + ReportOperationFailure("could not read the registers of the thread"); return; } if (!m_stepper->StepOver(tid, pc, sp, GetCallLength(pc), pcInfo->size)) - FailStep("could not step over the instruction"); + ReportOperationFailure("could not step over the instruction"); } @@ -1358,7 +1411,7 @@ namespace BinaryNinjaDebugger { uint64_t pc, sp; if (!arch || !ReadRegisterOf(tid, arch->pc, pc) || !ReadRegisterOf(tid, arch->sp, sp)) { - FailStep("could not read the registers of the thread"); + ReportOperationFailure("could not read the registers of the thread"); return; } @@ -1378,7 +1431,7 @@ namespace BinaryNinjaDebugger { // A return instruction has the stack pointer of the function or above it, on every ABI that keeps the return // address on the stack, as well as on those that do not once the epilogue has run if (!m_stepper->StepReturn(tid, pc, sp, sites, returnAddress, returnSp)) - FailStep("could not find where the function returns"); + ReportOperationFailure("could not find where the function returns"); } @@ -1439,17 +1492,21 @@ namespace BinaryNinjaDebugger { std::string PtraceAdapter::ContinueToSyscall(PtraceEngine::SyscallMode mode) { - if (!m_engine || !m_targetActive) + auto engine = Engine(); + if (!engine || !m_targetActive) return "PTRACE: there is no target\n"; - if (m_engine->IsRunning()) + if (engine->IsRunning()) return "PTRACE: the target is running\n"; auto arch = m_arch.load(); if (mode == PtraceEngine::SyscallMode::Emulate && (!arch || !arch->sysemu)) return "PTRACE: this architecture has no PTRACE_SYSEMU\n"; SyncEngineSettings(); - if (m_stepper) - m_stepper->Cancel(); + if (m_stepper && !m_stepper->Cancel()) + { + ReportOperationFailure("could not remove temporary step breakpoints; retry cleanup before resuming"); + return "PTRACE: could not remove temporary step breakpoints; target remains stopped\n"; + } m_stopGeneration++; // The controller did not ask for this, so it has to be told that the target runs. That comes before the resume, @@ -1458,7 +1515,7 @@ namespace BinaryNinjaDebugger { resumed.type = ResumeEventType; PostDebuggerEvent(resumed); - if (m_engine->ResumeToSyscall(mode)) + if (engine->ResumeToSyscall(mode)) return mode == PtraceEngine::SyscallMode::Trace ? "PTRACE: running to the entry or the exit of the next system call\n" : "PTRACE: running to the entry of the next system call, which will not be made\n"; @@ -1474,11 +1531,12 @@ namespace BinaryNinjaDebugger { std::string PtraceAdapter::DescribeCurrentSyscall() { - if (!m_engine || !m_targetActive) + auto engine = Engine(); + if (!engine || !m_targetActive) return "PTRACE: there is no target\n"; PtraceEngine::SyscallInfo info; - if (m_engine->IsRunning() || !m_engine->GetSyscallInfo(m_activeThreadId, info)) + if (engine->IsRunning() || !engine->GetSyscallInfo(m_activeThreadId, info)) return "PTRACE: the system call information could not be read. The target has to be stopped, on Linux 5.3 or " "newer.\n"; @@ -1496,11 +1554,12 @@ namespace BinaryNinjaDebugger { std::string PtraceAdapter::SetSyscallField(const std::string& field, const std::string& value) { - if (!m_engine || !m_targetActive || m_engine->IsRunning()) + auto engine = Engine(); + if (!engine || !m_targetActive || engine->IsRunning()) return "PTRACE: the target has to be stopped\n"; PtraceEngine::SyscallInfo info; - if (!m_engine->GetSyscallInfo(m_activeThreadId, info) + if (!engine->GetSyscallInfo(m_activeThreadId, info) || (info.op == PtraceEngine::SyscallInfo::None)) return "PTRACE: the active thread is not stopped at a system call\n"; @@ -1531,7 +1590,7 @@ namespace BinaryNinjaDebugger { if (value.empty() || !end || *end != '\0') return fmt::format("PTRACE: \"{}\" is not a number\n", value); - if (!m_engine->SetSyscallInfo(m_activeThreadId, info)) + if (!engine->SetSyscallInfo(m_activeThreadId, info)) return "PTRACE: the kernel did not take the change. It needs Linux 6.16.\n"; return "PTRACE: changed. " + DescribeCurrentSyscall(); } @@ -1572,8 +1631,9 @@ namespace BinaryNinjaDebugger { void PtraceAdapter::WriteStdin(const std::string& msg) { - if (m_engine) - m_engine->WriteInput(msg); + auto engine = Engine(); + if (engine) + engine->WriteInput(msg); } @@ -1582,12 +1642,13 @@ namespace BinaryNinjaDebugger { Ref PtraceAdapter::GetProperty(const std::string& name) { + auto engine = Engine(); // The system call that the active thread is stopped at, for scripts - if (name != "syscall" || !m_engine || !m_targetActive || m_engine->IsRunning()) + if (name != "syscall" || !engine || !m_targetActive || engine->IsRunning()) return nullptr; PtraceEngine::SyscallInfo info; - if (!m_engine->GetSyscallInfo(m_activeThreadId, info)) + if (!engine->GetSyscallInfo(m_activeThreadId, info)) return nullptr; static const char* const ops[] = {"none", "entry", "exit", "seccomp"}; @@ -1620,8 +1681,9 @@ namespace BinaryNinjaDebugger { void PtraceAdapter::ApplyBreakpoints() { + auto engine = Engine(); std::lock_guard lock(m_breakpointMutex); - if (!m_engine || !m_targetActive) + if (!engine || !m_targetActive) return; // The logical module-relative breakpoint remains authoritative after it has been applied. A loader rendezvous @@ -1640,7 +1702,10 @@ namespace BinaryNinjaDebugger { }); if (applied != m_breakpoints.end()) { - if (!ReleaseBreakpoint(oldAddress, false)) + PtraceModuleInfo oldModule; + bool restore = FindModule(oldAddress, oldModule) + && (oldModule.shortName == location.module || DebugModule::IsSameBaseModule(oldModule.path, location.module)); + if (!ReleaseBreakpoint(oldAddress, restore)) continue; m_breakpoints.erase(applied); } @@ -1655,7 +1720,7 @@ namespace BinaryNinjaDebugger { }); if (applied != m_breakpoints.end()) { - if (m_engine->AddBreakpoint(address)) + if (engine->AddBreakpoint(address)) m_knownBreakpoints[index].appliedAddress = address; } else if (AddBreakpoint(address, 0).m_address != 0) @@ -1679,7 +1744,7 @@ namespace BinaryNinjaDebugger { bool logical = std::any_of(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), [&breakpoint](const KnownBreakpoint& known) { return known.appliedAddress == breakpoint.m_address; }); if (!logical) - m_engine->AddBreakpoint(breakpoint.m_address); + engine->AddBreakpoint(breakpoint.m_address); } for (auto& known : m_knownHardwareBreakpoints) @@ -1692,11 +1757,11 @@ namespace BinaryNinjaDebugger { if (known.address && (!resolved || known.address != address)) { - if (!m_engine->RemoveHardwareBreakpoint(known.address, hwType, known.size)) + if (!engine->RemoveHardwareBreakpoint(known.address, hwType, known.size)) continue; known.address = 0; } - if (resolved && !known.address && m_engine->AddHardwareBreakpoint(address, hwType, known.size)) + if (resolved && !known.address && engine->AddHardwareBreakpoint(address, hwType, known.size)) known.address = address; } m_pendingHardwareBreakpoints.clear(); @@ -1713,14 +1778,15 @@ namespace BinaryNinjaDebugger { // the first. void PtraceAdapter::HandleExec(const PtraceEngine::Event& event) { + auto engine = Engine(); // A step that the exec cut short is over, and the stop is the end of it bool wasStepping = event.singleStep || (m_stepper && m_stepper->IsActive()); if (m_stepper) - m_stepper->Cancel(); + m_stepper->Discard(); ClearAppliedBreakpointState(); ResetTargetState(); - m_arch = m_engine->GetArch(); + m_arch = engine->GetArch(); BuildRegisterList(); if (!m_arch) LogWarn("PtraceAdapter: unsupported target architecture"); @@ -1739,7 +1805,7 @@ namespace BinaryNinjaDebugger { } std::error_code error; - auto program = std::filesystem::read_symlink("/proc/" + std::to_string(m_engine->GetPid()) + "/exe", error); + auto program = std::filesystem::read_symlink("/proc/" + std::to_string(engine->GetPid()) + "/exe", error); DebuggerEvent message; message.type = BackendMessageEventType; message.data.messageData.message = fmt::format("PTRACE: the process started {}\n", program.string()); @@ -1756,7 +1822,8 @@ namespace BinaryNinjaDebugger { bool stopOnExec = GetAdapterSettings()->Get("common.stopOnExec", GetData(), &scope); if (!stopOnExec && !wasStepping) { - m_engine->Resume(false, 0); + if (!engine->Resume(false, 0)) + ReportOperationFailure("could not resume after exec"); return; } @@ -1845,7 +1912,7 @@ namespace BinaryNinjaDebugger { if (!FindModule(address, module)) return false; - location = ModuleNameAndOffset(module.path, address - module.base); + location = ModuleNameAndOffset(module.shortName, address - module.base); return true; } @@ -1866,17 +1933,21 @@ namespace BinaryNinjaDebugger { function = symbol->name; } - ModuleNameAndOffset location(module.path, address - module.base); + ModuleNameAndOffset location(module.shortName, address - module.base); auto it = std::find_if(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), - [&location](const KnownBreakpoint& known) { return known.location == location; }); + [&](const KnownBreakpoint& known) { + return known.appliedAddress == address || known.location == location + || (!known.appliedAddress && known.location.offset == location.offset + && (known.location.module == module.path || known.location.module == module.shortName)); + }); if (it == m_knownBreakpoints.end()) m_knownBreakpoints.push_back({location, function, address}); - else if (it->function.empty()) - it->function = function; - it = std::find_if(m_knownBreakpoints.begin(), m_knownBreakpoints.end(), - [&location](const KnownBreakpoint& known) { return known.location == location; }); - if (it != m_knownBreakpoints.end()) + else + { + if (it->function.empty()) + it->function = function; it->appliedAddress = address; + } } @@ -2015,11 +2086,12 @@ namespace BinaryNinjaDebugger { // The setting can be changed while the target is stopped, so the engine is told again before every resume void PtraceAdapter::SyncEngineSettings() { - if (!m_engine) + auto engine = Engine(); + if (!engine) return; BNSettingsScope scope = SettingsResourceScope; - m_engine->SetDebugSignalHandlers( + engine->SetDebugSignalHandlers( GetAdapterSettings()->Get("common.debugSignalHandlers", GetData(), &scope)); } @@ -2042,12 +2114,13 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::AcquireBreakpoint(uint64_t address) { + auto engine = Engine(); std::lock_guard lock(m_breakpointMutex); - if (!m_engine) + if (!engine) return false; int& count = m_engineBreakpointRefs[address]; - if (count == 0 && !m_engine->AddBreakpoint(address)) + if (count == 0 && !engine->AddBreakpoint(address)) { m_engineBreakpointRefs.erase(address); return false; @@ -2059,9 +2132,10 @@ namespace BinaryNinjaDebugger { bool PtraceAdapter::ReleaseBreakpoint(uint64_t address, bool restore) { + auto engine = Engine(); std::lock_guard lock(m_breakpointMutex); auto it = m_engineBreakpointRefs.find(address); - if (!m_engine || it == m_engineBreakpointRefs.end()) + if (!engine || it == m_engineBreakpointRefs.end()) return false; if (it->second > 1) @@ -2070,7 +2144,7 @@ namespace BinaryNinjaDebugger { return true; } - bool removed = restore ? m_engine->RemoveBreakpoint(address) : m_engine->DiscardBreakpoint(address); + bool removed = restore ? engine->RemoveBreakpoint(address) : engine->DiscardBreakpoint(address); if (removed) m_engineBreakpointRefs.erase(it); return removed; @@ -2109,7 +2183,7 @@ namespace BinaryNinjaDebugger { } - PtraceAdapterType::PtraceAdapterType() : DebugAdapterType("PTRACE") {} + PtraceAdapterType::PtraceAdapterType() : DebugAdapterType("ptrace_x86/64") {} DebugAdapter* PtraceAdapterType::Create(BinaryNinja::BinaryView* data) diff --git a/core/adapters/ptrace/ptraceadapter.h b/core/adapters/ptrace/ptraceadapter.h index 1ad33b07..09a1ccb8 100644 --- a/core/adapters/ptrace/ptraceadapter.h +++ b/core/adapters/ptrace/ptraceadapter.h @@ -32,7 +32,8 @@ namespace BinaryNinjaDebugger { class PtraceAdapter : public DebugAdapter { private: - std::unique_ptr m_engine; + std::atomic> m_engine; + std::shared_ptr Engine() const { return m_engine.load(); } std::unique_ptr m_stepper; std::atomic m_targetActive; std::atomic m_activeThreadId {0}; @@ -114,7 +115,7 @@ namespace BinaryNinjaDebugger { bool IsUserBreakpoint(uint64_t address); void DoStepOver(uint32_t tid); void DoStepReturn(uint32_t tid); - void FailStep(const std::string& message); + void ReportOperationFailure(const std::string& message); size_t GetCallLength(uint64_t pc); std::vector GetReturnSites(uint64_t pc); bool IsInAnalyzedModule(uint64_t address); @@ -129,6 +130,8 @@ namespace BinaryNinjaDebugger { public: PtraceAdapter(BinaryView* data); virtual ~PtraceAdapter(); + void StopEventDelivery(); + bool WaitForEventCallbacks() const { return false; } bool Execute(const std::string& path, const LaunchConfigurations& configs) override; diff --git a/core/adapters/ptrace/ptracecmdline.cpp b/core/adapters/ptrace/ptracecmdline.cpp new file mode 100644 index 00000000..ab432065 --- /dev/null +++ b/core/adapters/ptrace/ptracecmdline.cpp @@ -0,0 +1,90 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +#include "ptracecmdline.h" + +namespace BinaryNinjaDebugger { + + std::optional> ParseCommandLineArguments(const std::string& commandLine) + { + enum class Quote + { + None, + Single, + Double + }; + Quote quote = Quote::None; + bool escaped = false; + bool argumentStarted = false; + std::string argument; + std::vector arguments; + + for (char ch : commandLine) + { + if (escaped) + { + escaped = false; + if (ch == '\n') + continue; + if (quote == Quote::Double && ch != '$' && ch != '`' && ch != '"' && ch != '\\') + argument += '\\'; + argument += ch; + argumentStarted = true; + continue; + } + + if (ch == '\\' && quote != Quote::Single) + { + escaped = true; + argumentStarted = true; + continue; + } + if (ch == '\'' && quote != Quote::Double) + { + quote = quote == Quote::Single ? Quote::None : Quote::Single; + argumentStarted = true; + continue; + } + if (ch == '"' && quote != Quote::Single) + { + quote = quote == Quote::Double ? Quote::None : Quote::Double; + argumentStarted = true; + continue; + } + if ((ch == ' ' || ch == '\t' || ch == '\n') && quote == Quote::None) + { + if (argumentStarted) + { + arguments.push_back(argument); + argument.clear(); + argumentStarted = false; + } + continue; + } + + argument += ch; + argumentStarted = true; + } + + if (escaped || quote != Quote::None) + return std::nullopt; + if (argumentStarted) + arguments.push_back(argument); + return arguments; + } + +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptracecmdline.h b/core/adapters/ptrace/ptracecmdline.h new file mode 100644 index 00000000..754d0d36 --- /dev/null +++ b/core/adapters/ptrace/ptracecmdline.h @@ -0,0 +1,26 @@ +/* +Copyright 2020-2026 Vector 35 Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + + +#pragma once +#include +#include +#include + +namespace BinaryNinjaDebugger { + // nullopt if a quote or a trailing backslash is left open + std::optional> ParseCommandLineArguments(const std::string& commandLine); +} // namespace BinaryNinjaDebugger diff --git a/core/adapters/ptrace/ptraceengine.cpp b/core/adapters/ptrace/ptraceengine.cpp index 2333d687..a5804a48 100644 --- a/core/adapters/ptrace/ptraceengine.cpp +++ b/core/adapters/ptrace/ptraceengine.cpp @@ -31,7 +31,9 @@ limitations under the License. #include #include #include +#include #include +#include #include #include #include @@ -94,6 +96,41 @@ namespace BinaryNinjaDebugger { KernelSyscallInfoSeccomp = 3 }; + static constexpr int spinPolls = 20; + static constexpr int maxBackoffShift = 6; + static constexpr auto strandedRetryInterval = std::chrono::milliseconds(20); + static constexpr auto strandedGiveUpAfter = std::chrono::seconds(2); + static constexpr auto unwatchedExitPollInterval = std::chrono::milliseconds(100); + static constexpr auto waitForever = std::chrono::nanoseconds::max(); + + // PIDFD_THREAD, Linux 6.9 + static constexpr int pidfdThreadFlag = O_EXCL; + + struct ProcStatus + { + char state = 0; + pid_t parent = 0; + pid_t tracer = 0; + }; + + static ProcStatus ReadProcStatus(const std::string& path) + { + ProcStatus status; + std::ifstream file(path); + std::string line; + while (std::getline(file, line)) + { + if (line.rfind("State:", 0) == 0 && line.size() > 7) + status.state = line[line.find_first_not_of(" \t", 6)]; + else if (line.rfind("PPid:", 0) == 0) + status.parent = atoi(line.c_str() + 5); + else if (line.rfind("TracerPid:", 0) == 0) + status.tracer = atoi(line.c_str() + 10); + } + return status; + } + + static bool ShouldAutoContinueSignal(int signal) { switch (signal) @@ -135,7 +172,7 @@ namespace BinaryNinjaDebugger { std::lock_guard lock(m_taskMutex); m_shutdown = true; } - m_taskCv.notify_all(); + WakeTracer(); m_tracerThread.join(); } @@ -178,6 +215,8 @@ namespace BinaryNinjaDebugger { close(m_masterFd); if (m_memFd >= 0) close(m_memFd); + if (m_wakeFd >= 0) + close(m_wakeFd); } @@ -255,11 +294,7 @@ namespace BinaryNinjaDebugger { bool PtraceEngine::Launch(const LaunchOptions& options, std::string& error) { m_options = options; - auto result = m_launchResult.get_future(); - m_eventThread = std::thread(&PtraceEngine::EventLoop, m_core); - m_tracerThread = std::thread(&PtraceEngine::TracerMain, this); - error = result.get(); - return error.empty(); + return StartTracer(error); } @@ -268,6 +303,19 @@ namespace BinaryNinjaDebugger { m_options.arch = arch; m_attachPid = pid; m_attached = true; + return StartTracer(error); + } + + + bool PtraceEngine::StartTracer(std::string& error) + { + m_wakeFd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); + if (m_wakeFd < 0) + { + error = std::string("failed to create the tracer wake-up descriptor: ") + strerror(errno); + return false; + } + auto result = m_launchResult.get_future(); m_eventThread = std::thread(&PtraceEngine::EventLoop, m_core); m_tracerThread = std::thread(&PtraceEngine::TracerMain, this); @@ -286,7 +334,7 @@ namespace BinaryNinjaDebugger { return false; m_tasks.push_back([task] { (*task)(); }); } - m_taskCv.notify_all(); + WakeTracer(); // Only the queue may keep the task alive, so that discarding it breaks the promise task.reset(); @@ -339,22 +387,34 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::SendStop(pid_t tid) + { + // Tag our requests instead of trying to count SIGSTOP acknowledgments: standard + // signals coalesce, and another component in this process can also send SIGSTOP. + siginfo_t signal {}; + signal.si_signo = SIGSTOP; + signal.si_code = SI_QUEUE; + signal.si_pid = getpid(); + signal.si_uid = getuid(); + signal.si_value.sival_ptr = this; + if (tid) + return syscall(SYS_rt_tgsigqueueinfo, m_pid, tid, SIGSTOP, &signal) == 0; + return syscall(SYS_rt_sigqueueinfo, m_pid, SIGSTOP, &signal) == 0; + } + + bool PtraceEngine::Interrupt() { + std::lock_guard lock(m_infoMutex); if (!m_publishedRunning) return false; m_interruptWanted = true; - // One signal on its way is enough, because the stop that it causes is the one that is wanted - if (m_interruptInFlight++ > 0) + // SIGSTOP coalesces, so requests cannot be counted as separate acknowledgments. + if (!SendStop()) { - m_interruptInFlight--; - return true; - } - if (kill(m_pid, SIGSTOP) != 0) - { - m_interruptInFlight--; + m_interruptWanted = false; return false; } return true; @@ -425,8 +485,10 @@ namespace BinaryNinjaDebugger { } - bool PtraceEngine::RawWriteMemory(uint64_t address, const void* buffer, size_t size) + bool PtraceEngine::RawWriteMemory(uint64_t address, const void* buffer, size_t size, size_t* written) { + if (written) + *written = 0; if (m_memFd < 0 || m_finished || address > INT64_MAX || size > INT64_MAX - address) return false; @@ -439,6 +501,8 @@ namespace BinaryNinjaDebugger { if (count <= 0) return false; done += count; + if (written) + *written = done; } return true; } @@ -472,7 +536,7 @@ namespace BinaryNinjaDebugger { std::lock_guard lock(m_breakpointMutex); std::vector data((const uint8_t*)buffer, (const uint8_t*)buffer + size); - // The breakpoint bytes stay in place, and what was written becomes the bytes underneath them + // Keep the trap instructions installed. Saved originals are updated only for the prefix actually written. for (auto& [breakpointAddress, breakpoint] : m_breakpoints) { if (!breakpoint.inserted) @@ -483,12 +547,24 @@ namespace BinaryNinjaDebugger { uint64_t byteAddress = breakpointAddress + i; if (byteAddress >= address && byteAddress - address < size) { - breakpoint.original[i] = data[byteAddress - address]; data[byteAddress - address] = m_arch->breakpointInstruction[i]; } } } - return RawWriteMemory(address, data.data(), size); + size_t written = 0; + bool success = RawWriteMemory(address, data.data(), size, &written); + for (auto& [breakpointAddress, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + for (size_t i = 0; i < breakpoint.original.size(); i++) + { + uint64_t byteAddress = breakpointAddress + i; + if (byteAddress >= address && byteAddress - address < written) + breakpoint.original[i] = ((const uint8_t*)buffer)[byteAddress - address]; + } + } + return success; } @@ -499,17 +575,20 @@ namespace BinaryNinjaDebugger { std::string line; while (std::getline(file, line)) { - unsigned long long start, end, offset; + unsigned long long start, end, offset, inode; + char device[32] = {}; char permissions[8] = {}; int consumed = 0; - if (sscanf(line.c_str(), "%llx-%llx %7s %llx %*s %*s %n", &start, &end, permissions, &offset, &consumed) - < 4) + if (sscanf(line.c_str(), "%llx-%llx %7s %llx %31s %llu %n", &start, &end, permissions, &offset, device, &inode, &consumed) + < 6) continue; MapEntry entry; entry.start = start; entry.end = end; entry.offset = offset; + entry.device = device; + entry.inode = inode; entry.read = permissions[0] == 'r'; entry.write = permissions[1] == 'w'; entry.execute = permissions[2] == 'x'; @@ -627,6 +706,8 @@ namespace BinaryNinjaDebugger { { { std::lock_guard lock(m_core->mutex); + if (m_core->stop) + return; if (event.type == OutputEvent) { m_core->pendingOutput += event.data.size(); @@ -646,6 +727,22 @@ namespace BinaryNinjaDebugger { } + void PtraceEngine::StopEventDelivery() + { + if (m_eventThread.joinable() && m_eventThread.get_id() == std::this_thread::get_id()) + throw std::logic_error("cannot join event delivery from its own callback"); + { + std::lock_guard lock(m_core->mutex); + m_core->stop = true; + m_core->handler.reset(); + m_core->events.clear(); + } + m_core->cv.notify_all(); + if (m_eventThread.joinable()) + m_eventThread.join(); + } + + void PtraceEngine::PostTask(std::function task) { Event event; @@ -662,6 +759,8 @@ namespace BinaryNinjaDebugger { for (const auto& [tid, info] : m_threads) m_publishedThreads.push_back(tid); m_publishedRunning = m_running; + if (!m_running) + m_interruptWanted = false; } @@ -934,6 +1033,15 @@ namespace BinaryNinjaDebugger { if (pid == 0) { + // exec preserves ignored dispositions. Launch the inferior independently of the host's signal policy. + struct sigaction action {}; + action.sa_handler = SIG_DFL; + sigemptyset(&action.sa_mask); + for (int signal = 1; signal < NSIG; signal++) + { + if (signal != SIGKILL && signal != SIGSTOP) + sigaction(signal, &action, nullptr); + } sigset_t noSignals; sigemptyset(&noSignals); sigprocmask(SIG_SETMASK, &noSignals, nullptr); @@ -1281,16 +1389,7 @@ namespace BinaryNinjaDebugger { { std::deque> tasks; { - std::unique_lock lock(m_taskMutex); - if (!m_running) - { - m_taskCv.wait(lock, [this] { return m_shutdown || !m_tasks.empty(); }); - } - else if (m_tasks.empty() && idle >= 20) - { - auto delay = std::chrono::microseconds(50 << std::min(idle - 20, 6)); - m_taskCv.wait_for(lock, delay, [this] { return m_shutdown || !m_tasks.empty(); }); - } + std::lock_guard lock(m_taskMutex); if (m_shutdown) break; tasks.swap(m_tasks); @@ -1301,51 +1400,151 @@ namespace BinaryNinjaDebugger { if (m_done) break; - if (m_running) - { - if (PollThreads()) - idle = 0; - else if (++idle < 20) - sched_yield(); - } + bool progressed = PollThreads(); + idle = progressed || !m_running ? 0 : idle + 1; + if (!m_done && !m_strandedChildren.empty()) + RetryStrandedChildren(); + + if (!m_running || idle >= spinPolls) + WaitForWork(idle); + else if (!progressed) + sched_yield(); } + CloseExitWatches(); std::lock_guard lock(m_taskMutex); m_tracerStop = true; m_tasks.clear(); } - bool PtraceEngine::PollThreads() + void PtraceEngine::WakeTracer() { - std::vector tids; + uint64_t one = 1; + [[maybe_unused]] auto ignored = write(m_wakeFd, &one, sizeof(one)); + } + + + void PtraceEngine::WaitForWork(int idle) + { + bool everyExitWatched = UpdateExitWatches(); + + auto timeout = waitForever; + if (m_running) + timeout = std::chrono::microseconds(50 << std::min(idle - spinPolls, maxBackoffShift)); + if (!m_strandedChildren.empty()) + timeout = std::min(timeout, strandedRetryInterval); + if (!everyExitWatched) + timeout = std::min(timeout, unwatchedExitPollInterval); + + std::vector fds {{m_wakeFd, POLLIN, 0}}; + for (const auto& [tid, fd] : m_exitWatches) + fds.push_back({fd, POLLIN, 0}); + + timespec limit {}; + if (timeout != waitForever) + { + limit.tv_sec = std::chrono::duration_cast(timeout).count(); + limit.tv_nsec = (timeout % std::chrono::seconds(1)).count(); + } + ppoll(fds.data(), fds.size(), timeout == waitForever ? nullptr : &limit, nullptr); + + if (fds[0].revents & POLLIN) + { + uint64_t count = 0; + [[maybe_unused]] auto ignored = read(m_wakeFd, &count, sizeof(count)); + } + } + + + static int OpenExitWatch(pid_t tid, bool leader) + { + // The leader's descriptor fires only once the other threads are collected + return (int)syscall(SYS_pidfd_open, tid, leader ? 0 : pidfdThreadFlag); + } + + + bool PtraceEngine::UpdateExitWatches() + { + for (auto it = m_exitWatches.begin(); it != m_exitWatches.end();) + { + if (m_threads.count(it->first)) + { + ++it; + continue; + } + if (it->second >= 0) + close(it->second); + it = m_exitWatches.erase(it); + } + + bool everyThreadWatched = true; for (const auto& [tid, info] : m_threads) { - if (!info.stopped) - tids.push_back(tid); + auto watch = m_exitWatches.find(tid); + if (watch == m_exitWatches.end()) + watch = m_exitWatches.emplace(tid, OpenExitWatch(tid, tid == m_pid)).first; + everyThreadWatched &= watch->second >= 0; + } + return everyThreadWatched; + } + + + void PtraceEngine::CloseExitWatches() + { + for (const auto& [tid, fd] : m_exitWatches) + { + if (fd >= 0) + close(fd); } + m_exitWatches.clear(); + } + + + static bool AnyTaskTerminated() + { + siginfo_t any {}; + return waitid(P_ALL, 0, &any, WEXITED | WNOHANG | WNOWAIT | __WALL) != 0 || any.si_pid != 0; + } + + bool PtraceEngine::PollThreads() + { + std::vector tids; + for (const auto& [tid, info] : m_threads) + tids.push_back(tid); + if (std::erase(tids, m_pid) > 0) + tids.push_back(m_pid); + + bool anyTaskTerminated = AnyTaskTerminated(); bool progressed = false; for (pid_t tid : tids) { - if (!m_running || m_done) + if (m_done) break; - if (m_threads.find(tid) == m_threads.end()) + auto it = m_threads.find(tid); + if (it == m_threads.end()) continue; + bool waitedFor = m_running && !it->second.stopped; + if (!waitedFor) + { + siginfo_t death {}; + if (!anyTaskTerminated + || waitid(P_PID, tid, &death, WEXITED | WNOHANG | WNOWAIT | __WALL) != 0 || death.si_pid == 0) + continue; + } + int status = 0; pid_t result = waitpid(tid, &status, __WALL | WNOHANG); if (result == 0) continue; + if (result < 0 && errno == EINTR) + continue; progressed = true; if (result < 0) - { - if (errno == EINTR) - continue; - // The thread is gone without a status we can read status = 0; - } HandleStatus(tid, status); } return progressed; @@ -1447,7 +1646,7 @@ namespace BinaryNinjaDebugger { // Architectures report a CPU breakpoint as TRAP_BRKPT or, notably for x86 int3, SI_KERNEL. Only those codes may // be matched by PC: a user-generated SIGTRAP can stop at the same PC by coincidence. bool breakpointCode = !haveInfo || code == TRAP_BRKPT || code == SI_KERNEL; - bool unownedTrapInstruction = haveInfo && code == TRAP_BRKPT; + bool ownsTrap = !(haveInfo && code == TRAP_BRKPT); uint64_t pc = 0; if (breakpointCode && m_arch && !m_arch->breakpointInstruction.empty() && ReadPc(tid, pc) && pc >= m_arch->breakpointPcAdjust) @@ -1481,11 +1680,12 @@ namespace BinaryNinjaDebugger { // SI_KERNEL is also used for some debugger-requested traps. It is target-owned when the instruction at the // adjusted PC is the architecture's trap opcode. TRAP_BRKPT itself is already definitive. std::vector instruction(m_arch->breakpointInstruction.size()); - unownedTrapInstruction |= code == SI_KERNEL && RawReadMemory(address, instruction.data(), instruction.size()) - && instruction == m_arch->breakpointInstruction; + if (code == SI_KERNEL && RawReadMemory(address, instruction.data(), instruction.size()) + && instruction == m_arch->breakpointInstruction) + ownsTrap = false; // The same trap can come from another encoding, which ends at the PC and not one byte before it - if (code == SI_KERNEL && !unownedTrapInstruction) + if (code == SI_KERNEL && ownsTrap) { for (const auto& encoding : m_arch->trapInstructions) { @@ -1493,16 +1693,26 @@ namespace BinaryNinjaDebugger { if (pc >= encoding.size() && RawReadMemory(pc - encoding.size(), found.data(), found.size()) && found == encoding) { - unownedTrapInstruction = true; + ownsTrap = false; break; } } } } + // x86 reports the step that ends after a system call as TRAP_BRKPT, not TRAP_TRACE + if (haveInfo && code == TRAP_BRKPT && info.stepping && !ownsTrap && m_arch + && !m_arch->breakpointInstruction.empty() && pc >= m_arch->breakpointPcAdjust) + { + std::vector before(m_arch->breakpointInstruction.size()); + if (RawReadMemory(pc - m_arch->breakpointPcAdjust, before.data(), before.size()) + && before != m_arch->breakpointInstruction) + ownsTrap = true; + } + // Some kernels report a requested step around a syscall with a generic kernel trap rather than TRAP_TRACE. Preserve // that compatibility fallback, but never let it consume a trap instruction or an explicitly sent signal. - if (info.stepping && !unownedTrapInstruction) + if (info.stepping && ownsTrap) { result.stepTrap = true; result.trapOrigin = TrapOrigin::SingleStep; @@ -1541,7 +1751,7 @@ namespace BinaryNinjaDebugger { if (event == PTRACE_EVENT_CLONE) { unsigned long newTid = 0; - if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &newTid) != 0 || newTid == 0) + if (!ReadNewTaskId(tid, newTid)) { QueueError("thread " + std::to_string(tid) + " made a new task, and its id could not be read, so the new task is " "not managed and stays stopped"); @@ -1566,7 +1776,7 @@ namespace BinaryNinjaDebugger { if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK) { unsigned long child = 0; - if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &child) != 0 || child == 0) + if (!ReadNewTaskId(tid, child)) { QueueError("thread " + std::to_string(tid) + " made a child process, and its id could not be read, so the child is " "not let go of and stays stopped"); @@ -1607,15 +1817,13 @@ namespace BinaryNinjaDebugger { + ", which will not stop at them"); return result; } + siginfo_t sender {}; + bool ours = ptrace(PTRACE_GETSIGINFO, tid, nullptr, &sender) == 0 + && sender.si_pid == getpid() && sender.si_code == SI_QUEUE && sender.si_value.sival_ptr == this; if (info.expectedStops > 0) + info.expectedStops = 0; + if (ours) { - info.expectedStops--; - return result; - } - if (m_interruptInFlight > 0) - { - m_interruptInFlight--; - // The pause may have been given by another stop since, and then this signal is only left over if (m_interruptWanted.exchange(false)) { RestoreBreakpoints(tid, true); @@ -1624,6 +1832,12 @@ namespace BinaryNinjaDebugger { } return result; } + // Continue from an externally requested stop resumes execution. Do not reinject + // SIGSTOP and enter an unmodelled job-control group stop. + RestoreBreakpoints(tid, true); + result.kind = StopKind::Report; + result.signal = SIGSTOP; + return result; } if (ShouldAutoContinueSignal(signal)) @@ -1652,6 +1866,12 @@ namespace BinaryNinjaDebugger { } + char PtraceEngine::TaskState(pid_t tid) const + { + return ReadProcStatus("/proc/" + std::to_string(m_pid) + "/task/" + std::to_string(tid) + "/status").state; + } + + bool PtraceEngine::ResumeThread(pid_t tid) { auto& info = m_threads[tid]; @@ -1677,8 +1897,15 @@ namespace BinaryNinjaDebugger { request = PTRACE_SYSCALL; else if (m_syscallMode == SyscallMode::Emulate) request = PTRACE_SYSEMU; - if (ptrace((__ptrace_request)request, tid, nullptr, (void*)(intptr_t)signal) != 0 && errno != ESRCH) - return false; + if (ptrace((__ptrace_request)request, tid, nullptr, (void*)(intptr_t)signal) != 0) + { + if (errno != ESRCH) + return false; + // ESRCH is also the answer for a thread that is still stopped, which was not resumed + char state = TaskState(tid); + if (state == 't' || state == 'T') + return false; + } // Only commit the transition after the kernel accepted it. Otherwise a stopped thread would disappear from // future resume attempts, and a pending signal could be lost. @@ -1862,6 +2089,49 @@ namespace BinaryNinjaDebugger { } + bool PtraceEngine::ReadNewTaskId(pid_t tid, unsigned long& id) + { + for (int attempt = 0; attempt < 3; attempt++) + { + id = 0; + if (ptrace(PTRACE_GETEVENTMSG, tid, nullptr, &id) == 0 && id != 0) + return true; + } + + pid_t me = (pid_t)syscall(SYS_gettid); + auto isTheNewTask = [&](pid_t task, const std::string& path) { + if (m_threads.count(task)) + return false; + ProcStatus status = ReadProcStatus(path); + return status.tracer == me && (status.state == 't' || status.state == 'T'); + }; + + std::vector found; + std::error_code error; + for (const auto& entry : std::filesystem::directory_iterator("/proc/" + std::to_string(m_pid) + "/task", error)) + { + pid_t task = atoi(entry.path().filename().c_str()); + if (task > 0 && isTheNewTask(task, entry.path().string() + "/status")) + found.push_back(task); + } + for (const auto& entry : std::filesystem::directory_iterator("/proc", error)) + { + pid_t process = atoi(entry.path().filename().c_str()); + if (process <= 0 || process == m_pid || std::find(found.begin(), found.end(), process) != found.end()) + continue; + if (ReadProcStatus(entry.path().string() + "/status").parent == m_pid && isTheNewTask(process, entry.path().string() + "/status")) + found.push_back(process); + } + if (found.size() != 1) + return false; + id = (unsigned long)found[0]; + QueueNote(fmt::format("the kernel would not say which task thread {} made, so it was taken to be {}, the only " + "stopped task of the target that was not known", + tid, found[0])); + return true; + } + + // A child of the target starts out as a copy of it, breakpoints included, and it is not ours to debug. So the // breakpoints come out of it, and it is let go. void PtraceEngine::HandleFork(pid_t child, bool sharedMemory) @@ -1878,67 +2148,118 @@ namespace BinaryNinjaDebugger { if (waited == WaitResult::Gone || !WIFSTOPPED(status)) return; + if (sharedMemory) { std::lock_guard lock(m_breakpointMutex); - if (sharedMemory) + for (auto& [address, breakpoint] : m_breakpoints) { - // There is only one memory, so the breakpoints are out of the target for as long as the child uses it - for (auto& [address, breakpoint] : m_breakpoints) - { - if (!breakpoint.inserted) - continue; + if (!breakpoint.inserted) + continue; - RawWriteMemory(address, breakpoint.original.data(), breakpoint.original.size()); - breakpoint.inserted = false; - breakpoint.suspended = true; + if (!RawWriteMemory(address, breakpoint.original.data(), breakpoint.original.size())) + { + QueueError(fmt::format("the breakpoint at 0x{:x} could not be taken out of the memory that the child " + "of vfork shares, so the child can run into it", + address)); + continue; } - m_vforkPending++; + breakpoint.inserted = false; + breakpoint.suspended = true; } - else - { - int fd = open(("/proc/" + std::to_string(child) + "/mem").c_str(), O_RDWR | O_CLOEXEC); - if (fd >= 0) - { - for (const auto& [address, breakpoint] : m_breakpoints) - { - { - if (!breakpoint.inserted) - continue; + m_vforkPending++; + } - // Best effort: a child that cannot be written to is simply let go - [[maybe_unused]] auto written = - pwrite(fd, breakpoint.original.data(), breakpoint.original.size(), address); - } - } - close(fd); + ChildMemory memory = sharedMemory ? ChildMemory::Shared : ChildMemory::Copied; + if (ReleaseChild(child, memory)) + return; - // A clone with CLONE_VM that is not a thread shares the memory of the target, and is not told by a - // vfork event when it is done with it. What was written to the child is then what is in the target now, - // and the breakpoints are put back. - for (const auto& [address, breakpoint] : m_breakpoints) - { - if (!breakpoint.inserted) - continue; + m_strandedChildren.push_back({child, memory, std::chrono::steady_clock::now() + strandedGiveUpAfter}); + } - std::vector now(breakpoint.original.size()); - if (RawReadMemory(address, now.data(), now.size()) && now == breakpoint.original) - { - for (auto& [otherAddress, other] : m_breakpoints) - { - if (other.inserted) - RawWriteMemory(otherAddress, m_arch->breakpointInstruction.data(), - m_arch->breakpointInstruction.size()); - } - QueueNote("a process made with clone shares the memory of the target, so it can run into the " - "breakpoints, which stay where they are"); - } - break; - } + + bool PtraceEngine::CleanForkChild(pid_t child) + { + std::lock_guard lock(m_breakpointMutex); + int fd = open(("/proc/" + std::to_string(child) + "/mem").c_str(), O_RDWR | O_CLOEXEC); + if (fd < 0) + return errno == ENOENT; // gone, so there is nothing to clean + + bool clean = true; + for (const auto& [address, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + auto written = pwrite(fd, breakpoint.original.data(), breakpoint.original.size(), address); + clean &= written == (ssize_t)breakpoint.original.size(); + } + close(fd); + if (!clean) + return false; + + for (const auto& [address, breakpoint] : m_breakpoints) + { + if (!breakpoint.inserted) + continue; + + std::vector now(breakpoint.original.size()); + if (RawReadMemory(address, now.data(), now.size()) && now == breakpoint.original) + { + for (auto& [otherAddress, other] : m_breakpoints) + { + if (other.inserted) + RawWriteMemory(otherAddress, m_arch->breakpointInstruction.data(), + m_arch->breakpointInstruction.size()); } + QueueNote("a process made with clone shares the memory of the target, so it can run into the " + "breakpoints, which stay where they are"); } + break; } + return true; + } + + + bool PtraceEngine::ReleaseChild(pid_t child, ChildMemory memory) + { + if (memory == ChildMemory::Copied && !CleanForkChild(child)) + return false; + if (ptrace(PTRACE_DETACH, child, nullptr, nullptr) == 0) + return true; + // ESRCH from a child that is gone is a release, from one that is still stopped it is not + if (errno != ESRCH) + return false; + char state = ReadProcStatus("/proc/" + std::to_string(child) + "/status").state; + return state != 't' && state != 'T'; + } + + + void PtraceEngine::RetryStrandedChildren() + { + auto now = std::chrono::steady_clock::now(); + if (now < m_strandedNextTry) + return; + m_strandedNextTry = now + strandedRetryInterval; + for (auto it = m_strandedChildren.begin(); it != m_strandedChildren.end();) + { + if (ReleaseChild(it->pid, it->memory)) + { + it = m_strandedChildren.erase(it); + continue; + } + if (now < it->giveUpAt) + { + ++it; + continue; + } - ptrace(PTRACE_DETACH, child, nullptr, nullptr); + QueueError(fmt::format("process {}, a child of the target, could not be let go of{}, and was ended so that its " + "parent does not wait for it for ever", + it->pid, it->memory == ChildMemory::Copied ? " (or cleaned of the breakpoints of the debugger)" : "")); + kill(it->pid, SIGKILL); + int status = 0; + WaitForThread(it->pid, status, std::chrono::milliseconds(200)); + it = m_strandedChildren.erase(it); + } } @@ -2042,7 +2363,8 @@ namespace BinaryNinjaDebugger { if (steppingOver && !m_done) { m_stepOverTid = -1; - StartNextStepOver(); + if (!StartNextStepOver()) + ReportResumeFailure(tid, ResumeFailure::AfterSteppedOverThreadWentAway); } break; case StopKind::Internal: @@ -2050,7 +2372,10 @@ namespace BinaryNinjaDebugger { auto it = m_threads.find(tid); if (it != m_threads.end() && it->second.stopped && ((m_continueMode && m_stepOverTid < 0) || it->second.stepping)) - ResumeThread(tid); + { + if (!ResumeThread(tid)) + ReportResumeFailure(tid, ResumeFailure::AfterInternalStop); + } break; } case StopKind::Report: @@ -2058,7 +2383,8 @@ namespace BinaryNinjaDebugger { { m_threads[tid].stepping = false; m_stepOverTid = -1; - StartNextStepOver(); + if (!StartNextStepOver()) + ReportResumeFailure(tid, ResumeFailure::AfterBreakpointStepOver); break; } if (steppingOver) @@ -2111,8 +2437,8 @@ namespace BinaryNinjaDebugger { auto& info = m_threads[next]; if (!info.awaitingInitialStop && info.expectedStops == 0) { - syscall(SYS_tgkill, m_pid, next, SIGSTOP); - info.expectedStops++; + if (SendStop(next)) + info.expectedStops = 1; } int status = 0; @@ -2129,6 +2455,44 @@ namespace BinaryNinjaDebugger { } + const char* PtraceEngine::DescribeResumeFailure(ResumeFailure failure) + { + switch (failure) + { + case ResumeFailure::AfterSteppedOverThreadWentAway: + return "after the thread that was stepped over went away"; + case ResumeFailure::AfterInternalStop: + return "after an internal stop"; + case ResumeFailure::AfterBreakpointStepOver: + return "after a thread stepped over a breakpoint"; + } + return ""; + } + + + void PtraceEngine::ReportResumeFailure(pid_t tid, ResumeFailure failure) + { + if (m_done) + return; + bool stoppedThread = false; + for (const auto& [id, info] : m_threads) + stoppedThread |= info.stopped; + if (!stoppedThread) + return; + + QueueError(fmt::format("thread {} could not be resumed {}, so the target is left stopped", tid, DescribeResumeFailure(failure))); + m_stepOverTid = -1; + m_stepOverQueue.clear(); + StopAll(); + if (m_done) + return; + ThreadStatusResult stop; + stop.kind = StopKind::Report; + stop.tid = tid; + ReportStopped(tid, stop); + } + + void PtraceEngine::ReportStopped(pid_t tid, const ThreadStatusResult& stop) { Event event; @@ -2157,8 +2521,7 @@ namespace BinaryNinjaDebugger { allStopped &= info.stopped; if (allStopped) m_recentlyRemoved.clear(); - // Any stop is a pause, so a request for one that has not been seen yet is answered - m_interruptWanted = false; + // Publishing the stopped state also satisfies pending pauses under the same lock used by Interrupt. auto& info = m_threads[tid]; info.atReportedStop = ReadPc(tid, info.reportedPc); diff --git a/core/adapters/ptrace/ptraceengine.h b/core/adapters/ptrace/ptraceengine.h index df18b2b7..a823c2a1 100644 --- a/core/adapters/ptrace/ptraceengine.h +++ b/core/adapters/ptrace/ptraceengine.h @@ -104,6 +104,8 @@ namespace BinaryNinjaDebugger { bool shared = false; uint64_t offset = 0; std::string path; + std::string device; + uint64_t inode = 0; }; // A stop at a system call, as PTRACE_GET_SYSCALL_INFO tells it @@ -285,7 +287,7 @@ namespace BinaryNinjaDebugger { std::thread m_ioThread; std::mutex m_taskMutex; - std::condition_variable m_taskCv; + int m_wakeFd = -1; std::deque> m_tasks; bool m_tracerStop = false; bool m_shutdown = false; @@ -314,10 +316,8 @@ namespace BinaryNinjaDebugger { std::shared_ptr m_detachedExit; std::vector m_publishedThreads; std::atomic m_publishedRunning {false}; - // An interrupt is a SIGSTOP that we send. It can be asked for again before the first one has been seen, so the - // signals that are on their way are counted, and whether a pause is still wanted is kept apart from that. + // A pause is satisfied by any reported stop. SIGSTOP requests may coalesce. std::atomic m_interruptWanted {false}; - std::atomic m_interruptInFlight {0}; std::atomic m_debugSignalHandlers {false}; // How long a wait for a thread lasts before it is given up on, in milliseconds std::atomic m_waitTimeoutMs {5000}; @@ -353,11 +353,19 @@ namespace BinaryNinjaDebugger { void StopIo(); void DrainOutput(char* buffer, size_t size); + bool StartTracer(std::string& error); + void WakeTracer(); + void WaitForWork(int idle); bool PollThreads(); + std::map m_exitWatches; + bool UpdateExitWatches(); + void CloseExitWatches(); void HandleStatus(pid_t tid, int status); // Consumes a waitpid status, updates thread and breakpoint state, and decides whether to report a stop. ThreadStatusResult ProcessThreadStatus(pid_t tid, int status); bool ResumeThread(pid_t tid); + char TaskState(pid_t tid) const; + bool SendStop(pid_t tid = 0); bool HasSignalHandler(int signal); bool ProcessTrap(pid_t tid, ThreadInfo& info, ThreadStatusResult& result); bool RawGetRegisterSet(pid_t tid, int regset, std::vector& data); @@ -365,7 +373,7 @@ namespace BinaryNinjaDebugger { bool ReadPc(pid_t tid, uint64_t& pc); bool WritePc(pid_t tid, uint64_t pc); bool RawReadMemory(uint64_t address, void* buffer, size_t size); - bool RawWriteMemory(uint64_t address, const void* buffer, size_t size); + bool RawWriteMemory(uint64_t address, const void* buffer, size_t size, size_t* written = nullptr); bool HasBreakpointAt(uint64_t address); bool NeedsStepOver(pid_t tid, const ThreadInfo& info); bool SuspendBreakpoints(pid_t tid, uint64_t address); @@ -374,6 +382,24 @@ namespace BinaryNinjaDebugger { bool ResumeAll(); bool ApplyHardwareToThread(pid_t tid); void HandleFork(pid_t child, bool sharedMemory); + enum class ChildMemory + { + Shared, + Copied + }; + + bool ReleaseChild(pid_t child, ChildMemory memory); + bool ReadNewTaskId(pid_t tid, unsigned long& id); + bool CleanForkChild(pid_t child); + struct StrandedChild + { + pid_t pid; + ChildMemory memory; + std::chrono::steady_clock::time_point giveUpAt; + }; + std::vector m_strandedChildren; + std::chrono::steady_clock::time_point m_strandedNextTry {}; + void RetryStrandedChildren(); ThreadStatusResult HandleExec(pid_t tid); void ResumeBreakpointsAfterVfork(); bool RemoveAllBreakpoints(); @@ -408,6 +434,15 @@ namespace BinaryNinjaDebugger { pid_t ThreadGroupOf(pid_t tid); // Finalizes the debugger state and emits the stopped event after StopAll has collected the other threads. void ReportStopped(pid_t tid, const ThreadStatusResult& stop); + enum class ResumeFailure + { + AfterSteppedOverThreadWentAway, + AfterInternalStop, + AfterBreakpointStepOver + }; + + static const char* DescribeResumeFailure(ResumeFailure failure); + void ReportResumeFailure(pid_t tid, ResumeFailure failure); void ReportExited(int status); bool DoResume(bool step, pid_t tid, SyscallMode mode = SyscallMode::None); @@ -447,6 +482,9 @@ namespace BinaryNinjaDebugger { // Runs a function on the thread that delivers the events, after everything that was posted before it. That // thread is not tied up by the caller, so it is the place for work that must not run under the caller's locks. void PostTask(std::function task); + // Stops callback/task admission and joins delivery while the tracer remains usable. + // Must be called outside the event thread and outside locks that a callback may acquire. + void StopEventDelivery(); // How long the engine waits for a thread to stop after it was asked to, to die after it was killed, and so on, // before it goes on without it. A thread in uninterruptible sleep, on NFS or FUSE for example, does neither until diff --git a/core/adapters/ptrace/ptracemodule.cpp b/core/adapters/ptrace/ptracemodule.cpp index 259d2923..b9e88d8a 100644 --- a/core/adapters/ptrace/ptracemodule.cpp +++ b/core/adapters/ptrace/ptracemodule.cpp @@ -19,6 +19,7 @@ limitations under the License. #include #include #include +#include namespace BinaryNinjaDebugger { @@ -36,7 +37,7 @@ namespace BinaryNinjaDebugger { std::vector modules; // The module of each path that is still being extended - std::map open; + std::map, size_t> open; for (size_t i = 0; i < sorted.size(); i++) { @@ -44,8 +45,12 @@ namespace BinaryNinjaDebugger { if (map.path.empty() || map.path[0] != '/') continue; - auto it = open.find(map.path); - if (it != open.end()) + // An offset-zero ELF mapping starts another load instance, even when its path matches + // a nearby instance. Never absorb its header mapping into the preceding module. + bool startsInstance = map.offset == 0 && isElf(map.start); + auto identity = std::make_tuple(map.path, map.device, map.inode); + auto it = open.find(identity); + if (!startsInstance && it != open.end()) { auto& module = modules[it->second]; uint64_t moduleEnd = module.base + module.size; @@ -57,14 +62,14 @@ namespace BinaryNinjaDebugger { } // A module begins where its file is mapped from the start - if (map.offset != 0 || !isElf(map.start)) + if (!startsInstance) continue; PtraceModuleInfo module; module.path = map.path; module.base = map.start; module.size = map.end - map.start; - open[map.path] = modules.size(); + open[identity] = modules.size(); modules.push_back(module); } diff --git a/core/adapters/ptrace/ptracestep.cpp b/core/adapters/ptrace/ptracestep.cpp index ba24f90d..2b9e35c9 100644 --- a/core/adapters/ptrace/ptracestep.cpp +++ b/core/adapters/ptrace/ptracestep.cpp @@ -24,12 +24,17 @@ namespace BinaryNinjaDebugger { {} - void PtraceStepper::EndStep() + bool PtraceStepper::EndStep() { - for (uint64_t address : m_addresses) - m_release(address); - m_addresses.clear(); - m_mode = Mode::None; + for (auto it = m_addresses.begin(); it != m_addresses.end();) + { + if (m_release(*it)) + it = m_addresses.erase(it); + else + ++it; + } + m_mode = m_addresses.empty() ? Mode::None : Mode::CleanupPending; + return m_addresses.empty(); } @@ -40,17 +45,26 @@ namespace BinaryNinjaDebugger { } - void PtraceStepper::Cancel() + bool PtraceStepper::Cancel() { std::lock_guard lock(m_mutex); - EndStep(); + return EndStep(); + } + + + void PtraceStepper::Discard() + { + std::lock_guard lock(m_mutex); + m_addresses.clear(); + m_mode = Mode::None; } bool PtraceStepper::StepOver(uint32_t tid, uint64_t pc, uint64_t sp, size_t callLength, size_t wordSize) { std::lock_guard lock(m_mutex); - EndStep(); + if (!EndStep()) + return false; if (callLength == 0) return m_engine.Resume(true, tid); @@ -75,7 +89,8 @@ namespace BinaryNinjaDebugger { uint64_t returnAddress, uint64_t returnSp) { std::lock_guard lock(m_mutex); - EndStep(); + if (!EndStep()) + return false; // Already at the instruction that returns, so the return is the next step if (std::find(returnSites.begin(), returnSites.end(), pc) != returnSites.end()) @@ -127,6 +142,9 @@ namespace BinaryNinjaDebugger { if (m_mode == Mode::None) return Result::Ignored; + if (m_mode == Mode::CleanupPending) + return EndStep() ? Result::Ignored : Result::Failed; + if (m_mode == Mode::FinalStep) { bool stepped = event.tid == m_tid && event.singleStep && !event.breakpoint; @@ -139,8 +157,7 @@ namespace BinaryNinjaDebugger { bool atOurs = event.breakpoint && m_addresses.count(pc); if (!atOurs || userBreakpoint) { - EndStep(); - return Result::Ignored; + return EndStep() ? Result::Ignored : Result::Failed; } if (event.tid != m_tid || sp < m_minSp) @@ -149,18 +166,17 @@ namespace BinaryNinjaDebugger { if (m_engine.Resume(false, 0)) return Result::Consumed; - EndStep(); - return Result::Ignored; + return EndStep() ? Result::Ignored : Result::Failed; } if (m_mode == Mode::ReturnAddress) { - EndStep(); - return Result::Finished; + return EndStep() ? Result::Finished : Result::Failed; } // At an instruction that returns: it takes one step to be out - EndStep(); + if (!EndStep()) + return Result::Failed; m_mode = Mode::FinalStep; if (m_engine.Resume(true, m_tid)) return Result::Consumed; diff --git a/core/adapters/ptrace/ptracestep.h b/core/adapters/ptrace/ptracestep.h index 48c75a92..6bfa57c3 100644 --- a/core/adapters/ptrace/ptracestep.h +++ b/core/adapters/ptrace/ptracestep.h @@ -36,7 +36,8 @@ namespace BinaryNinjaDebugger { ReturnAddress, // Run to the instructions that return from the function, and then step once more to do the return ReturnSites, - FinalStep + FinalStep, + CleanupPending }; using BreakpointFunction = std::function; @@ -51,7 +52,7 @@ namespace BinaryNinjaDebugger { uint64_t m_minSp = 0; std::set m_addresses; - void EndStep(); + bool EndStep(); public: enum class Result @@ -61,7 +62,8 @@ namespace BinaryNinjaDebugger { // The stop was part of the step, which goes on Consumed, // The step is done, and this stop is where it ended - Finished + Finished, + Failed }; // `acquire` and `release` place and remove the breakpoints of a step. They may be shared with other users of @@ -84,6 +86,8 @@ namespace BinaryNinjaDebugger { Result OnStop(const PtraceEngine::Event& event, uint64_t pc, uint64_t sp, bool userBreakpoint); bool IsActive(); - void Cancel(); + bool Cancel(); + // The engine has already discarded the old target's breakpoint state after exec, exit or detach. + void Discard(); }; } // namespace BinaryNinjaDebugger diff --git a/core/debuggerstate.cpp b/core/debuggerstate.cpp index 51321204..4b5076e1 100644 --- a/core/debuggerstate.cpp +++ b/core/debuggerstate.cpp @@ -512,7 +512,15 @@ uint64_t DebuggerModules::RelativeAddressToAbsolute(const ModuleNameAndOffset& r { if (!relativeAddress.module.empty()) { - for (const DebugModule& module : GetAllModules()) + const std::vector modules = GetAllModules(); + // A unique short name selects one load instance of a library that is mapped more than once + // (for example through dlmopen). Only then fall back to the first module sharing the base name. + for (const DebugModule& module : modules) + { + if (!module.m_short_name.empty() && module.m_short_name == relativeAddress.module) + return module.m_address + relativeAddress.offset; + } + for (const DebugModule& module : modules) { if (module.IsSameBaseModule(relativeAddress.module)) { diff --git a/test/debugger_test.py b/test/debugger_test.py index f3520a4c..cdf8bfac 100644 --- a/test/debugger_test.py +++ b/test/debugger_test.py @@ -15,9 +15,9 @@ from binaryninja import load, Settings from binaryninja.enums import SettingsScope try: - from debugger import DebuggerController, DebugStopReason, DebugBreakpointType + from debugger import DebuggerController, DebugStopReason, DebugBreakpointType, DebuggerEventType, ModuleNameAndOffset except: - from binaryninja.debugger import DebuggerController, DebugStopReason, DebugBreakpointType + from binaryninja.debugger import DebuggerController, DebugStopReason, DebugBreakpointType, DebuggerEventType, ModuleNameAndOffset # 'helloworld' -> '{BN_SOURCE_ROOT}\public\debugger\test\binaries\Windows-x64\helloworld.exe' (windows) # 'helloworld' -> '{BN_SOURCE_ROOT}/public/debugger/test/binaries/Darwin/arm64/helloworld' (linux, macOS) @@ -479,7 +479,7 @@ def test_breakpoints_list_and_repr(self): def test_hardware_breakpoint(self): """Test hardware breakpoint add and delete""" - if platform.system() == 'Linux' and self.adapter_type != 'PTRACE': + if platform.system() == 'Linux' and self.adapter_type != 'ptrace_x86/64': self.skipTest('Hardware breakpoints not yet supported on Linux') fpath = name_to_fpath('helloworld', self.arch) bv = load(fpath) @@ -644,7 +644,8 @@ def test_assembly_code(self): self.assertEqual(reason, DebugStopReason.ProcessExited) def test_attach(self): - if platform.system() == 'Linux' and not (self.adapter_type == 'PTRACE' and can_attach_to_unrelated_process()): + can_attach = self.adapter_type == 'ptrace_x86/64' and can_attach_to_unrelated_process() + if platform.system() == 'Linux' and not can_attach: self.skipTest('Cannot attach to pid unless running as root') from attach_test_runner import run_attach_test fpath = name_to_fpath('helloworld_loop', self.arch) @@ -752,6 +753,257 @@ def create_debugger(self, bv): return dbg + def ptrace_fixture(self): + if self.arch != 'x86_64': + self.skipTest('These lifecycle fixtures require a native x86-64 Linux build') + directory = os.environ.get('PTRACE_TEST_BUILD_DIR') + if not directory: + self.skipTest('Set PTRACE_TEST_BUILD_DIR to the standalone ptrace test build') + fixture = os.path.join(directory, 'progs') + self.assertTrue(os.path.isfile(fixture), fixture) + return fixture + + def _step_until_exit_after_marker(self, mode, expected_code=9): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = mode + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + marker = bv.get_symbols_by_name('marker')[0].address + dbg.add_breakpoint(marker) + self.assertEqual(dbg.go_and_wait(20000), DebugStopReason.Breakpoint) + self.assertEqual(dbg.ip, marker) + self.assertGreaterEqual(len(list(dbg.threads)), 2) + for _ in range(2000): + reason = dbg.step_into_and_wait(timeout=20000) + if reason == DebugStopReason.ProcessExited: + break + self.assertIn(reason, [DebugStopReason.SingleStep, DebugStopReason.Breakpoint], f'unexpected stop {reason}') + else: + self.fail('the exit of the target was not reported') + self.assertEqual(dbg.exit_code, expected_code) + + @unittest.skip('Needs the controller teardown synchronization that lands with the core change') + def test_relaunch_after_a_target_that_exits_at_once(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = 'hello' + hogs = [subprocess.Popen(['yes'], stdout=subprocess.DEVNULL) for _ in range(2 * (os.cpu_count() or 4))] + try: + for i in range(250): + reason = dbg.launch_and_wait(20000) + self.assertNotIn(reason, [DebugStopReason.InvalidStatusOrOperation, DebugStopReason.TimedOut], + f'launch {i} was refused') + self.assertEqual(dbg.go_and_wait(20000), DebugStopReason.ProcessExited) + self.assertFalse(dbg.connected, f'the controller is still connected after the exit in cycle {i}') + finally: + for hog in hogs: + hog.kill() + hog.wait() + + @unittest.skip('Needs the controller teardown synchronization that lands with the core change') + def test_pause_after_the_target_exited(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + for _ in range(5): + dbg.cmd_line = 'exitleader' + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + pid = dbg.active_pid + self.assertTrue(dbg.go()) + + def gone(): + try: + return all(open(f'/proc/{pid}/task/{t}/stat').read().rsplit(')', 1)[1].split()[0] in 'ZX' + for t in os.listdir(f'/proc/{pid}/task')) + except OSError: + return True + deadline = time.time() + 20 + while not gone() and time.time() < deadline: + time.sleep(0.01) + self.assertTrue(gone(), 'the target did not exit') + self.assertIn(dbg.pause_and_wait(10000), [DebugStopReason.ProcessExited, DebugStopReason.InvalidStatusOrOperation]) + dbg.quit_and_wait(10000) + + def test_exit_group_by_stepped_leader(self): + self._step_until_exit_after_marker('exitleader') + + def test_exit_group_by_stepped_thread(self): + self._step_until_exit_after_marker('exitthread') + + def test_remove_module_relative_breakpoint(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = 'bploop' + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + try: + self.assertEqual(dbg.go_and_wait(20000), DebugStopReason.SignalUsr1) + pid = dbg.active_pid + marker = bv.get_symbols_by_name('marker')[0].address + module = next(m for m in dbg.modules if os.path.realpath(m.name) == os.path.realpath(dbg.executable_path)) + location = ModuleNameAndOffset(module.short_name, marker - module.address) + + def raw_byte(): + with open(f'/proc/{pid}/mem', 'rb', buffering=0) as memory: + memory.seek(marker) + return memory.read(1) + original = raw_byte() + dbg.add_breakpoint(location) + self.assertEqual(raw_byte(), b'\xcc') + self.assertEqual(dbg.go_and_wait(20000), DebugStopReason.Breakpoint) + self.assertEqual(dbg.ip, marker) + dbg.delete_breakpoint(location) + self.assertEqual(raw_byte(), original, 'the breakpoint byte is still in the target') + self.assertEqual(dbg.go_and_wait(timeout=1500), DebugStopReason.TimedOut, 'the target still stops at the removed breakpoint') + dbg.pause_and_wait(10000) + self.assertEqual(raw_byte(), original) + finally: + dbg.quit_and_wait(10000) + + def test_single_step_through_system_calls(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = 'syscalls' + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + reasons = set() + for _ in range(60000): + reason = dbg.step_into_and_wait(timeout=20000) + if reason == DebugStopReason.ProcessExited: + break + reasons.add(reason) + else: + self.fail('the target did not exit while being stepped') + self.assertTrue(reasons <= {DebugStopReason.SingleStep, DebugStopReason.Breakpoint, DebugStopReason.SignalUsr1}, + f'unexpected stop reasons while stepping: {reasons}') + self.assertNotEqual(dbg.exit_code, 128 + 5, 'the target was killed by a SIGTRAP that the debugger delivered') + + @unittest.skip('Needs the controller teardown synchronization that lands with the core change') + def test_quit_after_queued_resume_operations(self): + # Resume operations queued behind a running Go must not run after Quit is requested. + # Otherwise the second Go resumes the target and Quit never gets to run. + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = 'loop' + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + pid = dbg.active_pid + self.assertEqual(dbg.go_and_wait(timeout=1000), DebugStopReason.TimedOut) + self.assertEqual(dbg.step_return_and_wait(timeout=500), DebugStopReason.TimedOut) + self.assertEqual(dbg.go_and_wait(timeout=500), DebugStopReason.TimedOut) + started = time.time() + dbg.quit_and_wait(10000) + self.assertLess(time.time() - started, 5) + deadline = time.time() + 5 + while os.path.exists(f'/proc/{pid}') and time.time() < deadline: + try: + with open(f'/proc/{pid}/stat') as f: + if f.read().rsplit(')', 1)[1].split()[0] == 'Z': + break + except OSError: + break + time.sleep(0.05) + self.assertFalse(os.path.exists(f'/proc/{pid}') and open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split()[0] != 'Z', + 'target survived quit') + + @unittest.skip('Needs the controller teardown synchronization that lands with the core change') + def test_restart_from_blocked_output_callback(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = 'bploop' + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + old_pid = dbg.active_pid + finished = threading.Event() + outcomes = [] + entered = threading.Event() + + def callback(event): + if event.type != DebuggerEventType.StdoutMessageEventType or entered.is_set(): + return + entered.set() + try: + # The dispatcher stays inside this callback while restart must stop the + # old target. Its engine must continue delivering internal stop/exit events. + dbg.restart() + deadline = time.monotonic() + 5 + while dbg.connected and dbg.active_pid == old_pid and time.monotonic() < deadline: + time.sleep(0.01) + outcomes.append(not dbg.connected or dbg.active_pid != old_pid) + finally: + finished.set() + + handle = dbg.register_event_callback(callback, 'ptrace blocked callback restart') + try: + dbg.go() + self.assertTrue(finished.wait(10), 'Restart could not progress while the public callback was blocked') + self.assertEqual(outcomes, [True]) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + if dbg.connected and dbg.active_pid != old_pid and not dbg.running: + break + time.sleep(0.02) + self.assertTrue(dbg.connected) + self.assertNotEqual(dbg.active_pid, old_pid) + self.assertFalse(dbg.running) + finally: + dbg.remove_event_callback(handle) + dbg.quit_and_wait(10000) + + def test_simultaneous_module_breakpoints(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + dbg.cmd_line = 'multiload' + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + try: + dbg.go_and_wait(20000) + first = [module for module in dbg.modules if module.name.endswith('/libtest.so')] + self.assertEqual(len(first), 1) + self.assertGreater(dbg.load_symbols_for_module(first[0].short_name), 0) + symbol = bv.get_symbols_by_name('libfunc')[0] + address = symbol.address + offset = address - first[0].address + dbg.add_breakpoint(ModuleNameAndOffset(first[0].short_name, offset)) + dbg.go_and_wait(20000) + copies = [module for module in dbg.modules if module.name.endswith('/libtest.so')] + self.assertEqual(len(copies), 2) + self.assertEqual(len({module.short_name for module in copies}), 2) + other = next(module for module in copies if module.address != first[0].address) + dbg.add_breakpoint(ModuleNameAndOffset(other.short_name, offset)) + hits = set() + for _ in range(2): + self.assertEqual(dbg.go_and_wait(20000), DebugStopReason.Breakpoint) + hits.add(dbg.ip) + self.assertEqual(hits, {address, other.address + offset}) + finally: + dbg.quit_and_wait(10000) + + def test_module_breakpoint_name_roundtrip(self): + bv = load(self.ptrace_fixture()) + dbg = self.create_debugger(bv) + self.assertNotIn(dbg.launch_and_wait(20000), [DebugStopReason.ProcessExited, DebugStopReason.InternalError]) + try: + module = next(module for module in dbg.modules if os.path.realpath(module.name) == os.path.realpath(dbg.executable_path)) + address = dbg.ip + 8 + offset = address - module.address + with open(f'/proc/{dbg.active_pid}/mem', 'rb', buffering=0) as memory: + def raw_byte(at=address): + memory.seek(at) + return memory.read(1) + original = raw_byte() + for name in (module.name, module.short_name): + location = ModuleNameAndOffset(name, offset) + survivor = address + 8 + survivor_original = raw_byte(survivor) + dbg.add_breakpoint(location) + dbg.add_breakpoint(survivor) + self.assertEqual(raw_byte(), b'\xcc') + dbg.delete_breakpoint(location) + self.assertEqual(raw_byte(), original) + self.assertEqual(raw_byte(survivor), b'\xcc') + self.assertTrue(dbg.has_breakpoint(survivor)) + dbg.delete_breakpoint(survivor) + self.assertEqual(raw_byte(survivor), survivor_original) + self.assertTrue(dbg.add_hardware_breakpoint(location, DebugBreakpointType.BNHardwareExecuteBreakpoint, 1)) + self.assertTrue(dbg.delete_hardware_breakpoint(location, DebugBreakpointType.BNHardwareExecuteBreakpoint, 1)) + finally: + dbg.quit_and_wait(10000) + def set_redirects(self, dbg, bv, redirects): settings = dbg.adapter_settings self.assertIsNotNone(settings) @@ -895,7 +1147,7 @@ def test_stripped_pie_entry_point(self): class PtraceLinuxx64Test(PtraceAdapterTests, DebuggerAPI): def setUp(self) -> None: self.arch = 'x86_64' - self.adapter_type = 'PTRACE' + self.adapter_type = 'ptrace_x86/64' @unittest.skipUnless(platform.system() == 'Linux', 'The PTRACE adapter only works on Linux') @@ -903,7 +1155,7 @@ def setUp(self) -> None: class PtraceLinuxx86Test(PtraceAdapterTests, DebuggerAPI): def setUp(self) -> None: self.arch = 'x86' - self.adapter_type = 'PTRACE' + self.adapter_type = 'ptrace_x86/64' @unittest.skipIf(platform.machine() not in ['arm64', 'aarch64'], "Only run arm64 tests on arm Mac or Linux") diff --git a/test/ptrace_engine/CMakeLists.txt b/test/ptrace_engine/CMakeLists.txt index 50d463cf..16b340c0 100644 --- a/test/ptrace_engine/CMakeLists.txt +++ b/test/ptrace_engine/CMakeLists.txt @@ -69,6 +69,7 @@ target_link_libraries(ptrace_test_arch PUBLIC ptrace_test_options ptrace_test_in add_library(ptrace_test_engine STATIC "${PTRACE_ENGINE_SRC}/ptraceengine.cpp" "${PTRACE_ENGINE_SRC}/ptracestep.cpp" + "${PTRACE_ENGINE_SRC}/ptracecmdline.cpp" "${PTRACE_ENGINE_SRC}/ptraceelf.cpp" "${PTRACE_ENGINE_SRC}/ptracemodule.cpp" "${PTRACE_ENGINE_SRC}/ptracesignal.cpp" @@ -88,7 +89,7 @@ add_library(ptrace_libtest SHARED libtest.c) set_target_properties(ptrace_libtest PROPERTIES OUTPUT_NAME test LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") -set(PTRACE_TEST_PROGRAMS driver elfcmp) +set(PTRACE_TEST_PROGRAMS driver elfcmp cmdline) foreach(program IN LISTS PTRACE_TEST_PROGRAMS) add_executable(ptrace_${program} ${program}.cpp) set_target_properties(ptrace_${program} PROPERTIES OUTPUT_NAME ${program} @@ -98,6 +99,6 @@ foreach(program IN LISTS PTRACE_TEST_PROGRAMS) endforeach() add_custom_target(ptrace_tests DEPENDS - ptrace_driver ptrace_elfcmp) + ptrace_driver ptrace_elfcmp ptrace_cmdline) file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/ptrace_test_config.json" CONTENT "{\"corpus\":\"${PTRACE_TEST_CORPUS_DIR}\",\"sanitizer\":\"${PTRACE_TEST_SANITIZER}\"}\n") diff --git a/test/ptrace_engine/README.md b/test/ptrace_engine/README.md new file mode 100644 index 00000000..a54f6808 --- /dev/null +++ b/test/ptrace_engine/README.md @@ -0,0 +1,73 @@ +# Ptrace engine tests + +The C++ drivers exercise the engine, architecture tables, ELF reader, modules, +frame walker and stepper without loading Binary Ninja. Pytest runs each named +scenario in its own process and reports individual failures, skips and timeouts. +The adapter and controller integration tests remain in `test/debugger_test.py`. +Production ptrace sources and headers live in `core/adapters/ptrace/`. + +## Build and run on Linux + +Only a C/C++ compiler, CMake, pthreads, binutils, Python and pytest are needed. +Initialize the `vendor/elfio` submodule with `git submodule update --init --recursive`. +The ELF reader uses its header-only C++ API; no system ELF library is required. +`BN_API_PATH` supplies Binary Ninja's API headers and bundled fmt sources; its +runtime and a license are not needed. Initialize the API's submodules as well. +From the debugger checkout: + +```sh +cmake -S test/ptrace_engine -B build-ptrace -G Ninja -DBN_API_PATH=/path/to/binaryninja-api +cmake --build build-ptrace --target ptrace_tests +PTRACE_TEST_BUILD_DIR="$PWD/build-ptrace" python3 -m pytest -v test/ptrace_engine_test.py +``` + +To build alongside the debugger, configure with `-DBUILD_PTRACE_TESTS=ON`. +The drivers are then under `/test/ptrace_engine`, which is the pytest +runner's default for a build directory named `build`. Standalone Linux CI enables +this option and includes the engine regression tests in its existing pytest/JUnit +run. A configured but missing build fails CI rather than silently skipping tests. + +The drivers also accept `--list` or a single scenario name. Unknown names fail. +CMake supplies the fixture paths, so the checkout and build need no special mount +locations. `PTRACE_TEST_CORPUS_DIR` can override the default repository corpus at +`test/binaries/Linux-` used by the `conf_*` cases. + +## Stress and sanitizers + +- Set `PTRACE_TEST_REPEAT=30` to repeat each selected scenario. Use pytest's `-k` + expression to select scenarios such as `stepover` or `attach`. +- Set `PTRACE_TEST_CPUS=0` or `PTRACE_TEST_CPUS=0,1` to constrain the native process + and its inferiors. Choose CPU numbers allowed by the host's affinity mask; + the runner checks them and invokes `taskset` without a shell. +- Set `PTRACE_TEST_TIMEOUT=180` to change the default 120-second per-scenario + deadline. Each supervisor adopts, kills and reaps leftover descendants, + including inferiors that create new sessions. Supervisor regression tests + cover failure propagation and cleanup after both normal exit and timeout. +- Configure a separate build with `-DPTRACE_TEST_SANITIZER=address` for ASan/UBSan, + or `-DPTRACE_TEST_SANITIZER=thread` for TSan. Use the same pytest command with + that build's `PTRACE_TEST_BUILD_DIR`. Instrumentation covers the engine and + drivers, while target fixtures keep their predictable instruction sequences. + Sanitizer errors fail tests even when a runtime is configured to recover. + +Hardware/kernel features that the drivers report as unavailable become pytest +skips. Failing cases remain failures even if they also print a skip message. +The ELF comparison tests check names, addresses, sizes and symbol kinds +against `readelf` for the built fixtures. + +## Optional Docker environment + +Docker supplies Linux on other hosts; no shell runner is required. For example: + +```sh +docker build -t ptrace-test test/ptrace_engine +docker run --rm --init -it --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \ + -v "$PWD:$PWD:ro" -v "$BN_API_PATH:$BN_API_PATH:ro" -w "$PWD" -e BN_API_PATH ptrace-test bash +``` + +Inside the container, use the build/run commands above with a build directory from +`mktemp -d`. The capabilities allow tracing and disabling ASLR. The fixtures themselves are +built in the output directory, leaving the source mount read-only. + +Run x86 ptrace coverage on a native x86 Linux host: Docker Desktop's architecture +emulation cannot reliably provide ptrace. The arm64 harness retains its test-only +architecture table; passing there does not establish support for an arm64 adapter. diff --git a/test/ptrace_engine/cmdline.cpp b/test/ptrace_engine/cmdline.cpp new file mode 100644 index 00000000..5826bf78 --- /dev/null +++ b/test/ptrace_engine/cmdline.cpp @@ -0,0 +1,14 @@ +#include "ptracecmdline.h" +#include + +int main(int argc, char** argv) +{ + if (argc != 2) + return 2; + auto arguments = BinaryNinjaDebugger::ParseCommandLineArguments(argv[1]); + if (!arguments) + return 3; + for (const auto& argument : *arguments) + fwrite(argument.c_str(), 1, argument.size() + 1, stdout); + return 0; +} diff --git a/test/ptrace_engine/driver.cpp b/test/ptrace_engine/driver.cpp index 32a20a4f..f96f2560 100644 --- a/test/ptrace_engine/driver.cpp +++ b/test/ptrace_engine/driver.cpp @@ -683,6 +683,65 @@ static void t_modules() e->Kill(); } +static void t_module_instances() +{ + std::vector maps; + for (uint64_t base : {0x100000ull, 0x200000ull}) + { + for (uint64_t offset : {0ull, 0x1000ull}) + { + PtraceEngine::MapEntry entry; + entry.start = base + offset; + entry.end = entry.start + 0x1000; + entry.offset = offset; + entry.path = "/same/library.so"; + maps.push_back(entry); + } + } + auto modules = BuildModules(maps, [](uint64_t address) { return address == 0x100000 || address == 0x200000; }); + CHECK(modules.size() == 2); + if (modules.size() != 2) return; + CHECK(modules[0].base == 0x100000 && modules[0].size == 0x2000); + CHECK(modules[1].base == 0x200000 && modules[1].size == 0x2000); + CHECK(modules[0].shortName != modules[1].shortName); +} + +static void t_module_loader_instances() +{ + Log log; + PtraceEngine::Event event; + uint32_t tid; + auto engine = startAtSignal(log, "multiload", tid, event); + if (!engine) return; + uint64_t first = addrOf(log, "first="); + CHECK(first != 0); + CHECK(engine->AddBreakpoint(first)); + CHECK(engine->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, event)); + CHECK(event.signal == SIGUSR1); + uint64_t second = addrOf(log, "second="); + CHECK(second != 0 && second != first); + auto modules = modulesOf(*engine); + std::vector copies; + for (const auto& module : modules) + if (module.path.ends_with("/libtest.so")) copies.push_back(module); + CHECK(copies.size() == 2); + for (uint64_t address : {first, second}) + { + size_t containing = 0; + for (const auto& module : copies) + containing += address >= module.base && address < module.base + module.size; + CHECK(containing == 1); + } + CHECK(engine->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::StoppedEvent, event)); + CHECK(event.breakpoint && pcOf(*engine, event.tid) == first); + CHECK(engine->RemoveBreakpoint(first)); + CHECK(engine->Resume(false, 0)); + CHECK(log.wait(PtraceEngine::ExitedEvent, event)); + CHECK(event.exitCode == 0 && event.signal == 0); +} + static void t_symbols() { Log log; PtraceEngine::Event ev; uint32_t tid; auto e = startAtSignal(log, "syms", tid, ev); if (!e) return; @@ -856,10 +915,11 @@ struct StepEnv Log log; // first, so that it outlives the engine that posts to it PtraceEngine::Event ev; uint32_t tid = 0; std::map refs; std::set user; + int failReleases = 0; std::unique_ptr e; std::unique_ptr stepper; bool acquire(uint64_t a) { if (refs[a] == 0 && !e->AddBreakpoint(a)) { refs.erase(a); return false; } refs[a]++; return true; } - bool release(uint64_t a) { auto it = refs.find(a); if (it == refs.end()) return false; if (--it->second > 0) return true; refs.erase(it); return e->RemoveBreakpoint(a); } + bool release(uint64_t a) { auto it = refs.find(a); if (it == refs.end()) return false; if (it->second > 1) { it->second--; return true; } if (failReleases > 0) { failReleases--; return false; } if (!e->RemoveBreakpoint(a)) return false; refs.erase(it); return true; } bool begin(const std::string& mode) { e = startAtSignal(log, mode, tid, ev); if (!e) return false; @@ -942,6 +1002,27 @@ static void t_stepover_basic() CHECK(u.exitsWith(11)); } +static void t_step_cleanup_failure() +{ + StepEnv t; + if (!t.begin("stepover")) return; + CHECK(t.runTo(addrOf(t.log, "here="))); + CHECK(t.stepToCall()); + uint64_t callPc = t.pc(), sp = t.sp(); + CHECK(t.stepper->StepOver(t.tid, callPc, sp, kCallLength, 8)); + t.failReleases = 3; + CHECK(t.follow() == PtraceStepper::Result::Failed); + CHECK(t.stepper->IsActive()); + CHECK(t.refs.count(callPc + kCallLength) == 1); + CHECK(!t.stepper->Cancel()); + CHECK(!t.stepper->StepOver(t.tid, t.pc(), t.sp(), 0, 8)); + CHECK(!t.e->IsRunning()); + CHECK(t.stepper->Cancel()); + CHECK(!t.stepper->IsActive()); + CHECK(t.refs.empty()); + CHECK(t.exitsWith(11)); +} + static void t_stepover_user_breakpoint() { StepEnv t; if (!t.begin("stepover")) return; @@ -2204,7 +2285,7 @@ int main(int argc, char** argv) {"hello", t_hello}, {"step", t_step}, {"interrupt", t_interrupt}, {"threads", t_threads}, {"churn", t_churn}, {"signal", t_signal}, {"silent", t_silent}, {"detach", t_detach}, {"kill_running", t_kill_running}, {"dtor_kills", t_dtor_kills}, {"launch_errors", t_launch_errors}, {"args_cwd", t_args_cwd}, {"stdin", t_stdin}, {"stdin_backpressure", t_stdin_backpressure}, - {"nopty", t_nopty}, {"relaunch", t_relaunch}, {"regs_step", t_regs_step}, {"regs_running", t_regs_running}, {"memory", t_memory}, {"bp_basic", t_bp_basic}, {"bp_step_remove", t_bp_step_remove}, {"bp_write", t_bp_write}, {"bp_threads", t_bp_threads}, {"bp_interrupts", t_bp_interrupts}, {"bp_remove_running", t_bp_remove_running}, {"bp_detach", t_bp_detach}, {"hw_watch", t_hw_watch}, {"hw_thread", t_hw_thread}, {"hw_exec", t_hw_exec}, {"hw_detach", t_hw_detach}, {"modules", t_modules}, {"symbols", t_symbols}, {"frames", t_frames}, {"loader", t_loader}, {"library_reload_breakpoint", t_library_reload_breakpoint}, {"library_rebase_breakpoint", t_library_rebase_breakpoint}, {"library_rebase_hardware", t_library_rebase_hardware}, {"processes", t_processes}, {"stepover_basic", t_stepover_basic}, {"stepover_user_breakpoint", t_stepover_user_breakpoint}, {"stepover_interrupt", t_stepover_interrupt}, {"stepover_recursion", t_stepover_recursion}, {"stepreturn_sites", t_stepreturn_sites}, {"stepreturn_address", t_stepreturn_address}, {"stepreturn_recursion", t_stepreturn_recursion}, {"stepover_threads", t_stepover_threads}, {"detach_reaped", t_detach_reaped}, {"fork_child", t_fork_child}, {"vfork", t_vfork}, {"spawn", t_spawn}, {"fork_threads", t_fork_threads}, {"interrupt_burst", t_interrupt_burst}, {"handlers_off", t_handlers_off}, {"handlers_on", t_handlers_on}, {"handlers_toggle", t_handlers_toggle}, {"handlers_thread", t_handlers_thread}, {"sigtrap_raise", t_sigtrap_raise}, {"sigtrap_kill", t_sigtrap_kill}, {"sigtrap_handler_debug", t_sigtrap_handler_debug}, {"sigtrap_instruction", t_sigtrap_instruction}, {"sigtrap_instruction_handler_debug", t_sigtrap_instruction_handler_debug}, {"sigtrap_unhandled", t_sigtrap_unhandled}, {"sigtrap_after_breakpoint", t_sigtrap_after_breakpoint}, {"sigtrap_while_stepping", t_sigtrap_while_stepping}, {"signal_reasons", t_signal_reasons}, {"conf_exitcode", t_conf_exitcode}, {"conf_exceptions", t_conf_exceptions}, {"conf_entry_step_exit", t_conf_entry_step_exit}, {"conf_memory_registers", t_conf_memory_registers}, {"conf_threads_restart", t_conf_threads_restart}, {"conf_symbols_modules", t_conf_symbols_modules}, {"elf_names", t_elf_names}, {"exec_by_name", t_exec_by_name}, {"exec_basic", t_exec_basic}, {"exec_rebreak", t_exec_rebreak}, {"exec_thread", t_exec_thread}, {"exec_continue", t_exec_continue}, {"winsize", t_winsize}, {"attach_threads", t_attach_threads}, {"attach_breakpoint", t_attach_breakpoint}, {"attach_step_at_breakpoint", t_attach_step_at_breakpoint}, {"attach_exit", t_attach_exit}, {"attach_kill", t_attach_kill}, {"attach_dtor_detaches", t_attach_dtor_detaches}, {"attach_errors", t_attach_errors}, {"attach_churn", t_attach_churn}, {"attach_syscall", t_attach_syscall}, {"redirect_parse", t_redirect_parse}, {"redirect_stdout", t_redirect_stdout}, {"redirect_stdin", t_redirect_stdin}, {"redirect_stderr_merge", t_redirect_stderr_merge}, {"redirect_other_fds", t_redirect_other_fds}, {"redirect_append_readwrite", t_redirect_append_readwrite}, {"redirect_relative", t_redirect_relative}, {"redirect_errors", t_redirect_errors}, {"redirect_leaks", t_redirect_leaks}, {"syscall_trace", t_syscall_trace}, {"syscall_breakpoint", t_syscall_breakpoint}, {"syscall_emulate", t_syscall_emulate}, {"syscall_set_info", t_syscall_set_info}, {"syscall_threads", t_syscall_threads}, {"syscall_unsupported", t_syscall_unsupported}, {"syscall_names", t_syscall_names}, {"register_aliases", t_register_aliases}, {"output_backpressure", t_output_backpressure}, {"output_flood_detach", t_output_flood_detach}, {"output_last_words", t_output_last_words}, {"hw_not_ours", t_hw_not_ours}, {"clone_process", t_clone_process}, {"clone_shared", t_clone_shared}, {"dtor_from_handler", t_dtor_from_handler}, {"dtor_blocked_handler", t_dtor_blocked_handler}}; + {"nopty", t_nopty}, {"relaunch", t_relaunch}, {"regs_step", t_regs_step}, {"regs_running", t_regs_running}, {"memory", t_memory}, {"bp_basic", t_bp_basic}, {"bp_step_remove", t_bp_step_remove}, {"bp_write", t_bp_write}, {"bp_threads", t_bp_threads}, {"bp_interrupts", t_bp_interrupts}, {"bp_remove_running", t_bp_remove_running}, {"bp_detach", t_bp_detach}, {"hw_watch", t_hw_watch}, {"hw_thread", t_hw_thread}, {"hw_exec", t_hw_exec}, {"hw_detach", t_hw_detach}, {"modules", t_modules}, {"module_instances", t_module_instances}, {"module_loader_instances", t_module_loader_instances}, {"symbols", t_symbols}, {"frames", t_frames}, {"loader", t_loader}, {"library_reload_breakpoint", t_library_reload_breakpoint}, {"library_rebase_breakpoint", t_library_rebase_breakpoint}, {"library_rebase_hardware", t_library_rebase_hardware}, {"processes", t_processes}, {"stepover_basic", t_stepover_basic}, {"step_cleanup_failure", t_step_cleanup_failure}, {"stepover_user_breakpoint", t_stepover_user_breakpoint}, {"stepover_interrupt", t_stepover_interrupt}, {"stepover_recursion", t_stepover_recursion}, {"stepreturn_sites", t_stepreturn_sites}, {"stepreturn_address", t_stepreturn_address}, {"stepreturn_recursion", t_stepreturn_recursion}, {"stepover_threads", t_stepover_threads}, {"detach_reaped", t_detach_reaped}, {"fork_child", t_fork_child}, {"vfork", t_vfork}, {"spawn", t_spawn}, {"fork_threads", t_fork_threads}, {"interrupt_burst", t_interrupt_burst}, {"handlers_off", t_handlers_off}, {"handlers_on", t_handlers_on}, {"handlers_toggle", t_handlers_toggle}, {"handlers_thread", t_handlers_thread}, {"sigtrap_raise", t_sigtrap_raise}, {"sigtrap_kill", t_sigtrap_kill}, {"sigtrap_handler_debug", t_sigtrap_handler_debug}, {"sigtrap_instruction", t_sigtrap_instruction}, {"sigtrap_instruction_handler_debug", t_sigtrap_instruction_handler_debug}, {"sigtrap_unhandled", t_sigtrap_unhandled}, {"sigtrap_after_breakpoint", t_sigtrap_after_breakpoint}, {"sigtrap_while_stepping", t_sigtrap_while_stepping}, {"signal_reasons", t_signal_reasons}, {"conf_exitcode", t_conf_exitcode}, {"conf_exceptions", t_conf_exceptions}, {"conf_entry_step_exit", t_conf_entry_step_exit}, {"conf_memory_registers", t_conf_memory_registers}, {"conf_threads_restart", t_conf_threads_restart}, {"conf_symbols_modules", t_conf_symbols_modules}, {"elf_names", t_elf_names}, {"exec_by_name", t_exec_by_name}, {"exec_basic", t_exec_basic}, {"exec_rebreak", t_exec_rebreak}, {"exec_thread", t_exec_thread}, {"exec_continue", t_exec_continue}, {"winsize", t_winsize}, {"attach_threads", t_attach_threads}, {"attach_breakpoint", t_attach_breakpoint}, {"attach_step_at_breakpoint", t_attach_step_at_breakpoint}, {"attach_exit", t_attach_exit}, {"attach_kill", t_attach_kill}, {"attach_dtor_detaches", t_attach_dtor_detaches}, {"attach_errors", t_attach_errors}, {"attach_churn", t_attach_churn}, {"attach_syscall", t_attach_syscall}, {"redirect_parse", t_redirect_parse}, {"redirect_stdout", t_redirect_stdout}, {"redirect_stdin", t_redirect_stdin}, {"redirect_stderr_merge", t_redirect_stderr_merge}, {"redirect_other_fds", t_redirect_other_fds}, {"redirect_append_readwrite", t_redirect_append_readwrite}, {"redirect_relative", t_redirect_relative}, {"redirect_errors", t_redirect_errors}, {"redirect_leaks", t_redirect_leaks}, {"syscall_trace", t_syscall_trace}, {"syscall_breakpoint", t_syscall_breakpoint}, {"syscall_emulate", t_syscall_emulate}, {"syscall_set_info", t_syscall_set_info}, {"syscall_threads", t_syscall_threads}, {"syscall_unsupported", t_syscall_unsupported}, {"syscall_names", t_syscall_names}, {"register_aliases", t_register_aliases}, {"output_backpressure", t_output_backpressure}, {"output_flood_detach", t_output_flood_detach}, {"output_last_words", t_output_last_words}, {"hw_not_ours", t_hw_not_ours}, {"clone_process", t_clone_process}, {"clone_shared", t_clone_shared}, {"dtor_from_handler", t_dtor_from_handler}, {"dtor_blocked_handler", t_dtor_blocked_handler}}; if (argc > 2) { fprintf(stderr, "usage: %s [--list|test-name]\n", argv[0]); diff --git a/test/ptrace_engine/progs.c b/test/ptrace_engine/progs.c index 0bab4158..92011505 100644 --- a/test/ptrace_engine/progs.c +++ b/test/ptrace_engine/progs.c @@ -68,6 +68,8 @@ static void* execWorker(void* a) { usleep(100000); execl(PTRACE_TEST_DIRECTORY " static void* forker(void* a) { for (int i = 0; i < 20; i++) { pid_t c = fork(); if (c == 0) { marker(); _exit(0); } int st = 0; waitpid(c, &st, 0); if (WIFSIGNALED(st)) __sync_fetch_and_add(&bad, 1); marker(); } return 0; } static void* markerThread(void* a) { for (int i = 0; i < 3; i++) { marker(); usleep(2000); } return 0; } // Threads that never stop running into a breakpoint, so that the debugger has to stop them all over and over +static void* idleThread(void* a) { while (1) usleep(1000); return 0; } +static void* exitGroupThread(void* a) { usleep(50000); marker(); syscall(SYS_exit_group, 9); return 0; } static void* markerSpinner(void* a) { while (1) { marker(); usleep(200); } return 0; } // The thread group leader leaves while this one is still running, so the group lives on without it static void* outliveLeader(void* a) { for (int i = 0; i < 40; i++) { marker(); usleep(25000); } printf("worker done\n"); _exit(7); return 0; } @@ -83,6 +85,9 @@ int main(int argc, char** argv) if (!strcmp(mode, "hello")) { printf("hello from target\n"); return 7; } if (!strcmp(mode, "loop")) { volatile unsigned long x = 0; while (1) x++; } if (!strcmp(mode, "threads")) { pthread_t t[3]; for (int i = 0; i < 3; i++) pthread_create(&t[i], 0, spin, 0); while (1) usleep(1000); } + // The leader ends the whole process with a sibling thread alive, and the other way round + if (!strcmp(mode, "exitleader")) { signal(SIGUSR1, SIG_IGN); pthread_t t; pthread_create(&t, 0, idleThread, 0); usleep(50000); marker(); syscall(SYS_exit_group, 9); return 0; } + if (!strcmp(mode, "exitthread")) { signal(SIGUSR1, SIG_IGN); pthread_t t; pthread_create(&t, 0, exitGroupThread, 0); pthread_join(t, 0); return 0; } if (!strcmp(mode, "markerthreads")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); raise(SIGUSR1); pthread_t t[4]; for (int i = 0; i < 4; i++) pthread_create(&t[i], 0, markerSpinner, 0); for (int i = 0; i < 4; i++) pthread_join(t[i], 0); return 0; } if (!strcmp(mode, "leaderexit")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p\n", (void*)marker); pthread_t t; pthread_create(&t, 0, outliveLeader, 0); raise(SIGUSR1); pthread_exit(0); } if (!strcmp(mode, "churn")) { for (int i = 0; i < 50; i++) { pthread_t t; pthread_create(&t, 0, shortlived, 0); pthread_join(t, 0); } printf("churn done\n"); return 0; } @@ -102,6 +107,20 @@ int main(int argc, char** argv) if (!strcmp(mode, "frames")) { signal(SIGUSR1, SIG_IGN); level1(); return counter; } if (!strcmp(mode, "syms")) { signal(SIGUSR1, SIG_IGN); printf("marker=%p puts=%p\n", (void*)marker, dlsym(RTLD_DEFAULT, "puts")); raise(SIGUSR1); return 0; } if (!strcmp(mode, "dl")) { signal(SIGUSR1, SIG_IGN); printf("ready\n"); raise(SIGUSR1); void* h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); printf("loaded=%p\n", h); void (*f)(void) = (void (*)(void))dlsym(h, "libfunc"); printf("libfunc=%p\n", (void*)f); raise(SIGUSR1); f(); return 0; } + if (!strcmp(mode, "multiload")) { + signal(SIGUSR1, SIG_IGN); + void* first = dlmopen(LM_ID_NEWLM, PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW | RTLD_LOCAL); + if (!first) return 98; + printf("first=%p\n", dlsym(first, "libfunc")); + raise(SIGUSR1); + void* second = dlmopen(LM_ID_NEWLM, PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW | RTLD_LOCAL); + if (!second) return 98; + printf("second=%p\n", dlsym(second, "libfunc")); + raise(SIGUSR1); + ((void (*)(void))dlsym(first, "libfunc"))(); + ((void (*)(void))dlsym(second, "libfunc"))(); + return 0; + } if (!strcmp(mode, "dlcycle")) { signal(SIGUSR1, SIG_IGN); for (int i = 1; i <= 2; i++) { void* h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); void (*f)(void) = (void (*)(void))dlsym(h, "libfunc"); printf("cycle%d=%p\n", i, (void*)f); raise(SIGUSR1); f(); dlclose(h); } return 0; } if (!strcmp(mode, "dlrebase")) { signal(SIGUSR1, SIG_IGN); void* h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); void (*f)(void) = (void (*)(void))dlsym(h, "libfunc"); uintptr_t lo, hi; int range = libraryRange(&lo, &hi); printf("cycle1=%p\n", (void*)f); raise(SIGUSR1); f(); dlclose(h); void* held = range ? mmap((void*)lo, hi - lo, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0) : MAP_FAILED; h = dlopen(PTRACE_TEST_DIRECTORY "/libtest.so", RTLD_NOW); f = (void (*)(void))dlsym(h, "libfunc"); printf("reserved=%p cycle2=%p\n", held, (void*)f); raise(SIGUSR1); f(); dlclose(h); return held == MAP_FAILED; } if (!strcmp(mode, "stepover")) { signal(SIGUSR1, SIG_IGN); caller(0); return counter; } diff --git a/test/ptrace_engine_test.py b/test/ptrace_engine_test.py index 8b6a1603..14acf9f6 100644 --- a/test/ptrace_engine_test.py +++ b/test/ptrace_engine_test.py @@ -139,7 +139,7 @@ def native(): pytest.fail(message) pytest.skip(message) config = json.loads(config_file.read_text()) - for name in ('driver', 'elfcmp', 'progs', 'progs_pad', 'libtest.so'): + for name in ('driver', 'elfcmp', 'cmdline', 'progs', 'progs_pad', 'libtest.so'): assert (directory / name).is_file(), f'Missing built ptrace fixture: {directory / name}' env = os.environ.copy() env['LC_ALL'] = 'C' @@ -195,6 +195,40 @@ def test_driver_selection(native): assert 'Unknown test:' in result['output'] +def _sh_arguments(text): + """What a POSIX shell makes of the words in `text` before it expands anything (None if it cannot parse them)""" + script = 'set -- ' + text + '\nfor a in "$@"; do printf "%s\\0" "$a"; done' + result = subprocess.run(['sh', '-c', script], capture_output=True) + return None if result.returncode else result.stdout + + +COMMAND_LINES = [ + '', ' ', 'a', 'a b c', "a 'b c' d", 'a "b c" d', "''", '""', "a'' b", 'a\\ b', 'a\\\\b', "'a\\b'", '"a\\b"', + '"a\\"b"', '"\\d+"', '"C:\\path"', '"a\\$b"', '"a\\`b"', '"a\\\\b"', 'a\\\nb', '"a\\\nb"', "a'b\"c'd", + 'x\ty', 'one\ttwo', "a'b", 'a"b', 'a\\', '"', "'", '"a\nb"', "'a\nb'", '"\\n"', "\\'", '"\'"', +] + + +def test_command_line_arguments_match_sh(native): + """The adapter splits `cmd_line` like a shell: this compares it with sh on fixed and random command lines. + + A newline between words is left out: for sh it ends the command, for the adapter it separates words like a blank. + """ + directory, _, _, run = native + import random + rng = random.Random(20260105) + tokens = ['a', 'b', '1', ' ', ' ', '\t', "'", '"', '\\', '\\"', '\\\\', '-', '=', ':', '.', '/', 'ab', '\\a'] + lines = list(COMMAND_LINES) + [''.join(rng.choice(tokens) for _ in range(rng.randrange(0, 14))) for _ in range(1500)] + for text in lines: + expected = _sh_arguments(text) + result = subprocess.run([directory / 'cmdline', text], capture_output=True) + if expected is None: + assert result.returncode == 3, f'{text!r}: sh cannot parse it, the adapter returned {result.stdout!r}' + else: + assert result.returncode == 0 and result.stdout == expected, \ + f'{text!r}: sh gives {expected!r}, the adapter {result.stdout!r} (rc {result.returncode})' + + @pytest.mark.parametrize('name', ['progs', 'progs_pad', 'libtest.so', 'Linux-x86/helloworld', 'Linux-x86_64/helloworld']) def test_elf_symbols(native, name):