Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lldb / source / Target / Target.cpp
blob5f8756c57675c9518f3a36f0687042473ac4f17d
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 //===----------------------------------------------------------------------===//
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/ValueObject.h"
28 #include "lldb/Core/ValueObjectConstResult.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/OptionGroupWatchpoint.h"
40 #include "lldb/Interpreter/OptionValues.h"
41 #include "lldb/Interpreter/Property.h"
42 #include "lldb/Symbol/Function.h"
43 #include "lldb/Symbol/ObjectFile.h"
44 #include "lldb/Symbol/Symbol.h"
45 #include "lldb/Target/ABI.h"
46 #include "lldb/Target/Language.h"
47 #include "lldb/Target/LanguageRuntime.h"
48 #include "lldb/Target/Process.h"
49 #include "lldb/Target/RegisterTypeBuilder.h"
50 #include "lldb/Target/SectionLoadList.h"
51 #include "lldb/Target/StackFrame.h"
52 #include "lldb/Target/StackFrameRecognizer.h"
53 #include "lldb/Target/SystemRuntime.h"
54 #include "lldb/Target/Thread.h"
55 #include "lldb/Target/ThreadSpec.h"
56 #include "lldb/Target/UnixSignals.h"
57 #include "lldb/Utility/Event.h"
58 #include "lldb/Utility/FileSpec.h"
59 #include "lldb/Utility/LLDBAssert.h"
60 #include "lldb/Utility/LLDBLog.h"
61 #include "lldb/Utility/Log.h"
62 #include "lldb/Utility/State.h"
63 #include "lldb/Utility/StreamString.h"
64 #include "lldb/Utility/Timer.h"
66 #include "llvm/ADT/ScopeExit.h"
67 #include "llvm/ADT/SetVector.h"
69 #include <memory>
70 #include <mutex>
71 #include <optional>
72 #include <sstream>
74 using namespace lldb;
75 using namespace lldb_private;
77 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
79 Target::Arch::Arch(const ArchSpec &spec)
80 : m_spec(spec),
81 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
83 const Target::Arch &Target::Arch::operator=(const ArchSpec &spec) {
84 m_spec = spec;
85 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
86 return *this;
89 ConstString &Target::GetStaticBroadcasterClass() {
90 static ConstString class_name("lldb.target");
91 return class_name;
94 Target::Target(Debugger &debugger, const ArchSpec &target_arch,
95 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
96 : TargetProperties(this),
97 Broadcaster(debugger.GetBroadcasterManager(),
98 Target::GetStaticBroadcasterClass().AsCString()),
99 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
100 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
101 m_breakpoint_list(false), m_internal_breakpoint_list(true),
102 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
103 m_image_search_paths(ImageSearchPathsChanged, this),
104 m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0),
105 m_latest_stop_hook_id(0), m_valid(true), m_suppress_stop_hooks(false),
106 m_is_dummy_target(is_dummy_target),
107 m_frame_recognizer_manager_up(
108 std::make_unique<StackFrameRecognizerManager>()) {
109 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
110 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
111 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
112 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
113 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
115 CheckInWithManager();
117 LLDB_LOG(GetLog(LLDBLog::Object), "{0} Target::Target()",
118 static_cast<void *>(this));
119 if (target_arch.IsValid()) {
120 LLDB_LOG(GetLog(LLDBLog::Target),
121 "Target::Target created with architecture {0} ({1})",
122 target_arch.GetArchitectureName(),
123 target_arch.GetTriple().getTriple().c_str());
126 UpdateLaunchInfoFromProperties();
129 Target::~Target() {
130 Log *log = GetLog(LLDBLog::Object);
131 LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
132 DeleteCurrentProcess();
135 void Target::PrimeFromDummyTarget(Target &target) {
136 m_stop_hooks = target.m_stop_hooks;
138 for (const auto &breakpoint_sp : target.m_breakpoint_list.Breakpoints()) {
139 if (breakpoint_sp->IsInternal())
140 continue;
142 BreakpointSP new_bp(
143 Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp));
144 AddBreakpoint(std::move(new_bp), false);
147 for (const auto &bp_name_entry : target.m_breakpoint_names) {
148 AddBreakpointName(std::make_unique<BreakpointName>(*bp_name_entry.second));
151 m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>(
152 *target.m_frame_recognizer_manager_up);
154 m_dummy_signals = target.m_dummy_signals;
157 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
158 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
159 if (description_level != lldb::eDescriptionLevelBrief) {
160 s->Indent();
161 s->PutCString("Target\n");
162 s->IndentMore();
163 m_images.Dump(s);
164 m_breakpoint_list.Dump(s);
165 m_internal_breakpoint_list.Dump(s);
166 s->IndentLess();
167 } else {
168 Module *exe_module = GetExecutableModulePointer();
169 if (exe_module)
170 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
171 else
172 s->PutCString("No executable module.");
176 void Target::CleanupProcess() {
177 // Do any cleanup of the target we need to do between process instances.
178 // NB It is better to do this before destroying the process in case the
179 // clean up needs some help from the process.
180 m_breakpoint_list.ClearAllBreakpointSites();
181 m_internal_breakpoint_list.ClearAllBreakpointSites();
182 ResetBreakpointHitCounts();
183 // Disable watchpoints just on the debugger side.
184 std::unique_lock<std::recursive_mutex> lock;
185 this->GetWatchpointList().GetListMutex(lock);
186 DisableAllWatchpoints(false);
187 ClearAllWatchpointHitCounts();
188 ClearAllWatchpointHistoricValues();
189 m_latest_stop_hook_id = 0;
192 void Target::DeleteCurrentProcess() {
193 if (m_process_sp) {
194 // We dispose any active tracing sessions on the current process
195 m_trace_sp.reset();
196 m_section_load_history.Clear();
197 if (m_process_sp->IsAlive())
198 m_process_sp->Destroy(false);
200 m_process_sp->Finalize();
202 CleanupProcess();
204 m_process_sp.reset();
208 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
209 llvm::StringRef plugin_name,
210 const FileSpec *crash_file,
211 bool can_connect) {
212 if (!listener_sp)
213 listener_sp = GetDebugger().GetListener();
214 DeleteCurrentProcess();
215 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
216 listener_sp, crash_file, can_connect);
217 return m_process_sp;
220 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
222 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
223 const char *repl_options, bool can_create) {
224 if (language == eLanguageTypeUnknown)
225 language = m_debugger.GetREPLLanguage();
227 if (language == eLanguageTypeUnknown) {
228 LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
230 if (auto single_lang = repl_languages.GetSingularLanguage()) {
231 language = *single_lang;
232 } else if (repl_languages.Empty()) {
233 err.SetErrorString(
234 "LLDB isn't configured with REPL support for any languages.");
235 return REPLSP();
236 } else {
237 err.SetErrorString(
238 "Multiple possible REPL languages. Please specify a language.");
239 return REPLSP();
243 REPLMap::iterator pos = m_repl_map.find(language);
245 if (pos != m_repl_map.end()) {
246 return pos->second;
249 if (!can_create) {
250 err.SetErrorStringWithFormat(
251 "Couldn't find an existing REPL for %s, and can't create a new one",
252 Language::GetNameForLanguageType(language));
253 return lldb::REPLSP();
256 Debugger *const debugger = nullptr;
257 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
259 if (ret) {
260 m_repl_map[language] = ret;
261 return m_repl_map[language];
264 if (err.Success()) {
265 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
266 Language::GetNameForLanguageType(language));
269 return lldb::REPLSP();
272 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
273 lldbassert(!m_repl_map.count(language));
275 m_repl_map[language] = repl_sp;
278 void Target::Destroy() {
279 std::lock_guard<std::recursive_mutex> guard(m_mutex);
280 m_valid = false;
281 DeleteCurrentProcess();
282 m_platform_sp.reset();
283 m_arch = ArchSpec();
284 ClearModules(true);
285 m_section_load_history.Clear();
286 const bool notify = false;
287 m_breakpoint_list.RemoveAll(notify);
288 m_internal_breakpoint_list.RemoveAll(notify);
289 m_last_created_breakpoint.reset();
290 m_watchpoint_list.RemoveAll(notify);
291 m_last_created_watchpoint.reset();
292 m_search_filter_sp.reset();
293 m_image_search_paths.Clear(notify);
294 m_stop_hooks.clear();
295 m_stop_hook_next_id = 0;
296 m_suppress_stop_hooks = false;
297 m_repl_map.clear();
298 Args signal_args;
299 ClearDummySignals(signal_args);
302 llvm::StringRef Target::GetABIName() const {
303 lldb::ABISP abi_sp;
304 if (m_process_sp)
305 abi_sp = m_process_sp->GetABI();
306 if (!abi_sp)
307 abi_sp = ABI::FindPlugin(ProcessSP(), GetArchitecture());
308 if (abi_sp)
309 return abi_sp->GetPluginName();
310 return {};
313 BreakpointList &Target::GetBreakpointList(bool internal) {
314 if (internal)
315 return m_internal_breakpoint_list;
316 else
317 return m_breakpoint_list;
320 const BreakpointList &Target::GetBreakpointList(bool internal) const {
321 if (internal)
322 return m_internal_breakpoint_list;
323 else
324 return m_breakpoint_list;
327 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
328 BreakpointSP bp_sp;
330 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
331 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
332 else
333 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
335 return bp_sp;
338 lldb::BreakpointSP
339 lldb_private::Target::CreateBreakpointAtUserEntry(Status &error) {
340 ModuleSP main_module_sp = GetExecutableModule();
341 FileSpecList shared_lib_filter;
342 shared_lib_filter.Append(main_module_sp->GetFileSpec());
343 llvm::SetVector<std::string, std::vector<std::string>,
344 std::unordered_set<std::string>>
345 entryPointNamesSet;
346 for (LanguageType lang_type : Language::GetSupportedLanguages()) {
347 Language *lang = Language::FindPlugin(lang_type);
348 if (!lang) {
349 error.SetErrorString("Language not found\n");
350 return lldb::BreakpointSP();
352 std::string entryPointName = lang->GetUserEntryPointName().str();
353 if (!entryPointName.empty())
354 entryPointNamesSet.insert(entryPointName);
356 if (entryPointNamesSet.empty()) {
357 error.SetErrorString("No entry point name found\n");
358 return lldb::BreakpointSP();
360 BreakpointSP bp_sp = CreateBreakpoint(
361 &shared_lib_filter,
362 /*containingSourceFiles=*/nullptr, entryPointNamesSet.takeVector(),
363 /*func_name_type_mask=*/eFunctionNameTypeFull,
364 /*language=*/eLanguageTypeUnknown,
365 /*offset=*/0,
366 /*skip_prologue=*/eLazyBoolNo,
367 /*internal=*/false,
368 /*hardware=*/false);
369 if (!bp_sp) {
370 error.SetErrorString("Breakpoint creation failed.\n");
371 return lldb::BreakpointSP();
373 bp_sp->SetOneShot(true);
374 return bp_sp;
377 BreakpointSP Target::CreateSourceRegexBreakpoint(
378 const FileSpecList *containingModules,
379 const FileSpecList *source_file_spec_list,
380 const std::unordered_set<std::string> &function_names,
381 RegularExpression source_regex, bool internal, bool hardware,
382 LazyBool move_to_nearest_code) {
383 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
384 containingModules, source_file_spec_list));
385 if (move_to_nearest_code == eLazyBoolCalculate)
386 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
387 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
388 nullptr, std::move(source_regex), function_names,
389 !static_cast<bool>(move_to_nearest_code)));
391 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
394 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
395 const FileSpec &file, uint32_t line_no,
396 uint32_t column, lldb::addr_t offset,
397 LazyBool check_inlines,
398 LazyBool skip_prologue, bool internal,
399 bool hardware,
400 LazyBool move_to_nearest_code) {
401 FileSpec remapped_file;
402 std::optional<llvm::StringRef> removed_prefix_opt =
403 GetSourcePathMap().ReverseRemapPath(file, remapped_file);
404 if (!removed_prefix_opt)
405 remapped_file = file;
407 if (check_inlines == eLazyBoolCalculate) {
408 const InlineStrategy inline_strategy = GetInlineStrategy();
409 switch (inline_strategy) {
410 case eInlineBreakpointsNever:
411 check_inlines = eLazyBoolNo;
412 break;
414 case eInlineBreakpointsHeaders:
415 if (remapped_file.IsSourceImplementationFile())
416 check_inlines = eLazyBoolNo;
417 else
418 check_inlines = eLazyBoolYes;
419 break;
421 case eInlineBreakpointsAlways:
422 check_inlines = eLazyBoolYes;
423 break;
426 SearchFilterSP filter_sp;
427 if (check_inlines == eLazyBoolNo) {
428 // Not checking for inlines, we are looking only for matching compile units
429 FileSpecList compile_unit_list;
430 compile_unit_list.Append(remapped_file);
431 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
432 &compile_unit_list);
433 } else {
434 filter_sp = GetSearchFilterForModuleList(containingModules);
436 if (skip_prologue == eLazyBoolCalculate)
437 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
438 if (move_to_nearest_code == eLazyBoolCalculate)
439 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
441 SourceLocationSpec location_spec(remapped_file, line_no, column,
442 check_inlines,
443 !static_cast<bool>(move_to_nearest_code));
444 if (!location_spec)
445 return nullptr;
447 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
448 nullptr, offset, skip_prologue, location_spec, removed_prefix_opt));
449 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
452 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
453 bool hardware) {
454 Address so_addr;
456 // Check for any reason we want to move this breakpoint to other address.
457 addr = GetBreakableLoadAddress(addr);
459 // Attempt to resolve our load address if possible, though it is ok if it
460 // doesn't resolve to section/offset.
462 // Try and resolve as a load address if possible
463 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
464 if (!so_addr.IsValid()) {
465 // The address didn't resolve, so just set this as an absolute address
466 so_addr.SetOffset(addr);
468 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
469 return bp_sp;
472 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
473 bool hardware) {
474 SearchFilterSP filter_sp(
475 new SearchFilterForUnconstrainedSearches(shared_from_this()));
476 BreakpointResolverSP resolver_sp(
477 new BreakpointResolverAddress(nullptr, addr));
478 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
481 lldb::BreakpointSP
482 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
483 const FileSpec &file_spec,
484 bool request_hardware) {
485 SearchFilterSP filter_sp(
486 new SearchFilterForUnconstrainedSearches(shared_from_this()));
487 BreakpointResolverSP resolver_sp(new BreakpointResolverAddress(
488 nullptr, file_addr, file_spec));
489 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
490 false);
493 BreakpointSP Target::CreateBreakpoint(
494 const FileSpecList *containingModules,
495 const FileSpecList *containingSourceFiles, const char *func_name,
496 FunctionNameType func_name_type_mask, LanguageType language,
497 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
498 BreakpointSP bp_sp;
499 if (func_name) {
500 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
501 containingModules, containingSourceFiles));
503 if (skip_prologue == eLazyBoolCalculate)
504 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
505 if (language == lldb::eLanguageTypeUnknown)
506 language = GetLanguage();
508 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
509 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
510 offset, skip_prologue));
511 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
513 return bp_sp;
516 lldb::BreakpointSP
517 Target::CreateBreakpoint(const FileSpecList *containingModules,
518 const FileSpecList *containingSourceFiles,
519 const std::vector<std::string> &func_names,
520 FunctionNameType func_name_type_mask,
521 LanguageType language, lldb::addr_t offset,
522 LazyBool skip_prologue, bool internal, bool hardware) {
523 BreakpointSP bp_sp;
524 size_t num_names = func_names.size();
525 if (num_names > 0) {
526 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
527 containingModules, containingSourceFiles));
529 if (skip_prologue == eLazyBoolCalculate)
530 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
531 if (language == lldb::eLanguageTypeUnknown)
532 language = GetLanguage();
534 BreakpointResolverSP resolver_sp(
535 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
536 language, offset, skip_prologue));
537 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
539 return bp_sp;
542 BreakpointSP
543 Target::CreateBreakpoint(const FileSpecList *containingModules,
544 const FileSpecList *containingSourceFiles,
545 const char *func_names[], size_t num_names,
546 FunctionNameType func_name_type_mask,
547 LanguageType language, lldb::addr_t offset,
548 LazyBool skip_prologue, bool internal, bool hardware) {
549 BreakpointSP bp_sp;
550 if (num_names > 0) {
551 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
552 containingModules, containingSourceFiles));
554 if (skip_prologue == eLazyBoolCalculate) {
555 if (offset == 0)
556 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
557 else
558 skip_prologue = eLazyBoolNo;
560 if (language == lldb::eLanguageTypeUnknown)
561 language = GetLanguage();
563 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
564 nullptr, func_names, num_names, func_name_type_mask, language, offset,
565 skip_prologue));
566 resolver_sp->SetOffset(offset);
567 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
569 return bp_sp;
572 SearchFilterSP
573 Target::GetSearchFilterForModule(const FileSpec *containingModule) {
574 SearchFilterSP filter_sp;
575 if (containingModule != nullptr) {
576 // TODO: We should look into sharing module based search filters
577 // across many breakpoints like we do for the simple target based one
578 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
579 *containingModule);
580 } else {
581 if (!m_search_filter_sp)
582 m_search_filter_sp =
583 std::make_shared<SearchFilterForUnconstrainedSearches>(
584 shared_from_this());
585 filter_sp = m_search_filter_sp;
587 return filter_sp;
590 SearchFilterSP
591 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
592 SearchFilterSP filter_sp;
593 if (containingModules && containingModules->GetSize() != 0) {
594 // TODO: We should look into sharing module based search filters
595 // across many breakpoints like we do for the simple target based one
596 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
597 *containingModules);
598 } else {
599 if (!m_search_filter_sp)
600 m_search_filter_sp =
601 std::make_shared<SearchFilterForUnconstrainedSearches>(
602 shared_from_this());
603 filter_sp = m_search_filter_sp;
605 return filter_sp;
608 SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
609 const FileSpecList *containingModules,
610 const FileSpecList *containingSourceFiles) {
611 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
612 return GetSearchFilterForModuleList(containingModules);
614 SearchFilterSP filter_sp;
615 if (containingModules == nullptr) {
616 // We could make a special "CU List only SearchFilter". Better yet was if
617 // these could be composable, but that will take a little reworking.
619 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
620 shared_from_this(), FileSpecList(), *containingSourceFiles);
621 } else {
622 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
623 shared_from_this(), *containingModules, *containingSourceFiles);
625 return filter_sp;
628 BreakpointSP Target::CreateFuncRegexBreakpoint(
629 const FileSpecList *containingModules,
630 const FileSpecList *containingSourceFiles, RegularExpression func_regex,
631 lldb::LanguageType requested_language, LazyBool skip_prologue,
632 bool internal, bool hardware) {
633 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
634 containingModules, containingSourceFiles));
635 bool skip = (skip_prologue == eLazyBoolCalculate)
636 ? GetSkipPrologue()
637 : static_cast<bool>(skip_prologue);
638 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
639 nullptr, std::move(func_regex), requested_language, 0, skip));
641 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
644 lldb::BreakpointSP
645 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
646 bool catch_bp, bool throw_bp, bool internal,
647 Args *additional_args, Status *error) {
648 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
649 *this, language, catch_bp, throw_bp, internal);
650 if (exc_bkpt_sp && additional_args) {
651 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
652 if (precondition_sp && additional_args) {
653 if (error)
654 *error = precondition_sp->ConfigurePrecondition(*additional_args);
655 else
656 precondition_sp->ConfigurePrecondition(*additional_args);
659 return exc_bkpt_sp;
662 lldb::BreakpointSP Target::CreateScriptedBreakpoint(
663 const llvm::StringRef class_name, const FileSpecList *containingModules,
664 const FileSpecList *containingSourceFiles, bool internal,
665 bool request_hardware, StructuredData::ObjectSP extra_args_sp,
666 Status *creation_error) {
667 SearchFilterSP filter_sp;
669 lldb::SearchDepth depth = lldb::eSearchDepthTarget;
670 bool has_files =
671 containingSourceFiles && containingSourceFiles->GetSize() > 0;
672 bool has_modules = containingModules && containingModules->GetSize() > 0;
674 if (has_files && has_modules) {
675 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
676 containingSourceFiles);
677 } else if (has_files) {
678 filter_sp =
679 GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
680 } else if (has_modules) {
681 filter_sp = GetSearchFilterForModuleList(containingModules);
682 } else {
683 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
684 shared_from_this());
687 BreakpointResolverSP resolver_sp(new BreakpointResolverScripted(
688 nullptr, class_name, depth, StructuredDataImpl(extra_args_sp)));
689 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
692 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
693 BreakpointResolverSP &resolver_sp,
694 bool internal, bool request_hardware,
695 bool resolve_indirect_symbols) {
696 BreakpointSP bp_sp;
697 if (filter_sp && resolver_sp) {
698 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
699 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
700 resolve_indirect_symbols));
701 resolver_sp->SetBreakpoint(bp_sp);
702 AddBreakpoint(bp_sp, internal);
704 return bp_sp;
707 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
708 if (!bp_sp)
709 return;
710 if (internal)
711 m_internal_breakpoint_list.Add(bp_sp, false);
712 else
713 m_breakpoint_list.Add(bp_sp, true);
715 Log *log = GetLog(LLDBLog::Breakpoints);
716 if (log) {
717 StreamString s;
718 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
719 LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
720 __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
723 bp_sp->ResolveBreakpoint();
725 if (!internal) {
726 m_last_created_breakpoint = bp_sp;
730 void Target::AddNameToBreakpoint(BreakpointID &id, const char *name,
731 Status &error) {
732 BreakpointSP bp_sp =
733 m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
734 if (!bp_sp) {
735 StreamString s;
736 id.GetDescription(&s, eDescriptionLevelBrief);
737 error.SetErrorStringWithFormat("Could not find breakpoint %s", s.GetData());
738 return;
740 AddNameToBreakpoint(bp_sp, name, error);
743 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, const char *name,
744 Status &error) {
745 if (!bp_sp)
746 return;
748 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
749 if (!bp_name)
750 return;
752 bp_name->ConfigureBreakpoint(bp_sp);
753 bp_sp->AddName(name);
756 void Target::AddBreakpointName(std::unique_ptr<BreakpointName> bp_name) {
757 m_breakpoint_names.insert(
758 std::make_pair(bp_name->GetName(), std::move(bp_name)));
761 BreakpointName *Target::FindBreakpointName(ConstString name, bool can_create,
762 Status &error) {
763 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
764 if (!error.Success())
765 return nullptr;
767 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
768 if (iter != m_breakpoint_names.end()) {
769 return iter->second.get();
772 if (!can_create) {
773 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
774 "can_create is false.",
775 name.AsCString());
776 return nullptr;
779 return m_breakpoint_names
780 .insert(std::make_pair(name, std::make_unique<BreakpointName>(name)))
781 .first->second.get();
784 void Target::DeleteBreakpointName(ConstString name) {
785 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
787 if (iter != m_breakpoint_names.end()) {
788 const char *name_cstr = name.AsCString();
789 m_breakpoint_names.erase(iter);
790 for (auto bp_sp : m_breakpoint_list.Breakpoints())
791 bp_sp->RemoveName(name_cstr);
795 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
796 ConstString name) {
797 bp_sp->RemoveName(name.AsCString());
800 void Target::ConfigureBreakpointName(
801 BreakpointName &bp_name, const BreakpointOptions &new_options,
802 const BreakpointName::Permissions &new_permissions) {
803 bp_name.GetOptions().CopyOverSetOptions(new_options);
804 bp_name.GetPermissions().MergeInto(new_permissions);
805 ApplyNameToBreakpoints(bp_name);
808 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
809 llvm::Expected<std::vector<BreakpointSP>> expected_vector =
810 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString());
812 if (!expected_vector) {
813 LLDB_LOG(GetLog(LLDBLog::Breakpoints), "invalid breakpoint name: {}",
814 llvm::toString(expected_vector.takeError()));
815 return;
818 for (auto bp_sp : *expected_vector)
819 bp_name.ConfigureBreakpoint(bp_sp);
822 void Target::GetBreakpointNames(std::vector<std::string> &names) {
823 names.clear();
824 for (const auto& bp_name_entry : m_breakpoint_names) {
825 names.push_back(bp_name_entry.first.AsCString());
827 llvm::sort(names);
830 bool Target::ProcessIsValid() {
831 return (m_process_sp && m_process_sp->IsAlive());
834 static bool CheckIfWatchpointsSupported(Target *target, Status &error) {
835 std::optional<uint32_t> num_supported_hardware_watchpoints =
836 target->GetProcessSP()->GetWatchpointSlotCount();
838 // If unable to determine the # of watchpoints available,
839 // assume they are supported.
840 if (!num_supported_hardware_watchpoints)
841 return true;
843 if (num_supported_hardware_watchpoints == 0) {
844 error.SetErrorStringWithFormat(
845 "Target supports (%u) hardware watchpoint slots.\n",
846 *num_supported_hardware_watchpoints);
847 return false;
849 return true;
852 // See also Watchpoint::SetWatchpointType(uint32_t type) and the
853 // OptionGroupWatchpoint::WatchType enum type.
854 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
855 const CompilerType *type, uint32_t kind,
856 Status &error) {
857 Log *log = GetLog(LLDBLog::Watchpoints);
858 LLDB_LOGF(log,
859 "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
860 " type = %u)\n",
861 __FUNCTION__, addr, (uint64_t)size, kind);
863 WatchpointSP wp_sp;
864 if (!ProcessIsValid()) {
865 error.SetErrorString("process is not alive");
866 return wp_sp;
869 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
870 if (size == 0)
871 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
872 else
873 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
874 return wp_sp;
877 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
878 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
881 if (!CheckIfWatchpointsSupported(this, error))
882 return wp_sp;
884 // Currently we only support one watchpoint per address, with total number of
885 // watchpoints limited by the hardware which the inferior is running on.
887 // Grab the list mutex while doing operations.
888 const bool notify = false; // Don't notify about all the state changes we do
889 // on creating the watchpoint.
891 // Mask off ignored bits from watchpoint address.
892 if (ABISP abi = m_process_sp->GetABI())
893 addr = abi->FixDataAddress(addr);
895 std::unique_lock<std::recursive_mutex> lock;
896 this->GetWatchpointList().GetListMutex(lock);
897 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
898 if (matched_sp) {
899 size_t old_size = matched_sp->GetByteSize();
900 uint32_t old_type =
901 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
902 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0) |
903 (matched_sp->WatchpointModify() ? LLDB_WATCH_TYPE_MODIFY : 0);
904 // Return the existing watchpoint if both size and type match.
905 if (size == old_size && kind == old_type) {
906 wp_sp = matched_sp;
907 wp_sp->SetEnabled(false, notify);
908 } else {
909 // Nil the matched watchpoint; we will be creating a new one.
910 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
911 m_watchpoint_list.Remove(matched_sp->GetID(), true);
915 if (!wp_sp) {
916 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
917 wp_sp->SetWatchpointType(kind, notify);
918 m_watchpoint_list.Add(wp_sp, true);
921 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
922 LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
923 __FUNCTION__, error.Success() ? "succeeded" : "failed",
924 wp_sp->GetID());
926 if (error.Fail()) {
927 // Enabling the watchpoint on the device side failed. Remove the said
928 // watchpoint from the list maintained by the target instance.
929 m_watchpoint_list.Remove(wp_sp->GetID(), true);
930 // See if we could provide more helpful error message.
931 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
932 error.SetErrorStringWithFormat(
933 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
935 wp_sp.reset();
936 } else
937 m_last_created_watchpoint = wp_sp;
938 return wp_sp;
941 void Target::RemoveAllowedBreakpoints() {
942 Log *log = GetLog(LLDBLog::Breakpoints);
943 LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
945 m_breakpoint_list.RemoveAllowed(true);
947 m_last_created_breakpoint.reset();
950 void Target::RemoveAllBreakpoints(bool internal_also) {
951 Log *log = GetLog(LLDBLog::Breakpoints);
952 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
953 internal_also ? "yes" : "no");
955 m_breakpoint_list.RemoveAll(true);
956 if (internal_also)
957 m_internal_breakpoint_list.RemoveAll(false);
959 m_last_created_breakpoint.reset();
962 void Target::DisableAllBreakpoints(bool internal_also) {
963 Log *log = GetLog(LLDBLog::Breakpoints);
964 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
965 internal_also ? "yes" : "no");
967 m_breakpoint_list.SetEnabledAll(false);
968 if (internal_also)
969 m_internal_breakpoint_list.SetEnabledAll(false);
972 void Target::DisableAllowedBreakpoints() {
973 Log *log = GetLog(LLDBLog::Breakpoints);
974 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
976 m_breakpoint_list.SetEnabledAllowed(false);
979 void Target::EnableAllBreakpoints(bool internal_also) {
980 Log *log = GetLog(LLDBLog::Breakpoints);
981 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
982 internal_also ? "yes" : "no");
984 m_breakpoint_list.SetEnabledAll(true);
985 if (internal_also)
986 m_internal_breakpoint_list.SetEnabledAll(true);
989 void Target::EnableAllowedBreakpoints() {
990 Log *log = GetLog(LLDBLog::Breakpoints);
991 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
993 m_breakpoint_list.SetEnabledAllowed(true);
996 bool Target::RemoveBreakpointByID(break_id_t break_id) {
997 Log *log = GetLog(LLDBLog::Breakpoints);
998 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
999 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1001 if (DisableBreakpointByID(break_id)) {
1002 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1003 m_internal_breakpoint_list.Remove(break_id, false);
1004 else {
1005 if (m_last_created_breakpoint) {
1006 if (m_last_created_breakpoint->GetID() == break_id)
1007 m_last_created_breakpoint.reset();
1009 m_breakpoint_list.Remove(break_id, true);
1011 return true;
1013 return false;
1016 bool Target::DisableBreakpointByID(break_id_t break_id) {
1017 Log *log = GetLog(LLDBLog::Breakpoints);
1018 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1019 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1021 BreakpointSP bp_sp;
1023 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1024 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1025 else
1026 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1027 if (bp_sp) {
1028 bp_sp->SetEnabled(false);
1029 return true;
1031 return false;
1034 bool Target::EnableBreakpointByID(break_id_t break_id) {
1035 Log *log = GetLog(LLDBLog::Breakpoints);
1036 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1037 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1039 BreakpointSP bp_sp;
1041 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1042 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1043 else
1044 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1046 if (bp_sp) {
1047 bp_sp->SetEnabled(true);
1048 return true;
1050 return false;
1053 void Target::ResetBreakpointHitCounts() {
1054 GetBreakpointList().ResetHitCounts();
1057 Status Target::SerializeBreakpointsToFile(const FileSpec &file,
1058 const BreakpointIDList &bp_ids,
1059 bool append) {
1060 Status error;
1062 if (!file) {
1063 error.SetErrorString("Invalid FileSpec.");
1064 return error;
1067 std::string path(file.GetPath());
1068 StructuredData::ObjectSP input_data_sp;
1070 StructuredData::ArraySP break_store_sp;
1071 StructuredData::Array *break_store_ptr = nullptr;
1073 if (append) {
1074 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1075 if (error.Success()) {
1076 break_store_ptr = input_data_sp->GetAsArray();
1077 if (!break_store_ptr) {
1078 error.SetErrorStringWithFormat(
1079 "Tried to append to invalid input file %s", path.c_str());
1080 return error;
1085 if (!break_store_ptr) {
1086 break_store_sp = std::make_shared<StructuredData::Array>();
1087 break_store_ptr = break_store_sp.get();
1090 StreamFile out_file(path.c_str(),
1091 File::eOpenOptionTruncate | File::eOpenOptionWriteOnly |
1092 File::eOpenOptionCanCreate |
1093 File::eOpenOptionCloseOnExec,
1094 lldb::eFilePermissionsFileDefault);
1095 if (!out_file.GetFile().IsValid()) {
1096 error.SetErrorStringWithFormat("Unable to open output file: %s.",
1097 path.c_str());
1098 return error;
1101 std::unique_lock<std::recursive_mutex> lock;
1102 GetBreakpointList().GetListMutex(lock);
1104 if (bp_ids.GetSize() == 0) {
1105 const BreakpointList &breakpoints = GetBreakpointList();
1107 size_t num_breakpoints = breakpoints.GetSize();
1108 for (size_t i = 0; i < num_breakpoints; i++) {
1109 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1110 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1111 // If a breakpoint can't serialize it, just ignore it for now:
1112 if (bkpt_save_sp)
1113 break_store_ptr->AddItem(bkpt_save_sp);
1115 } else {
1117 std::unordered_set<lldb::break_id_t> processed_bkpts;
1118 const size_t count = bp_ids.GetSize();
1119 for (size_t i = 0; i < count; ++i) {
1120 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1121 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1123 if (bp_id != LLDB_INVALID_BREAK_ID) {
1124 // Only do each breakpoint once:
1125 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1126 insert_result = processed_bkpts.insert(bp_id);
1127 if (!insert_result.second)
1128 continue;
1130 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1131 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1132 // If the user explicitly asked to serialize a breakpoint, and we
1133 // can't, then raise an error:
1134 if (!bkpt_save_sp) {
1135 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1136 bp_id);
1137 return error;
1139 break_store_ptr->AddItem(bkpt_save_sp);
1144 break_store_ptr->Dump(out_file, false);
1145 out_file.PutChar('\n');
1146 return error;
1149 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1150 BreakpointIDList &new_bps) {
1151 std::vector<std::string> no_names;
1152 return CreateBreakpointsFromFile(file, no_names, new_bps);
1155 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1156 std::vector<std::string> &names,
1157 BreakpointIDList &new_bps) {
1158 std::unique_lock<std::recursive_mutex> lock;
1159 GetBreakpointList().GetListMutex(lock);
1161 Status error;
1162 StructuredData::ObjectSP input_data_sp =
1163 StructuredData::ParseJSONFromFile(file, error);
1164 if (!error.Success()) {
1165 return error;
1166 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1167 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1168 file.GetPath().c_str());
1169 return error;
1172 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1173 if (!bkpt_array) {
1174 error.SetErrorStringWithFormat(
1175 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1176 return error;
1179 size_t num_bkpts = bkpt_array->GetSize();
1180 size_t num_names = names.size();
1182 for (size_t i = 0; i < num_bkpts; i++) {
1183 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1184 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1185 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1186 if (!bkpt_dict) {
1187 error.SetErrorStringWithFormat(
1188 "Invalid breakpoint data for element %zu from input file: %s.", i,
1189 file.GetPath().c_str());
1190 return error;
1192 StructuredData::ObjectSP bkpt_data_sp =
1193 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1194 if (num_names &&
1195 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1196 continue;
1198 BreakpointSP bkpt_sp = Breakpoint::CreateFromStructuredData(
1199 shared_from_this(), bkpt_data_sp, error);
1200 if (!error.Success()) {
1201 error.SetErrorStringWithFormat(
1202 "Error restoring breakpoint %zu from %s: %s.", i,
1203 file.GetPath().c_str(), error.AsCString());
1204 return error;
1206 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1208 return error;
1211 // The flag 'end_to_end', default to true, signifies that the operation is
1212 // performed end to end, for both the debugger and the debuggee.
1214 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1215 // to end operations.
1216 bool Target::RemoveAllWatchpoints(bool end_to_end) {
1217 Log *log = GetLog(LLDBLog::Watchpoints);
1218 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1220 if (!end_to_end) {
1221 m_watchpoint_list.RemoveAll(true);
1222 return true;
1225 // Otherwise, it's an end to end operation.
1227 if (!ProcessIsValid())
1228 return false;
1230 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1231 if (!wp_sp)
1232 return false;
1234 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1235 if (rc.Fail())
1236 return false;
1238 m_watchpoint_list.RemoveAll(true);
1239 m_last_created_watchpoint.reset();
1240 return true; // Success!
1243 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1244 // to end operations.
1245 bool Target::DisableAllWatchpoints(bool end_to_end) {
1246 Log *log = GetLog(LLDBLog::Watchpoints);
1247 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1249 if (!end_to_end) {
1250 m_watchpoint_list.SetEnabledAll(false);
1251 return true;
1254 // Otherwise, it's an end to end operation.
1256 if (!ProcessIsValid())
1257 return false;
1259 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1260 if (!wp_sp)
1261 return false;
1263 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1264 if (rc.Fail())
1265 return false;
1267 return true; // Success!
1270 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1271 // to end operations.
1272 bool Target::EnableAllWatchpoints(bool end_to_end) {
1273 Log *log = GetLog(LLDBLog::Watchpoints);
1274 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1276 if (!end_to_end) {
1277 m_watchpoint_list.SetEnabledAll(true);
1278 return true;
1281 // Otherwise, it's an end to end operation.
1283 if (!ProcessIsValid())
1284 return false;
1286 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1287 if (!wp_sp)
1288 return false;
1290 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1291 if (rc.Fail())
1292 return false;
1294 return true; // Success!
1297 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1298 bool Target::ClearAllWatchpointHitCounts() {
1299 Log *log = GetLog(LLDBLog::Watchpoints);
1300 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1302 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1303 if (!wp_sp)
1304 return false;
1306 wp_sp->ResetHitCount();
1308 return true; // Success!
1311 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1312 bool Target::ClearAllWatchpointHistoricValues() {
1313 Log *log = GetLog(LLDBLog::Watchpoints);
1314 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1316 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1317 if (!wp_sp)
1318 return false;
1320 wp_sp->ResetHistoricValues();
1322 return true; // Success!
1325 // Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1326 // these operations.
1327 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1328 Log *log = GetLog(LLDBLog::Watchpoints);
1329 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1331 if (!ProcessIsValid())
1332 return false;
1334 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1335 if (!wp_sp)
1336 return false;
1338 wp_sp->SetIgnoreCount(ignore_count);
1340 return true; // Success!
1343 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1344 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1345 Log *log = GetLog(LLDBLog::Watchpoints);
1346 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1348 if (!ProcessIsValid())
1349 return false;
1351 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1352 if (wp_sp) {
1353 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1354 if (rc.Success())
1355 return true;
1357 // Else, fallthrough.
1359 return false;
1362 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1363 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1364 Log *log = GetLog(LLDBLog::Watchpoints);
1365 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1367 if (!ProcessIsValid())
1368 return false;
1370 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1371 if (wp_sp) {
1372 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1373 if (rc.Success())
1374 return true;
1376 // Else, fallthrough.
1378 return false;
1381 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1382 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1383 Log *log = GetLog(LLDBLog::Watchpoints);
1384 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1386 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1387 if (watch_to_remove_sp == m_last_created_watchpoint)
1388 m_last_created_watchpoint.reset();
1390 if (DisableWatchpointByID(watch_id)) {
1391 m_watchpoint_list.Remove(watch_id, true);
1392 return true;
1394 return false;
1397 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1398 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1399 uint32_t ignore_count) {
1400 Log *log = GetLog(LLDBLog::Watchpoints);
1401 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1403 if (!ProcessIsValid())
1404 return false;
1406 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1407 if (wp_sp) {
1408 wp_sp->SetIgnoreCount(ignore_count);
1409 return true;
1411 return false;
1414 ModuleSP Target::GetExecutableModule() {
1415 // search for the first executable in the module list
1416 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1417 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1418 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1419 if (obj == nullptr)
1420 continue;
1421 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1422 return module_sp;
1424 // as fall back return the first module loaded
1425 return m_images.GetModuleAtIndex(0);
1428 Module *Target::GetExecutableModulePointer() {
1429 return GetExecutableModule().get();
1432 static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1433 Target *target) {
1434 Status error;
1435 StreamString feedback_stream;
1436 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error,
1437 feedback_stream)) {
1438 if (error.AsCString())
1439 target->GetDebugger().GetErrorStream().Printf(
1440 "unable to load scripting data for module %s - error reported was "
1441 "%s\n",
1442 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1443 error.AsCString());
1445 if (feedback_stream.GetSize())
1446 target->GetDebugger().GetErrorStream().Printf("%s\n",
1447 feedback_stream.GetData());
1450 void Target::ClearModules(bool delete_locations) {
1451 ModulesDidUnload(m_images, delete_locations);
1452 m_section_load_history.Clear();
1453 m_images.Clear();
1454 m_scratch_type_system_map.Clear();
1457 void Target::DidExec() {
1458 // When a process exec's we need to know about it so we can do some cleanup.
1459 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1460 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1463 void Target::SetExecutableModule(ModuleSP &executable_sp,
1464 LoadDependentFiles load_dependent_files) {
1465 Log *log = GetLog(LLDBLog::Target);
1466 ClearModules(false);
1468 if (executable_sp) {
1469 ElapsedTime elapsed(m_stats.GetCreateTime());
1470 LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')",
1471 executable_sp->GetFileSpec().GetPath().c_str());
1473 const bool notify = true;
1474 m_images.Append(executable_sp,
1475 notify); // The first image is our executable file
1477 // If we haven't set an architecture yet, reset our architecture based on
1478 // what we found in the executable module.
1479 if (!m_arch.GetSpec().IsValid()) {
1480 m_arch = executable_sp->GetArchitecture();
1481 LLDB_LOG(log,
1482 "Target::SetExecutableModule setting architecture to {0} ({1}) "
1483 "based on executable file",
1484 m_arch.GetSpec().GetArchitectureName(),
1485 m_arch.GetSpec().GetTriple().getTriple());
1488 FileSpecList dependent_files;
1489 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1490 bool load_dependents = true;
1491 switch (load_dependent_files) {
1492 case eLoadDependentsDefault:
1493 load_dependents = executable_sp->IsExecutable();
1494 break;
1495 case eLoadDependentsYes:
1496 load_dependents = true;
1497 break;
1498 case eLoadDependentsNo:
1499 load_dependents = false;
1500 break;
1503 if (executable_objfile && load_dependents) {
1504 ModuleList added_modules;
1505 executable_objfile->GetDependentModules(dependent_files);
1506 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1507 FileSpec dependent_file_spec(dependent_files.GetFileSpecAtIndex(i));
1508 FileSpec platform_dependent_file_spec;
1509 if (m_platform_sp)
1510 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1511 platform_dependent_file_spec);
1512 else
1513 platform_dependent_file_spec = dependent_file_spec;
1515 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1516 ModuleSP image_module_sp(
1517 GetOrCreateModule(module_spec, false /* notify */));
1518 if (image_module_sp) {
1519 added_modules.AppendIfNeeded(image_module_sp, false);
1520 ObjectFile *objfile = image_module_sp->GetObjectFile();
1521 if (objfile)
1522 objfile->GetDependentModules(dependent_files);
1525 ModulesDidLoad(added_modules);
1530 bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform,
1531 bool merge) {
1532 Log *log = GetLog(LLDBLog::Target);
1533 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1534 bool replace_local_arch = true;
1535 bool compatible_local_arch = false;
1536 ArchSpec other(arch_spec);
1538 // Changing the architecture might mean that the currently selected platform
1539 // isn't compatible. Set the platform correctly if we are asked to do so,
1540 // otherwise assume the user will set the platform manually.
1541 if (set_platform) {
1542 if (other.IsValid()) {
1543 auto platform_sp = GetPlatform();
1544 if (!platform_sp || !platform_sp->IsCompatibleArchitecture(
1545 other, {}, ArchSpec::CompatibleMatch, nullptr)) {
1546 ArchSpec platform_arch;
1547 if (PlatformSP arch_platform_sp =
1548 GetDebugger().GetPlatformList().GetOrCreate(other, {},
1549 &platform_arch)) {
1550 SetPlatform(arch_platform_sp);
1551 if (platform_arch.IsValid())
1552 other = platform_arch;
1558 if (!missing_local_arch) {
1559 if (merge && m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1560 other.MergeFrom(m_arch.GetSpec());
1562 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1563 compatible_local_arch = true;
1564 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1565 env_changed;
1567 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed,
1568 vendor_changed, os_changed,
1569 os_ver_changed, env_changed);
1571 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1572 replace_local_arch = false;
1577 if (compatible_local_arch || missing_local_arch) {
1578 // If we haven't got a valid arch spec, or the architectures are compatible
1579 // update the architecture, unless the one we already have is more
1580 // specified
1581 if (replace_local_arch)
1582 m_arch = other;
1583 LLDB_LOG(log,
1584 "Target::SetArchitecture merging compatible arch; arch "
1585 "is now {0} ({1})",
1586 m_arch.GetSpec().GetArchitectureName(),
1587 m_arch.GetSpec().GetTriple().getTriple());
1588 return true;
1591 // If we have an executable file, try to reset the executable to the desired
1592 // architecture
1593 LLDB_LOGF(
1594 log,
1595 "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)",
1596 arch_spec.GetArchitectureName(),
1597 arch_spec.GetTriple().getTriple().c_str(),
1598 m_arch.GetSpec().GetArchitectureName(),
1599 m_arch.GetSpec().GetTriple().getTriple().c_str());
1600 m_arch = other;
1601 ModuleSP executable_sp = GetExecutableModule();
1603 ClearModules(true);
1604 // Need to do something about unsetting breakpoints.
1606 if (executable_sp) {
1607 LLDB_LOGF(log,
1608 "Target::SetArchitecture Trying to select executable file "
1609 "architecture %s (%s)",
1610 arch_spec.GetArchitectureName(),
1611 arch_spec.GetTriple().getTriple().c_str());
1612 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1613 FileSpecList search_paths = GetExecutableSearchPaths();
1614 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1615 &search_paths, nullptr, nullptr);
1617 if (!error.Fail() && executable_sp) {
1618 SetExecutableModule(executable_sp, eLoadDependentsYes);
1619 return true;
1622 return false;
1625 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1626 Log *log = GetLog(LLDBLog::Target);
1627 if (arch_spec.IsValid()) {
1628 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1629 // The current target arch is compatible with "arch_spec", see if we can
1630 // improve our current architecture using bits from "arch_spec"
1632 LLDB_LOGF(log,
1633 "Target::MergeArchitecture target has arch %s, merging with "
1634 "arch %s",
1635 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1636 arch_spec.GetTriple().getTriple().c_str());
1638 // Merge bits from arch_spec into "merged_arch" and set our architecture
1639 ArchSpec merged_arch(m_arch.GetSpec());
1640 merged_arch.MergeFrom(arch_spec);
1641 return SetArchitecture(merged_arch);
1642 } else {
1643 // The new architecture is different, we just need to replace it
1644 return SetArchitecture(arch_spec);
1647 return false;
1650 void Target::NotifyWillClearList(const ModuleList &module_list) {}
1652 void Target::NotifyModuleAdded(const ModuleList &module_list,
1653 const ModuleSP &module_sp) {
1654 // A module is being added to this target for the first time
1655 if (m_valid) {
1656 ModuleList my_module_list;
1657 my_module_list.Append(module_sp);
1658 ModulesDidLoad(my_module_list);
1662 void Target::NotifyModuleRemoved(const ModuleList &module_list,
1663 const ModuleSP &module_sp) {
1664 // A module is being removed from this target.
1665 if (m_valid) {
1666 ModuleList my_module_list;
1667 my_module_list.Append(module_sp);
1668 ModulesDidUnload(my_module_list, false);
1672 void Target::NotifyModuleUpdated(const ModuleList &module_list,
1673 const ModuleSP &old_module_sp,
1674 const ModuleSP &new_module_sp) {
1675 // A module is replacing an already added module
1676 if (m_valid) {
1677 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1678 new_module_sp);
1679 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1680 old_module_sp, new_module_sp);
1684 void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) {
1685 ModulesDidUnload(module_list, false);
1688 void Target::ModulesDidLoad(ModuleList &module_list) {
1689 const size_t num_images = module_list.GetSize();
1690 if (m_valid && num_images) {
1691 for (size_t idx = 0; idx < num_images; ++idx) {
1692 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1693 LoadScriptingResourceForModule(module_sp, this);
1695 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1696 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1697 if (m_process_sp) {
1698 m_process_sp->ModulesDidLoad(module_list);
1700 BroadcastEvent(eBroadcastBitModulesLoaded,
1701 new TargetEventData(this->shared_from_this(), module_list));
1705 void Target::SymbolsDidLoad(ModuleList &module_list) {
1706 if (m_valid && module_list.GetSize()) {
1707 if (m_process_sp) {
1708 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1709 runtime->SymbolsDidLoad(module_list);
1713 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1714 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1715 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1716 new TargetEventData(this->shared_from_this(), module_list));
1720 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1721 if (m_valid && module_list.GetSize()) {
1722 UnloadModuleSections(module_list);
1723 BroadcastEvent(eBroadcastBitModulesUnloaded,
1724 new TargetEventData(this->shared_from_this(), module_list));
1725 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1726 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1727 delete_locations);
1729 // If a module was torn down it will have torn down the 'TypeSystemClang's
1730 // that we used as source 'ASTContext's for the persistent variables in
1731 // the current target. Those would now be unsafe to access because the
1732 // 'DeclOrigin' are now possibly stale. Thus clear all persistent
1733 // variables. We only want to flush 'TypeSystem's if the module being
1734 // unloaded was capable of describing a source type. JITted module unloads
1735 // happen frequently for Objective-C utility functions or the REPL and rely
1736 // on the persistent variables to stick around.
1737 const bool should_flush_type_systems =
1738 module_list.AnyOf([](lldb_private::Module &module) {
1739 auto *object_file = module.GetObjectFile();
1741 if (!object_file)
1742 return false;
1744 auto type = object_file->GetType();
1746 // eTypeExecutable: when debugged binary was rebuilt
1747 // eTypeSharedLibrary: if dylib was re-loaded
1748 return module.FileHasChanged() &&
1749 (type == ObjectFile::eTypeObjectFile ||
1750 type == ObjectFile::eTypeExecutable ||
1751 type == ObjectFile::eTypeSharedLibrary);
1754 if (should_flush_type_systems)
1755 m_scratch_type_system_map.Clear();
1759 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1760 const FileSpec &module_file_spec) {
1761 if (GetBreakpointsConsultPlatformAvoidList()) {
1762 ModuleList matchingModules;
1763 ModuleSpec module_spec(module_file_spec);
1764 GetImages().FindModules(module_spec, matchingModules);
1765 size_t num_modules = matchingModules.GetSize();
1767 // If there is more than one module for this file spec, only
1768 // return true if ALL the modules are on the black list.
1769 if (num_modules > 0) {
1770 for (size_t i = 0; i < num_modules; i++) {
1771 if (!ModuleIsExcludedForUnconstrainedSearches(
1772 matchingModules.GetModuleAtIndex(i)))
1773 return false;
1775 return true;
1778 return false;
1781 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1782 const lldb::ModuleSP &module_sp) {
1783 if (GetBreakpointsConsultPlatformAvoidList()) {
1784 if (m_platform_sp)
1785 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1786 module_sp);
1788 return false;
1791 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1792 size_t dst_len, Status &error) {
1793 SectionSP section_sp(addr.GetSection());
1794 if (section_sp) {
1795 // If the contents of this section are encrypted, the on-disk file is
1796 // unusable. Read only from live memory.
1797 if (section_sp->IsEncrypted()) {
1798 error.SetErrorString("section is encrypted");
1799 return 0;
1801 ModuleSP module_sp(section_sp->GetModule());
1802 if (module_sp) {
1803 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1804 if (objfile) {
1805 size_t bytes_read = objfile->ReadSectionData(
1806 section_sp.get(), addr.GetOffset(), dst, dst_len);
1807 if (bytes_read > 0)
1808 return bytes_read;
1809 else
1810 error.SetErrorStringWithFormat("error reading data from section %s",
1811 section_sp->GetName().GetCString());
1812 } else
1813 error.SetErrorString("address isn't from a object file");
1814 } else
1815 error.SetErrorString("address isn't in a module");
1816 } else
1817 error.SetErrorString("address doesn't contain a section that points to a "
1818 "section in a object file");
1820 return 0;
1823 size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
1824 Status &error, bool force_live_memory,
1825 lldb::addr_t *load_addr_ptr) {
1826 error.Clear();
1828 Address fixed_addr = addr;
1829 if (ProcessIsValid())
1830 if (const ABISP &abi = m_process_sp->GetABI())
1831 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
1832 this);
1834 // if we end up reading this from process memory, we will fill this with the
1835 // actual load address
1836 if (load_addr_ptr)
1837 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1839 size_t bytes_read = 0;
1841 addr_t load_addr = LLDB_INVALID_ADDRESS;
1842 addr_t file_addr = LLDB_INVALID_ADDRESS;
1843 Address resolved_addr;
1844 if (!fixed_addr.IsSectionOffset()) {
1845 SectionLoadList &section_load_list = GetSectionLoadList();
1846 if (section_load_list.IsEmpty()) {
1847 // No sections are loaded, so we must assume we are not running yet and
1848 // anything we are given is a file address.
1849 file_addr =
1850 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
1851 // its offset is the file address
1852 m_images.ResolveFileAddress(file_addr, resolved_addr);
1853 } else {
1854 // We have at least one section loaded. This can be because we have
1855 // manually loaded some sections with "target modules load ..." or
1856 // because we have a live process that has sections loaded through
1857 // the dynamic loader
1858 load_addr =
1859 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
1860 // its offset is the load address
1861 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1864 if (!resolved_addr.IsValid())
1865 resolved_addr = fixed_addr;
1867 // If we read from the file cache but can't get as many bytes as requested,
1868 // we keep the result around in this buffer, in case this result is the
1869 // best we can do.
1870 std::unique_ptr<uint8_t[]> file_cache_read_buffer;
1871 size_t file_cache_bytes_read = 0;
1873 // Read from file cache if read-only section.
1874 if (!force_live_memory && resolved_addr.IsSectionOffset()) {
1875 SectionSP section_sp(resolved_addr.GetSection());
1876 if (section_sp) {
1877 auto permissions = Flags(section_sp->GetPermissions());
1878 bool is_readonly = !permissions.Test(ePermissionsWritable) &&
1879 permissions.Test(ePermissionsReadable);
1880 if (is_readonly) {
1881 file_cache_bytes_read =
1882 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1883 if (file_cache_bytes_read == dst_len)
1884 return file_cache_bytes_read;
1885 else if (file_cache_bytes_read > 0) {
1886 file_cache_read_buffer =
1887 std::make_unique<uint8_t[]>(file_cache_bytes_read);
1888 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
1894 if (ProcessIsValid()) {
1895 if (load_addr == LLDB_INVALID_ADDRESS)
1896 load_addr = resolved_addr.GetLoadAddress(this);
1898 if (load_addr == LLDB_INVALID_ADDRESS) {
1899 ModuleSP addr_module_sp(resolved_addr.GetModule());
1900 if (addr_module_sp && addr_module_sp->GetFileSpec())
1901 error.SetErrorStringWithFormatv(
1902 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1903 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1904 else
1905 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1906 resolved_addr.GetFileAddress());
1907 } else {
1908 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1909 if (bytes_read != dst_len) {
1910 if (error.Success()) {
1911 if (bytes_read == 0)
1912 error.SetErrorStringWithFormat(
1913 "read memory from 0x%" PRIx64 " failed", load_addr);
1914 else
1915 error.SetErrorStringWithFormat(
1916 "only %" PRIu64 " of %" PRIu64
1917 " bytes were read from memory at 0x%" PRIx64,
1918 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1921 if (bytes_read) {
1922 if (load_addr_ptr)
1923 *load_addr_ptr = load_addr;
1924 return bytes_read;
1929 if (file_cache_read_buffer && file_cache_bytes_read > 0) {
1930 // Reading from the process failed. If we've previously succeeded in reading
1931 // something from the file cache, then copy that over and return that.
1932 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
1933 return file_cache_bytes_read;
1936 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
1937 // If we didn't already try and read from the object file cache, then try
1938 // it after failing to read from the process.
1939 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1941 return 0;
1944 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1945 Status &error, bool force_live_memory) {
1946 char buf[256];
1947 out_str.clear();
1948 addr_t curr_addr = addr.GetLoadAddress(this);
1949 Address address(addr);
1950 while (true) {
1951 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
1952 force_live_memory);
1953 if (length == 0)
1954 break;
1955 out_str.append(buf, length);
1956 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1957 // to read some more characters
1958 if (length == sizeof(buf) - 1)
1959 curr_addr += length;
1960 else
1961 break;
1962 address = Address(curr_addr);
1964 return out_str.size();
1967 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1968 size_t dst_max_len, Status &result_error,
1969 bool force_live_memory) {
1970 size_t total_cstr_len = 0;
1971 if (dst && dst_max_len) {
1972 result_error.Clear();
1973 // NULL out everything just to be safe
1974 memset(dst, 0, dst_max_len);
1975 Status error;
1976 addr_t curr_addr = addr.GetLoadAddress(this);
1977 Address address(addr);
1979 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1980 // this really needs to be tied to the memory cache subsystem's cache line
1981 // size, so leave this as a fixed constant.
1982 const size_t cache_line_size = 512;
1984 size_t bytes_left = dst_max_len - 1;
1985 char *curr_dst = dst;
1987 while (bytes_left > 0) {
1988 addr_t cache_line_bytes_left =
1989 cache_line_size - (curr_addr % cache_line_size);
1990 addr_t bytes_to_read =
1991 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1992 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
1993 force_live_memory);
1995 if (bytes_read == 0) {
1996 result_error = error;
1997 dst[total_cstr_len] = '\0';
1998 break;
2000 const size_t len = strlen(curr_dst);
2002 total_cstr_len += len;
2004 if (len < bytes_to_read)
2005 break;
2007 curr_dst += bytes_read;
2008 curr_addr += bytes_read;
2009 bytes_left -= bytes_read;
2010 address = Address(curr_addr);
2012 } else {
2013 if (dst == nullptr)
2014 result_error.SetErrorString("invalid arguments");
2015 else
2016 result_error.Clear();
2018 return total_cstr_len;
2021 addr_t Target::GetReasonableReadSize(const Address &addr) {
2022 addr_t load_addr = addr.GetLoadAddress(this);
2023 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2024 // Avoid crossing cache line boundaries.
2025 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2026 return cache_line_size - (load_addr % cache_line_size);
2029 // The read is going to go to the file cache, so we can just pick a largish
2030 // value.
2031 return 0x1000;
2034 size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2035 size_t max_bytes, Status &error,
2036 size_t type_width, bool force_live_memory) {
2037 if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2038 return 0;
2040 size_t total_bytes_read = 0;
2042 // Ensure a null terminator independent of the number of bytes that is
2043 // read.
2044 memset(dst, 0, max_bytes);
2045 size_t bytes_left = max_bytes - type_width;
2047 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2048 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2049 "string with more than 4 bytes "
2050 "per character!");
2052 Address address = addr;
2053 char *curr_dst = dst;
2055 error.Clear();
2056 while (bytes_left > 0 && error.Success()) {
2057 addr_t bytes_to_read =
2058 std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2059 size_t bytes_read =
2060 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2062 if (bytes_read == 0)
2063 break;
2065 // Search for a null terminator of correct size and alignment in
2066 // bytes_read
2067 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2068 for (size_t i = aligned_start;
2069 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2070 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2071 error.Clear();
2072 return i;
2075 total_bytes_read += bytes_read;
2076 curr_dst += bytes_read;
2077 address.Slide(bytes_read);
2078 bytes_left -= bytes_read;
2080 return total_bytes_read;
2083 size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2084 bool is_signed, Scalar &scalar,
2085 Status &error,
2086 bool force_live_memory) {
2087 uint64_t uval;
2089 if (byte_size <= sizeof(uval)) {
2090 size_t bytes_read =
2091 ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2092 if (bytes_read == byte_size) {
2093 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2094 m_arch.GetSpec().GetAddressByteSize());
2095 lldb::offset_t offset = 0;
2096 if (byte_size <= 4)
2097 scalar = data.GetMaxU32(&offset, byte_size);
2098 else
2099 scalar = data.GetMaxU64(&offset, byte_size);
2101 if (is_signed)
2102 scalar.SignExtend(byte_size * 8);
2103 return bytes_read;
2105 } else {
2106 error.SetErrorStringWithFormat(
2107 "byte size of %u is too large for integer scalar type", byte_size);
2109 return 0;
2112 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
2113 size_t integer_byte_size,
2114 uint64_t fail_value, Status &error,
2115 bool force_live_memory) {
2116 Scalar scalar;
2117 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2118 force_live_memory))
2119 return scalar.ULongLong(fail_value);
2120 return fail_value;
2123 bool Target::ReadPointerFromMemory(const Address &addr, Status &error,
2124 Address &pointer_addr,
2125 bool force_live_memory) {
2126 Scalar scalar;
2127 if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
2128 false, scalar, error, force_live_memory)) {
2129 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2130 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2131 SectionLoadList &section_load_list = GetSectionLoadList();
2132 if (section_load_list.IsEmpty()) {
2133 // No sections are loaded, so we must assume we are not running yet and
2134 // anything we are given is a file address.
2135 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2136 } else {
2137 // We have at least one section loaded. This can be because we have
2138 // manually loaded some sections with "target modules load ..." or
2139 // because we have a live process that has sections loaded through
2140 // the dynamic loader
2141 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2143 // We weren't able to resolve the pointer value, so just return an
2144 // address with no section
2145 if (!pointer_addr.IsValid())
2146 pointer_addr.SetOffset(pointer_vm_addr);
2147 return true;
2150 return false;
2153 ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
2154 Status *error_ptr) {
2155 ModuleSP module_sp;
2157 Status error;
2159 // First see if we already have this module in our module list. If we do,
2160 // then we're done, we don't need to consult the shared modules list. But
2161 // only do this if we are passed a UUID.
2163 if (module_spec.GetUUID().IsValid())
2164 module_sp = m_images.FindFirstModule(module_spec);
2166 if (!module_sp) {
2167 llvm::SmallVector<ModuleSP, 1>
2168 old_modules; // This will get filled in if we have a new version
2169 // of the library
2170 bool did_create_module = false;
2171 FileSpecList search_paths = GetExecutableSearchPaths();
2172 FileSpec symbol_file_spec;
2174 // Call locate module callback if set. This allows users to implement their
2175 // own module cache system. For example, to leverage build system artifacts,
2176 // to bypass pulling files from remote platform, or to search symbol files
2177 // from symbol servers.
2178 if (m_platform_sp)
2179 m_platform_sp->CallLocateModuleCallbackIfSet(
2180 module_spec, module_sp, symbol_file_spec, &did_create_module);
2182 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2183 // 1. module_sp:loaded, symbol_file_spec:set
2184 // The callback found a module file and a symbol file for the
2185 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2186 // the symbol_file_spec later.
2187 // 2. module_sp:loaded, symbol_file_spec:empty
2188 // The callback only found a module file for the module_spec.
2189 // 3. module_sp:empty, symbol_file_spec:set
2190 // The callback only found a symbol file for the module. We continue
2191 // to find a module file for this module_spec and we will call
2192 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2193 // 4. module_sp:empty, symbol_file_spec:empty
2194 // Platform does not exist, the callback is not set, the callback did
2195 // not find any module files nor any symbol files, the callback failed,
2196 // or something went wrong. We continue to find a module file for this
2197 // module_spec.
2199 if (!module_sp) {
2200 // If there are image search path entries, try to use them to acquire a
2201 // suitable image.
2202 if (m_image_search_paths.GetSize()) {
2203 ModuleSpec transformed_spec(module_spec);
2204 ConstString transformed_dir;
2205 if (m_image_search_paths.RemapPath(
2206 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2207 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2208 transformed_spec.GetFileSpec().SetFilename(
2209 module_spec.GetFileSpec().GetFilename());
2210 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2211 &search_paths, &old_modules,
2212 &did_create_module);
2217 if (!module_sp) {
2218 // If we have a UUID, we can check our global shared module list in case
2219 // we already have it. If we don't have a valid UUID, then we can't since
2220 // the path in "module_spec" will be a platform path, and we will need to
2221 // let the platform find that file. For example, we could be asking for
2222 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2223 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2224 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2225 // cache.
2226 if (module_spec.GetUUID().IsValid()) {
2227 // We have a UUID, it is OK to check the global module list...
2228 error =
2229 ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2230 &old_modules, &did_create_module);
2233 if (!module_sp) {
2234 // The platform is responsible for finding and caching an appropriate
2235 // module in the shared module cache.
2236 if (m_platform_sp) {
2237 error = m_platform_sp->GetSharedModule(
2238 module_spec, m_process_sp.get(), module_sp, &search_paths,
2239 &old_modules, &did_create_module);
2240 } else {
2241 error.SetErrorString("no platform is currently set");
2246 // We found a module that wasn't in our target list. Let's make sure that
2247 // there wasn't an equivalent module in the list already, and if there was,
2248 // let's remove it.
2249 if (module_sp) {
2250 ObjectFile *objfile = module_sp->GetObjectFile();
2251 if (objfile) {
2252 switch (objfile->GetType()) {
2253 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2254 /// a program's execution state
2255 case ObjectFile::eTypeExecutable: /// A normal executable
2256 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2257 /// executable
2258 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2259 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2260 /// used during execution
2261 break;
2262 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2263 /// debug information
2264 if (error_ptr)
2265 error_ptr->SetErrorString("debug info files aren't valid target "
2266 "modules, please specify an executable");
2267 return ModuleSP();
2268 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2269 /// against but not used for
2270 /// execution
2271 if (error_ptr)
2272 error_ptr->SetErrorString("stub libraries aren't valid target "
2273 "modules, please specify an executable");
2274 return ModuleSP();
2275 default:
2276 if (error_ptr)
2277 error_ptr->SetErrorString(
2278 "unsupported file type, please specify an executable");
2279 return ModuleSP();
2281 // GetSharedModule is not guaranteed to find the old shared module, for
2282 // instance in the common case where you pass in the UUID, it is only
2283 // going to find the one module matching the UUID. In fact, it has no
2284 // good way to know what the "old module" relevant to this target is,
2285 // since there might be many copies of a module with this file spec in
2286 // various running debug sessions, but only one of them will belong to
2287 // this target. So let's remove the UUID from the module list, and look
2288 // in the target's module list. Only do this if there is SOMETHING else
2289 // in the module spec...
2290 if (module_spec.GetUUID().IsValid() &&
2291 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2292 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2293 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2294 module_spec_copy.GetUUID().Clear();
2296 ModuleList found_modules;
2297 m_images.FindModules(module_spec_copy, found_modules);
2298 found_modules.ForEach([&](const ModuleSP &found_module) -> bool {
2299 old_modules.push_back(found_module);
2300 return true;
2304 // If the locate module callback had found a symbol file, set it to the
2305 // module_sp before preloading symbols.
2306 if (symbol_file_spec)
2307 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2309 // Preload symbols outside of any lock, so hopefully we can do this for
2310 // each library in parallel.
2311 if (GetPreloadSymbols())
2312 module_sp->PreloadSymbols();
2313 llvm::SmallVector<ModuleSP, 1> replaced_modules;
2314 for (ModuleSP &old_module_sp : old_modules) {
2315 if (m_images.GetIndexForModule(old_module_sp.get()) !=
2316 LLDB_INVALID_INDEX32) {
2317 if (replaced_modules.empty())
2318 m_images.ReplaceModule(old_module_sp, module_sp);
2319 else
2320 m_images.Remove(old_module_sp);
2322 replaced_modules.push_back(std::move(old_module_sp));
2326 if (replaced_modules.size() > 1) {
2327 // The same new module replaced multiple old modules
2328 // simultaneously. It's not clear this should ever
2329 // happen (if we always replace old modules as we add
2330 // new ones, presumably we should never have more than
2331 // one old one). If there are legitimate cases where
2332 // this happens, then the ModuleList::Notifier interface
2333 // may need to be adjusted to allow reporting this.
2334 // In the meantime, just log that this has happened; just
2335 // above we called ReplaceModule on the first one, and Remove
2336 // on the rest.
2337 if (Log *log = GetLog(LLDBLog::Target | LLDBLog::Modules)) {
2338 StreamString message;
2339 auto dump = [&message](Module &dump_module) -> void {
2340 UUID dump_uuid = dump_module.GetUUID();
2342 message << '[';
2343 dump_module.GetDescription(message.AsRawOstream());
2344 message << " (uuid ";
2346 if (dump_uuid.IsValid())
2347 dump_uuid.Dump(message);
2348 else
2349 message << "not specified";
2351 message << ")]";
2354 message << "New module ";
2355 dump(*module_sp);
2356 message.AsRawOstream()
2357 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2358 replaced_modules.size());
2359 for (ModuleSP &replaced_module_sp : replaced_modules)
2360 dump(*replaced_module_sp);
2362 log->PutString(message.GetString());
2366 if (replaced_modules.empty())
2367 m_images.Append(module_sp, notify);
2369 for (ModuleSP &old_module_sp : replaced_modules) {
2370 Module *old_module_ptr = old_module_sp.get();
2371 old_module_sp.reset();
2372 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2374 } else
2375 module_sp.reset();
2378 if (error_ptr)
2379 *error_ptr = error;
2380 return module_sp;
2383 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2385 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2387 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2389 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2391 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2392 exe_ctx.Clear();
2393 exe_ctx.SetTargetPtr(this);
2396 PathMappingList &Target::GetImageSearchPathList() {
2397 return m_image_search_paths;
2400 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2401 void *baton) {
2402 Target *target = (Target *)baton;
2403 ModuleSP exe_module_sp(target->GetExecutableModule());
2404 if (exe_module_sp)
2405 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2408 llvm::Expected<lldb::TypeSystemSP>
2409 Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2410 bool create_on_demand) {
2411 if (!m_valid)
2412 return llvm::make_error<llvm::StringError>("Invalid Target",
2413 llvm::inconvertibleErrorCode());
2415 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2416 // assembly code
2417 || language == eLanguageTypeUnknown) {
2418 LanguageSet languages_for_expressions =
2419 Language::GetLanguagesSupportingTypeSystemsForExpressions();
2421 if (languages_for_expressions[eLanguageTypeC]) {
2422 language = eLanguageTypeC; // LLDB's default. Override by setting the
2423 // target language.
2424 } else {
2425 if (languages_for_expressions.Empty())
2426 return llvm::make_error<llvm::StringError>(
2427 "No expression support for any languages",
2428 llvm::inconvertibleErrorCode());
2429 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2433 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2434 create_on_demand);
2437 CompilerType Target::GetRegisterType(const std::string &name,
2438 const lldb_private::RegisterFlags &flags,
2439 uint32_t byte_size) {
2440 RegisterTypeBuilderSP provider = PluginManager::GetRegisterTypeBuilder(*this);
2441 assert(provider);
2442 return provider->GetRegisterType(name, flags, byte_size);
2445 std::vector<lldb::TypeSystemSP>
2446 Target::GetScratchTypeSystems(bool create_on_demand) {
2447 if (!m_valid)
2448 return {};
2450 // Some TypeSystem instances are associated with several LanguageTypes so
2451 // they will show up several times in the loop below. The SetVector filters
2452 // out all duplicates as they serve no use for the caller.
2453 std::vector<lldb::TypeSystemSP> scratch_type_systems;
2455 LanguageSet languages_for_expressions =
2456 Language::GetLanguagesSupportingTypeSystemsForExpressions();
2458 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2459 auto language = (LanguageType)bit;
2460 auto type_system_or_err =
2461 GetScratchTypeSystemForLanguage(language, create_on_demand);
2462 if (!type_system_or_err)
2463 LLDB_LOG_ERROR(
2464 GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2465 "Language '{1}' has expression support but no scratch type "
2466 "system available: {0}",
2467 Language::GetNameForLanguageType(language));
2468 else
2469 if (auto ts = *type_system_or_err)
2470 scratch_type_systems.push_back(ts);
2473 std::sort(scratch_type_systems.begin(), scratch_type_systems.end());
2474 scratch_type_systems.erase(
2475 std::unique(scratch_type_systems.begin(), scratch_type_systems.end()),
2476 scratch_type_systems.end());
2477 return scratch_type_systems;
2480 PersistentExpressionState *
2481 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2482 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2484 if (auto err = type_system_or_err.takeError()) {
2485 LLDB_LOG_ERROR(
2486 GetLog(LLDBLog::Target), std::move(err),
2487 "Unable to get persistent expression state for language {1}: {0}",
2488 Language::GetNameForLanguageType(language));
2489 return nullptr;
2492 if (auto ts = *type_system_or_err)
2493 return ts->GetPersistentExpressionState();
2495 LLDB_LOG(GetLog(LLDBLog::Target),
2496 "Unable to get persistent expression state for language {1}: {0}",
2497 Language::GetNameForLanguageType(language));
2498 return nullptr;
2501 UserExpression *Target::GetUserExpressionForLanguage(
2502 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2503 Expression::ResultType desired_type,
2504 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2505 Status &error) {
2506 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2507 if (auto err = type_system_or_err.takeError()) {
2508 error.SetErrorStringWithFormat(
2509 "Could not find type system for language %s: %s",
2510 Language::GetNameForLanguageType(language),
2511 llvm::toString(std::move(err)).c_str());
2512 return nullptr;
2515 auto ts = *type_system_or_err;
2516 if (!ts) {
2517 error.SetErrorStringWithFormat(
2518 "Type system for language %s is no longer live",
2519 Language::GetNameForLanguageType(language));
2520 return nullptr;
2523 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2524 options, ctx_obj);
2525 if (!user_expr)
2526 error.SetErrorStringWithFormat(
2527 "Could not create an expression for language %s",
2528 Language::GetNameForLanguageType(language));
2530 return user_expr;
2533 FunctionCaller *Target::GetFunctionCallerForLanguage(
2534 lldb::LanguageType language, const CompilerType &return_type,
2535 const Address &function_address, const ValueList &arg_value_list,
2536 const char *name, Status &error) {
2537 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2538 if (auto err = type_system_or_err.takeError()) {
2539 error.SetErrorStringWithFormat(
2540 "Could not find type system for language %s: %s",
2541 Language::GetNameForLanguageType(language),
2542 llvm::toString(std::move(err)).c_str());
2543 return nullptr;
2545 auto ts = *type_system_or_err;
2546 if (!ts) {
2547 error.SetErrorStringWithFormat(
2548 "Type system for language %s is no longer live",
2549 Language::GetNameForLanguageType(language));
2550 return nullptr;
2552 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2553 arg_value_list, name);
2554 if (!persistent_fn)
2555 error.SetErrorStringWithFormat(
2556 "Could not create an expression for language %s",
2557 Language::GetNameForLanguageType(language));
2559 return persistent_fn;
2562 llvm::Expected<std::unique_ptr<UtilityFunction>>
2563 Target::CreateUtilityFunction(std::string expression, std::string name,
2564 lldb::LanguageType language,
2565 ExecutionContext &exe_ctx) {
2566 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2567 if (!type_system_or_err)
2568 return type_system_or_err.takeError();
2569 auto ts = *type_system_or_err;
2570 if (!ts)
2571 return llvm::make_error<llvm::StringError>(
2572 llvm::StringRef("Type system for language ") +
2573 Language::GetNameForLanguageType(language) +
2574 llvm::StringRef(" is no longer live"),
2575 llvm::inconvertibleErrorCode());
2576 std::unique_ptr<UtilityFunction> utility_fn =
2577 ts->CreateUtilityFunction(std::move(expression), std::move(name));
2578 if (!utility_fn)
2579 return llvm::make_error<llvm::StringError>(
2580 llvm::StringRef("Could not create an expression for language") +
2581 Language::GetNameForLanguageType(language),
2582 llvm::inconvertibleErrorCode());
2584 DiagnosticManager diagnostics;
2585 if (!utility_fn->Install(diagnostics, exe_ctx))
2586 return llvm::make_error<llvm::StringError>(diagnostics.GetString(),
2587 llvm::inconvertibleErrorCode());
2589 return std::move(utility_fn);
2592 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2594 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2596 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2597 return Target::GetGlobalProperties().GetExecutableSearchPaths();
2600 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2601 return Target::GetGlobalProperties().GetDebugFileSearchPaths();
2604 ArchSpec Target::GetDefaultArchitecture() {
2605 return Target::GetGlobalProperties().GetDefaultArchitecture();
2608 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2609 LLDB_LOG(GetLog(LLDBLog::Target),
2610 "setting target's default architecture to {0} ({1})",
2611 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2612 Target::GetGlobalProperties().SetDefaultArchitecture(arch);
2615 llvm::Error Target::SetLabel(llvm::StringRef label) {
2616 size_t n = LLDB_INVALID_INDEX32;
2617 if (llvm::to_integer(label, n))
2618 return llvm::make_error<llvm::StringError>(
2619 "Cannot use integer as target label.", llvm::inconvertibleErrorCode());
2620 TargetList &targets = GetDebugger().GetTargetList();
2621 for (size_t i = 0; i < targets.GetNumTargets(); i++) {
2622 TargetSP target_sp = targets.GetTargetAtIndex(i);
2623 if (target_sp && target_sp->GetLabel() == label) {
2624 return llvm::make_error<llvm::StringError>(
2625 llvm::formatv(
2626 "Cannot use label '{0}' since it's set in target #{1}.", label,
2628 llvm::inconvertibleErrorCode());
2632 m_label = label.str();
2633 return llvm::Error::success();
2636 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2637 const SymbolContext *sc_ptr) {
2638 // The target can either exist in the "process" of ExecutionContext, or in
2639 // the "target_sp" member of SymbolContext. This accessor helper function
2640 // will get the target from one of these locations.
2642 Target *target = nullptr;
2643 if (sc_ptr != nullptr)
2644 target = sc_ptr->target_sp.get();
2645 if (target == nullptr && exe_ctx_ptr)
2646 target = exe_ctx_ptr->GetTargetPtr();
2647 return target;
2650 ExpressionResults Target::EvaluateExpression(
2651 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2652 lldb::ValueObjectSP &result_valobj_sp,
2653 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2654 ValueObject *ctx_obj) {
2655 result_valobj_sp.reset();
2657 ExpressionResults execution_results = eExpressionSetupError;
2659 if (expr.empty()) {
2660 m_stats.GetExpressionStats().NotifyFailure();
2661 return execution_results;
2664 // We shouldn't run stop hooks in expressions.
2665 bool old_suppress_value = m_suppress_stop_hooks;
2666 m_suppress_stop_hooks = true;
2667 auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2668 m_suppress_stop_hooks = old_suppress_value;
2671 ExecutionContext exe_ctx;
2673 if (exe_scope) {
2674 exe_scope->CalculateExecutionContext(exe_ctx);
2675 } else if (m_process_sp) {
2676 m_process_sp->CalculateExecutionContext(exe_ctx);
2677 } else {
2678 CalculateExecutionContext(exe_ctx);
2681 // Make sure we aren't just trying to see the value of a persistent variable
2682 // (something like "$0")
2683 // Only check for persistent variables the expression starts with a '$'
2684 lldb::ExpressionVariableSP persistent_var_sp;
2685 if (expr[0] == '$') {
2686 auto type_system_or_err =
2687 GetScratchTypeSystemForLanguage(eLanguageTypeC);
2688 if (auto err = type_system_or_err.takeError()) {
2689 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2690 "Unable to get scratch type system");
2691 } else {
2692 auto ts = *type_system_or_err;
2693 if (!ts)
2694 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2695 "Scratch type system is no longer live: {0}");
2696 else
2697 persistent_var_sp =
2698 ts->GetPersistentExpressionState()->GetVariable(expr);
2701 if (persistent_var_sp) {
2702 result_valobj_sp = persistent_var_sp->GetValueObject();
2703 execution_results = eExpressionCompleted;
2704 } else {
2705 llvm::StringRef prefix = GetExpressionPrefixContents();
2706 Status error;
2707 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2708 result_valobj_sp, error,
2709 fixed_expression, ctx_obj);
2710 // Pass up the error by wrapping it inside an error result.
2711 if (error.Fail() && !result_valobj_sp)
2712 result_valobj_sp = ValueObjectConstResult::Create(
2713 exe_ctx.GetBestExecutionContextScope(), error);
2716 if (execution_results == eExpressionCompleted)
2717 m_stats.GetExpressionStats().NotifySuccess();
2718 else
2719 m_stats.GetExpressionStats().NotifyFailure();
2720 return execution_results;
2723 lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2724 lldb::ExpressionVariableSP variable_sp;
2725 m_scratch_type_system_map.ForEach(
2726 [name, &variable_sp](TypeSystemSP type_system) -> bool {
2727 auto ts = type_system.get();
2728 if (!ts)
2729 return true;
2730 if (PersistentExpressionState *persistent_state =
2731 ts->GetPersistentExpressionState()) {
2732 variable_sp = persistent_state->GetVariable(name);
2734 if (variable_sp)
2735 return false; // Stop iterating the ForEach
2737 return true; // Keep iterating the ForEach
2739 return variable_sp;
2742 lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2743 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2745 m_scratch_type_system_map.ForEach(
2746 [name, &address](lldb::TypeSystemSP type_system) -> bool {
2747 auto ts = type_system.get();
2748 if (!ts)
2749 return true;
2751 if (PersistentExpressionState *persistent_state =
2752 ts->GetPersistentExpressionState()) {
2753 address = persistent_state->LookupSymbol(name);
2754 if (address != LLDB_INVALID_ADDRESS)
2755 return false; // Stop iterating the ForEach
2757 return true; // Keep iterating the ForEach
2759 return address;
2762 llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2763 Module *exe_module = GetExecutableModulePointer();
2765 // Try to find the entry point address in the primary executable.
2766 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2767 if (has_primary_executable) {
2768 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2769 if (entry_addr.IsValid())
2770 return entry_addr;
2773 const ModuleList &modules = GetImages();
2774 const size_t num_images = modules.GetSize();
2775 for (size_t idx = 0; idx < num_images; ++idx) {
2776 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2777 if (!module_sp || !module_sp->GetObjectFile())
2778 continue;
2780 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2781 if (entry_addr.IsValid())
2782 return entry_addr;
2785 // We haven't found the entry point address. Return an appropriate error.
2786 if (!has_primary_executable)
2787 return llvm::make_error<llvm::StringError>(
2788 "No primary executable found and could not find entry point address in "
2789 "any executable module",
2790 llvm::inconvertibleErrorCode());
2792 return llvm::make_error<llvm::StringError>(
2793 "Could not find entry point address for primary executable module \"" +
2794 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2795 llvm::inconvertibleErrorCode());
2798 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2799 AddressClass addr_class) const {
2800 auto arch_plugin = GetArchitecturePlugin();
2801 return arch_plugin
2802 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2803 : load_addr;
2806 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2807 AddressClass addr_class) const {
2808 auto arch_plugin = GetArchitecturePlugin();
2809 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2810 : load_addr;
2813 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2814 auto arch_plugin = GetArchitecturePlugin();
2815 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2818 SourceManager &Target::GetSourceManager() {
2819 if (!m_source_manager_up)
2820 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2821 return *m_source_manager_up;
2824 Target::StopHookSP Target::CreateStopHook(StopHook::StopHookKind kind) {
2825 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2826 Target::StopHookSP stop_hook_sp;
2827 switch (kind) {
2828 case StopHook::StopHookKind::CommandBased:
2829 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2830 break;
2831 case StopHook::StopHookKind::ScriptBased:
2832 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2833 break;
2835 m_stop_hooks[new_uid] = stop_hook_sp;
2836 return stop_hook_sp;
2839 void Target::UndoCreateStopHook(lldb::user_id_t user_id) {
2840 if (!RemoveStopHookByID(user_id))
2841 return;
2842 if (user_id == m_stop_hook_next_id)
2843 m_stop_hook_next_id--;
2846 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2847 size_t num_removed = m_stop_hooks.erase(user_id);
2848 return (num_removed != 0);
2851 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2853 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2854 StopHookSP found_hook;
2856 StopHookCollection::iterator specified_hook_iter;
2857 specified_hook_iter = m_stop_hooks.find(user_id);
2858 if (specified_hook_iter != m_stop_hooks.end())
2859 found_hook = (*specified_hook_iter).second;
2860 return found_hook;
2863 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2864 bool active_state) {
2865 StopHookCollection::iterator specified_hook_iter;
2866 specified_hook_iter = m_stop_hooks.find(user_id);
2867 if (specified_hook_iter == m_stop_hooks.end())
2868 return false;
2870 (*specified_hook_iter).second->SetIsActive(active_state);
2871 return true;
2874 void Target::SetAllStopHooksActiveState(bool active_state) {
2875 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2876 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2877 (*pos).second->SetIsActive(active_state);
2881 bool Target::RunStopHooks() {
2882 if (m_suppress_stop_hooks)
2883 return false;
2885 if (!m_process_sp)
2886 return false;
2888 // Somebody might have restarted the process:
2889 // Still return false, the return value is about US restarting the target.
2890 if (m_process_sp->GetState() != eStateStopped)
2891 return false;
2893 if (m_stop_hooks.empty())
2894 return false;
2896 // If there aren't any active stop hooks, don't bother either.
2897 bool any_active_hooks = false;
2898 for (auto hook : m_stop_hooks) {
2899 if (hook.second->IsActive()) {
2900 any_active_hooks = true;
2901 break;
2904 if (!any_active_hooks)
2905 return false;
2907 // Make sure we check that we are not stopped because of us running a user
2908 // expression since in that case we do not want to run the stop-hooks. Note,
2909 // you can't just check whether the last stop was for a User Expression,
2910 // because breakpoint commands get run before stop hooks, and one of them
2911 // might have run an expression. You have to ensure you run the stop hooks
2912 // once per natural stop.
2913 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
2914 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
2915 return false;
2917 m_latest_stop_hook_id = last_natural_stop;
2919 std::vector<ExecutionContext> exc_ctx_with_reasons;
2921 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2922 size_t num_threads = cur_threadlist.GetSize();
2923 for (size_t i = 0; i < num_threads; i++) {
2924 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2925 if (cur_thread_sp->ThreadStoppedForAReason()) {
2926 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2927 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
2928 cur_frame_sp.get());
2932 // If no threads stopped for a reason, don't run the stop-hooks.
2933 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2934 if (num_exe_ctx == 0)
2935 return false;
2937 StreamSP output_sp = m_debugger.GetAsyncOutputStream();
2939 bool auto_continue = false;
2940 bool hooks_ran = false;
2941 bool print_hook_header = (m_stop_hooks.size() != 1);
2942 bool print_thread_header = (num_exe_ctx != 1);
2943 bool should_stop = false;
2944 bool somebody_restarted = false;
2946 for (auto stop_entry : m_stop_hooks) {
2947 StopHookSP cur_hook_sp = stop_entry.second;
2948 if (!cur_hook_sp->IsActive())
2949 continue;
2951 bool any_thread_matched = false;
2952 for (auto exc_ctx : exc_ctx_with_reasons) {
2953 // We detect somebody restarted in the stop-hook loop, and broke out of
2954 // that loop back to here. So break out of here too.
2955 if (somebody_restarted)
2956 break;
2958 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
2959 continue;
2961 // We only consult the auto-continue for a stop hook if it matched the
2962 // specifier.
2963 auto_continue |= cur_hook_sp->GetAutoContinue();
2965 if (!hooks_ran)
2966 hooks_ran = true;
2968 if (print_hook_header && !any_thread_matched) {
2969 StreamString s;
2970 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
2971 if (s.GetSize() != 0)
2972 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
2973 s.GetData());
2974 else
2975 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2976 any_thread_matched = true;
2979 if (print_thread_header)
2980 output_sp->Printf("-- Thread %d\n",
2981 exc_ctx.GetThreadPtr()->GetIndexID());
2983 StopHook::StopHookResult this_result =
2984 cur_hook_sp->HandleStop(exc_ctx, output_sp);
2985 bool this_should_stop = true;
2987 switch (this_result) {
2988 case StopHook::StopHookResult::KeepStopped:
2989 // If this hook is set to auto-continue that should override the
2990 // HandleStop result...
2991 if (cur_hook_sp->GetAutoContinue())
2992 this_should_stop = false;
2993 else
2994 this_should_stop = true;
2996 break;
2997 case StopHook::StopHookResult::RequestContinue:
2998 this_should_stop = false;
2999 break;
3000 case StopHook::StopHookResult::AlreadyContinued:
3001 // We don't have a good way to prohibit people from restarting the
3002 // target willy nilly in a stop hook. If the hook did so, give a
3003 // gentle suggestion here and bag out if the hook processing.
3004 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3005 " set the program running.\n"
3006 " Consider using '-G true' to make "
3007 "stop hooks auto-continue.\n",
3008 cur_hook_sp->GetID());
3009 somebody_restarted = true;
3010 break;
3012 // If we're already restarted, stop processing stop hooks.
3013 // FIXME: if we are doing non-stop mode for real, we would have to
3014 // check that OUR thread was restarted, otherwise we should keep
3015 // processing stop hooks.
3016 if (somebody_restarted)
3017 break;
3019 // If anybody wanted to stop, we should all stop.
3020 if (!should_stop)
3021 should_stop = this_should_stop;
3025 output_sp->Flush();
3027 // If one of the commands in the stop hook already restarted the target,
3028 // report that fact.
3029 if (somebody_restarted)
3030 return true;
3032 // Finally, if auto-continue was requested, do it now:
3033 // We only compute should_stop against the hook results if a hook got to run
3034 // which is why we have to do this conjoint test.
3035 if ((hooks_ran && !should_stop) || auto_continue) {
3036 Log *log = GetLog(LLDBLog::Process);
3037 Status error = m_process_sp->PrivateResume();
3038 if (error.Success()) {
3039 LLDB_LOG(log, "Resuming from RunStopHooks");
3040 return true;
3041 } else {
3042 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3043 return false;
3047 return false;
3050 TargetProperties &Target::GetGlobalProperties() {
3051 // NOTE: intentional leak so we don't crash if global destructor chain gets
3052 // called as other threads still use the result of this function
3053 static TargetProperties *g_settings_ptr =
3054 new TargetProperties(nullptr);
3055 return *g_settings_ptr;
3058 Status Target::Install(ProcessLaunchInfo *launch_info) {
3059 Status error;
3060 PlatformSP platform_sp(GetPlatform());
3061 if (platform_sp) {
3062 if (platform_sp->IsRemote()) {
3063 if (platform_sp->IsConnected()) {
3064 // Install all files that have an install path when connected to a
3065 // remote platform. If target.auto-install-main-executable is set then
3066 // also install the main executable even if it does not have an explicit
3067 // install path specified.
3068 const ModuleList &modules = GetImages();
3069 const size_t num_images = modules.GetSize();
3070 for (size_t idx = 0; idx < num_images; ++idx) {
3071 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
3072 if (module_sp) {
3073 const bool is_main_executable = module_sp == GetExecutableModule();
3074 FileSpec local_file(module_sp->GetFileSpec());
3075 if (local_file) {
3076 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
3077 if (!remote_file) {
3078 if (is_main_executable && GetAutoInstallMainExecutable()) {
3079 // Automatically install the main executable.
3080 remote_file = platform_sp->GetRemoteWorkingDirectory();
3081 remote_file.AppendPathComponent(
3082 module_sp->GetFileSpec().GetFilename().GetCString());
3085 if (remote_file) {
3086 error = platform_sp->Install(local_file, remote_file);
3087 if (error.Success()) {
3088 module_sp->SetPlatformFileSpec(remote_file);
3089 if (is_main_executable) {
3090 platform_sp->SetFilePermissions(remote_file, 0700);
3091 if (launch_info)
3092 launch_info->SetExecutableFile(remote_file, false);
3094 } else
3095 break;
3103 return error;
3106 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
3107 uint32_t stop_id) {
3108 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
3111 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
3112 Address &resolved_addr) {
3113 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3116 bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
3117 addr_t new_section_load_addr,
3118 bool warn_multiple) {
3119 const addr_t old_section_load_addr =
3120 m_section_load_history.GetSectionLoadAddress(
3121 SectionLoadHistory::eStopIDNow, section_sp);
3122 if (old_section_load_addr != new_section_load_addr) {
3123 uint32_t stop_id = 0;
3124 ProcessSP process_sp(GetProcessSP());
3125 if (process_sp)
3126 stop_id = process_sp->GetStopID();
3127 else
3128 stop_id = m_section_load_history.GetLastStopID();
3129 if (m_section_load_history.SetSectionLoadAddress(
3130 stop_id, section_sp, new_section_load_addr, warn_multiple))
3131 return true; // Return true if the section load address was changed...
3133 return false; // Return false to indicate nothing changed
3136 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3137 size_t section_unload_count = 0;
3138 size_t num_modules = module_list.GetSize();
3139 for (size_t i = 0; i < num_modules; ++i) {
3140 section_unload_count +=
3141 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3143 return section_unload_count;
3146 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
3147 uint32_t stop_id = 0;
3148 ProcessSP process_sp(GetProcessSP());
3149 if (process_sp)
3150 stop_id = process_sp->GetStopID();
3151 else
3152 stop_id = m_section_load_history.GetLastStopID();
3153 SectionList *sections = module_sp->GetSectionList();
3154 size_t section_unload_count = 0;
3155 if (sections) {
3156 const uint32_t num_sections = sections->GetNumSections(0);
3157 for (uint32_t i = 0; i < num_sections; ++i) {
3158 section_unload_count += m_section_load_history.SetSectionUnloaded(
3159 stop_id, sections->GetSectionAtIndex(i));
3162 return section_unload_count;
3165 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
3166 uint32_t stop_id = 0;
3167 ProcessSP process_sp(GetProcessSP());
3168 if (process_sp)
3169 stop_id = process_sp->GetStopID();
3170 else
3171 stop_id = m_section_load_history.GetLastStopID();
3172 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3175 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
3176 addr_t load_addr) {
3177 uint32_t stop_id = 0;
3178 ProcessSP process_sp(GetProcessSP());
3179 if (process_sp)
3180 stop_id = process_sp->GetStopID();
3181 else
3182 stop_id = m_section_load_history.GetLastStopID();
3183 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3184 load_addr);
3187 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
3189 void Target::SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info) {
3190 if (process_info.IsScriptedProcess()) {
3191 // Only copy scripted process launch options.
3192 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3193 GetGlobalProperties().GetProcessLaunchInfo());
3194 default_launch_info.SetProcessPluginName("ScriptedProcess");
3195 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3196 SetProcessLaunchInfo(default_launch_info);
3200 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
3201 m_stats.SetLaunchOrAttachTime();
3202 Status error;
3203 Log *log = GetLog(LLDBLog::Target);
3205 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3206 launch_info.GetExecutableFile().GetPath().c_str());
3208 StateType state = eStateInvalid;
3210 // Scope to temporarily get the process state in case someone has manually
3211 // remotely connected already to a process and we can skip the platform
3212 // launching.
3214 ProcessSP process_sp(GetProcessSP());
3216 if (process_sp) {
3217 state = process_sp->GetState();
3218 LLDB_LOGF(log,
3219 "Target::%s the process exists, and its current state is %s",
3220 __FUNCTION__, StateAsCString(state));
3221 } else {
3222 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3223 __FUNCTION__);
3227 launch_info.GetFlags().Set(eLaunchFlagDebug);
3229 SaveScriptedLaunchInfo(launch_info);
3231 // Get the value of synchronous execution here. If you wait till after you
3232 // have started to run, then you could have hit a breakpoint, whose command
3233 // might switch the value, and then you'll pick up that incorrect value.
3234 Debugger &debugger = GetDebugger();
3235 const bool synchronous_execution =
3236 debugger.GetCommandInterpreter().GetSynchronous();
3238 PlatformSP platform_sp(GetPlatform());
3240 FinalizeFileActions(launch_info);
3242 if (state == eStateConnected) {
3243 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3244 error.SetErrorString(
3245 "can't launch in tty when launching through a remote connection");
3246 return error;
3250 if (!launch_info.GetArchitecture().IsValid())
3251 launch_info.GetArchitecture() = GetArchitecture();
3253 // Hijacking events of the process to be created to be sure that all events
3254 // until the first stop are intercepted (in case if platform doesn't define
3255 // its own hijacking listener or if the process is created by the target
3256 // manually, without the platform).
3257 if (!launch_info.GetHijackListener())
3258 launch_info.SetHijackListener(Listener::MakeListener(
3259 Process::LaunchSynchronousHijackListenerName.data()));
3261 // If we're not already connected to the process, and if we have a platform
3262 // that can launch a process for debugging, go ahead and do that here.
3263 if (state != eStateConnected && platform_sp &&
3264 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3265 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3266 __FUNCTION__);
3268 // If there was a previous process, delete it before we make the new one.
3269 // One subtle point, we delete the process before we release the reference
3270 // to m_process_sp. That way even if we are the last owner, the process
3271 // will get Finalized before it gets destroyed.
3272 DeleteCurrentProcess();
3274 m_process_sp =
3275 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3277 } else {
3278 LLDB_LOGF(log,
3279 "Target::%s the platform doesn't know how to debug a "
3280 "process, getting a process plugin to do this for us.",
3281 __FUNCTION__);
3283 if (state == eStateConnected) {
3284 assert(m_process_sp);
3285 } else {
3286 // Use a Process plugin to construct the process.
3287 CreateProcess(launch_info.GetListener(),
3288 launch_info.GetProcessPluginName(), nullptr, false);
3291 // Since we didn't have a platform launch the process, launch it here.
3292 if (m_process_sp) {
3293 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3294 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3295 error = m_process_sp->Launch(launch_info);
3299 if (!m_process_sp && error.Success())
3300 error.SetErrorString("failed to launch or debug process");
3302 if (!error.Success())
3303 return error;
3305 bool rebroadcast_first_stop =
3306 !synchronous_execution &&
3307 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3309 assert(launch_info.GetHijackListener());
3311 EventSP first_stop_event_sp;
3312 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3313 rebroadcast_first_stop,
3314 launch_info.GetHijackListener());
3315 m_process_sp->RestoreProcessEvents();
3317 if (rebroadcast_first_stop) {
3318 assert(first_stop_event_sp);
3319 m_process_sp->BroadcastEvent(first_stop_event_sp);
3320 return error;
3323 switch (state) {
3324 case eStateStopped: {
3325 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3326 break;
3327 if (synchronous_execution)
3328 // Now we have handled the stop-from-attach, and we are just
3329 // switching to a synchronous resume. So we should switch to the
3330 // SyncResume hijacker.
3331 m_process_sp->ResumeSynchronous(stream);
3332 else
3333 error = m_process_sp->Resume();
3334 if (!error.Success()) {
3335 Status error2;
3336 error2.SetErrorStringWithFormat(
3337 "process resume at entry point failed: %s", error.AsCString());
3338 error = error2;
3340 } break;
3341 case eStateExited: {
3342 bool with_shell = !!launch_info.GetShell();
3343 const int exit_status = m_process_sp->GetExitStatus();
3344 const char *exit_desc = m_process_sp->GetExitDescription();
3345 std::string desc;
3346 if (exit_desc && exit_desc[0])
3347 desc = " (" + std::string(exit_desc) + ')';
3348 if (with_shell)
3349 error.SetErrorStringWithFormat(
3350 "process exited with status %i%s\n"
3351 "'r' and 'run' are aliases that default to launching through a "
3352 "shell.\n"
3353 "Try launching without going through a shell by using "
3354 "'process launch'.",
3355 exit_status, desc.c_str());
3356 else
3357 error.SetErrorStringWithFormat("process exited with status %i%s",
3358 exit_status, desc.c_str());
3359 } break;
3360 default:
3361 error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
3362 StateAsCString(state));
3363 break;
3365 return error;
3368 void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3370 TraceSP Target::GetTrace() { return m_trace_sp; }
3372 llvm::Expected<TraceSP> Target::CreateTrace() {
3373 if (!m_process_sp)
3374 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3375 "A process is required for tracing");
3376 if (m_trace_sp)
3377 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3378 "A trace already exists for the target");
3380 llvm::Expected<TraceSupportedResponse> trace_type =
3381 m_process_sp->TraceSupported();
3382 if (!trace_type)
3383 return llvm::createStringError(
3384 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3385 llvm::toString(trace_type.takeError()).c_str());
3386 if (llvm::Expected<TraceSP> trace_sp =
3387 Trace::FindPluginForLiveProcess(trace_type->name, *m_process_sp))
3388 m_trace_sp = *trace_sp;
3389 else
3390 return llvm::createStringError(
3391 llvm::inconvertibleErrorCode(),
3392 "Couldn't create a Trace object for the process. %s",
3393 llvm::toString(trace_sp.takeError()).c_str());
3394 return m_trace_sp;
3397 llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3398 if (m_trace_sp)
3399 return m_trace_sp;
3400 return CreateTrace();
3403 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3404 m_stats.SetLaunchOrAttachTime();
3405 auto state = eStateInvalid;
3406 auto process_sp = GetProcessSP();
3407 if (process_sp) {
3408 state = process_sp->GetState();
3409 if (process_sp->IsAlive() && state != eStateConnected) {
3410 if (state == eStateAttaching)
3411 return Status("process attach is in progress");
3412 return Status("a process is already being debugged");
3416 const ModuleSP old_exec_module_sp = GetExecutableModule();
3418 // If no process info was specified, then use the target executable name as
3419 // the process to attach to by default
3420 if (!attach_info.ProcessInfoSpecified()) {
3421 if (old_exec_module_sp)
3422 attach_info.GetExecutableFile().SetFilename(
3423 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3425 if (!attach_info.ProcessInfoSpecified()) {
3426 return Status("no process specified, create a target with a file, or "
3427 "specify the --pid or --name");
3431 const auto platform_sp =
3432 GetDebugger().GetPlatformList().GetSelectedPlatform();
3433 ListenerSP hijack_listener_sp;
3434 const bool async = attach_info.GetAsync();
3435 if (!async) {
3436 hijack_listener_sp = Listener::MakeListener(
3437 Process::AttachSynchronousHijackListenerName.data());
3438 attach_info.SetHijackListener(hijack_listener_sp);
3441 Status error;
3442 if (state != eStateConnected && platform_sp != nullptr &&
3443 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3444 SetPlatform(platform_sp);
3445 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3446 } else {
3447 if (state != eStateConnected) {
3448 SaveScriptedLaunchInfo(attach_info);
3449 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3450 process_sp =
3451 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3452 plugin_name, nullptr, false);
3453 if (!process_sp) {
3454 error.SetErrorStringWithFormatv(
3455 "failed to create process using plugin '{0}'",
3456 plugin_name.empty() ? "<empty>" : plugin_name);
3457 return error;
3460 if (hijack_listener_sp)
3461 process_sp->HijackProcessEvents(hijack_listener_sp);
3462 error = process_sp->Attach(attach_info);
3465 if (error.Success() && process_sp) {
3466 if (async) {
3467 process_sp->RestoreProcessEvents();
3468 } else {
3469 // We are stopping all the way out to the user, so update selected frames.
3470 state = process_sp->WaitForProcessToStop(
3471 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3472 true, SelectMostRelevantFrame);
3473 process_sp->RestoreProcessEvents();
3475 if (state != eStateStopped) {
3476 const char *exit_desc = process_sp->GetExitDescription();
3477 if (exit_desc)
3478 error.SetErrorStringWithFormat("%s", exit_desc);
3479 else
3480 error.SetErrorString(
3481 "process did not stop (no such process or permission problem?)");
3482 process_sp->Destroy(false);
3486 return error;
3489 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3490 Log *log = GetLog(LLDBLog::Process);
3492 // Finalize the file actions, and if none were given, default to opening up a
3493 // pseudo terminal
3494 PlatformSP platform_sp = GetPlatform();
3495 const bool default_to_use_pty =
3496 m_platform_sp ? m_platform_sp->IsHost() : false;
3497 LLDB_LOG(
3498 log,
3499 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3500 bool(platform_sp),
3501 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3502 default_to_use_pty);
3504 // If nothing for stdin or stdout or stderr was specified, then check the
3505 // process for any default settings that were set with "settings set"
3506 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3507 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3508 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3509 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3510 "default handling");
3512 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3513 // Do nothing, if we are launching in a remote terminal no file actions
3514 // should be done at all.
3515 return;
3518 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3519 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3520 "for stdin, stdout and stderr");
3521 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3522 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3523 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3524 } else {
3525 // Check for any values that might have gotten set with any of: (lldb)
3526 // settings set target.input-path (lldb) settings set target.output-path
3527 // (lldb) settings set target.error-path
3528 FileSpec in_file_spec;
3529 FileSpec out_file_spec;
3530 FileSpec err_file_spec;
3531 // Only override with the target settings if we don't already have an
3532 // action for in, out or error
3533 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3534 in_file_spec = GetStandardInputPath();
3535 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3536 out_file_spec = GetStandardOutputPath();
3537 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3538 err_file_spec = GetStandardErrorPath();
3540 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3541 in_file_spec, out_file_spec, err_file_spec);
3543 if (in_file_spec) {
3544 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3545 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3548 if (out_file_spec) {
3549 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3550 LLDB_LOG(log, "appended stdout open file action for {0}",
3551 out_file_spec);
3554 if (err_file_spec) {
3555 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3556 LLDB_LOG(log, "appended stderr open file action for {0}",
3557 err_file_spec);
3560 if (default_to_use_pty) {
3561 llvm::Error Err = info.SetUpPtyRedirection();
3562 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3568 void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
3569 LazyBool stop) {
3570 if (name.empty())
3571 return;
3572 // Don't add a signal if all the actions are trivial:
3573 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
3574 && stop == eLazyBoolCalculate)
3575 return;
3577 auto& elem = m_dummy_signals[name];
3578 elem.pass = pass;
3579 elem.notify = notify;
3580 elem.stop = stop;
3583 bool Target::UpdateSignalFromDummy(UnixSignalsSP signals_sp,
3584 const DummySignalElement &elem) {
3585 if (!signals_sp)
3586 return false;
3588 int32_t signo
3589 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3590 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3591 return false;
3593 if (elem.second.pass == eLazyBoolYes)
3594 signals_sp->SetShouldSuppress(signo, false);
3595 else if (elem.second.pass == eLazyBoolNo)
3596 signals_sp->SetShouldSuppress(signo, true);
3598 if (elem.second.notify == eLazyBoolYes)
3599 signals_sp->SetShouldNotify(signo, true);
3600 else if (elem.second.notify == eLazyBoolNo)
3601 signals_sp->SetShouldNotify(signo, false);
3603 if (elem.second.stop == eLazyBoolYes)
3604 signals_sp->SetShouldStop(signo, true);
3605 else if (elem.second.stop == eLazyBoolNo)
3606 signals_sp->SetShouldStop(signo, false);
3607 return true;
3610 bool Target::ResetSignalFromDummy(UnixSignalsSP signals_sp,
3611 const DummySignalElement &elem) {
3612 if (!signals_sp)
3613 return false;
3614 int32_t signo
3615 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3616 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3617 return false;
3618 bool do_pass = elem.second.pass != eLazyBoolCalculate;
3619 bool do_stop = elem.second.stop != eLazyBoolCalculate;
3620 bool do_notify = elem.second.notify != eLazyBoolCalculate;
3621 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
3622 return true;
3625 void Target::UpdateSignalsFromDummy(UnixSignalsSP signals_sp,
3626 StreamSP warning_stream_sp) {
3627 if (!signals_sp)
3628 return;
3630 for (const auto &elem : m_dummy_signals) {
3631 if (!UpdateSignalFromDummy(signals_sp, elem))
3632 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
3633 elem.first().str().c_str());
3637 void Target::ClearDummySignals(Args &signal_names) {
3638 ProcessSP process_sp = GetProcessSP();
3639 // The simplest case, delete them all with no process to update.
3640 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
3641 m_dummy_signals.clear();
3642 return;
3644 UnixSignalsSP signals_sp;
3645 if (process_sp)
3646 signals_sp = process_sp->GetUnixSignals();
3648 for (const Args::ArgEntry &entry : signal_names) {
3649 const char *signal_name = entry.c_str();
3650 auto elem = m_dummy_signals.find(signal_name);
3651 // If we didn't find it go on.
3652 // FIXME: Should I pipe error handling through here?
3653 if (elem == m_dummy_signals.end()) {
3654 continue;
3656 if (signals_sp)
3657 ResetSignalFromDummy(signals_sp, *elem);
3658 m_dummy_signals.erase(elem);
3662 void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
3663 strm.Printf("NAME PASS STOP NOTIFY\n");
3664 strm.Printf("=========== ======= ======= =======\n");
3666 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
3667 switch (lazy) {
3668 case eLazyBoolCalculate: return "not set";
3669 case eLazyBoolYes: return "true ";
3670 case eLazyBoolNo: return "false ";
3672 llvm_unreachable("Fully covered switch above!");
3674 size_t num_args = signal_args.GetArgumentCount();
3675 for (const auto &elem : m_dummy_signals) {
3676 bool print_it = false;
3677 for (size_t idx = 0; idx < num_args; idx++) {
3678 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
3679 print_it = true;
3680 break;
3683 if (print_it) {
3684 strm.Printf("%-11s ", elem.first().str().c_str());
3685 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
3686 str_for_lazy(elem.second.stop),
3687 str_for_lazy(elem.second.notify));
3692 // Target::StopHook
3693 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3694 : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3695 m_thread_spec_up() {}
3697 Target::StopHook::StopHook(const StopHook &rhs)
3698 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3699 m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3700 m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3701 if (rhs.m_thread_spec_up)
3702 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3705 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3706 m_specifier_sp.reset(specifier);
3709 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3710 m_thread_spec_up.reset(specifier);
3713 bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) {
3714 SymbolContextSpecifier *specifier = GetSpecifier();
3715 if (!specifier)
3716 return true;
3718 bool will_run = true;
3719 if (exc_ctx.GetFramePtr())
3720 will_run = GetSpecifier()->SymbolContextMatches(
3721 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3722 if (will_run && GetThreadSpecifier() != nullptr)
3723 will_run =
3724 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3726 return will_run;
3729 void Target::StopHook::GetDescription(Stream &s,
3730 lldb::DescriptionLevel level) const {
3732 // For brief descriptions, only print the subclass description:
3733 if (level == eDescriptionLevelBrief) {
3734 GetSubclassDescription(s, level);
3735 return;
3738 unsigned indent_level = s.GetIndentLevel();
3740 s.SetIndentLevel(indent_level + 2);
3742 s.Printf("Hook: %" PRIu64 "\n", GetID());
3743 if (m_active)
3744 s.Indent("State: enabled\n");
3745 else
3746 s.Indent("State: disabled\n");
3748 if (m_auto_continue)
3749 s.Indent("AutoContinue on\n");
3751 if (m_specifier_sp) {
3752 s.Indent();
3753 s.PutCString("Specifier:\n");
3754 s.SetIndentLevel(indent_level + 4);
3755 m_specifier_sp->GetDescription(&s, level);
3756 s.SetIndentLevel(indent_level + 2);
3759 if (m_thread_spec_up) {
3760 StreamString tmp;
3761 s.Indent("Thread:\n");
3762 m_thread_spec_up->GetDescription(&tmp, level);
3763 s.SetIndentLevel(indent_level + 4);
3764 s.Indent(tmp.GetString());
3765 s.PutCString("\n");
3766 s.SetIndentLevel(indent_level + 2);
3768 GetSubclassDescription(s, level);
3771 void Target::StopHookCommandLine::GetSubclassDescription(
3772 Stream &s, lldb::DescriptionLevel level) const {
3773 // The brief description just prints the first command.
3774 if (level == eDescriptionLevelBrief) {
3775 if (m_commands.GetSize() == 1)
3776 s.PutCString(m_commands.GetStringAtIndex(0));
3777 return;
3779 s.Indent("Commands: \n");
3780 s.SetIndentLevel(s.GetIndentLevel() + 4);
3781 uint32_t num_commands = m_commands.GetSize();
3782 for (uint32_t i = 0; i < num_commands; i++) {
3783 s.Indent(m_commands.GetStringAtIndex(i));
3784 s.PutCString("\n");
3786 s.SetIndentLevel(s.GetIndentLevel() - 4);
3789 // Target::StopHookCommandLine
3790 void Target::StopHookCommandLine::SetActionFromString(const std::string &string) {
3791 GetCommands().SplitIntoLines(string);
3794 void Target::StopHookCommandLine::SetActionFromStrings(
3795 const std::vector<std::string> &strings) {
3796 for (auto string : strings)
3797 GetCommands().AppendString(string.c_str());
3800 Target::StopHook::StopHookResult
3801 Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx,
3802 StreamSP output_sp) {
3803 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3804 "with no target");
3806 if (!m_commands.GetSize())
3807 return StopHookResult::KeepStopped;
3809 CommandReturnObject result(false);
3810 result.SetImmediateOutputStream(output_sp);
3811 result.SetInteractive(false);
3812 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3813 CommandInterpreterRunOptions options;
3814 options.SetStopOnContinue(true);
3815 options.SetStopOnError(true);
3816 options.SetEchoCommands(false);
3817 options.SetPrintResults(true);
3818 options.SetPrintErrors(true);
3819 options.SetAddToHistory(false);
3821 // Force Async:
3822 bool old_async = debugger.GetAsyncExecution();
3823 debugger.SetAsyncExecution(true);
3824 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
3825 options, result);
3826 debugger.SetAsyncExecution(old_async);
3827 lldb::ReturnStatus status = result.GetStatus();
3828 if (status == eReturnStatusSuccessContinuingNoResult ||
3829 status == eReturnStatusSuccessContinuingResult)
3830 return StopHookResult::AlreadyContinued;
3831 return StopHookResult::KeepStopped;
3834 // Target::StopHookScripted
3835 Status Target::StopHookScripted::SetScriptCallback(
3836 std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3837 Status error;
3839 ScriptInterpreter *script_interp =
3840 GetTarget()->GetDebugger().GetScriptInterpreter();
3841 if (!script_interp) {
3842 error.SetErrorString("No script interpreter installed.");
3843 return error;
3846 m_class_name = class_name;
3847 m_extra_args.SetObjectSP(extra_args_sp);
3849 m_implementation_sp = script_interp->CreateScriptedStopHook(
3850 GetTarget(), m_class_name.c_str(), m_extra_args, error);
3852 return error;
3855 Target::StopHook::StopHookResult
3856 Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx,
3857 StreamSP output_sp) {
3858 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3859 "with no target");
3861 ScriptInterpreter *script_interp =
3862 GetTarget()->GetDebugger().GetScriptInterpreter();
3863 if (!script_interp)
3864 return StopHookResult::KeepStopped;
3866 bool should_stop = script_interp->ScriptedStopHookHandleStop(
3867 m_implementation_sp, exc_ctx, output_sp);
3869 return should_stop ? StopHookResult::KeepStopped
3870 : StopHookResult::RequestContinue;
3873 void Target::StopHookScripted::GetSubclassDescription(
3874 Stream &s, lldb::DescriptionLevel level) const {
3875 if (level == eDescriptionLevelBrief) {
3876 s.PutCString(m_class_name);
3877 return;
3879 s.Indent("Class:");
3880 s.Printf("%s\n", m_class_name.c_str());
3882 // Now print the extra args:
3883 // FIXME: We should use StructuredData.GetDescription on the m_extra_args
3884 // but that seems to rely on some printing plugin that doesn't exist.
3885 if (!m_extra_args.IsValid())
3886 return;
3887 StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP();
3888 if (!object_sp || !object_sp->IsValid())
3889 return;
3891 StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
3892 if (!as_dict || !as_dict->IsValid())
3893 return;
3895 uint32_t num_keys = as_dict->GetSize();
3896 if (num_keys == 0)
3897 return;
3899 s.Indent("Args:\n");
3900 s.SetIndentLevel(s.GetIndentLevel() + 4);
3902 auto print_one_element = [&s](llvm::StringRef key,
3903 StructuredData::Object *object) {
3904 s.Indent();
3905 s.Format("{0} : {1}\n", key, object->GetStringValue());
3906 return true;
3909 as_dict->ForEach(print_one_element);
3911 s.SetIndentLevel(s.GetIndentLevel() - 4);
3914 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3916 eNoDynamicValues,
3917 "no-dynamic-values",
3918 "Don't calculate the dynamic type of values",
3921 eDynamicCanRunTarget,
3922 "run-target",
3923 "Calculate the dynamic type of values "
3924 "even if you have to run the target.",
3927 eDynamicDontRunTarget,
3928 "no-run-target",
3929 "Calculate the dynamic type of values, but don't run the target.",
3933 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3934 return OptionEnumValues(g_dynamic_value_types);
3937 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3939 eInlineBreakpointsNever,
3940 "never",
3941 "Never look for inline breakpoint locations (fastest). This setting "
3942 "should only be used if you know that no inlining occurs in your"
3943 "programs.",
3946 eInlineBreakpointsHeaders,
3947 "headers",
3948 "Only check for inline breakpoint locations when setting breakpoints "
3949 "in header files, but not when setting breakpoint in implementation "
3950 "source files (default).",
3953 eInlineBreakpointsAlways,
3954 "always",
3955 "Always look for inline breakpoint locations when setting file and "
3956 "line breakpoints (slower but most accurate).",
3960 enum x86DisassemblyFlavor {
3961 eX86DisFlavorDefault,
3962 eX86DisFlavorIntel,
3963 eX86DisFlavorATT
3966 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3968 eX86DisFlavorDefault,
3969 "default",
3970 "Disassembler default (currently att).",
3973 eX86DisFlavorIntel,
3974 "intel",
3975 "Intel disassembler flavor.",
3978 eX86DisFlavorATT,
3979 "att",
3980 "AT&T disassembler flavor.",
3984 static constexpr OptionEnumValueElement g_import_std_module_value_types[] = {
3986 eImportStdModuleFalse,
3987 "false",
3988 "Never import the 'std' C++ module in the expression parser.",
3991 eImportStdModuleFallback,
3992 "fallback",
3993 "Retry evaluating expressions with an imported 'std' C++ module if they"
3994 " failed to parse without the module. This allows evaluating more "
3995 "complex expressions involving C++ standard library types."
3998 eImportStdModuleTrue,
3999 "true",
4000 "Always import the 'std' C++ module. This allows evaluating more "
4001 "complex expressions involving C++ standard library types. This feature"
4002 " is experimental."
4006 static constexpr OptionEnumValueElement
4007 g_dynamic_class_info_helper_value_types[] = {
4009 eDynamicClassInfoHelperAuto,
4010 "auto",
4011 "Automatically determine the most appropriate method for the "
4012 "target OS.",
4014 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4015 "Prefer using the realized classes struct."},
4016 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4017 "Prefer using the CopyRealizedClassList API."},
4018 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4019 "Prefer using the GetRealizedClassList API."},
4022 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
4024 Disassembler::eHexStyleC,
4025 "c",
4026 "C-style (0xffff).",
4029 Disassembler::eHexStyleAsm,
4030 "asm",
4031 "Asm-style (0ffffh).",
4035 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
4037 eLoadScriptFromSymFileTrue,
4038 "true",
4039 "Load debug scripts inside symbol files",
4042 eLoadScriptFromSymFileFalse,
4043 "false",
4044 "Do not load debug scripts inside symbol files.",
4047 eLoadScriptFromSymFileWarn,
4048 "warn",
4049 "Warn about debug scripts inside symbol files but do not load them.",
4053 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
4055 eLoadCWDlldbinitTrue,
4056 "true",
4057 "Load .lldbinit files from current directory",
4060 eLoadCWDlldbinitFalse,
4061 "false",
4062 "Do not load .lldbinit files from current directory",
4065 eLoadCWDlldbinitWarn,
4066 "warn",
4067 "Warn about loading .lldbinit files from current directory",
4071 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
4073 eMemoryModuleLoadLevelMinimal,
4074 "minimal",
4075 "Load minimal information when loading modules from memory. Currently "
4076 "this setting loads sections only.",
4079 eMemoryModuleLoadLevelPartial,
4080 "partial",
4081 "Load partial information when loading modules from memory. Currently "
4082 "this setting loads sections and function bounds.",
4085 eMemoryModuleLoadLevelComplete,
4086 "complete",
4087 "Load complete information when loading modules from memory. Currently "
4088 "this setting loads sections and all symbols.",
4092 #define LLDB_PROPERTIES_target
4093 #include "TargetProperties.inc"
4095 enum {
4096 #define LLDB_PROPERTIES_target
4097 #include "TargetPropertiesEnum.inc"
4098 ePropertyExperimental,
4101 class TargetOptionValueProperties
4102 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
4103 public:
4104 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
4106 const Property *
4107 GetPropertyAtIndex(size_t idx,
4108 const ExecutionContext *exe_ctx = nullptr) const override {
4109 // When getting the value for a key from the target options, we will always
4110 // try and grab the setting from the current target if there is one. Else
4111 // we just use the one from this instance.
4112 if (exe_ctx) {
4113 Target *target = exe_ctx->GetTargetPtr();
4114 if (target) {
4115 TargetOptionValueProperties *target_properties =
4116 static_cast<TargetOptionValueProperties *>(
4117 target->GetValueProperties().get());
4118 if (this != target_properties)
4119 return target_properties->ProtectedGetPropertyAtIndex(idx);
4122 return ProtectedGetPropertyAtIndex(idx);
4126 // TargetProperties
4127 #define LLDB_PROPERTIES_target_experimental
4128 #include "TargetProperties.inc"
4130 enum {
4131 #define LLDB_PROPERTIES_target_experimental
4132 #include "TargetPropertiesEnum.inc"
4135 class TargetExperimentalOptionValueProperties
4136 : public Cloneable<TargetExperimentalOptionValueProperties,
4137 OptionValueProperties> {
4138 public:
4139 TargetExperimentalOptionValueProperties()
4140 : Cloneable(Properties::GetExperimentalSettingsName()) {}
4143 TargetExperimentalProperties::TargetExperimentalProperties()
4144 : Properties(OptionValuePropertiesSP(
4145 new TargetExperimentalOptionValueProperties())) {
4146 m_collection_sp->Initialize(g_target_experimental_properties);
4149 // TargetProperties
4150 TargetProperties::TargetProperties(Target *target)
4151 : Properties(), m_launch_info(), m_target(target) {
4152 if (target) {
4153 m_collection_sp =
4154 OptionValueProperties::CreateLocalCopy(Target::GetGlobalProperties());
4156 // Set callbacks to update launch_info whenever "settins set" updated any
4157 // of these properties
4158 m_collection_sp->SetValueChangedCallback(
4159 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
4160 m_collection_sp->SetValueChangedCallback(
4161 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
4162 m_collection_sp->SetValueChangedCallback(
4163 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
4164 m_collection_sp->SetValueChangedCallback(
4165 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
4166 m_collection_sp->SetValueChangedCallback(
4167 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
4168 m_collection_sp->SetValueChangedCallback(
4169 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
4170 m_collection_sp->SetValueChangedCallback(
4171 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
4172 m_collection_sp->SetValueChangedCallback(
4173 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
4174 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
4175 DetachOnErrorValueChangedCallback();
4177 m_collection_sp->SetValueChangedCallback(
4178 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
4179 m_collection_sp->SetValueChangedCallback(
4180 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
4181 m_collection_sp->SetValueChangedCallback(
4182 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
4184 m_collection_sp->SetValueChangedCallback(
4185 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4186 m_experimental_properties_up =
4187 std::make_unique<TargetExperimentalProperties>();
4188 m_collection_sp->AppendProperty(
4189 Properties::GetExperimentalSettingsName(),
4190 "Experimental settings - setting these won't produce "
4191 "errors if the setting is not present.",
4192 true, m_experimental_properties_up->GetValueProperties());
4193 } else {
4194 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
4195 m_collection_sp->Initialize(g_target_properties);
4196 m_experimental_properties_up =
4197 std::make_unique<TargetExperimentalProperties>();
4198 m_collection_sp->AppendProperty(
4199 Properties::GetExperimentalSettingsName(),
4200 "Experimental settings - setting these won't produce "
4201 "errors if the setting is not present.",
4202 true, m_experimental_properties_up->GetValueProperties());
4203 m_collection_sp->AppendProperty(
4204 "process", "Settings specific to processes.", true,
4205 Process::GetGlobalProperties().GetValueProperties());
4206 m_collection_sp->SetValueChangedCallback(
4207 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4211 TargetProperties::~TargetProperties() = default;
4213 void TargetProperties::UpdateLaunchInfoFromProperties() {
4214 Arg0ValueChangedCallback();
4215 RunArgsValueChangedCallback();
4216 EnvVarsValueChangedCallback();
4217 InputPathValueChangedCallback();
4218 OutputPathValueChangedCallback();
4219 ErrorPathValueChangedCallback();
4220 DetachOnErrorValueChangedCallback();
4221 DisableASLRValueChangedCallback();
4222 InheritTCCValueChangedCallback();
4223 DisableSTDIOValueChangedCallback();
4226 bool TargetProperties::GetInjectLocalVariables(
4227 ExecutionContext *exe_ctx) const {
4228 const Property *exp_property =
4229 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4230 OptionValueProperties *exp_values =
4231 exp_property->GetValue()->GetAsProperties();
4232 if (exp_values)
4233 return exp_values
4234 ->GetPropertyAtIndexAs<bool>(ePropertyInjectLocalVars, exe_ctx)
4235 .value_or(true);
4236 else
4237 return true;
4240 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
4241 bool b) {
4242 const Property *exp_property =
4243 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4244 OptionValueProperties *exp_values =
4245 exp_property->GetValue()->GetAsProperties();
4246 if (exp_values)
4247 exp_values->SetPropertyAtIndex(ePropertyInjectLocalVars, true, exe_ctx);
4250 ArchSpec TargetProperties::GetDefaultArchitecture() const {
4251 const uint32_t idx = ePropertyDefaultArch;
4252 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
4255 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
4256 const uint32_t idx = ePropertyDefaultArch;
4257 SetPropertyAtIndex(idx, arch);
4260 bool TargetProperties::GetMoveToNearestCode() const {
4261 const uint32_t idx = ePropertyMoveToNearestCode;
4262 return GetPropertyAtIndexAs<bool>(
4263 idx, g_target_properties[idx].default_uint_value != 0);
4266 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
4267 const uint32_t idx = ePropertyPreferDynamic;
4268 return GetPropertyAtIndexAs<lldb::DynamicValueType>(
4269 idx, static_cast<lldb::DynamicValueType>(
4270 g_target_properties[idx].default_uint_value));
4273 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
4274 const uint32_t idx = ePropertyPreferDynamic;
4275 return SetPropertyAtIndex(idx, d);
4278 bool TargetProperties::GetPreloadSymbols() const {
4279 if (INTERRUPT_REQUESTED(m_target->GetDebugger(),
4280 "Interrupted checking preload symbols")) {
4281 return false;
4283 const uint32_t idx = ePropertyPreloadSymbols;
4284 return GetPropertyAtIndexAs<bool>(
4285 idx, g_target_properties[idx].default_uint_value != 0);
4288 void TargetProperties::SetPreloadSymbols(bool b) {
4289 const uint32_t idx = ePropertyPreloadSymbols;
4290 SetPropertyAtIndex(idx, b);
4293 bool TargetProperties::GetDisableASLR() const {
4294 const uint32_t idx = ePropertyDisableASLR;
4295 return GetPropertyAtIndexAs<bool>(
4296 idx, g_target_properties[idx].default_uint_value != 0);
4299 void TargetProperties::SetDisableASLR(bool b) {
4300 const uint32_t idx = ePropertyDisableASLR;
4301 SetPropertyAtIndex(idx, b);
4304 bool TargetProperties::GetInheritTCC() const {
4305 const uint32_t idx = ePropertyInheritTCC;
4306 return GetPropertyAtIndexAs<bool>(
4307 idx, g_target_properties[idx].default_uint_value != 0);
4310 void TargetProperties::SetInheritTCC(bool b) {
4311 const uint32_t idx = ePropertyInheritTCC;
4312 SetPropertyAtIndex(idx, b);
4315 bool TargetProperties::GetDetachOnError() const {
4316 const uint32_t idx = ePropertyDetachOnError;
4317 return GetPropertyAtIndexAs<bool>(
4318 idx, g_target_properties[idx].default_uint_value != 0);
4321 void TargetProperties::SetDetachOnError(bool b) {
4322 const uint32_t idx = ePropertyDetachOnError;
4323 SetPropertyAtIndex(idx, b);
4326 bool TargetProperties::GetDisableSTDIO() const {
4327 const uint32_t idx = ePropertyDisableSTDIO;
4328 return GetPropertyAtIndexAs<bool>(
4329 idx, g_target_properties[idx].default_uint_value != 0);
4332 void TargetProperties::SetDisableSTDIO(bool b) {
4333 const uint32_t idx = ePropertyDisableSTDIO;
4334 SetPropertyAtIndex(idx, b);
4337 const char *TargetProperties::GetDisassemblyFlavor() const {
4338 const uint32_t idx = ePropertyDisassemblyFlavor;
4339 const char *return_value;
4341 x86DisassemblyFlavor flavor_value =
4342 GetPropertyAtIndexAs<x86DisassemblyFlavor>(
4343 idx, static_cast<x86DisassemblyFlavor>(
4344 g_target_properties[idx].default_uint_value));
4346 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
4347 return return_value;
4350 InlineStrategy TargetProperties::GetInlineStrategy() const {
4351 const uint32_t idx = ePropertyInlineStrategy;
4352 return GetPropertyAtIndexAs<InlineStrategy>(
4353 idx,
4354 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
4357 llvm::StringRef TargetProperties::GetArg0() const {
4358 const uint32_t idx = ePropertyArg0;
4359 return GetPropertyAtIndexAs<llvm::StringRef>(
4360 idx, g_target_properties[idx].default_cstr_value);
4363 void TargetProperties::SetArg0(llvm::StringRef arg) {
4364 const uint32_t idx = ePropertyArg0;
4365 SetPropertyAtIndex(idx, arg);
4366 m_launch_info.SetArg0(arg);
4369 bool TargetProperties::GetRunArguments(Args &args) const {
4370 const uint32_t idx = ePropertyRunArgs;
4371 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4374 void TargetProperties::SetRunArguments(const Args &args) {
4375 const uint32_t idx = ePropertyRunArgs;
4376 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4377 m_launch_info.GetArguments() = args;
4380 Environment TargetProperties::ComputeEnvironment() const {
4381 Environment env;
4383 if (m_target &&
4384 GetPropertyAtIndexAs<bool>(
4385 ePropertyInheritEnv,
4386 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
4387 if (auto platform_sp = m_target->GetPlatform()) {
4388 Environment platform_env = platform_sp->GetEnvironment();
4389 for (const auto &KV : platform_env)
4390 env[KV.first()] = KV.second;
4394 Args property_unset_env;
4395 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4396 property_unset_env);
4397 for (const auto &var : property_unset_env)
4398 env.erase(var.ref());
4400 Args property_env;
4401 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
4402 for (const auto &KV : Environment(property_env))
4403 env[KV.first()] = KV.second;
4405 return env;
4408 Environment TargetProperties::GetEnvironment() const {
4409 return ComputeEnvironment();
4412 Environment TargetProperties::GetInheritedEnvironment() const {
4413 Environment environment;
4415 if (m_target == nullptr)
4416 return environment;
4418 if (!GetPropertyAtIndexAs<bool>(
4419 ePropertyInheritEnv,
4420 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
4421 return environment;
4423 PlatformSP platform_sp = m_target->GetPlatform();
4424 if (platform_sp == nullptr)
4425 return environment;
4427 Environment platform_environment = platform_sp->GetEnvironment();
4428 for (const auto &KV : platform_environment)
4429 environment[KV.first()] = KV.second;
4431 Args property_unset_environment;
4432 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4433 property_unset_environment);
4434 for (const auto &var : property_unset_environment)
4435 environment.erase(var.ref());
4437 return environment;
4440 Environment TargetProperties::GetTargetEnvironment() const {
4441 Args property_environment;
4442 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
4443 property_environment);
4444 Environment environment;
4445 for (const auto &KV : Environment(property_environment))
4446 environment[KV.first()] = KV.second;
4448 return environment;
4451 void TargetProperties::SetEnvironment(Environment env) {
4452 // TODO: Get rid of the Args intermediate step
4453 const uint32_t idx = ePropertyEnvVars;
4454 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
4457 bool TargetProperties::GetSkipPrologue() const {
4458 const uint32_t idx = ePropertySkipPrologue;
4459 return GetPropertyAtIndexAs<bool>(
4460 idx, g_target_properties[idx].default_uint_value != 0);
4463 PathMappingList &TargetProperties::GetSourcePathMap() const {
4464 const uint32_t idx = ePropertySourceMap;
4465 OptionValuePathMappings *option_value =
4466 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4467 assert(option_value);
4468 return option_value->GetCurrentValue();
4471 bool TargetProperties::GetAutoSourceMapRelative() const {
4472 const uint32_t idx = ePropertyAutoSourceMapRelative;
4473 return GetPropertyAtIndexAs<bool>(
4474 idx, g_target_properties[idx].default_uint_value != 0);
4477 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
4478 const uint32_t idx = ePropertyExecutableSearchPaths;
4479 OptionValueFileSpecList *option_value =
4480 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
4481 assert(option_value);
4482 option_value->AppendCurrentValue(dir);
4485 FileSpecList TargetProperties::GetExecutableSearchPaths() {
4486 const uint32_t idx = ePropertyExecutableSearchPaths;
4487 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4490 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
4491 const uint32_t idx = ePropertyDebugFileSearchPaths;
4492 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4495 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
4496 const uint32_t idx = ePropertyClangModuleSearchPaths;
4497 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4500 bool TargetProperties::GetEnableAutoImportClangModules() const {
4501 const uint32_t idx = ePropertyAutoImportClangModules;
4502 return GetPropertyAtIndexAs<bool>(
4503 idx, g_target_properties[idx].default_uint_value != 0);
4506 ImportStdModule TargetProperties::GetImportStdModule() const {
4507 const uint32_t idx = ePropertyImportStdModule;
4508 return GetPropertyAtIndexAs<ImportStdModule>(
4509 idx, static_cast<ImportStdModule>(
4510 g_target_properties[idx].default_uint_value));
4513 DynamicClassInfoHelper TargetProperties::GetDynamicClassInfoHelper() const {
4514 const uint32_t idx = ePropertyDynamicClassInfoHelper;
4515 return GetPropertyAtIndexAs<DynamicClassInfoHelper>(
4516 idx, static_cast<DynamicClassInfoHelper>(
4517 g_target_properties[idx].default_uint_value));
4520 bool TargetProperties::GetEnableAutoApplyFixIts() const {
4521 const uint32_t idx = ePropertyAutoApplyFixIts;
4522 return GetPropertyAtIndexAs<bool>(
4523 idx, g_target_properties[idx].default_uint_value != 0);
4526 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const {
4527 const uint32_t idx = ePropertyRetriesWithFixIts;
4528 return GetPropertyAtIndexAs<uint64_t>(
4529 idx, g_target_properties[idx].default_uint_value);
4532 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
4533 const uint32_t idx = ePropertyNotifyAboutFixIts;
4534 return GetPropertyAtIndexAs<bool>(
4535 idx, g_target_properties[idx].default_uint_value != 0);
4538 FileSpec TargetProperties::GetSaveJITObjectsDir() const {
4539 const uint32_t idx = ePropertySaveObjectsDir;
4540 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4543 void TargetProperties::CheckJITObjectsDir() {
4544 FileSpec new_dir = GetSaveJITObjectsDir();
4545 if (!new_dir)
4546 return;
4548 const FileSystem &instance = FileSystem::Instance();
4549 bool exists = instance.Exists(new_dir);
4550 bool is_directory = instance.IsDirectory(new_dir);
4551 std::string path = new_dir.GetPath(true);
4552 bool writable = llvm::sys::fs::can_write(path);
4553 if (exists && is_directory && writable)
4554 return;
4556 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
4557 ->GetValue()
4558 ->Clear();
4560 std::string buffer;
4561 llvm::raw_string_ostream os(buffer);
4562 os << "JIT object dir '" << path << "' ";
4563 if (!exists)
4564 os << "does not exist";
4565 else if (!is_directory)
4566 os << "is not a directory";
4567 else if (!writable)
4568 os << "is not writable";
4570 std::optional<lldb::user_id_t> debugger_id;
4571 if (m_target)
4572 debugger_id = m_target->GetDebugger().GetID();
4573 Debugger::ReportError(os.str(), debugger_id);
4576 bool TargetProperties::GetEnableSyntheticValue() const {
4577 const uint32_t idx = ePropertyEnableSynthetic;
4578 return GetPropertyAtIndexAs<bool>(
4579 idx, g_target_properties[idx].default_uint_value != 0);
4582 bool TargetProperties::ShowHexVariableValuesWithLeadingZeroes() const {
4583 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
4584 return GetPropertyAtIndexAs<bool>(
4585 idx, g_target_properties[idx].default_uint_value != 0);
4588 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
4589 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4590 return GetPropertyAtIndexAs<uint64_t>(
4591 idx, g_target_properties[idx].default_uint_value);
4594 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
4595 const uint32_t idx = ePropertyMaxChildrenCount;
4596 return GetPropertyAtIndexAs<int64_t>(
4597 idx, g_target_properties[idx].default_uint_value);
4600 std::pair<uint32_t, bool>
4601 TargetProperties::GetMaximumDepthOfChildrenToDisplay() const {
4602 const uint32_t idx = ePropertyMaxChildrenDepth;
4603 auto *option_value =
4604 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
4605 bool is_default = !option_value->OptionWasSet();
4606 return {option_value->GetCurrentValue(), is_default};
4609 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
4610 const uint32_t idx = ePropertyMaxSummaryLength;
4611 return GetPropertyAtIndexAs<uint64_t>(
4612 idx, g_target_properties[idx].default_uint_value);
4615 uint32_t TargetProperties::GetMaximumMemReadSize() const {
4616 const uint32_t idx = ePropertyMaxMemReadSize;
4617 return GetPropertyAtIndexAs<uint64_t>(
4618 idx, g_target_properties[idx].default_uint_value);
4621 FileSpec TargetProperties::GetStandardInputPath() const {
4622 const uint32_t idx = ePropertyInputPath;
4623 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4626 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4627 const uint32_t idx = ePropertyInputPath;
4628 SetPropertyAtIndex(idx, path);
4631 FileSpec TargetProperties::GetStandardOutputPath() const {
4632 const uint32_t idx = ePropertyOutputPath;
4633 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4636 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
4637 const uint32_t idx = ePropertyOutputPath;
4638 SetPropertyAtIndex(idx, path);
4641 FileSpec TargetProperties::GetStandardErrorPath() const {
4642 const uint32_t idx = ePropertyErrorPath;
4643 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4646 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4647 const uint32_t idx = ePropertyErrorPath;
4648 SetPropertyAtIndex(idx, path);
4651 LanguageType TargetProperties::GetLanguage() const {
4652 const uint32_t idx = ePropertyLanguage;
4653 return GetPropertyAtIndexAs<LanguageType>(idx, {});
4656 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4657 const uint32_t idx = ePropertyExprPrefix;
4658 OptionValueFileSpec *file =
4659 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
4660 if (file) {
4661 DataBufferSP data_sp(file->GetFileContents());
4662 if (data_sp)
4663 return llvm::StringRef(
4664 reinterpret_cast<const char *>(data_sp->GetBytes()),
4665 data_sp->GetByteSize());
4667 return "";
4670 uint64_t TargetProperties::GetExprErrorLimit() const {
4671 const uint32_t idx = ePropertyExprErrorLimit;
4672 return GetPropertyAtIndexAs<uint64_t>(
4673 idx, g_target_properties[idx].default_uint_value);
4676 uint64_t TargetProperties::GetExprAllocAddress() const {
4677 const uint32_t idx = ePropertyExprAllocAddress;
4678 return GetPropertyAtIndexAs<uint64_t>(
4679 idx, g_target_properties[idx].default_uint_value);
4682 uint64_t TargetProperties::GetExprAllocSize() const {
4683 const uint32_t idx = ePropertyExprAllocSize;
4684 return GetPropertyAtIndexAs<uint64_t>(
4685 idx, g_target_properties[idx].default_uint_value);
4688 uint64_t TargetProperties::GetExprAllocAlign() const {
4689 const uint32_t idx = ePropertyExprAllocAlign;
4690 return GetPropertyAtIndexAs<uint64_t>(
4691 idx, g_target_properties[idx].default_uint_value);
4694 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4695 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4696 return GetPropertyAtIndexAs<bool>(
4697 idx, g_target_properties[idx].default_uint_value != 0);
4700 bool TargetProperties::GetUseHexImmediates() const {
4701 const uint32_t idx = ePropertyUseHexImmediates;
4702 return GetPropertyAtIndexAs<bool>(
4703 idx, g_target_properties[idx].default_uint_value != 0);
4706 bool TargetProperties::GetUseFastStepping() const {
4707 const uint32_t idx = ePropertyUseFastStepping;
4708 return GetPropertyAtIndexAs<bool>(
4709 idx, g_target_properties[idx].default_uint_value != 0);
4712 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4713 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4714 return GetPropertyAtIndexAs<bool>(
4715 idx, g_target_properties[idx].default_uint_value != 0);
4718 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4719 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4720 return GetPropertyAtIndexAs<LoadScriptFromSymFile>(
4721 idx, static_cast<LoadScriptFromSymFile>(
4722 g_target_properties[idx].default_uint_value));
4725 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4726 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4727 return GetPropertyAtIndexAs<LoadCWDlldbinitFile>(
4728 idx, static_cast<LoadCWDlldbinitFile>(
4729 g_target_properties[idx].default_uint_value));
4732 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4733 const uint32_t idx = ePropertyHexImmediateStyle;
4734 return GetPropertyAtIndexAs<Disassembler::HexImmediateStyle>(
4735 idx, static_cast<Disassembler::HexImmediateStyle>(
4736 g_target_properties[idx].default_uint_value));
4739 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4740 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4741 return GetPropertyAtIndexAs<MemoryModuleLoadLevel>(
4742 idx, static_cast<MemoryModuleLoadLevel>(
4743 g_target_properties[idx].default_uint_value));
4746 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4747 const uint32_t idx = ePropertyTrapHandlerNames;
4748 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4751 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4752 const uint32_t idx = ePropertyTrapHandlerNames;
4753 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4756 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4757 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4758 return GetPropertyAtIndexAs<bool>(
4759 idx, g_target_properties[idx].default_uint_value != 0);
4762 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4763 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4764 SetPropertyAtIndex(idx, b);
4767 bool TargetProperties::GetDisplayRecognizedArguments() const {
4768 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4769 return GetPropertyAtIndexAs<bool>(
4770 idx, g_target_properties[idx].default_uint_value != 0);
4773 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4774 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4775 SetPropertyAtIndex(idx, b);
4778 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() const {
4779 return m_launch_info;
4782 void TargetProperties::SetProcessLaunchInfo(
4783 const ProcessLaunchInfo &launch_info) {
4784 m_launch_info = launch_info;
4785 SetArg0(launch_info.GetArg0());
4786 SetRunArguments(launch_info.GetArguments());
4787 SetEnvironment(launch_info.GetEnvironment());
4788 const FileAction *input_file_action =
4789 launch_info.GetFileActionForFD(STDIN_FILENO);
4790 if (input_file_action) {
4791 SetStandardInputPath(input_file_action->GetPath());
4793 const FileAction *output_file_action =
4794 launch_info.GetFileActionForFD(STDOUT_FILENO);
4795 if (output_file_action) {
4796 SetStandardOutputPath(output_file_action->GetPath());
4798 const FileAction *error_file_action =
4799 launch_info.GetFileActionForFD(STDERR_FILENO);
4800 if (error_file_action) {
4801 SetStandardErrorPath(error_file_action->GetPath());
4803 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4804 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4805 SetInheritTCC(
4806 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4807 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4810 bool TargetProperties::GetRequireHardwareBreakpoints() const {
4811 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4812 return GetPropertyAtIndexAs<bool>(
4813 idx, g_target_properties[idx].default_uint_value != 0);
4816 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4817 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4818 m_collection_sp->SetPropertyAtIndex(idx, b);
4821 bool TargetProperties::GetAutoInstallMainExecutable() const {
4822 const uint32_t idx = ePropertyAutoInstallMainExecutable;
4823 return GetPropertyAtIndexAs<bool>(
4824 idx, g_target_properties[idx].default_uint_value != 0);
4827 void TargetProperties::Arg0ValueChangedCallback() {
4828 m_launch_info.SetArg0(GetArg0());
4831 void TargetProperties::RunArgsValueChangedCallback() {
4832 Args args;
4833 if (GetRunArguments(args))
4834 m_launch_info.GetArguments() = args;
4837 void TargetProperties::EnvVarsValueChangedCallback() {
4838 m_launch_info.GetEnvironment() = ComputeEnvironment();
4841 void TargetProperties::InputPathValueChangedCallback() {
4842 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
4843 false);
4846 void TargetProperties::OutputPathValueChangedCallback() {
4847 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
4848 false, true);
4851 void TargetProperties::ErrorPathValueChangedCallback() {
4852 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
4853 false, true);
4856 void TargetProperties::DetachOnErrorValueChangedCallback() {
4857 if (GetDetachOnError())
4858 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4859 else
4860 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4863 void TargetProperties::DisableASLRValueChangedCallback() {
4864 if (GetDisableASLR())
4865 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4866 else
4867 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4870 void TargetProperties::InheritTCCValueChangedCallback() {
4871 if (GetInheritTCC())
4872 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4873 else
4874 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4877 void TargetProperties::DisableSTDIOValueChangedCallback() {
4878 if (GetDisableSTDIO())
4879 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4880 else
4881 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4884 bool TargetProperties::GetDebugUtilityExpression() const {
4885 const uint32_t idx = ePropertyDebugUtilityExpression;
4886 return GetPropertyAtIndexAs<bool>(
4887 idx, g_target_properties[idx].default_uint_value != 0);
4890 void TargetProperties::SetDebugUtilityExpression(bool debug) {
4891 const uint32_t idx = ePropertyDebugUtilityExpression;
4892 SetPropertyAtIndex(idx, debug);
4895 // Target::TargetEventData
4897 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4898 : EventData(), m_target_sp(target_sp), m_module_list() {}
4900 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4901 const ModuleList &module_list)
4902 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4904 Target::TargetEventData::~TargetEventData() = default;
4906 llvm::StringRef Target::TargetEventData::GetFlavorString() {
4907 return "Target::TargetEventData";
4910 void Target::TargetEventData::Dump(Stream *s) const {
4911 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4912 if (i != 0)
4913 *s << ", ";
4914 m_module_list.GetModuleAtIndex(i)->GetDescription(
4915 s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4919 const Target::TargetEventData *
4920 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4921 if (event_ptr) {
4922 const EventData *event_data = event_ptr->GetData();
4923 if (event_data &&
4924 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4925 return static_cast<const TargetEventData *>(event_ptr->GetData());
4927 return nullptr;
4930 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4931 TargetSP target_sp;
4932 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4933 if (event_data)
4934 target_sp = event_data->m_target_sp;
4935 return target_sp;
4938 ModuleList
4939 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4940 ModuleList module_list;
4941 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4942 if (event_data)
4943 module_list = event_data->m_module_list;
4944 return module_list;
4947 std::recursive_mutex &Target::GetAPIMutex() {
4948 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4949 return m_private_mutex;
4950 else
4951 return m_mutex;
4954 /// Get metrics associated with this target in JSON format.
4955 llvm::json::Value Target::ReportStatistics() { return m_stats.ToJSON(*this); }