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_loc_is_const_data(false),
54 m_static_member(static_member) {}
56 //----------------------------------------------------------------------
58 //----------------------------------------------------------------------
59 Variable::~Variable() {}
61 lldb::LanguageType Variable::GetLanguage() const {
62 SymbolContext variable_sc;
63 m_owner_scope->CalculateSymbolContext(&variable_sc);
64 if (variable_sc.comp_unit)
65 return variable_sc.comp_unit->GetLanguage();
66 return lldb::eLanguageTypeUnknown;
69 ConstString Variable::GetName() const {
70 ConstString name = m_mangled.GetName(GetLanguage());
76 ConstString Variable::GetUnqualifiedName() const { return m_name; }
78 bool Variable::NameMatches(const ConstString &name) const {
81 SymbolContext variable_sc;
82 m_owner_scope->CalculateSymbolContext(&variable_sc);
84 LanguageType language = eLanguageTypeUnknown;
85 if (variable_sc.comp_unit)
86 language = variable_sc.comp_unit->GetLanguage();
87 return m_mangled.NameMatches(name, language);
89 bool Variable::NameMatches(const RegularExpression ®ex) const {
90 if (regex.Execute(m_name.AsCString()))
93 return m_mangled.NameMatches(regex, GetLanguage());
97 Type *Variable::GetType() {
98 if (m_symfile_type_sp)
99 return m_symfile_type_sp->GetType();
103 void Variable::Dump(Stream *s, bool show_context) const {
104 s->Printf("%p: ", static_cast<const void *>(this));
106 *s << "Variable" << (const UserID &)*this;
109 *s << ", name = \"" << m_name << "\"";
111 if (m_symfile_type_sp) {
112 Type *type = m_symfile_type_sp->GetType();
114 *s << ", type = {" << type->GetID() << "} " << (void *)type << " (";
115 type->DumpTypeName(s);
120 if (m_scope != eValueTypeInvalid) {
121 s->PutCString(", scope = ");
123 case eValueTypeVariableGlobal:
124 s->PutCString(m_external ? "global" : "static");
126 case eValueTypeVariableArgument:
127 s->PutCString("parameter");
129 case eValueTypeVariableLocal:
130 s->PutCString("local");
132 case eValueTypeVariableThreadLocal:
133 s->PutCString("thread local");
136 *s << "??? (" << m_scope << ')';
140 if (show_context && m_owner_scope != nullptr) {
141 s->PutCString(", context = ( ");
142 m_owner_scope->DumpSymbolContext(s);
146 bool show_fullpaths = false;
147 m_declaration.Dump(s, show_fullpaths);
149 if (m_location.IsValid()) {
150 s->PutCString(", location = ");
151 lldb::addr_t loclist_base_addr = LLDB_INVALID_ADDRESS;
152 if (m_location.IsLocationList()) {
153 SymbolContext variable_sc;
154 m_owner_scope->CalculateSymbolContext(&variable_sc);
155 if (variable_sc.function)
156 loclist_base_addr = variable_sc.function->GetAddressRange()
162 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
164 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
166 m_location.GetDescription(s, lldb::eDescriptionLevelBrief,
167 loclist_base_addr, abi.get());
171 s->PutCString(", external");
174 s->PutCString(", artificial");
179 bool Variable::DumpDeclaration(Stream *s, bool show_fullpaths,
181 bool dumped_declaration_info = false;
184 m_owner_scope->CalculateSymbolContext(&sc);
186 sc.line_entry.Clear();
187 bool show_inlined_frames = false;
188 const bool show_function_arguments = true;
189 const bool show_function_name = true;
191 dumped_declaration_info = sc.DumpStopContext(
192 s, nullptr, Address(), show_fullpaths, show_module, show_inlined_frames,
193 show_function_arguments, show_function_name);
198 if (m_declaration.DumpStopContext(s, false))
199 dumped_declaration_info = true;
200 return dumped_declaration_info;
203 size_t Variable::MemorySize() const { return sizeof(Variable); }
205 CompilerDeclContext Variable::GetDeclContext() {
206 Type *type = GetType();
208 return type->GetSymbolFile()->GetDeclContextContainingUID(GetID());
209 return CompilerDeclContext();
212 CompilerDecl Variable::GetDecl() {
213 Type *type = GetType();
214 return type ? type->GetSymbolFile()->GetDeclForUID(GetID()) : CompilerDecl();
217 void Variable::CalculateSymbolContext(SymbolContext *sc) {
219 m_owner_scope->CalculateSymbolContext(sc);
225 bool Variable::LocationIsValidForFrame(StackFrame *frame) {
226 // Is the variable is described by a single location?
227 if (!m_location.IsLocationList()) {
228 // Yes it is, the location is valid.
234 frame->GetSymbolContext(eSymbolContextFunction).function;
236 TargetSP target_sp(frame->CalculateTarget());
238 addr_t loclist_base_load_addr =
239 function->GetAddressRange().GetBaseAddress().GetLoadAddress(
241 if (loclist_base_load_addr == LLDB_INVALID_ADDRESS)
243 // It is a location list. We just need to tell if the location list
244 // contains the current address when converted to a load address
245 return m_location.LocationListContainsAddress(
246 loclist_base_load_addr,
247 frame->GetFrameCodeAddress().GetLoadAddress(target_sp.get()));
253 bool Variable::LocationIsValidForAddress(const Address &address) {
254 // Be sure to resolve the address to section offset prior to calling this
256 if (address.IsSectionOffset()) {
258 CalculateSymbolContext(&sc);
259 if (sc.module_sp == address.GetModule()) {
260 // Is the variable is described by a single location?
261 if (!m_location.IsLocationList()) {
262 // Yes it is, the location is valid.
267 addr_t loclist_base_file_addr =
268 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
269 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
271 // It is a location list. We just need to tell if the location list
272 // contains the current address when converted to a load address
273 return m_location.LocationListContainsAddress(loclist_base_file_addr,
274 address.GetFileAddress());
281 bool Variable::IsInScope(StackFrame *frame) {
283 case eValueTypeRegister:
284 case eValueTypeRegisterSet:
285 return frame != nullptr;
287 case eValueTypeConstResult:
288 case eValueTypeVariableGlobal:
289 case eValueTypeVariableStatic:
290 case eValueTypeVariableThreadLocal:
293 case eValueTypeVariableArgument:
294 case eValueTypeVariableLocal:
296 // We don't have a location list, we just need to see if the block that
297 // this variable was defined in is currently
298 Block *deepest_frame_block =
299 frame->GetSymbolContext(eSymbolContextBlock).block;
300 if (deepest_frame_block) {
301 SymbolContext variable_sc;
302 CalculateSymbolContext(&variable_sc);
304 // Check for static or global variable defined at the compile unit
305 // level that wasn't defined in a block
306 if (variable_sc.block == nullptr)
309 // Check if the variable is valid in the current block
310 if (variable_sc.block != deepest_frame_block &&
311 !variable_sc.block->Contains(deepest_frame_block))
314 // If no scope range is specified then it means that the scope is the
315 // same as the scope of the enclosing lexical block.
316 if (m_scope_range.IsEmpty())
319 addr_t file_address = frame->GetFrameCodeAddress().GetFileAddress();
320 return m_scope_range.FindEntryThatContains(file_address) != nullptr;
331 Status Variable::GetValuesForVariableExpressionPath(
332 llvm::StringRef variable_expr_path, ExecutionContextScope *scope,
333 GetVariableCallback callback, void *baton, VariableList &variable_list,
334 ValueObjectList &valobj_list) {
336 if (!callback || variable_expr_path.empty()) {
337 error.SetErrorString("unknown error");
341 switch (variable_expr_path.front()) {
343 error = Variable::GetValuesForVariableExpressionPath(
344 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
347 error.SetErrorString("unknown error");
350 for (uint32_t i = 0; i < valobj_list.GetSize();) {
352 ValueObjectSP valobj_sp(
353 valobj_list.GetValueObjectAtIndex(i)->Dereference(tmp_error));
354 if (tmp_error.Fail()) {
355 variable_list.RemoveVariableAtIndex(i);
356 valobj_list.RemoveValueObjectAtIndex(i);
358 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
364 error = Variable::GetValuesForVariableExpressionPath(
365 variable_expr_path.drop_front(), scope, callback, baton, variable_list,
367 if (error.Success()) {
368 for (uint32_t i = 0; i < valobj_list.GetSize();) {
370 ValueObjectSP valobj_sp(
371 valobj_list.GetValueObjectAtIndex(i)->AddressOf(tmp_error));
372 if (tmp_error.Fail()) {
373 variable_list.RemoveVariableAtIndex(i);
374 valobj_list.RemoveValueObjectAtIndex(i);
376 valobj_list.SetValueObjectAtIndex(i, valobj_sp);
381 error.SetErrorString("unknown error");
387 static RegularExpression g_regex(
388 llvm::StringRef("^([A-Za-z_:][A-Za-z_0-9:]*)(.*)"));
389 RegularExpression::Match regex_match(1);
390 std::string variable_name;
391 variable_list.Clear();
392 if (!g_regex.Execute(variable_expr_path, ®ex_match)) {
393 error.SetErrorStringWithFormat(
394 "unable to extract a variable name from '%s'",
395 variable_expr_path.str().c_str());
398 if (!regex_match.GetMatchAtIndex(variable_expr_path, 1, variable_name)) {
399 error.SetErrorStringWithFormat(
400 "unable to extract a variable name from '%s'",
401 variable_expr_path.str().c_str());
404 if (!callback(baton, variable_name.c_str(), variable_list)) {
405 error.SetErrorString("unknown error");
409 while (i < variable_list.GetSize()) {
410 VariableSP var_sp(variable_list.GetVariableAtIndex(i));
411 ValueObjectSP valobj_sp;
413 variable_list.RemoveVariableAtIndex(i);
416 ValueObjectSP variable_valobj_sp(
417 ValueObjectVariable::Create(scope, var_sp));
418 if (!variable_valobj_sp) {
419 variable_list.RemoveVariableAtIndex(i);
423 llvm::StringRef variable_sub_expr_path =
424 variable_expr_path.drop_front(variable_name.size());
425 if (!variable_sub_expr_path.empty()) {
426 valobj_sp = variable_valobj_sp->GetValueForExpressionPath(
427 variable_sub_expr_path);
429 error.SetErrorStringWithFormat(
430 "invalid expression path '%s' for variable '%s'",
431 variable_sub_expr_path.str().c_str(),
432 var_sp->GetName().GetCString());
433 variable_list.RemoveVariableAtIndex(i);
437 // Just the name of a variable with no extras
438 valobj_sp = variable_valobj_sp;
441 valobj_list.Append(valobj_sp);
445 if (variable_list.GetSize() > 0) {
451 error.SetErrorString("unknown error");
455 bool Variable::DumpLocationForAddress(Stream *s, const Address &address) {
456 // Be sure to resolve the address to section offset prior to calling this
458 if (address.IsSectionOffset()) {
460 CalculateSymbolContext(&sc);
461 if (sc.module_sp == address.GetModule()) {
464 ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
466 abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
469 const addr_t file_addr = address.GetFileAddress();
471 if (sc.function->GetAddressRange().ContainsFileAddress(address)) {
472 addr_t loclist_base_file_addr =
473 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
474 if (loclist_base_file_addr == LLDB_INVALID_ADDRESS)
476 return m_location.DumpLocationForAddress(s, eDescriptionLevelBrief,
477 loclist_base_file_addr,
478 file_addr, abi.get());
481 return m_location.DumpLocationForAddress(s, eDescriptionLevelBrief,
482 LLDB_INVALID_ADDRESS, file_addr,
489 static void PrivateAutoComplete(
490 StackFrame *frame, llvm::StringRef partial_path,
492 &prefix_path, // Anything that has been resolved already will be in here
493 const CompilerType &compiler_type,
494 StringList &matches, bool &word_complete);
496 static void PrivateAutoCompleteMembers(
497 StackFrame *frame, const std::string &partial_member_name,
498 llvm::StringRef partial_path,
500 &prefix_path, // Anything that has been resolved already will be in here
501 const CompilerType &compiler_type,
502 StringList &matches, bool &word_complete);
504 static void PrivateAutoCompleteMembers(
505 StackFrame *frame, const std::string &partial_member_name,
506 llvm::StringRef partial_path,
508 &prefix_path, // Anything that has been resolved already will be in here
509 const CompilerType &compiler_type,
510 StringList &matches, bool &word_complete) {
512 // We are in a type parsing child members
513 const uint32_t num_bases = compiler_type.GetNumDirectBaseClasses();
516 for (uint32_t i = 0; i < num_bases; ++i) {
517 CompilerType base_class_type =
518 compiler_type.GetDirectBaseClassAtIndex(i, nullptr);
520 PrivateAutoCompleteMembers(
521 frame, partial_member_name, partial_path, prefix_path,
522 base_class_type.GetCanonicalType(), matches, word_complete);
526 const uint32_t num_vbases = compiler_type.GetNumVirtualBaseClasses();
528 if (num_vbases > 0) {
529 for (uint32_t i = 0; i < num_vbases; ++i) {
530 CompilerType vbase_class_type =
531 compiler_type.GetVirtualBaseClassAtIndex(i, nullptr);
533 PrivateAutoCompleteMembers(
534 frame, partial_member_name, partial_path, prefix_path,
535 vbase_class_type.GetCanonicalType(), matches, word_complete);
539 // We are in a type parsing child members
540 const uint32_t num_fields = compiler_type.GetNumFields();
542 if (num_fields > 0) {
543 for (uint32_t i = 0; i < num_fields; ++i) {
544 std::string member_name;
546 CompilerType member_compiler_type = compiler_type.GetFieldAtIndex(
547 i, member_name, nullptr, nullptr, nullptr);
549 if (partial_member_name.empty() ||
550 member_name.find(partial_member_name) == 0) {
551 if (member_name == partial_member_name) {
554 prefix_path + member_name, // Anything that has been resolved
555 // already will be in here
556 member_compiler_type.GetCanonicalType(), matches, word_complete);
558 matches.AppendString((prefix_path + member_name).str());
565 static void PrivateAutoComplete(
566 StackFrame *frame, llvm::StringRef partial_path,
568 &prefix_path, // Anything that has been resolved already will be in here
569 const CompilerType &compiler_type,
570 StringList &matches, bool &word_complete) {
571 // printf ("\nPrivateAutoComplete()\n\tprefix_path = '%s'\n\tpartial_path =
572 // '%s'\n", prefix_path.c_str(), partial_path.c_str());
573 std::string remaining_partial_path;
575 const lldb::TypeClass type_class = compiler_type.GetTypeClass();
576 if (partial_path.empty()) {
577 if (compiler_type.IsValid()) {
578 switch (type_class) {
580 case eTypeClassArray:
581 case eTypeClassBlockPointer:
582 case eTypeClassBuiltin:
583 case eTypeClassComplexFloat:
584 case eTypeClassComplexInteger:
585 case eTypeClassEnumeration:
586 case eTypeClassFunction:
587 case eTypeClassMemberPointer:
588 case eTypeClassReference:
589 case eTypeClassTypedef:
590 case eTypeClassVector: {
591 matches.AppendString(prefix_path.str());
592 word_complete = matches.GetSize() == 1;
595 case eTypeClassClass:
596 case eTypeClassStruct:
597 case eTypeClassUnion:
598 if (prefix_path.str().back() != '.')
599 matches.AppendString((prefix_path + ".").str());
602 case eTypeClassObjCObject:
603 case eTypeClassObjCInterface:
605 case eTypeClassObjCObjectPointer:
606 case eTypeClassPointer: {
607 bool omit_empty_base_classes = true;
608 if (compiler_type.GetNumChildren(omit_empty_base_classes, nullptr) > 0)
609 matches.AppendString((prefix_path + "->").str());
611 matches.AppendString(prefix_path.str());
612 word_complete = true;
618 const bool get_file_globals = true;
620 VariableList *variable_list = frame->GetVariableList(get_file_globals);
623 const size_t num_variables = variable_list->GetSize();
624 for (size_t i = 0; i < num_variables; ++i) {
625 Variable *variable = variable_list->GetVariableAtIndex(i).get();
626 matches.AppendString(variable->GetName().AsCString());
632 const char ch = partial_path[0];
635 if (prefix_path.str().empty()) {
636 PrivateAutoComplete(frame, partial_path.substr(1), "*", compiler_type,
637 matches, word_complete);
642 if (prefix_path.isTriviallyEmpty()) {
643 PrivateAutoComplete(frame, partial_path.substr(1), std::string("&"),
644 compiler_type, matches, word_complete);
649 if (partial_path.size() > 1 && partial_path[1] == '>' &&
650 !prefix_path.str().empty()) {
651 switch (type_class) {
652 case lldb::eTypeClassPointer: {
653 CompilerType pointee_type(compiler_type.GetPointeeType());
654 if (partial_path.size() > 2 && partial_path[2]) {
655 // If there is more after the "->", then search deeper
657 frame, partial_path.substr(2), prefix_path + "->",
658 pointee_type.GetCanonicalType(), matches, word_complete);
660 // Nothing after the "->", so list all members
661 PrivateAutoCompleteMembers(
662 frame, std::string(), std::string(), prefix_path + "->",
663 pointee_type.GetCanonicalType(), matches, word_complete);
673 if (compiler_type.IsValid()) {
674 switch (type_class) {
675 case lldb::eTypeClassUnion:
676 case lldb::eTypeClassStruct:
677 case lldb::eTypeClassClass:
678 if (partial_path.size() > 1 && partial_path[1]) {
679 // If there is more after the ".", then search deeper
680 PrivateAutoComplete(frame, partial_path.substr(1),
681 prefix_path + ".", compiler_type, matches,
685 // Nothing after the ".", so list all members
686 PrivateAutoCompleteMembers(frame, std::string(), partial_path,
687 prefix_path + ".", compiler_type,
688 matches, word_complete);
697 if (isalpha(ch) || ch == '_' || ch == '$') {
698 const size_t partial_path_len = partial_path.size();
700 while (pos < partial_path_len) {
701 const char curr_ch = partial_path[pos];
702 if (isalnum(curr_ch) || curr_ch == '_' || curr_ch == '$') {
709 std::string token(partial_path, 0, pos);
710 remaining_partial_path = partial_path.substr(pos);
712 if (compiler_type.IsValid()) {
713 PrivateAutoCompleteMembers(frame, token, remaining_partial_path,
714 prefix_path, compiler_type, matches,
717 // We haven't found our variable yet
718 const bool get_file_globals = true;
720 VariableList *variable_list =
721 frame->GetVariableList(get_file_globals);
726 const size_t num_variables = variable_list->GetSize();
727 for (size_t i = 0; i < num_variables; ++i) {
728 Variable *variable = variable_list->GetVariableAtIndex(i).get();
733 const char *variable_name = variable->GetName().AsCString();
734 if (strstr(variable_name, token.c_str()) == variable_name) {
735 if (strcmp(variable_name, token.c_str()) == 0) {
736 Type *variable_type = variable->GetType();
738 CompilerType variable_compiler_type(
739 variable_type->GetForwardCompilerType());
741 frame, remaining_partial_path,
742 prefix_path + token, // Anything that has been resolved
743 // already will be in here
744 variable_compiler_type.GetCanonicalType(), matches,
747 matches.AppendString((prefix_path + variable_name).str());
749 } else if (remaining_partial_path.empty()) {
750 matches.AppendString((prefix_path + variable_name).str());
761 size_t Variable::AutoComplete(const ExecutionContext &exe_ctx,
762 CompletionRequest &request) {
763 CompilerType compiler_type;
765 bool word_complete = false;
767 PrivateAutoComplete(exe_ctx.GetFramePtr(), request.GetCursorArgumentPrefix(),
768 "", compiler_type, matches, word_complete);
769 request.SetWordComplete(word_complete);
770 request.AddCompletions(matches);
772 return request.GetNumberOfMatches();