1 //===-- Variable.cpp --------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Symbol/Variable.h"
11 #include "lldb/Core/Module.h"
12 #include "lldb/Core/ValueObject.h"
13 #include "lldb/Core/ValueObjectVariable.h"
14 #include "lldb/Symbol/Block.h"
15 #include "lldb/Symbol/CompileUnit.h"
16 #include "lldb/Symbol/CompilerDecl.h"
17 #include "lldb/Symbol/CompilerDeclContext.h"
18 #include "lldb/Symbol/Function.h"
19 #include "lldb/Symbol/SymbolContext.h"
20 #include "lldb/Symbol/SymbolFile.h"
21 #include "lldb/Symbol/Type.h"
22 #include "lldb/Symbol/TypeSystem.h"
23 #include "lldb/Symbol/VariableList.h"
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/StackFrame.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 #include "lldb/Utility/RegularExpression.h"
31 #include "lldb/Utility/Stream.h"
33 #include "llvm/ADT/Twine.h"
36 using namespace lldb_private;
38 Variable::Variable(lldb::user_id_t uid, const char *name, const char *mangled,
39 const lldb::SymbolFileTypeSP &symfile_type_sp,
40 ValueType scope, SymbolContextScope *context,
41 const RangeList &scope_range, Declaration *decl_ptr,
42 const DWARFExpression &location, bool external,
43 bool artificial, bool static_member)
44 : UserID(uid), m_name(name), m_mangled(ConstString(mangled)),
45 m_symfile_type_sp(symfile_type_sp), m_scope(scope),
46 m_owner_scope(context), m_scope_range(scope_range),
47 m_declaration(decl_ptr), m_location(location), m_external(external),
48 m_artificial(artificial), m_loc_is_const_data(false),
49 m_static_member(static_member) {}
51 Variable::~Variable() {}
53 lldb::LanguageType Variable::GetLanguage() const {
54 lldb::LanguageType lang = m_mangled.GuessLanguage();
55 if (lang != lldb::eLanguageTypeUnknown)
58 if (auto *func = m_owner_scope->CalculateSymbolContextFunction()) {
59 if ((lang = func->GetLanguage()) != lldb::eLanguageTypeUnknown)
61 } else if (auto *comp_unit =
62 m_owner_scope->CalculateSymbolContextCompileUnit()) {
63 if ((lang = comp_unit->GetLanguage()) != lldb::eLanguageTypeUnknown)
67 return lldb::eLanguageTypeUnknown;
70 ConstString Variable::GetName() const {
71 ConstString name = m_mangled.GetName(GetLanguage());
77 ConstString Variable::GetUnqualifiedName() const { return m_name; }
79 bool Variable::NameMatches(ConstString name) const {
82 SymbolContext variable_sc;
83 m_owner_scope->CalculateSymbolContext(&variable_sc);
85 LanguageType language = eLanguageTypeUnknown;
86 if (variable_sc.comp_unit)
87 language = variable_sc.comp_unit->GetLanguage();
88 return m_mangled.NameMatches(name, language);
90 bool Variable::NameMatches(const RegularExpression ®ex) const {
91 if (regex.Execute(m_name.AsCString()))
94 return m_mangled.NameMatches(regex, GetLanguage());
98 Type *Variable::GetType() {
99 if (m_symfile_type_sp)
100 return m_symfile_type_sp->GetType();
104 void Variable::Dump(Stream *s, bool show_context) const {
105 s->Printf("%p: ", static_cast<const void *>(this));
107 *s << "Variable" << (const UserID &)*this;
110 *s << ", name = \"" << m_name << "\"";
112 if (m_symfile_type_sp) {
113 Type *type = m_symfile_type_sp->GetType();
115 s->Format(", type = {{{0:x-16}} {1} (", type->GetID(), type);
116 type->DumpTypeName(s);
121 if (m_scope != eValueTypeInvalid) {
122 s->PutCString(", scope = ");
124 case eValueTypeVariableGlobal:
125 s->PutCString(m_external ? "global" : "static");
127 case eValueTypeVariableArgument:
128 s->PutCString("parameter");
130 case eValueTypeVariableLocal:
131 s->PutCString("local");
133 case eValueTypeVariableThreadLocal:
134 s->PutCString("thread local");
137 s->AsRawOstream() << "??? (" << m_scope << ')';
141 if (show_context && m_owner_scope != nullptr) {
142 s->PutCString(", context = ( ");
143 m_owner_scope->DumpSymbolContext(s);
147 bool show_fullpaths = false;
148 m_declaration.Dump(s, show_fullpaths);
150 if (m_location.IsValid()) {
151 s->PutCString(", location = ");
152 lldb::addr_t loclist_base_addr = LLDB_INVALID_ADDRESS;
153 if (m_location.IsLocationList()) {
154 SymbolContext variable_sc;
155 m_owner_scope->CalculateSymbolContext(&variable_sc);
156 if (variable_sc.function)
157 loclist_base_addr = variable_sc.function->GetAddressRange()
163 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
165 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
167 m_location.GetDescription(s, lldb::eDescriptionLevelBrief,
168 loclist_base_addr, abi.get());
172 s->PutCString(", external");
175 s->PutCString(", artificial");
180 bool Variable::DumpDeclaration(Stream *s, bool show_fullpaths,
182 bool dumped_declaration_info = false;
185 m_owner_scope->CalculateSymbolContext(&sc);
187 sc.line_entry.Clear();
188 bool show_inlined_frames = false;
189 const bool show_function_arguments = true;
190 const bool show_function_name = true;
192 dumped_declaration_info = sc.DumpStopContext(
193 s, nullptr, Address(), show_fullpaths, show_module, show_inlined_frames,
194 show_function_arguments, show_function_name);
199 if (m_declaration.DumpStopContext(s, false))
200 dumped_declaration_info = true;
201 return dumped_declaration_info;
204 size_t Variable::MemorySize() const { return sizeof(Variable); }
206 CompilerDeclContext Variable::GetDeclContext() {
207 Type *type = GetType();
209 return type->GetSymbolFile()->GetDeclContextContainingUID(GetID());
210 return CompilerDeclContext();
213 CompilerDecl Variable::GetDecl() {
214 Type *type = GetType();
215 return type ? type->GetSymbolFile()->GetDeclForUID(GetID()) : CompilerDecl();
218 void Variable::CalculateSymbolContext(SymbolContext *sc) {
220 m_owner_scope->CalculateSymbolContext(sc);
226 bool Variable::LocationIsValidForFrame(StackFrame *frame) {
227 // Is the variable is described by a single location?
228 if (!m_location.IsLocationList()) {
229 // Yes it is, the location is valid.
235 frame->GetSymbolContext(eSymbolContextFunction).function;
237 TargetSP target_sp(frame->CalculateTarget());
239 addr_t loclist_base_load_addr =
240 function->GetAddressRange().GetBaseAddress().GetLoadAddress(
242 if (loclist_base_load_addr == LLDB_INVALID_ADDRESS)
244 // It is a location list. We just need to tell if the location list
245 // contains the current address when converted to a load address
246 return m_location.LocationListContainsAddress(
247 loclist_base_load_addr,
248 frame->GetFrameCodeAddress().GetLoadAddress(target_sp.get()));
254 bool Variable::LocationIsValidForAddress(const Address &address) {
255 // Be sure to resolve the address to section offset prior to calling this
257 if (address.IsSectionOffset()) {
259 CalculateSymbolContext(&sc);
260 if (sc.module_sp == address.GetModule()) {
261 // Is the variable is described by a single location?
262 if (!m_location.IsLocationList()) {
263 // Yes it is, the location is valid.
268 addr_t loclist_base_file_addr =
269 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
270 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
272 // It is a location list. We just need to tell if the location list
273 // contains the current address when converted to a load address
274 return m_location.LocationListContainsAddress(loclist_base_file_addr,
275 address.GetFileAddress());
282 bool Variable::IsInScope(StackFrame *frame) {
284 case eValueTypeRegister:
285 case eValueTypeRegisterSet:
286 return frame != nullptr;
288 case eValueTypeConstResult:
289 case eValueTypeVariableGlobal:
290 case eValueTypeVariableStatic:
291 case eValueTypeVariableThreadLocal:
294 case eValueTypeVariableArgument:
295 case eValueTypeVariableLocal:
297 // We don't have a location list, we just need to see if the block that
298 // this variable was defined in is currently
299 Block *deepest_frame_block =
300 frame->GetSymbolContext(eSymbolContextBlock).block;
301 if (deepest_frame_block) {
302 SymbolContext variable_sc;
303 CalculateSymbolContext(&variable_sc);
305 // Check for static or global variable defined at the compile unit
306 // level that wasn't defined in a block
307 if (variable_sc.block == nullptr)
310 // Check if the variable is valid in the current block
311 if (variable_sc.block != deepest_frame_block &&
312 !variable_sc.block->Contains(deepest_frame_block))
315 // If no scope range is specified then it means that the scope is the
316 // same as the scope of the enclosing lexical block.
317 if (m_scope_range.IsEmpty())
320 addr_t file_address = frame->GetFrameCodeAddress().GetFileAddress();
321 return m_scope_range.FindEntryThatContains(file_address) != nullptr;
332 Status Variable::GetValuesForVariableExpressionPath(
333 llvm::StringRef variable_expr_path, ExecutionContextScope *scope,
334 GetVariableCallback callback, void *baton, VariableList &variable_list,
335 ValueObjectList &valobj_list) {
337 if (!callback || variable_expr_path.empty()) {
338 error.SetErrorString("unknown error");
342 switch (variable_expr_path.front()) {
344 error = Variable::GetValuesForVariableExpressionPath(
345 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
348 error.SetErrorString("unknown error");
351 for (uint32_t i = 0; i < valobj_list.GetSize();) {
353 ValueObjectSP valobj_sp(
354 valobj_list.GetValueObjectAtIndex(i)->Dereference(tmp_error));
355 if (tmp_error.Fail()) {
356 variable_list.RemoveVariableAtIndex(i);
357 valobj_list.RemoveValueObjectAtIndex(i);
359 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
365 error = Variable::GetValuesForVariableExpressionPath(
366 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
368 if (error.Success()) {
369 for (uint32_t i = 0; i < valobj_list.GetSize();) {
371 ValueObjectSP valobj_sp(
372 valobj_list.GetValueObjectAtIndex(i)->AddressOf(tmp_error));
373 if (tmp_error.Fail()) {
374 variable_list.RemoveVariableAtIndex(i);
375 valobj_list.RemoveValueObjectAtIndex(i);
377 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
382 error.SetErrorString("unknown error");
388 static RegularExpression g_regex(
389 llvm::StringRef("^([A-Za-z_:][A-Za-z_0-9:]*)(.*)"));
390 llvm::SmallVector<llvm::StringRef, 2> matches;
391 variable_list.Clear();
392 if (!g_regex.Execute(variable_expr_path, &matches)) {
393 error.SetErrorStringWithFormat(
394 "unable to extract a variable name from '%s'",
395 variable_expr_path.str().c_str());
398 std::string variable_name = matches[1].str();
399 if (!callback(baton, variable_name.c_str(), variable_list)) {
400 error.SetErrorString("unknown error");
404 while (i < variable_list.GetSize()) {
405 VariableSP var_sp(variable_list.GetVariableAtIndex(i));
406 ValueObjectSP valobj_sp;
408 variable_list.RemoveVariableAtIndex(i);
411 ValueObjectSP variable_valobj_sp(
412 ValueObjectVariable::Create(scope, var_sp));
413 if (!variable_valobj_sp) {
414 variable_list.RemoveVariableAtIndex(i);
418 llvm::StringRef variable_sub_expr_path =
419 variable_expr_path.drop_front(variable_name.size());
420 if (!variable_sub_expr_path.empty()) {
421 valobj_sp = variable_valobj_sp->GetValueForExpressionPath(
422 variable_sub_expr_path);
424 error.SetErrorStringWithFormat(
425 "invalid expression path '%s' for variable '%s'",
426 variable_sub_expr_path.str().c_str(),
427 var_sp->GetName().GetCString());
428 variable_list.RemoveVariableAtIndex(i);
432 // Just the name of a variable with no extras
433 valobj_sp = variable_valobj_sp;
436 valobj_list.Append(valobj_sp);
440 if (variable_list.GetSize() > 0) {
446 error.SetErrorString("unknown error");
450 bool Variable::DumpLocationForAddress(Stream *s, const Address &address) {
451 // Be sure to resolve the address to section offset prior to calling this
453 if (address.IsSectionOffset()) {
455 CalculateSymbolContext(&sc);
456 if (sc.module_sp == address.GetModule()) {
459 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
461 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
464 const addr_t file_addr = address.GetFileAddress();
466 if (sc.function->GetAddressRange().ContainsFileAddress(address)) {
467 addr_t loclist_base_file_addr =
468 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
469 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
471 return m_location.DumpLocationForAddress(s, eDescriptionLevelBrief,
472 loclist_base_file_addr,
473 file_addr, abi.get());
476 return m_location.DumpLocationForAddress(s, eDescriptionLevelBrief,
477 LLDB_INVALID_ADDRESS, file_addr,
484 static void PrivateAutoComplete(
485 StackFrame *frame, llvm::StringRef partial_path,
487 &prefix_path, // Anything that has been resolved already will be in here
488 const CompilerType &compiler_type, CompletionRequest &request);
490 static void PrivateAutoCompleteMembers(
491 StackFrame *frame, const std::string &partial_member_name,
492 llvm::StringRef partial_path,
494 &prefix_path, // Anything that has been resolved already will be in here
495 const CompilerType &compiler_type, CompletionRequest &request) {
497 // We are in a type parsing child members
498 const uint32_t num_bases = compiler_type.GetNumDirectBaseClasses();
501 for (uint32_t i = 0; i < num_bases; ++i) {
502 CompilerType base_class_type =
503 compiler_type.GetDirectBaseClassAtIndex(i, nullptr);
505 PrivateAutoCompleteMembers(frame, partial_member_name, partial_path,
507 base_class_type.GetCanonicalType(), request);
511 const uint32_t num_vbases = compiler_type.GetNumVirtualBaseClasses();
513 if (num_vbases > 0) {
514 for (uint32_t i = 0; i < num_vbases; ++i) {
515 CompilerType vbase_class_type =
516 compiler_type.GetVirtualBaseClassAtIndex(i, nullptr);
518 PrivateAutoCompleteMembers(frame, partial_member_name, partial_path,
520 vbase_class_type.GetCanonicalType(), request);
524 // We are in a type parsing child members
525 const uint32_t num_fields = compiler_type.GetNumFields();
527 if (num_fields > 0) {
528 for (uint32_t i = 0; i < num_fields; ++i) {
529 std::string member_name;
531 CompilerType member_compiler_type = compiler_type.GetFieldAtIndex(
532 i, member_name, nullptr, nullptr, nullptr);
534 if (partial_member_name.empty() ||
535 member_name.find(partial_member_name) == 0) {
536 if (member_name == partial_member_name) {
539 prefix_path + member_name, // Anything that has been resolved
540 // already will be in here
541 member_compiler_type.GetCanonicalType(), request);
543 request.AddCompletion((prefix_path + member_name).str());
550 static void PrivateAutoComplete(
551 StackFrame *frame, llvm::StringRef partial_path,
553 &prefix_path, // Anything that has been resolved already will be in here
554 const CompilerType &compiler_type, CompletionRequest &request) {
555 // printf ("\nPrivateAutoComplete()\n\tprefix_path = '%s'\n\tpartial_path =
556 // '%s'\n", prefix_path.c_str(), partial_path.c_str());
557 std::string remaining_partial_path;
559 const lldb::TypeClass type_class = compiler_type.GetTypeClass();
560 if (partial_path.empty()) {
561 if (compiler_type.IsValid()) {
562 switch (type_class) {
564 case eTypeClassArray:
565 case eTypeClassBlockPointer:
566 case eTypeClassBuiltin:
567 case eTypeClassComplexFloat:
568 case eTypeClassComplexInteger:
569 case eTypeClassEnumeration:
570 case eTypeClassFunction:
571 case eTypeClassMemberPointer:
572 case eTypeClassReference:
573 case eTypeClassTypedef:
574 case eTypeClassVector: {
575 request.AddCompletion(prefix_path.str());
578 case eTypeClassClass:
579 case eTypeClassStruct:
580 case eTypeClassUnion:
581 if (prefix_path.str().back() != '.')
582 request.AddCompletion((prefix_path + ".").str());
585 case eTypeClassObjCObject:
586 case eTypeClassObjCInterface:
588 case eTypeClassObjCObjectPointer:
589 case eTypeClassPointer: {
590 bool omit_empty_base_classes = true;
591 if (compiler_type.GetNumChildren(omit_empty_base_classes, nullptr) > 0)
592 request.AddCompletion((prefix_path + "->").str());
594 request.AddCompletion(prefix_path.str());
600 const bool get_file_globals = true;
602 VariableList *variable_list = frame->GetVariableList(get_file_globals);
605 for (const VariableSP &var_sp : *variable_list)
606 request.AddCompletion(var_sp->GetName().AsCString());
611 const char ch = partial_path[0];
614 if (prefix_path.str().empty()) {
615 PrivateAutoComplete(frame, partial_path.substr(1), "*", compiler_type,
621 if (prefix_path.isTriviallyEmpty()) {
622 PrivateAutoComplete(frame, partial_path.substr(1), std::string("&"),
623 compiler_type, request);
628 if (partial_path.size() > 1 && partial_path[1] == '>' &&
629 !prefix_path.str().empty()) {
630 switch (type_class) {
631 case lldb::eTypeClassPointer: {
632 CompilerType pointee_type(compiler_type.GetPointeeType());
633 if (partial_path.size() > 2 && partial_path[2]) {
634 // If there is more after the "->", then search deeper
635 PrivateAutoComplete(frame, partial_path.substr(2),
637 pointee_type.GetCanonicalType(), request);
639 // Nothing after the "->", so list all members
640 PrivateAutoCompleteMembers(
641 frame, std::string(), std::string(), prefix_path + "->",
642 pointee_type.GetCanonicalType(), request);
652 if (compiler_type.IsValid()) {
653 switch (type_class) {
654 case lldb::eTypeClassUnion:
655 case lldb::eTypeClassStruct:
656 case lldb::eTypeClassClass:
657 if (partial_path.size() > 1 && partial_path[1]) {
658 // If there is more after the ".", then search deeper
659 PrivateAutoComplete(frame, partial_path.substr(1),
660 prefix_path + ".", compiler_type, request);
663 // Nothing after the ".", so list all members
664 PrivateAutoCompleteMembers(frame, std::string(), partial_path,
665 prefix_path + ".", compiler_type,
675 if (isalpha(ch) || ch == '_' || ch == '$') {
676 const size_t partial_path_len = partial_path.size();
678 while (pos < partial_path_len) {
679 const char curr_ch = partial_path[pos];
680 if (isalnum(curr_ch) || curr_ch == '_' || curr_ch == '$') {
687 std::string token(partial_path, 0, pos);
688 remaining_partial_path = partial_path.substr(pos);
690 if (compiler_type.IsValid()) {
691 PrivateAutoCompleteMembers(frame, token, remaining_partial_path,
692 prefix_path, compiler_type, request);
694 // We haven't found our variable yet
695 const bool get_file_globals = true;
697 VariableList *variable_list =
698 frame->GetVariableList(get_file_globals);
703 for (VariableSP var_sp : *variable_list) {
708 llvm::StringRef variable_name = var_sp->GetName().GetStringRef();
709 if (variable_name.startswith(token)) {
710 if (variable_name == token) {
711 Type *variable_type = var_sp->GetType();
713 CompilerType variable_compiler_type(
714 variable_type->GetForwardCompilerType());
716 frame, remaining_partial_path,
717 prefix_path + token, // Anything that has been resolved
718 // already will be in here
719 variable_compiler_type.GetCanonicalType(), request);
721 request.AddCompletion((prefix_path + variable_name).str());
723 } else if (remaining_partial_path.empty()) {
724 request.AddCompletion((prefix_path + variable_name).str());
735 void Variable::AutoComplete(const ExecutionContext &exe_ctx,
736 CompletionRequest &request) {
737 CompilerType compiler_type;
739 PrivateAutoComplete(exe_ctx.GetFramePtr(), request.GetCursorArgumentPrefix(),
740 "", compiler_type, request);