1 //===-- Variable.cpp ------------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Symbol/Variable.h"
10 
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"
32 
33 #include "llvm/ADT/Twine.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 
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 DWARFExpressionList &location_list, bool external,
43                    bool artificial, bool location_is_constant_data,
44                    bool static_member)
45     : UserID(uid), m_name(name), m_mangled(ConstString(mangled)),
46       m_symfile_type_sp(symfile_type_sp), m_scope(scope),
47       m_owner_scope(context), m_scope_range(scope_range),
48       m_declaration(decl_ptr), m_location_list(location_list), m_external(external),
49       m_artificial(artificial), m_loc_is_const_data(location_is_constant_data),
50       m_static_member(static_member) {}
51 
52 Variable::~Variable() = default;
53 
54 lldb::LanguageType Variable::GetLanguage() const {
55   lldb::LanguageType lang = m_mangled.GuessLanguage();
56   if (lang != lldb::eLanguageTypeUnknown)
57     return lang;
58 
59   if (auto *func = m_owner_scope->CalculateSymbolContextFunction()) {
60     if ((lang = func->GetLanguage()) != lldb::eLanguageTypeUnknown)
61       return lang;
62   } else if (auto *comp_unit =
63                  m_owner_scope->CalculateSymbolContextCompileUnit()) {
64     if ((lang = comp_unit->GetLanguage()) != lldb::eLanguageTypeUnknown)
65       return lang;
66   }
67 
68   return lldb::eLanguageTypeUnknown;
69 }
70 
71 ConstString Variable::GetName() const {
72   ConstString name = m_mangled.GetName();
73   if (name)
74     return name;
75   return m_name;
76 }
77 
78 ConstString Variable::GetUnqualifiedName() const { return m_name; }
79 
80 bool Variable::NameMatches(ConstString name) const {
81   if (m_name == name)
82     return true;
83   SymbolContext variable_sc;
84   m_owner_scope->CalculateSymbolContext(&variable_sc);
85 
86   return m_mangled.NameMatches(name);
87 }
88 bool Variable::NameMatches(const RegularExpression &regex) const {
89   if (regex.Execute(m_name.AsCString()))
90     return true;
91   if (m_mangled)
92     return m_mangled.NameMatches(regex);
93   return false;
94 }
95 
96 Type *Variable::GetType() {
97   if (m_symfile_type_sp)
98     return m_symfile_type_sp->GetType();
99   return nullptr;
100 }
101 
102 void Variable::Dump(Stream *s, bool show_context) const {
103   s->Printf("%p: ", static_cast<const void *>(this));
104   s->Indent();
105   *s << "Variable" << (const UserID &)*this;
106 
107   if (m_name)
108     *s << ", name = \"" << m_name << "\"";
109 
110   if (m_symfile_type_sp) {
111     Type *type = m_symfile_type_sp->GetType();
112     if (type) {
113       s->Format(", type = {{{0:x-16}} {1} (", type->GetID(), type);
114       type->DumpTypeName(s);
115       s->PutChar(')');
116     }
117   }
118 
119   if (m_scope != eValueTypeInvalid) {
120     s->PutCString(", scope = ");
121     switch (m_scope) {
122     case eValueTypeVariableGlobal:
123       s->PutCString(m_external ? "global" : "static");
124       break;
125     case eValueTypeVariableArgument:
126       s->PutCString("parameter");
127       break;
128     case eValueTypeVariableLocal:
129       s->PutCString("local");
130       break;
131     case eValueTypeVariableThreadLocal:
132       s->PutCString("thread local");
133       break;
134     default:
135       s->AsRawOstream() << "??? (" << m_scope << ')';
136     }
137   }
138 
139   if (show_context && m_owner_scope != nullptr) {
140     s->PutCString(", context = ( ");
141     m_owner_scope->DumpSymbolContext(s);
142     s->PutCString(" )");
143   }
144 
145   bool show_fullpaths = false;
146   m_declaration.Dump(s, show_fullpaths);
147 
148   if (m_location_list.IsValid()) {
149     s->PutCString(", location = ");
150     ABISP abi;
151     if (m_owner_scope) {
152       ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
153       if (module_sp)
154         abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
155     }
156     m_location_list.GetDescription(s, lldb::eDescriptionLevelBrief, abi.get());
157   }
158 
159   if (m_external)
160     s->PutCString(", external");
161 
162   if (m_artificial)
163     s->PutCString(", artificial");
164 
165   s->EOL();
166 }
167 
168 bool Variable::DumpDeclaration(Stream *s, bool show_fullpaths,
169                                bool show_module) {
170   bool dumped_declaration_info = false;
171   if (m_owner_scope) {
172     SymbolContext sc;
173     m_owner_scope->CalculateSymbolContext(&sc);
174     sc.block = nullptr;
175     sc.line_entry.Clear();
176     bool show_inlined_frames = false;
177     const bool show_function_arguments = true;
178     const bool show_function_name = true;
179 
180     dumped_declaration_info = sc.DumpStopContext(
181         s, nullptr, Address(), show_fullpaths, show_module, show_inlined_frames,
182         show_function_arguments, show_function_name);
183 
184     if (sc.function)
185       s->PutChar(':');
186   }
187   if (m_declaration.DumpStopContext(s, false))
188     dumped_declaration_info = true;
189   return dumped_declaration_info;
190 }
191 
192 size_t Variable::MemorySize() const { return sizeof(Variable); }
193 
194 CompilerDeclContext Variable::GetDeclContext() {
195   Type *type = GetType();
196   if (type)
197     return type->GetSymbolFile()->GetDeclContextContainingUID(GetID());
198   return CompilerDeclContext();
199 }
200 
201 CompilerDecl Variable::GetDecl() {
202   Type *type = GetType();
203   return type ? type->GetSymbolFile()->GetDeclForUID(GetID()) : CompilerDecl();
204 }
205 
206 void Variable::CalculateSymbolContext(SymbolContext *sc) {
207   if (m_owner_scope) {
208     m_owner_scope->CalculateSymbolContext(sc);
209     sc->variable = this;
210   } else
211     sc->Clear(false);
212 }
213 
214 bool Variable::LocationIsValidForFrame(StackFrame *frame) {
215   return m_location_list.ContainsAddress(
216       frame->GetFrameCodeAddress().GetFileAddress());
217 }
218 
219 bool Variable::LocationIsValidForAddress(const Address &address) {
220   // Be sure to resolve the address to section offset prior to calling this
221   // function.
222   if (address.IsSectionOffset()) {
223     // We need to check if the address is valid for both scope range and value
224     // range.
225     // Empty scope range means block range.
226     bool valid_in_scope_range =
227         GetScopeRange().IsEmpty() || GetScopeRange().FindEntryThatContains(
228                                          address.GetFileAddress()) != nullptr;
229     if (!valid_in_scope_range)
230       return false;
231     SymbolContext sc;
232     CalculateSymbolContext(&sc);
233     if (sc.module_sp == address.GetModule()) {
234       // Empty location list means we have missing value range info, but it's in
235       // the scope.
236       return m_location_list.GetSize() == 0 ||
237              m_location_list.ContainsAddress(address.GetFileAddress());
238     }
239   }
240   return false;
241 }
242 
243 bool Variable::IsInScope(StackFrame *frame) {
244   switch (m_scope) {
245   case eValueTypeRegister:
246   case eValueTypeRegisterSet:
247     return frame != nullptr;
248 
249   case eValueTypeConstResult:
250   case eValueTypeVariableGlobal:
251   case eValueTypeVariableStatic:
252   case eValueTypeVariableThreadLocal:
253     return true;
254 
255   case eValueTypeVariableArgument:
256   case eValueTypeVariableLocal:
257     if (frame) {
258       // We don't have a location list, we just need to see if the block that
259       // this variable was defined in is currently
260       Block *deepest_frame_block =
261           frame->GetSymbolContext(eSymbolContextBlock).block;
262       if (deepest_frame_block) {
263         SymbolContext variable_sc;
264         CalculateSymbolContext(&variable_sc);
265 
266         // Check for static or global variable defined at the compile unit
267         // level that wasn't defined in a block
268         if (variable_sc.block == nullptr)
269           return true;
270 
271         // Check if the variable is valid in the current block
272         if (variable_sc.block != deepest_frame_block &&
273             !variable_sc.block->Contains(deepest_frame_block))
274           return false;
275 
276         // If no scope range is specified then it means that the scope is the
277         // same as the scope of the enclosing lexical block.
278         if (m_scope_range.IsEmpty())
279           return true;
280 
281         addr_t file_address = frame->GetFrameCodeAddress().GetFileAddress();
282         return m_scope_range.FindEntryThatContains(file_address) != nullptr;
283       }
284     }
285     break;
286 
287   default:
288     break;
289   }
290   return false;
291 }
292 
293 Status Variable::GetValuesForVariableExpressionPath(
294     llvm::StringRef variable_expr_path, ExecutionContextScope *scope,
295     GetVariableCallback callback, void *baton, VariableList &variable_list,
296     ValueObjectList &valobj_list) {
297   Status error;
298   if (!callback || variable_expr_path.empty()) {
299     error.SetErrorString("unknown error");
300     return error;
301   }
302 
303   switch (variable_expr_path.front()) {
304   case '*':
305     error = Variable::GetValuesForVariableExpressionPath(
306         variable_expr_path.drop_front(), scope, callback, baton, variable_list,
307         valobj_list);
308     if (error.Fail()) {
309       error.SetErrorString("unknown error");
310       return error;
311     }
312     for (uint32_t i = 0; i < valobj_list.GetSize();) {
313       Status tmp_error;
314       ValueObjectSP valobj_sp(
315           valobj_list.GetValueObjectAtIndex(i)->Dereference(tmp_error));
316       if (tmp_error.Fail()) {
317         variable_list.RemoveVariableAtIndex(i);
318         valobj_list.RemoveValueObjectAtIndex(i);
319       } else {
320         valobj_list.SetValueObjectAtIndex(i, valobj_sp);
321         ++i;
322       }
323     }
324     return error;
325   case '&': {
326     error = Variable::GetValuesForVariableExpressionPath(
327         variable_expr_path.drop_front(), scope, callback, baton, variable_list,
328         valobj_list);
329     if (error.Success()) {
330       for (uint32_t i = 0; i < valobj_list.GetSize();) {
331         Status tmp_error;
332         ValueObjectSP valobj_sp(
333             valobj_list.GetValueObjectAtIndex(i)->AddressOf(tmp_error));
334         if (tmp_error.Fail()) {
335           variable_list.RemoveVariableAtIndex(i);
336           valobj_list.RemoveValueObjectAtIndex(i);
337         } else {
338           valobj_list.SetValueObjectAtIndex(i, valobj_sp);
339           ++i;
340         }
341       }
342     } else {
343       error.SetErrorString("unknown error");
344     }
345     return error;
346   } break;
347 
348   default: {
349     static RegularExpression g_regex(
350         llvm::StringRef("^([A-Za-z_:][A-Za-z_0-9:]*)(.*)"));
351     llvm::SmallVector<llvm::StringRef, 2> matches;
352     variable_list.Clear();
353     if (!g_regex.Execute(variable_expr_path, &matches)) {
354       error.SetErrorStringWithFormat(
355           "unable to extract a variable name from '%s'",
356           variable_expr_path.str().c_str());
357       return error;
358     }
359     std::string variable_name = matches[1].str();
360     if (!callback(baton, variable_name.c_str(), variable_list)) {
361       error.SetErrorString("unknown error");
362       return error;
363     }
364     uint32_t i = 0;
365     while (i < variable_list.GetSize()) {
366       VariableSP var_sp(variable_list.GetVariableAtIndex(i));
367       ValueObjectSP valobj_sp;
368       if (!var_sp) {
369         variable_list.RemoveVariableAtIndex(i);
370         continue;
371       }
372       ValueObjectSP variable_valobj_sp(
373           ValueObjectVariable::Create(scope, var_sp));
374       if (!variable_valobj_sp) {
375         variable_list.RemoveVariableAtIndex(i);
376         continue;
377       }
378 
379       llvm::StringRef variable_sub_expr_path =
380           variable_expr_path.drop_front(variable_name.size());
381       if (!variable_sub_expr_path.empty()) {
382         valobj_sp = variable_valobj_sp->GetValueForExpressionPath(
383             variable_sub_expr_path);
384         if (!valobj_sp) {
385           error.SetErrorStringWithFormat(
386               "invalid expression path '%s' for variable '%s'",
387               variable_sub_expr_path.str().c_str(),
388               var_sp->GetName().GetCString());
389           variable_list.RemoveVariableAtIndex(i);
390           continue;
391         }
392       } else {
393         // Just the name of a variable with no extras
394         valobj_sp = variable_valobj_sp;
395       }
396 
397       valobj_list.Append(valobj_sp);
398       ++i;
399     }
400 
401     if (variable_list.GetSize() > 0) {
402       error.Clear();
403       return error;
404     }
405   } break;
406   }
407   error.SetErrorString("unknown error");
408   return error;
409 }
410 
411 bool Variable::DumpLocations(Stream *s, const Address &address) {
412   SymbolContext sc;
413   CalculateSymbolContext(&sc);
414   ABISP abi;
415   if (m_owner_scope) {
416     ModuleSP module_sp(m_owner_scope->CalculateSymbolContextModule());
417     if (module_sp)
418       abi = ABI::FindPlugin(ProcessSP(), module_sp->GetArchitecture());
419   }
420 
421   const addr_t file_addr = address.GetFileAddress();
422   return m_location_list.DumpLocations(s, eDescriptionLevelBrief, file_addr,
423                                        abi.get());
424 }
425 
426 static void PrivateAutoComplete(
427     StackFrame *frame, llvm::StringRef partial_path,
428     const llvm::Twine
429         &prefix_path, // Anything that has been resolved already will be in here
430     const CompilerType &compiler_type, CompletionRequest &request);
431 
432 static void PrivateAutoCompleteMembers(
433     StackFrame *frame, const std::string &partial_member_name,
434     llvm::StringRef partial_path,
435     const llvm::Twine
436         &prefix_path, // Anything that has been resolved already will be in here
437     const CompilerType &compiler_type, CompletionRequest &request) {
438 
439   // We are in a type parsing child members
440   const uint32_t num_bases = compiler_type.GetNumDirectBaseClasses();
441 
442   if (num_bases > 0) {
443     for (uint32_t i = 0; i < num_bases; ++i) {
444       CompilerType base_class_type =
445           compiler_type.GetDirectBaseClassAtIndex(i, nullptr);
446 
447       PrivateAutoCompleteMembers(frame, partial_member_name, partial_path,
448                                  prefix_path,
449                                  base_class_type.GetCanonicalType(), request);
450     }
451   }
452 
453   const uint32_t num_vbases = compiler_type.GetNumVirtualBaseClasses();
454 
455   if (num_vbases > 0) {
456     for (uint32_t i = 0; i < num_vbases; ++i) {
457       CompilerType vbase_class_type =
458           compiler_type.GetVirtualBaseClassAtIndex(i, nullptr);
459 
460       PrivateAutoCompleteMembers(frame, partial_member_name, partial_path,
461                                  prefix_path,
462                                  vbase_class_type.GetCanonicalType(), request);
463     }
464   }
465 
466   // We are in a type parsing child members
467   const uint32_t num_fields = compiler_type.GetNumFields();
468 
469   if (num_fields > 0) {
470     for (uint32_t i = 0; i < num_fields; ++i) {
471       std::string member_name;
472 
473       CompilerType member_compiler_type = compiler_type.GetFieldAtIndex(
474           i, member_name, nullptr, nullptr, nullptr);
475 
476       if (partial_member_name.empty() ||
477           llvm::StringRef(member_name).startswith(partial_member_name)) {
478         if (member_name == partial_member_name) {
479           PrivateAutoComplete(
480               frame, partial_path,
481               prefix_path + member_name, // Anything that has been resolved
482                                          // already will be in here
483               member_compiler_type.GetCanonicalType(), request);
484         } else {
485           request.AddCompletion((prefix_path + member_name).str());
486         }
487       }
488     }
489   }
490 }
491 
492 static void PrivateAutoComplete(
493     StackFrame *frame, llvm::StringRef partial_path,
494     const llvm::Twine
495         &prefix_path, // Anything that has been resolved already will be in here
496     const CompilerType &compiler_type, CompletionRequest &request) {
497   //    printf ("\nPrivateAutoComplete()\n\tprefix_path = '%s'\n\tpartial_path =
498   //    '%s'\n", prefix_path.c_str(), partial_path.c_str());
499   std::string remaining_partial_path;
500 
501   const lldb::TypeClass type_class = compiler_type.GetTypeClass();
502   if (partial_path.empty()) {
503     if (compiler_type.IsValid()) {
504       switch (type_class) {
505       default:
506       case eTypeClassArray:
507       case eTypeClassBlockPointer:
508       case eTypeClassBuiltin:
509       case eTypeClassComplexFloat:
510       case eTypeClassComplexInteger:
511       case eTypeClassEnumeration:
512       case eTypeClassFunction:
513       case eTypeClassMemberPointer:
514       case eTypeClassReference:
515       case eTypeClassTypedef:
516       case eTypeClassVector: {
517         request.AddCompletion(prefix_path.str());
518       } break;
519 
520       case eTypeClassClass:
521       case eTypeClassStruct:
522       case eTypeClassUnion:
523         if (prefix_path.str().back() != '.')
524           request.AddCompletion((prefix_path + ".").str());
525         break;
526 
527       case eTypeClassObjCObject:
528       case eTypeClassObjCInterface:
529         break;
530       case eTypeClassObjCObjectPointer:
531       case eTypeClassPointer: {
532         bool omit_empty_base_classes = true;
533         if (compiler_type.GetNumChildren(omit_empty_base_classes, nullptr) > 0)
534           request.AddCompletion((prefix_path + "->").str());
535         else {
536           request.AddCompletion(prefix_path.str());
537         }
538       } break;
539       }
540     } else {
541       if (frame) {
542         const bool get_file_globals = true;
543 
544         VariableList *variable_list = frame->GetVariableList(get_file_globals);
545 
546         if (variable_list) {
547           for (const VariableSP &var_sp : *variable_list)
548             request.AddCompletion(var_sp->GetName().AsCString());
549         }
550       }
551     }
552   } else {
553     const char ch = partial_path[0];
554     switch (ch) {
555     case '*':
556       if (prefix_path.str().empty()) {
557         PrivateAutoComplete(frame, partial_path.substr(1), "*", compiler_type,
558                             request);
559       }
560       break;
561 
562     case '&':
563       if (prefix_path.isTriviallyEmpty()) {
564         PrivateAutoComplete(frame, partial_path.substr(1), std::string("&"),
565                             compiler_type, request);
566       }
567       break;
568 
569     case '-':
570       if (partial_path.size() > 1 && partial_path[1] == '>' &&
571           !prefix_path.str().empty()) {
572         switch (type_class) {
573         case lldb::eTypeClassPointer: {
574           CompilerType pointee_type(compiler_type.GetPointeeType());
575           if (partial_path.size() > 2 && partial_path[2]) {
576             // If there is more after the "->", then search deeper
577             PrivateAutoComplete(frame, partial_path.substr(2),
578                                 prefix_path + "->",
579                                 pointee_type.GetCanonicalType(), request);
580           } else {
581             // Nothing after the "->", so list all members
582             PrivateAutoCompleteMembers(
583                 frame, std::string(), std::string(), prefix_path + "->",
584                 pointee_type.GetCanonicalType(), request);
585           }
586         } break;
587         default:
588           break;
589         }
590       }
591       break;
592 
593     case '.':
594       if (compiler_type.IsValid()) {
595         switch (type_class) {
596         case lldb::eTypeClassUnion:
597         case lldb::eTypeClassStruct:
598         case lldb::eTypeClassClass:
599           if (partial_path.size() > 1 && partial_path[1]) {
600             // If there is more after the ".", then search deeper
601             PrivateAutoComplete(frame, partial_path.substr(1),
602                                 prefix_path + ".", compiler_type, request);
603 
604           } else {
605             // Nothing after the ".", so list all members
606             PrivateAutoCompleteMembers(frame, std::string(), partial_path,
607                                        prefix_path + ".", compiler_type,
608                                        request);
609           }
610           break;
611         default:
612           break;
613         }
614       }
615       break;
616     default:
617       if (isalpha(ch) || ch == '_' || ch == '$') {
618         const size_t partial_path_len = partial_path.size();
619         size_t pos = 1;
620         while (pos < partial_path_len) {
621           const char curr_ch = partial_path[pos];
622           if (isalnum(curr_ch) || curr_ch == '_' || curr_ch == '$') {
623             ++pos;
624             continue;
625           }
626           break;
627         }
628 
629         std::string token(std::string(partial_path), 0, pos);
630         remaining_partial_path = std::string(partial_path.substr(pos));
631 
632         if (compiler_type.IsValid()) {
633           PrivateAutoCompleteMembers(frame, token, remaining_partial_path,
634                                      prefix_path, compiler_type, request);
635         } else if (frame) {
636           // We haven't found our variable yet
637           const bool get_file_globals = true;
638 
639           VariableList *variable_list =
640               frame->GetVariableList(get_file_globals);
641 
642           if (!variable_list)
643             break;
644 
645           for (VariableSP var_sp : *variable_list) {
646 
647             if (!var_sp)
648               continue;
649 
650             llvm::StringRef variable_name = var_sp->GetName().GetStringRef();
651             if (variable_name.startswith(token)) {
652               if (variable_name == token) {
653                 Type *variable_type = var_sp->GetType();
654                 if (variable_type) {
655                   CompilerType variable_compiler_type(
656                       variable_type->GetForwardCompilerType());
657                   PrivateAutoComplete(
658                       frame, remaining_partial_path,
659                       prefix_path + token, // Anything that has been resolved
660                                            // already will be in here
661                       variable_compiler_type.GetCanonicalType(), request);
662                 } else {
663                   request.AddCompletion((prefix_path + variable_name).str());
664                 }
665               } else if (remaining_partial_path.empty()) {
666                 request.AddCompletion((prefix_path + variable_name).str());
667               }
668             }
669           }
670         }
671       }
672       break;
673     }
674   }
675 }
676 
677 void Variable::AutoComplete(const ExecutionContext &exe_ctx,
678                             CompletionRequest &request) {
679   CompilerType compiler_type;
680 
681   PrivateAutoComplete(exe_ctx.GetFramePtr(), request.GetCursorArgumentPrefix(),
682                       "", compiler_type, request);
683 }
684