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 llvm::Error error = llvm::Error::success();
2416 assert(!error); // Check the success value when assertions are enabled.
2417
2418 if (!exe_module || !exe_module->GetObjectFile()) {
2419 error = llvm::make_error<llvm::StringError>("No primary executable found",
2420 llvm::inconvertibleErrorCode());
2421 } else {
2422 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2423 if (entry_addr.IsValid())
2424 return entry_addr;
2425
2426 error = llvm::make_error<llvm::StringError>(
2427 "Could not find entry point address for executable module \"" +
2428 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2429 llvm::inconvertibleErrorCode());
2430 }
2431
2432 const ModuleList &modules = GetImages();
2433 const size_t num_images = modules.GetSize();
2434 for (size_t idx = 0; idx < num_images; ++idx) {
2435 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2436 if (!module_sp || !module_sp->GetObjectFile())
2437 continue;
2438
2439 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2440 if (entry_addr.IsValid()) {
2441 // Discard the error.
2442 llvm::consumeError(std::move(error));
2443 return entry_addr;
2444 }
2445 }
2446
2447 return std::move(error);
2448 }
2449
GetCallableLoadAddress(lldb::addr_t load_addr,AddressClass addr_class) const2450 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2451 AddressClass addr_class) const {
2452 auto arch_plugin = GetArchitecturePlugin();
2453 return arch_plugin
2454 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2455 : load_addr;
2456 }
2457
GetOpcodeLoadAddress(lldb::addr_t load_addr,AddressClass addr_class) const2458 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2459 AddressClass addr_class) const {
2460 auto arch_plugin = GetArchitecturePlugin();
2461 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2462 : load_addr;
2463 }
2464
GetBreakableLoadAddress(lldb::addr_t addr)2465 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2466 auto arch_plugin = GetArchitecturePlugin();
2467 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2468 }
2469
GetSourceManager()2470 SourceManager &Target::GetSourceManager() {
2471 if (!m_source_manager_up)
2472 m_source_manager_up.reset(new SourceManager(shared_from_this()));
2473 return *m_source_manager_up;
2474 }
2475
GetClangModulesDeclVendor()2476 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2477 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2478 // we can make it
2479 // per-target
2480
2481 {
2482 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2483
2484 if (!m_clang_modules_decl_vendor_up) {
2485 m_clang_modules_decl_vendor_up.reset(
2486 ClangModulesDeclVendor::Create(*this));
2487 }
2488 }
2489
2490 return m_clang_modules_decl_vendor_up.get();
2491 }
2492
CreateStopHook()2493 Target::StopHookSP Target::CreateStopHook() {
2494 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2495 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2496 m_stop_hooks[new_uid] = stop_hook_sp;
2497 return stop_hook_sp;
2498 }
2499
RemoveStopHookByID(lldb::user_id_t user_id)2500 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2501 size_t num_removed = m_stop_hooks.erase(user_id);
2502 return (num_removed != 0);
2503 }
2504
RemoveAllStopHooks()2505 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2506
GetStopHookByID(lldb::user_id_t user_id)2507 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2508 StopHookSP found_hook;
2509
2510 StopHookCollection::iterator specified_hook_iter;
2511 specified_hook_iter = m_stop_hooks.find(user_id);
2512 if (specified_hook_iter != m_stop_hooks.end())
2513 found_hook = (*specified_hook_iter).second;
2514 return found_hook;
2515 }
2516
SetStopHookActiveStateByID(lldb::user_id_t user_id,bool active_state)2517 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2518 bool active_state) {
2519 StopHookCollection::iterator specified_hook_iter;
2520 specified_hook_iter = m_stop_hooks.find(user_id);
2521 if (specified_hook_iter == m_stop_hooks.end())
2522 return false;
2523
2524 (*specified_hook_iter).second->SetIsActive(active_state);
2525 return true;
2526 }
2527
SetAllStopHooksActiveState(bool active_state)2528 void Target::SetAllStopHooksActiveState(bool active_state) {
2529 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2530 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2531 (*pos).second->SetIsActive(active_state);
2532 }
2533 }
2534
RunStopHooks()2535 void Target::RunStopHooks() {
2536 if (m_suppress_stop_hooks)
2537 return;
2538
2539 if (!m_process_sp)
2540 return;
2541
2542 // Somebody might have restarted the process:
2543 if (m_process_sp->GetState() != eStateStopped)
2544 return;
2545
2546 // <rdar://problem/12027563> make sure we check that we are not stopped
2547 // because of us running a user expression since in that case we do not want
2548 // to run the stop-hooks
2549 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2550 return;
2551
2552 if (m_stop_hooks.empty())
2553 return;
2554
2555 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2556
2557 // If there aren't any active stop hooks, don't bother either.
2558 // Also see if any of the active hooks want to auto-continue.
2559 bool any_active_hooks = false;
2560 bool auto_continue = false;
2561 for (auto hook : m_stop_hooks) {
2562 if (hook.second->IsActive()) {
2563 any_active_hooks = true;
2564 auto_continue |= hook.second->GetAutoContinue();
2565 }
2566 }
2567 if (!any_active_hooks)
2568 return;
2569
2570 CommandReturnObject result;
2571
2572 std::vector<ExecutionContext> exc_ctx_with_reasons;
2573 std::vector<SymbolContext> sym_ctx_with_reasons;
2574
2575 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2576 size_t num_threads = cur_threadlist.GetSize();
2577 for (size_t i = 0; i < num_threads; i++) {
2578 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2579 if (cur_thread_sp->ThreadStoppedForAReason()) {
2580 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2581 exc_ctx_with_reasons.push_back(ExecutionContext(
2582 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2583 sym_ctx_with_reasons.push_back(
2584 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2585 }
2586 }
2587
2588 // If no threads stopped for a reason, don't run the stop-hooks.
2589 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2590 if (num_exe_ctx == 0)
2591 return;
2592
2593 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2594 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2595
2596 bool keep_going = true;
2597 bool hooks_ran = false;
2598 bool print_hook_header = (m_stop_hooks.size() != 1);
2599 bool print_thread_header = (num_exe_ctx != 1);
2600 bool did_restart = false;
2601
2602 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2603 // result.Clear();
2604 StopHookSP cur_hook_sp = (*pos).second;
2605 if (!cur_hook_sp->IsActive())
2606 continue;
2607
2608 bool any_thread_matched = false;
2609 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2610 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2611 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2612 sym_ctx_with_reasons[i])) &&
2613 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2614 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2615 exc_ctx_with_reasons[i].GetThreadRef()))) {
2616 if (!hooks_ran) {
2617 hooks_ran = true;
2618 }
2619 if (print_hook_header && !any_thread_matched) {
2620 const char *cmd =
2621 (cur_hook_sp->GetCommands().GetSize() == 1
2622 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2623 : nullptr);
2624 if (cmd)
2625 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2626 cur_hook_sp->GetID(), cmd);
2627 else
2628 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2629 cur_hook_sp->GetID());
2630 any_thread_matched = true;
2631 }
2632
2633 if (print_thread_header)
2634 result.AppendMessageWithFormat(
2635 "-- Thread %d\n",
2636 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2637
2638 CommandInterpreterRunOptions options;
2639 options.SetStopOnContinue(true);
2640 options.SetStopOnError(true);
2641 options.SetEchoCommands(false);
2642 options.SetPrintResults(true);
2643 options.SetPrintErrors(true);
2644 options.SetAddToHistory(false);
2645
2646 // Force Async:
2647 bool old_async = GetDebugger().GetAsyncExecution();
2648 GetDebugger().SetAsyncExecution(true);
2649 GetDebugger().GetCommandInterpreter().HandleCommands(
2650 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2651 result);
2652 GetDebugger().SetAsyncExecution(old_async);
2653 // If the command started the target going again, we should bag out of
2654 // running the stop hooks.
2655 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2656 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2657 // But only complain if there were more stop hooks to do:
2658 StopHookCollection::iterator tmp = pos;
2659 if (++tmp != end)
2660 result.AppendMessageWithFormat(
2661 "\nAborting stop hooks, hook %" PRIu64
2662 " set the program running.\n"
2663 " Consider using '-G true' to make "
2664 "stop hooks auto-continue.\n",
2665 cur_hook_sp->GetID());
2666 keep_going = false;
2667 did_restart = true;
2668 }
2669 }
2670 }
2671 }
2672 // Finally, if auto-continue was requested, do it now:
2673 if (!did_restart && auto_continue)
2674 m_process_sp->PrivateResume();
2675
2676 result.GetImmediateOutputStream()->Flush();
2677 result.GetImmediateErrorStream()->Flush();
2678 }
2679
GetGlobalProperties()2680 const TargetPropertiesSP &Target::GetGlobalProperties() {
2681 // NOTE: intentional leak so we don't crash if global destructor chain gets
2682 // called as other threads still use the result of this function
2683 static TargetPropertiesSP *g_settings_sp_ptr =
2684 new TargetPropertiesSP(new TargetProperties(nullptr));
2685 return *g_settings_sp_ptr;
2686 }
2687
Install(ProcessLaunchInfo * launch_info)2688 Status Target::Install(ProcessLaunchInfo *launch_info) {
2689 Status error;
2690 PlatformSP platform_sp(GetPlatform());
2691 if (platform_sp) {
2692 if (platform_sp->IsRemote()) {
2693 if (platform_sp->IsConnected()) {
2694 // Install all files that have an install path, and always install the
2695 // main executable when connected to a remote platform
2696 const ModuleList &modules = GetImages();
2697 const size_t num_images = modules.GetSize();
2698 for (size_t idx = 0; idx < num_images; ++idx) {
2699 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2700 if (module_sp) {
2701 const bool is_main_executable = module_sp == GetExecutableModule();
2702 FileSpec local_file(module_sp->GetFileSpec());
2703 if (local_file) {
2704 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2705 if (!remote_file) {
2706 if (is_main_executable) // TODO: add setting for always
2707 // installing main executable???
2708 {
2709 // Always install the main executable
2710 remote_file = platform_sp->GetRemoteWorkingDirectory();
2711 remote_file.AppendPathComponent(
2712 module_sp->GetFileSpec().GetFilename().GetCString());
2713 }
2714 }
2715 if (remote_file) {
2716 error = platform_sp->Install(local_file, remote_file);
2717 if (error.Success()) {
2718 module_sp->SetPlatformFileSpec(remote_file);
2719 if (is_main_executable) {
2720 platform_sp->SetFilePermissions(remote_file, 0700);
2721 if (launch_info)
2722 launch_info->SetExecutableFile(remote_file, false);
2723 }
2724 } else
2725 break;
2726 }
2727 }
2728 }
2729 }
2730 }
2731 }
2732 }
2733 return error;
2734 }
2735
ResolveLoadAddress(addr_t load_addr,Address & so_addr,uint32_t stop_id)2736 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2737 uint32_t stop_id) {
2738 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2739 }
2740
ResolveFileAddress(lldb::addr_t file_addr,Address & resolved_addr)2741 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2742 Address &resolved_addr) {
2743 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2744 }
2745
SetSectionLoadAddress(const SectionSP & section_sp,addr_t new_section_load_addr,bool warn_multiple)2746 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp,
2747 addr_t new_section_load_addr,
2748 bool warn_multiple) {
2749 const addr_t old_section_load_addr =
2750 m_section_load_history.GetSectionLoadAddress(
2751 SectionLoadHistory::eStopIDNow, section_sp);
2752 if (old_section_load_addr != new_section_load_addr) {
2753 uint32_t stop_id = 0;
2754 ProcessSP process_sp(GetProcessSP());
2755 if (process_sp)
2756 stop_id = process_sp->GetStopID();
2757 else
2758 stop_id = m_section_load_history.GetLastStopID();
2759 if (m_section_load_history.SetSectionLoadAddress(
2760 stop_id, section_sp, new_section_load_addr, warn_multiple))
2761 return true; // Return true if the section load address was changed...
2762 }
2763 return false; // Return false to indicate nothing changed
2764 }
2765
UnloadModuleSections(const ModuleList & module_list)2766 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2767 size_t section_unload_count = 0;
2768 size_t num_modules = module_list.GetSize();
2769 for (size_t i = 0; i < num_modules; ++i) {
2770 section_unload_count +=
2771 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2772 }
2773 return section_unload_count;
2774 }
2775
UnloadModuleSections(const lldb::ModuleSP & module_sp)2776 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2777 uint32_t stop_id = 0;
2778 ProcessSP process_sp(GetProcessSP());
2779 if (process_sp)
2780 stop_id = process_sp->GetStopID();
2781 else
2782 stop_id = m_section_load_history.GetLastStopID();
2783 SectionList *sections = module_sp->GetSectionList();
2784 size_t section_unload_count = 0;
2785 if (sections) {
2786 const uint32_t num_sections = sections->GetNumSections(0);
2787 for (uint32_t i = 0; i < num_sections; ++i) {
2788 section_unload_count += m_section_load_history.SetSectionUnloaded(
2789 stop_id, sections->GetSectionAtIndex(i));
2790 }
2791 }
2792 return section_unload_count;
2793 }
2794
SetSectionUnloaded(const lldb::SectionSP & section_sp)2795 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) {
2796 uint32_t stop_id = 0;
2797 ProcessSP process_sp(GetProcessSP());
2798 if (process_sp)
2799 stop_id = process_sp->GetStopID();
2800 else
2801 stop_id = m_section_load_history.GetLastStopID();
2802 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2803 }
2804
SetSectionUnloaded(const lldb::SectionSP & section_sp,addr_t load_addr)2805 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp,
2806 addr_t load_addr) {
2807 uint32_t stop_id = 0;
2808 ProcessSP process_sp(GetProcessSP());
2809 if (process_sp)
2810 stop_id = process_sp->GetStopID();
2811 else
2812 stop_id = m_section_load_history.GetLastStopID();
2813 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2814 load_addr);
2815 }
2816
ClearAllLoadedSections()2817 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2818
Launch(ProcessLaunchInfo & launch_info,Stream * stream)2819 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2820 Status error;
2821 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2822
2823 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2824 launch_info.GetExecutableFile().GetPath().c_str());
2825
2826 StateType state = eStateInvalid;
2827
2828 // Scope to temporarily get the process state in case someone has manually
2829 // remotely connected already to a process and we can skip the platform
2830 // launching.
2831 {
2832 ProcessSP process_sp(GetProcessSP());
2833
2834 if (process_sp) {
2835 state = process_sp->GetState();
2836 LLDB_LOGF(log,
2837 "Target::%s the process exists, and its current state is %s",
2838 __FUNCTION__, StateAsCString(state));
2839 } else {
2840 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2841 __FUNCTION__);
2842 }
2843 }
2844
2845 launch_info.GetFlags().Set(eLaunchFlagDebug);
2846
2847 // Get the value of synchronous execution here. If you wait till after you
2848 // have started to run, then you could have hit a breakpoint, whose command
2849 // might switch the value, and then you'll pick up that incorrect value.
2850 Debugger &debugger = GetDebugger();
2851 const bool synchronous_execution =
2852 debugger.GetCommandInterpreter().GetSynchronous();
2853
2854 PlatformSP platform_sp(GetPlatform());
2855
2856 FinalizeFileActions(launch_info);
2857
2858 if (state == eStateConnected) {
2859 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2860 error.SetErrorString(
2861 "can't launch in tty when launching through a remote connection");
2862 return error;
2863 }
2864 }
2865
2866 if (!launch_info.GetArchitecture().IsValid())
2867 launch_info.GetArchitecture() = GetArchitecture();
2868
2869 // If we're not already connected to the process, and if we have a platform
2870 // that can launch a process for debugging, go ahead and do that here.
2871 if (state != eStateConnected && platform_sp &&
2872 platform_sp->CanDebugProcess()) {
2873 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2874 __FUNCTION__);
2875
2876 // If there was a previous process, delete it before we make the new one.
2877 // One subtle point, we delete the process before we release the reference
2878 // to m_process_sp. That way even if we are the last owner, the process
2879 // will get Finalized before it gets destroyed.
2880 DeleteCurrentProcess();
2881
2882 m_process_sp =
2883 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2884
2885 } else {
2886 LLDB_LOGF(log,
2887 "Target::%s the platform doesn't know how to debug a "
2888 "process, getting a process plugin to do this for us.",
2889 __FUNCTION__);
2890
2891 if (state == eStateConnected) {
2892 assert(m_process_sp);
2893 } else {
2894 // Use a Process plugin to construct the process.
2895 const char *plugin_name = launch_info.GetProcessPluginName();
2896 CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2897 }
2898
2899 // Since we didn't have a platform launch the process, launch it here.
2900 if (m_process_sp)
2901 error = m_process_sp->Launch(launch_info);
2902 }
2903
2904 if (!m_process_sp) {
2905 if (error.Success())
2906 error.SetErrorString("failed to launch or debug process");
2907 return error;
2908 }
2909
2910 if (error.Success()) {
2911 if (synchronous_execution ||
2912 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2913 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2914 if (!hijack_listener_sp) {
2915 hijack_listener_sp =
2916 Listener::MakeListener("lldb.Target.Launch.hijack");
2917 launch_info.SetHijackListener(hijack_listener_sp);
2918 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2919 }
2920
2921 StateType state = m_process_sp->WaitForProcessToStop(
2922 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
2923
2924 if (state == eStateStopped) {
2925 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2926 if (synchronous_execution) {
2927 // Now we have handled the stop-from-attach, and we are just
2928 // switching to a synchronous resume. So we should switch to the
2929 // SyncResume hijacker.
2930 m_process_sp->RestoreProcessEvents();
2931 m_process_sp->ResumeSynchronous(stream);
2932 } else {
2933 m_process_sp->RestoreProcessEvents();
2934 error = m_process_sp->PrivateResume();
2935 }
2936 if (!error.Success()) {
2937 Status error2;
2938 error2.SetErrorStringWithFormat(
2939 "process resume at entry point failed: %s", error.AsCString());
2940 error = error2;
2941 }
2942 }
2943 } else if (state == eStateExited) {
2944 bool with_shell = !!launch_info.GetShell();
2945 const int exit_status = m_process_sp->GetExitStatus();
2946 const char *exit_desc = m_process_sp->GetExitDescription();
2947 #define LAUNCH_SHELL_MESSAGE \
2948 "\n'r' and 'run' are aliases that default to launching through a " \
2949 "shell.\nTry launching without going through a shell by using 'process " \
2950 "launch'."
2951 if (exit_desc && exit_desc[0]) {
2952 if (with_shell)
2953 error.SetErrorStringWithFormat(
2954 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2955 exit_status, exit_desc);
2956 else
2957 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2958 exit_status, exit_desc);
2959 } else {
2960 if (with_shell)
2961 error.SetErrorStringWithFormat(
2962 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2963 exit_status);
2964 else
2965 error.SetErrorStringWithFormat("process exited with status %i",
2966 exit_status);
2967 }
2968 } else {
2969 error.SetErrorStringWithFormat(
2970 "initial process state wasn't stopped: %s", StateAsCString(state));
2971 }
2972 }
2973 m_process_sp->RestoreProcessEvents();
2974 } else {
2975 Status error2;
2976 error2.SetErrorStringWithFormat("process launch failed: %s",
2977 error.AsCString());
2978 error = error2;
2979 }
2980 return error;
2981 }
2982
Attach(ProcessAttachInfo & attach_info,Stream * stream)2983 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2984 auto state = eStateInvalid;
2985 auto process_sp = GetProcessSP();
2986 if (process_sp) {
2987 state = process_sp->GetState();
2988 if (process_sp->IsAlive() && state != eStateConnected) {
2989 if (state == eStateAttaching)
2990 return Status("process attach is in progress");
2991 return Status("a process is already being debugged");
2992 }
2993 }
2994
2995 const ModuleSP old_exec_module_sp = GetExecutableModule();
2996
2997 // If no process info was specified, then use the target executable name as
2998 // the process to attach to by default
2999 if (!attach_info.ProcessInfoSpecified()) {
3000 if (old_exec_module_sp)
3001 attach_info.GetExecutableFile().GetFilename() =
3002 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3003
3004 if (!attach_info.ProcessInfoSpecified()) {
3005 return Status("no process specified, create a target with a file, or "
3006 "specify the --pid or --name");
3007 }
3008 }
3009
3010 const auto platform_sp =
3011 GetDebugger().GetPlatformList().GetSelectedPlatform();
3012 ListenerSP hijack_listener_sp;
3013 const bool async = attach_info.GetAsync();
3014 if (!async) {
3015 hijack_listener_sp =
3016 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3017 attach_info.SetHijackListener(hijack_listener_sp);
3018 }
3019
3020 Status error;
3021 if (state != eStateConnected && platform_sp != nullptr &&
3022 platform_sp->CanDebugProcess()) {
3023 SetPlatform(platform_sp);
3024 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3025 } else {
3026 if (state != eStateConnected) {
3027 const char *plugin_name = attach_info.GetProcessPluginName();
3028 process_sp =
3029 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3030 plugin_name, nullptr);
3031 if (process_sp == nullptr) {
3032 error.SetErrorStringWithFormat(
3033 "failed to create process using plugin %s",
3034 (plugin_name) ? plugin_name : "null");
3035 return error;
3036 }
3037 }
3038 if (hijack_listener_sp)
3039 process_sp->HijackProcessEvents(hijack_listener_sp);
3040 error = process_sp->Attach(attach_info);
3041 }
3042
3043 if (error.Success() && process_sp) {
3044 if (async) {
3045 process_sp->RestoreProcessEvents();
3046 } else {
3047 state = process_sp->WaitForProcessToStop(
3048 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3049 process_sp->RestoreProcessEvents();
3050
3051 if (state != eStateStopped) {
3052 const char *exit_desc = process_sp->GetExitDescription();
3053 if (exit_desc)
3054 error.SetErrorStringWithFormat("%s", exit_desc);
3055 else
3056 error.SetErrorString(
3057 "process did not stop (no such process or permission problem?)");
3058 process_sp->Destroy(false);
3059 }
3060 }
3061 }
3062 return error;
3063 }
3064
FinalizeFileActions(ProcessLaunchInfo & info)3065 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3066 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3067
3068 // Finalize the file actions, and if none were given, default to opening up a
3069 // pseudo terminal
3070 PlatformSP platform_sp = GetPlatform();
3071 const bool default_to_use_pty =
3072 m_platform_sp ? m_platform_sp->IsHost() : false;
3073 LLDB_LOG(
3074 log,
3075 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3076 bool(platform_sp),
3077 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3078 default_to_use_pty);
3079
3080 // If nothing for stdin or stdout or stderr was specified, then check the
3081 // process for any default settings that were set with "settings set"
3082 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3083 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3084 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3085 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3086 "default handling");
3087
3088 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3089 // Do nothing, if we are launching in a remote terminal no file actions
3090 // should be done at all.
3091 return;
3092 }
3093
3094 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3095 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3096 "for stdin, stdout and stderr");
3097 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3098 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3099 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3100 } else {
3101 // Check for any values that might have gotten set with any of: (lldb)
3102 // settings set target.input-path (lldb) settings set target.output-path
3103 // (lldb) settings set target.error-path
3104 FileSpec in_file_spec;
3105 FileSpec out_file_spec;
3106 FileSpec err_file_spec;
3107 // Only override with the target settings if we don't already have an
3108 // action for in, out or error
3109 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3110 in_file_spec = GetStandardInputPath();
3111 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3112 out_file_spec = GetStandardOutputPath();
3113 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3114 err_file_spec = GetStandardErrorPath();
3115
3116 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3117 in_file_spec, out_file_spec, err_file_spec);
3118
3119 if (in_file_spec) {
3120 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3121 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3122 }
3123
3124 if (out_file_spec) {
3125 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3126 LLDB_LOG(log, "appended stdout open file action for {0}",
3127 out_file_spec);
3128 }
3129
3130 if (err_file_spec) {
3131 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3132 LLDB_LOG(log, "appended stderr open file action for {0}",
3133 err_file_spec);
3134 }
3135
3136 if (default_to_use_pty &&
3137 (!in_file_spec || !out_file_spec || !err_file_spec)) {
3138 llvm::Error Err = info.SetUpPtyRedirection();
3139 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3140 }
3141 }
3142 }
3143 }
3144
3145 // Target::StopHook
StopHook(lldb::TargetSP target_sp,lldb::user_id_t uid)3146 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3147 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3148 m_thread_spec_up() {}
3149
StopHook(const StopHook & rhs)3150 Target::StopHook::StopHook(const StopHook &rhs)
3151 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3152 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3153 m_thread_spec_up(), m_active(rhs.m_active),
3154 m_auto_continue(rhs.m_auto_continue) {
3155 if (rhs.m_thread_spec_up)
3156 m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up));
3157 }
3158
3159 Target::StopHook::~StopHook() = default;
3160
SetSpecifier(SymbolContextSpecifier * specifier)3161 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3162 m_specifier_sp.reset(specifier);
3163 }
3164
SetThreadSpecifier(ThreadSpec * specifier)3165 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3166 m_thread_spec_up.reset(specifier);
3167 }
3168
GetDescription(Stream * s,lldb::DescriptionLevel level) const3169 void Target::StopHook::GetDescription(Stream *s,
3170 lldb::DescriptionLevel level) const {
3171 unsigned indent_level = s->GetIndentLevel();
3172
3173 s->SetIndentLevel(indent_level + 2);
3174
3175 s->Printf("Hook: %" PRIu64 "\n", GetID());
3176 if (m_active)
3177 s->Indent("State: enabled\n");
3178 else
3179 s->Indent("State: disabled\n");
3180
3181 if (m_auto_continue)
3182 s->Indent("AutoContinue on\n");
3183
3184 if (m_specifier_sp) {
3185 s->Indent();
3186 s->PutCString("Specifier:\n");
3187 s->SetIndentLevel(indent_level + 4);
3188 m_specifier_sp->GetDescription(s, level);
3189 s->SetIndentLevel(indent_level + 2);
3190 }
3191
3192 if (m_thread_spec_up) {
3193 StreamString tmp;
3194 s->Indent("Thread:\n");
3195 m_thread_spec_up->GetDescription(&tmp, level);
3196 s->SetIndentLevel(indent_level + 4);
3197 s->Indent(tmp.GetString());
3198 s->PutCString("\n");
3199 s->SetIndentLevel(indent_level + 2);
3200 }
3201
3202 s->Indent("Commands: \n");
3203 s->SetIndentLevel(indent_level + 4);
3204 uint32_t num_commands = m_commands.GetSize();
3205 for (uint32_t i = 0; i < num_commands; i++) {
3206 s->Indent(m_commands.GetStringAtIndex(i));
3207 s->PutCString("\n");
3208 }
3209 s->SetIndentLevel(indent_level);
3210 }
3211
3212 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3213 {
3214 eNoDynamicValues,
3215 "no-dynamic-values",
3216 "Don't calculate the dynamic type of values",
3217 },
3218 {
3219 eDynamicCanRunTarget,
3220 "run-target",
3221 "Calculate the dynamic type of values "
3222 "even if you have to run the target.",
3223 },
3224 {
3225 eDynamicDontRunTarget,
3226 "no-run-target",
3227 "Calculate the dynamic type of values, but don't run the target.",
3228 },
3229 };
3230
GetDynamicValueTypes()3231 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3232 return OptionEnumValues(g_dynamic_value_types);
3233 }
3234
3235 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3236 {
3237 eInlineBreakpointsNever,
3238 "never",
3239 "Never look for inline breakpoint locations (fastest). This setting "
3240 "should only be used if you know that no inlining occurs in your"
3241 "programs.",
3242 },
3243 {
3244 eInlineBreakpointsHeaders,
3245 "headers",
3246 "Only check for inline breakpoint locations when setting breakpoints "
3247 "in header files, but not when setting breakpoint in implementation "
3248 "source files (default).",
3249 },
3250 {
3251 eInlineBreakpointsAlways,
3252 "always",
3253 "Always look for inline breakpoint locations when setting file and "
3254 "line breakpoints (slower but most accurate).",
3255 },
3256 };
3257
3258 enum x86DisassemblyFlavor {
3259 eX86DisFlavorDefault,
3260 eX86DisFlavorIntel,
3261 eX86DisFlavorATT
3262 };
3263
3264 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3265 {
3266 eX86DisFlavorDefault,
3267 "default",
3268 "Disassembler default (currently att).",
3269 },
3270 {
3271 eX86DisFlavorIntel,
3272 "intel",
3273 "Intel disassembler flavor.",
3274 },
3275 {
3276 eX86DisFlavorATT,
3277 "att",
3278 "AT&T disassembler flavor.",
3279 },
3280 };
3281
3282 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3283 {
3284 Disassembler::eHexStyleC,
3285 "c",
3286 "C-style (0xffff).",
3287 },
3288 {
3289 Disassembler::eHexStyleAsm,
3290 "asm",
3291 "Asm-style (0ffffh).",
3292 },
3293 };
3294
3295 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3296 {
3297 eLoadScriptFromSymFileTrue,
3298 "true",
3299 "Load debug scripts inside symbol files",
3300 },
3301 {
3302 eLoadScriptFromSymFileFalse,
3303 "false",
3304 "Do not load debug scripts inside symbol files.",
3305 },
3306 {
3307 eLoadScriptFromSymFileWarn,
3308 "warn",
3309 "Warn about debug scripts inside symbol files but do not load them.",
3310 },
3311 };
3312
3313 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3314 {
3315 eLoadCWDlldbinitTrue,
3316 "true",
3317 "Load .lldbinit files from current directory",
3318 },
3319 {
3320 eLoadCWDlldbinitFalse,
3321 "false",
3322 "Do not load .lldbinit files from current directory",
3323 },
3324 {
3325 eLoadCWDlldbinitWarn,
3326 "warn",
3327 "Warn about loading .lldbinit files from current directory",
3328 },
3329 };
3330
3331 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3332 {
3333 eMemoryModuleLoadLevelMinimal,
3334 "minimal",
3335 "Load minimal information when loading modules from memory. Currently "
3336 "this setting loads sections only.",
3337 },
3338 {
3339 eMemoryModuleLoadLevelPartial,
3340 "partial",
3341 "Load partial information when loading modules from memory. Currently "
3342 "this setting loads sections and function bounds.",
3343 },
3344 {
3345 eMemoryModuleLoadLevelComplete,
3346 "complete",
3347 "Load complete information when loading modules from memory. Currently "
3348 "this setting loads sections and all symbols.",
3349 },
3350 };
3351
3352 #define LLDB_PROPERTIES_target
3353 #include "TargetProperties.inc"
3354
3355 enum {
3356 #define LLDB_PROPERTIES_target
3357 #include "TargetPropertiesEnum.inc"
3358 ePropertyExperimental,
3359 };
3360
3361 class TargetOptionValueProperties : public OptionValueProperties {
3362 public:
TargetOptionValueProperties(ConstString name)3363 TargetOptionValueProperties(ConstString name)
3364 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3365
3366 // This constructor is used when creating TargetOptionValueProperties when it
3367 // is part of a new lldb_private::Target instance. It will copy all current
3368 // global property values as needed
TargetOptionValueProperties(Target * target,const TargetPropertiesSP & target_properties_sp)3369 TargetOptionValueProperties(Target *target,
3370 const TargetPropertiesSP &target_properties_sp)
3371 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3372 m_target(target), m_got_host_env(false) {}
3373
GetPropertyAtIndex(const ExecutionContext * exe_ctx,bool will_modify,uint32_t idx) const3374 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3375 bool will_modify,
3376 uint32_t idx) const override {
3377 // When getting the value for a key from the target options, we will always
3378 // try and grab the setting from the current target if there is one. Else
3379 // we just use the one from this instance.
3380 if (idx == ePropertyEnvVars)
3381 GetHostEnvironmentIfNeeded();
3382
3383 if (exe_ctx) {
3384 Target *target = exe_ctx->GetTargetPtr();
3385 if (target) {
3386 TargetOptionValueProperties *target_properties =
3387 static_cast<TargetOptionValueProperties *>(
3388 target->GetValueProperties().get());
3389 if (this != target_properties)
3390 return target_properties->ProtectedGetPropertyAtIndex(idx);
3391 }
3392 }
3393 return ProtectedGetPropertyAtIndex(idx);
3394 }
3395
GetTargetSP()3396 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3397
3398 protected:
GetHostEnvironmentIfNeeded() const3399 void GetHostEnvironmentIfNeeded() const {
3400 if (!m_got_host_env) {
3401 if (m_target) {
3402 m_got_host_env = true;
3403 const uint32_t idx = ePropertyInheritEnv;
3404 if (GetPropertyAtIndexAsBoolean(
3405 nullptr, idx, g_target_properties[idx].default_uint_value != 0)) {
3406 PlatformSP platform_sp(m_target->GetPlatform());
3407 if (platform_sp) {
3408 Environment env = platform_sp->GetEnvironment();
3409 OptionValueDictionary *env_dict =
3410 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3411 ePropertyEnvVars);
3412 if (env_dict) {
3413 const bool can_replace = false;
3414 for (const auto &KV : env) {
3415 // Don't allow existing keys to be replaced with ones we get
3416 // from the platform environment
3417 env_dict->SetValueForKey(
3418 ConstString(KV.first()),
3419 OptionValueSP(new OptionValueString(KV.second.c_str())),
3420 can_replace);
3421 }
3422 }
3423 }
3424 }
3425 }
3426 }
3427 }
3428 Target *m_target;
3429 mutable bool m_got_host_env;
3430 };
3431
3432 // TargetProperties
3433 #define LLDB_PROPERTIES_experimental
3434 #include "TargetProperties.inc"
3435
3436 enum {
3437 #define LLDB_PROPERTIES_experimental
3438 #include "TargetPropertiesEnum.inc"
3439 };
3440
3441 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3442 public:
TargetExperimentalOptionValueProperties()3443 TargetExperimentalOptionValueProperties()
3444 : OptionValueProperties(
3445 ConstString(Properties::GetExperimentalSettingsName())) {}
3446 };
3447
TargetExperimentalProperties()3448 TargetExperimentalProperties::TargetExperimentalProperties()
3449 : Properties(OptionValuePropertiesSP(
3450 new TargetExperimentalOptionValueProperties())) {
3451 m_collection_sp->Initialize(g_experimental_properties);
3452 }
3453
3454 // TargetProperties
TargetProperties(Target * target)3455 TargetProperties::TargetProperties(Target *target)
3456 : Properties(), m_launch_info() {
3457 if (target) {
3458 m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3459 target, Target::GetGlobalProperties());
3460
3461 // Set callbacks to update launch_info whenever "settins set" updated any
3462 // of these properties
3463 m_collection_sp->SetValueChangedCallback(
3464 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3465 m_collection_sp->SetValueChangedCallback(
3466 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3467 m_collection_sp->SetValueChangedCallback(
3468 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3469 m_collection_sp->SetValueChangedCallback(
3470 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3471 m_collection_sp->SetValueChangedCallback(
3472 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3473 m_collection_sp->SetValueChangedCallback(
3474 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3475 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3476 DetachOnErrorValueChangedCallback();
3477 });
3478 m_collection_sp->SetValueChangedCallback(
3479 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3480 m_collection_sp->SetValueChangedCallback(
3481 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3482
3483 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3484 m_collection_sp->AppendProperty(
3485 ConstString(Properties::GetExperimentalSettingsName()),
3486 ConstString("Experimental settings - setting these won't produce "
3487 "errors if the setting is not present."),
3488 true, m_experimental_properties_up->GetValueProperties());
3489
3490 // Update m_launch_info once it was created
3491 Arg0ValueChangedCallback();
3492 RunArgsValueChangedCallback();
3493 // EnvVarsValueChangedCallback(); // FIXME: cause segfault in
3494 // Target::GetPlatform()
3495 InputPathValueChangedCallback();
3496 OutputPathValueChangedCallback();
3497 ErrorPathValueChangedCallback();
3498 DetachOnErrorValueChangedCallback();
3499 DisableASLRValueChangedCallback();
3500 DisableSTDIOValueChangedCallback();
3501 } else {
3502 m_collection_sp =
3503 std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3504 m_collection_sp->Initialize(g_target_properties);
3505 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3506 m_collection_sp->AppendProperty(
3507 ConstString(Properties::GetExperimentalSettingsName()),
3508 ConstString("Experimental settings - setting these won't produce "
3509 "errors if the setting is not present."),
3510 true, m_experimental_properties_up->GetValueProperties());
3511 m_collection_sp->AppendProperty(
3512 ConstString("process"), ConstString("Settings specific to processes."),
3513 true, Process::GetGlobalProperties()->GetValueProperties());
3514 }
3515 }
3516
3517 TargetProperties::~TargetProperties() = default;
3518
GetInjectLocalVariables(ExecutionContext * exe_ctx) const3519 bool TargetProperties::GetInjectLocalVariables(
3520 ExecutionContext *exe_ctx) const {
3521 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3522 exe_ctx, false, ePropertyExperimental);
3523 OptionValueProperties *exp_values =
3524 exp_property->GetValue()->GetAsProperties();
3525 if (exp_values)
3526 return exp_values->GetPropertyAtIndexAsBoolean(
3527 exe_ctx, ePropertyInjectLocalVars, true);
3528 else
3529 return true;
3530 }
3531
SetInjectLocalVariables(ExecutionContext * exe_ctx,bool b)3532 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3533 bool b) {
3534 const Property *exp_property =
3535 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3536 OptionValueProperties *exp_values =
3537 exp_property->GetValue()->GetAsProperties();
3538 if (exp_values)
3539 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3540 true);
3541 }
3542
GetDefaultArchitecture() const3543 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3544 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3545 nullptr, ePropertyDefaultArch);
3546 if (value)
3547 return value->GetCurrentValue();
3548 return ArchSpec();
3549 }
3550
SetDefaultArchitecture(const ArchSpec & arch)3551 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3552 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3553 nullptr, ePropertyDefaultArch);
3554 if (value)
3555 return value->SetCurrentValue(arch, true);
3556 }
3557
GetMoveToNearestCode() const3558 bool TargetProperties::GetMoveToNearestCode() const {
3559 const uint32_t idx = ePropertyMoveToNearestCode;
3560 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3561 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3562 }
3563
GetPreferDynamicValue() const3564 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3565 const uint32_t idx = ePropertyPreferDynamic;
3566 return (lldb::DynamicValueType)
3567 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3568 nullptr, idx, g_target_properties[idx].default_uint_value);
3569 }
3570
SetPreferDynamicValue(lldb::DynamicValueType d)3571 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3572 const uint32_t idx = ePropertyPreferDynamic;
3573 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3574 }
3575
GetPreloadSymbols() const3576 bool TargetProperties::GetPreloadSymbols() const {
3577 const uint32_t idx = ePropertyPreloadSymbols;
3578 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3579 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3580 }
3581
SetPreloadSymbols(bool b)3582 void TargetProperties::SetPreloadSymbols(bool b) {
3583 const uint32_t idx = ePropertyPreloadSymbols;
3584 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3585 }
3586
GetDisableASLR() const3587 bool TargetProperties::GetDisableASLR() const {
3588 const uint32_t idx = ePropertyDisableASLR;
3589 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3590 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3591 }
3592
SetDisableASLR(bool b)3593 void TargetProperties::SetDisableASLR(bool b) {
3594 const uint32_t idx = ePropertyDisableASLR;
3595 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3596 }
3597
GetDetachOnError() const3598 bool TargetProperties::GetDetachOnError() const {
3599 const uint32_t idx = ePropertyDetachOnError;
3600 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3601 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3602 }
3603
SetDetachOnError(bool b)3604 void TargetProperties::SetDetachOnError(bool b) {
3605 const uint32_t idx = ePropertyDetachOnError;
3606 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3607 }
3608
GetDisableSTDIO() const3609 bool TargetProperties::GetDisableSTDIO() const {
3610 const uint32_t idx = ePropertyDisableSTDIO;
3611 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3612 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3613 }
3614
SetDisableSTDIO(bool b)3615 void TargetProperties::SetDisableSTDIO(bool b) {
3616 const uint32_t idx = ePropertyDisableSTDIO;
3617 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3618 }
3619
GetDisassemblyFlavor() const3620 const char *TargetProperties::GetDisassemblyFlavor() const {
3621 const uint32_t idx = ePropertyDisassemblyFlavor;
3622 const char *return_value;
3623
3624 x86DisassemblyFlavor flavor_value =
3625 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3626 nullptr, idx, g_target_properties[idx].default_uint_value);
3627 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3628 return return_value;
3629 }
3630
GetInlineStrategy() const3631 InlineStrategy TargetProperties::GetInlineStrategy() const {
3632 const uint32_t idx = ePropertyInlineStrategy;
3633 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3634 nullptr, idx, g_target_properties[idx].default_uint_value);
3635 }
3636
GetArg0() const3637 llvm::StringRef TargetProperties::GetArg0() const {
3638 const uint32_t idx = ePropertyArg0;
3639 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3640 llvm::StringRef());
3641 }
3642
SetArg0(llvm::StringRef arg)3643 void TargetProperties::SetArg0(llvm::StringRef arg) {
3644 const uint32_t idx = ePropertyArg0;
3645 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3646 m_launch_info.SetArg0(arg);
3647 }
3648
GetRunArguments(Args & args) const3649 bool TargetProperties::GetRunArguments(Args &args) const {
3650 const uint32_t idx = ePropertyRunArgs;
3651 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3652 }
3653
SetRunArguments(const Args & args)3654 void TargetProperties::SetRunArguments(const Args &args) {
3655 const uint32_t idx = ePropertyRunArgs;
3656 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3657 m_launch_info.GetArguments() = args;
3658 }
3659
GetEnvironment() const3660 Environment TargetProperties::GetEnvironment() const {
3661 // TODO: Get rid of the Args intermediate step
3662 Args env;
3663 const uint32_t idx = ePropertyEnvVars;
3664 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3665 return Environment(env);
3666 }
3667
SetEnvironment(Environment env)3668 void TargetProperties::SetEnvironment(Environment env) {
3669 // TODO: Get rid of the Args intermediate step
3670 const uint32_t idx = ePropertyEnvVars;
3671 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3672 m_launch_info.GetEnvironment() = std::move(env);
3673 }
3674
GetSkipPrologue() const3675 bool TargetProperties::GetSkipPrologue() const {
3676 const uint32_t idx = ePropertySkipPrologue;
3677 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3678 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3679 }
3680
GetSourcePathMap() const3681 PathMappingList &TargetProperties::GetSourcePathMap() const {
3682 const uint32_t idx = ePropertySourceMap;
3683 OptionValuePathMappings *option_value =
3684 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3685 false, idx);
3686 assert(option_value);
3687 return option_value->GetCurrentValue();
3688 }
3689
AppendExecutableSearchPaths(const FileSpec & dir)3690 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3691 const uint32_t idx = ePropertyExecutableSearchPaths;
3692 OptionValueFileSpecList *option_value =
3693 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3694 false, idx);
3695 assert(option_value);
3696 option_value->AppendCurrentValue(dir);
3697 }
3698
GetExecutableSearchPaths()3699 FileSpecList TargetProperties::GetExecutableSearchPaths() {
3700 const uint32_t idx = ePropertyExecutableSearchPaths;
3701 const OptionValueFileSpecList *option_value =
3702 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3703 false, idx);
3704 assert(option_value);
3705 return option_value->GetCurrentValue();
3706 }
3707
GetDebugFileSearchPaths()3708 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
3709 const uint32_t idx = ePropertyDebugFileSearchPaths;
3710 const OptionValueFileSpecList *option_value =
3711 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3712 false, idx);
3713 assert(option_value);
3714 return option_value->GetCurrentValue();
3715 }
3716
GetClangModuleSearchPaths()3717 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
3718 const uint32_t idx = ePropertyClangModuleSearchPaths;
3719 const OptionValueFileSpecList *option_value =
3720 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3721 false, idx);
3722 assert(option_value);
3723 return option_value->GetCurrentValue();
3724 }
3725
GetEnableAutoImportClangModules() const3726 bool TargetProperties::GetEnableAutoImportClangModules() const {
3727 const uint32_t idx = ePropertyAutoImportClangModules;
3728 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3729 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3730 }
3731
GetEnableImportStdModule() const3732 bool TargetProperties::GetEnableImportStdModule() const {
3733 const uint32_t idx = ePropertyImportStdModule;
3734 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3735 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3736 }
3737
GetEnableAutoApplyFixIts() const3738 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3739 const uint32_t idx = ePropertyAutoApplyFixIts;
3740 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3741 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3742 }
3743
GetEnableNotifyAboutFixIts() const3744 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3745 const uint32_t idx = ePropertyNotifyAboutFixIts;
3746 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3747 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3748 }
3749
GetEnableSaveObjects() const3750 bool TargetProperties::GetEnableSaveObjects() const {
3751 const uint32_t idx = ePropertySaveObjects;
3752 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3753 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3754 }
3755
GetEnableSyntheticValue() const3756 bool TargetProperties::GetEnableSyntheticValue() const {
3757 const uint32_t idx = ePropertyEnableSynthetic;
3758 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3759 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3760 }
3761
GetMaxZeroPaddingInFloatFormat() const3762 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
3763 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
3764 return m_collection_sp->GetPropertyAtIndexAsUInt64(
3765 nullptr, idx, g_target_properties[idx].default_uint_value);
3766 }
3767
GetMaximumNumberOfChildrenToDisplay() const3768 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3769 const uint32_t idx = ePropertyMaxChildrenCount;
3770 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3771 nullptr, idx, g_target_properties[idx].default_uint_value);
3772 }
3773
GetMaximumSizeOfStringSummary() const3774 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3775 const uint32_t idx = ePropertyMaxSummaryLength;
3776 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3777 nullptr, idx, g_target_properties[idx].default_uint_value);
3778 }
3779
GetMaximumMemReadSize() const3780 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3781 const uint32_t idx = ePropertyMaxMemReadSize;
3782 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3783 nullptr, idx, g_target_properties[idx].default_uint_value);
3784 }
3785
GetStandardInputPath() const3786 FileSpec TargetProperties::GetStandardInputPath() const {
3787 const uint32_t idx = ePropertyInputPath;
3788 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3789 }
3790
SetStandardInputPath(llvm::StringRef path)3791 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3792 const uint32_t idx = ePropertyInputPath;
3793 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3794 }
3795
GetStandardOutputPath() const3796 FileSpec TargetProperties::GetStandardOutputPath() const {
3797 const uint32_t idx = ePropertyOutputPath;
3798 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3799 }
3800
SetStandardOutputPath(llvm::StringRef path)3801 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3802 const uint32_t idx = ePropertyOutputPath;
3803 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3804 }
3805
GetStandardErrorPath() const3806 FileSpec TargetProperties::GetStandardErrorPath() const {
3807 const uint32_t idx = ePropertyErrorPath;
3808 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3809 }
3810
SetStandardErrorPath(llvm::StringRef path)3811 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3812 const uint32_t idx = ePropertyErrorPath;
3813 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3814 }
3815
GetLanguage() const3816 LanguageType TargetProperties::GetLanguage() const {
3817 OptionValueLanguage *value =
3818 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3819 nullptr, ePropertyLanguage);
3820 if (value)
3821 return value->GetCurrentValue();
3822 return LanguageType();
3823 }
3824
GetExpressionPrefixContents()3825 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
3826 const uint32_t idx = ePropertyExprPrefix;
3827 OptionValueFileSpec *file =
3828 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3829 idx);
3830 if (file) {
3831 DataBufferSP data_sp(file->GetFileContents());
3832 if (data_sp)
3833 return llvm::StringRef(
3834 reinterpret_cast<const char *>(data_sp->GetBytes()),
3835 data_sp->GetByteSize());
3836 }
3837 return "";
3838 }
3839
GetBreakpointsConsultPlatformAvoidList()3840 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3841 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3842 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3843 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3844 }
3845
GetUseHexImmediates() const3846 bool TargetProperties::GetUseHexImmediates() const {
3847 const uint32_t idx = ePropertyUseHexImmediates;
3848 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3849 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3850 }
3851
GetUseFastStepping() const3852 bool TargetProperties::GetUseFastStepping() const {
3853 const uint32_t idx = ePropertyUseFastStepping;
3854 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3855 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3856 }
3857
GetDisplayExpressionsInCrashlogs() const3858 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3859 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3860 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3861 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3862 }
3863
GetLoadScriptFromSymbolFile() const3864 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3865 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3866 return (LoadScriptFromSymFile)
3867 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3868 nullptr, idx, g_target_properties[idx].default_uint_value);
3869 }
3870
GetLoadCWDlldbinitFile() const3871 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3872 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3873 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3874 nullptr, idx, g_target_properties[idx].default_uint_value);
3875 }
3876
GetHexImmediateStyle() const3877 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3878 const uint32_t idx = ePropertyHexImmediateStyle;
3879 return (Disassembler::HexImmediateStyle)
3880 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3881 nullptr, idx, g_target_properties[idx].default_uint_value);
3882 }
3883
GetMemoryModuleLoadLevel() const3884 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3885 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3886 return (MemoryModuleLoadLevel)
3887 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3888 nullptr, idx, g_target_properties[idx].default_uint_value);
3889 }
3890
GetUserSpecifiedTrapHandlerNames(Args & args) const3891 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3892 const uint32_t idx = ePropertyTrapHandlerNames;
3893 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3894 }
3895
SetUserSpecifiedTrapHandlerNames(const Args & args)3896 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3897 const uint32_t idx = ePropertyTrapHandlerNames;
3898 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3899 }
3900
GetDisplayRuntimeSupportValues() const3901 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3902 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3903 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3904 }
3905
SetDisplayRuntimeSupportValues(bool b)3906 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3907 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3908 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3909 }
3910
GetDisplayRecognizedArguments() const3911 bool TargetProperties::GetDisplayRecognizedArguments() const {
3912 const uint32_t idx = ePropertyDisplayRecognizedArguments;
3913 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3914 }
3915
SetDisplayRecognizedArguments(bool b)3916 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
3917 const uint32_t idx = ePropertyDisplayRecognizedArguments;
3918 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3919 }
3920
GetNonStopModeEnabled() const3921 bool TargetProperties::GetNonStopModeEnabled() const {
3922 const uint32_t idx = ePropertyNonStopModeEnabled;
3923 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3924 }
3925
SetNonStopModeEnabled(bool b)3926 void TargetProperties::SetNonStopModeEnabled(bool b) {
3927 const uint32_t idx = ePropertyNonStopModeEnabled;
3928 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3929 }
3930
GetProcessLaunchInfo()3931 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3932 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3933 return m_launch_info;
3934 }
3935
SetProcessLaunchInfo(const ProcessLaunchInfo & launch_info)3936 void TargetProperties::SetProcessLaunchInfo(
3937 const ProcessLaunchInfo &launch_info) {
3938 m_launch_info = launch_info;
3939 SetArg0(launch_info.GetArg0());
3940 SetRunArguments(launch_info.GetArguments());
3941 SetEnvironment(launch_info.GetEnvironment());
3942 const FileAction *input_file_action =
3943 launch_info.GetFileActionForFD(STDIN_FILENO);
3944 if (input_file_action) {
3945 SetStandardInputPath(input_file_action->GetPath());
3946 }
3947 const FileAction *output_file_action =
3948 launch_info.GetFileActionForFD(STDOUT_FILENO);
3949 if (output_file_action) {
3950 SetStandardOutputPath(output_file_action->GetPath());
3951 }
3952 const FileAction *error_file_action =
3953 launch_info.GetFileActionForFD(STDERR_FILENO);
3954 if (error_file_action) {
3955 SetStandardErrorPath(error_file_action->GetPath());
3956 }
3957 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3958 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3959 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
3960 }
3961
GetRequireHardwareBreakpoints() const3962 bool TargetProperties::GetRequireHardwareBreakpoints() const {
3963 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3964 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3965 nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3966 }
3967
SetRequireHardwareBreakpoints(bool b)3968 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
3969 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3970 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3971 }
3972
Arg0ValueChangedCallback()3973 void TargetProperties::Arg0ValueChangedCallback() {
3974 m_launch_info.SetArg0(GetArg0());
3975 }
3976
RunArgsValueChangedCallback()3977 void TargetProperties::RunArgsValueChangedCallback() {
3978 Args args;
3979 if (GetRunArguments(args))
3980 m_launch_info.GetArguments() = args;
3981 }
3982
EnvVarsValueChangedCallback()3983 void TargetProperties::EnvVarsValueChangedCallback() {
3984 m_launch_info.GetEnvironment() = GetEnvironment();
3985 }
3986
InputPathValueChangedCallback()3987 void TargetProperties::InputPathValueChangedCallback() {
3988 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
3989 false);
3990 }
3991
OutputPathValueChangedCallback()3992 void TargetProperties::OutputPathValueChangedCallback() {
3993 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
3994 false, true);
3995 }
3996
ErrorPathValueChangedCallback()3997 void TargetProperties::ErrorPathValueChangedCallback() {
3998 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
3999 false, true);
4000 }
4001
DetachOnErrorValueChangedCallback()4002 void TargetProperties::DetachOnErrorValueChangedCallback() {
4003 if (GetDetachOnError())
4004 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4005 else
4006 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4007 }
4008
DisableASLRValueChangedCallback()4009 void TargetProperties::DisableASLRValueChangedCallback() {
4010 if (GetDisableASLR())
4011 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4012 else
4013 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4014 }
4015
DisableSTDIOValueChangedCallback()4016 void TargetProperties::DisableSTDIOValueChangedCallback() {
4017 if (GetDisableSTDIO())
4018 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4019 else
4020 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4021 }
4022
4023 // Target::TargetEventData
4024
TargetEventData(const lldb::TargetSP & target_sp)4025 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4026 : EventData(), m_target_sp(target_sp), m_module_list() {}
4027
TargetEventData(const lldb::TargetSP & target_sp,const ModuleList & module_list)4028 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4029 const ModuleList &module_list)
4030 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4031
4032 Target::TargetEventData::~TargetEventData() = default;
4033
GetFlavorString()4034 ConstString Target::TargetEventData::GetFlavorString() {
4035 static ConstString g_flavor("Target::TargetEventData");
4036 return g_flavor;
4037 }
4038
Dump(Stream * s) const4039 void Target::TargetEventData::Dump(Stream *s) const {
4040 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4041 if (i != 0)
4042 *s << ", ";
4043 m_module_list.GetModuleAtIndex(i)->GetDescription(
4044 s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4045 }
4046 }
4047
4048 const Target::TargetEventData *
GetEventDataFromEvent(const Event * event_ptr)4049 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4050 if (event_ptr) {
4051 const EventData *event_data = event_ptr->GetData();
4052 if (event_data &&
4053 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4054 return static_cast<const TargetEventData *>(event_ptr->GetData());
4055 }
4056 return nullptr;
4057 }
4058
GetTargetFromEvent(const Event * event_ptr)4059 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4060 TargetSP target_sp;
4061 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4062 if (event_data)
4063 target_sp = event_data->m_target_sp;
4064 return target_sp;
4065 }
4066
4067 ModuleList
GetModuleListFromEvent(const Event * event_ptr)4068 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4069 ModuleList module_list;
4070 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4071 if (event_data)
4072 module_list = event_data->m_module_list;
4073 return module_list;
4074 }
4075
GetAPIMutex()4076 std::recursive_mutex &Target::GetAPIMutex() {
4077 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4078 return m_private_mutex;
4079 else
4080 return m_mutex;
4081 }
4082