20#include "llvm/Support/Error.h"
33#define LLDB_PROPERTIES_processfreebsdkernelcore
34#include "ProcessFreeBSDKernelCoreProperties.inc"
37#define LLDB_PROPERTIES_processfreebsdkernelcore
38#include "ProcessFreeBSDKernelCorePropertiesEnum.inc"
43 static llvm::StringRef GetSettingName() {
47 PluginProperties() : Properties() {
48 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
49 m_collection_sp->Initialize(g_processfreebsdkernelcore_properties_def);
52 ~PluginProperties()
override =
default;
54 bool GetReadOnly()
const {
55 const uint32_t idx = ePropertyReadOnly;
56 return GetPropertyAtIndexAs<bool>(idx,
true);
63 static PluginProperties g_settings;
73 interpreter,
"process plugin refresh-threads",
74 "Refresh the thread list from the FreeBSD kernel core. The thread "
75 "list and related data structures may be being read from live "
76 "memory (/dev/mem), which may have changed since the last refresh. "
77 "This command clears LLDB's thread list and memory cache then "
78 "re-reads the kernel's allproc/zombie lists to rebuild the thread "
80 "process plugin refresh-threads",
81 eCommandRequiresProcess | eCommandTryTargetAPILock) {}
103 process->m_thread_list_real.Clear();
104 process->m_thread_list.Clear();
107 const uint32_t num_threads =
108 process->GetThreadList().GetSize(
true);
110 "Thread list refreshed, {0} thread{1} found.", num_threads,
111 num_threads == 1 ?
"" :
"s");
133 const FileSpec *crash_file,
bool can_connect) {
134 ModuleSP executable = target_sp->GetExecutableModule();
135 if (crash_file && !can_connect && executable) {
136 char errbuf[_POSIX2_LINE_MAX];
138 kvm_open2(executable->GetFileSpec().GetPath().c_str(),
139 crash_file->
GetPath().c_str(), O_RDONLY, errbuf,
nullptr);
142 return std::make_shared<ProcessFreeBSDKernelCore>(target_sp, listener_sp,
158 debugger, PluginProperties::GetSettingName())) {
159 const bool is_global_setting =
true;
162 "Properties for the freebsd-kernel process plug-in.",
172 bool plugin_specified_by_name) {
180 m_command_sp = std::make_unique<CommandObjectMultiword>(
181 interp,
"process plugin",
182 "Commands for the FreeBSD kernel process plug-in.",
183 "process plugin <subcommand> [<subcommand-options>]");
196 "ProcessFreeBSDKernelCore: no executable module set on target");
198 char errbuf[_POSIX2_LINE_MAX];
199 m_kvm = kvm_open2(executable->GetFileSpec().GetPath().c_str(),
200 GetCoreFile().GetPath().c_str(), O_RDWR, errbuf,
nullptr);
205 "ProcessFreeBSDKernelCore: kvm_open2 failed for core '%s' "
208 executable->GetFileSpec().GetPath().c_str());
239 const void *buf,
size_t size,
243 "Memory writes are currently disabled. You can enable them with "
244 "`settings set plugin.process.freebsd-kernel-core.read-only false`.");
249 rd = kvm_write(
m_kvm, addr, buf, size);
250 if (rd < 0 ||
static_cast<size_t>(rd) != size) {
253 return rd > 0 ? rd : 0;
260 if (old_thread_list.
GetSize(
false) == 0) {
267 switch (
GetTarget().GetArchitecture().GetMachine()) {
268 case llvm::Triple::arm:
269 case llvm::Triple::aarch64:
270 case llvm::Triple::ppc64le:
271 case llvm::Triple::riscv64:
272 case llvm::Triple::x86:
273 case llvm::Triple::x86_64:
289 int32_t offset_p_pid =
331 if (offset_p_list == -1 || offset_p_pid == -1 || offset_p_threads == -1 ||
332 offset_p_comm == -1 || offset_td_tid == -1 || offset_td_plist == -1 ||
333 offset_td_pcb == -1 || offset_td_oncpu == -1 || offset_td_name == -1)
356 uint32_t mp_maxid = 0;
367 uint32_t long_bit = long_size_bytes * 8;
369 if (
auto type_system_or_err =
375 long_size_bytes = *size;
376 long_bit = long_size_bytes * 8;
378 llvm::consumeError(type_system_or_err.takeError());
381 constexpr size_t fbsd_maxcomlen = 19;
391 std::vector<std::pair<lldb::addr_t, int32_t>> process_addrs;
392 llvm::Expected<lldb::addr_t> proc_or_err =
394 for (; proc_or_err && *proc_or_err != 0;
401 process_addrs.emplace_back(proc, pid);
405 llvm::consumeError(proc_or_err.takeError());
409 std::sort(process_addrs.begin(), process_addrs.end(),
410 [](
const auto &a,
const auto &b) { return a.second < b.second; });
412 for (
auto [proc, pid] : process_addrs) {
414 char comm[fbsd_maxcomlen + 1];
423 llvm::Expected<lldb::addr_t> td_or_err =
425 for (; td_or_err && *td_or_err != 0;
433 llvm::Expected<lldb::addr_t> pcb_addr_or_err =
435 if (!pcb_addr_or_err) {
436 llvm::consumeError(pcb_addr_or_err.takeError());
448 char thread_name[fbsd_maxcomlen + 1];
450 sizeof(thread_name),
error);
458 std::string thread_desc = llvm::formatv(
"(pid {0}) {1}", pid, comm);
459 if (*thread_name && strcmp(thread_name, comm)) {
461 thread_desc += thread_name;
468 if (tid == dumptid) {
471 thread_desc +=
" (crashed)";
472 }
else if (oncpu != -1) {
475 bool is_stopped =
false;
476 if (oncpu >= 0 &&
static_cast<uint32_t
>(oncpu) <= mp_maxid &&
478 uint32_t
bit = oncpu % long_bit;
479 uint32_t word = oncpu / long_bit;
480 lldb::addr_t mask_addr = stopped_cpus + word * long_size_bytes;
482 mask_addr, long_size_bytes, 0,
error);
484 is_stopped = (mask & (1ULL <<
bit)) != 0;
490 pcb_addr = stoppcbs + oncpu * pcbsize;
494 thread_desc += llvm::formatv(
" (on CPU {0})", oncpu);
501 thread->SetIsCrashedThread(
true);
508 llvm::consumeError(td_or_err.takeError());
513 const uint32_t num_threads = old_thread_list.
GetSize(
false);
514 for (uint32_t i = 0; i < num_threads; ++i)
517 return new_thread_list.
GetSize(
false) > 0;
525 rd = kvm_read2(
m_kvm, addr, buf, size);
526 if (rd < 0 ||
static_cast<size_t>(rd) != size) {
529 return rd > 0 ? rd : 0;
541 kssize_t displacement = kvm_kerndisp(
m_kvm);
543 if (displacement == 0)
548 if (!kernel_module_sp)
551 bool changed =
false;
552 kernel_module_sp->SetLoadAddress(target,
558 loaded_module_list.
Append(kernel_module_sp);
575 llvm::Expected<lldb::addr_t> msgbufp_or_err =
577 if (!msgbufp_or_err) {
578 llvm::consumeError(msgbufp_or_err.takeError());
588 uint64_t offset_msg_ptr = 0;
589 uint64_t offset_msg_size = 0;
590 uint64_t offset_msg_wseq = 0;
591 uint64_t offset_msg_rseq = 0;
600 for (uint32_t i = 0; i < num_fields; i++) {
601 std::string field_name;
602 uint64_t field_offset = 0;
607 if (field_name ==
"msg_ptr") {
608 offset_msg_ptr = field_offset / 8;
610 }
else if (field_name ==
"msg_size") {
611 offset_msg_size = field_offset / 8;
613 }
else if (field_name ==
"msg_wseq") {
614 offset_msg_wseq = field_offset / 8;
616 }
else if (field_name ==
"msg_rseq") {
617 offset_msg_rseq = field_offset / 8;
622 if (field_found != 4) {
625 "FreeBSD-Kernel-Core: Could not find all required fields for msgbuf");
638 offset_msg_size = ptr_size + 4;
639 offset_msg_wseq = ptr_size + 8;
640 offset_msg_rseq = ptr_size + 12;
644 llvm::Expected<lldb::addr_t> bufp_or_err =
647 llvm::consumeError(bufp_or_err.takeError());
654 if (
error.Fail() || size == 0)
669 uint32_t rseq_pos = rseq % size;
670 uint32_t wseq_pos = wseq % size;
672 if (rseq_pos == wseq_pos)
680 stream_sp->PutCString(
"\nUnread portion of the kernel message buffer:\n");
683 if (rseq_pos < wseq_pos) {
685 size_t len = wseq_pos - rseq_pos;
686 std::string buf(len,
'\0');
688 if (
error.Success() && bytes_read > 0) {
689 buf.resize(bytes_read);
694 size_t len1 = size - rseq_pos;
695 std::string buf1(len1,
'\0');
696 size_t bytes_read1 =
ReadMemory(bufp + rseq_pos, &buf1[0], len1,
error);
697 if (
error.Success() && bytes_read1 > 0) {
698 buf1.resize(bytes_read1);
703 std::string buf2(wseq_pos,
'\0');
705 if (
error.Success() && bytes_read2 > 0) {
706 buf2.resize(bytes_read2);
712 stream_sp->PutChar(
'\n');
static llvm::raw_ostream & error(Stream &strm)
static PluginProperties & GetGlobalPluginProperties()
#define LLDB_LOGF(log,...)
#define LLDB_PLUGIN_DEFINE(PluginName)
static PluginProperties & GetGlobalPluginProperties()
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectProcessFreeBSDKernelCoreRefreshThreads(CommandInterpreter &interpreter)
~CommandObjectProcessFreeBSDKernelCoreRefreshThreads() override=default
static llvm::StringRef GetPluginNameStatic()
lldb_private::Status DoDestroy() override
static llvm::StringRef GetPluginNameStatic()
void PrintUnreadMessage()
ProcessFreeBSDKernelCore(lldb::TargetSP target_sp, lldb::ListenerSP listener, const lldb_private::FileSpec &core_file)
lldb::addr_t FindSymbol(const char *name)
~ProcessFreeBSDKernelCore()
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener, const lldb_private::FileSpec *crash_file_path, bool can_connect)
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
static void DebuggerInitialize(lldb_private::Debugger &debugger)
static llvm::StringRef GetPluginDescriptionStatic()
lldb_private::Status DoLoadCore() override
lldb_private::CommandObject * GetPluginCommandObject() override
Return a multi-word command object that can be used to expose plug-in specific commands.
void SetKernelDisplacement()
friend class CommandObjectProcessFreeBSDKernelCoreRefreshThreads
lldb_private::DynamicLoader * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, lldb_private::Status &error) override
Actually do the writing of memory to a process.
bool DoUpdateThreadList(lldb_private::ThreadList &old_thread_list, lldb_private::ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
size_t DoReadMemory(const lldb_private::ProcessAddress &addr, void *buf, size_t size, lldb_private::Status &error) override
Actually do the reading of memory from a process.
bool m_printed_unread_message
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
std::unique_ptr< lldb_private::CommandObjectMultiword > m_command_sp
A command line argument class.
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandInterpreter & m_interpreter
void SetStatus(lldb::ReturnStatus status)
void void AppendMessageWithFormatv(const char *format, Args &&...args)
Generic representation of a type in a programming language.
CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) const
Create related types using the current type's AST.
CompilerType GetFieldAtIndex(size_t idx, std::string &name, uint64_t *bit_offset_ptr, uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) const
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
uint32_t GetNumFields() const
A uniqued constant string class.
CommandInterpreter & GetCommandInterpreter()
lldb::StreamUP GetAsyncOutputStream()
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
void Clear(bool clear_invalid_ranges=false)
A collection class for Module objects.
void FindTypes(Module *search_first, const TypeQuery &query, lldb_private::TypeResults &results) const
Find types using a type-matching object that contains all search parameters.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool CreateSettingForProcessPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static lldb::OptionValuePropertiesSP GetSettingForProcessPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool UnregisterPlugin(ABICreateInstance create_callback)
PostMortemProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec &core_file)
FileSpec GetCoreFile() const override
Provide a way to retrieve the core dump file that is loaded for debugging.
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, int64_t fail_value, Status &error)
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a NULL terminated C string from memory.
virtual size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
lldb::DynamicLoaderUP m_dyld_up
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
MemoryCache m_memory_cache
uint32_t GetAddressByteSize() const
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
ThreadList m_thread_list
The threads for this process as the user will see them.
friend class DynamicLoader
Target & GetTarget()
Get the target object pointer for this module.
lldb::OptionValuePropertiesSP GetValueProperties() const
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
lldb::addr_t GetLoadAddress(Target *target) const
void ModulesDidLoad(ModuleList &module_list)
This call may preload module symbols, and may do so in parallel depending on the following target set...
Debugger & GetDebugger() const
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
const ModuleList & GetImages() const
Get accessor for the images for this process.
void AddThread(const lldb::ThreadSP &thread_sp)
uint32_t GetSize(bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
lldb::TypeSP GetTypeAtIndex(uint32_t idx)
A class that contains all state required for type lookups.
This class tracks the state and results of a TypeQuery.
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::Process > ProcessSP
@ eReturnStatusSuccessFinishResult
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP