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