1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
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/Target/Target.h"
10 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
11 #include "lldb/Breakpoint/BreakpointIDList.h"
12 #include "lldb/Breakpoint/BreakpointPrecondition.h"
13 #include "lldb/Breakpoint/BreakpointResolver.h"
14 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
15 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
16 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
17 #include "lldb/Breakpoint/BreakpointResolverName.h"
18 #include "lldb/Breakpoint/BreakpointResolverScripted.h"
19 #include "lldb/Breakpoint/Watchpoint.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/SearchFilter.h"
25 #include "lldb/Core/Section.h"
26 #include "lldb/Core/SourceManager.h"
27 #include "lldb/Core/StreamFile.h"
28 #include "lldb/Core/StructuredDataImpl.h"
29 #include "lldb/Core/ValueObject.h"
30 #include "lldb/Expression/REPL.h"
31 #include "lldb/Expression/UserExpression.h"
32 #include "lldb/Host/Host.h"
33 #include "lldb/Host/PosixApi.h"
34 #include "lldb/Interpreter/CommandInterpreter.h"
35 #include "lldb/Interpreter/CommandReturnObject.h"
36 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
37 #include "lldb/Interpreter/OptionValues.h"
38 #include "lldb/Interpreter/Property.h"
39 #include "lldb/Symbol/ClangASTContext.h"
40 #include "lldb/Symbol/ClangASTImporter.h"
41 #include "lldb/Symbol/Function.h"
42 #include "lldb/Symbol/ObjectFile.h"
43 #include "lldb/Symbol/Symbol.h"
44 #include "lldb/Target/Language.h"
45 #include "lldb/Target/LanguageRuntime.h"
46 #include "lldb/Target/Process.h"
47 #include "lldb/Target/SectionLoadList.h"
48 #include "lldb/Target/StackFrame.h"
49 #include "lldb/Target/SystemRuntime.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Target/ThreadSpec.h"
52 #include "lldb/Utility/Event.h"
53 #include "lldb/Utility/FileSpec.h"
54 #include "lldb/Utility/LLDBAssert.h"
55 #include "lldb/Utility/Log.h"
56 #include "lldb/Utility/State.h"
57 #include "lldb/Utility/StreamString.h"
58 #include "lldb/Utility/Timer.h"
59
60 #include "llvm/ADT/ScopeExit.h"
61
62 #include <memory>
63 #include <mutex>
64
65 using namespace lldb;
66 using namespace lldb_private;
67
68 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
69
Arch(const ArchSpec & spec)70 Target::Arch::Arch(const ArchSpec &spec)
71 : m_spec(spec),
72 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
73
operator =(const ArchSpec & spec)74 const Target::Arch &Target::Arch::operator=(const ArchSpec &spec) {
75 m_spec = spec;
76 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
77 return *this;
78 }
79
GetStaticBroadcasterClass()80 ConstString &Target::GetStaticBroadcasterClass() {
81 static ConstString class_name("lldb.target");
82 return class_name;
83 }
84
Target(Debugger & debugger,const ArchSpec & target_arch,const lldb::PlatformSP & platform_sp,bool is_dummy_target)85 Target::Target(Debugger &debugger, const ArchSpec &target_arch,
86 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
87 : TargetProperties(this),
88 Broadcaster(debugger.GetBroadcasterManager(),
89 Target::GetStaticBroadcasterClass().AsCString()),
90 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
91 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
92 m_breakpoint_list(false), m_internal_breakpoint_list(true),
93 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
94 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
95 m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0),
96 m_valid(true), m_suppress_stop_hooks(false),
97 m_is_dummy_target(is_dummy_target),
98 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
99
100 {
101 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
102 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
103 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
104 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
105 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
106
107 CheckInWithManager();
108
109 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT),
110 "{0} Target::Target()", static_cast<void *>(this));
111 if (target_arch.IsValid()) {
112 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
113 "Target::Target created with architecture {0} ({1})",
114 target_arch.GetArchitectureName(),
115 target_arch.GetTriple().getTriple().c_str());
116 }
117 }
118
~Target()119 Target::~Target() {
120 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
121 LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
122 DeleteCurrentProcess();
123 }
124
PrimeFromDummyTarget(Target * target)125 void Target::PrimeFromDummyTarget(Target *target) {
126 if (!target)
127 return;
128
129 m_stop_hooks = target->m_stop_hooks;
130
131 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
132 if (breakpoint_sp->IsInternal())
133 continue;
134
135 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
136 AddBreakpoint(new_bp, false);
137 }
138
139 for (auto bp_name_entry : target->m_breakpoint_names) {
140
141 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
142 AddBreakpointName(new_bp_name);
143 }
144 }
145
Dump(Stream * s,lldb::DescriptionLevel description_level)146 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
147 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
148 if (description_level != lldb::eDescriptionLevelBrief) {
149 s->Indent();
150 s->PutCString("Target\n");
151 s->IndentMore();
152 m_images.Dump(s);
153 m_breakpoint_list.Dump(s);
154 m_internal_breakpoint_list.Dump(s);
155 s->IndentLess();
156 } else {
157 Module *exe_module = GetExecutableModulePointer();
158 if (exe_module)
159 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
160 else
161 s->PutCString("No executable module.");
162 }
163 }
164
CleanupProcess()165 void Target::CleanupProcess() {
166 // Do any cleanup of the target we need to do between process instances.
167 // NB It is better to do this before destroying the process in case the
168 // clean up needs some help from the process.
169 m_breakpoint_list.ClearAllBreakpointSites();
170 m_internal_breakpoint_list.ClearAllBreakpointSites();
171 // Disable watchpoints just on the debugger side.
172 std::unique_lock<std::recursive_mutex> lock;
173 this->GetWatchpointList().GetListMutex(lock);
174 DisableAllWatchpoints(false);
175 ClearAllWatchpointHitCounts();
176 ClearAllWatchpointHistoricValues();
177 }
178
DeleteCurrentProcess()179 void Target::DeleteCurrentProcess() {
180 if (m_process_sp) {
181 m_section_load_history.Clear();
182 if (m_process_sp->IsAlive())
183 m_process_sp->Destroy(false);
184
185 m_process_sp->Finalize();
186
187 CleanupProcess();
188
189 m_process_sp.reset();
190 }
191 }
192
CreateProcess(ListenerSP listener_sp,llvm::StringRef plugin_name,const FileSpec * crash_file)193 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
194 llvm::StringRef plugin_name,
195 const FileSpec *crash_file) {
196 if (!listener_sp)
197 listener_sp = GetDebugger().GetListener();
198 DeleteCurrentProcess();
199 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
200 listener_sp, crash_file);
201 return m_process_sp;
202 }
203
GetProcessSP() const204 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
205
GetREPL(Status & err,lldb::LanguageType language,const char * repl_options,bool can_create)206 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
207 const char *repl_options, bool can_create) {
208 if (language == eLanguageTypeUnknown) {
209 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
210
211 if (auto single_lang = repl_languages.GetSingularLanguage()) {
212 language = *single_lang;
213 } else if (repl_languages.Empty()) {
214 err.SetErrorStringWithFormat(
215 "LLDB isn't configured with REPL support for any languages.");
216 return REPLSP();
217 } else {
218 err.SetErrorStringWithFormat(
219 "Multiple possible REPL languages. Please specify a language.");
220 return REPLSP();
221 }
222 }
223
224 REPLMap::iterator pos = m_repl_map.find(language);
225
226 if (pos != m_repl_map.end()) {
227 return pos->second;
228 }
229
230 if (!can_create) {
231 err.SetErrorStringWithFormat(
232 "Couldn't find an existing REPL for %s, and can't create a new one",
233 Language::GetNameForLanguageType(language));
234 return lldb::REPLSP();
235 }
236
237 Debugger *const debugger = nullptr;
238 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
239
240 if (ret) {
241 m_repl_map[language] = ret;
242 return m_repl_map[language];
243 }
244
245 if (err.Success()) {
246 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
247 Language::GetNameForLanguageType(language));
248 }
249
250 return lldb::REPLSP();
251 }
252
SetREPL(lldb::LanguageType language,lldb::REPLSP repl_sp)253 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
254 lldbassert(!m_repl_map.count(language));
255
256 m_repl_map[language] = repl_sp;
257 }
258
Destroy()259 void Target::Destroy() {
260 std::lock_guard<std::recursive_mutex> guard(m_mutex);
261 m_valid = false;
262 DeleteCurrentProcess();
263 m_platform_sp.reset();
264 m_arch = ArchSpec();
265 ClearModules(true);
266 m_section_load_history.Clear();
267 const bool notify = false;
268 m_breakpoint_list.RemoveAll(notify);
269 m_internal_breakpoint_list.RemoveAll(notify);
270 m_last_created_breakpoint.reset();
271 m_last_created_watchpoint.reset();
272 m_search_filter_sp.reset();
273 m_image_search_paths.Clear(notify);
274 m_stop_hooks.clear();
275 m_stop_hook_next_id = 0;
276 m_suppress_stop_hooks = false;
277 }
278
GetBreakpointList(bool internal)279 BreakpointList &Target::GetBreakpointList(bool internal) {
280 if (internal)
281 return m_internal_breakpoint_list;
282 else
283 return m_breakpoint_list;
284 }
285
GetBreakpointList(bool internal) const286 const BreakpointList &Target::GetBreakpointList(bool internal) const {
287 if (internal)
288 return m_internal_breakpoint_list;
289 else
290 return m_breakpoint_list;
291 }
292
GetBreakpointByID(break_id_t break_id)293 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
294 BreakpointSP bp_sp;
295
296 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
297 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
298 else
299 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
300
301 return bp_sp;
302 }
303
CreateSourceRegexBreakpoint(const FileSpecList * containingModules,const FileSpecList * source_file_spec_list,const std::unordered_set<std::string> & function_names,RegularExpression source_regex,bool internal,bool hardware,LazyBool move_to_nearest_code)304 BreakpointSP Target::CreateSourceRegexBreakpoint(
305 const FileSpecList *containingModules,
306 const FileSpecList *source_file_spec_list,
307 const std::unordered_set<std::string> &function_names,
308 RegularExpression source_regex, bool internal, bool hardware,
309 LazyBool move_to_nearest_code) {
310 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
311 containingModules, source_file_spec_list));
312 if (move_to_nearest_code == eLazyBoolCalculate)
313 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
314 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
315 nullptr, std::move(source_regex), function_names,
316 !static_cast<bool>(move_to_nearest_code)));
317
318 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
319 }
320
CreateBreakpoint(const FileSpecList * containingModules,const FileSpec & file,uint32_t line_no,uint32_t column,lldb::addr_t offset,LazyBool check_inlines,LazyBool skip_prologue,bool internal,bool hardware,LazyBool move_to_nearest_code)321 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
322 const FileSpec &file, uint32_t line_no,
323 uint32_t column, lldb::addr_t offset,
324 LazyBool check_inlines,
325 LazyBool skip_prologue, bool internal,
326 bool hardware,
327 LazyBool move_to_nearest_code) {
328 FileSpec remapped_file;
329 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
330 remapped_file = file;
331
332 if (check_inlines == eLazyBoolCalculate) {
333 const InlineStrategy inline_strategy = GetInlineStrategy();
334 switch (inline_strategy) {
335 case eInlineBreakpointsNever:
336 check_inlines = eLazyBoolNo;
337 break;
338
339 case eInlineBreakpointsHeaders:
340 if (remapped_file.IsSourceImplementationFile())
341 check_inlines = eLazyBoolNo;
342 else
343 check_inlines = eLazyBoolYes;
344 break;
345
346 case eInlineBreakpointsAlways:
347 check_inlines = eLazyBoolYes;
348 break;
349 }
350 }
351 SearchFilterSP filter_sp;
352 if (check_inlines == eLazyBoolNo) {
353 // Not checking for inlines, we are looking only for matching compile units
354 FileSpecList compile_unit_list;
355 compile_unit_list.Append(remapped_file);
356 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
357 &compile_unit_list);
358 } else {
359 filter_sp = GetSearchFilterForModuleList(containingModules);
360 }
361 if (skip_prologue == eLazyBoolCalculate)
362 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
363 if (move_to_nearest_code == eLazyBoolCalculate)
364 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
365
366 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
367 nullptr, remapped_file, line_no, column, offset, check_inlines,
368 skip_prologue, !static_cast<bool>(move_to_nearest_code)));
369 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
370 }
371
CreateBreakpoint(lldb::addr_t addr,bool internal,bool hardware)372 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
373 bool hardware) {
374 Address so_addr;
375
376 // Check for any reason we want to move this breakpoint to other address.
377 addr = GetBreakableLoadAddress(addr);
378
379 // Attempt to resolve our load address if possible, though it is ok if it
380 // doesn't resolve to section/offset.
381
382 // Try and resolve as a load address if possible
383 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
384 if (!so_addr.IsValid()) {
385 // The address didn't resolve, so just set this as an absolute address
386 so_addr.SetOffset(addr);
387 }
388 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
389 return bp_sp;
390 }
391
CreateBreakpoint(const Address & addr,bool internal,bool hardware)392 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
393 bool hardware) {
394 SearchFilterSP filter_sp(
395 new SearchFilterForUnconstrainedSearches(shared_from_this()));
396 BreakpointResolverSP resolver_sp(
397 new BreakpointResolverAddress(nullptr, addr));
398 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
399 }
400
401 lldb::BreakpointSP
CreateAddressInModuleBreakpoint(lldb::addr_t file_addr,bool internal,const FileSpec * file_spec,bool request_hardware)402 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
403 const FileSpec *file_spec,
404 bool request_hardware) {
405 SearchFilterSP filter_sp(
406 new SearchFilterForUnconstrainedSearches(shared_from_this()));
407 BreakpointResolverSP resolver_sp(new BreakpointResolverAddress(
408 nullptr, file_addr, file_spec ? *file_spec : FileSpec()));
409 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
410 false);
411 }
412
CreateBreakpoint(const FileSpecList * containingModules,const FileSpecList * containingSourceFiles,const char * func_name,FunctionNameType func_name_type_mask,LanguageType language,lldb::addr_t offset,LazyBool skip_prologue,bool internal,bool hardware)413 BreakpointSP Target::CreateBreakpoint(
414 const FileSpecList *containingModules,
415 const FileSpecList *containingSourceFiles, const char *func_name,
416 FunctionNameType func_name_type_mask, LanguageType language,
417 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
418 BreakpointSP bp_sp;
419 if (func_name) {
420 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
421 containingModules, containingSourceFiles));
422
423 if (skip_prologue == eLazyBoolCalculate)
424 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
425 if (language == lldb::eLanguageTypeUnknown)
426 language = GetLanguage();
427
428 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
429 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
430 offset, skip_prologue));
431 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
432 }
433 return bp_sp;
434 }
435
436 lldb::BreakpointSP
CreateBreakpoint(const FileSpecList * containingModules,const FileSpecList * containingSourceFiles,const std::vector<std::string> & func_names,FunctionNameType func_name_type_mask,LanguageType language,lldb::addr_t offset,LazyBool skip_prologue,bool internal,bool hardware)437 Target::CreateBreakpoint(const FileSpecList *containingModules,
438 const FileSpecList *containingSourceFiles,
439 const std::vector<std::string> &func_names,
440 FunctionNameType func_name_type_mask,
441 LanguageType language, lldb::addr_t offset,
442 LazyBool skip_prologue, bool internal, bool hardware) {
443 BreakpointSP bp_sp;
444 size_t num_names = func_names.size();
445 if (num_names > 0) {
446 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
447 containingModules, containingSourceFiles));
448
449 if (skip_prologue == eLazyBoolCalculate)
450 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
451 if (language == lldb::eLanguageTypeUnknown)
452 language = GetLanguage();
453
454 BreakpointResolverSP resolver_sp(
455 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
456 language, offset, skip_prologue));
457 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
458 }
459 return bp_sp;
460 }
461
462 BreakpointSP
CreateBreakpoint(const FileSpecList * containingModules,const FileSpecList * containingSourceFiles,const char * func_names[],size_t num_names,FunctionNameType func_name_type_mask,LanguageType language,lldb::addr_t offset,LazyBool skip_prologue,bool internal,bool hardware)463 Target::CreateBreakpoint(const FileSpecList *containingModules,
464 const FileSpecList *containingSourceFiles,
465 const char *func_names[], size_t num_names,
466 FunctionNameType func_name_type_mask,
467 LanguageType language, lldb::addr_t offset,
468 LazyBool skip_prologue, bool internal, bool hardware) {
469 BreakpointSP bp_sp;
470 if (num_names > 0) {
471 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
472 containingModules, containingSourceFiles));
473
474 if (skip_prologue == eLazyBoolCalculate) {
475 if (offset == 0)
476 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
477 else
478 skip_prologue = eLazyBoolNo;
479 }
480 if (language == lldb::eLanguageTypeUnknown)
481 language = GetLanguage();
482
483 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
484 nullptr, func_names, num_names, func_name_type_mask, language, offset,
485 skip_prologue));
486 resolver_sp->SetOffset(offset);
487 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
488 }
489 return bp_sp;
490 }
491
492 SearchFilterSP
GetSearchFilterForModule(const FileSpec * containingModule)493 Target::GetSearchFilterForModule(const FileSpec *containingModule) {
494 SearchFilterSP filter_sp;
495 if (containingModule != nullptr) {
496 // TODO: We should look into sharing module based search filters
497 // across many breakpoints like we do for the simple target based one
498 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
499 *containingModule);
500 } else {
501 if (!m_search_filter_sp)
502 m_search_filter_sp =
503 std::make_shared<SearchFilterForUnconstrainedSearches>(
504 shared_from_this());
505 filter_sp = m_search_filter_sp;
506 }
507 return filter_sp;
508 }
509
510 SearchFilterSP
GetSearchFilterForModuleList(const FileSpecList * containingModules)511 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
512 SearchFilterSP filter_sp;
513 if (containingModules && containingModules->GetSize() != 0) {
514 // TODO: We should look into sharing module based search filters
515 // across many breakpoints like we do for the simple target based one
516 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
517 *containingModules);
518 } else {
519 if (!m_search_filter_sp)
520 m_search_filter_sp =
521 std::make_shared<SearchFilterForUnconstrainedSearches>(
522 shared_from_this());
523 filter_sp = m_search_filter_sp;
524 }
525 return filter_sp;
526 }
527
GetSearchFilterForModuleAndCUList(const FileSpecList * containingModules,const FileSpecList * containingSourceFiles)528 SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
529 const FileSpecList *containingModules,
530 const FileSpecList *containingSourceFiles) {
531 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
532 return GetSearchFilterForModuleList(containingModules);
533
534 SearchFilterSP filter_sp;
535 if (containingModules == nullptr) {
536 // We could make a special "CU List only SearchFilter". Better yet was if
537 // these could be composable, but that will take a little reworking.
538
539 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
540 shared_from_this(), FileSpecList(), *containingSourceFiles);
541 } else {
542 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
543 shared_from_this(), *containingModules, *containingSourceFiles);
544 }
545 return filter_sp;
546 }
547
CreateFuncRegexBreakpoint(const FileSpecList * containingModules,const FileSpecList * containingSourceFiles,RegularExpression func_regex,lldb::LanguageType requested_language,LazyBool skip_prologue,bool internal,bool hardware)548 BreakpointSP Target::CreateFuncRegexBreakpoint(
549 const FileSpecList *containingModules,
550 const FileSpecList *containingSourceFiles, RegularExpression func_regex,
551 lldb::LanguageType requested_language, LazyBool skip_prologue,
552 bool internal, bool hardware) {
553 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
554 containingModules, containingSourceFiles));
555 bool skip = (skip_prologue == eLazyBoolCalculate)
556 ? GetSkipPrologue()
557 : static_cast<bool>(skip_prologue);
558 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
559 nullptr, std::move(func_regex), requested_language, 0, skip));
560
561 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
562 }
563
564 lldb::BreakpointSP
CreateExceptionBreakpoint(enum lldb::LanguageType language,bool catch_bp,bool throw_bp,bool internal,Args * additional_args,Status * error)565 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
566 bool catch_bp, bool throw_bp, bool internal,
567 Args *additional_args, Status *error) {
568 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
569 *this, language, catch_bp, throw_bp, internal);
570 if (exc_bkpt_sp && additional_args) {
571 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
572 if (precondition_sp && additional_args) {
573 if (error)
574 *error = precondition_sp->ConfigurePrecondition(*additional_args);
575 else
576 precondition_sp->ConfigurePrecondition(*additional_args);
577 }
578 }
579 return exc_bkpt_sp;
580 }
581
CreateScriptedBreakpoint(const llvm::StringRef class_name,const FileSpecList * containingModules,const FileSpecList * containingSourceFiles,bool internal,bool request_hardware,StructuredData::ObjectSP extra_args_sp,Status * creation_error)582 lldb::BreakpointSP Target::CreateScriptedBreakpoint(
583 const llvm::StringRef class_name, const FileSpecList *containingModules,
584 const FileSpecList *containingSourceFiles, bool internal,
585 bool request_hardware, StructuredData::ObjectSP extra_args_sp,
586 Status *creation_error) {
587 SearchFilterSP filter_sp;
588
589 lldb::SearchDepth depth = lldb::eSearchDepthTarget;
590 bool has_files =
591 containingSourceFiles && containingSourceFiles->GetSize() > 0;
592 bool has_modules = containingModules && containingModules->GetSize() > 0;
593
594 if (has_files && has_modules) {
595 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
596 containingSourceFiles);
597 } else if (has_files) {
598 filter_sp =
599 GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
600 } else if (has_modules) {
601 filter_sp = GetSearchFilterForModuleList(containingModules);
602 } else {
603 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
604 shared_from_this());
605 }
606
607 StructuredDataImpl *extra_args_impl = new StructuredDataImpl();
608 if (extra_args_sp)
609 extra_args_impl->SetObjectSP(extra_args_sp);
610
611 BreakpointResolverSP resolver_sp(new BreakpointResolverScripted(
612 nullptr, class_name, depth, extra_args_impl));
613 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
614 }
615
CreateBreakpoint(SearchFilterSP & filter_sp,BreakpointResolverSP & resolver_sp,bool internal,bool request_hardware,bool resolve_indirect_symbols)616 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
617 BreakpointResolverSP &resolver_sp,
618 bool internal, bool request_hardware,
619 bool resolve_indirect_symbols) {
620 BreakpointSP bp_sp;
621 if (filter_sp && resolver_sp) {
622 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
623 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
624 resolve_indirect_symbols));
625 resolver_sp->SetBreakpoint(bp_sp.get());
626 AddBreakpoint(bp_sp, internal);
627 }
628 return bp_sp;
629 }
630
AddBreakpoint(lldb::BreakpointSP bp_sp,bool internal)631 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
632 if (!bp_sp)
633 return;
634 if (internal)
635 m_internal_breakpoint_list.Add(bp_sp, false);
636 else
637 m_breakpoint_list.Add(bp_sp, true);
638
639 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
640 if (log) {
641 StreamString s;
642 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
643 LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
644 __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
645 }
646
647 bp_sp->ResolveBreakpoint();
648
649 if (!internal) {
650 m_last_created_breakpoint = bp_sp;
651 }
652 }
653
AddNameToBreakpoint(BreakpointID & id,const char * name,Status & error)654 void Target::AddNameToBreakpoint(BreakpointID &id, const char *name,
655 Status &error) {
656 BreakpointSP bp_sp =
657 m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
658 if (!bp_sp) {
659 StreamString s;
660 id.GetDescription(&s, eDescriptionLevelBrief);
661 error.SetErrorStringWithFormat("Could not find breakpoint %s", s.GetData());
662 return;
663 }
664 AddNameToBreakpoint(bp_sp, name, error);
665 }
666
AddNameToBreakpoint(BreakpointSP & bp_sp,const char * name,Status & error)667 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, const char *name,
668 Status &error) {
669 if (!bp_sp)
670 return;
671
672 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
673 if (!bp_name)
674 return;
675
676 bp_name->ConfigureBreakpoint(bp_sp);
677 bp_sp->AddName(name);
678 }
679
AddBreakpointName(BreakpointName * bp_name)680 void Target::AddBreakpointName(BreakpointName *bp_name) {
681 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
682 }
683
FindBreakpointName(ConstString name,bool can_create,Status & error)684 BreakpointName *Target::FindBreakpointName(ConstString name, bool can_create,
685 Status &error) {
686 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
687 if (!error.Success())
688 return nullptr;
689
690 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
691 if (iter == m_breakpoint_names.end()) {
692 if (!can_create) {
693 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
694 "can_create is false.",
695 name.AsCString());
696 return nullptr;
697 }
698
699 iter = m_breakpoint_names
700 .insert(std::make_pair(name, new BreakpointName(name)))
701 .first;
702 }
703 return (iter->second);
704 }
705
DeleteBreakpointName(ConstString name)706 void Target::DeleteBreakpointName(ConstString name) {
707 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
708
709 if (iter != m_breakpoint_names.end()) {
710 const char *name_cstr = name.AsCString();
711 m_breakpoint_names.erase(iter);
712 for (auto bp_sp : m_breakpoint_list.Breakpoints())
713 bp_sp->RemoveName(name_cstr);
714 }
715 }
716
RemoveNameFromBreakpoint(lldb::BreakpointSP & bp_sp,ConstString name)717 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
718 ConstString name) {
719 bp_sp->RemoveName(name.AsCString());
720 }
721
ConfigureBreakpointName(BreakpointName & bp_name,const BreakpointOptions & new_options,const BreakpointName::Permissions & new_permissions)722 void Target::ConfigureBreakpointName(
723 BreakpointName &bp_name, const BreakpointOptions &new_options,
724 const BreakpointName::Permissions &new_permissions) {
725 bp_name.GetOptions().CopyOverSetOptions(new_options);
726 bp_name.GetPermissions().MergeInto(new_permissions);
727 ApplyNameToBreakpoints(bp_name);
728 }
729
ApplyNameToBreakpoints(BreakpointName & bp_name)730 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
731 llvm::Expected<std::vector<BreakpointSP>> expected_vector =
732 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString());
733
734 if (!expected_vector) {
735 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS),
736 "invalid breakpoint name: {}",
737 llvm::toString(expected_vector.takeError()));
738 return;
739 }
740
741 for (auto bp_sp : *expected_vector)
742 bp_name.ConfigureBreakpoint(bp_sp);
743 }
744
GetBreakpointNames(std::vector<std::string> & names)745 void Target::GetBreakpointNames(std::vector<std::string> &names) {
746 names.clear();
747 for (auto bp_name : m_breakpoint_names) {
748 names.push_back(bp_name.first.AsCString());
749 }
750 llvm::sort(names.begin(), names.end());
751 }
752
ProcessIsValid()753 bool Target::ProcessIsValid() {
754 return (m_process_sp && m_process_sp->IsAlive());
755 }
756
CheckIfWatchpointsSupported(Target * target,Status & error)757 static bool CheckIfWatchpointsSupported(Target *target, Status &error) {
758 uint32_t num_supported_hardware_watchpoints;
759 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
760 num_supported_hardware_watchpoints);
761
762 // If unable to determine the # of watchpoints available,
763 // assume they are supported.
764 if (rc.Fail())
765 return true;
766
767 if (num_supported_hardware_watchpoints == 0) {
768 error.SetErrorStringWithFormat(
769 "Target supports (%u) hardware watchpoint slots.\n",
770 num_supported_hardware_watchpoints);
771 return false;
772 }
773 return true;
774 }
775
776 // See also Watchpoint::SetWatchpointType(uint32_t type) and the
777 // OptionGroupWatchpoint::WatchType enum type.
CreateWatchpoint(lldb::addr_t addr,size_t size,const CompilerType * type,uint32_t kind,Status & error)778 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
779 const CompilerType *type, uint32_t kind,
780 Status &error) {
781 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
782 LLDB_LOGF(log,
783 "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
784 " type = %u)\n",
785 __FUNCTION__, addr, (uint64_t)size, kind);
786
787 WatchpointSP wp_sp;
788 if (!ProcessIsValid()) {
789 error.SetErrorString("process is not alive");
790 return wp_sp;
791 }
792
793 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
794 if (size == 0)
795 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
796 else
797 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
798 return wp_sp;
799 }
800
801 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
802 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
803 }
804
805 if (!CheckIfWatchpointsSupported(this, error))
806 return wp_sp;
807
808 // Currently we only support one watchpoint per address, with total number of
809 // watchpoints limited by the hardware which the inferior is running on.
810
811 // Grab the list mutex while doing operations.
812 const bool notify = false; // Don't notify about all the state changes we do
813 // on creating the watchpoint.
814 std::unique_lock<std::recursive_mutex> lock;
815 this->GetWatchpointList().GetListMutex(lock);
816 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
817 if (matched_sp) {
818 size_t old_size = matched_sp->GetByteSize();
819 uint32_t old_type =
820 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
821 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
822 // Return the existing watchpoint if both size and type match.
823 if (size == old_size && kind == old_type) {
824 wp_sp = matched_sp;
825 wp_sp->SetEnabled(false, notify);
826 } else {
827 // Nil the matched watchpoint; we will be creating a new one.
828 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
829 m_watchpoint_list.Remove(matched_sp->GetID(), true);
830 }
831 }
832
833 if (!wp_sp) {
834 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
835 wp_sp->SetWatchpointType(kind, notify);
836 m_watchpoint_list.Add(wp_sp, true);
837 }
838
839 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
840 LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
841 __FUNCTION__, error.Success() ? "succeeded" : "failed",
842 wp_sp->GetID());
843
844 if (error.Fail()) {
845 // Enabling the watchpoint on the device side failed. Remove the said
846 // watchpoint from the list maintained by the target instance.
847 m_watchpoint_list.Remove(wp_sp->GetID(), true);
848 // See if we could provide more helpful error message.
849 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
850 error.SetErrorStringWithFormat(
851 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
852
853 wp_sp.reset();
854 } else
855 m_last_created_watchpoint = wp_sp;
856 return wp_sp;
857 }
858
RemoveAllowedBreakpoints()859 void Target::RemoveAllowedBreakpoints() {
860 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
861 LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
862
863 m_breakpoint_list.RemoveAllowed(true);
864
865 m_last_created_breakpoint.reset();
866 }
867
RemoveAllBreakpoints(bool internal_also)868 void Target::RemoveAllBreakpoints(bool internal_also) {
869 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
870 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
871 internal_also ? "yes" : "no");
872
873 m_breakpoint_list.RemoveAll(true);
874 if (internal_also)
875 m_internal_breakpoint_list.RemoveAll(false);
876
877 m_last_created_breakpoint.reset();
878 }
879
DisableAllBreakpoints(bool internal_also)880 void Target::DisableAllBreakpoints(bool internal_also) {
881 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
882 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
883 internal_also ? "yes" : "no");
884
885 m_breakpoint_list.SetEnabledAll(false);
886 if (internal_also)
887 m_internal_breakpoint_list.SetEnabledAll(false);
888 }
889
DisableAllowedBreakpoints()890 void Target::DisableAllowedBreakpoints() {
891 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
892 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
893
894 m_breakpoint_list.SetEnabledAllowed(false);
895 }
896
EnableAllBreakpoints(bool internal_also)897 void Target::EnableAllBreakpoints(bool internal_also) {
898 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
899 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
900 internal_also ? "yes" : "no");
901
902 m_breakpoint_list.SetEnabledAll(true);
903 if (internal_also)
904 m_internal_breakpoint_list.SetEnabledAll(true);
905 }
906
EnableAllowedBreakpoints()907 void Target::EnableAllowedBreakpoints() {
908 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
909 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
910
911 m_breakpoint_list.SetEnabledAllowed(true);
912 }
913
RemoveBreakpointByID(break_id_t break_id)914 bool Target::RemoveBreakpointByID(break_id_t break_id) {
915 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
916 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
917 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
918
919 if (DisableBreakpointByID(break_id)) {
920 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
921 m_internal_breakpoint_list.Remove(break_id, false);
922 else {
923 if (m_last_created_breakpoint) {
924 if (m_last_created_breakpoint->GetID() == break_id)
925 m_last_created_breakpoint.reset();
926 }
927 m_breakpoint_list.Remove(break_id, true);
928 }
929 return true;
930 }
931 return false;
932 }
933
DisableBreakpointByID(break_id_t break_id)934 bool Target::DisableBreakpointByID(break_id_t break_id) {
935 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
936 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
937 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
938
939 BreakpointSP bp_sp;
940
941 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
942 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
943 else
944 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
945 if (bp_sp) {
946 bp_sp->SetEnabled(false);
947 return true;
948 }
949 return false;
950 }
951
EnableBreakpointByID(break_id_t break_id)952 bool Target::EnableBreakpointByID(break_id_t break_id) {
953 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
954 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
955 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
956
957 BreakpointSP bp_sp;
958
959 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
960 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
961 else
962 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
963
964 if (bp_sp) {
965 bp_sp->SetEnabled(true);
966 return true;
967 }
968 return false;
969 }
970
SerializeBreakpointsToFile(const FileSpec & file,const BreakpointIDList & bp_ids,bool append)971 Status Target::SerializeBreakpointsToFile(const FileSpec &file,
972 const BreakpointIDList &bp_ids,
973 bool append) {
974 Status error;
975
976 if (!file) {
977 error.SetErrorString("Invalid FileSpec.");
978 return error;
979 }
980
981 std::string path(file.GetPath());
982 StructuredData::ObjectSP input_data_sp;
983
984 StructuredData::ArraySP break_store_sp;
985 StructuredData::Array *break_store_ptr = nullptr;
986
987 if (append) {
988 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
989 if (error.Success()) {
990 break_store_ptr = input_data_sp->GetAsArray();
991 if (!break_store_ptr) {
992 error.SetErrorStringWithFormat(
993 "Tried to append to invalid input file %s", path.c_str());
994 return error;
995 }
996 }
997 }
998
999 if (!break_store_ptr) {
1000 break_store_sp = std::make_shared<StructuredData::Array>();
1001 break_store_ptr = break_store_sp.get();
1002 }
1003
1004 StreamFile out_file(path.c_str(),
1005 File::eOpenOptionTruncate | File::eOpenOptionWrite |
1006 File::eOpenOptionCanCreate |
1007 File::eOpenOptionCloseOnExec,
1008 lldb::eFilePermissionsFileDefault);
1009 if (!out_file.GetFile().IsValid()) {
1010 error.SetErrorStringWithFormat("Unable to open output file: %s.",
1011 path.c_str());
1012 return error;
1013 }
1014
1015 std::unique_lock<std::recursive_mutex> lock;
1016 GetBreakpointList().GetListMutex(lock);
1017
1018 if (bp_ids.GetSize() == 0) {
1019 const BreakpointList &breakpoints = GetBreakpointList();
1020
1021 size_t num_breakpoints = breakpoints.GetSize();
1022 for (size_t i = 0; i < num_breakpoints; i++) {
1023 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1024 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1025 // If a breakpoint can't serialize it, just ignore it for now:
1026 if (bkpt_save_sp)
1027 break_store_ptr->AddItem(bkpt_save_sp);
1028 }
1029 } else {
1030
1031 std::unordered_set<lldb::break_id_t> processed_bkpts;
1032 const size_t count = bp_ids.GetSize();
1033 for (size_t i = 0; i < count; ++i) {
1034 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1035 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1036
1037 if (bp_id != LLDB_INVALID_BREAK_ID) {
1038 // Only do each breakpoint once:
1039 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1040 insert_result = processed_bkpts.insert(bp_id);
1041 if (!insert_result.second)
1042 continue;
1043
1044 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1045 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1046 // If the user explicitly asked to serialize a breakpoint, and we
1047 // can't, then raise an error:
1048 if (!bkpt_save_sp) {
1049 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1050 bp_id);
1051 return error;
1052 }
1053 break_store_ptr->AddItem(bkpt_save_sp);
1054 }
1055 }
1056 }
1057
1058 break_store_ptr->Dump(out_file, false);
1059 out_file.PutChar('\n');
1060 return error;
1061 }
1062
CreateBreakpointsFromFile(const FileSpec & file,BreakpointIDList & new_bps)1063 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1064 BreakpointIDList &new_bps) {
1065 std::vector<std::string> no_names;
1066 return CreateBreakpointsFromFile(file, no_names, new_bps);
1067 }
1068
CreateBreakpointsFromFile(const FileSpec & file,std::vector<std::string> & names,BreakpointIDList & new_bps)1069 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1070 std::vector<std::string> &names,
1071 BreakpointIDList &new_bps) {
1072 std::unique_lock<std::recursive_mutex> lock;
1073 GetBreakpointList().GetListMutex(lock);
1074
1075 Status error;
1076 StructuredData::ObjectSP input_data_sp =
1077 StructuredData::ParseJSONFromFile(file, error);
1078 if (!error.Success()) {
1079 return error;
1080 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1081 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1082 file.GetPath().c_str());
1083 return error;
1084 }
1085
1086 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1087 if (!bkpt_array) {
1088 error.SetErrorStringWithFormat(
1089 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1090 return error;
1091 }
1092
1093 size_t num_bkpts = bkpt_array->GetSize();
1094 size_t num_names = names.size();
1095
1096 for (size_t i = 0; i < num_bkpts; i++) {
1097 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1098 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1099 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1100 if (!bkpt_dict) {
1101 error.SetErrorStringWithFormat(
1102 "Invalid breakpoint data for element %zu from input file: %s.", i,
1103 file.GetPath().c_str());
1104 return error;
1105 }
1106 StructuredData::ObjectSP bkpt_data_sp =
1107 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1108 if (num_names &&
1109 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1110 continue;
1111
1112 BreakpointSP bkpt_sp =
1113 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1114 if (!error.Success()) {
1115 error.SetErrorStringWithFormat(
1116 "Error restoring breakpoint %zu from %s: %s.", i,
1117 file.GetPath().c_str(), error.AsCString());
1118 return error;
1119 }
1120 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1121 }
1122 return error;
1123 }
1124
1125 // The flag 'end_to_end', default to true, signifies that the operation is
1126 // performed end to end, for both the debugger and the debuggee.
1127
1128 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1129 // to end operations.
RemoveAllWatchpoints(bool end_to_end)1130 bool Target::RemoveAllWatchpoints(bool end_to_end) {
1131 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1132 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1133
1134 if (!end_to_end) {
1135 m_watchpoint_list.RemoveAll(true);
1136 return true;
1137 }
1138
1139 // Otherwise, it's an end to end operation.
1140
1141 if (!ProcessIsValid())
1142 return false;
1143
1144 size_t num_watchpoints = m_watchpoint_list.GetSize();
1145 for (size_t i = 0; i < num_watchpoints; ++i) {
1146 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1147 if (!wp_sp)
1148 return false;
1149
1150 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1151 if (rc.Fail())
1152 return false;
1153 }
1154 m_watchpoint_list.RemoveAll(true);
1155 m_last_created_watchpoint.reset();
1156 return true; // Success!
1157 }
1158
1159 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1160 // to end operations.
DisableAllWatchpoints(bool end_to_end)1161 bool Target::DisableAllWatchpoints(bool end_to_end) {
1162 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1163 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1164
1165 if (!end_to_end) {
1166 m_watchpoint_list.SetEnabledAll(false);
1167 return true;
1168 }
1169
1170 // Otherwise, it's an end to end operation.
1171
1172 if (!ProcessIsValid())
1173 return false;
1174
1175 size_t num_watchpoints = m_watchpoint_list.GetSize();
1176 for (size_t i = 0; i < num_watchpoints; ++i) {
1177 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1178 if (!wp_sp)
1179 return false;
1180
1181 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1182 if (rc.Fail())
1183 return false;
1184 }
1185 return true; // Success!
1186 }
1187
1188 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1189 // to end operations.
EnableAllWatchpoints(bool end_to_end)1190 bool Target::EnableAllWatchpoints(bool end_to_end) {
1191 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1192 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1193
1194 if (!end_to_end) {
1195 m_watchpoint_list.SetEnabledAll(true);
1196 return true;
1197 }
1198
1199 // Otherwise, it's an end to end operation.
1200
1201 if (!ProcessIsValid())
1202 return false;
1203
1204 size_t num_watchpoints = m_watchpoint_list.GetSize();
1205 for (size_t i = 0; i < num_watchpoints; ++i) {
1206 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1207 if (!wp_sp)
1208 return false;
1209
1210 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1211 if (rc.Fail())
1212 return false;
1213 }
1214 return true; // Success!
1215 }
1216
1217 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
ClearAllWatchpointHitCounts()1218 bool Target::ClearAllWatchpointHitCounts() {
1219 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1220 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1221
1222 size_t num_watchpoints = m_watchpoint_list.GetSize();
1223 for (size_t i = 0; i < num_watchpoints; ++i) {
1224 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1225 if (!wp_sp)
1226 return false;
1227
1228 wp_sp->ResetHitCount();
1229 }
1230 return true; // Success!
1231 }
1232
1233 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
ClearAllWatchpointHistoricValues()1234 bool Target::ClearAllWatchpointHistoricValues() {
1235 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1236 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1237
1238 size_t num_watchpoints = m_watchpoint_list.GetSize();
1239 for (size_t i = 0; i < num_watchpoints; ++i) {
1240 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1241 if (!wp_sp)
1242 return false;
1243
1244 wp_sp->ResetHistoricValues();
1245 }
1246 return true; // Success!
1247 }
1248
1249 // Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1250 // these operations.
IgnoreAllWatchpoints(uint32_t ignore_count)1251 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1252 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1253 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1254
1255 if (!ProcessIsValid())
1256 return false;
1257
1258 size_t num_watchpoints = m_watchpoint_list.GetSize();
1259 for (size_t i = 0; i < num_watchpoints; ++i) {
1260 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1261 if (!wp_sp)
1262 return false;
1263
1264 wp_sp->SetIgnoreCount(ignore_count);
1265 }
1266 return true; // Success!
1267 }
1268
1269 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
DisableWatchpointByID(lldb::watch_id_t watch_id)1270 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1271 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1272 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1273
1274 if (!ProcessIsValid())
1275 return false;
1276
1277 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1278 if (wp_sp) {
1279 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1280 if (rc.Success())
1281 return true;
1282
1283 // Else, fallthrough.
1284 }
1285 return false;
1286 }
1287
1288 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
EnableWatchpointByID(lldb::watch_id_t watch_id)1289 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1290 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1291 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1292
1293 if (!ProcessIsValid())
1294 return false;
1295
1296 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1297 if (wp_sp) {
1298 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1299 if (rc.Success())
1300 return true;
1301
1302 // Else, fallthrough.
1303 }
1304 return false;
1305 }
1306
1307 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
RemoveWatchpointByID(lldb::watch_id_t watch_id)1308 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1309 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1310 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1311
1312 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1313 if (watch_to_remove_sp == m_last_created_watchpoint)
1314 m_last_created_watchpoint.reset();
1315
1316 if (DisableWatchpointByID(watch_id)) {
1317 m_watchpoint_list.Remove(watch_id, true);
1318 return true;
1319 }
1320 return false;
1321 }
1322
1323 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
IgnoreWatchpointByID(lldb::watch_id_t watch_id,uint32_t ignore_count)1324 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1325 uint32_t ignore_count) {
1326 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1327 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1328
1329 if (!ProcessIsValid())
1330 return false;
1331
1332 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1333 if (wp_sp) {
1334 wp_sp->SetIgnoreCount(ignore_count);
1335 return true;
1336 }
1337 return false;
1338 }
1339
GetExecutableModule()1340 ModuleSP Target::GetExecutableModule() {
1341 // search for the first executable in the module list
1342 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1343 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1344 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1345 if (obj == nullptr)
1346 continue;
1347 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1348 return module_sp;
1349 }
1350 // as fall back return the first module loaded
1351 return m_images.GetModuleAtIndex(0);
1352 }
1353
GetExecutableModulePointer()1354 Module *Target::GetExecutableModulePointer() {
1355 return GetExecutableModule().get();
1356 }
1357
LoadScriptingResourceForModule(const ModuleSP & module_sp,Target * target)1358 static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1359 Target *target) {
1360 Status error;
1361 StreamString feedback_stream;
1362 if (module_sp && !module_sp->LoadScriptingResourceInTarget(
1363 target, error, &feedback_stream)) {
1364 if (error.AsCString())
1365 target->GetDebugger().GetErrorStream().Printf(
1366 "unable to load scripting data for module %s - error reported was "
1367 "%s\n",
1368 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1369 error.AsCString());
1370 }
1371 if (feedback_stream.GetSize())
1372 target->GetDebugger().GetErrorStream().Printf("%s\n",
1373 feedback_stream.GetData());
1374 }
1375
ClearModules(bool delete_locations)1376 void Target::ClearModules(bool delete_locations) {
1377 ModulesDidUnload(m_images, delete_locations);
1378 m_section_load_history.Clear();
1379 m_images.Clear();
1380 m_scratch_type_system_map.Clear();
1381 m_ast_importer_sp.reset();
1382 }
1383
DidExec()1384 void Target::DidExec() {
1385 // When a process exec's we need to know about it so we can do some cleanup.
1386 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1387 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1388 }
1389
SetExecutableModule(ModuleSP & executable_sp,LoadDependentFiles load_dependent_files)1390 void Target::SetExecutableModule(ModuleSP &executable_sp,
1391 LoadDependentFiles load_dependent_files) {
1392 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1393 ClearModules(false);
1394
1395 if (executable_sp) {
1396 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1397 Timer scoped_timer(func_cat,
1398 "Target::SetExecutableModule (executable = '%s')",
1399 executable_sp->GetFileSpec().GetPath().c_str());
1400
1401 const bool notify = true;
1402 m_images.Append(executable_sp,
1403 notify); // The first image is our executable file
1404
1405 // If we haven't set an architecture yet, reset our architecture based on
1406 // what we found in the executable module.
1407 if (!m_arch.GetSpec().IsValid()) {
1408 m_arch = executable_sp->GetArchitecture();
1409 LLDB_LOG(log,
1410 "setting architecture to {0} ({1}) based on executable file",
1411 m_arch.GetSpec().GetArchitectureName(),
1412 m_arch.GetSpec().GetTriple().getTriple());
1413 }
1414
1415 FileSpecList dependent_files;
1416 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1417 bool load_dependents = true;
1418 switch (load_dependent_files) {
1419 case eLoadDependentsDefault:
1420 load_dependents = executable_sp->IsExecutable();
1421 break;
1422 case eLoadDependentsYes:
1423 load_dependents = true;
1424 break;
1425 case eLoadDependentsNo:
1426 load_dependents = false;
1427 break;
1428 }
1429
1430 if (executable_objfile && load_dependents) {
1431 ModuleList added_modules;
1432 executable_objfile->GetDependentModules(dependent_files);
1433 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1434 FileSpec dependent_file_spec(dependent_files.GetFileSpecAtIndex(i));
1435 FileSpec platform_dependent_file_spec;
1436 if (m_platform_sp)
1437 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1438 platform_dependent_file_spec);
1439 else
1440 platform_dependent_file_spec = dependent_file_spec;
1441
1442 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1443 ModuleSP image_module_sp(
1444 GetOrCreateModule(module_spec, false /* notify */));
1445 if (image_module_sp) {
1446 added_modules.AppendIfNeeded(image_module_sp, false);
1447 ObjectFile *objfile = image_module_sp->GetObjectFile();
1448 if (objfile)
1449 objfile->GetDependentModules(dependent_files);
1450 }
1451 }
1452 ModulesDidLoad(added_modules);
1453 }
1454 }
1455 }
1456
SetArchitecture(const ArchSpec & arch_spec,bool set_platform)1457 bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
1458 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1459 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1460 bool replace_local_arch = true;
1461 bool compatible_local_arch = false;
1462 ArchSpec other(arch_spec);
1463
1464 // Changing the architecture might mean that the currently selected platform
1465 // isn't compatible. Set the platform correctly if we are asked to do so,
1466 // otherwise assume the user will set the platform manually.
1467 if (set_platform) {
1468 if (other.IsValid()) {
1469 auto platform_sp = GetPlatform();
1470 if (!platform_sp ||
1471 !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1472 ArchSpec platform_arch;
1473 auto arch_platform_sp =
1474 Platform::GetPlatformForArchitecture(other, &platform_arch);
1475 if (arch_platform_sp) {
1476 SetPlatform(arch_platform_sp);
1477 if (platform_arch.IsValid())
1478 other = platform_arch;
1479 }
1480 }
1481 }
1482 }
1483
1484 if (!missing_local_arch) {
1485 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1486 other.MergeFrom(m_arch.GetSpec());
1487
1488 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1489 compatible_local_arch = true;
1490 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1491 env_changed;
1492
1493 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed,
1494 vendor_changed, os_changed,
1495 os_ver_changed, env_changed);
1496
1497 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1498 replace_local_arch = false;
1499 }
1500 }
1501 }
1502
1503 if (compatible_local_arch || missing_local_arch) {
1504 // If we haven't got a valid arch spec, or the architectures are compatible
1505 // update the architecture, unless the one we already have is more
1506 // specified
1507 if (replace_local_arch)
1508 m_arch = other;
1509 LLDB_LOG(log, "set architecture to {0} ({1})",
1510 m_arch.GetSpec().GetArchitectureName(),
1511 m_arch.GetSpec().GetTriple().getTriple());
1512 return true;
1513 }
1514
1515 // If we have an executable file, try to reset the executable to the desired
1516 // architecture
1517 LLDB_LOGF(log, "Target::SetArchitecture changing architecture to %s (%s)",
1518 arch_spec.GetArchitectureName(),
1519 arch_spec.GetTriple().getTriple().c_str());
1520 m_arch = other;
1521 ModuleSP executable_sp = GetExecutableModule();
1522
1523 ClearModules(true);
1524 // Need to do something about unsetting breakpoints.
1525
1526 if (executable_sp) {
1527 LLDB_LOGF(log,
1528 "Target::SetArchitecture Trying to select executable file "
1529 "architecture %s (%s)",
1530 arch_spec.GetArchitectureName(),
1531 arch_spec.GetTriple().getTriple().c_str());
1532 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1533 FileSpecList search_paths = GetExecutableSearchPaths();
1534 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1535 &search_paths, nullptr, nullptr);
1536
1537 if (!error.Fail() && executable_sp) {
1538 SetExecutableModule(executable_sp, eLoadDependentsYes);
1539 return true;
1540 }
1541 }
1542 return false;
1543 }
1544
MergeArchitecture(const ArchSpec & arch_spec)1545 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1546 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1547 if (arch_spec.IsValid()) {
1548 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1549 // The current target arch is compatible with "arch_spec", see if we can
1550 // improve our current architecture using bits from "arch_spec"
1551
1552 LLDB_LOGF(log,
1553 "Target::MergeArchitecture target has arch %s, merging with "
1554 "arch %s",
1555 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1556 arch_spec.GetTriple().getTriple().c_str());
1557
1558 // Merge bits from arch_spec into "merged_arch" and set our architecture
1559 ArchSpec merged_arch(m_arch.GetSpec());
1560 merged_arch.MergeFrom(arch_spec);
1561 return SetArchitecture(merged_arch);
1562 } else {
1563 // The new architecture is different, we just need to replace it
1564 return SetArchitecture(arch_spec);
1565 }
1566 }
1567 return false;
1568 }
1569
NotifyWillClearList(const ModuleList & module_list)1570 void Target::NotifyWillClearList(const ModuleList &module_list) {}
1571
NotifyModuleAdded(const ModuleList & module_list,const ModuleSP & module_sp)1572 void Target::NotifyModuleAdded(const ModuleList &module_list,
1573 const ModuleSP &module_sp) {
1574 // A module is being added to this target for the first time
1575 if (m_valid) {
1576 ModuleList my_module_list;
1577 my_module_list.Append(module_sp);
1578 ModulesDidLoad(my_module_list);
1579 }
1580 }
1581
NotifyModuleRemoved(const ModuleList & module_list,const ModuleSP & module_sp)1582 void Target::NotifyModuleRemoved(const ModuleList &module_list,
1583 const ModuleSP &module_sp) {
1584 // A module is being removed from this target.
1585 if (m_valid) {
1586 ModuleList my_module_list;
1587 my_module_list.Append(module_sp);
1588 ModulesDidUnload(my_module_list, false);
1589 }
1590 }
1591
NotifyModuleUpdated(const ModuleList & module_list,const ModuleSP & old_module_sp,const ModuleSP & new_module_sp)1592 void Target::NotifyModuleUpdated(const ModuleList &module_list,
1593 const ModuleSP &old_module_sp,
1594 const ModuleSP &new_module_sp) {
1595 // A module is replacing an already added module
1596 if (m_valid) {
1597 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1598 new_module_sp);
1599 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1600 old_module_sp, new_module_sp);
1601 }
1602 }
1603
NotifyModulesRemoved(lldb_private::ModuleList & module_list)1604 void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) {
1605 ModulesDidUnload(module_list, false);
1606 }
1607
ModulesDidLoad(ModuleList & module_list)1608 void Target::ModulesDidLoad(ModuleList &module_list) {
1609 const size_t num_images = module_list.GetSize();
1610 if (m_valid && num_images) {
1611 for (size_t idx = 0; idx < num_images; ++idx) {
1612 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1613 LoadScriptingResourceForModule(module_sp, this);
1614 }
1615 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1616 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1617 if (m_process_sp) {
1618 m_process_sp->ModulesDidLoad(module_list);
1619 }
1620 BroadcastEvent(eBroadcastBitModulesLoaded,
1621 new TargetEventData(this->shared_from_this(), module_list));
1622 }
1623 }
1624
SymbolsDidLoad(ModuleList & module_list)1625 void Target::SymbolsDidLoad(ModuleList &module_list) {
1626 if (m_valid && module_list.GetSize()) {
1627 if (m_process_sp) {
1628 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1629 runtime->SymbolsDidLoad(module_list);
1630 }
1631 }
1632
1633 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1634 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1635 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1636 new TargetEventData(this->shared_from_this(), module_list));
1637 }
1638 }
1639
ModulesDidUnload(ModuleList & module_list,bool delete_locations)1640 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1641 if (m_valid && module_list.GetSize()) {
1642 UnloadModuleSections(module_list);
1643 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1644 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1645 delete_locations);
1646 BroadcastEvent(eBroadcastBitModulesUnloaded,
1647 new TargetEventData(this->shared_from_this(), module_list));
1648 }
1649 }
1650
ModuleIsExcludedForUnconstrainedSearches(const FileSpec & module_file_spec)1651 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1652 const FileSpec &module_file_spec) {
1653 if (GetBreakpointsConsultPlatformAvoidList()) {
1654 ModuleList matchingModules;
1655 ModuleSpec module_spec(module_file_spec);
1656 GetImages().FindModules(module_spec, matchingModules);
1657 size_t num_modules = matchingModules.GetSize();
1658
1659 // If there is more than one module for this file spec, only
1660 // return true if ALL the modules are on the black list.
1661 if (num_modules > 0) {
1662 for (size_t i = 0; i < num_modules; i++) {
1663 if (!ModuleIsExcludedForUnconstrainedSearches(
1664 matchingModules.GetModuleAtIndex(i)))
1665 return false;
1666 }
1667 return true;
1668 }
1669 }
1670 return false;
1671 }
1672
ModuleIsExcludedForUnconstrainedSearches(const lldb::ModuleSP & module_sp)1673 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1674 const lldb::ModuleSP &module_sp) {
1675 if (GetBreakpointsConsultPlatformAvoidList()) {
1676 if (m_platform_sp)
1677 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1678 module_sp);
1679 }
1680 return false;
1681 }
1682
ReadMemoryFromFileCache(const Address & addr,void * dst,size_t dst_len,Status & error)1683 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1684 size_t dst_len, Status &error) {
1685 SectionSP section_sp(addr.GetSection());
1686 if (section_sp) {
1687 // If the contents of this section are encrypted, the on-disk file is
1688 // unusable. Read only from live memory.
1689 if (section_sp->IsEncrypted()) {
1690 error.SetErrorString("section is encrypted");
1691 return 0;
1692 }
1693 ModuleSP module_sp(section_sp->GetModule());
1694 if (module_sp) {
1695 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1696 if (objfile) {
1697 size_t bytes_read = objfile->ReadSectionData(
1698 section_sp.get(), addr.GetOffset(), dst, dst_len);
1699 if (bytes_read > 0)
1700 return bytes_read;
1701 else
1702 error.SetErrorStringWithFormat("error reading data from section %s",
1703 section_sp->GetName().GetCString());
1704 } else
1705 error.SetErrorString("address isn't from a object file");
1706 } else
1707 error.SetErrorString("address isn't in a module");
1708 } else
1709 error.SetErrorString("address doesn't contain a section that points to a "
1710 "section in a object file");
1711
1712 return 0;
1713 }
1714
ReadMemory(const Address & addr,bool prefer_file_cache,void * dst,size_t dst_len,Status & error,lldb::addr_t * load_addr_ptr)1715 size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1716 void *dst, size_t dst_len, Status &error,
1717 lldb::addr_t *load_addr_ptr) {
1718 error.Clear();
1719
1720 // if we end up reading this from process memory, we will fill this with the
1721 // actual load address
1722 if (load_addr_ptr)
1723 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1724
1725 size_t bytes_read = 0;
1726
1727 addr_t load_addr = LLDB_INVALID_ADDRESS;
1728 addr_t file_addr = LLDB_INVALID_ADDRESS;
1729 Address resolved_addr;
1730 if (!addr.IsSectionOffset()) {
1731 SectionLoadList §ion_load_list = GetSectionLoadList();
1732 if (section_load_list.IsEmpty()) {
1733 // No sections are loaded, so we must assume we are not running yet and
1734 // anything we are given is a file address.
1735 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1736 // offset is the file address
1737 m_images.ResolveFileAddress(file_addr, resolved_addr);
1738 } else {
1739 // We have at least one section loaded. This can be because we have
1740 // manually loaded some sections with "target modules load ..." or
1741 // because we have have a live process that has sections loaded through
1742 // the dynamic loader
1743 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1744 // offset is the load address
1745 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1746 }
1747 }
1748 if (!resolved_addr.IsValid())
1749 resolved_addr = addr;
1750
1751 if (prefer_file_cache) {
1752 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1753 if (bytes_read > 0)
1754 return bytes_read;
1755 }
1756
1757 if (ProcessIsValid()) {
1758 if (load_addr == LLDB_INVALID_ADDRESS)
1759 load_addr = resolved_addr.GetLoadAddress(this);
1760
1761 if (load_addr == LLDB_INVALID_ADDRESS) {
1762 ModuleSP addr_module_sp(resolved_addr.GetModule());
1763 if (addr_module_sp && addr_module_sp->GetFileSpec())
1764 error.SetErrorStringWithFormatv(
1765 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1766 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1767 else
1768 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1769 resolved_addr.GetFileAddress());
1770 } else {
1771 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1772 if (bytes_read != dst_len) {
1773 if (error.Success()) {
1774 if (bytes_read == 0)
1775 error.SetErrorStringWithFormat(
1776 "read memory from 0x%" PRIx64 " failed", load_addr);
1777 else
1778 error.SetErrorStringWithFormat(
1779 "only %" PRIu64 " of %" PRIu64
1780 " bytes were read from memory at 0x%" PRIx64,
1781 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1782 }
1783 }
1784 if (bytes_read) {
1785 if (load_addr_ptr)
1786 *load_addr_ptr = load_addr;
1787 return bytes_read;
1788 }
1789 // If the address is not section offset we have an address that doesn't
1790 // resolve to any address in any currently loaded shared libraries and we
1791 // failed to read memory so there isn't anything more we can do. If it is
1792 // section offset, we might be able to read cached memory from the object
1793 // file.
1794 if (!resolved_addr.IsSectionOffset())
1795 return 0;
1796 }
1797 }
1798
1799 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1800 // If we didn't already try and read from the object file cache, then try
1801 // it after failing to read from the process.
1802 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1803 }
1804 return 0;
1805 }
1806
ReadCStringFromMemory(const Address & addr,std::string & out_str,Status & error)1807 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1808 Status &error) {
1809 char buf[256];
1810 out_str.clear();
1811 addr_t curr_addr = addr.GetLoadAddress(this);
1812 Address address(addr);
1813 while (true) {
1814 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1815 if (length == 0)
1816 break;
1817 out_str.append(buf, length);
1818 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1819 // to read some more characters
1820 if (length == sizeof(buf) - 1)
1821 curr_addr += length;
1822 else
1823 break;
1824 address = Address(curr_addr);
1825 }
1826 return out_str.size();
1827 }
1828
ReadCStringFromMemory(const Address & addr,char * dst,size_t dst_max_len,Status & result_error)1829 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1830 size_t dst_max_len, Status &result_error) {
1831 size_t total_cstr_len = 0;
1832 if (dst && dst_max_len) {
1833 result_error.Clear();
1834 // NULL out everything just to be safe
1835 memset(dst, 0, dst_max_len);
1836 Status error;
1837 addr_t curr_addr = addr.GetLoadAddress(this);
1838 Address address(addr);
1839
1840 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1841 // this really needs to be tied to the memory cache subsystem's cache line
1842 // size, so leave this as a fixed constant.
1843 const size_t cache_line_size = 512;
1844
1845 size_t bytes_left = dst_max_len - 1;
1846 char *curr_dst = dst;
1847
1848 while (bytes_left > 0) {
1849 addr_t cache_line_bytes_left =
1850 cache_line_size - (curr_addr % cache_line_size);
1851 addr_t bytes_to_read =
1852 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1853 size_t bytes_read =
1854 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1855
1856 if (bytes_read == 0) {
1857 result_error = error;
1858 dst[total_cstr_len] = '\0';
1859 break;
1860 }
1861 const size_t len = strlen(curr_dst);
1862
1863 total_cstr_len += len;
1864
1865 if (len < bytes_to_read)
1866 break;
1867
1868 curr_dst += bytes_read;
1869 curr_addr += bytes_read;
1870 bytes_left -= bytes_read;
1871 address = Address(curr_addr);
1872 }
1873 } else {
1874 if (dst == nullptr)
1875 result_error.SetErrorString("invalid arguments");
1876 else
1877 result_error.Clear();
1878 }
1879 return total_cstr_len;
1880 }
1881
ReadScalarIntegerFromMemory(const Address & addr,bool prefer_file_cache,uint32_t byte_size,bool is_signed,Scalar & scalar,Status & error)1882 size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1883 bool prefer_file_cache,
1884 uint32_t byte_size, bool is_signed,
1885 Scalar &scalar, Status &error) {
1886 uint64_t uval;
1887
1888 if (byte_size <= sizeof(uval)) {
1889 size_t bytes_read =
1890 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1891 if (bytes_read == byte_size) {
1892 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1893 m_arch.GetSpec().GetAddressByteSize());
1894 lldb::offset_t offset = 0;
1895 if (byte_size <= 4)
1896 scalar = data.GetMaxU32(&offset, byte_size);
1897 else
1898 scalar = data.GetMaxU64(&offset, byte_size);
1899
1900 if (is_signed)
1901 scalar.SignExtend(byte_size * 8);
1902 return bytes_read;
1903 }
1904 } else {
1905 error.SetErrorStringWithFormat(
1906 "byte size of %u is too large for integer scalar type", byte_size);
1907 }
1908 return 0;
1909 }
1910
ReadUnsignedIntegerFromMemory(const Address & addr,bool prefer_file_cache,size_t integer_byte_size,uint64_t fail_value,Status & error)1911 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1912 bool prefer_file_cache,
1913 size_t integer_byte_size,
1914 uint64_t fail_value,
1915 Status &error) {
1916 Scalar scalar;
1917 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1918 false, scalar, error))
1919 return scalar.ULongLong(fail_value);
1920 return fail_value;
1921 }
1922
ReadPointerFromMemory(const Address & addr,bool prefer_file_cache,Status & error,Address & pointer_addr)1923 bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1924 Status &error, Address &pointer_addr) {
1925 Scalar scalar;
1926 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1927 m_arch.GetSpec().GetAddressByteSize(), false,
1928 scalar, error)) {
1929 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1930 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1931 SectionLoadList §ion_load_list = GetSectionLoadList();
1932 if (section_load_list.IsEmpty()) {
1933 // No sections are loaded, so we must assume we are not running yet and
1934 // anything we are given is a file address.
1935 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1936 } else {
1937 // We have at least one section loaded. This can be because we have
1938 // manually loaded some sections with "target modules load ..." or
1939 // because we have have a live process that has sections loaded through
1940 // the dynamic loader
1941 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1942 }
1943 // We weren't able to resolve the pointer value, so just return an
1944 // address with no section
1945 if (!pointer_addr.IsValid())
1946 pointer_addr.SetOffset(pointer_vm_addr);
1947 return true;
1948 }
1949 }
1950 return false;
1951 }
1952
GetOrCreateModule(const ModuleSpec & module_spec,bool notify,Status * error_ptr)1953 ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
1954 Status *error_ptr) {
1955 ModuleSP module_sp;
1956
1957 Status error;
1958
1959 // First see if we already have this module in our module list. If we do,
1960 // then we're done, we don't need to consult the shared modules list. But
1961 // only do this if we are passed a UUID.
1962
1963 if (module_spec.GetUUID().IsValid())
1964 module_sp = m_images.FindFirstModule(module_spec);
1965
1966 if (!module_sp) {
1967 ModuleSP old_module_sp; // This will get filled in if we have a new version
1968 // of the library
1969 bool did_create_module = false;
1970 FileSpecList search_paths = GetExecutableSearchPaths();
1971 // If there are image search path entries, try to use them first to acquire
1972 // a suitable image.
1973 if (m_image_search_paths.GetSize()) {
1974 ModuleSpec transformed_spec(module_spec);
1975 if (m_image_search_paths.RemapPath(
1976 module_spec.GetFileSpec().GetDirectory(),
1977 transformed_spec.GetFileSpec().GetDirectory())) {
1978 transformed_spec.GetFileSpec().GetFilename() =
1979 module_spec.GetFileSpec().GetFilename();
1980 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1981 &search_paths, &old_module_sp,
1982 &did_create_module);
1983 }
1984 }
1985
1986 if (!module_sp) {
1987 // If we have a UUID, we can check our global shared module list in case
1988 // we already have it. If we don't have a valid UUID, then we can't since
1989 // the path in "module_spec" will be a platform path, and we will need to
1990 // let the platform find that file. For example, we could be asking for
1991 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1992 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1993 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1994 // cache.
1995 if (module_spec.GetUUID().IsValid()) {
1996 // We have a UUID, it is OK to check the global module list...
1997 error =
1998 ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
1999 &old_module_sp, &did_create_module);
2000 }
2001
2002 if (!module_sp) {
2003 // The platform is responsible for finding and caching an appropriate
2004 // module in the shared module cache.
2005 if (m_platform_sp) {
2006 error = m_platform_sp->GetSharedModule(
2007 module_spec, m_process_sp.get(), module_sp, &search_paths,
2008 &old_module_sp, &did_create_module);
2009 } else {
2010 error.SetErrorString("no platform is currently set");
2011 }
2012 }
2013 }
2014
2015 // We found a module that wasn't in our target list. Let's make sure that
2016 // there wasn't an equivalent module in the list already, and if there was,
2017 // let's remove it.
2018 if (module_sp) {
2019 ObjectFile *objfile = module_sp->GetObjectFile();
2020 if (objfile) {
2021 switch (objfile->GetType()) {
2022 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2023 /// a program's execution state
2024 case ObjectFile::eTypeExecutable: /// A normal executable
2025 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2026 /// executable
2027 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2028 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2029 /// used during execution
2030 break;
2031 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2032 /// debug information
2033 if (error_ptr)
2034 error_ptr->SetErrorString("debug info files aren't valid target "
2035 "modules, please specify an executable");
2036 return ModuleSP();
2037 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2038 /// against but not used for
2039 /// execution
2040 if (error_ptr)
2041 error_ptr->SetErrorString("stub libraries aren't valid target "
2042 "modules, please specify an executable");
2043 return ModuleSP();
2044 default:
2045 if (error_ptr)
2046 error_ptr->SetErrorString(
2047 "unsupported file type, please specify an executable");
2048 return ModuleSP();
2049 }
2050 // GetSharedModule is not guaranteed to find the old shared module, for
2051 // instance in the common case where you pass in the UUID, it is only
2052 // going to find the one module matching the UUID. In fact, it has no
2053 // good way to know what the "old module" relevant to this target is,
2054 // since there might be many copies of a module with this file spec in
2055 // various running debug sessions, but only one of them will belong to
2056 // this target. So let's remove the UUID from the module list, and look
2057 // in the target's module list. Only do this if there is SOMETHING else
2058 // in the module spec...
2059 if (!old_module_sp) {
2060 if (module_spec.GetUUID().IsValid() &&
2061 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2062 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2063 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2064 module_spec_copy.GetUUID().Clear();
2065
2066 ModuleList found_modules;
2067 m_images.FindModules(module_spec_copy, found_modules);
2068 if (found_modules.GetSize() == 1)
2069 old_module_sp = found_modules.GetModuleAtIndex(0);
2070 }
2071 }
2072
2073 // Preload symbols outside of any lock, so hopefully we can do this for
2074 // each library in parallel.
2075 if (GetPreloadSymbols())
2076 module_sp->PreloadSymbols();
2077
2078 if (old_module_sp && m_images.GetIndexForModule(old_module_sp.get()) !=
2079 LLDB_INVALID_INDEX32) {
2080 m_images.ReplaceModule(old_module_sp, module_sp);
2081 Module *old_module_ptr = old_module_sp.get();
2082 old_module_sp.reset();
2083 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2084 } else {
2085 m_images.Append(module_sp, notify);
2086 }
2087 } else
2088 module_sp.reset();
2089 }
2090 }
2091 if (error_ptr)
2092 *error_ptr = error;
2093 return module_sp;
2094 }
2095
CalculateTarget()2096 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2097
CalculateProcess()2098 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2099
CalculateThread()2100 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2101
CalculateStackFrame()2102 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2103
CalculateExecutionContext(ExecutionContext & exe_ctx)2104 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2105 exe_ctx.Clear();
2106 exe_ctx.SetTargetPtr(this);
2107 }
2108
GetImageSearchPathList()2109 PathMappingList &Target::GetImageSearchPathList() {
2110 return m_image_search_paths;
2111 }
2112
ImageSearchPathsChanged(const PathMappingList & path_list,void * baton)2113 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2114 void *baton) {
2115 Target *target = (Target *)baton;
2116 ModuleSP exe_module_sp(target->GetExecutableModule());
2117 if (exe_module_sp)
2118 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2119 }
2120
2121 llvm::Expected<TypeSystem &>
GetScratchTypeSystemForLanguage(lldb::LanguageType language,bool create_on_demand)2122 Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2123 bool create_on_demand) {
2124 if (!m_valid)
2125 return llvm::make_error<llvm::StringError>("Invalid Target",
2126 llvm::inconvertibleErrorCode());
2127
2128 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2129 // assembly code
2130 || language == eLanguageTypeUnknown) {
2131 LanguageSet languages_for_expressions =
2132 Language::GetLanguagesSupportingTypeSystemsForExpressions();
2133
2134 if (languages_for_expressions[eLanguageTypeC]) {
2135 language = eLanguageTypeC; // LLDB's default. Override by setting the
2136 // target language.
2137 } else {
2138 if (languages_for_expressions.Empty())
2139 return llvm::make_error<llvm::StringError>(
2140 "No expression support for any languages",
2141 llvm::inconvertibleErrorCode());
2142 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2143 }
2144 }
2145
2146 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2147 create_on_demand);
2148 }
2149
GetScratchTypeSystems(bool create_on_demand)2150 std::vector<TypeSystem *> Target::GetScratchTypeSystems(bool create_on_demand) {
2151 if (!m_valid)
2152 return {};
2153
2154 std::vector<TypeSystem *> scratch_type_systems;
2155
2156 LanguageSet languages_for_expressions =
2157 Language::GetLanguagesSupportingTypeSystemsForExpressions();
2158
2159 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2160 auto language = (LanguageType)bit;
2161 auto type_system_or_err =
2162 GetScratchTypeSystemForLanguage(language, create_on_demand);
2163 if (!type_system_or_err)
2164 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2165 type_system_or_err.takeError(),
2166 "Language '{}' has expression support but no scratch type "
2167 "system available",
2168 Language::GetNameForLanguageType(language));
2169 else
2170 scratch_type_systems.emplace_back(&type_system_or_err.get());
2171 }
2172
2173 return scratch_type_systems;
2174 }
2175
2176 PersistentExpressionState *
GetPersistentExpressionStateForLanguage(lldb::LanguageType language)2177 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2178 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2179
2180 if (auto err = type_system_or_err.takeError()) {
2181 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2182 std::move(err),
2183 "Unable to get persistent expression state for language {}",
2184 Language::GetNameForLanguageType(language));
2185 return nullptr;
2186 }
2187
2188 return type_system_or_err->GetPersistentExpressionState();
2189 }
2190
GetUserExpressionForLanguage(llvm::StringRef expr,llvm::StringRef prefix,lldb::LanguageType language,Expression::ResultType desired_type,const EvaluateExpressionOptions & options,ValueObject * ctx_obj,Status & error)2191 UserExpression *Target::GetUserExpressionForLanguage(
2192 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2193 Expression::ResultType desired_type,
2194 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2195 Status &error) {
2196 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2197 if (auto err = type_system_or_err.takeError()) {
2198 error.SetErrorStringWithFormat(
2199 "Could not find type system for language %s: %s",
2200 Language::GetNameForLanguageType(language),
2201 llvm::toString(std::move(err)).c_str());
2202 return nullptr;
2203 }
2204
2205 auto *user_expr = type_system_or_err->GetUserExpression(
2206 expr, prefix, language, desired_type, options, ctx_obj);
2207 if (!user_expr)
2208 error.SetErrorStringWithFormat(
2209 "Could not create an expression for language %s",
2210 Language::GetNameForLanguageType(language));
2211
2212 return user_expr;
2213 }
2214
GetFunctionCallerForLanguage(lldb::LanguageType language,const CompilerType & return_type,const Address & function_address,const ValueList & arg_value_list,const char * name,Status & error)2215 FunctionCaller *Target::GetFunctionCallerForLanguage(
2216 lldb::LanguageType language, const CompilerType &return_type,
2217 const Address &function_address, const ValueList &arg_value_list,
2218 const char *name, Status &error) {
2219 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2220 if (auto err = type_system_or_err.takeError()) {
2221 error.SetErrorStringWithFormat(
2222 "Could not find type system for language %s: %s",
2223 Language::GetNameForLanguageType(language),
2224 llvm::toString(std::move(err)).c_str());
2225 return nullptr;
2226 }
2227
2228 auto *persistent_fn = type_system_or_err->GetFunctionCaller(
2229 return_type, function_address, arg_value_list, name);
2230 if (!persistent_fn)
2231 error.SetErrorStringWithFormat(
2232 "Could not create an expression for language %s",
2233 Language::GetNameForLanguageType(language));
2234
2235 return persistent_fn;
2236 }
2237
2238 UtilityFunction *
GetUtilityFunctionForLanguage(const char * text,lldb::LanguageType language,const char * name,Status & error)2239 Target::GetUtilityFunctionForLanguage(const char *text,
2240 lldb::LanguageType language,
2241 const char *name, Status &error) {
2242 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2243
2244 if (auto err = type_system_or_err.takeError()) {
2245 error.SetErrorStringWithFormat(
2246 "Could not find type system for language %s: %s",
2247 Language::GetNameForLanguageType(language),
2248 llvm::toString(std::move(err)).c_str());
2249 return nullptr;
2250 }
2251
2252 auto *utility_fn = type_system_or_err->GetUtilityFunction(text, name);
2253 if (!utility_fn)
2254 error.SetErrorStringWithFormat(
2255 "Could not create an expression for language %s",
2256 Language::GetNameForLanguageType(language));
2257
2258 return utility_fn;
2259 }
2260
GetClangASTImporter()2261 ClangASTImporterSP Target::GetClangASTImporter() {
2262 if (m_valid) {
2263 if (!m_ast_importer_sp) {
2264 m_ast_importer_sp = std::make_shared<ClangASTImporter>();
2265 }
2266 return m_ast_importer_sp;
2267 }
2268 return ClangASTImporterSP();
2269 }
2270
SettingsInitialize()2271 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2272
SettingsTerminate()2273 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2274
GetDefaultExecutableSearchPaths()2275 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2276 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2277 if (properties_sp)
2278 return properties_sp->GetExecutableSearchPaths();
2279 return FileSpecList();
2280 }
2281
GetDefaultDebugFileSearchPaths()2282 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2283 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2284 if (properties_sp)
2285 return properties_sp->GetDebugFileSearchPaths();
2286 return FileSpecList();
2287 }
2288
GetDefaultArchitecture()2289 ArchSpec Target::GetDefaultArchitecture() {
2290 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2291 if (properties_sp)
2292 return properties_sp->GetDefaultArchitecture();
2293 return ArchSpec();
2294 }
2295
SetDefaultArchitecture(const ArchSpec & arch)2296 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2297 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2298 if (properties_sp) {
2299 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
2300 "Target::SetDefaultArchitecture setting target's "
2301 "default architecture to {0} ({1})",
2302 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2303 return properties_sp->SetDefaultArchitecture(arch);
2304 }
2305 }
2306
GetTargetFromContexts(const ExecutionContext * exe_ctx_ptr,const SymbolContext * sc_ptr)2307 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2308 const SymbolContext *sc_ptr) {
2309 // The target can either exist in the "process" of ExecutionContext, or in
2310 // the "target_sp" member of SymbolContext. This accessor helper function
2311 // will get the target from one of these locations.
2312
2313 Target *target = nullptr;
2314 if (sc_ptr != nullptr)
2315 target = sc_ptr->target_sp.get();
2316 if (target == nullptr && exe_ctx_ptr)
2317 target = exe_ctx_ptr->GetTargetPtr();
2318 return target;
2319 }
2320
EvaluateExpression(llvm::StringRef expr,ExecutionContextScope * exe_scope,lldb::ValueObjectSP & result_valobj_sp,const EvaluateExpressionOptions & options,std::string * fixed_expression,ValueObject * ctx_obj)2321 ExpressionResults Target::EvaluateExpression(
2322 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2323 lldb::ValueObjectSP &result_valobj_sp,
2324 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2325 ValueObject *ctx_obj) {
2326 result_valobj_sp.reset();
2327
2328 ExpressionResults execution_results = eExpressionSetupError;
2329
2330 if (expr.empty())
2331 return execution_results;
2332
2333 // We shouldn't run stop hooks in expressions.
2334 bool old_suppress_value = m_suppress_stop_hooks;
2335 m_suppress_stop_hooks = true;
2336 auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2337 m_suppress_stop_hooks = old_suppress_value;
2338 });
2339
2340 ExecutionContext exe_ctx;
2341
2342 if (exe_scope) {
2343 exe_scope->CalculateExecutionContext(exe_ctx);
2344 } else if (m_process_sp) {
2345 m_process_sp->CalculateExecutionContext(exe_ctx);
2346 } else {
2347 CalculateExecutionContext(exe_ctx);
2348 }
2349
2350 // Make sure we aren't just trying to see the value of a persistent variable
2351 // (something like "$0")
2352 // Only check for persistent variables the expression starts with a '$'
2353 lldb::ExpressionVariableSP persistent_var_sp;
2354 if (expr[0] == '$') {
2355 auto type_system_or_err =
2356 GetScratchTypeSystemForLanguage(eLanguageTypeC);
2357 if (auto err = type_system_or_err.takeError()) {
2358 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2359 std::move(err), "Unable to get scratch type system");
2360 } else {
2361 persistent_var_sp =
2362 type_system_or_err->GetPersistentExpressionState()->GetVariable(expr);
2363 }
2364 }
2365 if (persistent_var_sp) {
2366 result_valobj_sp = persistent_var_sp->GetValueObject();
2367 execution_results = eExpressionCompleted;
2368 } else {
2369 llvm::StringRef prefix = GetExpressionPrefixContents();
2370 Status error;
2371 execution_results =
2372 UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2373 result_valobj_sp, error, fixed_expression,
2374 nullptr, // Module
2375 ctx_obj);
2376 }
2377
2378 return execution_results;
2379 }
2380
GetPersistentVariable(ConstString name)2381 lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2382 lldb::ExpressionVariableSP variable_sp;
2383 m_scratch_type_system_map.ForEach(
2384 [name, &variable_sp](TypeSystem *type_system) -> bool {
2385 if (PersistentExpressionState *persistent_state =
2386 type_system->GetPersistentExpressionState()) {
2387 variable_sp = persistent_state->GetVariable(name);
2388
2389 if (variable_sp)
2390 return false; // Stop iterating the ForEach
2391 }
2392 return true; // Keep iterating the ForEach
2393 });
2394 return variable_sp;
2395 }
2396
GetPersistentSymbol(ConstString name)2397 lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2398 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2399
2400 m_scratch_type_system_map.ForEach(
2401 [name, &address](TypeSystem *type_system) -> bool {
2402 if (PersistentExpressionState *persistent_state =
2403 type_system->GetPersistentExpressionState()) {
2404 address = persistent_state->LookupSymbol(name);
2405 if (address != LLDB_INVALID_ADDRESS)
2406 return false; // Stop iterating the ForEach
2407 }
2408 return true; // Keep iterating the ForEach
2409 });
2410 return address;
2411 }
2412
GetEntryPointAddress()2413 llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2414 Module *exe_module = GetExecutableModulePointer();
2415
2416 // Try to find the entry point address in the primary executable.
2417 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2418 if (has_primary_executable) {
2419 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2420 if (entry_addr.IsValid())
2421 return entry_addr;
2422 }
2423
2424 const ModuleList &modules = GetImages();
2425 const size_t num_images = modules.GetSize();
2426 for (size_t idx = 0; idx < num_images; ++idx) {
2427 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2428 if (!module_sp || !module_sp->GetObjectFile())
2429 continue;
2430
2431 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2432 if (entry_addr.IsValid())
2433 return entry_addr;
2434 }
2435
2436 // We haven't found the entry point address. Return an appropriate error.
2437 if (!has_primary_executable)
2438 return llvm::make_error<llvm::StringError>(
2439 "No primary executable found and could not find entry point address in "
2440 "any executable module",
2441 llvm::inconvertibleErrorCode());
2442
2443 return llvm::make_error<llvm::StringError>(
2444 "Could not find entry point address for primary executable module \"" +
2445 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2446 llvm::inconvertibleErrorCode());
2447 }
2448
GetCallableLoadAddress(lldb::addr_t load_addr,AddressClass addr_class) const2449 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2450 AddressClass addr_class) const {
2451 auto arch_plugin = GetArchitecturePlugin();
2452 return arch_plugin
2453 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2454 : load_addr;
2455 }
2456
GetOpcodeLoadAddress(lldb::addr_t load_addr,AddressClass addr_class) const2457 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2458 AddressClass addr_class) const {
2459 auto arch_plugin = GetArchitecturePlugin();
2460 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2461 : load_addr;
2462 }
2463
GetBreakableLoadAddress(lldb::addr_t addr)2464 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2465 auto arch_plugin = GetArchitecturePlugin();
2466 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2467 }
2468
GetSourceManager()2469 SourceManager &Target::GetSourceManager() {
2470 if (!m_source_manager_up)
2471 m_source_manager_up.reset(new SourceManager(shared_from_this()));
2472 return *m_source_manager_up;
2473 }
2474
GetClangModulesDeclVendor()2475 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2476 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2477 // we can make it
2478 // per-target
2479
2480 {
2481 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2482
2483 if (!m_clang_modules_decl_vendor_up) {
2484 m_clang_modules_decl_vendor_up.reset(
2485 ClangModulesDeclVendor::Create(*this));
2486 }
2487 }
2488
2489 return m_clang_modules_decl_vendor_up.get();
2490 }
2491
CreateStopHook()2492 Target::StopHookSP Target::CreateStopHook() {
2493 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2494 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2495 m_stop_hooks[new_uid] = stop_hook_sp;
2496 return stop_hook_sp;
2497 }
2498
RemoveStopHookByID(lldb::user_id_t user_id)2499 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2500 size_t num_removed = m_stop_hooks.erase(user_id);
2501 return (num_removed != 0);
2502 }
2503
RemoveAllStopHooks()2504 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2505
GetStopHookByID(lldb::user_id_t user_id)2506 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2507 StopHookSP found_hook;
2508
2509 StopHookCollection::iterator specified_hook_iter;
2510 specified_hook_iter = m_stop_hooks.find(user_id);
2511 if (specified_hook_iter != m_stop_hooks.end())
2512 found_hook = (*specified_hook_iter).second;
2513 return found_hook;
2514 }
2515
SetStopHookActiveStateByID(lldb::user_id_t user_id,bool active_state)2516 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2517 bool active_state) {
2518 StopHookCollection::iterator specified_hook_iter;
2519 specified_hook_iter = m_stop_hooks.find(user_id);
2520 if (specified_hook_iter == m_stop_hooks.end())
2521 return false;
2522
2523 (*specified_hook_iter).second->SetIsActive(active_state);
2524 return true;
2525 }
2526
SetAllStopHooksActiveState(bool active_state)2527 void Target::SetAllStopHooksActiveState(bool active_state) {
2528 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2529 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2530 (*pos).second->SetIsActive(active_state);
2531 }
2532 }
2533
RunStopHooks()2534 void Target::RunStopHooks() {
2535 if (m_suppress_stop_hooks)
2536 return;
2537
2538 if (!m_process_sp)
2539 return;
2540
2541 // Somebody might have restarted the process:
2542 if (m_process_sp->GetState() != eStateStopped)
2543 return;
2544
2545 // <rdar://problem/12027563> make sure we check that we are not stopped
2546 // because of us running a user expression since in that case we do not want
2547 // to run the stop-hooks
2548 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2549 return;
2550
2551 if (m_stop_hooks.empty())
2552 return;
2553
2554 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2555
2556 // If there aren't any active stop hooks, don't bother either.
2557 // Also see if any of the active hooks want to auto-continue.
2558 bool any_active_hooks = false;
2559 bool auto_continue = false;
2560 for (auto hook : m_stop_hooks) {
2561 if (hook.second->IsActive()) {
2562 any_active_hooks = true;
2563 auto_continue |= hook.second->GetAutoContinue();
2564 }
2565 }
2566 if (!any_active_hooks)
2567 return;
2568
2569 CommandReturnObject result;
2570
2571 std::vector<ExecutionContext> exc_ctx_with_reasons;
2572 std::vector<SymbolContext> sym_ctx_with_reasons;
2573
2574 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2575 size_t num_threads = cur_threadlist.GetSize();
2576 for (size_t i = 0; i < num_threads; i++) {
2577 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2578 if (cur_thread_sp->ThreadStoppedForAReason()) {
2579 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2580 exc_ctx_with_reasons.push_back(ExecutionContext(
2581 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2582 sym_ctx_with_reasons.push_back(
2583 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2584 }
2585 }
2586
2587 // If no threads stopped for a reason, don't run the stop-hooks.
2588 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2589 if (num_exe_ctx == 0)
2590 return;
2591
2592 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2593 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2594
2595 bool keep_going = true;
2596 bool hooks_ran = false;
2597 bool print_hook_header = (m_stop_hooks.size() != 1);
2598 bool print_thread_header = (num_exe_ctx != 1);
2599 bool did_restart = false;
2600
2601 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2602 // result.Clear();
2603 StopHookSP cur_hook_sp = (*pos).second;
2604 if (!cur_hook_sp->IsActive())
2605 continue;
2606
2607 bool any_thread_matched = false;
2608 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2609 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2610 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2611 sym_ctx_with_reasons[i])) &&
2612 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2613 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2614 exc_ctx_with_reasons[i].GetThreadRef()))) {
2615 if (!hooks_ran) {
2616 hooks_ran = true;
2617 }
2618 if (print_hook_header && !any_thread_matched) {
2619 const char *cmd =
2620 (cur_hook_sp->GetCommands().GetSize() == 1
2621 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2622 : nullptr);
2623 if (cmd)
2624 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2625 cur_hook_sp->GetID(), cmd);
2626 else
2627 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2628 cur_hook_sp->GetID());
2629 any_thread_matched = true;
2630 }
2631
2632 if (print_thread_header)
2633 result.AppendMessageWithFormat(
2634 "-- Thread %d\n",
2635 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2636
2637 CommandInterpreterRunOptions options;
2638 options.SetStopOnContinue(true);
2639 options.SetStopOnError(true);
2640 options.SetEchoCommands(false);
2641 options.SetPrintResults(true);
2642 options.SetPrintErrors(true);
2643 options.SetAddToHistory(false);
2644
2645 // Force Async:
2646 bool old_async = GetDebugger().GetAsyncExecution();
2647 GetDebugger().SetAsyncExecution(true);
2648 GetDebugger().GetCommandInterpreter().HandleCommands(
2649 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2650 result);
2651 GetDebugger().SetAsyncExecution(old_async);
2652 // If the command started the target going again, we should bag out of
2653 // running the stop hooks.
2654 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2655 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2656 // But only complain if there were more stop hooks to do:
2657 StopHookCollection::iterator tmp = pos;
2658 if (++tmp != end)
2659 result.AppendMessageWithFormat(
2660 "\nAborting stop hooks, hook %" PRIu64
2661 " set the program running.\n"
2662 " Consider using '-G true' to make "
2663 "stop hooks auto-continue.\n",
2664 cur_hook_sp->GetID());
2665 keep_going = false;
2666 did_restart = true;
2667 }
2668 }
2669 }
2670 }
2671 // Finally, if auto-continue was requested, do it now:
2672 if (!did_restart && auto_continue)
2673 m_process_sp->PrivateResume();
2674
2675 result.GetImmediateOutputStream()->Flush();
2676 result.GetImmediateErrorStream()->Flush();
2677 }
2678
GetGlobalProperties()2679 const TargetPropertiesSP &Target::GetGlobalProperties() {
2680 // NOTE: intentional leak so we don't crash if global destructor chain gets
2681 // called as other threads still use the result of this function
2682 static TargetPropertiesSP *g_settings_sp_ptr =
2683 new TargetPropertiesSP(new TargetProperties(nullptr));
2684 return *g_settings_sp_ptr;
2685 }
2686
Install(ProcessLaunchInfo * launch_info)2687 Status Target::Install(ProcessLaunchInfo *launch_info) {
2688 Status error;
2689 PlatformSP platform_sp(GetPlatform());
2690 if (platform_sp) {
2691 if (platform_sp->IsRemote()) {
2692 if (platform_sp->IsConnected()) {
2693 // Install all files that have an install path, and always install the
2694 // main executable when connected to a remote platform
2695 const ModuleList &modules = GetImages();
2696 const size_t num_images = modules.GetSize();
2697 for (size_t idx = 0; idx < num_images; ++idx) {
2698 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2699 if (module_sp) {
2700 const bool is_main_executable = module_sp == GetExecutableModule();
2701 FileSpec local_file(module_sp->GetFileSpec());
2702 if (local_file) {
2703 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2704 if (!remote_file) {
2705 if (is_main_executable) // TODO: add setting for always
2706 // installing main executable???
2707 {
2708 // Always install the main executable
2709 remote_file = platform_sp->GetRemoteWorkingDirectory();
2710 remote_file.AppendPathComponent(
2711 module_sp->GetFileSpec().GetFilename().GetCString());
2712 }
2713 }
2714 if (remote_file) {
2715 error = platform_sp->Install(local_file, remote_file);
2716 if (error.Success()) {
2717 module_sp->SetPlatformFileSpec(remote_file);
2718 if (is_main_executable) {
2719 platform_sp->SetFilePermissions(remote_file, 0700);
2720 if (launch_info)
2721 launch_info->SetExecutableFile(remote_file, false);
2722 }
2723 } else
2724 break;
2725 }
2726 }
2727 }
2728 }
2729 }
2730 }
2731 }
2732 return error;
2733 }
2734
ResolveLoadAddress(addr_t load_addr,Address & so_addr,uint32_t stop_id)2735 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2736 uint32_t stop_id) {
2737 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2738 }
2739
ResolveFileAddress(lldb::addr_t file_addr,Address & resolved_addr)2740 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2741 Address &resolved_addr) {
2742 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2743 }
2744
SetSectionLoadAddress(const SectionSP & section_sp,addr_t new_section_load_addr,bool warn_multiple)2745 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp,
2746 addr_t new_section_load_addr,
2747 bool warn_multiple) {
2748 const addr_t old_section_load_addr =
2749 m_section_load_history.GetSectionLoadAddress(
2750 SectionLoadHistory::eStopIDNow, section_sp);
2751 if (old_section_load_addr != new_section_load_addr) {
2752 uint32_t stop_id = 0;
2753 ProcessSP process_sp(GetProcessSP());
2754 if (process_sp)
2755 stop_id = process_sp->GetStopID();
2756 else
2757 stop_id = m_section_load_history.GetLastStopID();
2758 if (m_section_load_history.SetSectionLoadAddress(
2759 stop_id, section_sp, new_section_load_addr, warn_multiple))
2760 return true; // Return true if the section load address was changed...
2761 }
2762 return false; // Return false to indicate nothing changed
2763 }
2764
UnloadModuleSections(const ModuleList & module_list)2765 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2766 size_t section_unload_count = 0;
2767 size_t num_modules = module_list.GetSize();
2768 for (size_t i = 0; i < num_modules; ++i) {
2769 section_unload_count +=
2770 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2771 }
2772 return section_unload_count;
2773 }
2774
UnloadModuleSections(const lldb::ModuleSP & module_sp)2775 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2776 uint32_t stop_id = 0;
2777 ProcessSP process_sp(GetProcessSP());
2778 if (process_sp)
2779 stop_id = process_sp->GetStopID();
2780 else
2781 stop_id = m_section_load_history.GetLastStopID();
2782 SectionList *sections = module_sp->GetSectionList();
2783 size_t section_unload_count = 0;
2784 if (sections) {
2785 const uint32_t num_sections = sections->GetNumSections(0);
2786 for (uint32_t i = 0; i < num_sections; ++i) {
2787 section_unload_count += m_section_load_history.SetSectionUnloaded(
2788 stop_id, sections->GetSectionAtIndex(i));
2789 }
2790 }
2791 return section_unload_count;
2792 }
2793
SetSectionUnloaded(const lldb::SectionSP & section_sp)2794 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) {
2795 uint32_t stop_id = 0;
2796 ProcessSP process_sp(GetProcessSP());
2797 if (process_sp)
2798 stop_id = process_sp->GetStopID();
2799 else
2800 stop_id = m_section_load_history.GetLastStopID();
2801 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2802 }
2803
SetSectionUnloaded(const lldb::SectionSP & section_sp,addr_t load_addr)2804 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp,
2805 addr_t load_addr) {
2806 uint32_t stop_id = 0;
2807 ProcessSP process_sp(GetProcessSP());
2808 if (process_sp)
2809 stop_id = process_sp->GetStopID();
2810 else
2811 stop_id = m_section_load_history.GetLastStopID();
2812 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2813 load_addr);
2814 }
2815
ClearAllLoadedSections()2816 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2817
Launch(ProcessLaunchInfo & launch_info,Stream * stream)2818 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2819 Status error;
2820 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2821
2822 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2823 launch_info.GetExecutableFile().GetPath().c_str());
2824
2825 StateType state = eStateInvalid;
2826
2827 // Scope to temporarily get the process state in case someone has manually
2828 // remotely connected already to a process and we can skip the platform
2829 // launching.
2830 {
2831 ProcessSP process_sp(GetProcessSP());
2832
2833 if (process_sp) {
2834 state = process_sp->GetState();
2835 LLDB_LOGF(log,
2836 "Target::%s the process exists, and its current state is %s",
2837 __FUNCTION__, StateAsCString(state));
2838 } else {
2839 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2840 __FUNCTION__);
2841 }
2842 }
2843
2844 launch_info.GetFlags().Set(eLaunchFlagDebug);
2845
2846 // Get the value of synchronous execution here. If you wait till after you
2847 // have started to run, then you could have hit a breakpoint, whose command
2848 // might switch the value, and then you'll pick up that incorrect value.
2849 Debugger &debugger = GetDebugger();
2850 const bool synchronous_execution =
2851 debugger.GetCommandInterpreter().GetSynchronous();
2852
2853 PlatformSP platform_sp(GetPlatform());
2854
2855 FinalizeFileActions(launch_info);
2856
2857 if (state == eStateConnected) {
2858 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2859 error.SetErrorString(
2860 "can't launch in tty when launching through a remote connection");
2861 return error;
2862 }
2863 }
2864
2865 if (!launch_info.GetArchitecture().IsValid())
2866 launch_info.GetArchitecture() = GetArchitecture();
2867
2868 // If we're not already connected to the process, and if we have a platform
2869 // that can launch a process for debugging, go ahead and do that here.
2870 if (state != eStateConnected && platform_sp &&
2871 platform_sp->CanDebugProcess()) {
2872 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2873 __FUNCTION__);
2874
2875 // If there was a previous process, delete it before we make the new one.
2876 // One subtle point, we delete the process before we release the reference
2877 // to m_process_sp. That way even if we are the last owner, the process
2878 // will get Finalized before it gets destroyed.
2879 DeleteCurrentProcess();
2880
2881 m_process_sp =
2882 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2883
2884 } else {
2885 LLDB_LOGF(log,
2886 "Target::%s the platform doesn't know how to debug a "
2887 "process, getting a process plugin to do this for us.",
2888 __FUNCTION__);
2889
2890 if (state == eStateConnected) {
2891 assert(m_process_sp);
2892 } else {
2893 // Use a Process plugin to construct the process.
2894 const char *plugin_name = launch_info.GetProcessPluginName();
2895 CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2896 }
2897
2898 // Since we didn't have a platform launch the process, launch it here.
2899 if (m_process_sp)
2900 error = m_process_sp->Launch(launch_info);
2901 }
2902
2903 if (!m_process_sp) {
2904 if (error.Success())
2905 error.SetErrorString("failed to launch or debug process");
2906 return error;
2907 }
2908
2909 if (error.Success()) {
2910 if (synchronous_execution ||
2911 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2912 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2913 if (!hijack_listener_sp) {
2914 hijack_listener_sp =
2915 Listener::MakeListener("lldb.Target.Launch.hijack");
2916 launch_info.SetHijackListener(hijack_listener_sp);
2917 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2918 }
2919
2920 StateType state = m_process_sp->WaitForProcessToStop(
2921 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
2922
2923 if (state == eStateStopped) {
2924 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2925 if (synchronous_execution) {
2926 // Now we have handled the stop-from-attach, and we are just
2927 // switching to a synchronous resume. So we should switch to the
2928 // SyncResume hijacker.
2929 m_process_sp->RestoreProcessEvents();
2930 m_process_sp->ResumeSynchronous(stream);
2931 } else {
2932 m_process_sp->RestoreProcessEvents();
2933 error = m_process_sp->PrivateResume();
2934 }
2935 if (!error.Success()) {
2936 Status error2;
2937 error2.SetErrorStringWithFormat(
2938 "process resume at entry point failed: %s", error.AsCString());
2939 error = error2;
2940 }
2941 }
2942 } else if (state == eStateExited) {
2943 bool with_shell = !!launch_info.GetShell();
2944 const int exit_status = m_process_sp->GetExitStatus();
2945 const char *exit_desc = m_process_sp->GetExitDescription();
2946 #define LAUNCH_SHELL_MESSAGE \
2947 "\n'r' and 'run' are aliases that default to launching through a " \
2948 "shell.\nTry launching without going through a shell by using 'process " \
2949 "launch'."
2950 if (exit_desc && exit_desc[0]) {
2951 if (with_shell)
2952 error.SetErrorStringWithFormat(
2953 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2954 exit_status, exit_desc);
2955 else
2956 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2957 exit_status, exit_desc);
2958 } else {
2959 if (with_shell)
2960 error.SetErrorStringWithFormat(
2961 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2962 exit_status);
2963 else
2964 error.SetErrorStringWithFormat("process exited with status %i",
2965 exit_status);
2966 }
2967 } else {
2968 error.SetErrorStringWithFormat(
2969 "initial process state wasn't stopped: %s", StateAsCString(state));
2970 }
2971 }
2972 m_process_sp->RestoreProcessEvents();
2973 } else {
2974 Status error2;
2975 error2.SetErrorStringWithFormat("process launch failed: %s",
2976 error.AsCString());
2977 error = error2;
2978 }
2979 return error;
2980 }
2981
Attach(ProcessAttachInfo & attach_info,Stream * stream)2982 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2983 auto state = eStateInvalid;
2984 auto process_sp = GetProcessSP();
2985 if (process_sp) {
2986 state = process_sp->GetState();
2987 if (process_sp->IsAlive() && state != eStateConnected) {
2988 if (state == eStateAttaching)
2989 return Status("process attach is in progress");
2990 return Status("a process is already being debugged");
2991 }
2992 }
2993
2994 const ModuleSP old_exec_module_sp = GetExecutableModule();
2995
2996 // If no process info was specified, then use the target executable name as
2997 // the process to attach to by default
2998 if (!attach_info.ProcessInfoSpecified()) {
2999 if (old_exec_module_sp)
3000 attach_info.GetExecutableFile().GetFilename() =
3001 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3002
3003 if (!attach_info.ProcessInfoSpecified()) {
3004 return Status("no process specified, create a target with a file, or "
3005 "specify the --pid or --name");
3006 }
3007 }
3008
3009 const auto platform_sp =
3010 GetDebugger().GetPlatformList().GetSelectedPlatform();
3011 ListenerSP hijack_listener_sp;
3012 const bool async = attach_info.GetAsync();
3013 if (!async) {
3014 hijack_listener_sp =
3015 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3016 attach_info.SetHijackListener(hijack_listener_sp);
3017 }
3018
3019 Status error;
3020 if (state != eStateConnected && platform_sp != nullptr &&
3021 platform_sp->CanDebugProcess()) {
3022 SetPlatform(platform_sp);
3023 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3024 } else {
3025 if (state != eStateConnected) {
3026 const char *plugin_name = attach_info.GetProcessPluginName();
3027 process_sp =
3028 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3029 plugin_name, nullptr);
3030 if (process_sp == nullptr) {
3031 error.SetErrorStringWithFormat(
3032 "failed to create process using plugin %s",
3033 (plugin_name) ? plugin_name : "null");
3034 return error;
3035 }
3036 }
3037 if (hijack_listener_sp)
3038 process_sp->HijackProcessEvents(hijack_listener_sp);
3039 error = process_sp->Attach(attach_info);
3040 }
3041
3042 if (error.Success() && process_sp) {
3043 if (async) {
3044 process_sp->RestoreProcessEvents();
3045 } else {
3046 state = process_sp->WaitForProcessToStop(
3047 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3048 process_sp->RestoreProcessEvents();
3049
3050 if (state != eStateStopped) {
3051 const char *exit_desc = process_sp->GetExitDescription();
3052 if (exit_desc)
3053 error.SetErrorStringWithFormat("%s", exit_desc);
3054 else
3055 error.SetErrorString(
3056 "process did not stop (no such process or permission problem?)");
3057 process_sp->Destroy(false);
3058 }
3059 }
3060 }
3061 return error;
3062 }
3063
FinalizeFileActions(ProcessLaunchInfo & info)3064 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3065 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3066
3067 // Finalize the file actions, and if none were given, default to opening up a
3068 // pseudo terminal
3069 PlatformSP platform_sp = GetPlatform();
3070 const bool default_to_use_pty =
3071 m_platform_sp ? m_platform_sp->IsHost() : false;
3072 LLDB_LOG(
3073 log,
3074 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3075 bool(platform_sp),
3076 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3077 default_to_use_pty);
3078
3079 // If nothing for stdin or stdout or stderr was specified, then check the
3080 // process for any default settings that were set with "settings set"
3081 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3082 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3083 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3084 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3085 "default handling");
3086
3087 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3088 // Do nothing, if we are launching in a remote terminal no file actions
3089 // should be done at all.
3090 return;
3091 }
3092
3093 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3094 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3095 "for stdin, stdout and stderr");
3096 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3097 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3098 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3099 } else {
3100 // Check for any values that might have gotten set with any of: (lldb)
3101 // settings set target.input-path (lldb) settings set target.output-path
3102 // (lldb) settings set target.error-path
3103 FileSpec in_file_spec;
3104 FileSpec out_file_spec;
3105 FileSpec err_file_spec;
3106 // Only override with the target settings if we don't already have an
3107 // action for in, out or error
3108 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3109 in_file_spec = GetStandardInputPath();
3110 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3111 out_file_spec = GetStandardOutputPath();
3112 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3113 err_file_spec = GetStandardErrorPath();
3114
3115 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3116 in_file_spec, out_file_spec, err_file_spec);
3117
3118 if (in_file_spec) {
3119 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3120 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3121 }
3122
3123 if (out_file_spec) {
3124 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3125 LLDB_LOG(log, "appended stdout open file action for {0}",
3126 out_file_spec);
3127 }
3128
3129 if (err_file_spec) {
3130 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3131 LLDB_LOG(log, "appended stderr open file action for {0}",
3132 err_file_spec);
3133 }
3134
3135 if (default_to_use_pty &&
3136 (!in_file_spec || !out_file_spec || !err_file_spec)) {
3137 llvm::Error Err = info.SetUpPtyRedirection();
3138 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3139 }
3140 }
3141 }
3142 }
3143
3144 // Target::StopHook
StopHook(lldb::TargetSP target_sp,lldb::user_id_t uid)3145 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3146 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3147 m_thread_spec_up() {}
3148
StopHook(const StopHook & rhs)3149 Target::StopHook::StopHook(const StopHook &rhs)
3150 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3151 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3152 m_thread_spec_up(), m_active(rhs.m_active),
3153 m_auto_continue(rhs.m_auto_continue) {
3154 if (rhs.m_thread_spec_up)
3155 m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up));
3156 }
3157
3158 Target::StopHook::~StopHook() = default;
3159
SetSpecifier(SymbolContextSpecifier * specifier)3160 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3161 m_specifier_sp.reset(specifier);
3162 }
3163
SetThreadSpecifier(ThreadSpec * specifier)3164 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3165 m_thread_spec_up.reset(specifier);
3166 }
3167
GetDescription(Stream * s,lldb::DescriptionLevel level) const3168 void Target::StopHook::GetDescription(Stream *s,
3169 lldb::DescriptionLevel level) const {
3170 unsigned indent_level = s->GetIndentLevel();
3171
3172 s->SetIndentLevel(indent_level + 2);
3173
3174 s->Printf("Hook: %" PRIu64 "\n", GetID());
3175 if (m_active)
3176 s->Indent("State: enabled\n");
3177 else
3178 s->Indent("State: disabled\n");
3179
3180 if (m_auto_continue)
3181 s->Indent("AutoContinue on\n");
3182
3183 if (m_specifier_sp) {
3184 s->Indent();
3185 s->PutCString("Specifier:\n");
3186 s->SetIndentLevel(indent_level + 4);
3187 m_specifier_sp->GetDescription(s, level);
3188 s->SetIndentLevel(indent_level + 2);
3189 }
3190
3191 if (m_thread_spec_up) {
3192 StreamString tmp;
3193 s->Indent("Thread:\n");
3194 m_thread_spec_up->GetDescription(&tmp, level);
3195 s->SetIndentLevel(indent_level + 4);
3196 s->Indent(tmp.GetString());
3197 s->PutCString("\n");
3198 s->SetIndentLevel(indent_level + 2);
3199 }
3200
3201 s->Indent("Commands: \n");
3202 s->SetIndentLevel(indent_level + 4);
3203 uint32_t num_commands = m_commands.GetSize();
3204 for (uint32_t i = 0; i < num_commands; i++) {
3205 s->Indent(m_commands.GetStringAtIndex(i));
3206 s->PutCString("\n");
3207 }
3208 s->SetIndentLevel(indent_level);
3209 }
3210
3211 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3212 {
3213 eNoDynamicValues,
3214 "no-dynamic-values",
3215 "Don't calculate the dynamic type of values",
3216 },
3217 {
3218 eDynamicCanRunTarget,
3219 "run-target",
3220 "Calculate the dynamic type of values "
3221 "even if you have to run the target.",
3222 },
3223 {
3224 eDynamicDontRunTarget,
3225 "no-run-target",
3226 "Calculate the dynamic type of values, but don't run the target.",
3227 },
3228 };
3229
GetDynamicValueTypes()3230 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3231 return OptionEnumValues(g_dynamic_value_types);
3232 }
3233
3234 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3235 {
3236 eInlineBreakpointsNever,
3237 "never",
3238 "Never look for inline breakpoint locations (fastest). This setting "
3239 "should only be used if you know that no inlining occurs in your"
3240 "programs.",
3241 },
3242 {
3243 eInlineBreakpointsHeaders,
3244 "headers",
3245 "Only check for inline breakpoint locations when setting breakpoints "
3246 "in header files, but not when setting breakpoint in implementation "
3247 "source files (default).",
3248 },
3249 {
3250 eInlineBreakpointsAlways,
3251 "always",
3252 "Always look for inline breakpoint locations when setting file and "
3253 "line breakpoints (slower but most accurate).",
3254 },
3255 };
3256
3257 enum x86DisassemblyFlavor {
3258 eX86DisFlavorDefault,
3259 eX86DisFlavorIntel,
3260 eX86DisFlavorATT
3261 };
3262
3263 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3264 {
3265 eX86DisFlavorDefault,
3266 "default",
3267 "Disassembler default (currently att).",
3268 },
3269 {
3270 eX86DisFlavorIntel,
3271 "intel",
3272 "Intel disassembler flavor.",
3273 },
3274 {
3275 eX86DisFlavorATT,
3276 "att",
3277 "AT&T disassembler flavor.",
3278 },
3279 };
3280
3281 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3282 {
3283 Disassembler::eHexStyleC,
3284 "c",
3285 "C-style (0xffff).",
3286 },
3287 {
3288 Disassembler::eHexStyleAsm,
3289 "asm",
3290 "Asm-style (0ffffh).",
3291 },
3292 };
3293
3294 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3295 {
3296 eLoadScriptFromSymFileTrue,
3297 "true",
3298 "Load debug scripts inside symbol files",
3299 },
3300 {
3301 eLoadScriptFromSymFileFalse,
3302 "false",
3303 "Do not load debug scripts inside symbol files.",
3304 },
3305 {
3306 eLoadScriptFromSymFileWarn,
3307 "warn",
3308 "Warn about debug scripts inside symbol files but do not load them.",
3309 },
3310 };
3311
3312 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3313 {
3314 eLoadCWDlldbinitTrue,
3315 "true",
3316 "Load .lldbinit files from current directory",
3317 },
3318 {
3319 eLoadCWDlldbinitFalse,
3320 "false",
3321 "Do not load .lldbinit files from current directory",
3322 },
3323 {
3324 eLoadCWDlldbinitWarn,
3325 "warn",
3326 "Warn about loading .lldbinit files from current directory",
3327 },
3328 };
3329
3330 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3331 {
3332 eMemoryModuleLoadLevelMinimal,
3333 "minimal",
3334 "Load minimal information when loading modules from memory. Currently "
3335 "this setting loads sections only.",
3336 },
3337 {
3338 eMemoryModuleLoadLevelPartial,
3339 "partial",
3340 "Load partial information when loading modules from memory. Currently "
3341 "this setting loads sections and function bounds.",
3342 },
3343 {
3344 eMemoryModuleLoadLevelComplete,
3345 "complete",
3346 "Load complete information when loading modules from memory. Currently "
3347 "this setting loads sections and all symbols.",
3348 },
3349 };
3350
3351 #define LLDB_PROPERTIES_target
3352 #include "TargetProperties.inc"
3353
3354 enum {
3355 #define LLDB_PROPERTIES_target
3356 #include "TargetPropertiesEnum.inc"
3357 ePropertyExperimental,
3358 };
3359
3360 class TargetOptionValueProperties : public OptionValueProperties {
3361 public:
TargetOptionValueProperties(ConstString name)3362 TargetOptionValueProperties(ConstString name)
3363 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3364
3365 // This constructor is used when creating TargetOptionValueProperties when it
3366 // is part of a new lldb_private::Target instance. It will copy all current
3367 // global property values as needed
TargetOptionValueProperties(Target * target,const TargetPropertiesSP & target_properties_sp)3368 TargetOptionValueProperties(Target *target,
3369 const TargetPropertiesSP &target_properties_sp)
3370 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3371 m_target(target), m_got_host_env(false) {}
3372
GetPropertyAtIndex(const ExecutionContext * exe_ctx,bool will_modify,uint32_t idx) const3373 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3374 bool will_modify,
3375 uint32_t idx) const override {
3376 // When getting the value for a key from the target options, we will always
3377 // try and grab the setting from the current target if there is one. Else
3378 // we just use the one from this instance.
3379 if (idx == ePropertyEnvVars)
3380 GetHostEnvironmentIfNeeded();
3381
3382 if (exe_ctx) {
3383 Target *target = exe_ctx->GetTargetPtr();
3384 if (target) {
3385 TargetOptionValueProperties *target_properties =
3386 static_cast<TargetOptionValueProperties *>(
3387 target->GetValueProperties().get());
3388 if (this != target_properties)
3389 return target_properties->ProtectedGetPropertyAtIndex(idx);
3390 }
3391 }
3392 return ProtectedGetPropertyAtIndex(idx);
3393 }
3394
GetTargetSP()3395 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3396
3397 protected:
GetHostEnvironmentIfNeeded() const3398 void GetHostEnvironmentIfNeeded() const {
3399 if (!m_got_host_env) {
3400 if (m_target) {
3401 m_got_host_env = true;
3402 const uint32_t idx = ePropertyInheritEnv;
3403 if (GetPropertyAtIndexAsBoolean(
3404 nullptr, idx, g_target_properties[idx].default_uint_value != 0)) {
3405 PlatformSP platform_sp(m_target->GetPlatform());
3406 if (platform_sp) {
3407 Environment env = platform_sp->GetEnvironment();
3408 OptionValueDictionary *env_dict =
3409 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3410 ePropertyEnvVars);
3411 if (env_dict) {
3412 const bool can_replace = false;
3413 for (const auto &KV : env) {
3414 // Don't allow existing keys to be replaced with ones we get
3415 // from the platform environment
3416 env_dict->SetValueForKey(
3417 ConstString(KV.first()),
3418 OptionValueSP(new OptionValueString(KV.second.c_str())),
3419 can_replace);
3420 }
3421 }
3422 }
3423 }
3424 }
3425 }
3426 }
3427 Target *m_target;
3428 mutable bool m_got_host_env;
3429 };
3430
3431 // TargetProperties
3432 #define LLDB_PROPERTIES_experimental
3433 #include "TargetProperties.inc"
3434
3435 enum {
3436 #define LLDB_PROPERTIES_experimental
3437 #include "TargetPropertiesEnum.inc"
3438 };
3439
3440 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3441 public:
TargetExperimentalOptionValueProperties()3442 TargetExperimentalOptionValueProperties()
3443 : OptionValueProperties(
3444 ConstString(Properties::GetExperimentalSettingsName())) {}
3445 };
3446
TargetExperimentalProperties()3447 TargetExperimentalProperties::TargetExperimentalProperties()
3448 : Properties(OptionValuePropertiesSP(
3449 new TargetExperimentalOptionValueProperties())) {
3450 m_collection_sp->Initialize(g_experimental_properties);
3451 }
3452
3453 // TargetProperties
TargetProperties(Target * target)3454 TargetProperties::TargetProperties(Target *target)
3455 : Properties(), m_launch_info() {
3456 if (target) {
3457 m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3458 target, Target::GetGlobalProperties());
3459
3460 // Set callbacks to update launch_info whenever "settins set" updated any
3461 // of these properties
3462 m_collection_sp->SetValueChangedCallback(
3463 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3464 m_collection_sp->SetValueChangedCallback(
3465 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3466 m_collection_sp->SetValueChangedCallback(
3467 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3468 m_collection_sp->SetValueChangedCallback(
3469 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3470 m_collection_sp->SetValueChangedCallback(
3471 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3472 m_collection_sp->SetValueChangedCallback(
3473 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3474 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3475 DetachOnErrorValueChangedCallback();
3476 });
3477 m_collection_sp->SetValueChangedCallback(
3478 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3479 m_collection_sp->SetValueChangedCallback(
3480 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3481
3482 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3483 m_collection_sp->AppendProperty(
3484 ConstString(Properties::GetExperimentalSettingsName()),
3485 ConstString("Experimental settings - setting these won't produce "
3486 "errors if the setting is not present."),
3487 true, m_experimental_properties_up->GetValueProperties());
3488
3489 // Update m_launch_info once it was created
3490 Arg0ValueChangedCallback();
3491 RunArgsValueChangedCallback();
3492 // EnvVarsValueChangedCallback(); // FIXME: cause segfault in
3493 // Target::GetPlatform()
3494 InputPathValueChangedCallback();
3495 OutputPathValueChangedCallback();
3496 ErrorPathValueChangedCallback();
3497 DetachOnErrorValueChangedCallback();
3498 DisableASLRValueChangedCallback();
3499 DisableSTDIOValueChangedCallback();
3500 } else {
3501 m_collection_sp =
3502 std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3503 m_collection_sp->Initialize(g_target_properties);
3504 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3505 m_collection_sp->AppendProperty(
3506 ConstString(Properties::GetExperimentalSettingsName()),
3507 ConstString("Experimental settings - setting these won't produce "
3508 "errors if the setting is not present."),
3509 true, m_experimental_properties_up->GetValueProperties());
3510 m_collection_sp->AppendProperty(
3511 ConstString("process"), ConstString("Settings specific to processes."),
3512 true, Process::GetGlobalProperties()->GetValueProperties());
3513 }
3514 }
3515
3516 TargetProperties::~TargetProperties() = default;
3517
GetInjectLocalVariables(ExecutionContext * exe_ctx) const3518 bool TargetProperties::GetInjectLocalVariables(
3519 ExecutionContext *exe_ctx) const {
3520 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3521 exe_ctx, false, ePropertyExperimental);
3522 OptionValueProperties *exp_values =
3523 exp_property->GetValue()->GetAsProperties();
3524 if (exp_values)
3525 return exp_values->GetPropertyAtIndexAsBoolean(
3526 exe_ctx, ePropertyInjectLocalVars, true);
3527 else
3528 return true;
3529 }
3530
SetInjectLocalVariables(ExecutionContext * exe_ctx,bool b)3531 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3532 bool b) {
3533 const Property *exp_property =
3534 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3535 OptionValueProperties *exp_values =
3536 exp_property->GetValue()->GetAsProperties();
3537 if (exp_values)
3538 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3539 true);
3540 }
3541
GetDefaultArchitecture() const3542 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3543 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3544 nullptr, ePropertyDefaultArch);
3545 if (value)
3546 return value->GetCurrentValue();
3547 return ArchSpec();
3548 }
3549
SetDefaultArchitecture(const ArchSpec & arch)3550 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3551 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3552 nullptr, ePropertyDefaultArch);
3553 if (value)
3554 return value->SetCurrentValue(arch, true);
3555 }
3556
GetMoveToNearestCode() const3557 bool TargetProperties::GetMoveToNearestCode() const {
3558 const uint32_t idx = ePropertyMoveToNearestCode;
3559 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3560 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3561 }
3562
GetPreferDynamicValue() const3563 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3564 const uint32_t idx = ePropertyPreferDynamic;
3565 return (lldb::DynamicValueType)
3566 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3567 nullptr, idx, g_target_properties[idx].default_uint_value);
3568 }
3569
SetPreferDynamicValue(lldb::DynamicValueType d)3570 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3571 const uint32_t idx = ePropertyPreferDynamic;
3572 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3573 }
3574
GetPreloadSymbols() const3575 bool TargetProperties::GetPreloadSymbols() const {
3576 const uint32_t idx = ePropertyPreloadSymbols;
3577 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3578 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3579 }
3580
SetPreloadSymbols(bool b)3581 void TargetProperties::SetPreloadSymbols(bool b) {
3582 const uint32_t idx = ePropertyPreloadSymbols;
3583 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3584 }
3585
GetDisableASLR() const3586 bool TargetProperties::GetDisableASLR() const {
3587 const uint32_t idx = ePropertyDisableASLR;
3588 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3589 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3590 }
3591
SetDisableASLR(bool b)3592 void TargetProperties::SetDisableASLR(bool b) {
3593 const uint32_t idx = ePropertyDisableASLR;
3594 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3595 }
3596
GetDetachOnError() const3597 bool TargetProperties::GetDetachOnError() const {
3598 const uint32_t idx = ePropertyDetachOnError;
3599 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3600 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3601 }
3602
SetDetachOnError(bool b)3603 void TargetProperties::SetDetachOnError(bool b) {
3604 const uint32_t idx = ePropertyDetachOnError;
3605 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3606 }
3607
GetDisableSTDIO() const3608 bool TargetProperties::GetDisableSTDIO() const {
3609 const uint32_t idx = ePropertyDisableSTDIO;
3610 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3611 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3612 }
3613
SetDisableSTDIO(bool b)3614 void TargetProperties::SetDisableSTDIO(bool b) {
3615 const uint32_t idx = ePropertyDisableSTDIO;
3616 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3617 }
3618
GetDisassemblyFlavor() const3619 const char *TargetProperties::GetDisassemblyFlavor() const {
3620 const uint32_t idx = ePropertyDisassemblyFlavor;
3621 const char *return_value;
3622
3623 x86DisassemblyFlavor flavor_value =
3624 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3625 nullptr, idx, g_target_properties[idx].default_uint_value);
3626 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3627 return return_value;
3628 }
3629
GetInlineStrategy() const3630 InlineStrategy TargetProperties::GetInlineStrategy() const {
3631 const uint32_t idx = ePropertyInlineStrategy;
3632 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3633 nullptr, idx, g_target_properties[idx].default_uint_value);
3634 }
3635
GetArg0() const3636 llvm::StringRef TargetProperties::GetArg0() const {
3637 const uint32_t idx = ePropertyArg0;
3638 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3639 llvm::StringRef());
3640 }
3641
SetArg0(llvm::StringRef arg)3642 void TargetProperties::SetArg0(llvm::StringRef arg) {
3643 const uint32_t idx = ePropertyArg0;
3644 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3645 m_launch_info.SetArg0(arg);
3646 }
3647
GetRunArguments(Args & args) const3648 bool TargetProperties::GetRunArguments(Args &args) const {
3649 const uint32_t idx = ePropertyRunArgs;
3650 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3651 }
3652
SetRunArguments(const Args & args)3653 void TargetProperties::SetRunArguments(const Args &args) {
3654 const uint32_t idx = ePropertyRunArgs;
3655 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3656 m_launch_info.GetArguments() = args;
3657 }
3658
GetEnvironment() const3659 Environment TargetProperties::GetEnvironment() const {
3660 // TODO: Get rid of the Args intermediate step
3661 Args env;
3662 const uint32_t idx = ePropertyEnvVars;
3663 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3664 return Environment(env);
3665 }
3666
SetEnvironment(Environment env)3667 void TargetProperties::SetEnvironment(Environment env) {
3668 // TODO: Get rid of the Args intermediate step
3669 const uint32_t idx = ePropertyEnvVars;
3670 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3671 m_launch_info.GetEnvironment() = std::move(env);
3672 }
3673
GetSkipPrologue() const3674 bool TargetProperties::GetSkipPrologue() const {
3675 const uint32_t idx = ePropertySkipPrologue;
3676 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3677 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3678 }
3679
GetSourcePathMap() const3680 PathMappingList &TargetProperties::GetSourcePathMap() const {
3681 const uint32_t idx = ePropertySourceMap;
3682 OptionValuePathMappings *option_value =
3683 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3684 false, idx);
3685 assert(option_value);
3686 return option_value->GetCurrentValue();
3687 }
3688
AppendExecutableSearchPaths(const FileSpec & dir)3689 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3690 const uint32_t idx = ePropertyExecutableSearchPaths;
3691 OptionValueFileSpecList *option_value =
3692 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3693 false, idx);
3694 assert(option_value);
3695 option_value->AppendCurrentValue(dir);
3696 }
3697
GetExecutableSearchPaths()3698 FileSpecList TargetProperties::GetExecutableSearchPaths() {
3699 const uint32_t idx = ePropertyExecutableSearchPaths;
3700 const OptionValueFileSpecList *option_value =
3701 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3702 false, idx);
3703 assert(option_value);
3704 return option_value->GetCurrentValue();
3705 }
3706
GetDebugFileSearchPaths()3707 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
3708 const uint32_t idx = ePropertyDebugFileSearchPaths;
3709 const OptionValueFileSpecList *option_value =
3710 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3711 false, idx);
3712 assert(option_value);
3713 return option_value->GetCurrentValue();
3714 }
3715
GetClangModuleSearchPaths()3716 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
3717 const uint32_t idx = ePropertyClangModuleSearchPaths;
3718 const OptionValueFileSpecList *option_value =
3719 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3720 false, idx);
3721 assert(option_value);
3722 return option_value->GetCurrentValue();
3723 }
3724
GetEnableAutoImportClangModules() const3725 bool TargetProperties::GetEnableAutoImportClangModules() const {
3726 const uint32_t idx = ePropertyAutoImportClangModules;
3727 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3728 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3729 }
3730
GetEnableImportStdModule() const3731 bool TargetProperties::GetEnableImportStdModule() const {
3732 const uint32_t idx = ePropertyImportStdModule;
3733 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3734 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3735 }
3736
GetEnableAutoApplyFixIts() const3737 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3738 const uint32_t idx = ePropertyAutoApplyFixIts;
3739 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3740 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3741 }
3742
GetEnableNotifyAboutFixIts() const3743 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3744 const uint32_t idx = ePropertyNotifyAboutFixIts;
3745 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3746 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3747 }
3748
GetEnableSaveObjects() const3749 bool TargetProperties::GetEnableSaveObjects() const {
3750 const uint32_t idx = ePropertySaveObjects;
3751 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3752 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3753 }
3754
GetEnableSyntheticValue() const3755 bool TargetProperties::GetEnableSyntheticValue() const {
3756 const uint32_t idx = ePropertyEnableSynthetic;
3757 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3758 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3759 }
3760
GetMaxZeroPaddingInFloatFormat() const3761 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
3762 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
3763 return m_collection_sp->GetPropertyAtIndexAsUInt64(
3764 nullptr, idx, g_target_properties[idx].default_uint_value);
3765 }
3766
GetMaximumNumberOfChildrenToDisplay() const3767 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3768 const uint32_t idx = ePropertyMaxChildrenCount;
3769 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3770 nullptr, idx, g_target_properties[idx].default_uint_value);
3771 }
3772
GetMaximumSizeOfStringSummary() const3773 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3774 const uint32_t idx = ePropertyMaxSummaryLength;
3775 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3776 nullptr, idx, g_target_properties[idx].default_uint_value);
3777 }
3778
GetMaximumMemReadSize() const3779 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3780 const uint32_t idx = ePropertyMaxMemReadSize;
3781 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3782 nullptr, idx, g_target_properties[idx].default_uint_value);
3783 }
3784
GetStandardInputPath() const3785 FileSpec TargetProperties::GetStandardInputPath() const {
3786 const uint32_t idx = ePropertyInputPath;
3787 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3788 }
3789
SetStandardInputPath(llvm::StringRef path)3790 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3791 const uint32_t idx = ePropertyInputPath;
3792 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3793 }
3794
GetStandardOutputPath() const3795 FileSpec TargetProperties::GetStandardOutputPath() const {
3796 const uint32_t idx = ePropertyOutputPath;
3797 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3798 }
3799
SetStandardOutputPath(llvm::StringRef path)3800 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3801 const uint32_t idx = ePropertyOutputPath;
3802 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3803 }
3804
GetStandardErrorPath() const3805 FileSpec TargetProperties::GetStandardErrorPath() const {
3806 const uint32_t idx = ePropertyErrorPath;
3807 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3808 }
3809
SetStandardErrorPath(llvm::StringRef path)3810 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3811 const uint32_t idx = ePropertyErrorPath;
3812 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3813 }
3814
GetLanguage() const3815 LanguageType TargetProperties::GetLanguage() const {
3816 OptionValueLanguage *value =
3817 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3818 nullptr, ePropertyLanguage);
3819 if (value)
3820 return value->GetCurrentValue();
3821 return LanguageType();
3822 }
3823
GetExpressionPrefixContents()3824 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
3825 const uint32_t idx = ePropertyExprPrefix;
3826 OptionValueFileSpec *file =
3827 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3828 idx);
3829 if (file) {
3830 DataBufferSP data_sp(file->GetFileContents());
3831 if (data_sp)
3832 return llvm::StringRef(
3833 reinterpret_cast<const char *>(data_sp->GetBytes()),
3834 data_sp->GetByteSize());
3835 }
3836 return "";
3837 }
3838
GetBreakpointsConsultPlatformAvoidList()3839 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3840 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3841 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3842 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3843 }
3844
GetUseHexImmediates() const3845 bool TargetProperties::GetUseHexImmediates() const {
3846 const uint32_t idx = ePropertyUseHexImmediates;
3847 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3848 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3849 }
3850
GetUseFastStepping() const3851 bool TargetProperties::GetUseFastStepping() const {
3852 const uint32_t idx = ePropertyUseFastStepping;
3853 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3854 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3855 }
3856
GetDisplayExpressionsInCrashlogs() const3857 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3858 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3859 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3860 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3861 }
3862
GetLoadScriptFromSymbolFile() const3863 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3864 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3865 return (LoadScriptFromSymFile)
3866 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3867 nullptr, idx, g_target_properties[idx].default_uint_value);
3868 }
3869
GetLoadCWDlldbinitFile() const3870 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3871 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3872 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3873 nullptr, idx, g_target_properties[idx].default_uint_value);
3874 }
3875
GetHexImmediateStyle() const3876 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3877 const uint32_t idx = ePropertyHexImmediateStyle;
3878 return (Disassembler::HexImmediateStyle)
3879 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3880 nullptr, idx, g_target_properties[idx].default_uint_value);
3881 }
3882
GetMemoryModuleLoadLevel() const3883 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3884 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3885 return (MemoryModuleLoadLevel)
3886 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3887 nullptr, idx, g_target_properties[idx].default_uint_value);
3888 }
3889
GetUserSpecifiedTrapHandlerNames(Args & args) const3890 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3891 const uint32_t idx = ePropertyTrapHandlerNames;
3892 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3893 }
3894
SetUserSpecifiedTrapHandlerNames(const Args & args)3895 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3896 const uint32_t idx = ePropertyTrapHandlerNames;
3897 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3898 }
3899
GetDisplayRuntimeSupportValues() const3900 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3901 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3902 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3903 }
3904
SetDisplayRuntimeSupportValues(bool b)3905 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3906 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3907 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3908 }
3909
GetDisplayRecognizedArguments() const3910 bool TargetProperties::GetDisplayRecognizedArguments() const {
3911 const uint32_t idx = ePropertyDisplayRecognizedArguments;
3912 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3913 }
3914
SetDisplayRecognizedArguments(bool b)3915 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
3916 const uint32_t idx = ePropertyDisplayRecognizedArguments;
3917 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3918 }
3919
GetNonStopModeEnabled() const3920 bool TargetProperties::GetNonStopModeEnabled() const {
3921 const uint32_t idx = ePropertyNonStopModeEnabled;
3922 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3923 }
3924
SetNonStopModeEnabled(bool b)3925 void TargetProperties::SetNonStopModeEnabled(bool b) {
3926 const uint32_t idx = ePropertyNonStopModeEnabled;
3927 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3928 }
3929
GetProcessLaunchInfo()3930 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3931 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3932 return m_launch_info;
3933 }
3934
SetProcessLaunchInfo(const ProcessLaunchInfo & launch_info)3935 void TargetProperties::SetProcessLaunchInfo(
3936 const ProcessLaunchInfo &launch_info) {
3937 m_launch_info = launch_info;
3938 SetArg0(launch_info.GetArg0());
3939 SetRunArguments(launch_info.GetArguments());
3940 SetEnvironment(launch_info.GetEnvironment());
3941 const FileAction *input_file_action =
3942 launch_info.GetFileActionForFD(STDIN_FILENO);
3943 if (input_file_action) {
3944 SetStandardInputPath(input_file_action->GetPath());
3945 }
3946 const FileAction *output_file_action =
3947 launch_info.GetFileActionForFD(STDOUT_FILENO);
3948 if (output_file_action) {
3949 SetStandardOutputPath(output_file_action->GetPath());
3950 }
3951 const FileAction *error_file_action =
3952 launch_info.GetFileActionForFD(STDERR_FILENO);
3953 if (error_file_action) {
3954 SetStandardErrorPath(error_file_action->GetPath());
3955 }
3956 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3957 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3958 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
3959 }
3960
GetRequireHardwareBreakpoints() const3961 bool TargetProperties::GetRequireHardwareBreakpoints() const {
3962 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3963 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3964 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3965 }
3966
SetRequireHardwareBreakpoints(bool b)3967 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
3968 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3969 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3970 }
3971
Arg0ValueChangedCallback()3972 void TargetProperties::Arg0ValueChangedCallback() {
3973 m_launch_info.SetArg0(GetArg0());
3974 }
3975
RunArgsValueChangedCallback()3976 void TargetProperties::RunArgsValueChangedCallback() {
3977 Args args;
3978 if (GetRunArguments(args))
3979 m_launch_info.GetArguments() = args;
3980 }
3981
EnvVarsValueChangedCallback()3982 void TargetProperties::EnvVarsValueChangedCallback() {
3983 m_launch_info.GetEnvironment() = GetEnvironment();
3984 }
3985
InputPathValueChangedCallback()3986 void TargetProperties::InputPathValueChangedCallback() {
3987 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
3988 false);
3989 }
3990
OutputPathValueChangedCallback()3991 void TargetProperties::OutputPathValueChangedCallback() {
3992 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
3993 false, true);
3994 }
3995
ErrorPathValueChangedCallback()3996 void TargetProperties::ErrorPathValueChangedCallback() {
3997 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
3998 false, true);
3999 }
4000
DetachOnErrorValueChangedCallback()4001 void TargetProperties::DetachOnErrorValueChangedCallback() {
4002 if (GetDetachOnError())
4003 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4004 else
4005 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4006 }
4007
DisableASLRValueChangedCallback()4008 void TargetProperties::DisableASLRValueChangedCallback() {
4009 if (GetDisableASLR())
4010 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4011 else
4012 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4013 }
4014
DisableSTDIOValueChangedCallback()4015 void TargetProperties::DisableSTDIOValueChangedCallback() {
4016 if (GetDisableSTDIO())
4017 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4018 else
4019 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4020 }
4021
4022 // Target::TargetEventData
4023
TargetEventData(const lldb::TargetSP & target_sp)4024 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4025 : EventData(), m_target_sp(target_sp), m_module_list() {}
4026
TargetEventData(const lldb::TargetSP & target_sp,const ModuleList & module_list)4027 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4028 const ModuleList &module_list)
4029 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4030
4031 Target::TargetEventData::~TargetEventData() = default;
4032
GetFlavorString()4033 ConstString Target::TargetEventData::GetFlavorString() {
4034 static ConstString g_flavor("Target::TargetEventData");
4035 return g_flavor;
4036 }
4037
Dump(Stream * s) const4038 void Target::TargetEventData::Dump(Stream *s) const {
4039 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4040 if (i != 0)
4041 *s << ", ";
4042 m_module_list.GetModuleAtIndex(i)->GetDescription(
4043 s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4044 }
4045 }
4046
4047 const Target::TargetEventData *
GetEventDataFromEvent(const Event * event_ptr)4048 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4049 if (event_ptr) {
4050 const EventData *event_data = event_ptr->GetData();
4051 if (event_data &&
4052 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4053 return static_cast<const TargetEventData *>(event_ptr->GetData());
4054 }
4055 return nullptr;
4056 }
4057
GetTargetFromEvent(const Event * event_ptr)4058 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4059 TargetSP target_sp;
4060 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4061 if (event_data)
4062 target_sp = event_data->m_target_sp;
4063 return target_sp;
4064 }
4065
4066 ModuleList
GetModuleListFromEvent(const Event * event_ptr)4067 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4068 ModuleList module_list;
4069 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4070 if (event_data)
4071 module_list = event_data->m_module_list;
4072 return module_list;
4073 }
4074
GetAPIMutex()4075 std::recursive_mutex &Target::GetAPIMutex() {
4076 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4077 return m_private_mutex;
4078 else
4079 return m_mutex;
4080 }
4081