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
2158ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
2159 Status *error_ptr) {
2160 ModuleSP module_sp;
2161
2162 Status error;
2163
2164 // First see if we already have this module in our module list. If we do,
2165 // then we're done, we don't need to consult the shared modules list. But
2166 // only do this if we are passed a UUID.
2167
2168 if (module_spec.GetUUID().IsValid())
2169 module_sp = m_images.FindFirstModule(module_spec);
2170
2171 if (!module_sp) {
2172 llvm::SmallVector<ModuleSP, 1>
2173 old_modules; // This will get filled in if we have a new version
2174 // of the library
2175 bool did_create_module = false;
2176 FileSpecList search_paths = GetExecutableSearchPaths();
2177 FileSpec symbol_file_spec;
2178
2179 // Call locate module callback if set. This allows users to implement their
2180 // own module cache system. For example, to leverage build system artifacts,
2181 // to bypass pulling files from remote platform, or to search symbol files
2182 // from symbol servers.
2183 if (m_platform_sp)
2184 m_platform_sp->CallLocateModuleCallbackIfSet(
2185 module_spec, module_sp, symbol_file_spec, &did_create_module);
2186
2187 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2188 // 1. module_sp:loaded, symbol_file_spec:set
2189 // The callback found a module file and a symbol file for the
2190 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2191 // the symbol_file_spec later.
2192 // 2. module_sp:loaded, symbol_file_spec:empty
2193 // The callback only found a module file for the module_spec.
2194 // 3. module_sp:empty, symbol_file_spec:set
2195 // The callback only found a symbol file for the module. We continue
2196 // to find a module file for this module_spec and we will call
2197 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2198 // 4. module_sp:empty, symbol_file_spec:empty
2199 // Platform does not exist, the callback is not set, the callback did
2200 // not find any module files nor any symbol files, the callback failed,
2201 // or something went wrong. We continue to find a module file for this
2202 // module_spec.
2203
2204 if (!module_sp) {
2205 // If there are image search path entries, try to use them to acquire a
2206 // suitable image.
2208 ModuleSpec transformed_spec(module_spec);
2209 ConstString transformed_dir;
2211 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2212 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2213 transformed_spec.GetFileSpec().SetFilename(
2214 module_spec.GetFileSpec().GetFilename());
2215 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2216 &search_paths, &old_modules,
2217 &did_create_module);
2218 }
2219 }
2220 }
2221
2222 if (!module_sp) {
2223 // If we have a UUID, we can check our global shared module list in case
2224 // we already have it. If we don't have a valid UUID, then we can't since
2225 // the path in "module_spec" will be a platform path, and we will need to
2226 // let the platform find that file. For example, we could be asking for
2227 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2228 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2229 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2230 // cache.
2231 if (module_spec.GetUUID().IsValid()) {
2232 // We have a UUID, it is OK to check the global module list...
2233 error =
2234 ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2235 &old_modules, &did_create_module);
2236 }
2237
2238 if (!module_sp) {
2239 // The platform is responsible for finding and caching an appropriate
2240 // module in the shared module cache.
2241 if (m_platform_sp) {
2242 error = m_platform_sp->GetSharedModule(
2243 module_spec, m_process_sp.get(), module_sp, &search_paths,
2244 &old_modules, &did_create_module);
2245 } else {
2246 error.SetErrorString("no platform is currently set");
2247 }
2248 }
2249 }
2250
2251 // We found a module that wasn't in our target list. Let's make sure that
2252 // there wasn't an equivalent module in the list already, and if there was,
2253 // let's remove it.
2254 if (module_sp) {
2255 ObjectFile *objfile = module_sp->GetObjectFile();
2256 if (objfile) {
2257 switch (objfile->GetType()) {
2258 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2259 /// a program's execution state
2260 case ObjectFile::eTypeExecutable: /// A normal executable
2261 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2262 /// executable
2263 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2264 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2265 /// used during execution
2266 break;
2267 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2268 /// debug information
2269 if (error_ptr)
2270 error_ptr->SetErrorString("debug info files aren't valid target "
2271 "modules, please specify an executable");
2272 return ModuleSP();
2273 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2274 /// against but not used for
2275 /// execution
2276 if (error_ptr)
2277 error_ptr->SetErrorString("stub libraries aren't valid target "
2278 "modules, please specify an executable");
2279 return ModuleSP();
2280 default:
2281 if (error_ptr)
2282 error_ptr->SetErrorString(
2283 "unsupported file type, please specify an executable");
2284 return ModuleSP();
2285 }
2286 // GetSharedModule is not guaranteed to find the old shared module, for
2287 // instance in the common case where you pass in the UUID, it is only
2288 // going to find the one module matching the UUID. In fact, it has no
2289 // good way to know what the "old module" relevant to this target is,
2290 // since there might be many copies of a module with this file spec in
2291 // various running debug sessions, but only one of them will belong to
2292 // this target. So let's remove the UUID from the module list, and look
2293 // in the target's module list. Only do this if there is SOMETHING else
2294 // in the module spec...
2295 if (module_spec.GetUUID().IsValid() &&
2296 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2297 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2298 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2299 module_spec_copy.GetUUID().Clear();
2300
2301 ModuleList found_modules;
2302 m_images.FindModules(module_spec_copy, found_modules);
2303 found_modules.ForEach([&](const ModuleSP &found_module) -> bool {
2304 old_modules.push_back(found_module);
2305 return true;
2306 });
2307 }
2308
2309 // If the locate module callback had found a symbol file, set it to the
2310 // module_sp before preloading symbols.
2311 if (symbol_file_spec)
2312 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2313
2314 // Preload symbols outside of any lock, so hopefully we can do this for
2315 // each library in parallel.
2316 if (GetPreloadSymbols())
2317 module_sp->PreloadSymbols();
2318 llvm::SmallVector<ModuleSP, 1> replaced_modules;
2319 for (ModuleSP &old_module_sp : old_modules) {
2320 if (m_images.GetIndexForModule(old_module_sp.get()) !=
2322 if (replaced_modules.empty())
2323 m_images.ReplaceModule(old_module_sp, module_sp);
2324 else
2325 m_images.Remove(old_module_sp);
2326
2327 replaced_modules.push_back(std::move(old_module_sp));
2328 }
2329 }
2330
2331 if (replaced_modules.size() > 1) {
2332 // The same new module replaced multiple old modules
2333 // simultaneously. It's not clear this should ever
2334 // happen (if we always replace old modules as we add
2335 // new ones, presumably we should never have more than
2336 // one old one). If there are legitimate cases where
2337 // this happens, then the ModuleList::Notifier interface
2338 // may need to be adjusted to allow reporting this.
2339 // In the meantime, just log that this has happened; just
2340 // above we called ReplaceModule on the first one, and Remove
2341 // on the rest.
2343 StreamString message;
2344 auto dump = [&message](Module &dump_module) -> void {
2345 UUID dump_uuid = dump_module.GetUUID();
2346
2347 message << '[';
2348 dump_module.GetDescription(message.AsRawOstream());
2349 message << " (uuid ";
2350
2351 if (dump_uuid.IsValid())
2352 dump_uuid.Dump(message);
2353 else
2354 message << "not specified";
2355
2356 message << ")]";
2357 };
2358
2359 message << "New module ";
2360 dump(*module_sp);
2361 message.AsRawOstream()
2362 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2363 replaced_modules.size());
2364 for (ModuleSP &replaced_module_sp : replaced_modules)
2365 dump(*replaced_module_sp);
2366
2367 log->PutString(message.GetString());
2368 }
2369 }
2370
2371 if (replaced_modules.empty())
2372 m_images.Append(module_sp, notify);
2373
2374 for (ModuleSP &old_module_sp : replaced_modules) {
2375 Module *old_module_ptr = old_module_sp.get();
2376 old_module_sp.reset();
2378 }
2379 } else
2380 module_sp.reset();
2381 }
2382 }
2383 if (error_ptr)
2384 *error_ptr = error;
2385 return module_sp;
2386}
2387
2388TargetSP Target::CalculateTarget() { return shared_from_this(); }
2389
2391
2393
2395
2397 exe_ctx.Clear();
2398 exe_ctx.SetTargetPtr(this);
2399}
2400
2402 return m_image_search_paths;
2403}
2404
2406 void *baton) {
2407 Target *target = (Target *)baton;
2408 ModuleSP exe_module_sp(target->GetExecutableModule());
2409 if (exe_module_sp)
2410 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2411}
2412
2413llvm::Expected<lldb::TypeSystemSP>
2415 bool create_on_demand) {
2416 if (!m_valid)
2417 return llvm::createStringError("Invalid Target");
2418
2419 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2420 // assembly code
2421 || language == eLanguageTypeUnknown) {
2422 LanguageSet languages_for_expressions =
2424
2425 if (languages_for_expressions[eLanguageTypeC]) {
2426 language = eLanguageTypeC; // LLDB's default. Override by setting the
2427 // target language.
2428 } else {
2429 if (languages_for_expressions.Empty())
2430 return llvm::createStringError(
2431 "No expression support for any languages");
2432 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2433 }
2434 }
2435
2437 create_on_demand);
2438}
2439
2441 const lldb_private::RegisterFlags &flags,
2442 uint32_t byte_size) {
2444 assert(provider);
2445 return provider->GetRegisterType(name, flags, byte_size);
2446}
2447
2448std::vector<lldb::TypeSystemSP>
2449Target::GetScratchTypeSystems(bool create_on_demand) {
2450 if (!m_valid)
2451 return {};
2452
2453 // Some TypeSystem instances are associated with several LanguageTypes so
2454 // they will show up several times in the loop below. The SetVector filters
2455 // out all duplicates as they serve no use for the caller.
2456 std::vector<lldb::TypeSystemSP> scratch_type_systems;
2457
2458 LanguageSet languages_for_expressions =
2460
2461 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2462 auto language = (LanguageType)bit;
2463 auto type_system_or_err =
2464 GetScratchTypeSystemForLanguage(language, create_on_demand);
2465 if (!type_system_or_err)
2467 GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2468 "Language '{1}' has expression support but no scratch type "
2469 "system available: {0}",
2471 else
2472 if (auto ts = *type_system_or_err)
2473 scratch_type_systems.push_back(ts);
2474 }
2475
2476 std::sort(scratch_type_systems.begin(), scratch_type_systems.end());
2477 scratch_type_systems.erase(
2478 std::unique(scratch_type_systems.begin(), scratch_type_systems.end()),
2479 scratch_type_systems.end());
2480 return scratch_type_systems;
2481}
2482
2485 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2486
2487 if (auto err = type_system_or_err.takeError()) {
2489 GetLog(LLDBLog::Target), std::move(err),
2490 "Unable to get persistent expression state for language {1}: {0}",
2492 return nullptr;
2493 }
2494
2495 if (auto ts = *type_system_or_err)
2496 return ts->GetPersistentExpressionState();
2497
2499 "Unable to get persistent expression state for language {1}: {0}",
2501 return nullptr;
2502}
2503
2505 llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language,
2506 Expression::ResultType desired_type,
2507 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2508 Status &error) {
2509 auto type_system_or_err =
2511 if (auto err = type_system_or_err.takeError()) {
2512 error.SetErrorStringWithFormat(
2513 "Could not find type system for language %s: %s",
2515 llvm::toString(std::move(err)).c_str());
2516 return nullptr;
2517 }
2518
2519 auto ts = *type_system_or_err;
2520 if (!ts) {
2521 error.SetErrorStringWithFormat(
2522 "Type system for language %s is no longer live",
2523 language.GetDescription().data());
2524 return nullptr;
2525 }
2526
2527 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2528 options, ctx_obj);
2529 if (!user_expr)
2530 error.SetErrorStringWithFormat(
2531 "Could not create an expression for language %s",
2532 language.GetDescription().data());
2533
2534 return user_expr;
2535}
2536
2538 lldb::LanguageType language, const CompilerType &return_type,
2539 const Address &function_address, const ValueList &arg_value_list,
2540 const char *name, Status &error) {
2541 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2542 if (auto err = type_system_or_err.takeError()) {
2543 error.SetErrorStringWithFormat(
2544 "Could not find type system for language %s: %s",
2546 llvm::toString(std::move(err)).c_str());
2547 return nullptr;
2548 }
2549 auto ts = *type_system_or_err;
2550 if (!ts) {
2551 error.SetErrorStringWithFormat(
2552 "Type system for language %s is no longer live",
2554 return nullptr;
2555 }
2556 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2557 arg_value_list, name);
2558 if (!persistent_fn)
2559 error.SetErrorStringWithFormat(
2560 "Could not create an expression for language %s",
2562
2563 return persistent_fn;
2564}
2565
2566llvm::Expected<std::unique_ptr<UtilityFunction>>
2567Target::CreateUtilityFunction(std::string expression, std::string name,
2568 lldb::LanguageType language,
2569 ExecutionContext &exe_ctx) {
2570 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2571 if (!type_system_or_err)
2572 return type_system_or_err.takeError();
2573 auto ts = *type_system_or_err;
2574 if (!ts)
2575 return llvm::createStringError(
2576 llvm::StringRef("Type system for language ") +
2578 llvm::StringRef(" is no longer live"));
2579 std::unique_ptr<UtilityFunction> utility_fn =
2580 ts->CreateUtilityFunction(std::move(expression), std::move(name));
2581 if (!utility_fn)
2582 return llvm::createStringError(
2583 llvm::StringRef("Could not create an expression for language") +
2585
2586 DiagnosticManager diagnostics;
2587 if (!utility_fn->Install(diagnostics, exe_ctx))
2588 return llvm::createStringError(diagnostics.GetString());
2589
2590 return std::move(utility_fn);
2591}
2592
2594
2596
2599}
2600
2603}
2604
2607}
2608
2611 "setting target's default architecture to {0} ({1})",
2612 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2614}
2615
2616llvm::Error Target::SetLabel(llvm::StringRef label) {
2617 size_t n = LLDB_INVALID_INDEX32;
2618 if (llvm::to_integer(label, n))
2619 return llvm::createStringError("Cannot use integer as target label.");
2620 TargetList &targets = GetDebugger().GetTargetList();
2621 for (size_t i = 0; i < targets.GetNumTargets(); i++) {
2622 TargetSP target_sp = targets.GetTargetAtIndex(i);
2623 if (target_sp && target_sp->GetLabel() == label) {
2624 return llvm::make_error<llvm::StringError>(
2625 llvm::formatv(
2626 "Cannot use label '{0}' since it's set in target #{1}.", label,
2627 i),
2628 llvm::inconvertibleErrorCode());
2629 }
2630 }
2631
2632 m_label = label.str();
2633 return llvm::Error::success();
2634}
2635
2637 const SymbolContext *sc_ptr) {
2638 // The target can either exist in the "process" of ExecutionContext, or in
2639 // the "target_sp" member of SymbolContext. This accessor helper function
2640 // will get the target from one of these locations.
2641
2642 Target *target = nullptr;
2643 if (sc_ptr != nullptr)
2644 target = sc_ptr->target_sp.get();
2645 if (target == nullptr && exe_ctx_ptr)
2646 target = exe_ctx_ptr->GetTargetPtr();
2647 return target;
2648}
2649
2651 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2652 lldb::ValueObjectSP &result_valobj_sp,
2653 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2654 ValueObject *ctx_obj) {
2655 result_valobj_sp.reset();
2656
2657 ExpressionResults execution_results = eExpressionSetupError;
2658
2659 if (expr.empty()) {
2661 return execution_results;
2662 }
2663
2664 // We shouldn't run stop hooks in expressions.
2665 bool old_suppress_value = m_suppress_stop_hooks;
2666 m_suppress_stop_hooks = true;
2667 auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2668 m_suppress_stop_hooks = old_suppress_value;
2669 });
2670
2671 ExecutionContext exe_ctx;
2672
2673 if (exe_scope) {
2674 exe_scope->CalculateExecutionContext(exe_ctx);
2675 } else if (m_process_sp) {
2676 m_process_sp->CalculateExecutionContext(exe_ctx);
2677 } else {
2679 }
2680
2681 // Make sure we aren't just trying to see the value of a persistent variable
2682 // (something like "$0")
2683 // Only check for persistent variables the expression starts with a '$'
2684 lldb::ExpressionVariableSP persistent_var_sp;
2685 if (expr[0] == '$') {
2686 auto type_system_or_err =
2688 if (auto err = type_system_or_err.takeError()) {
2689 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2690 "Unable to get scratch type system");
2691 } else {
2692 auto ts = *type_system_or_err;
2693 if (!ts)
2694 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2695 "Scratch type system is no longer live: {0}");
2696 else
2697 persistent_var_sp =
2698 ts->GetPersistentExpressionState()->GetVariable(expr);
2699 }
2700 }
2701 if (persistent_var_sp) {
2702 result_valobj_sp = persistent_var_sp->GetValueObject();
2703 execution_results = eExpressionCompleted;
2704 } else {
2705 llvm::StringRef prefix = GetExpressionPrefixContents();
2706 Status error;
2707 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2708 result_valobj_sp, error,
2709 fixed_expression, ctx_obj);
2710 // Pass up the error by wrapping it inside an error result.
2711 if (error.Fail() && !result_valobj_sp)
2712 result_valobj_sp = ValueObjectConstResult::Create(
2713 exe_ctx.GetBestExecutionContextScope(), error);
2714 }
2715
2716 if (execution_results == eExpressionCompleted)
2718 else
2720 return execution_results;
2721}
2722
2724 lldb::ExpressionVariableSP variable_sp;
2726 [name, &variable_sp](TypeSystemSP type_system) -> bool {
2727 auto ts = type_system.get();
2728 if (!ts)
2729 return true;
2730 if (PersistentExpressionState *persistent_state =
2731 ts->GetPersistentExpressionState()) {
2732 variable_sp = persistent_state->GetVariable(name);
2733
2734 if (variable_sp)
2735 return false; // Stop iterating the ForEach
2736 }
2737 return true; // Keep iterating the ForEach
2738 });
2739 return variable_sp;
2740}
2741
2744
2746 [name, &address](lldb::TypeSystemSP type_system) -> bool {
2747 auto ts = type_system.get();
2748 if (!ts)
2749 return true;
2750
2751 if (PersistentExpressionState *persistent_state =
2752 ts->GetPersistentExpressionState()) {
2753 address = persistent_state->LookupSymbol(name);
2754 if (address != LLDB_INVALID_ADDRESS)
2755 return false; // Stop iterating the ForEach
2756 }
2757 return true; // Keep iterating the ForEach
2758 });
2759 return address;
2760}
2761
2762llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2763 Module *exe_module = GetExecutableModulePointer();
2764
2765 // Try to find the entry point address in the primary executable.
2766 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2767 if (has_primary_executable) {
2768 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2769 if (entry_addr.IsValid())
2770 return entry_addr;
2771 }
2772
2773 const ModuleList &modules = GetImages();
2774 const size_t num_images = modules.GetSize();
2775 for (size_t idx = 0; idx < num_images; ++idx) {
2776 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2777 if (!module_sp || !module_sp->GetObjectFile())
2778 continue;
2779
2780 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2781 if (entry_addr.IsValid())
2782 return entry_addr;
2783 }
2784
2785 // We haven't found the entry point address. Return an appropriate error.
2786 if (!has_primary_executable)
2787 return llvm::createStringError(
2788 "No primary executable found and could not find entry point address in "
2789 "any executable module");
2790
2791 return llvm::createStringError(
2792 "Could not find entry point address for primary executable module \"" +
2793 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"");
2794}
2795
2797 AddressClass addr_class) const {
2798 auto arch_plugin = GetArchitecturePlugin();
2799 return arch_plugin
2800 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2801 : load_addr;
2802}
2803
2805 AddressClass addr_class) const {
2806 auto arch_plugin = GetArchitecturePlugin();
2807 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2808 : load_addr;
2809}
2810
2812 auto arch_plugin = GetArchitecturePlugin();
2813 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2814}
2815
2818 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2819 return *m_source_manager_up;
2820}
2821
2824 Target::StopHookSP stop_hook_sp;
2825 switch (kind) {
2827 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2828 break;
2830 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2831 break;
2832 }
2833 m_stop_hooks[new_uid] = stop_hook_sp;
2834 return stop_hook_sp;
2835}
2836
2838 if (!RemoveStopHookByID(user_id))
2839 return;
2840 if (user_id == m_stop_hook_next_id)
2842}
2843
2845 size_t num_removed = m_stop_hooks.erase(user_id);
2846 return (num_removed != 0);
2847}
2848
2850
2852 StopHookSP found_hook;
2853
2854 StopHookCollection::iterator specified_hook_iter;
2855 specified_hook_iter = m_stop_hooks.find(user_id);
2856 if (specified_hook_iter != m_stop_hooks.end())
2857 found_hook = (*specified_hook_iter).second;
2858 return found_hook;
2859}
2860
2862 bool active_state) {
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 return false;
2867
2868 (*specified_hook_iter).second->SetIsActive(active_state);
2869 return true;
2870}
2871
2872void Target::SetAllStopHooksActiveState(bool active_state) {
2873 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2874 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2875 (*pos).second->SetIsActive(active_state);
2876 }
2877}
2878
2881 return false;
2882
2883 if (!m_process_sp)
2884 return false;
2885
2886 // Somebody might have restarted the process:
2887 // Still return false, the return value is about US restarting the target.
2888 if (m_process_sp->GetState() != eStateStopped)
2889 return false;
2890
2891 if (m_stop_hooks.empty())
2892 return false;
2893
2894 // If there aren't any active stop hooks, don't bother either.
2895 bool any_active_hooks = false;
2896 for (auto hook : m_stop_hooks) {
2897 if (hook.second->IsActive()) {
2898 any_active_hooks = true;
2899 break;
2900 }
2901 }
2902 if (!any_active_hooks)
2903 return false;
2904
2905 // Make sure we check that we are not stopped because of us running a user
2906 // expression since in that case we do not want to run the stop-hooks. Note,
2907 // you can't just check whether the last stop was for a User Expression,
2908 // because breakpoint commands get run before stop hooks, and one of them
2909 // might have run an expression. You have to ensure you run the stop hooks
2910 // once per natural stop.
2911 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
2912 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
2913 return false;
2914
2915 m_latest_stop_hook_id = last_natural_stop;
2916
2917 std::vector<ExecutionContext> exc_ctx_with_reasons;
2918
2919 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2920 size_t num_threads = cur_threadlist.GetSize();
2921 for (size_t i = 0; i < num_threads; i++) {
2922 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2923 if (cur_thread_sp->ThreadStoppedForAReason()) {
2924 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2925 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
2926 cur_frame_sp.get());
2927 }
2928 }
2929
2930 // If no threads stopped for a reason, don't run the stop-hooks.
2931 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2932 if (num_exe_ctx == 0)
2933 return false;
2934
2936
2937 bool auto_continue = false;
2938 bool hooks_ran = false;
2939 bool print_hook_header = (m_stop_hooks.size() != 1);
2940 bool print_thread_header = (num_exe_ctx != 1);
2941 bool should_stop = false;
2942 bool somebody_restarted = false;
2943
2944 for (auto stop_entry : m_stop_hooks) {
2945 StopHookSP cur_hook_sp = stop_entry.second;
2946 if (!cur_hook_sp->IsActive())
2947 continue;
2948
2949 bool any_thread_matched = false;
2950 for (auto exc_ctx : exc_ctx_with_reasons) {
2951 // We detect somebody restarted in the stop-hook loop, and broke out of
2952 // that loop back to here. So break out of here too.
2953 if (somebody_restarted)
2954 break;
2955
2956 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
2957 continue;
2958
2959 // We only consult the auto-continue for a stop hook if it matched the
2960 // specifier.
2961 auto_continue |= cur_hook_sp->GetAutoContinue();
2962
2963 if (!hooks_ran)
2964 hooks_ran = true;
2965
2966 if (print_hook_header && !any_thread_matched) {
2967 StreamString s;
2968 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
2969 if (s.GetSize() != 0)
2970 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
2971 s.GetData());
2972 else
2973 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2974 any_thread_matched = true;
2975 }
2976
2977 if (print_thread_header)
2978 output_sp->Printf("-- Thread %d\n",
2979 exc_ctx.GetThreadPtr()->GetIndexID());
2980
2981 StopHook::StopHookResult this_result =
2982 cur_hook_sp->HandleStop(exc_ctx, output_sp);
2983 bool this_should_stop = true;
2984
2985 switch (this_result) {
2987 // If this hook is set to auto-continue that should override the
2988 // HandleStop result...
2989 if (cur_hook_sp->GetAutoContinue())
2990 this_should_stop = false;
2991 else
2992 this_should_stop = true;
2993
2994 break;
2996 this_should_stop = false;
2997 break;
2999 // We don't have a good way to prohibit people from restarting the
3000 // target willy nilly in a stop hook. If the hook did so, give a
3001 // gentle suggestion here and bag out if the hook processing.
3002 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3003 " set the program running.\n"
3004 " Consider using '-G true' to make "
3005 "stop hooks auto-continue.\n",
3006 cur_hook_sp->GetID());
3007 somebody_restarted = true;
3008 break;
3009 }
3010 // If we're already restarted, stop processing stop hooks.
3011 // FIXME: if we are doing non-stop mode for real, we would have to
3012 // check that OUR thread was restarted, otherwise we should keep
3013 // processing stop hooks.
3014 if (somebody_restarted)
3015 break;
3016
3017 // If anybody wanted to stop, we should all stop.
3018 if (!should_stop)
3019 should_stop = this_should_stop;
3020 }
3021 }
3022
3023 output_sp->Flush();
3024
3025 // If one of the commands in the stop hook already restarted the target,
3026 // report that fact.
3027 if (somebody_restarted)
3028 return true;
3029
3030 // Finally, if auto-continue was requested, do it now:
3031 // We only compute should_stop against the hook results if a hook got to run
3032 // which is why we have to do this conjoint test.
3033 if ((hooks_ran && !should_stop) || auto_continue) {
3034 Log *log = GetLog(LLDBLog::Process);
3035 Status error = m_process_sp->PrivateResume();
3036 if (error.Success()) {
3037 LLDB_LOG(log, "Resuming from RunStopHooks");
3038 return true;
3039 } else {
3040 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3041 return false;
3042 }
3043 }
3044
3045 return false;
3046}
3047
3049 // NOTE: intentional leak so we don't crash if global destructor chain gets
3050 // called as other threads still use the result of this function
3051 static TargetProperties *g_settings_ptr =
3052 new TargetProperties(nullptr);
3053 return *g_settings_ptr;
3054}
3055
3057 Status error;
3058 PlatformSP platform_sp(GetPlatform());
3059 if (platform_sp) {
3060 if (platform_sp->IsRemote()) {
3061 if (platform_sp->IsConnected()) {
3062 // Install all files that have an install path when connected to a
3063 // remote platform. If target.auto-install-main-executable is set then
3064 // also install the main executable even if it does not have an explicit
3065 // install path specified.
3066 const ModuleList &modules = GetImages();
3067 const size_t num_images = modules.GetSize();
3068 for (size_t idx = 0; idx < num_images; ++idx) {
3069 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
3070 if (module_sp) {
3071 const bool is_main_executable = module_sp == GetExecutableModule();
3072 FileSpec local_file(module_sp->GetFileSpec());
3073 if (local_file) {
3074 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
3075 if (!remote_file) {
3076 if (is_main_executable && GetAutoInstallMainExecutable()) {
3077 // Automatically install the main executable.
3078 remote_file = platform_sp->GetRemoteWorkingDirectory();
3079 remote_file.AppendPathComponent(
3080 module_sp->GetFileSpec().GetFilename().GetCString());
3081 }
3082 }
3083 if (remote_file) {
3084 error = platform_sp->Install(local_file, remote_file);
3085 if (error.Success()) {
3086 module_sp->SetPlatformFileSpec(remote_file);
3087 if (is_main_executable) {
3088 platform_sp->SetFilePermissions(remote_file, 0700);
3089 if (launch_info)
3090 launch_info->SetExecutableFile(remote_file, false);
3091 }
3092 } else
3093 break;
3094 }
3095 }
3096 }
3097 }
3098 }
3099 }
3100 }
3101 return error;
3102}
3103
3105 uint32_t stop_id) {
3106 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
3107}
3108
3110 Address &resolved_addr) {
3111 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3112}
3113
3115 addr_t new_section_load_addr,
3116 bool warn_multiple) {
3117 const addr_t old_section_load_addr =
3119 SectionLoadHistory::eStopIDNow, section_sp);
3120 if (old_section_load_addr != new_section_load_addr) {
3121 uint32_t stop_id = 0;
3122 ProcessSP process_sp(GetProcessSP());
3123 if (process_sp)
3124 stop_id = process_sp->GetStopID();
3125 else
3128 stop_id, section_sp, new_section_load_addr, warn_multiple))
3129 return true; // Return true if the section load address was changed...
3130 }
3131 return false; // Return false to indicate nothing changed
3132}
3133
3134size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3135 size_t section_unload_count = 0;
3136 size_t num_modules = module_list.GetSize();
3137 for (size_t i = 0; i < num_modules; ++i) {
3138 section_unload_count +=
3139 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3140 }
3141 return section_unload_count;
3142}
3143
3145 uint32_t stop_id = 0;
3146 ProcessSP process_sp(GetProcessSP());
3147 if (process_sp)
3148 stop_id = process_sp->GetStopID();
3149 else
3151 SectionList *sections = module_sp->GetSectionList();
3152 size_t section_unload_count = 0;
3153 if (sections) {
3154 const uint32_t num_sections = sections->GetNumSections(0);
3155 for (uint32_t i = 0; i < num_sections; ++i) {
3156 section_unload_count += m_section_load_history.SetSectionUnloaded(
3157 stop_id, sections->GetSectionAtIndex(i));
3158 }
3159 }
3160 return section_unload_count;
3161}
3162
3164 uint32_t stop_id = 0;
3165 ProcessSP process_sp(GetProcessSP());
3166 if (process_sp)
3167 stop_id = process_sp->GetStopID();
3168 else
3170 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3171}
3172
3174 addr_t load_addr) {
3175 uint32_t stop_id = 0;
3176 ProcessSP process_sp(GetProcessSP());
3177 if (process_sp)
3178 stop_id = process_sp->GetStopID();
3179 else
3181 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3182 load_addr);
3183}
3184
3186
3188 if (process_info.IsScriptedProcess()) {
3189 // Only copy scripted process launch options.
3190 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3192 default_launch_info.SetProcessPluginName("ScriptedProcess");
3193 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3194 SetProcessLaunchInfo(default_launch_info);
3195 }
3196}
3197
3200 Status error;
3201 Log *log = GetLog(LLDBLog::Target);
3202
3203 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3204 launch_info.GetExecutableFile().GetPath().c_str());
3205
3206 StateType state = eStateInvalid;
3207
3208 // Scope to temporarily get the process state in case someone has manually
3209 // remotely connected already to a process and we can skip the platform
3210 // launching.
3211 {
3212 ProcessSP process_sp(GetProcessSP());
3213
3214 if (process_sp) {
3215 state = process_sp->GetState();
3216 LLDB_LOGF(log,
3217 "Target::%s the process exists, and its current state is %s",
3218 __FUNCTION__, StateAsCString(state));
3219 } else {
3220 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3221 __FUNCTION__);
3222 }
3223 }
3224
3225 launch_info.GetFlags().Set(eLaunchFlagDebug);
3226
3227 SaveScriptedLaunchInfo(launch_info);
3228
3229 // Get the value of synchronous execution here. If you wait till after you
3230 // have started to run, then you could have hit a breakpoint, whose command
3231 // might switch the value, and then you'll pick up that incorrect value.
3232 Debugger &debugger = GetDebugger();
3233 const bool synchronous_execution =
3235
3236 PlatformSP platform_sp(GetPlatform());
3237
3238 FinalizeFileActions(launch_info);
3239
3240 if (state == eStateConnected) {
3241 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3242 error.SetErrorString(
3243 "can't launch in tty when launching through a remote connection");
3244 return error;
3245 }
3246 }
3247
3248 if (!launch_info.GetArchitecture().IsValid())
3249 launch_info.GetArchitecture() = GetArchitecture();
3250
3251 // Hijacking events of the process to be created to be sure that all events
3252 // until the first stop are intercepted (in case if platform doesn't define
3253 // its own hijacking listener or if the process is created by the target
3254 // manually, without the platform).
3255 if (!launch_info.GetHijackListener())
3258
3259 // If we're not already connected to the process, and if we have a platform
3260 // that can launch a process for debugging, go ahead and do that here.
3261 if (state != eStateConnected && platform_sp &&
3262 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3263 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3264 __FUNCTION__);
3265
3266 // If there was a previous process, delete it before we make the new one.
3267 // One subtle point, we delete the process before we release the reference
3268 // to m_process_sp. That way even if we are the last owner, the process
3269 // will get Finalized before it gets destroyed.
3271
3272 m_process_sp =
3273 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3274
3275 } else {
3276 LLDB_LOGF(log,
3277 "Target::%s the platform doesn't know how to debug a "
3278 "process, getting a process plugin to do this for us.",
3279 __FUNCTION__);
3280
3281 if (state == eStateConnected) {
3282 assert(m_process_sp);
3283 } else {
3284 // Use a Process plugin to construct the process.
3285 CreateProcess(launch_info.GetListener(),
3286 launch_info.GetProcessPluginName(), nullptr, false);
3287 }
3288
3289 // Since we didn't have a platform launch the process, launch it here.
3290 if (m_process_sp) {
3291 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3292 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3293 error = m_process_sp->Launch(launch_info);
3294 }
3295 }
3296
3297 if (!m_process_sp && error.Success())
3298 error.SetErrorString("failed to launch or debug process");
3299
3300 if (!error.Success())
3301 return error;
3302
3303 bool rebroadcast_first_stop =
3304 !synchronous_execution &&
3305 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3306
3307 assert(launch_info.GetHijackListener());
3308
3309 EventSP first_stop_event_sp;
3310 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3311 rebroadcast_first_stop,
3312 launch_info.GetHijackListener());
3313 m_process_sp->RestoreProcessEvents();
3314
3315 if (rebroadcast_first_stop) {
3316 assert(first_stop_event_sp);
3317 m_process_sp->BroadcastEvent(first_stop_event_sp);
3318 return error;
3319 }
3320
3321 switch (state) {
3322 case eStateStopped: {
3323 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3324 break;
3325 if (synchronous_execution)
3326 // Now we have handled the stop-from-attach, and we are just
3327 // switching to a synchronous resume. So we should switch to the
3328 // SyncResume hijacker.
3329 m_process_sp->ResumeSynchronous(stream);
3330 else
3331 error = m_process_sp->Resume();
3332 if (!error.Success()) {
3333 Status error2;
3335 "process resume at entry point failed: %s", error.AsCString());
3336 error = error2;
3337 }
3338 } break;
3339 case eStateExited: {
3340 bool with_shell = !!launch_info.GetShell();
3341 const int exit_status = m_process_sp->GetExitStatus();
3342 const char *exit_desc = m_process_sp->GetExitDescription();
3343 std::string desc;
3344 if (exit_desc && exit_desc[0])
3345 desc = " (" + std::string(exit_desc) + ')';
3346 if (with_shell)
3347 error.SetErrorStringWithFormat(
3348 "process exited with status %i%s\n"
3349 "'r' and 'run' are aliases that default to launching through a "
3350 "shell.\n"
3351 "Try launching without going through a shell by using "
3352 "'process launch'.",
3353 exit_status, desc.c_str());
3354 else
3355 error.SetErrorStringWithFormat("process exited with status %i%s",
3356 exit_status, desc.c_str());
3357 } break;
3358 default:
3359 error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
3360 StateAsCString(state));
3361 break;
3362 }
3363 return error;
3364}
3365
3366void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3367
3369
3370llvm::Expected<TraceSP> Target::CreateTrace() {
3371 if (!m_process_sp)
3372 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3373 "A process is required for tracing");
3374 if (m_trace_sp)
3375 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3376 "A trace already exists for the target");
3377
3378 llvm::Expected<TraceSupportedResponse> trace_type =
3379 m_process_sp->TraceSupported();
3380 if (!trace_type)
3381 return llvm::createStringError(
3382 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3383 llvm::toString(trace_type.takeError()).c_str());
3384 if (llvm::Expected<TraceSP> trace_sp =
3386 m_trace_sp = *trace_sp;
3387 else
3388 return llvm::createStringError(
3389 llvm::inconvertibleErrorCode(),
3390 "Couldn't create a Trace object for the process. %s",
3391 llvm::toString(trace_sp.takeError()).c_str());
3392 return m_trace_sp;
3393}
3394
3395llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3396 if (m_trace_sp)
3397 return m_trace_sp;
3398 return CreateTrace();
3399}
3400
3403 auto state = eStateInvalid;
3404 auto process_sp = GetProcessSP();
3405 if (process_sp) {
3406 state = process_sp->GetState();
3407 if (process_sp->IsAlive() && state != eStateConnected) {
3408 if (state == eStateAttaching)
3409 return Status("process attach is in progress");
3410 return Status("a process is already being debugged");
3411 }
3412 }
3413
3414 const ModuleSP old_exec_module_sp = GetExecutableModule();
3415
3416 // If no process info was specified, then use the target executable name as
3417 // the process to attach to by default
3418 if (!attach_info.ProcessInfoSpecified()) {
3419 if (old_exec_module_sp)
3420 attach_info.GetExecutableFile().SetFilename(
3421 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3422
3423 if (!attach_info.ProcessInfoSpecified()) {
3424 return Status("no process specified, create a target with a file, or "
3425 "specify the --pid or --name");
3426 }
3427 }
3428
3429 const auto platform_sp =
3431 ListenerSP hijack_listener_sp;
3432 const bool async = attach_info.GetAsync();
3433 if (!async) {
3434 hijack_listener_sp = Listener::MakeListener(
3436 attach_info.SetHijackListener(hijack_listener_sp);
3437 }
3438
3439 Status error;
3440 if (state != eStateConnected && platform_sp != nullptr &&
3441 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3442 SetPlatform(platform_sp);
3443 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3444 } else {
3445 if (state != eStateConnected) {
3446 SaveScriptedLaunchInfo(attach_info);
3447 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3448 process_sp =
3450 plugin_name, nullptr, false);
3451 if (!process_sp) {
3452 error.SetErrorStringWithFormatv(
3453 "failed to create process using plugin '{0}'",
3454 plugin_name.empty() ? "<empty>" : plugin_name);
3455 return error;
3456 }
3457 }
3458 if (hijack_listener_sp)
3459 process_sp->HijackProcessEvents(hijack_listener_sp);
3460 error = process_sp->Attach(attach_info);
3461 }
3462
3463 if (error.Success() && process_sp) {
3464 if (async) {
3465 process_sp->RestoreProcessEvents();
3466 } else {
3467 // We are stopping all the way out to the user, so update selected frames.
3468 state = process_sp->WaitForProcessToStop(
3469 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3471 process_sp->RestoreProcessEvents();
3472
3473 if (state != eStateStopped) {
3474 const char *exit_desc = process_sp->GetExitDescription();
3475 if (exit_desc)
3476 error.SetErrorStringWithFormat("%s", exit_desc);
3477 else
3478 error.SetErrorString(
3479 "process did not stop (no such process or permission problem?)");
3480 process_sp->Destroy(false);
3481 }
3482 }
3483 }
3484 return error;
3485}
3486
3488 Log *log = GetLog(LLDBLog::Process);
3489
3490 // Finalize the file actions, and if none were given, default to opening up a
3491 // pseudo terminal
3492 PlatformSP platform_sp = GetPlatform();
3493 const bool default_to_use_pty =
3494 m_platform_sp ? m_platform_sp->IsHost() : false;
3495 LLDB_LOG(
3496 log,
3497 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3498 bool(platform_sp),
3499 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3500 default_to_use_pty);
3501
3502 // If nothing for stdin or stdout or stderr was specified, then check the
3503 // process for any default settings that were set with "settings set"
3504 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3505 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3506 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3507 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3508 "default handling");
3509
3510 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3511 // Do nothing, if we are launching in a remote terminal no file actions
3512 // should be done at all.
3513 return;
3514 }
3515
3516 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3517 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3518 "for stdin, stdout and stderr");
3519 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3520 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3521 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3522 } else {
3523 // Check for any values that might have gotten set with any of: (lldb)
3524 // settings set target.input-path (lldb) settings set target.output-path
3525 // (lldb) settings set target.error-path
3526 FileSpec in_file_spec;
3527 FileSpec out_file_spec;
3528 FileSpec err_file_spec;
3529 // Only override with the target settings if we don't already have an
3530 // action for in, out or error
3531 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3532 in_file_spec = GetStandardInputPath();
3533 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3534 out_file_spec = GetStandardOutputPath();
3535 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3536 err_file_spec = GetStandardErrorPath();
3537
3538 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3539 in_file_spec, out_file_spec, err_file_spec);
3540
3541 if (in_file_spec) {
3542 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3543 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3544 }
3545
3546 if (out_file_spec) {
3547 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3548 LLDB_LOG(log, "appended stdout open file action for {0}",
3549 out_file_spec);
3550 }
3551
3552 if (err_file_spec) {
3553 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3554 LLDB_LOG(log, "appended stderr open file action for {0}",
3555 err_file_spec);
3556 }
3557
3558 if (default_to_use_pty) {
3559 llvm::Error Err = info.SetUpPtyRedirection();
3560 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3561 }
3562 }
3563 }
3564}
3565
3566void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
3567 LazyBool stop) {
3568 if (name.empty())
3569 return;
3570 // Don't add a signal if all the actions are trivial:
3571 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
3572 && stop == eLazyBoolCalculate)
3573 return;
3574
3575 auto& elem = m_dummy_signals[name];
3576 elem.pass = pass;
3577 elem.notify = notify;
3578 elem.stop = stop;
3579}
3580
3582 const DummySignalElement &elem) {
3583 if (!signals_sp)
3584 return false;
3585
3586 int32_t signo
3587 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3588 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3589 return false;
3590
3591 if (elem.second.pass == eLazyBoolYes)
3592 signals_sp->SetShouldSuppress(signo, false);
3593 else if (elem.second.pass == eLazyBoolNo)
3594 signals_sp->SetShouldSuppress(signo, true);
3595
3596 if (elem.second.notify == eLazyBoolYes)
3597 signals_sp->SetShouldNotify(signo, true);
3598 else if (elem.second.notify == eLazyBoolNo)
3599 signals_sp->SetShouldNotify(signo, false);
3600
3601 if (elem.second.stop == eLazyBoolYes)
3602 signals_sp->SetShouldStop(signo, true);
3603 else if (elem.second.stop == eLazyBoolNo)
3604 signals_sp->SetShouldStop(signo, false);
3605 return true;
3606}
3607
3609 const DummySignalElement &elem) {
3610 if (!signals_sp)
3611 return false;
3612 int32_t signo
3613 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3614 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3615 return false;
3616 bool do_pass = elem.second.pass != eLazyBoolCalculate;
3617 bool do_stop = elem.second.stop != eLazyBoolCalculate;
3618 bool do_notify = elem.second.notify != eLazyBoolCalculate;
3619 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
3620 return true;
3621}
3622
3624 StreamSP warning_stream_sp) {
3625 if (!signals_sp)
3626 return;
3627
3628 for (const auto &elem : m_dummy_signals) {
3629 if (!UpdateSignalFromDummy(signals_sp, elem))
3630 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
3631 elem.first().str().c_str());
3632 }
3633}
3634
3635void Target::ClearDummySignals(Args &signal_names) {
3636 ProcessSP process_sp = GetProcessSP();
3637 // The simplest case, delete them all with no process to update.
3638 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
3639 m_dummy_signals.clear();
3640 return;
3641 }
3642 UnixSignalsSP signals_sp;
3643 if (process_sp)
3644 signals_sp = process_sp->GetUnixSignals();
3645
3646 for (const Args::ArgEntry &entry : signal_names) {
3647 const char *signal_name = entry.c_str();
3648 auto elem = m_dummy_signals.find(signal_name);
3649 // If we didn't find it go on.
3650 // FIXME: Should I pipe error handling through here?
3651 if (elem == m_dummy_signals.end()) {
3652 continue;
3653 }
3654 if (signals_sp)
3655 ResetSignalFromDummy(signals_sp, *elem);
3656 m_dummy_signals.erase(elem);
3657 }
3658}
3659
3660void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
3661 strm.Printf("NAME PASS STOP NOTIFY\n");
3662 strm.Printf("=========== ======= ======= =======\n");
3663
3664 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
3665 switch (lazy) {
3666 case eLazyBoolCalculate: return "not set";
3667 case eLazyBoolYes: return "true ";
3668 case eLazyBoolNo: return "false ";
3669 }
3670 llvm_unreachable("Fully covered switch above!");
3671 };
3672 size_t num_args = signal_args.GetArgumentCount();
3673 for (const auto &elem : m_dummy_signals) {
3674 bool print_it = false;
3675 for (size_t idx = 0; idx < num_args; idx++) {
3676 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
3677 print_it = true;
3678 break;
3679 }
3680 }
3681 if (print_it) {
3682 strm.Printf("%-11s ", elem.first().str().c_str());
3683 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
3684 str_for_lazy(elem.second.stop),
3685 str_for_lazy(elem.second.notify));
3686 }
3687 }
3688}
3689
3690// Target::StopHook
3692 : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3693 m_thread_spec_up() {}
3694
3696 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3697 m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3698 m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3699 if (rhs.m_thread_spec_up)
3700 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3701}
3702
3704 m_specifier_sp.reset(specifier);
3705}
3706
3708 m_thread_spec_up.reset(specifier);
3709}
3710
3712 SymbolContextSpecifier *specifier = GetSpecifier();
3713 if (!specifier)
3714 return true;
3715
3716 bool will_run = true;
3717 if (exc_ctx.GetFramePtr())
3718 will_run = GetSpecifier()->SymbolContextMatches(
3719 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3720 if (will_run && GetThreadSpecifier() != nullptr)
3721 will_run =
3722 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3723
3724 return will_run;
3725}
3726
3728 lldb::DescriptionLevel level) const {
3729
3730 // For brief descriptions, only print the subclass description:
3731 if (level == eDescriptionLevelBrief) {
3732 GetSubclassDescription(s, level);
3733 return;
3734 }
3735
3736 unsigned indent_level = s.GetIndentLevel();
3737
3738 s.SetIndentLevel(indent_level + 2);
3739
3740 s.Printf("Hook: %" PRIu64 "\n", GetID());
3741 if (m_active)
3742 s.Indent("State: enabled\n");
3743 else
3744 s.Indent("State: disabled\n");
3745
3746 if (m_auto_continue)
3747 s.Indent("AutoContinue on\n");
3748
3749 if (m_specifier_sp) {
3750 s.Indent();
3751 s.PutCString("Specifier:\n");
3752 s.SetIndentLevel(indent_level + 4);
3753 m_specifier_sp->GetDescription(&s, level);
3754 s.SetIndentLevel(indent_level + 2);
3755 }
3756
3757 if (m_thread_spec_up) {
3758 StreamString tmp;
3759 s.Indent("Thread:\n");
3760 m_thread_spec_up->GetDescription(&tmp, level);
3761 s.SetIndentLevel(indent_level + 4);
3762 s.Indent(tmp.GetString());
3763 s.PutCString("\n");
3764 s.SetIndentLevel(indent_level + 2);
3765 }
3766 GetSubclassDescription(s, level);
3767}
3768
3770 Stream &s, lldb::DescriptionLevel level) const {
3771 // The brief description just prints the first command.
3772 if (level == eDescriptionLevelBrief) {
3773 if (m_commands.GetSize() == 1)
3774 s.PutCString(m_commands.GetStringAtIndex(0));
3775 return;
3776 }
3777 s.Indent("Commands: \n");
3778 s.SetIndentLevel(s.GetIndentLevel() + 4);
3779 uint32_t num_commands = m_commands.GetSize();
3780 for (uint32_t i = 0; i < num_commands; i++) {
3781 s.Indent(m_commands.GetStringAtIndex(i));
3782 s.PutCString("\n");
3783 }
3784 s.SetIndentLevel(s.GetIndentLevel() - 4);
3785}
3786
3787// Target::StopHookCommandLine
3789 GetCommands().SplitIntoLines(string);
3790}
3791
3793 const std::vector<std::string> &strings) {
3794 for (auto string : strings)
3795 GetCommands().AppendString(string.c_str());
3796}
3797
3800 StreamSP output_sp) {
3801 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3802 "with no target");
3803
3804 if (!m_commands.GetSize())
3805 return StopHookResult::KeepStopped;
3806
3807 CommandReturnObject result(false);
3808 result.SetImmediateOutputStream(output_sp);
3809 result.SetInteractive(false);
3810 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3812 options.SetStopOnContinue(true);
3813 options.SetStopOnError(true);
3814 options.SetEchoCommands(false);
3815 options.SetPrintResults(true);
3816 options.SetPrintErrors(true);
3817 options.SetAddToHistory(false);
3818
3819 // Force Async:
3820 bool old_async = debugger.GetAsyncExecution();
3821 debugger.SetAsyncExecution(true);
3822 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
3823 options, result);
3824 debugger.SetAsyncExecution(old_async);
3825 lldb::ReturnStatus status = result.GetStatus();
3828 return StopHookResult::AlreadyContinued;
3829 return StopHookResult::KeepStopped;
3830}
3831
3832// Target::StopHookScripted
3834 std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3835 Status error;
3836
3837 ScriptInterpreter *script_interp =
3838 GetTarget()->GetDebugger().GetScriptInterpreter();
3839 if (!script_interp) {
3840 error.SetErrorString("No script interpreter installed.");
3841 return error;
3842 }
3843
3844 m_class_name = class_name;
3845 m_extra_args.SetObjectSP(extra_args_sp);
3846
3847 m_implementation_sp = script_interp->CreateScriptedStopHook(
3848 GetTarget(), m_class_name.c_str(), m_extra_args, error);
3849
3850 return error;
3851}
3852
3855 StreamSP output_sp) {
3856 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3857 "with no target");
3858
3859 ScriptInterpreter *script_interp =
3860 GetTarget()->GetDebugger().GetScriptInterpreter();
3861 if (!script_interp)
3862 return StopHookResult::KeepStopped;
3863
3864 bool should_stop = script_interp->ScriptedStopHookHandleStop(
3865 m_implementation_sp, exc_ctx, output_sp);
3866
3867 return should_stop ? StopHookResult::KeepStopped
3868 : StopHookResult::RequestContinue;
3869}
3870
3872 Stream &s, lldb::DescriptionLevel level) const {
3873 if (level == eDescriptionLevelBrief) {
3874 s.PutCString(m_class_name);
3875 return;
3876 }
3877 s.Indent("Class:");
3878 s.Printf("%s\n", m_class_name.c_str());
3879
3880 // Now print the extra args:
3881 // FIXME: We should use StructuredData.GetDescription on the m_extra_args
3882 // but that seems to rely on some printing plugin that doesn't exist.
3883 if (!m_extra_args.IsValid())
3884 return;
3885 StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP();
3886 if (!object_sp || !object_sp->IsValid())
3887 return;
3888
3889 StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
3890 if (!as_dict || !as_dict->IsValid())
3891 return;
3892
3893 uint32_t num_keys = as_dict->GetSize();
3894 if (num_keys == 0)
3895 return;
3896
3897 s.Indent("Args:\n");
3898 s.SetIndentLevel(s.GetIndentLevel() + 4);
3899
3900 auto print_one_element = [&s](llvm::StringRef key,
3901 StructuredData::Object *object) {
3902 s.Indent();
3903 s.Format("{0} : {1}\n", key, object->GetStringValue());
3904 return true;
3905 };
3906
3907 as_dict->ForEach(print_one_element);
3908
3909 s.SetIndentLevel(s.GetIndentLevel() - 4);
3910}
3911
3913 {
3915 "no-dynamic-values",
3916 "Don't calculate the dynamic type of values",
3917 },
3918 {
3920 "run-target",
3921 "Calculate the dynamic type of values "
3922 "even if you have to run the target.",
3923 },
3924 {
3926 "no-run-target",
3927 "Calculate the dynamic type of values, but don't run the target.",
3928 },
3929};
3930
3933}
3934
3936 {
3938 "never",
3939 "Never look for inline breakpoint locations (fastest). This setting "
3940 "should only be used if you know that no inlining occurs in your"
3941 "programs.",
3942 },
3943 {
3945 "headers",
3946 "Only check for inline breakpoint locations when setting breakpoints "
3947 "in header files, but not when setting breakpoint in implementation "
3948 "source files (default).",
3949 },
3950 {
3952 "always",
3953 "Always look for inline breakpoint locations when setting file and "
3954 "line breakpoints (slower but most accurate).",
3955 },
3956};
3957
3963
3965 {
3967 "default",
3968 "Disassembler default (currently att).",
3969 },
3970 {
3972 "intel",
3973 "Intel disassembler flavor.",
3974 },
3975 {
3977 "att",
3978 "AT&T disassembler flavor.",
3979 },
3980};
3981
3983 {
3985 "false",
3986 "Never import the 'std' C++ module in the expression parser.",
3987 },
3988 {
3990 "fallback",
3991 "Retry evaluating expressions with an imported 'std' C++ module if they"
3992 " failed to parse without the module. This allows evaluating more "
3993 "complex expressions involving C++ standard library types."
3994 },
3995 {
3997 "true",
3998 "Always import the 'std' C++ module. This allows evaluating more "
3999 "complex expressions involving C++ standard library types. This feature"
4000 " is experimental."
4001 },
4002};
4003
4004static constexpr OptionEnumValueElement
4006 {
4008 "auto",
4009 "Automatically determine the most appropriate method for the "
4010 "target OS.",
4011 },
4012 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4013 "Prefer using the realized classes struct."},
4014 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4015 "Prefer using the CopyRealizedClassList API."},
4016 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4017 "Prefer using the GetRealizedClassList API."},
4018};
4019
4021 {
4023 "c",
4024 "C-style (0xffff).",
4025 },
4026 {
4028 "asm",
4029 "Asm-style (0ffffh).",
4030 },
4031};
4032
4034 {
4036 "true",
4037 "Load debug scripts inside symbol files",
4038 },
4039 {
4041 "false",
4042 "Do not load debug scripts inside symbol files.",
4043 },
4044 {
4046 "warn",
4047 "Warn about debug scripts inside symbol files but do not load them.",
4048 },
4049};
4050
4052 {
4054 "true",
4055 "Load .lldbinit files from current directory",
4056 },
4057 {
4059 "false",
4060 "Do not load .lldbinit files from current directory",
4061 },
4062 {
4064 "warn",
4065 "Warn about loading .lldbinit files from current directory",
4066 },
4067};
4068
4070 {
4072 "minimal",
4073 "Load minimal information when loading modules from memory. Currently "
4074 "this setting loads sections only.",
4075 },
4076 {
4078 "partial",
4079 "Load partial information when loading modules from memory. Currently "
4080 "this setting loads sections and function bounds.",
4081 },
4082 {
4084 "complete",
4085 "Load complete information when loading modules from memory. Currently "
4086 "this setting loads sections and all symbols.",
4087 },
4088};
4089
4090#define LLDB_PROPERTIES_target
4091#include "TargetProperties.inc"
4092
4093enum {
4094#define LLDB_PROPERTIES_target
4095#include "TargetPropertiesEnum.inc"
4097};
4098
4100 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
4101public:
4102 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
4103
4104 const Property *
4106 const ExecutionContext *exe_ctx = nullptr) const override {
4107 // When getting the value for a key from the target options, we will always
4108 // try and grab the setting from the current target if there is one. Else
4109 // we just use the one from this instance.
4110 if (exe_ctx) {
4111 Target *target = exe_ctx->GetTargetPtr();
4112 if (target) {
4113 TargetOptionValueProperties *target_properties =
4114 static_cast<TargetOptionValueProperties *>(
4115 target->GetValueProperties().get());
4116 if (this != target_properties)
4117 return target_properties->ProtectedGetPropertyAtIndex(idx);
4118 }
4119 }
4120 return ProtectedGetPropertyAtIndex(idx);
4121 }
4122};
4123
4124// TargetProperties
4125#define LLDB_PROPERTIES_target_experimental
4126#include "TargetProperties.inc"
4127
4128enum {
4129#define LLDB_PROPERTIES_target_experimental
4130#include "TargetPropertiesEnum.inc"
4131};
4132
4134 : public Cloneable<TargetExperimentalOptionValueProperties,
4135 OptionValueProperties> {
4136public:
4138 : Cloneable(Properties::GetExperimentalSettingsName()) {}
4139};
4140
4144 m_collection_sp->Initialize(g_target_experimental_properties);
4145}
4146
4147// TargetProperties
4149 : Properties(), m_launch_info(), m_target(target) {
4150 if (target) {
4153
4154 // Set callbacks to update launch_info whenever "settins set" updated any
4155 // of these properties
4156 m_collection_sp->SetValueChangedCallback(
4157 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
4158 m_collection_sp->SetValueChangedCallback(
4159 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
4160 m_collection_sp->SetValueChangedCallback(
4161 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
4162 m_collection_sp->SetValueChangedCallback(
4163 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
4164 m_collection_sp->SetValueChangedCallback(
4165 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
4166 m_collection_sp->SetValueChangedCallback(
4167 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
4168 m_collection_sp->SetValueChangedCallback(
4169 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
4170 m_collection_sp->SetValueChangedCallback(
4171 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
4172 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
4174 });
4175 m_collection_sp->SetValueChangedCallback(
4176 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
4177 m_collection_sp->SetValueChangedCallback(
4178 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
4179 m_collection_sp->SetValueChangedCallback(
4180 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
4181
4182 m_collection_sp->SetValueChangedCallback(
4183 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4185 std::make_unique<TargetExperimentalProperties>();
4186 m_collection_sp->AppendProperty(
4188 "Experimental settings - setting these won't produce "
4189 "errors if the setting is not present.",
4190 true, m_experimental_properties_up->GetValueProperties());
4191 } else {
4192 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
4193 m_collection_sp->Initialize(g_target_properties);
4195 std::make_unique<TargetExperimentalProperties>();
4196 m_collection_sp->AppendProperty(
4198 "Experimental settings - setting these won't produce "
4199 "errors if the setting is not present.",
4200 true, m_experimental_properties_up->GetValueProperties());
4201 m_collection_sp->AppendProperty(
4202 "process", "Settings specific to processes.", true,
4204 m_collection_sp->SetValueChangedCallback(
4205 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4206 }
4207}
4208
4210
4222}
4223
4225 size_t prop_idx, ExecutionContext *exe_ctx) const {
4226 const Property *exp_property =
4227 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4228 OptionValueProperties *exp_values =
4229 exp_property->GetValue()->GetAsProperties();
4230 if (exp_values)
4231 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx);
4232 return std::nullopt;
4233}
4234
4236 ExecutionContext *exe_ctx) const {
4237 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx)
4238 .value_or(true);
4239}
4240
4242 const uint32_t idx = ePropertyDefaultArch;
4243 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
4244}
4245
4247 const uint32_t idx = ePropertyDefaultArch;
4248 SetPropertyAtIndex(idx, arch);
4249}
4250
4252 const uint32_t idx = ePropertyMoveToNearestCode;
4253 return GetPropertyAtIndexAs<bool>(
4254 idx, g_target_properties[idx].default_uint_value != 0);
4255}
4256
4258 const uint32_t idx = ePropertyPreferDynamic;
4259 return GetPropertyAtIndexAs<lldb::DynamicValueType>(
4260 idx, static_cast<lldb::DynamicValueType>(
4261 g_target_properties[idx].default_uint_value));
4262}
4263
4265 const uint32_t idx = ePropertyPreferDynamic;
4266 return SetPropertyAtIndex(idx, d);
4267}
4268
4271 "Interrupted checking preload symbols")) {
4272 return false;
4273 }
4274 const uint32_t idx = ePropertyPreloadSymbols;
4275 return GetPropertyAtIndexAs<bool>(
4276 idx, g_target_properties[idx].default_uint_value != 0);
4277}
4278
4280 const uint32_t idx = ePropertyPreloadSymbols;
4281 SetPropertyAtIndex(idx, b);
4282}
4283
4285 const uint32_t idx = ePropertyDisableASLR;
4286 return GetPropertyAtIndexAs<bool>(
4287 idx, g_target_properties[idx].default_uint_value != 0);
4288}
4289
4291 const uint32_t idx = ePropertyDisableASLR;
4292 SetPropertyAtIndex(idx, b);
4293}
4294
4296 const uint32_t idx = ePropertyInheritTCC;
4297 return GetPropertyAtIndexAs<bool>(
4298 idx, g_target_properties[idx].default_uint_value != 0);
4299}
4300
4302 const uint32_t idx = ePropertyInheritTCC;
4303 SetPropertyAtIndex(idx, b);
4304}
4305
4307 const uint32_t idx = ePropertyDetachOnError;
4308 return GetPropertyAtIndexAs<bool>(
4309 idx, g_target_properties[idx].default_uint_value != 0);
4310}
4311
4313 const uint32_t idx = ePropertyDetachOnError;
4314 SetPropertyAtIndex(idx, b);
4315}
4316
4318 const uint32_t idx = ePropertyDisableSTDIO;
4319 return GetPropertyAtIndexAs<bool>(
4320 idx, g_target_properties[idx].default_uint_value != 0);
4321}
4322
4324 const uint32_t idx = ePropertyDisableSTDIO;
4325 SetPropertyAtIndex(idx, b);
4326}
4327
4329 const uint32_t idx = ePropertyDisassemblyFlavor;
4330 const char *return_value;
4331
4332 x86DisassemblyFlavor flavor_value =
4333 GetPropertyAtIndexAs<x86DisassemblyFlavor>(
4334 idx, static_cast<x86DisassemblyFlavor>(
4335 g_target_properties[idx].default_uint_value));
4336
4337 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
4338 return return_value;
4339}
4340
4342 const uint32_t idx = ePropertyInlineStrategy;
4343 return GetPropertyAtIndexAs<InlineStrategy>(
4344 idx,
4345 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
4346}
4347
4348llvm::StringRef TargetProperties::GetArg0() const {
4349 const uint32_t idx = ePropertyArg0;
4350 return GetPropertyAtIndexAs<llvm::StringRef>(
4351 idx, g_target_properties[idx].default_cstr_value);
4352}
4353
4354void TargetProperties::SetArg0(llvm::StringRef arg) {
4355 const uint32_t idx = ePropertyArg0;
4356 SetPropertyAtIndex(idx, arg);
4358}
4359
4361 const uint32_t idx = ePropertyRunArgs;
4362 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4363}
4364
4366 const uint32_t idx = ePropertyRunArgs;
4367 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4368 m_launch_info.GetArguments() = args;
4369}
4370
4372 Environment env;
4373
4374 if (m_target &&
4375 GetPropertyAtIndexAs<bool>(
4376 ePropertyInheritEnv,
4377 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
4378 if (auto platform_sp = m_target->GetPlatform()) {
4379 Environment platform_env = platform_sp->GetEnvironment();
4380 for (const auto &KV : platform_env)
4381 env[KV.first()] = KV.second;
4382 }
4383 }
4384
4385 Args property_unset_env;
4386 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4387 property_unset_env);
4388 for (const auto &var : property_unset_env)
4389 env.erase(var.ref());
4390
4391 Args property_env;
4392 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
4393 for (const auto &KV : Environment(property_env))
4394 env[KV.first()] = KV.second;
4395
4396 return env;
4397}
4398
4400 return ComputeEnvironment();
4401}
4402
4404 Environment environment;
4405
4406 if (m_target == nullptr)
4407 return environment;
4408
4409 if (!GetPropertyAtIndexAs<bool>(
4410 ePropertyInheritEnv,
4411 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
4412 return environment;
4413
4414 PlatformSP platform_sp = m_target->GetPlatform();
4415 if (platform_sp == nullptr)
4416 return environment;
4417
4418 Environment platform_environment = platform_sp->GetEnvironment();
4419 for (const auto &KV : platform_environment)
4420 environment[KV.first()] = KV.second;
4421
4422 Args property_unset_environment;
4423 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4424 property_unset_environment);
4425 for (const auto &var : property_unset_environment)
4426 environment.erase(var.ref());
4427
4428 return environment;
4429}
4430
4432 Args property_environment;
4433 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
4434 property_environment);
4435 Environment environment;
4436 for (const auto &KV : Environment(property_environment))
4437 environment[KV.first()] = KV.second;
4438
4439 return environment;
4440}
4441
4443 // TODO: Get rid of the Args intermediate step
4444 const uint32_t idx = ePropertyEnvVars;
4445 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
4446}
4447
4449 const uint32_t idx = ePropertySkipPrologue;
4450 return GetPropertyAtIndexAs<bool>(
4451 idx, g_target_properties[idx].default_uint_value != 0);
4452}
4453
4455 const uint32_t idx = ePropertySourceMap;
4456 OptionValuePathMappings *option_value =
4457 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4458 assert(option_value);
4459 return option_value->GetCurrentValue();
4460}
4461
4463 const uint32_t idx = ePropertyAutoSourceMapRelative;
4464 return GetPropertyAtIndexAs<bool>(
4465 idx, g_target_properties[idx].default_uint_value != 0);
4466}
4467
4469 const uint32_t idx = ePropertyExecutableSearchPaths;
4470 OptionValueFileSpecList *option_value =
4471 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
4472 assert(option_value);
4473 option_value->AppendCurrentValue(dir);
4474}
4475
4477 const uint32_t idx = ePropertyExecutableSearchPaths;
4478 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4479}
4480
4482 const uint32_t idx = ePropertyDebugFileSearchPaths;
4483 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4484}
4485
4487 const uint32_t idx = ePropertyClangModuleSearchPaths;
4488 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4489}
4490
4492 const uint32_t idx = ePropertyAutoImportClangModules;
4493 return GetPropertyAtIndexAs<bool>(
4494 idx, g_target_properties[idx].default_uint_value != 0);
4495}
4496
4498 const uint32_t idx = ePropertyImportStdModule;
4499 return GetPropertyAtIndexAs<ImportStdModule>(
4500 idx, static_cast<ImportStdModule>(
4501 g_target_properties[idx].default_uint_value));
4502}
4503
4505 const uint32_t idx = ePropertyDynamicClassInfoHelper;
4506 return GetPropertyAtIndexAs<DynamicClassInfoHelper>(
4507 idx, static_cast<DynamicClassInfoHelper>(
4508 g_target_properties[idx].default_uint_value));
4509}
4510
4512 const uint32_t idx = ePropertyAutoApplyFixIts;
4513 return GetPropertyAtIndexAs<bool>(
4514 idx, g_target_properties[idx].default_uint_value != 0);
4515}
4516
4518 const uint32_t idx = ePropertyRetriesWithFixIts;
4519 return GetPropertyAtIndexAs<uint64_t>(
4520 idx, g_target_properties[idx].default_uint_value);
4521}
4522
4524 const uint32_t idx = ePropertyNotifyAboutFixIts;
4525 return GetPropertyAtIndexAs<bool>(
4526 idx, g_target_properties[idx].default_uint_value != 0);
4527}
4528
4530 const uint32_t idx = ePropertySaveObjectsDir;
4531 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4532}
4533
4535 FileSpec new_dir = GetSaveJITObjectsDir();
4536 if (!new_dir)
4537 return;
4538
4539 const FileSystem &instance = FileSystem::Instance();
4540 bool exists = instance.Exists(new_dir);
4541 bool is_directory = instance.IsDirectory(new_dir);
4542 std::string path = new_dir.GetPath(true);
4543 bool writable = llvm::sys::fs::can_write(path);
4544 if (exists && is_directory && writable)
4545 return;
4546
4547 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
4548 ->GetValue()
4549 ->Clear();
4550
4551 std::string buffer;
4552 llvm::raw_string_ostream os(buffer);
4553 os << "JIT object dir '" << path << "' ";
4554 if (!exists)
4555 os << "does not exist";
4556 else if (!is_directory)
4557 os << "is not a directory";
4558 else if (!writable)
4559 os << "is not writable";
4560
4561 std::optional<lldb::user_id_t> debugger_id;
4562 if (m_target)
4563 debugger_id = m_target->GetDebugger().GetID();
4564 Debugger::ReportError(os.str(), debugger_id);
4565}
4566
4568 const uint32_t idx = ePropertyEnableSynthetic;
4569 return GetPropertyAtIndexAs<bool>(
4570 idx, g_target_properties[idx].default_uint_value != 0);
4571}
4572
4574 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
4575 return GetPropertyAtIndexAs<bool>(
4576 idx, g_target_properties[idx].default_uint_value != 0);
4577}
4578
4580 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4581 return GetPropertyAtIndexAs<uint64_t>(
4582 idx, g_target_properties[idx].default_uint_value);
4583}
4584
4586 const uint32_t idx = ePropertyMaxChildrenCount;
4587 return GetPropertyAtIndexAs<int64_t>(
4588 idx, g_target_properties[idx].default_uint_value);
4589}
4590
4591std::pair<uint32_t, bool>
4593 const uint32_t idx = ePropertyMaxChildrenDepth;
4594 auto *option_value =
4595 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
4596 bool is_default = !option_value->OptionWasSet();
4597 return {option_value->GetCurrentValue(), is_default};
4598}
4599
4601 const uint32_t idx = ePropertyMaxSummaryLength;
4602 return GetPropertyAtIndexAs<uint64_t>(
4603 idx, g_target_properties[idx].default_uint_value);
4604}
4605
4607 const uint32_t idx = ePropertyMaxMemReadSize;
4608 return GetPropertyAtIndexAs<uint64_t>(
4609 idx, g_target_properties[idx].default_uint_value);
4610}
4611
4613 const uint32_t idx = ePropertyInputPath;
4614 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4615}
4616
4617void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4618 const uint32_t idx = ePropertyInputPath;
4619 SetPropertyAtIndex(idx, path);
4620}
4621
4623 const uint32_t idx = ePropertyOutputPath;
4624 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4625}
4626
4628 const uint32_t idx = ePropertyOutputPath;
4629 SetPropertyAtIndex(idx, path);
4630}
4631
4633 const uint32_t idx = ePropertyErrorPath;
4634 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4635}
4636
4637void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4638 const uint32_t idx = ePropertyErrorPath;
4639 SetPropertyAtIndex(idx, path);
4640}
4641
4643 const uint32_t idx = ePropertyLanguage;
4644 return {GetPropertyAtIndexAs<LanguageType>(idx, {})};
4645}
4646
4648 const uint32_t idx = ePropertyExprPrefix;
4649 OptionValueFileSpec *file =
4650 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
4651 if (file) {
4652 DataBufferSP data_sp(file->GetFileContents());
4653 if (data_sp)
4654 return llvm::StringRef(
4655 reinterpret_cast<const char *>(data_sp->GetBytes()),
4656 data_sp->GetByteSize());
4657 }
4658 return "";
4659}
4660
4662 const uint32_t idx = ePropertyExprErrorLimit;
4663 return GetPropertyAtIndexAs<uint64_t>(
4664 idx, g_target_properties[idx].default_uint_value);
4665}
4666
4668 const uint32_t idx = ePropertyExprAllocAddress;
4669 return GetPropertyAtIndexAs<uint64_t>(
4670 idx, g_target_properties[idx].default_uint_value);
4671}
4672
4674 const uint32_t idx = ePropertyExprAllocSize;
4675 return GetPropertyAtIndexAs<uint64_t>(
4676 idx, g_target_properties[idx].default_uint_value);
4677}
4678
4680 const uint32_t idx = ePropertyExprAllocAlign;
4681 return GetPropertyAtIndexAs<uint64_t>(
4682 idx, g_target_properties[idx].default_uint_value);
4683}
4684
4686 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4687 return GetPropertyAtIndexAs<bool>(
4688 idx, g_target_properties[idx].default_uint_value != 0);
4689}
4690
4692 const uint32_t idx = ePropertyUseHexImmediates;
4693 return GetPropertyAtIndexAs<bool>(
4694 idx, g_target_properties[idx].default_uint_value != 0);
4695}
4696
4698 const uint32_t idx = ePropertyUseFastStepping;
4699 return GetPropertyAtIndexAs<bool>(
4700 idx, g_target_properties[idx].default_uint_value != 0);
4701}
4702
4704 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4705 return GetPropertyAtIndexAs<bool>(
4706 idx, g_target_properties[idx].default_uint_value != 0);
4707}
4708
4710 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4711 return GetPropertyAtIndexAs<LoadScriptFromSymFile>(
4712 idx, static_cast<LoadScriptFromSymFile>(
4713 g_target_properties[idx].default_uint_value));
4714}
4715
4717 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4718 return GetPropertyAtIndexAs<LoadCWDlldbinitFile>(
4719 idx, static_cast<LoadCWDlldbinitFile>(
4720 g_target_properties[idx].default_uint_value));
4721}
4722
4724 const uint32_t idx = ePropertyHexImmediateStyle;
4725 return GetPropertyAtIndexAs<Disassembler::HexImmediateStyle>(
4726 idx, static_cast<Disassembler::HexImmediateStyle>(
4727 g_target_properties[idx].default_uint_value));
4728}
4729
4731 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4732 return GetPropertyAtIndexAs<MemoryModuleLoadLevel>(
4733 idx, static_cast<MemoryModuleLoadLevel>(
4734 g_target_properties[idx].default_uint_value));
4735}
4736
4738 const uint32_t idx = ePropertyTrapHandlerNames;
4739 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4740}
4741
4743 const uint32_t idx = ePropertyTrapHandlerNames;
4744 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4745}
4746
4748 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4749 return GetPropertyAtIndexAs<bool>(
4750 idx, g_target_properties[idx].default_uint_value != 0);
4751}
4752
4754 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4755 SetPropertyAtIndex(idx, b);
4756}
4757
4759 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4760 return GetPropertyAtIndexAs<bool>(
4761 idx, g_target_properties[idx].default_uint_value != 0);
4762}
4763
4765 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4766 SetPropertyAtIndex(idx, b);
4767}
4768
4770 return m_launch_info;
4771}
4772
4774 const ProcessLaunchInfo &launch_info) {
4775 m_launch_info = launch_info;
4776 SetArg0(launch_info.GetArg0());
4777 SetRunArguments(launch_info.GetArguments());
4778 SetEnvironment(launch_info.GetEnvironment());
4779 const FileAction *input_file_action =
4780 launch_info.GetFileActionForFD(STDIN_FILENO);
4781 if (input_file_action) {
4782 SetStandardInputPath(input_file_action->GetPath());
4783 }
4784 const FileAction *output_file_action =
4785 launch_info.GetFileActionForFD(STDOUT_FILENO);
4786 if (output_file_action) {
4787 SetStandardOutputPath(output_file_action->GetPath());
4788 }
4789 const FileAction *error_file_action =
4790 launch_info.GetFileActionForFD(STDERR_FILENO);
4791 if (error_file_action) {
4792 SetStandardErrorPath(error_file_action->GetPath());
4793 }
4794 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4795 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4797 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4798 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4799}
4800
4802 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4803 return GetPropertyAtIndexAs<bool>(
4804 idx, g_target_properties[idx].default_uint_value != 0);
4805}
4806
4808 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4809 m_collection_sp->SetPropertyAtIndex(idx, b);
4810}
4811
4813 const uint32_t idx = ePropertyAutoInstallMainExecutable;
4814 return GetPropertyAtIndexAs<bool>(
4815 idx, g_target_properties[idx].default_uint_value != 0);
4816}
4817
4820}
4821
4823 Args args;
4824 if (GetRunArguments(args))
4825 m_launch_info.GetArguments() = args;
4826}
4827
4830}
4831
4834 false);
4835}
4836
4839 false, true);
4840}
4841
4844 false, true);
4845}
4846
4848 if (GetDetachOnError())
4849 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4850 else
4851 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4852}
4853
4855 if (GetDisableASLR())
4856 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4857 else
4858 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4859}
4860
4862 if (GetInheritTCC())
4863 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4864 else
4865 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4866}
4867
4869 if (GetDisableSTDIO())
4870 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4871 else
4872 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4873}
4874
4876 const uint32_t idx = ePropertyDebugUtilityExpression;
4877 return GetPropertyAtIndexAs<bool>(
4878 idx, g_target_properties[idx].default_uint_value != 0);
4879}
4880
4882 const uint32_t idx = ePropertyDebugUtilityExpression;
4883 SetPropertyAtIndex(idx, debug);
4884}
4885
4886// Target::TargetEventData
4887
4889 : EventData(), m_target_sp(target_sp), m_module_list() {}
4890
4892 const ModuleList &module_list)
4893 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4894
4896
4898 return "Target::TargetEventData";
4899}
4900
4902 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4903 if (i != 0)
4904 *s << ", ";
4905 m_module_list.GetModuleAtIndex(i)->GetDescription(
4907 }
4908}
4909
4912 if (event_ptr) {
4913 const EventData *event_data = event_ptr->GetData();
4914 if (event_data &&
4916 return static_cast<const TargetEventData *>(event_ptr->GetData());
4917 }
4918 return nullptr;
4919}
4920
4922 TargetSP target_sp;
4923 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4924 if (event_data)
4925 target_sp = event_data->m_target_sp;
4926 return target_sp;
4927}
4928
4931 ModuleList module_list;
4932 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4933 if (event_data)
4934 module_list = event_data->m_module_list;
4935 return module_list;
4936}
4937
4938std::recursive_mutex &Target::GetAPIMutex() {
4939 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4940 return m_private_mutex;
4941 else
4942 return m_mutex;
4943}
4944
4945/// Get metrics associated with this target in JSON format.
4946llvm::json::Value
4948 return m_stats.ToJSON(*this, options);
4949}
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
#define lldbassert(x)
Definition: LLDBAssert.h:15
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:359
#define LLDB_LOGF(log,...)
Definition: Log.h:366
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:382
@ ePropertyExperimental
Definition: Process.cpp:162