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