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