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 constructor
40 lldb::user_id_t uid, const char *name,
41 const char *mangled, // The mangled or fully qualified name of the variable.
42 const lldb::SymbolFileTypeSP &symfile_type_sp, ValueType scope,
43 SymbolContextScope *context, const RangeList &scope_range,
44 Declaration *decl_ptr, const DWARFExpression &location, bool external,
45 bool artificial, bool static_member)
46 : UserID(uid), m_name(name), m_mangled(ConstString(mangled)),
47 m_symfile_type_sp(symfile_type_sp), m_scope(scope),
48 m_owner_scope(context), m_scope_range(scope_range),
49 m_declaration(decl_ptr), m_location(location), m_external(external),
50 m_artificial(artificial), m_loc_is_const_data(false),
51 m_static_member(static_member) {}
54 Variable::~Variable() {}
56 lldb::LanguageType Variable::GetLanguage() const {
57 SymbolContext variable_sc;
58 m_owner_scope->CalculateSymbolContext(&variable_sc);
59 if (variable_sc.comp_unit)
60 return variable_sc.comp_unit->GetLanguage();
61 return lldb::eLanguageTypeUnknown;
64 ConstString Variable::GetName() const {
65 ConstString name = m_mangled.GetName(GetLanguage());
71 ConstString Variable::GetUnqualifiedName() const { return m_name; }
73 bool Variable::NameMatches(ConstString name) const {
76 SymbolContext variable_sc;
77 m_owner_scope->CalculateSymbolContext(&variable_sc);
79 LanguageType language = eLanguageTypeUnknown;
80 if (variable_sc.comp_unit)
81 language = variable_sc.comp_unit->GetLanguage();
82 return m_mangled.NameMatches(name, language);
84 bool Variable::NameMatches(const RegularExpression ®ex) const {
85 if (regex.Execute(m_name.AsCString()))
88 return m_mangled.NameMatches(regex, GetLanguage());
92 Type *Variable::GetType() {
93 if (m_symfile_type_sp)
94 return m_symfile_type_sp->GetType();
98 void Variable::Dump(Stream *s, bool show_context) const {
99 s->Printf("%p: ", static_cast<const void *>(this));
101 *s << "Variable" << (const UserID &)*this;
104 *s << ", name = \"" << m_name << "\"";
106 if (m_symfile_type_sp) {
107 Type *type = m_symfile_type_sp->GetType();
109 *s << ", type = {" << type->GetID() << "} " << (void *)type << " (";
110 type->DumpTypeName(s);
115 if (m_scope != eValueTypeInvalid) {
116 s->PutCString(", scope = ");
118 case eValueTypeVariableGlobal:
119 s->PutCString(m_external ? "global" : "static");
121 case eValueTypeVariableArgument:
122 s->PutCString("parameter");
124 case eValueTypeVariableLocal:
125 s->PutCString("local");
127 case eValueTypeVariableThreadLocal:
128 s->PutCString("thread local");
131 *s << "??? (" << m_scope << ')';
135 if (show_context && m_owner_scope != nullptr) {
136 s->PutCString(", context = ( ");
137 m_owner_scope->DumpSymbolContext(s);
141 bool show_fullpaths = false;
142 m_declaration.Dump(s, show_fullpaths);
144 if (m_location.IsValid()) {
145 s->PutCString(", location = ");
146 lldb::addr_t loclist_base_addr = LLDB_INVALID_ADDRESS;
147 if (m_location.IsLocationList()) {
148 SymbolContext variable_sc;
149 m_owner_scope->CalculateSymbolContext(&variable_sc);
150 if (variable_sc.function)
151 loclist_base_addr = variable_sc.function->GetAddressRange()
157 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
159 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
161 m_location.GetDescription(s, lldb::eDescriptionLevelBrief,
162 loclist_base_addr, abi.get());
166 s->PutCString(", external");
169 s->PutCString(", artificial");
174 bool Variable::DumpDeclaration(Stream *s, bool show_fullpaths,
176 bool dumped_declaration_info = false;
179 m_owner_scope->CalculateSymbolContext(&sc);
181 sc.line_entry.Clear();
182 bool show_inlined_frames = false;
183 const bool show_function_arguments = true;
184 const bool show_function_name = true;
186 dumped_declaration_info = sc.DumpStopContext(
187 s, nullptr, Address(), show_fullpaths, show_module, show_inlined_frames,
188 show_function_arguments, show_function_name);
193 if (m_declaration.DumpStopContext(s, false))
194 dumped_declaration_info = true;
195 return dumped_declaration_info;
198 size_t Variable::MemorySize() const { return sizeof(Variable); }
200 CompilerDeclContext Variable::GetDeclContext() {
201 Type *type = GetType();
203 return type->GetSymbolFile()->GetDeclContextContainingUID(GetID());
204 return CompilerDeclContext();
207 CompilerDecl Variable::GetDecl() {
208 Type *type = GetType();
209 return type ? type->GetSymbolFile()->GetDeclForUID(GetID()) : CompilerDecl();
212 void Variable::CalculateSymbolContext(SymbolContext *sc) {
214 m_owner_scope->CalculateSymbolContext(sc);
220 bool Variable::LocationIsValidForFrame(StackFrame *frame) {
221 // Is the variable is described by a single location?
222 if (!m_location.IsLocationList()) {
223 // Yes it is, the location is valid.
229 frame->GetSymbolContext(eSymbolContextFunction).function;
231 TargetSP target_sp(frame->CalculateTarget());
233 addr_t loclist_base_load_addr =
234 function->GetAddressRange().GetBaseAddress().GetLoadAddress(
236 if (loclist_base_load_addr == LLDB_INVALID_ADDRESS)
238 // It is a location list. We just need to tell if the location list
239 // contains the current address when converted to a load address
240 return m_location.LocationListContainsAddress(
241 loclist_base_load_addr,
242 frame->GetFrameCodeAddress().GetLoadAddress(target_sp.get()));
248 bool Variable::LocationIsValidForAddress(const Address &address) {
249 // Be sure to resolve the address to section offset prior to calling this
251 if (address.IsSectionOffset()) {
253 CalculateSymbolContext(&sc);
254 if (sc.module_sp == address.GetModule()) {
255 // Is the variable is described by a single location?
256 if (!m_location.IsLocationList()) {
257 // Yes it is, the location is valid.
262 addr_t loclist_base_file_addr =
263 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
264 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
266 // It is a location list. We just need to tell if the location list
267 // contains the current address when converted to a load address
268 return m_location.LocationListContainsAddress(loclist_base_file_addr,
269 address.GetFileAddress());
276 bool Variable::IsInScope(StackFrame *frame) {
278 case eValueTypeRegister:
279 case eValueTypeRegisterSet:
280 return frame != nullptr;
282 case eValueTypeConstResult:
283 case eValueTypeVariableGlobal:
284 case eValueTypeVariableStatic:
285 case eValueTypeVariableThreadLocal:
288 case eValueTypeVariableArgument:
289 case eValueTypeVariableLocal:
291 // We don't have a location list, we just need to see if the block that
292 // this variable was defined in is currently
293 Block *deepest_frame_block =
294 frame->GetSymbolContext(eSymbolContextBlock).block;
295 if (deepest_frame_block) {
296 SymbolContext variable_sc;
297 CalculateSymbolContext(&variable_sc);
299 // Check for static or global variable defined at the compile unit
300 // level that wasn't defined in a block
301 if (variable_sc.block == nullptr)
304 // Check if the variable is valid in the current block
305 if (variable_sc.block != deepest_frame_block &&
306 !variable_sc.block->Contains(deepest_frame_block))
309 // If no scope range is specified then it means that the scope is the
310 // same as the scope of the enclosing lexical block.
311 if (m_scope_range.IsEmpty())
314 addr_t file_address = frame->GetFrameCodeAddress().GetFileAddress();
315 return m_scope_range.FindEntryThatContains(file_address) != nullptr;
326 Status Variable::GetValuesForVariableExpressionPath(
327 llvm::StringRef variable_expr_path, ExecutionContextScope *scope,
328 GetVariableCallback callback, void *baton, VariableList &variable_list,
329 ValueObjectList &valobj_list) {
331 if (!callback || variable_expr_path.empty()) {
332 error.SetErrorString("unknown error");
336 switch (variable_expr_path.front()) {
338 error = Variable::GetValuesForVariableExpressionPath(
339 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
342 error.SetErrorString("unknown error");
345 for (uint32_t i = 0; i < valobj_list.GetSize();) {
347 ValueObjectSP valobj_sp(
348 valobj_list.GetValueObjectAtIndex(i)->Dereference(tmp_error));
349 if (tmp_error.Fail()) {
350 variable_list.RemoveVariableAtIndex(i);
351 valobj_list.RemoveValueObjectAtIndex(i);
353 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
359 error = Variable::GetValuesForVariableExpressionPath(
360 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
362 if (error.Success()) {
363 for (uint32_t i = 0; i < valobj_list.GetSize();) {
365 ValueObjectSP valobj_sp(
366 valobj_list.GetValueObjectAtIndex(i)->AddressOf(tmp_error));
367 if (tmp_error.Fail()) {
368 variable_list.RemoveVariableAtIndex(i);
369 valobj_list.RemoveValueObjectAtIndex(i);
371 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
376 error.SetErrorString("unknown error");
382 static RegularExpression g_regex(
383 llvm::StringRef("^([A-Za-z_:][A-Za-z_0-9:]*)(.*)"));
384 RegularExpression::Match regex_match(1);
385 std::string variable_name;
386 variable_list.Clear();
387 if (!g_regex.Execute(variable_expr_path, ®ex_match)) {
388 error.SetErrorStringWithFormat(
389 "unable to extract a variable name from '%s'",
390 variable_expr_path.str().c_str());
393 if (!regex_match.GetMatchAtIndex(variable_expr_path, 1, variable_name)) {
394 error.SetErrorStringWithFormat(
395 "unable to extract a variable name from '%s'",
396 variable_expr_path.str().c_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,
489 StringList &matches, bool &word_complete);
491 static void PrivateAutoCompleteMembers(
492 StackFrame *frame, const std::string &partial_member_name,
493 llvm::StringRef partial_path,
495 &prefix_path, // Anything that has been resolved already will be in here
496 const CompilerType &compiler_type,
497 StringList &matches, bool &word_complete);
499 static void PrivateAutoCompleteMembers(
500 StackFrame *frame, const std::string &partial_member_name,
501 llvm::StringRef partial_path,
503 &prefix_path, // Anything that has been resolved already will be in here
504 const CompilerType &compiler_type,
505 StringList &matches, bool &word_complete) {
507 // We are in a type parsing child members
508 const uint32_t num_bases = compiler_type.GetNumDirectBaseClasses();
511 for (uint32_t i = 0; i < num_bases; ++i) {
512 CompilerType base_class_type =
513 compiler_type.GetDirectBaseClassAtIndex(i, nullptr);
515 PrivateAutoCompleteMembers(
516 frame, partial_member_name, partial_path, prefix_path,
517 base_class_type.GetCanonicalType(), matches, word_complete);
521 const uint32_t num_vbases = compiler_type.GetNumVirtualBaseClasses();
523 if (num_vbases > 0) {
524 for (uint32_t i = 0; i < num_vbases; ++i) {
525 CompilerType vbase_class_type =
526 compiler_type.GetVirtualBaseClassAtIndex(i, nullptr);
528 PrivateAutoCompleteMembers(
529 frame, partial_member_name, partial_path, prefix_path,
530 vbase_class_type.GetCanonicalType(), matches, word_complete);
534 // We are in a type parsing child members
535 const uint32_t num_fields = compiler_type.GetNumFields();
537 if (num_fields > 0) {
538 for (uint32_t i = 0; i < num_fields; ++i) {
539 std::string member_name;
541 CompilerType member_compiler_type = compiler_type.GetFieldAtIndex(
542 i, member_name, nullptr, nullptr, nullptr);
544 if (partial_member_name.empty() ||
545 member_name.find(partial_member_name) == 0) {
546 if (member_name == partial_member_name) {
549 prefix_path + member_name, // Anything that has been resolved
550 // already will be in here
551 member_compiler_type.GetCanonicalType(), matches, word_complete);
553 matches.AppendString((prefix_path + member_name).str());
560 static void PrivateAutoComplete(
561 StackFrame *frame, llvm::StringRef partial_path,
563 &prefix_path, // Anything that has been resolved already will be in here
564 const CompilerType &compiler_type,
565 StringList &matches, bool &word_complete) {
566 // printf ("\nPrivateAutoComplete()\n\tprefix_path = '%s'\n\tpartial_path =
567 // '%s'\n", prefix_path.c_str(), partial_path.c_str());
568 std::string remaining_partial_path;
570 const lldb::TypeClass type_class = compiler_type.GetTypeClass();
571 if (partial_path.empty()) {
572 if (compiler_type.IsValid()) {
573 switch (type_class) {
575 case eTypeClassArray:
576 case eTypeClassBlockPointer:
577 case eTypeClassBuiltin:
578 case eTypeClassComplexFloat:
579 case eTypeClassComplexInteger:
580 case eTypeClassEnumeration:
581 case eTypeClassFunction:
582 case eTypeClassMemberPointer:
583 case eTypeClassReference:
584 case eTypeClassTypedef:
585 case eTypeClassVector: {
586 matches.AppendString(prefix_path.str());
587 word_complete = matches.GetSize() == 1;
590 case eTypeClassClass:
591 case eTypeClassStruct:
592 case eTypeClassUnion:
593 if (prefix_path.str().back() != '.')
594 matches.AppendString((prefix_path + ".").str());
597 case eTypeClassObjCObject:
598 case eTypeClassObjCInterface:
600 case eTypeClassObjCObjectPointer:
601 case eTypeClassPointer: {
602 bool omit_empty_base_classes = true;
603 if (compiler_type.GetNumChildren(omit_empty_base_classes, nullptr) > 0)
604 matches.AppendString((prefix_path + "->").str());
606 matches.AppendString(prefix_path.str());
607 word_complete = true;
613 const bool get_file_globals = true;
615 VariableList *variable_list = frame->GetVariableList(get_file_globals);
618 const size_t num_variables = variable_list->GetSize();
619 for (size_t i = 0; i < num_variables; ++i) {
620 Variable *variable = variable_list->GetVariableAtIndex(i).get();
621 matches.AppendString(variable->GetName().AsCString());
627 const char ch = partial_path[0];
630 if (prefix_path.str().empty()) {
631 PrivateAutoComplete(frame, partial_path.substr(1), "*", compiler_type,
632 matches, word_complete);
637 if (prefix_path.isTriviallyEmpty()) {
638 PrivateAutoComplete(frame, partial_path.substr(1), std::string("&"),
639 compiler_type, matches, word_complete);
644 if (partial_path.size() > 1 && partial_path[1] == '>' &&
645 !prefix_path.str().empty()) {
646 switch (type_class) {
647 case lldb::eTypeClassPointer: {
648 CompilerType pointee_type(compiler_type.GetPointeeType());
649 if (partial_path.size() > 2 && partial_path[2]) {
650 // If there is more after the "->", then search deeper
652 frame, partial_path.substr(2), prefix_path + "->",
653 pointee_type.GetCanonicalType(), matches, word_complete);
655 // Nothing after the "->", so list all members
656 PrivateAutoCompleteMembers(
657 frame, std::string(), std::string(), prefix_path + "->",
658 pointee_type.GetCanonicalType(), matches, word_complete);
668 if (compiler_type.IsValid()) {
669 switch (type_class) {
670 case lldb::eTypeClassUnion:
671 case lldb::eTypeClassStruct:
672 case lldb::eTypeClassClass:
673 if (partial_path.size() > 1 && partial_path[1]) {
674 // If there is more after the ".", then search deeper
675 PrivateAutoComplete(frame, partial_path.substr(1),
676 prefix_path + ".", compiler_type, matches,
680 // Nothing after the ".", so list all members
681 PrivateAutoCompleteMembers(frame, std::string(), partial_path,
682 prefix_path + ".", compiler_type,
683 matches, word_complete);
692 if (isalpha(ch) || ch == '_' || ch == '$') {
693 const size_t partial_path_len = partial_path.size();
695 while (pos < partial_path_len) {
696 const char curr_ch = partial_path[pos];
697 if (isalnum(curr_ch) || curr_ch == '_' || curr_ch == '$') {
704 std::string token(partial_path, 0, pos);
705 remaining_partial_path = partial_path.substr(pos);
707 if (compiler_type.IsValid()) {
708 PrivateAutoCompleteMembers(frame, token, remaining_partial_path,
709 prefix_path, compiler_type, matches,
712 // We haven't found our variable yet
713 const bool get_file_globals = true;
715 VariableList *variable_list =
716 frame->GetVariableList(get_file_globals);
721 const size_t num_variables = variable_list->GetSize();
722 for (size_t i = 0; i < num_variables; ++i) {
723 Variable *variable = variable_list->GetVariableAtIndex(i).get();
728 const char *variable_name = variable->GetName().AsCString();
729 if (strstr(variable_name, token.c_str()) == variable_name) {
730 if (strcmp(variable_name, token.c_str()) == 0) {
731 Type *variable_type = variable->GetType();
733 CompilerType variable_compiler_type(
734 variable_type->GetForwardCompilerType());
736 frame, remaining_partial_path,
737 prefix_path + token, // Anything that has been resolved
738 // already will be in here
739 variable_compiler_type.GetCanonicalType(), matches,
742 matches.AppendString((prefix_path + variable_name).str());
744 } else if (remaining_partial_path.empty()) {
745 matches.AppendString((prefix_path + variable_name).str());
756 size_t Variable::AutoComplete(const ExecutionContext &exe_ctx,
757 CompletionRequest &request) {
758 CompilerType compiler_type;
760 bool word_complete = false;
762 PrivateAutoComplete(exe_ctx.GetFramePtr(), request.GetCursorArgumentPrefix(),
763 "", compiler_type, matches, word_complete);
764 request.SetWordComplete(word_complete);
765 request.AddCompletions(matches);
767 return request.GetNumberOfMatches();