1 //===-- OperatingSystemGo.cpp -----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include <unordered_map>
14 // Other libraries and framework includes
16 #include "OperatingSystemGo.h"
18 #include "Plugins/Process/Utility/DynamicRegisterInfo.h"
19 #include "Plugins/Process/Utility/RegisterContextMemory.h"
20 #include "Plugins/Process/Utility/ThreadMemory.h"
21 #include "lldb/Core/Debugger.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/RegisterValue.h"
25 #include "lldb/Core/Section.h"
26 #include "lldb/Core/ValueObjectVariable.h"
27 #include "lldb/Interpreter/CommandInterpreter.h"
28 #include "lldb/Interpreter/OptionGroupBoolean.h"
29 #include "lldb/Interpreter/OptionGroupUInt64.h"
30 #include "lldb/Interpreter/OptionValueProperties.h"
31 #include "lldb/Interpreter/Options.h"
32 #include "lldb/Interpreter/Property.h"
33 #include "lldb/Symbol/ObjectFile.h"
34 #include "lldb/Symbol/Type.h"
35 #include "lldb/Symbol/VariableList.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/StopInfo.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Target/Thread.h"
40 #include "lldb/Target/ThreadList.h"
41 #include "lldb/Utility/DataBufferHeap.h"
42 #include "lldb/Utility/StreamString.h"
45 using namespace lldb_private;
49 static PropertyDefinition g_properties[] = {
50 {"enable", OptionValue::eTypeBoolean, true, true, nullptr, nullptr,
51 "Specify whether goroutines should be treated as threads."},
52 {NULL, OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL}};
55 ePropertyEnableGoroutines,
58 class PluginProperties : public Properties {
60 PluginProperties() : Properties() {
61 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
62 m_collection_sp->Initialize(g_properties);
65 ~PluginProperties() override = default;
67 static ConstString GetSettingName() {
68 return OperatingSystemGo::GetPluginNameStatic();
71 bool GetEnableGoroutines() {
72 const uint32_t idx = ePropertyEnableGoroutines;
73 return m_collection_sp->GetPropertyAtIndexAsBoolean(
74 NULL, idx, g_properties[idx].default_uint_value);
77 bool SetEnableGoroutines(bool enable) {
78 const uint32_t idx = ePropertyEnableGoroutines;
79 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, enable);
83 typedef std::shared_ptr<PluginProperties> OperatingSystemGoPropertiesSP;
85 static const OperatingSystemGoPropertiesSP &GetGlobalPluginProperties() {
86 static OperatingSystemGoPropertiesSP g_settings_sp;
88 g_settings_sp.reset(new PluginProperties());
92 class RegisterContextGo : public RegisterContextMemory {
94 RegisterContextGo(lldb_private::Thread &thread, uint32_t concrete_frame_idx,
95 DynamicRegisterInfo ®_info, lldb::addr_t reg_data_addr)
96 : RegisterContextMemory(thread, concrete_frame_idx, reg_info,
98 const RegisterInfo *sp = reg_info.GetRegisterInfoAtIndex(
99 reg_info.ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
100 LLDB_REGNUM_GENERIC_SP));
101 const RegisterInfo *pc = reg_info.GetRegisterInfoAtIndex(
102 reg_info.ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
103 LLDB_REGNUM_GENERIC_PC));
104 size_t byte_size = std::max(sp->byte_offset + sp->byte_size,
105 pc->byte_offset + pc->byte_size);
107 DataBufferSP reg_data_sp(new DataBufferHeap(byte_size, 0));
108 m_reg_data.SetData(reg_data_sp);
111 ~RegisterContextGo() override = default;
113 bool ReadRegister(const lldb_private::RegisterInfo *reg_info,
114 lldb_private::RegisterValue ®_value) override {
115 switch (reg_info->kinds[eRegisterKindGeneric]) {
116 case LLDB_REGNUM_GENERIC_SP:
117 case LLDB_REGNUM_GENERIC_PC:
118 return RegisterContextMemory::ReadRegister(reg_info, reg_value);
120 reg_value.SetValueToInvalid();
125 bool WriteRegister(const lldb_private::RegisterInfo *reg_info,
126 const lldb_private::RegisterValue ®_value) override {
127 switch (reg_info->kinds[eRegisterKindGeneric]) {
128 case LLDB_REGNUM_GENERIC_SP:
129 case LLDB_REGNUM_GENERIC_PC:
130 return RegisterContextMemory::WriteRegister(reg_info, reg_value);
137 DISALLOW_COPY_AND_ASSIGN(RegisterContextGo);
140 } // anonymous namespace
142 struct OperatingSystemGo::Goroutine {
150 void OperatingSystemGo::Initialize() {
151 PluginManager::RegisterPlugin(GetPluginNameStatic(),
152 GetPluginDescriptionStatic(), CreateInstance,
156 void OperatingSystemGo::DebuggerInitialize(Debugger &debugger) {
157 if (!PluginManager::GetSettingForOperatingSystemPlugin(
158 debugger, PluginProperties::GetSettingName())) {
159 const bool is_global_setting = true;
160 PluginManager::CreateSettingForOperatingSystemPlugin(
161 debugger, GetGlobalPluginProperties()->GetValueProperties(),
162 ConstString("Properties for the goroutine thread plug-in."),
167 void OperatingSystemGo::Terminate() {
168 PluginManager::UnregisterPlugin(CreateInstance);
171 OperatingSystem *OperatingSystemGo::CreateInstance(Process *process,
174 TargetSP target_sp = process->CalculateTarget();
177 ModuleList &module_list = target_sp->GetImages();
178 std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
179 const size_t num_modules = module_list.GetSize();
180 bool found_go_runtime = false;
181 for (size_t i = 0; i < num_modules; ++i) {
182 Module *module = module_list.GetModulePointerAtIndexUnlocked(i);
183 const SectionList *section_list = module->GetSectionList();
185 SectionSP section_sp(
186 section_list->FindSectionByType(eSectionTypeGoSymtab, true));
188 found_go_runtime = true;
193 if (!found_go_runtime)
196 return new OperatingSystemGo(process);
199 OperatingSystemGo::OperatingSystemGo(lldb_private::Process *process)
200 : OperatingSystem(process), m_reginfo(new DynamicRegisterInfo) {}
202 OperatingSystemGo::~OperatingSystemGo() = default;
204 ConstString OperatingSystemGo::GetPluginNameStatic() {
205 static ConstString g_name("goroutines");
209 const char *OperatingSystemGo::GetPluginDescriptionStatic() {
210 return "Operating system plug-in that reads runtime data-structures for "
214 bool OperatingSystemGo::Init(ThreadList &threads) {
215 if (threads.GetSize(false) < 1)
217 TargetSP target_sp = m_process->CalculateTarget();
220 // Go 1.6 stores goroutines in a slice called runtime.allgs
221 ValueObjectSP allgs_sp = FindGlobal(target_sp, "runtime.allgs");
223 m_allg_sp = allgs_sp->GetChildMemberWithName(ConstString("array"), true);
224 m_allglen_sp = allgs_sp->GetChildMemberWithName(ConstString("len"), true);
226 // Go 1.4 stores goroutines in the variable runtime.allg.
227 m_allg_sp = FindGlobal(target_sp, "runtime.allg");
228 m_allglen_sp = FindGlobal(target_sp, "runtime.allglen");
231 if (m_allg_sp && !m_allglen_sp) {
232 StreamSP error_sp = target_sp->GetDebugger().GetAsyncErrorStream();
233 error_sp->Printf("Unsupported Go runtime version detected.");
240 RegisterContextSP real_registers_sp =
241 threads.GetThreadAtIndex(0, false)->GetRegisterContext();
243 std::unordered_map<size_t, ConstString> register_sets;
244 for (size_t set_idx = 0; set_idx < real_registers_sp->GetRegisterSetCount();
246 const RegisterSet *set = real_registers_sp->GetRegisterSet(set_idx);
247 ConstString name(set->name);
248 for (size_t reg_idx = 0; reg_idx < set->num_registers; ++reg_idx) {
249 register_sets[reg_idx] = name;
252 TypeSP gobuf_sp = FindType(target_sp, "runtime.gobuf");
254 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
257 log->Printf("OperatingSystemGo unable to find struct Gobuf");
260 CompilerType gobuf_type(gobuf_sp->GetLayoutCompilerType());
261 for (size_t idx = 0; idx < real_registers_sp->GetRegisterCount(); ++idx) {
262 RegisterInfo reg = *real_registers_sp->GetRegisterInfoAtIndex(idx);
263 int field_index = -1;
264 if (reg.kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_SP) {
266 } else if (reg.kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_PC) {
269 if (field_index == -1) {
270 reg.byte_offset = ~0;
272 std::string field_name;
273 uint64_t bit_offset = 0;
274 CompilerType field_type = gobuf_type.GetFieldAtIndex(
275 field_index, field_name, &bit_offset, nullptr, nullptr);
276 reg.byte_size = field_type.GetByteSize(nullptr);
277 reg.byte_offset = bit_offset / 8;
279 ConstString name(reg.name);
280 ConstString alt_name(reg.alt_name);
281 m_reginfo->AddRegister(reg, name, alt_name, register_sets[idx]);
286 //------------------------------------------------------------------
287 // PluginInterface protocol
288 //------------------------------------------------------------------
289 ConstString OperatingSystemGo::GetPluginName() { return GetPluginNameStatic(); }
291 uint32_t OperatingSystemGo::GetPluginVersion() { return 1; }
293 bool OperatingSystemGo::UpdateThreadList(ThreadList &old_thread_list,
294 ThreadList &real_thread_list,
295 ThreadList &new_thread_list) {
296 new_thread_list = real_thread_list;
297 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
299 if (!(m_allg_sp || Init(real_thread_list)) || (m_allg_sp && !m_allglen_sp) ||
300 !GetGlobalPluginProperties()->GetEnableGoroutines()) {
301 return new_thread_list.GetSize(false) > 0;
305 log->Printf("OperatingSystemGo::UpdateThreadList(%d, %d, %d) fetching "
306 "thread data from Go for pid %" PRIu64,
307 old_thread_list.GetSize(false), real_thread_list.GetSize(false),
308 new_thread_list.GetSize(0), m_process->GetID());
309 uint64_t allglen = m_allglen_sp->GetValueAsUnsigned(0);
311 return new_thread_list.GetSize(false) > 0;
313 std::vector<Goroutine> goroutines;
314 // The threads that are in "new_thread_list" upon entry are the threads from
315 // the lldb_private::Process subclass, no memory threads will be in this
319 for (uint64_t i = 0; i < allglen; ++i) {
320 goroutines.push_back(CreateGoroutineAtIndex(i, err));
322 LLDB_LOG(log, "error: {0}", err);
323 return new_thread_list.GetSize(false) > 0;
326 // Make a map so we can match goroutines with backing threads.
327 std::map<uint64_t, ThreadSP> stack_map;
328 for (uint32_t i = 0; i < real_thread_list.GetSize(false); ++i) {
329 ThreadSP thread = real_thread_list.GetThreadAtIndex(i, false);
330 stack_map[thread->GetRegisterContext()->GetSP()] = thread;
332 for (const Goroutine &goroutine : goroutines) {
333 if (0 /* Gidle */ == goroutine.m_status ||
334 6 /* Gdead */ == goroutine.m_status) {
337 ThreadSP memory_thread =
338 old_thread_list.FindThreadByID(goroutine.m_goid, false);
339 if (memory_thread && IsOperatingSystemPluginThread(memory_thread) &&
340 memory_thread->IsValid()) {
341 memory_thread->ClearBackingThread();
343 memory_thread.reset(new ThreadMemory(*m_process, goroutine.m_goid, "", "",
346 // Search for the backing thread if the goroutine is running.
347 if (2 == (goroutine.m_status & 0xfff)) {
348 auto backing_it = stack_map.lower_bound(goroutine.m_lostack);
349 if (backing_it != stack_map.end()) {
350 if (goroutine.m_histack >= backing_it->first) {
353 "OperatingSystemGo::UpdateThreadList found backing thread "
354 "%" PRIx64 " (%" PRIx64 ") for thread %" PRIx64 "",
355 backing_it->second->GetID(),
356 backing_it->second->GetProtocolID(), memory_thread->GetID());
357 memory_thread->SetBackingThread(backing_it->second);
358 new_thread_list.RemoveThreadByID(backing_it->second->GetID(), false);
362 new_thread_list.AddThread(memory_thread);
365 return new_thread_list.GetSize(false) > 0;
368 void OperatingSystemGo::ThreadWasSelected(Thread *thread) {}
371 OperatingSystemGo::CreateRegisterContextForThread(Thread *thread,
372 addr_t reg_data_addr) {
373 RegisterContextSP reg_ctx_sp;
377 if (!IsOperatingSystemPluginThread(thread->shared_from_this()))
381 new RegisterContextGo(*thread, 0, *m_reginfo, reg_data_addr));
386 OperatingSystemGo::CreateThreadStopReason(lldb_private::Thread *thread) {
387 StopInfoSP stop_info_sp;
391 lldb::ThreadSP OperatingSystemGo::CreateThread(lldb::tid_t tid,
393 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
396 log->Printf("OperatingSystemGo::CreateThread (tid = 0x%" PRIx64
397 ", context = 0x%" PRIx64 ") not implemented",
403 ValueObjectSP OperatingSystemGo::FindGlobal(TargetSP target, const char *name) {
404 VariableList variable_list;
406 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
411 target->GetExecutableModule()->GetSpecificationDescription().c_str());
412 log->Printf("modules: %zu", target->GetImages().GetSize());
415 uint32_t match_count = target->GetImages().FindGlobalVariables(
416 ConstString(name), 1, variable_list);
417 if (match_count > 0) {
418 ExecutionContextScope *exe_scope = target->GetProcessSP().get();
419 if (exe_scope == NULL)
420 exe_scope = target.get();
421 return ValueObjectVariable::Create(exe_scope,
422 variable_list.GetVariableAtIndex(0));
424 return ValueObjectSP();
427 TypeSP OperatingSystemGo::FindType(TargetSP target_sp, const char *name) {
428 ConstString const_typename(name);
430 const bool exact_match = false;
432 const ModuleList &module_list = target_sp->GetImages();
433 size_t count = module_list.GetSize();
434 for (size_t idx = 0; idx < count; idx++) {
435 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
437 TypeSP type_sp(module_sp->FindFirstType(sc, const_typename, exact_match));
442 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS));
445 log->Printf("OperatingSystemGo::FindType(%s): not found", name);
449 OperatingSystemGo::Goroutine
450 OperatingSystemGo::CreateGoroutineAtIndex(uint64_t idx, Status &err) {
452 Goroutine result = {};
454 m_allg_sp->GetSyntheticArrayMember(idx, true)->Dereference(err);
459 ConstString name("goid");
460 ValueObjectSP val = g->GetChildMemberWithName(name, true);
461 bool success = false;
462 result.m_goid = val->GetValueAsUnsigned(0, &success);
464 err.SetErrorToGenericError();
465 err.SetErrorString("unable to read goid");
468 name.SetCString("atomicstatus");
469 val = g->GetChildMemberWithName(name, true);
470 result.m_status = (uint32_t)val->GetValueAsUnsigned(0, &success);
472 err.SetErrorToGenericError();
473 err.SetErrorString("unable to read atomicstatus");
476 name.SetCString("sched");
477 val = g->GetChildMemberWithName(name, true);
478 result.m_gobuf = val->GetAddressOf(false);
479 name.SetCString("stack");
480 val = g->GetChildMemberWithName(name, true);
481 name.SetCString("lo");
482 ValueObjectSP child = val->GetChildMemberWithName(name, true);
483 result.m_lostack = child->GetValueAsUnsigned(0, &success);
485 err.SetErrorToGenericError();
486 err.SetErrorString("unable to read stack.lo");
489 name.SetCString("hi");
490 child = val->GetChildMemberWithName(name, true);
491 result.m_histack = child->GetValueAsUnsigned(0, &success);
493 err.SetErrorToGenericError();
494 err.SetErrorString("unable to read stack.hi");