1 //===-- Variable.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 //===----------------------------------------------------------------------===//
10 #include "lldb/Symbol/Variable.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ValueObject.h"
14 #include "lldb/Core/ValueObjectVariable.h"
15 #include "lldb/Symbol/Block.h"
16 #include "lldb/Symbol/CompileUnit.h"
17 #include "lldb/Symbol/CompilerDecl.h"
18 #include "lldb/Symbol/CompilerDeclContext.h"
19 #include "lldb/Symbol/Function.h"
20 #include "lldb/Symbol/SymbolContext.h"
21 #include "lldb/Symbol/SymbolFile.h"
22 #include "lldb/Symbol/Type.h"
23 #include "lldb/Symbol/TypeSystem.h"
24 #include "lldb/Symbol/VariableList.h"
25 #include "lldb/Target/ABI.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/StackFrame.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Utility/RegularExpression.h"
32 #include "lldb/Utility/Stream.h"
34 #include "llvm/ADT/Twine.h"
37 using namespace lldb_private;
39 //----------------------------------------------------------------------
40 // Variable constructor
41 //----------------------------------------------------------------------
43 lldb::user_id_t uid, const char *name,
44 const char *mangled, // The mangled or fully qualified name of the variable.
45 const lldb::SymbolFileTypeSP &symfile_type_sp, ValueType scope,
46 SymbolContextScope *context, const RangeList &scope_range,
47 Declaration *decl_ptr, const DWARFExpression &location, bool external,
48 bool artificial, bool static_member)
49 : UserID(uid), m_name(name), m_mangled(ConstString(mangled)),
50 m_symfile_type_sp(symfile_type_sp), m_scope(scope),
51 m_owner_scope(context), m_scope_range(scope_range),
52 m_declaration(decl_ptr), m_location(location), m_external(external),
53 m_artificial(artificial), m_static_member(static_member) {}
55 //----------------------------------------------------------------------
57 //----------------------------------------------------------------------
58 Variable::~Variable() {}
60 lldb::LanguageType Variable::GetLanguage() const {
61 SymbolContext variable_sc;
62 m_owner_scope->CalculateSymbolContext(&variable_sc);
63 if (variable_sc.comp_unit)
64 return variable_sc.comp_unit->GetLanguage();
65 return lldb::eLanguageTypeUnknown;
68 ConstString Variable::GetName() const {
69 ConstString name = m_mangled.GetName(GetLanguage());
75 ConstString Variable::GetUnqualifiedName() const { return m_name; }
77 bool Variable::NameMatches(const ConstString &name) const {
80 SymbolContext variable_sc;
81 m_owner_scope->CalculateSymbolContext(&variable_sc);
83 LanguageType language = eLanguageTypeUnknown;
84 if (variable_sc.comp_unit)
85 language = variable_sc.comp_unit->GetLanguage();
86 return m_mangled.NameMatches(name, language);
88 bool Variable::NameMatches(const RegularExpression ®ex) const {
89 if (regex.Execute(m_name.AsCString()))
92 return m_mangled.NameMatches(regex, GetLanguage());
96 Type *Variable::GetType() {
97 if (m_symfile_type_sp)
98 return m_symfile_type_sp->GetType();
102 void Variable::Dump(Stream *s, bool show_context) const {
103 s->Printf("%p: ", static_cast<const void *>(this));
105 *s << "Variable" << (const UserID &)*this;
108 *s << ", name = \"" << m_name << "\"";
110 if (m_symfile_type_sp) {
111 Type *type = m_symfile_type_sp->GetType();
113 *s << ", type = {" << type->GetID() << "} " << (void *)type << " (";
114 type->DumpTypeName(s);
119 if (m_scope != eValueTypeInvalid) {
120 s->PutCString(", scope = ");
122 case eValueTypeVariableGlobal:
123 s->PutCString(m_external ? "global" : "static");
125 case eValueTypeVariableArgument:
126 s->PutCString("parameter");
128 case eValueTypeVariableLocal:
129 s->PutCString("local");
131 case eValueTypeVariableThreadLocal:
132 s->PutCString("thread local");
135 *s << "??? (" << m_scope << ')';
139 if (show_context && m_owner_scope != nullptr) {
140 s->PutCString(", context = ( ");
141 m_owner_scope->DumpSymbolContext(s);
145 bool show_fullpaths = false;
146 m_declaration.Dump(s, show_fullpaths);
148 if (m_location.IsValid()) {
149 s->PutCString(", location = ");
150 lldb::addr_t loclist_base_addr = LLDB_INVALID_ADDRESS;
151 if (m_location.IsLocationList()) {
152 SymbolContext variable_sc;
153 m_owner_scope->CalculateSymbolContext(&variable_sc);
154 if (variable_sc.function)
155 loclist_base_addr = variable_sc.function->GetAddressRange()
161 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
163 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture()).get();
165 m_location.GetDescription(s, lldb::eDescriptionLevelBrief,
166 loclist_base_addr, abi);
170 s->PutCString(", external");
173 s->PutCString(", artificial");
178 bool Variable::DumpDeclaration(Stream *s, bool show_fullpaths,
180 bool dumped_declaration_info = false;
183 m_owner_scope->CalculateSymbolContext(&sc);
185 sc.line_entry.Clear();
186 bool show_inlined_frames = false;
187 const bool show_function_arguments = true;
188 const bool show_function_name = true;
190 dumped_declaration_info = sc.DumpStopContext(
191 s, nullptr, Address(), show_fullpaths, show_module, show_inlined_frames,
192 show_function_arguments, show_function_name);
197 if (m_declaration.DumpStopContext(s, false))
198 dumped_declaration_info = true;
199 return dumped_declaration_info;
202 size_t Variable::MemorySize() const { return sizeof(Variable); }
204 CompilerDeclContext Variable::GetDeclContext() {
205 Type *type = GetType();
207 return type->GetSymbolFile()->GetDeclContextContainingUID(GetID());
208 return CompilerDeclContext();
211 CompilerDecl Variable::GetDecl() {
212 Type *type = GetType();
213 return type ? type->GetSymbolFile()->GetDeclForUID(GetID()) : CompilerDecl();
216 void Variable::CalculateSymbolContext(SymbolContext *sc) {
218 m_owner_scope->CalculateSymbolContext(sc);
224 bool Variable::LocationIsValidForFrame(StackFrame *frame) {
225 // Is the variable is described by a single location?
226 if (!m_location.IsLocationList()) {
227 // Yes it is, the location is valid.
233 frame->GetSymbolContext(eSymbolContextFunction).function;
235 TargetSP target_sp(frame->CalculateTarget());
237 addr_t loclist_base_load_addr =
238 function->GetAddressRange().GetBaseAddress().GetLoadAddress(
240 if (loclist_base_load_addr == LLDB_INVALID_ADDRESS)
242 // It is a location list. We just need to tell if the location list
243 // contains the current address when converted to a load address
244 return m_location.LocationListContainsAddress(
245 loclist_base_load_addr,
246 frame->GetFrameCodeAddress().GetLoadAddress(target_sp.get()));
252 bool Variable::LocationIsValidForAddress(const Address &address) {
253 // Be sure to resolve the address to section offset prior to calling this
255 if (address.IsSectionOffset()) {
257 CalculateSymbolContext(&sc);
258 if (sc.module_sp == address.GetModule()) {
259 // Is the variable is described by a single location?
260 if (!m_location.IsLocationList()) {
261 // Yes it is, the location is valid.
266 addr_t loclist_base_file_addr =
267 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
268 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
270 // It is a location list. We just need to tell if the location list
271 // contains the current address when converted to a load address
272 return m_location.LocationListContainsAddress(loclist_base_file_addr,
273 address.GetFileAddress());
280 bool Variable::IsInScope(StackFrame *frame) {
282 case eValueTypeRegister:
283 case eValueTypeRegisterSet:
284 return frame != nullptr;
286 case eValueTypeConstResult:
287 case eValueTypeVariableGlobal:
288 case eValueTypeVariableStatic:
289 case eValueTypeVariableThreadLocal:
292 case eValueTypeVariableArgument:
293 case eValueTypeVariableLocal:
295 // We don't have a location list, we just need to see if the block that
296 // this variable was defined in is currently
297 Block *deepest_frame_block =
298 frame->GetSymbolContext(eSymbolContextBlock).block;
299 if (deepest_frame_block) {
300 SymbolContext variable_sc;
301 CalculateSymbolContext(&variable_sc);
303 // Check for static or global variable defined at the compile unit
304 // level that wasn't defined in a block
305 if (variable_sc.block == nullptr)
308 // Check if the variable is valid in the current block
309 if (variable_sc.block != deepest_frame_block &&
310 !variable_sc.block->Contains(deepest_frame_block))
313 // If no scope range is specified then it means that the scope is the
314 // same as the scope of the enclosing lexical block.
315 if (m_scope_range.IsEmpty())
318 addr_t file_address = frame->GetFrameCodeAddress().GetFileAddress();
319 return m_scope_range.FindEntryThatContains(file_address) != nullptr;
330 Status Variable::GetValuesForVariableExpressionPath(
331 llvm::StringRef variable_expr_path, ExecutionContextScope *scope,
332 GetVariableCallback callback, void *baton, VariableList &variable_list,
333 ValueObjectList &valobj_list) {
335 if (!callback || variable_expr_path.empty()) {
336 error.SetErrorString("unknown error");
340 switch (variable_expr_path.front()) {
342 error = Variable::GetValuesForVariableExpressionPath(
343 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
346 error.SetErrorString("unknown error");
349 for (uint32_t i = 0; i < valobj_list.GetSize();) {
351 ValueObjectSP valobj_sp(
352 valobj_list.GetValueObjectAtIndex(i)->Dereference(tmp_error));
353 if (tmp_error.Fail()) {
354 variable_list.RemoveVariableAtIndex(i);
355 valobj_list.RemoveValueObjectAtIndex(i);
357 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
363 error = Variable::GetValuesForVariableExpressionPath(
364 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
366 if (error.Success()) {
367 for (uint32_t i = 0; i < valobj_list.GetSize();) {
369 ValueObjectSP valobj_sp(
370 valobj_list.GetValueObjectAtIndex(i)->AddressOf(tmp_error));
371 if (tmp_error.Fail()) {
372 variable_list.RemoveVariableAtIndex(i);
373 valobj_list.RemoveValueObjectAtIndex(i);
375 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
380 error.SetErrorString("unknown error");
386 static RegularExpression g_regex(
387 llvm::StringRef("^([A-Za-z_:][A-Za-z_0-9:]*)(.*)"));
388 RegularExpression::Match regex_match(1);
389 std::string variable_name;
390 variable_list.Clear();
391 if (!g_regex.Execute(variable_expr_path, ®ex_match)) {
392 error.SetErrorStringWithFormat(
393 "unable to extract a variable name from '%s'",
394 variable_expr_path.str().c_str());
397 if (!regex_match.GetMatchAtIndex(variable_expr_path, 1, variable_name)) {
398 error.SetErrorStringWithFormat(
399 "unable to extract a variable name from '%s'",
400 variable_expr_path.str().c_str());
403 if (!callback(baton, variable_name.c_str(), variable_list)) {
404 error.SetErrorString("unknown error");
408 while (i < variable_list.GetSize()) {
409 VariableSP var_sp(variable_list.GetVariableAtIndex(i));
410 ValueObjectSP valobj_sp;
412 variable_list.RemoveVariableAtIndex(i);
415 ValueObjectSP variable_valobj_sp(
416 ValueObjectVariable::Create(scope, var_sp));
417 if (!variable_valobj_sp) {
418 variable_list.RemoveVariableAtIndex(i);
422 llvm::StringRef variable_sub_expr_path =
423 variable_expr_path.drop_front(variable_name.size());
424 if (!variable_sub_expr_path.empty()) {
425 valobj_sp = variable_valobj_sp->GetValueForExpressionPath(
426 variable_sub_expr_path);
428 error.SetErrorStringWithFormat(
429 "invalid expression path '%s' for variable '%s'",
430 variable_sub_expr_path.str().c_str(),
431 var_sp->GetName().GetCString());
432 variable_list.RemoveVariableAtIndex(i);
436 // Just the name of a variable with no extras
437 valobj_sp = variable_valobj_sp;
440 valobj_list.Append(valobj_sp);
444 if (variable_list.GetSize() > 0) {
450 error.SetErrorString("unknown error");
454 bool Variable::DumpLocationForAddress(Stream *s, const Address &address) {
455 // Be sure to resolve the address to section offset prior to calling this
457 if (address.IsSectionOffset()) {
459 CalculateSymbolContext(&sc);
460 if (sc.module_sp == address.GetModule()) {
463 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
465 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture()).get();
468 const addr_t file_addr = address.GetFileAddress();
470 if (sc.function->GetAddressRange().ContainsFileAddress(address)) {
471 addr_t loclist_base_file_addr =
472 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
473 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
475 return m_location.DumpLocationForAddress(s, eDescriptionLevelBrief,
476 loclist_base_file_addr,
480 return m_location.DumpLocationForAddress(
481 s, eDescriptionLevelBrief, LLDB_INVALID_ADDRESS, file_addr, abi);
487 static void PrivateAutoComplete(
488 StackFrame *frame, llvm::StringRef partial_path,
490 &prefix_path, // Anything that has been resolved already will be in here
491 const CompilerType &compiler_type,
492 StringList &matches, bool &word_complete);
494 static void PrivateAutoCompleteMembers(
495 StackFrame *frame, const std::string &partial_member_name,
496 llvm::StringRef partial_path,
498 &prefix_path, // Anything that has been resolved already will be in here
499 const CompilerType &compiler_type,
500 StringList &matches, bool &word_complete);
502 static void PrivateAutoCompleteMembers(
503 StackFrame *frame, const std::string &partial_member_name,
504 llvm::StringRef partial_path,
506 &prefix_path, // Anything that has been resolved already will be in here
507 const CompilerType &compiler_type,
508 StringList &matches, bool &word_complete) {
510 // We are in a type parsing child members
511 const uint32_t num_bases = compiler_type.GetNumDirectBaseClasses();
514 for (uint32_t i = 0; i < num_bases; ++i) {
515 CompilerType base_class_type =
516 compiler_type.GetDirectBaseClassAtIndex(i, nullptr);
518 PrivateAutoCompleteMembers(
519 frame, partial_member_name, partial_path, prefix_path,
520 base_class_type.GetCanonicalType(), matches, word_complete);
524 const uint32_t num_vbases = compiler_type.GetNumVirtualBaseClasses();
526 if (num_vbases > 0) {
527 for (uint32_t i = 0; i < num_vbases; ++i) {
528 CompilerType vbase_class_type =
529 compiler_type.GetVirtualBaseClassAtIndex(i, nullptr);
531 PrivateAutoCompleteMembers(
532 frame, partial_member_name, partial_path, prefix_path,
533 vbase_class_type.GetCanonicalType(), matches, word_complete);
537 // We are in a type parsing child members
538 const uint32_t num_fields = compiler_type.GetNumFields();
540 if (num_fields > 0) {
541 for (uint32_t i = 0; i < num_fields; ++i) {
542 std::string member_name;
544 CompilerType member_compiler_type = compiler_type.GetFieldAtIndex(
545 i, member_name, nullptr, nullptr, nullptr);
547 if (partial_member_name.empty() ||
548 member_name.find(partial_member_name) == 0) {
549 if (member_name == partial_member_name) {
552 prefix_path + member_name, // Anything that has been resolved
553 // already will be in here
554 member_compiler_type.GetCanonicalType(), matches, word_complete);
556 matches.AppendString((prefix_path + member_name).str());
563 static void PrivateAutoComplete(
564 StackFrame *frame, llvm::StringRef partial_path,
566 &prefix_path, // Anything that has been resolved already will be in here
567 const CompilerType &compiler_type,
568 StringList &matches, bool &word_complete) {
569 // printf ("\nPrivateAutoComplete()\n\tprefix_path = '%s'\n\tpartial_path =
570 // '%s'\n", prefix_path.c_str(), partial_path.c_str());
571 std::string remaining_partial_path;
573 const lldb::TypeClass type_class = compiler_type.GetTypeClass();
574 if (partial_path.empty()) {
575 if (compiler_type.IsValid()) {
576 switch (type_class) {
578 case eTypeClassArray:
579 case eTypeClassBlockPointer:
580 case eTypeClassBuiltin:
581 case eTypeClassComplexFloat:
582 case eTypeClassComplexInteger:
583 case eTypeClassEnumeration:
584 case eTypeClassFunction:
585 case eTypeClassMemberPointer:
586 case eTypeClassReference:
587 case eTypeClassTypedef:
588 case eTypeClassVector: {
589 matches.AppendString(prefix_path.str());
590 word_complete = matches.GetSize() == 1;
593 case eTypeClassClass:
594 case eTypeClassStruct:
595 case eTypeClassUnion:
596 if (prefix_path.str().back() != '.')
597 matches.AppendString((prefix_path + ".").str());
600 case eTypeClassObjCObject:
601 case eTypeClassObjCInterface:
603 case eTypeClassObjCObjectPointer:
604 case eTypeClassPointer: {
605 bool omit_empty_base_classes = true;
606 if (compiler_type.GetNumChildren(omit_empty_base_classes) > 0)
607 matches.AppendString((prefix_path + "->").str());
609 matches.AppendString(prefix_path.str());
610 word_complete = true;
616 const bool get_file_globals = true;
618 VariableList *variable_list = frame->GetVariableList(get_file_globals);
621 const size_t num_variables = variable_list->GetSize();
622 for (size_t i = 0; i < num_variables; ++i) {
623 Variable *variable = variable_list->GetVariableAtIndex(i).get();
624 matches.AppendString(variable->GetName().AsCString());
630 const char ch = partial_path[0];
633 if (prefix_path.str().empty()) {
634 PrivateAutoComplete(frame, partial_path.substr(1), "*", compiler_type,
635 matches, word_complete);
640 if (prefix_path.isTriviallyEmpty()) {
641 PrivateAutoComplete(frame, partial_path.substr(1), std::string("&"),
642 compiler_type, matches, word_complete);
647 if (partial_path.size() > 1 && partial_path[1] == '>' &&
648 !prefix_path.str().empty()) {
649 switch (type_class) {
650 case lldb::eTypeClassPointer: {
651 CompilerType pointee_type(compiler_type.GetPointeeType());
652 if (partial_path.size() > 2 && partial_path[2]) {
653 // If there is more after the "->", then search deeper
655 frame, partial_path.substr(2), prefix_path + "->",
656 pointee_type.GetCanonicalType(), matches, word_complete);
658 // Nothing after the "->", so list all members
659 PrivateAutoCompleteMembers(
660 frame, std::string(), std::string(), prefix_path + "->",
661 pointee_type.GetCanonicalType(), matches, word_complete);
671 if (compiler_type.IsValid()) {
672 switch (type_class) {
673 case lldb::eTypeClassUnion:
674 case lldb::eTypeClassStruct:
675 case lldb::eTypeClassClass:
676 if (partial_path.size() > 1 && partial_path[1]) {
677 // If there is more after the ".", then search deeper
678 PrivateAutoComplete(frame, partial_path.substr(1),
679 prefix_path + ".", compiler_type, matches,
683 // Nothing after the ".", so list all members
684 PrivateAutoCompleteMembers(frame, std::string(), partial_path,
685 prefix_path + ".", compiler_type,
686 matches, word_complete);
695 if (isalpha(ch) || ch == '_' || ch == '$') {
696 const size_t partial_path_len = partial_path.size();
698 while (pos < partial_path_len) {
699 const char curr_ch = partial_path[pos];
700 if (isalnum(curr_ch) || curr_ch == '_' || curr_ch == '$') {
707 std::string token(partial_path, 0, pos);
708 remaining_partial_path = partial_path.substr(pos);
710 if (compiler_type.IsValid()) {
711 PrivateAutoCompleteMembers(frame, token, remaining_partial_path,
712 prefix_path, compiler_type, matches,
715 // We haven't found our variable yet
716 const bool get_file_globals = true;
718 VariableList *variable_list =
719 frame->GetVariableList(get_file_globals);
724 const size_t num_variables = variable_list->GetSize();
725 for (size_t i = 0; i < num_variables; ++i) {
726 Variable *variable = variable_list->GetVariableAtIndex(i).get();
731 const char *variable_name = variable->GetName().AsCString();
732 if (strstr(variable_name, token.c_str()) == variable_name) {
733 if (strcmp(variable_name, token.c_str()) == 0) {
734 Type *variable_type = variable->GetType();
736 CompilerType variable_compiler_type(
737 variable_type->GetForwardCompilerType());
739 frame, remaining_partial_path,
740 prefix_path + token, // Anything that has been resolved
741 // already will be in here
742 variable_compiler_type.GetCanonicalType(), matches,
745 matches.AppendString((prefix_path + variable_name).str());
747 } else if (remaining_partial_path.empty()) {
748 matches.AppendString((prefix_path + variable_name).str());
759 size_t Variable::AutoComplete(const ExecutionContext &exe_ctx,
760 CompletionRequest &request) {
761 CompilerType compiler_type;
763 bool word_complete = false;
765 PrivateAutoComplete(exe_ctx.GetFramePtr(), request.GetCursorArgumentPrefix(),
766 "", compiler_type, matches, word_complete);
767 request.SetWordComplete(word_complete);
768 request.AddCompletions(matches);
770 return request.GetNumberOfMatches();