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