xref: /freebsd/contrib/llvm-project/lldb/source/API/SBTarget.cpp (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===-- SBTarget.cpp ------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/API/SBTarget.h"
10 #include "lldb/API/SBBreakpoint.h"
11 #include "lldb/API/SBDebugger.h"
12 #include "lldb/API/SBEnvironment.h"
13 #include "lldb/API/SBEvent.h"
14 #include "lldb/API/SBExpressionOptions.h"
15 #include "lldb/API/SBFileSpec.h"
16 #include "lldb/API/SBListener.h"
17 #include "lldb/API/SBModule.h"
18 #include "lldb/API/SBModuleSpec.h"
19 #include "lldb/API/SBMutex.h"
20 #include "lldb/API/SBProcess.h"
21 #include "lldb/API/SBSourceManager.h"
22 #include "lldb/API/SBStream.h"
23 #include "lldb/API/SBStringList.h"
24 #include "lldb/API/SBStructuredData.h"
25 #include "lldb/API/SBSymbolContextList.h"
26 #include "lldb/API/SBTrace.h"
27 #include "lldb/Breakpoint/BreakpointID.h"
28 #include "lldb/Breakpoint/BreakpointIDList.h"
29 #include "lldb/Breakpoint/BreakpointList.h"
30 #include "lldb/Breakpoint/BreakpointLocation.h"
31 #include "lldb/Core/Address.h"
32 #include "lldb/Core/AddressResolver.h"
33 #include "lldb/Core/Debugger.h"
34 #include "lldb/Core/Disassembler.h"
35 #include "lldb/Core/Module.h"
36 #include "lldb/Core/ModuleSpec.h"
37 #include "lldb/Core/PluginManager.h"
38 #include "lldb/Core/SearchFilter.h"
39 #include "lldb/Core/Section.h"
40 #include "lldb/Core/StructuredDataImpl.h"
41 #include "lldb/Host/Host.h"
42 #include "lldb/Symbol/DeclVendor.h"
43 #include "lldb/Symbol/ObjectFile.h"
44 #include "lldb/Symbol/SymbolFile.h"
45 #include "lldb/Symbol/SymbolVendor.h"
46 #include "lldb/Symbol/TypeSystem.h"
47 #include "lldb/Symbol/VariableList.h"
48 #include "lldb/Target/ABI.h"
49 #include "lldb/Target/Language.h"
50 #include "lldb/Target/LanguageRuntime.h"
51 #include "lldb/Target/Process.h"
52 #include "lldb/Target/StackFrame.h"
53 #include "lldb/Target/Target.h"
54 #include "lldb/Target/TargetList.h"
55 #include "lldb/Utility/ArchSpec.h"
56 #include "lldb/Utility/Args.h"
57 #include "lldb/Utility/FileSpec.h"
58 #include "lldb/Utility/Instrumentation.h"
59 #include "lldb/Utility/LLDBLog.h"
60 #include "lldb/Utility/ProcessInfo.h"
61 #include "lldb/Utility/RegularExpression.h"
62 #include "lldb/ValueObject/ValueObjectConstResult.h"
63 #include "lldb/ValueObject/ValueObjectList.h"
64 #include "lldb/ValueObject/ValueObjectVariable.h"
65 #include "lldb/lldb-public.h"
66 
67 #include "Commands/CommandObjectBreakpoint.h"
68 #include "lldb/Interpreter/CommandReturnObject.h"
69 #include "llvm/Support/PrettyStackTrace.h"
70 #include "llvm/Support/Regex.h"
71 
72 using namespace lldb;
73 using namespace lldb_private;
74 
75 #define DEFAULT_DISASM_BYTE_SIZE 32
76 
AttachToProcess(ProcessAttachInfo & attach_info,Target & target)77 static Status AttachToProcess(ProcessAttachInfo &attach_info, Target &target) {
78   std::lock_guard<std::recursive_mutex> guard(target.GetAPIMutex());
79 
80   auto process_sp = target.GetProcessSP();
81   if (process_sp) {
82     const auto state = process_sp->GetState();
83     if (process_sp->IsAlive() && state == eStateConnected) {
84       // If we are already connected, then we have already specified the
85       // listener, so if a valid listener is supplied, we need to error out to
86       // let the client know.
87       if (attach_info.GetListener())
88         return Status::FromErrorString(
89             "process is connected and already has a listener, pass "
90             "empty listener");
91     }
92   }
93 
94   return target.Attach(attach_info, nullptr);
95 }
96 
97 // SBTarget constructor
SBTarget()98 SBTarget::SBTarget() { LLDB_INSTRUMENT_VA(this); }
99 
SBTarget(const SBTarget & rhs)100 SBTarget::SBTarget(const SBTarget &rhs) : m_opaque_sp(rhs.m_opaque_sp) {
101   LLDB_INSTRUMENT_VA(this, rhs);
102 }
103 
SBTarget(const TargetSP & target_sp)104 SBTarget::SBTarget(const TargetSP &target_sp) : m_opaque_sp(target_sp) {
105   LLDB_INSTRUMENT_VA(this, target_sp);
106 }
107 
operator =(const SBTarget & rhs)108 const SBTarget &SBTarget::operator=(const SBTarget &rhs) {
109   LLDB_INSTRUMENT_VA(this, rhs);
110 
111   if (this != &rhs)
112     m_opaque_sp = rhs.m_opaque_sp;
113   return *this;
114 }
115 
116 // Destructor
117 SBTarget::~SBTarget() = default;
118 
EventIsTargetEvent(const SBEvent & event)119 bool SBTarget::EventIsTargetEvent(const SBEvent &event) {
120   LLDB_INSTRUMENT_VA(event);
121 
122   return Target::TargetEventData::GetEventDataFromEvent(event.get()) != nullptr;
123 }
124 
GetTargetFromEvent(const SBEvent & event)125 SBTarget SBTarget::GetTargetFromEvent(const SBEvent &event) {
126   LLDB_INSTRUMENT_VA(event);
127 
128   return Target::TargetEventData::GetTargetFromEvent(event.get());
129 }
130 
GetNumModulesFromEvent(const SBEvent & event)131 uint32_t SBTarget::GetNumModulesFromEvent(const SBEvent &event) {
132   LLDB_INSTRUMENT_VA(event);
133 
134   const ModuleList module_list =
135       Target::TargetEventData::GetModuleListFromEvent(event.get());
136   return module_list.GetSize();
137 }
138 
GetModuleAtIndexFromEvent(const uint32_t idx,const SBEvent & event)139 SBModule SBTarget::GetModuleAtIndexFromEvent(const uint32_t idx,
140                                              const SBEvent &event) {
141   LLDB_INSTRUMENT_VA(idx, event);
142 
143   const ModuleList module_list =
144       Target::TargetEventData::GetModuleListFromEvent(event.get());
145   return SBModule(module_list.GetModuleAtIndex(idx));
146 }
147 
GetBroadcasterClassName()148 const char *SBTarget::GetBroadcasterClassName() {
149   LLDB_INSTRUMENT();
150 
151   return ConstString(Target::GetStaticBroadcasterClass()).AsCString();
152 }
153 
IsValid() const154 bool SBTarget::IsValid() const {
155   LLDB_INSTRUMENT_VA(this);
156   return this->operator bool();
157 }
operator bool() const158 SBTarget::operator bool() const {
159   LLDB_INSTRUMENT_VA(this);
160 
161   return m_opaque_sp.get() != nullptr && m_opaque_sp->IsValid();
162 }
163 
GetProcess()164 SBProcess SBTarget::GetProcess() {
165   LLDB_INSTRUMENT_VA(this);
166 
167   SBProcess sb_process;
168   ProcessSP process_sp;
169   if (TargetSP target_sp = GetSP()) {
170     process_sp = target_sp->GetProcessSP();
171     sb_process.SetSP(process_sp);
172   }
173 
174   return sb_process;
175 }
176 
GetPlatform()177 SBPlatform SBTarget::GetPlatform() {
178   LLDB_INSTRUMENT_VA(this);
179 
180   if (TargetSP target_sp = GetSP()) {
181     SBPlatform platform;
182     platform.m_opaque_sp = target_sp->GetPlatform();
183     return platform;
184   }
185   return SBPlatform();
186 }
187 
GetDebugger() const188 SBDebugger SBTarget::GetDebugger() const {
189   LLDB_INSTRUMENT_VA(this);
190 
191   SBDebugger debugger;
192   if (TargetSP target_sp = GetSP())
193     debugger.reset(target_sp->GetDebugger().shared_from_this());
194   return debugger;
195 }
196 
GetStatistics()197 SBStructuredData SBTarget::GetStatistics() {
198   LLDB_INSTRUMENT_VA(this);
199   SBStatisticsOptions options;
200   return GetStatistics(options);
201 }
202 
GetStatistics(SBStatisticsOptions options)203 SBStructuredData SBTarget::GetStatistics(SBStatisticsOptions options) {
204   LLDB_INSTRUMENT_VA(this);
205 
206   SBStructuredData data;
207   if (TargetSP target_sp = GetSP()) {
208     std::string json_str =
209         llvm::formatv("{0:2}", DebuggerStats::ReportStatistics(
210                                    target_sp->GetDebugger(), target_sp.get(),
211                                    options.ref()))
212             .str();
213     data.m_impl_up->SetObjectSP(StructuredData::ParseJSON(json_str));
214     return data;
215   }
216   return data;
217 }
218 
ResetStatistics()219 void SBTarget::ResetStatistics() {
220   LLDB_INSTRUMENT_VA(this);
221 
222   if (TargetSP target_sp = GetSP())
223     DebuggerStats::ResetStatistics(target_sp->GetDebugger(), target_sp.get());
224 }
225 
SetCollectingStats(bool v)226 void SBTarget::SetCollectingStats(bool v) {
227   LLDB_INSTRUMENT_VA(this, v);
228 
229   if (TargetSP target_sp = GetSP())
230     DebuggerStats::SetCollectingStats(v);
231 }
232 
GetCollectingStats()233 bool SBTarget::GetCollectingStats() {
234   LLDB_INSTRUMENT_VA(this);
235 
236   if (TargetSP target_sp = GetSP())
237     return DebuggerStats::GetCollectingStats();
238   return false;
239 }
240 
LoadCore(const char * core_file)241 SBProcess SBTarget::LoadCore(const char *core_file) {
242   LLDB_INSTRUMENT_VA(this, core_file);
243 
244   lldb::SBError error; // Ignored
245   return LoadCore(core_file, error);
246 }
247 
LoadCore(const char * core_file,lldb::SBError & error)248 SBProcess SBTarget::LoadCore(const char *core_file, lldb::SBError &error) {
249   LLDB_INSTRUMENT_VA(this, core_file, error);
250 
251   SBProcess sb_process;
252   if (TargetSP target_sp = GetSP()) {
253     FileSpec filespec(core_file);
254     FileSystem::Instance().Resolve(filespec);
255     ProcessSP process_sp(target_sp->CreateProcess(
256         target_sp->GetDebugger().GetListener(), "", &filespec, false));
257     if (process_sp) {
258       error.SetError(process_sp->LoadCore());
259       if (error.Success())
260         sb_process.SetSP(process_sp);
261     } else {
262       error.SetErrorString("Failed to create the process");
263     }
264   } else {
265     error.SetErrorString("SBTarget is invalid");
266   }
267   return sb_process;
268 }
269 
LaunchSimple(char const ** argv,char const ** envp,const char * working_directory)270 SBProcess SBTarget::LaunchSimple(char const **argv, char const **envp,
271                                  const char *working_directory) {
272   LLDB_INSTRUMENT_VA(this, argv, envp, working_directory);
273 
274   TargetSP target_sp = GetSP();
275   if (!target_sp)
276     return SBProcess();
277 
278   SBLaunchInfo launch_info = GetLaunchInfo();
279 
280   if (Module *exe_module = target_sp->GetExecutableModulePointer())
281     launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(),
282                                   /*add_as_first_arg*/ true);
283   if (argv)
284     launch_info.SetArguments(argv, /*append*/ true);
285   if (envp)
286     launch_info.SetEnvironmentEntries(envp, /*append*/ false);
287   if (working_directory)
288     launch_info.SetWorkingDirectory(working_directory);
289 
290   SBError error;
291   return Launch(launch_info, error);
292 }
293 
Install()294 SBError SBTarget::Install() {
295   LLDB_INSTRUMENT_VA(this);
296 
297   SBError sb_error;
298   if (TargetSP target_sp = GetSP()) {
299     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
300     sb_error.ref() = target_sp->Install(nullptr);
301   }
302   return sb_error;
303 }
304 
Launch(SBListener & listener,char const ** argv,char const ** envp,const char * stdin_path,const char * stdout_path,const char * stderr_path,const char * working_directory,uint32_t launch_flags,bool stop_at_entry,lldb::SBError & error)305 SBProcess SBTarget::Launch(SBListener &listener, char const **argv,
306                            char const **envp, const char *stdin_path,
307                            const char *stdout_path, const char *stderr_path,
308                            const char *working_directory,
309                            uint32_t launch_flags, // See LaunchFlags
310                            bool stop_at_entry, lldb::SBError &error) {
311   LLDB_INSTRUMENT_VA(this, listener, argv, envp, stdin_path, stdout_path,
312                      stderr_path, working_directory, launch_flags,
313                      stop_at_entry, error);
314 
315   SBProcess sb_process;
316   ProcessSP process_sp;
317   if (TargetSP target_sp = GetSP()) {
318     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
319 
320     if (stop_at_entry)
321       launch_flags |= eLaunchFlagStopAtEntry;
322 
323     if (getenv("LLDB_LAUNCH_FLAG_DISABLE_ASLR"))
324       launch_flags |= eLaunchFlagDisableASLR;
325 
326     StateType state = eStateInvalid;
327     process_sp = target_sp->GetProcessSP();
328     if (process_sp) {
329       state = process_sp->GetState();
330 
331       if (process_sp->IsAlive() && state != eStateConnected) {
332         if (state == eStateAttaching)
333           error.SetErrorString("process attach is in progress");
334         else
335           error.SetErrorString("a process is already being debugged");
336         return sb_process;
337       }
338     }
339 
340     if (state == eStateConnected) {
341       // If we are already connected, then we have already specified the
342       // listener, so if a valid listener is supplied, we need to error out to
343       // let the client know.
344       if (listener.IsValid()) {
345         error.SetErrorString("process is connected and already has a listener, "
346                              "pass empty listener");
347         return sb_process;
348       }
349     }
350 
351     if (getenv("LLDB_LAUNCH_FLAG_DISABLE_STDIO"))
352       launch_flags |= eLaunchFlagDisableSTDIO;
353 
354     ProcessLaunchInfo launch_info(FileSpec(stdin_path), FileSpec(stdout_path),
355                                   FileSpec(stderr_path),
356                                   FileSpec(working_directory), launch_flags);
357 
358     Module *exe_module = target_sp->GetExecutableModulePointer();
359     if (exe_module)
360       launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true);
361     if (argv) {
362       launch_info.GetArguments().AppendArguments(argv);
363     } else {
364       auto default_launch_info = target_sp->GetProcessLaunchInfo();
365       launch_info.GetArguments().AppendArguments(
366           default_launch_info.GetArguments());
367     }
368     if (envp) {
369       launch_info.GetEnvironment() = Environment(envp);
370     } else {
371       auto default_launch_info = target_sp->GetProcessLaunchInfo();
372       launch_info.GetEnvironment() = default_launch_info.GetEnvironment();
373     }
374 
375     if (listener.IsValid())
376       launch_info.SetListener(listener.GetSP());
377 
378     error.SetError(target_sp->Launch(launch_info, nullptr));
379 
380     sb_process.SetSP(target_sp->GetProcessSP());
381   } else {
382     error.SetErrorString("SBTarget is invalid");
383   }
384 
385   return sb_process;
386 }
387 
Launch(SBLaunchInfo & sb_launch_info,SBError & error)388 SBProcess SBTarget::Launch(SBLaunchInfo &sb_launch_info, SBError &error) {
389   LLDB_INSTRUMENT_VA(this, sb_launch_info, error);
390 
391   SBProcess sb_process;
392   if (TargetSP target_sp = GetSP()) {
393     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
394     StateType state = eStateInvalid;
395     {
396       ProcessSP process_sp = target_sp->GetProcessSP();
397       if (process_sp) {
398         state = process_sp->GetState();
399 
400         if (process_sp->IsAlive() && state != eStateConnected) {
401           if (state == eStateAttaching)
402             error.SetErrorString("process attach is in progress");
403           else
404             error.SetErrorString("a process is already being debugged");
405           return sb_process;
406         }
407       }
408     }
409 
410     lldb_private::ProcessLaunchInfo launch_info = sb_launch_info.ref();
411 
412     if (!launch_info.GetExecutableFile()) {
413       Module *exe_module = target_sp->GetExecutableModulePointer();
414       if (exe_module)
415         launch_info.SetExecutableFile(exe_module->GetPlatformFileSpec(), true);
416     }
417 
418     const ArchSpec &arch_spec = target_sp->GetArchitecture();
419     if (arch_spec.IsValid())
420       launch_info.GetArchitecture() = arch_spec;
421 
422     error.SetError(target_sp->Launch(launch_info, nullptr));
423     sb_launch_info.set_ref(launch_info);
424     sb_process.SetSP(target_sp->GetProcessSP());
425   } else {
426     error.SetErrorString("SBTarget is invalid");
427   }
428 
429   return sb_process;
430 }
431 
Attach(SBAttachInfo & sb_attach_info,SBError & error)432 lldb::SBProcess SBTarget::Attach(SBAttachInfo &sb_attach_info, SBError &error) {
433   LLDB_INSTRUMENT_VA(this, sb_attach_info, error);
434 
435   SBProcess sb_process;
436   if (TargetSP target_sp = GetSP()) {
437     ProcessAttachInfo &attach_info = sb_attach_info.ref();
438     if (attach_info.ProcessIDIsValid() && !attach_info.UserIDIsValid() &&
439         !attach_info.IsScriptedProcess()) {
440       PlatformSP platform_sp = target_sp->GetPlatform();
441       // See if we can pre-verify if a process exists or not
442       if (platform_sp && platform_sp->IsConnected()) {
443         lldb::pid_t attach_pid = attach_info.GetProcessID();
444         ProcessInstanceInfo instance_info;
445         if (platform_sp->GetProcessInfo(attach_pid, instance_info)) {
446           attach_info.SetUserID(instance_info.GetEffectiveUserID());
447         } else {
448           error.ref() = Status::FromErrorStringWithFormat(
449               "no process found with process ID %" PRIu64, attach_pid);
450           return sb_process;
451         }
452       }
453     }
454     error.SetError(AttachToProcess(attach_info, *target_sp));
455     if (error.Success())
456       sb_process.SetSP(target_sp->GetProcessSP());
457   } else {
458     error.SetErrorString("SBTarget is invalid");
459   }
460 
461   return sb_process;
462 }
463 
AttachToProcessWithID(SBListener & listener,lldb::pid_t pid,SBError & error)464 lldb::SBProcess SBTarget::AttachToProcessWithID(
465     SBListener &listener,
466     lldb::pid_t pid, // The process ID to attach to
467     SBError &error   // An error explaining what went wrong if attach fails
468 ) {
469   LLDB_INSTRUMENT_VA(this, listener, pid, error);
470 
471   SBProcess sb_process;
472   if (TargetSP target_sp = GetSP()) {
473     ProcessAttachInfo attach_info;
474     attach_info.SetProcessID(pid);
475     if (listener.IsValid())
476       attach_info.SetListener(listener.GetSP());
477 
478     ProcessInstanceInfo instance_info;
479     if (target_sp->GetPlatform()->GetProcessInfo(pid, instance_info))
480       attach_info.SetUserID(instance_info.GetEffectiveUserID());
481 
482     error.SetError(AttachToProcess(attach_info, *target_sp));
483     if (error.Success())
484       sb_process.SetSP(target_sp->GetProcessSP());
485   } else
486     error.SetErrorString("SBTarget is invalid");
487 
488   return sb_process;
489 }
490 
AttachToProcessWithName(SBListener & listener,const char * name,bool wait_for,SBError & error)491 lldb::SBProcess SBTarget::AttachToProcessWithName(
492     SBListener &listener,
493     const char *name, // basename of process to attach to
494     bool wait_for, // if true wait for a new instance of "name" to be launched
495     SBError &error // An error explaining what went wrong if attach fails
496 ) {
497   LLDB_INSTRUMENT_VA(this, listener, name, wait_for, error);
498 
499   SBProcess sb_process;
500 
501   if (!name) {
502     error.SetErrorString("invalid name");
503     return sb_process;
504   }
505 
506   if (TargetSP target_sp = GetSP()) {
507     ProcessAttachInfo attach_info;
508     attach_info.GetExecutableFile().SetFile(name, FileSpec::Style::native);
509     attach_info.SetWaitForLaunch(wait_for);
510     if (listener.IsValid())
511       attach_info.SetListener(listener.GetSP());
512 
513     error.SetError(AttachToProcess(attach_info, *target_sp));
514     if (error.Success())
515       sb_process.SetSP(target_sp->GetProcessSP());
516   } else {
517     error.SetErrorString("SBTarget is invalid");
518   }
519 
520   return sb_process;
521 }
522 
ConnectRemote(SBListener & listener,const char * url,const char * plugin_name,SBError & error)523 lldb::SBProcess SBTarget::ConnectRemote(SBListener &listener, const char *url,
524                                         const char *plugin_name,
525                                         SBError &error) {
526   LLDB_INSTRUMENT_VA(this, listener, url, plugin_name, error);
527 
528   SBProcess sb_process;
529   ProcessSP process_sp;
530   if (TargetSP target_sp = GetSP()) {
531     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
532     if (listener.IsValid())
533       process_sp =
534           target_sp->CreateProcess(listener.m_opaque_sp, plugin_name, nullptr,
535                                    true);
536     else
537       process_sp = target_sp->CreateProcess(
538           target_sp->GetDebugger().GetListener(), plugin_name, nullptr, true);
539 
540     if (process_sp) {
541       sb_process.SetSP(process_sp);
542       error.SetError(process_sp->ConnectRemote(url));
543     } else {
544       error.SetErrorString("unable to create lldb_private::Process");
545     }
546   } else {
547     error.SetErrorString("SBTarget is invalid");
548   }
549 
550   return sb_process;
551 }
552 
GetExecutable()553 SBFileSpec SBTarget::GetExecutable() {
554   LLDB_INSTRUMENT_VA(this);
555 
556   SBFileSpec exe_file_spec;
557   if (TargetSP target_sp = GetSP()) {
558     Module *exe_module = target_sp->GetExecutableModulePointer();
559     if (exe_module)
560       exe_file_spec.SetFileSpec(exe_module->GetFileSpec());
561   }
562 
563   return exe_file_spec;
564 }
565 
operator ==(const SBTarget & rhs) const566 bool SBTarget::operator==(const SBTarget &rhs) const {
567   LLDB_INSTRUMENT_VA(this, rhs);
568 
569   return m_opaque_sp.get() == rhs.m_opaque_sp.get();
570 }
571 
operator !=(const SBTarget & rhs) const572 bool SBTarget::operator!=(const SBTarget &rhs) const {
573   LLDB_INSTRUMENT_VA(this, rhs);
574 
575   return m_opaque_sp.get() != rhs.m_opaque_sp.get();
576 }
577 
GetSP() const578 lldb::TargetSP SBTarget::GetSP() const { return m_opaque_sp; }
579 
SetSP(const lldb::TargetSP & target_sp)580 void SBTarget::SetSP(const lldb::TargetSP &target_sp) {
581   m_opaque_sp = target_sp;
582 }
583 
ResolveLoadAddress(lldb::addr_t vm_addr)584 lldb::SBAddress SBTarget::ResolveLoadAddress(lldb::addr_t vm_addr) {
585   LLDB_INSTRUMENT_VA(this, vm_addr);
586 
587   lldb::SBAddress sb_addr;
588   Address &addr = sb_addr.ref();
589   if (TargetSP target_sp = GetSP()) {
590     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
591     if (target_sp->ResolveLoadAddress(vm_addr, addr))
592       return sb_addr;
593   }
594 
595   // We have a load address that isn't in a section, just return an address
596   // with the offset filled in (the address) and the section set to NULL
597   addr.SetRawAddress(vm_addr);
598   return sb_addr;
599 }
600 
ResolveFileAddress(lldb::addr_t file_addr)601 lldb::SBAddress SBTarget::ResolveFileAddress(lldb::addr_t file_addr) {
602   LLDB_INSTRUMENT_VA(this, file_addr);
603 
604   lldb::SBAddress sb_addr;
605   Address &addr = sb_addr.ref();
606   if (TargetSP target_sp = GetSP()) {
607     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
608     if (target_sp->ResolveFileAddress(file_addr, addr))
609       return sb_addr;
610   }
611 
612   addr.SetRawAddress(file_addr);
613   return sb_addr;
614 }
615 
ResolvePastLoadAddress(uint32_t stop_id,lldb::addr_t vm_addr)616 lldb::SBAddress SBTarget::ResolvePastLoadAddress(uint32_t stop_id,
617                                                  lldb::addr_t vm_addr) {
618   LLDB_INSTRUMENT_VA(this, stop_id, vm_addr);
619 
620   lldb::SBAddress sb_addr;
621   Address &addr = sb_addr.ref();
622   if (TargetSP target_sp = GetSP()) {
623     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
624     if (target_sp->ResolveLoadAddress(vm_addr, addr))
625       return sb_addr;
626   }
627 
628   // We have a load address that isn't in a section, just return an address
629   // with the offset filled in (the address) and the section set to NULL
630   addr.SetRawAddress(vm_addr);
631   return sb_addr;
632 }
633 
634 SBSymbolContext
ResolveSymbolContextForAddress(const SBAddress & addr,uint32_t resolve_scope)635 SBTarget::ResolveSymbolContextForAddress(const SBAddress &addr,
636                                          uint32_t resolve_scope) {
637   LLDB_INSTRUMENT_VA(this, addr, resolve_scope);
638 
639   SBSymbolContext sb_sc;
640   SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope);
641   if (addr.IsValid()) {
642     if (TargetSP target_sp = GetSP()) {
643       lldb_private::SymbolContext &sc = sb_sc.ref();
644       sc.target_sp = target_sp;
645       target_sp->GetImages().ResolveSymbolContextForAddress(addr.ref(), scope,
646                                                             sc);
647     }
648   }
649   return sb_sc;
650 }
651 
ReadMemory(const SBAddress addr,void * buf,size_t size,lldb::SBError & error)652 size_t SBTarget::ReadMemory(const SBAddress addr, void *buf, size_t size,
653                             lldb::SBError &error) {
654   LLDB_INSTRUMENT_VA(this, addr, buf, size, error);
655 
656   size_t bytes_read = 0;
657   if (TargetSP target_sp = GetSP()) {
658     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
659     bytes_read =
660         target_sp->ReadMemory(addr.ref(), buf, size, error.ref(), true);
661   } else {
662     error.SetErrorString("invalid target");
663   }
664 
665   return bytes_read;
666 }
667 
BreakpointCreateByLocation(const char * file,uint32_t line)668 SBBreakpoint SBTarget::BreakpointCreateByLocation(const char *file,
669                                                   uint32_t line) {
670   LLDB_INSTRUMENT_VA(this, file, line);
671 
672   return SBBreakpoint(
673       BreakpointCreateByLocation(SBFileSpec(file, false), line));
674 }
675 
676 SBBreakpoint
BreakpointCreateByLocation(const SBFileSpec & sb_file_spec,uint32_t line)677 SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec,
678                                      uint32_t line) {
679   LLDB_INSTRUMENT_VA(this, sb_file_spec, line);
680 
681   return BreakpointCreateByLocation(sb_file_spec, line, 0);
682 }
683 
684 SBBreakpoint
BreakpointCreateByLocation(const SBFileSpec & sb_file_spec,uint32_t line,lldb::addr_t offset)685 SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec,
686                                      uint32_t line, lldb::addr_t offset) {
687   LLDB_INSTRUMENT_VA(this, sb_file_spec, line, offset);
688 
689   SBFileSpecList empty_list;
690   return BreakpointCreateByLocation(sb_file_spec, line, offset, empty_list);
691 }
692 
693 SBBreakpoint
BreakpointCreateByLocation(const SBFileSpec & sb_file_spec,uint32_t line,lldb::addr_t offset,SBFileSpecList & sb_module_list)694 SBTarget::BreakpointCreateByLocation(const SBFileSpec &sb_file_spec,
695                                      uint32_t line, lldb::addr_t offset,
696                                      SBFileSpecList &sb_module_list) {
697   LLDB_INSTRUMENT_VA(this, sb_file_spec, line, offset, sb_module_list);
698 
699   return BreakpointCreateByLocation(sb_file_spec, line, 0, offset,
700                                     sb_module_list);
701 }
702 
BreakpointCreateByLocation(const SBFileSpec & sb_file_spec,uint32_t line,uint32_t column,lldb::addr_t offset,SBFileSpecList & sb_module_list)703 SBBreakpoint SBTarget::BreakpointCreateByLocation(
704     const SBFileSpec &sb_file_spec, uint32_t line, uint32_t column,
705     lldb::addr_t offset, SBFileSpecList &sb_module_list) {
706   LLDB_INSTRUMENT_VA(this, sb_file_spec, line, column, offset, sb_module_list);
707 
708   SBBreakpoint sb_bp;
709   if (TargetSP target_sp = GetSP(); target_sp && line != 0) {
710     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
711 
712     const LazyBool check_inlines = eLazyBoolCalculate;
713     const LazyBool skip_prologue = eLazyBoolCalculate;
714     const bool internal = false;
715     const bool hardware = false;
716     const LazyBool move_to_nearest_code = eLazyBoolCalculate;
717     const FileSpecList *module_list = nullptr;
718     if (sb_module_list.GetSize() > 0) {
719       module_list = sb_module_list.get();
720     }
721     sb_bp = target_sp->CreateBreakpoint(
722         module_list, *sb_file_spec, line, column, offset, check_inlines,
723         skip_prologue, internal, hardware, move_to_nearest_code);
724   }
725 
726   return sb_bp;
727 }
728 
BreakpointCreateByLocation(const SBFileSpec & sb_file_spec,uint32_t line,uint32_t column,lldb::addr_t offset,SBFileSpecList & sb_module_list,bool move_to_nearest_code)729 SBBreakpoint SBTarget::BreakpointCreateByLocation(
730     const SBFileSpec &sb_file_spec, uint32_t line, uint32_t column,
731     lldb::addr_t offset, SBFileSpecList &sb_module_list,
732     bool move_to_nearest_code) {
733   LLDB_INSTRUMENT_VA(this, sb_file_spec, line, column, offset, sb_module_list,
734                      move_to_nearest_code);
735 
736   SBBreakpoint sb_bp;
737   if (TargetSP target_sp = GetSP(); target_sp && line != 0) {
738     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
739 
740     const LazyBool check_inlines = eLazyBoolCalculate;
741     const LazyBool skip_prologue = eLazyBoolCalculate;
742     const bool internal = false;
743     const bool hardware = false;
744     const FileSpecList *module_list = nullptr;
745     if (sb_module_list.GetSize() > 0) {
746       module_list = sb_module_list.get();
747     }
748     sb_bp = target_sp->CreateBreakpoint(
749         module_list, *sb_file_spec, line, column, offset, check_inlines,
750         skip_prologue, internal, hardware,
751         move_to_nearest_code ? eLazyBoolYes : eLazyBoolNo);
752   }
753 
754   return sb_bp;
755 }
756 
BreakpointCreateByName(const char * symbol_name,const char * module_name)757 SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name,
758                                               const char *module_name) {
759   LLDB_INSTRUMENT_VA(this, symbol_name, module_name);
760 
761   SBBreakpoint sb_bp;
762   if (TargetSP target_sp = GetSP()) {
763     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
764 
765     const bool internal = false;
766     const bool hardware = false;
767     const LazyBool skip_prologue = eLazyBoolCalculate;
768     const lldb::addr_t offset = 0;
769     if (module_name && module_name[0]) {
770       FileSpecList module_spec_list;
771       module_spec_list.Append(FileSpec(module_name));
772       sb_bp = target_sp->CreateBreakpoint(
773           &module_spec_list, nullptr, symbol_name, eFunctionNameTypeAuto,
774           eLanguageTypeUnknown, offset, skip_prologue, internal, hardware);
775     } else {
776       sb_bp = target_sp->CreateBreakpoint(
777           nullptr, nullptr, symbol_name, eFunctionNameTypeAuto,
778           eLanguageTypeUnknown, offset, skip_prologue, internal, hardware);
779     }
780   }
781 
782   return sb_bp;
783 }
784 
785 lldb::SBBreakpoint
BreakpointCreateByName(const char * symbol_name,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)786 SBTarget::BreakpointCreateByName(const char *symbol_name,
787                                  const SBFileSpecList &module_list,
788                                  const SBFileSpecList &comp_unit_list) {
789   LLDB_INSTRUMENT_VA(this, symbol_name, module_list, comp_unit_list);
790 
791   lldb::FunctionNameType name_type_mask = eFunctionNameTypeAuto;
792   return BreakpointCreateByName(symbol_name, name_type_mask,
793                                 eLanguageTypeUnknown, module_list,
794                                 comp_unit_list);
795 }
796 
BreakpointCreateByName(const char * symbol_name,uint32_t name_type_mask,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)797 lldb::SBBreakpoint SBTarget::BreakpointCreateByName(
798     const char *symbol_name, uint32_t name_type_mask,
799     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
800   LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, module_list,
801                      comp_unit_list);
802 
803   return BreakpointCreateByName(symbol_name, name_type_mask,
804                                 eLanguageTypeUnknown, module_list,
805                                 comp_unit_list);
806 }
807 
BreakpointCreateByName(const char * symbol_name,uint32_t name_type_mask,LanguageType symbol_language,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)808 lldb::SBBreakpoint SBTarget::BreakpointCreateByName(
809     const char *symbol_name, uint32_t name_type_mask,
810     LanguageType symbol_language, const SBFileSpecList &module_list,
811     const SBFileSpecList &comp_unit_list) {
812   LLDB_INSTRUMENT_VA(this, symbol_name, name_type_mask, symbol_language,
813                      module_list, comp_unit_list);
814 
815   SBBreakpoint sb_bp;
816   if (TargetSP target_sp = GetSP();
817       target_sp && symbol_name && symbol_name[0]) {
818     const bool internal = false;
819     const bool hardware = false;
820     const LazyBool skip_prologue = eLazyBoolCalculate;
821     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
822     FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask);
823     sb_bp = target_sp->CreateBreakpoint(module_list.get(), comp_unit_list.get(),
824                                         symbol_name, mask, symbol_language, 0,
825                                         skip_prologue, internal, hardware);
826   }
827 
828   return sb_bp;
829 }
830 
BreakpointCreateByNames(const char * symbol_names[],uint32_t num_names,uint32_t name_type_mask,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)831 lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(
832     const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,
833     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
834   LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask, module_list,
835                      comp_unit_list);
836 
837   return BreakpointCreateByNames(symbol_names, num_names, name_type_mask,
838                                  eLanguageTypeUnknown, module_list,
839                                  comp_unit_list);
840 }
841 
BreakpointCreateByNames(const char * symbol_names[],uint32_t num_names,uint32_t name_type_mask,LanguageType symbol_language,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)842 lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(
843     const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,
844     LanguageType symbol_language, const SBFileSpecList &module_list,
845     const SBFileSpecList &comp_unit_list) {
846   LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask,
847                      symbol_language, module_list, comp_unit_list);
848 
849   return BreakpointCreateByNames(symbol_names, num_names, name_type_mask,
850                                  eLanguageTypeUnknown, 0, module_list,
851                                  comp_unit_list);
852 }
853 
BreakpointCreateByNames(const char * symbol_names[],uint32_t num_names,uint32_t name_type_mask,LanguageType symbol_language,lldb::addr_t offset,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)854 lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(
855     const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,
856     LanguageType symbol_language, lldb::addr_t offset,
857     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
858   LLDB_INSTRUMENT_VA(this, symbol_names, num_names, name_type_mask,
859                      symbol_language, offset, module_list, comp_unit_list);
860 
861   SBBreakpoint sb_bp;
862   if (TargetSP target_sp = GetSP(); target_sp && num_names > 0) {
863     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
864     const bool internal = false;
865     const bool hardware = false;
866     FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask);
867     const LazyBool skip_prologue = eLazyBoolCalculate;
868     sb_bp = target_sp->CreateBreakpoint(
869         module_list.get(), comp_unit_list.get(), symbol_names, num_names, mask,
870         symbol_language, offset, skip_prologue, internal, hardware);
871   }
872 
873   return sb_bp;
874 }
875 
BreakpointCreateByRegex(const char * symbol_name_regex,const char * module_name)876 SBBreakpoint SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex,
877                                                const char *module_name) {
878   LLDB_INSTRUMENT_VA(this, symbol_name_regex, module_name);
879 
880   SBFileSpecList module_spec_list;
881   SBFileSpecList comp_unit_list;
882   if (module_name && module_name[0]) {
883     module_spec_list.Append(FileSpec(module_name));
884   }
885   return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown,
886                                  module_spec_list, comp_unit_list);
887 }
888 
889 lldb::SBBreakpoint
BreakpointCreateByRegex(const char * symbol_name_regex,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)890 SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex,
891                                   const SBFileSpecList &module_list,
892                                   const SBFileSpecList &comp_unit_list) {
893   LLDB_INSTRUMENT_VA(this, symbol_name_regex, module_list, comp_unit_list);
894 
895   return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown,
896                                  module_list, comp_unit_list);
897 }
898 
BreakpointCreateByRegex(const char * symbol_name_regex,LanguageType symbol_language,const SBFileSpecList & module_list,const SBFileSpecList & comp_unit_list)899 lldb::SBBreakpoint SBTarget::BreakpointCreateByRegex(
900     const char *symbol_name_regex, LanguageType symbol_language,
901     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
902   LLDB_INSTRUMENT_VA(this, symbol_name_regex, symbol_language, module_list,
903                      comp_unit_list);
904 
905   SBBreakpoint sb_bp;
906   if (TargetSP target_sp = GetSP();
907       target_sp && symbol_name_regex && symbol_name_regex[0]) {
908     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
909     RegularExpression regexp((llvm::StringRef(symbol_name_regex)));
910     const bool internal = false;
911     const bool hardware = false;
912     const LazyBool skip_prologue = eLazyBoolCalculate;
913 
914     sb_bp = target_sp->CreateFuncRegexBreakpoint(
915         module_list.get(), comp_unit_list.get(), std::move(regexp),
916         symbol_language, skip_prologue, internal, hardware);
917   }
918 
919   return sb_bp;
920 }
921 
BreakpointCreateByAddress(addr_t address)922 SBBreakpoint SBTarget::BreakpointCreateByAddress(addr_t address) {
923   LLDB_INSTRUMENT_VA(this, address);
924 
925   SBBreakpoint sb_bp;
926   if (TargetSP target_sp = GetSP()) {
927     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
928     const bool hardware = false;
929     sb_bp = target_sp->CreateBreakpoint(address, false, hardware);
930   }
931 
932   return sb_bp;
933 }
934 
BreakpointCreateBySBAddress(SBAddress & sb_address)935 SBBreakpoint SBTarget::BreakpointCreateBySBAddress(SBAddress &sb_address) {
936   LLDB_INSTRUMENT_VA(this, sb_address);
937 
938   SBBreakpoint sb_bp;
939   if (!sb_address.IsValid()) {
940     return sb_bp;
941   }
942 
943   if (TargetSP target_sp = GetSP()) {
944     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
945     const bool hardware = false;
946     sb_bp = target_sp->CreateBreakpoint(sb_address.ref(), false, hardware);
947   }
948 
949   return sb_bp;
950 }
951 
952 lldb::SBBreakpoint
BreakpointCreateBySourceRegex(const char * source_regex,const lldb::SBFileSpec & source_file,const char * module_name)953 SBTarget::BreakpointCreateBySourceRegex(const char *source_regex,
954                                         const lldb::SBFileSpec &source_file,
955                                         const char *module_name) {
956   LLDB_INSTRUMENT_VA(this, source_regex, source_file, module_name);
957 
958   SBFileSpecList module_spec_list;
959 
960   if (module_name && module_name[0]) {
961     module_spec_list.Append(FileSpec(module_name));
962   }
963 
964   SBFileSpecList source_file_list;
965   if (source_file.IsValid()) {
966     source_file_list.Append(source_file);
967   }
968 
969   return BreakpointCreateBySourceRegex(source_regex, module_spec_list,
970                                        source_file_list);
971 }
972 
BreakpointCreateBySourceRegex(const char * source_regex,const SBFileSpecList & module_list,const lldb::SBFileSpecList & source_file_list)973 lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(
974     const char *source_regex, const SBFileSpecList &module_list,
975     const lldb::SBFileSpecList &source_file_list) {
976   LLDB_INSTRUMENT_VA(this, source_regex, module_list, source_file_list);
977 
978   return BreakpointCreateBySourceRegex(source_regex, module_list,
979                                        source_file_list, SBStringList());
980 }
981 
BreakpointCreateBySourceRegex(const char * source_regex,const SBFileSpecList & module_list,const lldb::SBFileSpecList & source_file_list,const SBStringList & func_names)982 lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(
983     const char *source_regex, const SBFileSpecList &module_list,
984     const lldb::SBFileSpecList &source_file_list,
985     const SBStringList &func_names) {
986   LLDB_INSTRUMENT_VA(this, source_regex, module_list, source_file_list,
987                      func_names);
988 
989   SBBreakpoint sb_bp;
990   if (TargetSP target_sp = GetSP();
991       target_sp && source_regex && source_regex[0]) {
992     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
993     const bool hardware = false;
994     const LazyBool move_to_nearest_code = eLazyBoolCalculate;
995     RegularExpression regexp((llvm::StringRef(source_regex)));
996     std::unordered_set<std::string> func_names_set;
997     for (size_t i = 0; i < func_names.GetSize(); i++) {
998       func_names_set.insert(func_names.GetStringAtIndex(i));
999     }
1000 
1001     sb_bp = target_sp->CreateSourceRegexBreakpoint(
1002         module_list.get(), source_file_list.get(), func_names_set,
1003         std::move(regexp), false, hardware, move_to_nearest_code);
1004   }
1005 
1006   return sb_bp;
1007 }
1008 
1009 lldb::SBBreakpoint
BreakpointCreateForException(lldb::LanguageType language,bool catch_bp,bool throw_bp)1010 SBTarget::BreakpointCreateForException(lldb::LanguageType language,
1011                                        bool catch_bp, bool throw_bp) {
1012   LLDB_INSTRUMENT_VA(this, language, catch_bp, throw_bp);
1013 
1014   SBBreakpoint sb_bp;
1015   if (TargetSP target_sp = GetSP()) {
1016     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1017     const bool hardware = false;
1018     sb_bp = target_sp->CreateExceptionBreakpoint(language, catch_bp, throw_bp,
1019                                                   hardware);
1020   }
1021 
1022   return sb_bp;
1023 }
1024 
BreakpointCreateFromScript(const char * class_name,SBStructuredData & extra_args,const SBFileSpecList & module_list,const SBFileSpecList & file_list,bool request_hardware)1025 lldb::SBBreakpoint SBTarget::BreakpointCreateFromScript(
1026     const char *class_name, SBStructuredData &extra_args,
1027     const SBFileSpecList &module_list, const SBFileSpecList &file_list,
1028     bool request_hardware) {
1029   LLDB_INSTRUMENT_VA(this, class_name, extra_args, module_list, file_list,
1030                      request_hardware);
1031 
1032   SBBreakpoint sb_bp;
1033   if (TargetSP target_sp = GetSP()) {
1034     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1035     Status error;
1036 
1037     StructuredData::ObjectSP obj_sp = extra_args.m_impl_up->GetObjectSP();
1038     sb_bp =
1039         target_sp->CreateScriptedBreakpoint(class_name,
1040                                             module_list.get(),
1041                                             file_list.get(),
1042                                             false, /* internal */
1043                                             request_hardware,
1044                                             obj_sp,
1045                                             &error);
1046   }
1047 
1048   return sb_bp;
1049 }
1050 
GetNumBreakpoints() const1051 uint32_t SBTarget::GetNumBreakpoints() const {
1052   LLDB_INSTRUMENT_VA(this);
1053 
1054   if (TargetSP target_sp = GetSP()) {
1055     // The breakpoint list is thread safe, no need to lock
1056     return target_sp->GetBreakpointList().GetSize();
1057   }
1058   return 0;
1059 }
1060 
GetBreakpointAtIndex(uint32_t idx) const1061 SBBreakpoint SBTarget::GetBreakpointAtIndex(uint32_t idx) const {
1062   LLDB_INSTRUMENT_VA(this, idx);
1063 
1064   SBBreakpoint sb_breakpoint;
1065   if (TargetSP target_sp = GetSP()) {
1066     // The breakpoint list is thread safe, no need to lock
1067     sb_breakpoint = target_sp->GetBreakpointList().GetBreakpointAtIndex(idx);
1068   }
1069   return sb_breakpoint;
1070 }
1071 
BreakpointDelete(break_id_t bp_id)1072 bool SBTarget::BreakpointDelete(break_id_t bp_id) {
1073   LLDB_INSTRUMENT_VA(this, bp_id);
1074 
1075   bool result = false;
1076   if (TargetSP target_sp = GetSP()) {
1077     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1078     result = target_sp->RemoveBreakpointByID(bp_id);
1079   }
1080 
1081   return result;
1082 }
1083 
FindBreakpointByID(break_id_t bp_id)1084 SBBreakpoint SBTarget::FindBreakpointByID(break_id_t bp_id) {
1085   LLDB_INSTRUMENT_VA(this, bp_id);
1086 
1087   SBBreakpoint sb_breakpoint;
1088   if (TargetSP target_sp = GetSP();
1089       target_sp && bp_id != LLDB_INVALID_BREAK_ID) {
1090     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1091     sb_breakpoint = target_sp->GetBreakpointByID(bp_id);
1092   }
1093 
1094   return sb_breakpoint;
1095 }
1096 
FindBreakpointsByName(const char * name,SBBreakpointList & bkpts)1097 bool SBTarget::FindBreakpointsByName(const char *name,
1098                                      SBBreakpointList &bkpts) {
1099   LLDB_INSTRUMENT_VA(this, name, bkpts);
1100 
1101   if (TargetSP target_sp = GetSP()) {
1102     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1103     llvm::Expected<std::vector<BreakpointSP>> expected_vector =
1104         target_sp->GetBreakpointList().FindBreakpointsByName(name);
1105     if (!expected_vector) {
1106       LLDB_LOG_ERROR(GetLog(LLDBLog::Breakpoints), expected_vector.takeError(),
1107                      "invalid breakpoint name: {0}");
1108       return false;
1109     }
1110     for (BreakpointSP bkpt_sp : *expected_vector) {
1111       bkpts.AppendByID(bkpt_sp->GetID());
1112     }
1113   }
1114   return true;
1115 }
1116 
GetBreakpointNames(SBStringList & names)1117 void SBTarget::GetBreakpointNames(SBStringList &names) {
1118   LLDB_INSTRUMENT_VA(this, names);
1119 
1120   names.Clear();
1121 
1122   if (TargetSP target_sp = GetSP()) {
1123     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1124 
1125     std::vector<std::string> name_vec;
1126     target_sp->GetBreakpointNames(name_vec);
1127     for (const auto &name : name_vec)
1128       names.AppendString(name.c_str());
1129   }
1130 }
1131 
DeleteBreakpointName(const char * name)1132 void SBTarget::DeleteBreakpointName(const char *name) {
1133   LLDB_INSTRUMENT_VA(this, name);
1134 
1135   if (TargetSP target_sp = GetSP()) {
1136     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1137     target_sp->DeleteBreakpointName(ConstString(name));
1138   }
1139 }
1140 
EnableAllBreakpoints()1141 bool SBTarget::EnableAllBreakpoints() {
1142   LLDB_INSTRUMENT_VA(this);
1143 
1144   if (TargetSP target_sp = GetSP()) {
1145     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1146     target_sp->EnableAllowedBreakpoints();
1147     return true;
1148   }
1149   return false;
1150 }
1151 
DisableAllBreakpoints()1152 bool SBTarget::DisableAllBreakpoints() {
1153   LLDB_INSTRUMENT_VA(this);
1154 
1155   if (TargetSP target_sp = GetSP()) {
1156     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1157     target_sp->DisableAllowedBreakpoints();
1158     return true;
1159   }
1160   return false;
1161 }
1162 
DeleteAllBreakpoints()1163 bool SBTarget::DeleteAllBreakpoints() {
1164   LLDB_INSTRUMENT_VA(this);
1165 
1166   if (TargetSP target_sp = GetSP()) {
1167     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1168     target_sp->RemoveAllowedBreakpoints();
1169     return true;
1170   }
1171   return false;
1172 }
1173 
BreakpointsCreateFromFile(SBFileSpec & source_file,SBBreakpointList & new_bps)1174 lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file,
1175                                                   SBBreakpointList &new_bps) {
1176   LLDB_INSTRUMENT_VA(this, source_file, new_bps);
1177 
1178   SBStringList empty_name_list;
1179   return BreakpointsCreateFromFile(source_file, empty_name_list, new_bps);
1180 }
1181 
BreakpointsCreateFromFile(SBFileSpec & source_file,SBStringList & matching_names,SBBreakpointList & new_bps)1182 lldb::SBError SBTarget::BreakpointsCreateFromFile(SBFileSpec &source_file,
1183                                                   SBStringList &matching_names,
1184                                                   SBBreakpointList &new_bps) {
1185   LLDB_INSTRUMENT_VA(this, source_file, matching_names, new_bps);
1186 
1187   SBError sberr;
1188   if (TargetSP target_sp = GetSP()) {
1189     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1190 
1191     BreakpointIDList bp_ids;
1192 
1193     std::vector<std::string> name_vector;
1194     size_t num_names = matching_names.GetSize();
1195     for (size_t i = 0; i < num_names; i++)
1196       name_vector.push_back(matching_names.GetStringAtIndex(i));
1197 
1198     sberr.ref() = target_sp->CreateBreakpointsFromFile(source_file.ref(),
1199                                                        name_vector, bp_ids);
1200     if (sberr.Fail())
1201       return sberr;
1202 
1203     size_t num_bkpts = bp_ids.GetSize();
1204     for (size_t i = 0; i < num_bkpts; i++) {
1205       BreakpointID bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1206       new_bps.AppendByID(bp_id.GetBreakpointID());
1207     }
1208   } else {
1209     sberr.SetErrorString(
1210         "BreakpointCreateFromFile called with invalid target.");
1211   }
1212   return sberr;
1213 }
1214 
BreakpointsWriteToFile(SBFileSpec & dest_file)1215 lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file) {
1216   LLDB_INSTRUMENT_VA(this, dest_file);
1217 
1218   SBError sberr;
1219   if (TargetSP target_sp = GetSP()) {
1220     SBBreakpointList bkpt_list(*this);
1221     return BreakpointsWriteToFile(dest_file, bkpt_list);
1222   }
1223   sberr.SetErrorString("BreakpointWriteToFile called with invalid target.");
1224   return sberr;
1225 }
1226 
BreakpointsWriteToFile(SBFileSpec & dest_file,SBBreakpointList & bkpt_list,bool append)1227 lldb::SBError SBTarget::BreakpointsWriteToFile(SBFileSpec &dest_file,
1228                                                SBBreakpointList &bkpt_list,
1229                                                bool append) {
1230   LLDB_INSTRUMENT_VA(this, dest_file, bkpt_list, append);
1231 
1232   SBError sberr;
1233   if (TargetSP target_sp = GetSP()) {
1234     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1235     BreakpointIDList bp_id_list;
1236     bkpt_list.CopyToBreakpointIDList(bp_id_list);
1237     sberr.ref() = target_sp->SerializeBreakpointsToFile(dest_file.ref(),
1238                                                         bp_id_list, append);
1239   } else {
1240     sberr.SetErrorString("BreakpointWriteToFile called with invalid target.");
1241   }
1242   return sberr;
1243 }
1244 
GetNumWatchpoints() const1245 uint32_t SBTarget::GetNumWatchpoints() const {
1246   LLDB_INSTRUMENT_VA(this);
1247 
1248   if (TargetSP target_sp = GetSP()) {
1249     // The watchpoint list is thread safe, no need to lock
1250     return target_sp->GetWatchpointList().GetSize();
1251   }
1252   return 0;
1253 }
1254 
GetWatchpointAtIndex(uint32_t idx) const1255 SBWatchpoint SBTarget::GetWatchpointAtIndex(uint32_t idx) const {
1256   LLDB_INSTRUMENT_VA(this, idx);
1257 
1258   SBWatchpoint sb_watchpoint;
1259   if (TargetSP target_sp = GetSP()) {
1260     // The watchpoint list is thread safe, no need to lock
1261     sb_watchpoint.SetSP(target_sp->GetWatchpointList().GetByIndex(idx));
1262   }
1263   return sb_watchpoint;
1264 }
1265 
DeleteWatchpoint(watch_id_t wp_id)1266 bool SBTarget::DeleteWatchpoint(watch_id_t wp_id) {
1267   LLDB_INSTRUMENT_VA(this, wp_id);
1268 
1269   bool result = false;
1270   if (TargetSP target_sp = GetSP()) {
1271     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1272     std::unique_lock<std::recursive_mutex> lock;
1273     target_sp->GetWatchpointList().GetListMutex(lock);
1274     result = target_sp->RemoveWatchpointByID(wp_id);
1275   }
1276 
1277   return result;
1278 }
1279 
FindWatchpointByID(lldb::watch_id_t wp_id)1280 SBWatchpoint SBTarget::FindWatchpointByID(lldb::watch_id_t wp_id) {
1281   LLDB_INSTRUMENT_VA(this, wp_id);
1282 
1283   SBWatchpoint sb_watchpoint;
1284   lldb::WatchpointSP watchpoint_sp;
1285   if (TargetSP target_sp = GetSP();
1286       target_sp && wp_id != LLDB_INVALID_WATCH_ID) {
1287     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1288     std::unique_lock<std::recursive_mutex> lock;
1289     target_sp->GetWatchpointList().GetListMutex(lock);
1290     watchpoint_sp = target_sp->GetWatchpointList().FindByID(wp_id);
1291     sb_watchpoint.SetSP(watchpoint_sp);
1292   }
1293 
1294   return sb_watchpoint;
1295 }
1296 
WatchAddress(lldb::addr_t addr,size_t size,bool read,bool modify,SBError & error)1297 lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size,
1298                                           bool read, bool modify,
1299                                           SBError &error) {
1300   LLDB_INSTRUMENT_VA(this, addr, size, read, write, error);
1301 
1302   SBWatchpointOptions options;
1303   options.SetWatchpointTypeRead(read);
1304   if (modify)
1305     options.SetWatchpointTypeWrite(eWatchpointWriteTypeOnModify);
1306   return WatchpointCreateByAddress(addr, size, options, error);
1307 }
1308 
1309 lldb::SBWatchpoint
WatchpointCreateByAddress(lldb::addr_t addr,size_t size,SBWatchpointOptions options,SBError & error)1310 SBTarget::WatchpointCreateByAddress(lldb::addr_t addr, size_t size,
1311                                     SBWatchpointOptions options,
1312                                     SBError &error) {
1313   LLDB_INSTRUMENT_VA(this, addr, size, options, error);
1314 
1315   SBWatchpoint sb_watchpoint;
1316   lldb::WatchpointSP watchpoint_sp;
1317   uint32_t watch_type = 0;
1318   if (options.GetWatchpointTypeRead())
1319     watch_type |= LLDB_WATCH_TYPE_READ;
1320   if (options.GetWatchpointTypeWrite() == eWatchpointWriteTypeAlways)
1321     watch_type |= LLDB_WATCH_TYPE_WRITE;
1322   if (options.GetWatchpointTypeWrite() == eWatchpointWriteTypeOnModify)
1323     watch_type |= LLDB_WATCH_TYPE_MODIFY;
1324   if (watch_type == 0) {
1325     error.SetErrorString("Can't create a watchpoint that is neither read nor "
1326                          "write nor modify.");
1327     return sb_watchpoint;
1328   }
1329 
1330   if (TargetSP target_sp = GetSP();
1331       target_sp && addr != LLDB_INVALID_ADDRESS && size > 0) {
1332     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1333     // Target::CreateWatchpoint() is thread safe.
1334     Status cw_error;
1335     // This API doesn't take in a type, so we can't figure out what it is.
1336     CompilerType *type = nullptr;
1337     watchpoint_sp =
1338         target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error);
1339     error.SetError(std::move(cw_error));
1340     sb_watchpoint.SetSP(watchpoint_sp);
1341   }
1342 
1343   return sb_watchpoint;
1344 }
1345 
EnableAllWatchpoints()1346 bool SBTarget::EnableAllWatchpoints() {
1347   LLDB_INSTRUMENT_VA(this);
1348 
1349   if (TargetSP target_sp = GetSP()) {
1350     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1351     std::unique_lock<std::recursive_mutex> lock;
1352     target_sp->GetWatchpointList().GetListMutex(lock);
1353     target_sp->EnableAllWatchpoints();
1354     return true;
1355   }
1356   return false;
1357 }
1358 
DisableAllWatchpoints()1359 bool SBTarget::DisableAllWatchpoints() {
1360   LLDB_INSTRUMENT_VA(this);
1361 
1362   if (TargetSP target_sp = GetSP()) {
1363     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1364     std::unique_lock<std::recursive_mutex> lock;
1365     target_sp->GetWatchpointList().GetListMutex(lock);
1366     target_sp->DisableAllWatchpoints();
1367     return true;
1368   }
1369   return false;
1370 }
1371 
CreateValueFromAddress(const char * name,SBAddress addr,SBType type)1372 SBValue SBTarget::CreateValueFromAddress(const char *name, SBAddress addr,
1373                                          SBType type) {
1374   LLDB_INSTRUMENT_VA(this, name, addr, type);
1375 
1376   SBValue sb_value;
1377   lldb::ValueObjectSP new_value_sp;
1378   if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) {
1379     lldb::addr_t load_addr(addr.GetLoadAddress(*this));
1380     ExecutionContext exe_ctx(
1381         ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));
1382     CompilerType ast_type(type.GetSP()->GetCompilerType(true));
1383     new_value_sp = ValueObject::CreateValueObjectFromAddress(name, load_addr,
1384                                                              exe_ctx, ast_type);
1385   }
1386   sb_value.SetSP(new_value_sp);
1387   return sb_value;
1388 }
1389 
CreateValueFromData(const char * name,lldb::SBData data,lldb::SBType type)1390 lldb::SBValue SBTarget::CreateValueFromData(const char *name, lldb::SBData data,
1391                                             lldb::SBType type) {
1392   LLDB_INSTRUMENT_VA(this, name, data, type);
1393 
1394   SBValue sb_value;
1395   lldb::ValueObjectSP new_value_sp;
1396   if (IsValid() && name && *name && data.IsValid() && type.IsValid()) {
1397     DataExtractorSP extractor(*data);
1398     ExecutionContext exe_ctx(
1399         ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));
1400     CompilerType ast_type(type.GetSP()->GetCompilerType(true));
1401     new_value_sp = ValueObject::CreateValueObjectFromData(name, *extractor,
1402                                                           exe_ctx, ast_type);
1403   }
1404   sb_value.SetSP(new_value_sp);
1405   return sb_value;
1406 }
1407 
CreateValueFromExpression(const char * name,const char * expr)1408 lldb::SBValue SBTarget::CreateValueFromExpression(const char *name,
1409                                                   const char *expr) {
1410   LLDB_INSTRUMENT_VA(this, name, expr);
1411 
1412   SBValue sb_value;
1413   lldb::ValueObjectSP new_value_sp;
1414   if (IsValid() && name && *name && expr && *expr) {
1415     ExecutionContext exe_ctx(
1416         ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));
1417     new_value_sp =
1418         ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx);
1419   }
1420   sb_value.SetSP(new_value_sp);
1421   return sb_value;
1422 }
1423 
DeleteAllWatchpoints()1424 bool SBTarget::DeleteAllWatchpoints() {
1425   LLDB_INSTRUMENT_VA(this);
1426 
1427   if (TargetSP target_sp = GetSP()) {
1428     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1429     std::unique_lock<std::recursive_mutex> lock;
1430     target_sp->GetWatchpointList().GetListMutex(lock);
1431     target_sp->RemoveAllWatchpoints();
1432     return true;
1433   }
1434   return false;
1435 }
1436 
AppendImageSearchPath(const char * from,const char * to,lldb::SBError & error)1437 void SBTarget::AppendImageSearchPath(const char *from, const char *to,
1438                                      lldb::SBError &error) {
1439   LLDB_INSTRUMENT_VA(this, from, to, error);
1440 
1441   if (TargetSP target_sp = GetSP()) {
1442     llvm::StringRef srFrom = from, srTo = to;
1443     if (srFrom.empty())
1444       return error.SetErrorString("<from> path can't be empty");
1445     if (srTo.empty())
1446       return error.SetErrorString("<to> path can't be empty");
1447 
1448     target_sp->GetImageSearchPathList().Append(srFrom, srTo, true);
1449   } else {
1450     error.SetErrorString("invalid target");
1451   }
1452 }
1453 
AddModule(const char * path,const char * triple,const char * uuid_cstr)1454 lldb::SBModule SBTarget::AddModule(const char *path, const char *triple,
1455                                    const char *uuid_cstr) {
1456   LLDB_INSTRUMENT_VA(this, path, triple, uuid_cstr);
1457 
1458   return AddModule(path, triple, uuid_cstr, nullptr);
1459 }
1460 
AddModule(const char * path,const char * triple,const char * uuid_cstr,const char * symfile)1461 lldb::SBModule SBTarget::AddModule(const char *path, const char *triple,
1462                                    const char *uuid_cstr, const char *symfile) {
1463   LLDB_INSTRUMENT_VA(this, path, triple, uuid_cstr, symfile);
1464 
1465   if (TargetSP target_sp = GetSP()) {
1466     ModuleSpec module_spec;
1467     if (path)
1468       module_spec.GetFileSpec().SetFile(path, FileSpec::Style::native);
1469 
1470     if (uuid_cstr)
1471       module_spec.GetUUID().SetFromStringRef(uuid_cstr);
1472 
1473     if (triple)
1474       module_spec.GetArchitecture() = Platform::GetAugmentedArchSpec(
1475           target_sp->GetPlatform().get(), triple);
1476     else
1477       module_spec.GetArchitecture() = target_sp->GetArchitecture();
1478 
1479     if (symfile)
1480       module_spec.GetSymbolFileSpec().SetFile(symfile, FileSpec::Style::native);
1481 
1482     SBModuleSpec sb_modulespec(module_spec);
1483 
1484     return AddModule(sb_modulespec);
1485   }
1486   return SBModule();
1487 }
1488 
AddModule(const SBModuleSpec & module_spec)1489 lldb::SBModule SBTarget::AddModule(const SBModuleSpec &module_spec) {
1490   LLDB_INSTRUMENT_VA(this, module_spec);
1491 
1492   lldb::SBModule sb_module;
1493   if (TargetSP target_sp = GetSP()) {
1494     sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up,
1495                                                  true /* notify */));
1496     if (!sb_module.IsValid() && module_spec.m_opaque_up->GetUUID().IsValid()) {
1497       Status error;
1498       if (PluginManager::DownloadObjectAndSymbolFile(*module_spec.m_opaque_up,
1499                                                      error,
1500                                                      /* force_lookup */ true)) {
1501         if (FileSystem::Instance().Exists(
1502                 module_spec.m_opaque_up->GetFileSpec())) {
1503           sb_module.SetSP(target_sp->GetOrCreateModule(*module_spec.m_opaque_up,
1504                                                        true /* notify */));
1505         }
1506       }
1507     }
1508 
1509     // If the target hasn't initialized any architecture yet, use the
1510     // binary's architecture.
1511     if (sb_module.IsValid() && !target_sp->GetArchitecture().IsValid() &&
1512         sb_module.GetSP()->GetArchitecture().IsValid())
1513       target_sp->SetArchitecture(sb_module.GetSP()->GetArchitecture());
1514   }
1515   return sb_module;
1516 }
1517 
AddModule(lldb::SBModule & module)1518 bool SBTarget::AddModule(lldb::SBModule &module) {
1519   LLDB_INSTRUMENT_VA(this, module);
1520 
1521   if (TargetSP target_sp = GetSP()) {
1522     target_sp->GetImages().AppendIfNeeded(module.GetSP());
1523     return true;
1524   }
1525   return false;
1526 }
1527 
GetNumModules() const1528 uint32_t SBTarget::GetNumModules() const {
1529   LLDB_INSTRUMENT_VA(this);
1530 
1531   uint32_t num = 0;
1532   if (TargetSP target_sp = GetSP()) {
1533     // The module list is thread safe, no need to lock
1534     num = target_sp->GetImages().GetSize();
1535   }
1536 
1537   return num;
1538 }
1539 
Clear()1540 void SBTarget::Clear() {
1541   LLDB_INSTRUMENT_VA(this);
1542 
1543   m_opaque_sp.reset();
1544 }
1545 
FindModule(const SBFileSpec & sb_file_spec)1546 SBModule SBTarget::FindModule(const SBFileSpec &sb_file_spec) {
1547   LLDB_INSTRUMENT_VA(this, sb_file_spec);
1548 
1549   SBModule sb_module;
1550   if (TargetSP target_sp = GetSP(); target_sp && sb_file_spec.IsValid()) {
1551     ModuleSpec module_spec(*sb_file_spec);
1552     // The module list is thread safe, no need to lock
1553     sb_module.SetSP(target_sp->GetImages().FindFirstModule(module_spec));
1554   }
1555   return sb_module;
1556 }
1557 
FindCompileUnits(const SBFileSpec & sb_file_spec)1558 SBSymbolContextList SBTarget::FindCompileUnits(const SBFileSpec &sb_file_spec) {
1559   LLDB_INSTRUMENT_VA(this, sb_file_spec);
1560 
1561   SBSymbolContextList sb_sc_list;
1562   if (TargetSP target_sp = GetSP(); target_sp && sb_file_spec.IsValid())
1563     target_sp->GetImages().FindCompileUnits(*sb_file_spec, *sb_sc_list);
1564   return sb_sc_list;
1565 }
1566 
GetByteOrder()1567 lldb::ByteOrder SBTarget::GetByteOrder() {
1568   LLDB_INSTRUMENT_VA(this);
1569 
1570   if (TargetSP target_sp = GetSP())
1571     return target_sp->GetArchitecture().GetByteOrder();
1572   return eByteOrderInvalid;
1573 }
1574 
GetTriple()1575 const char *SBTarget::GetTriple() {
1576   LLDB_INSTRUMENT_VA(this);
1577 
1578   if (TargetSP target_sp = GetSP()) {
1579     std::string triple(target_sp->GetArchitecture().GetTriple().str());
1580     // Unique the string so we don't run into ownership issues since the const
1581     // strings put the string into the string pool once and the strings never
1582     // comes out
1583     ConstString const_triple(triple.c_str());
1584     return const_triple.GetCString();
1585   }
1586   return nullptr;
1587 }
1588 
GetABIName()1589 const char *SBTarget::GetABIName() {
1590   LLDB_INSTRUMENT_VA(this);
1591 
1592   if (TargetSP target_sp = GetSP()) {
1593     std::string abi_name(target_sp->GetABIName().str());
1594     ConstString const_name(abi_name.c_str());
1595     return const_name.GetCString();
1596   }
1597   return nullptr;
1598 }
1599 
GetLabel() const1600 const char *SBTarget::GetLabel() const {
1601   LLDB_INSTRUMENT_VA(this);
1602 
1603   if (TargetSP target_sp = GetSP())
1604     return ConstString(target_sp->GetLabel().data()).AsCString();
1605   return nullptr;
1606 }
1607 
SetLabel(const char * label)1608 SBError SBTarget::SetLabel(const char *label) {
1609   LLDB_INSTRUMENT_VA(this, label);
1610 
1611   if (TargetSP target_sp = GetSP())
1612     return Status::FromError(target_sp->SetLabel(label));
1613   return Status::FromErrorString("Couldn't get internal target object.");
1614 }
1615 
GetMinimumOpcodeByteSize() const1616 uint32_t SBTarget::GetMinimumOpcodeByteSize() const {
1617   LLDB_INSTRUMENT_VA(this);
1618 
1619   if (TargetSP target_sp = GetSP())
1620     return target_sp->GetArchitecture().GetMinimumOpcodeByteSize();
1621   return 0;
1622 }
1623 
GetMaximumOpcodeByteSize() const1624 uint32_t SBTarget::GetMaximumOpcodeByteSize() const {
1625   LLDB_INSTRUMENT_VA(this);
1626 
1627   TargetSP target_sp(GetSP());
1628   if (target_sp)
1629     return target_sp->GetArchitecture().GetMaximumOpcodeByteSize();
1630 
1631   return 0;
1632 }
1633 
GetDataByteSize()1634 uint32_t SBTarget::GetDataByteSize() {
1635   LLDB_INSTRUMENT_VA(this);
1636 
1637   if (TargetSP target_sp = GetSP())
1638     return target_sp->GetArchitecture().GetDataByteSize();
1639   return 0;
1640 }
1641 
GetCodeByteSize()1642 uint32_t SBTarget::GetCodeByteSize() {
1643   LLDB_INSTRUMENT_VA(this);
1644 
1645   if (TargetSP target_sp = GetSP())
1646     return target_sp->GetArchitecture().GetCodeByteSize();
1647   return 0;
1648 }
1649 
GetMaximumNumberOfChildrenToDisplay() const1650 uint32_t SBTarget::GetMaximumNumberOfChildrenToDisplay() const {
1651   LLDB_INSTRUMENT_VA(this);
1652 
1653   if (TargetSP target_sp = GetSP())
1654     return target_sp->GetMaximumNumberOfChildrenToDisplay();
1655   return 0;
1656 }
1657 
GetAddressByteSize()1658 uint32_t SBTarget::GetAddressByteSize() {
1659   LLDB_INSTRUMENT_VA(this);
1660 
1661   if (TargetSP target_sp = GetSP())
1662     return target_sp->GetArchitecture().GetAddressByteSize();
1663   return sizeof(void *);
1664 }
1665 
GetModuleAtIndex(uint32_t idx)1666 SBModule SBTarget::GetModuleAtIndex(uint32_t idx) {
1667   LLDB_INSTRUMENT_VA(this, idx);
1668 
1669   SBModule sb_module;
1670   ModuleSP module_sp;
1671   if (TargetSP target_sp = GetSP()) {
1672     // The module list is thread safe, no need to lock
1673     module_sp = target_sp->GetImages().GetModuleAtIndex(idx);
1674     sb_module.SetSP(module_sp);
1675   }
1676 
1677   return sb_module;
1678 }
1679 
RemoveModule(lldb::SBModule module)1680 bool SBTarget::RemoveModule(lldb::SBModule module) {
1681   LLDB_INSTRUMENT_VA(this, module);
1682 
1683   if (TargetSP target_sp = GetSP())
1684     return target_sp->GetImages().Remove(module.GetSP());
1685   return false;
1686 }
1687 
GetBroadcaster() const1688 SBBroadcaster SBTarget::GetBroadcaster() const {
1689   LLDB_INSTRUMENT_VA(this);
1690 
1691   if (TargetSP target_sp = GetSP()) {
1692     SBBroadcaster broadcaster(target_sp.get(), false);
1693     return broadcaster;
1694   }
1695   return SBBroadcaster();
1696 }
1697 
GetDescription(SBStream & description,lldb::DescriptionLevel description_level)1698 bool SBTarget::GetDescription(SBStream &description,
1699                               lldb::DescriptionLevel description_level) {
1700   LLDB_INSTRUMENT_VA(this, description, description_level);
1701 
1702   Stream &strm = description.ref();
1703 
1704   if (TargetSP target_sp = GetSP()) {
1705     target_sp->Dump(&strm, description_level);
1706   } else
1707     strm.PutCString("No value");
1708 
1709   return true;
1710 }
1711 
FindFunctions(const char * name,uint32_t name_type_mask)1712 lldb::SBSymbolContextList SBTarget::FindFunctions(const char *name,
1713                                                   uint32_t name_type_mask) {
1714   LLDB_INSTRUMENT_VA(this, name, name_type_mask);
1715 
1716   lldb::SBSymbolContextList sb_sc_list;
1717   if (!name || !name[0])
1718     return sb_sc_list;
1719 
1720   if (TargetSP target_sp = GetSP()) {
1721     ModuleFunctionSearchOptions function_options;
1722     function_options.include_symbols = true;
1723     function_options.include_inlines = true;
1724 
1725     FunctionNameType mask = static_cast<FunctionNameType>(name_type_mask);
1726     target_sp->GetImages().FindFunctions(ConstString(name), mask,
1727                                          function_options, *sb_sc_list);
1728   }
1729   return sb_sc_list;
1730 }
1731 
FindGlobalFunctions(const char * name,uint32_t max_matches,MatchType matchtype)1732 lldb::SBSymbolContextList SBTarget::FindGlobalFunctions(const char *name,
1733                                                         uint32_t max_matches,
1734                                                         MatchType matchtype) {
1735   LLDB_INSTRUMENT_VA(this, name, max_matches, matchtype);
1736 
1737   lldb::SBSymbolContextList sb_sc_list;
1738   if (name && name[0]) {
1739     llvm::StringRef name_ref(name);
1740     if (TargetSP target_sp = GetSP()) {
1741       ModuleFunctionSearchOptions function_options;
1742       function_options.include_symbols = true;
1743       function_options.include_inlines = true;
1744 
1745       std::string regexstr;
1746       switch (matchtype) {
1747       case eMatchTypeRegex:
1748         target_sp->GetImages().FindFunctions(RegularExpression(name_ref),
1749                                              function_options, *sb_sc_list);
1750         break;
1751       case eMatchTypeRegexInsensitive:
1752         target_sp->GetImages().FindFunctions(
1753             RegularExpression(name_ref, llvm::Regex::RegexFlags::IgnoreCase),
1754             function_options, *sb_sc_list);
1755         break;
1756       case eMatchTypeStartsWith:
1757         regexstr = llvm::Regex::escape(name) + ".*";
1758         target_sp->GetImages().FindFunctions(RegularExpression(regexstr),
1759                                              function_options, *sb_sc_list);
1760         break;
1761       default:
1762         target_sp->GetImages().FindFunctions(ConstString(name),
1763                                              eFunctionNameTypeAny,
1764                                              function_options, *sb_sc_list);
1765         break;
1766       }
1767     }
1768   }
1769   return sb_sc_list;
1770 }
1771 
FindFirstType(const char * typename_cstr)1772 lldb::SBType SBTarget::FindFirstType(const char *typename_cstr) {
1773   LLDB_INSTRUMENT_VA(this, typename_cstr);
1774 
1775   if (TargetSP target_sp = GetSP();
1776       target_sp && typename_cstr && typename_cstr[0]) {
1777     ConstString const_typename(typename_cstr);
1778     TypeQuery query(const_typename.GetStringRef(),
1779                     TypeQueryOptions::e_find_one);
1780     TypeResults results;
1781     target_sp->GetImages().FindTypes(/*search_first=*/nullptr, query, results);
1782     if (TypeSP type_sp = results.GetFirstType())
1783       return SBType(type_sp);
1784     // Didn't find the type in the symbols; Try the loaded language runtimes.
1785     if (auto process_sp = target_sp->GetProcessSP()) {
1786       for (auto *runtime : process_sp->GetLanguageRuntimes()) {
1787         if (auto vendor = runtime->GetDeclVendor()) {
1788           auto types = vendor->FindTypes(const_typename, /*max_matches*/ 1);
1789           if (!types.empty())
1790             return SBType(types.front());
1791         }
1792       }
1793     }
1794 
1795     // No matches, search for basic typename matches.
1796     for (auto type_system_sp : target_sp->GetScratchTypeSystems())
1797       if (auto type = type_system_sp->GetBuiltinTypeByName(const_typename))
1798         return SBType(type);
1799   }
1800 
1801   return SBType();
1802 }
1803 
GetBasicType(lldb::BasicType type)1804 SBType SBTarget::GetBasicType(lldb::BasicType type) {
1805   LLDB_INSTRUMENT_VA(this, type);
1806 
1807   if (TargetSP target_sp = GetSP()) {
1808     for (auto type_system_sp : target_sp->GetScratchTypeSystems())
1809       if (auto compiler_type = type_system_sp->GetBasicTypeFromAST(type))
1810         return SBType(compiler_type);
1811   }
1812   return SBType();
1813 }
1814 
FindTypes(const char * typename_cstr)1815 lldb::SBTypeList SBTarget::FindTypes(const char *typename_cstr) {
1816   LLDB_INSTRUMENT_VA(this, typename_cstr);
1817 
1818   SBTypeList sb_type_list;
1819   if (TargetSP target_sp = GetSP();
1820       target_sp && typename_cstr && typename_cstr[0]) {
1821     ModuleList &images = target_sp->GetImages();
1822     ConstString const_typename(typename_cstr);
1823     TypeQuery query(typename_cstr);
1824     TypeResults results;
1825     images.FindTypes(nullptr, query, results);
1826     for (const TypeSP &type_sp : results.GetTypeMap().Types())
1827       sb_type_list.Append(SBType(type_sp));
1828 
1829     // Try the loaded language runtimes
1830     if (ProcessSP process_sp = target_sp->GetProcessSP()) {
1831       for (auto *runtime : process_sp->GetLanguageRuntimes()) {
1832         if (auto *vendor = runtime->GetDeclVendor()) {
1833           auto types =
1834               vendor->FindTypes(const_typename, /*max_matches*/ UINT32_MAX);
1835           for (auto type : types)
1836             sb_type_list.Append(SBType(type));
1837         }
1838       }
1839     }
1840 
1841     if (sb_type_list.GetSize() == 0) {
1842       // No matches, search for basic typename matches
1843       for (auto type_system_sp : target_sp->GetScratchTypeSystems())
1844         if (auto compiler_type =
1845                 type_system_sp->GetBuiltinTypeByName(const_typename))
1846           sb_type_list.Append(SBType(compiler_type));
1847     }
1848   }
1849   return sb_type_list;
1850 }
1851 
FindGlobalVariables(const char * name,uint32_t max_matches)1852 SBValueList SBTarget::FindGlobalVariables(const char *name,
1853                                           uint32_t max_matches) {
1854   LLDB_INSTRUMENT_VA(this, name, max_matches);
1855 
1856   SBValueList sb_value_list;
1857 
1858   if (TargetSP target_sp = GetSP(); target_sp && name) {
1859     VariableList variable_list;
1860     target_sp->GetImages().FindGlobalVariables(ConstString(name), max_matches,
1861                                                variable_list);
1862     if (!variable_list.Empty()) {
1863       ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get();
1864       if (exe_scope == nullptr)
1865         exe_scope = target_sp.get();
1866       for (const VariableSP &var_sp : variable_list) {
1867         lldb::ValueObjectSP valobj_sp(
1868             ValueObjectVariable::Create(exe_scope, var_sp));
1869         if (valobj_sp)
1870           sb_value_list.Append(SBValue(valobj_sp));
1871       }
1872     }
1873   }
1874 
1875   return sb_value_list;
1876 }
1877 
FindGlobalVariables(const char * name,uint32_t max_matches,MatchType matchtype)1878 SBValueList SBTarget::FindGlobalVariables(const char *name,
1879                                           uint32_t max_matches,
1880                                           MatchType matchtype) {
1881   LLDB_INSTRUMENT_VA(this, name, max_matches, matchtype);
1882 
1883   SBValueList sb_value_list;
1884 
1885   if (TargetSP target_sp = GetSP(); target_sp && name) {
1886     llvm::StringRef name_ref(name);
1887     VariableList variable_list;
1888 
1889     std::string regexstr;
1890     switch (matchtype) {
1891     case eMatchTypeNormal:
1892       target_sp->GetImages().FindGlobalVariables(ConstString(name), max_matches,
1893                                                  variable_list);
1894       break;
1895     case eMatchTypeRegex:
1896       target_sp->GetImages().FindGlobalVariables(RegularExpression(name_ref),
1897                                                  max_matches, variable_list);
1898       break;
1899     case eMatchTypeRegexInsensitive:
1900       target_sp->GetImages().FindGlobalVariables(
1901           RegularExpression(name_ref, llvm::Regex::IgnoreCase), max_matches,
1902           variable_list);
1903       break;
1904     case eMatchTypeStartsWith:
1905       regexstr = "^" + llvm::Regex::escape(name) + ".*";
1906       target_sp->GetImages().FindGlobalVariables(RegularExpression(regexstr),
1907                                                  max_matches, variable_list);
1908       break;
1909     }
1910     if (!variable_list.Empty()) {
1911       ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get();
1912       if (exe_scope == nullptr)
1913         exe_scope = target_sp.get();
1914       for (const VariableSP &var_sp : variable_list) {
1915         lldb::ValueObjectSP valobj_sp(
1916             ValueObjectVariable::Create(exe_scope, var_sp));
1917         if (valobj_sp)
1918           sb_value_list.Append(SBValue(valobj_sp));
1919       }
1920     }
1921   }
1922 
1923   return sb_value_list;
1924 }
1925 
FindFirstGlobalVariable(const char * name)1926 lldb::SBValue SBTarget::FindFirstGlobalVariable(const char *name) {
1927   LLDB_INSTRUMENT_VA(this, name);
1928 
1929   SBValueList sb_value_list(FindGlobalVariables(name, 1));
1930   if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0)
1931     return sb_value_list.GetValueAtIndex(0);
1932   return SBValue();
1933 }
1934 
GetSourceManager()1935 SBSourceManager SBTarget::GetSourceManager() {
1936   LLDB_INSTRUMENT_VA(this);
1937 
1938   SBSourceManager source_manager(*this);
1939   return source_manager;
1940 }
1941 
ReadInstructions(lldb::SBAddress base_addr,uint32_t count)1942 lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr,
1943                                                    uint32_t count) {
1944   LLDB_INSTRUMENT_VA(this, base_addr, count);
1945 
1946   return ReadInstructions(base_addr, count, nullptr);
1947 }
1948 
ReadInstructions(lldb::SBAddress base_addr,uint32_t count,const char * flavor_string)1949 lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr,
1950                                                    uint32_t count,
1951                                                    const char *flavor_string) {
1952   LLDB_INSTRUMENT_VA(this, base_addr, count, flavor_string);
1953 
1954   SBInstructionList sb_instructions;
1955 
1956   if (TargetSP target_sp = GetSP()) {
1957     if (Address *addr_ptr = base_addr.get()) {
1958       DataBufferHeap data(
1959           target_sp->GetArchitecture().GetMaximumOpcodeByteSize() * count, 0);
1960       bool force_live_memory = true;
1961       lldb_private::Status error;
1962       lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1963       const size_t bytes_read =
1964           target_sp->ReadMemory(*addr_ptr, data.GetBytes(), data.GetByteSize(),
1965                                 error, force_live_memory, &load_addr);
1966 
1967       const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1968       if (!flavor_string || flavor_string[0] == '\0') {
1969         // FIXME - we don't have the mechanism in place to do per-architecture
1970         // settings.  But since we know that for now we only support flavors on
1971         // x86 & x86_64,
1972         const llvm::Triple::ArchType arch =
1973             target_sp->GetArchitecture().GetTriple().getArch();
1974         if (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64)
1975           flavor_string = target_sp->GetDisassemblyFlavor();
1976       }
1977       sb_instructions.SetDisassembler(Disassembler::DisassembleBytes(
1978           target_sp->GetArchitecture(), nullptr, flavor_string,
1979           target_sp->GetDisassemblyCPU(), target_sp->GetDisassemblyFeatures(),
1980           *addr_ptr, data.GetBytes(), bytes_read, count, data_from_file));
1981     }
1982   }
1983 
1984   return sb_instructions;
1985 }
1986 
ReadInstructions(lldb::SBAddress start_addr,lldb::SBAddress end_addr,const char * flavor_string)1987 lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress start_addr,
1988                                                    lldb::SBAddress end_addr,
1989                                                    const char *flavor_string) {
1990   LLDB_INSTRUMENT_VA(this, start_addr, end_addr, flavor_string);
1991 
1992   SBInstructionList sb_instructions;
1993 
1994   if (TargetSP target_sp = GetSP()) {
1995     lldb::addr_t start_load_addr = start_addr.GetLoadAddress(*this);
1996     lldb::addr_t end_load_addr = end_addr.GetLoadAddress(*this);
1997     if (end_load_addr > start_load_addr) {
1998       lldb::addr_t size = end_load_addr - start_load_addr;
1999 
2000       AddressRange range(start_load_addr, size);
2001       const bool force_live_memory = true;
2002       sb_instructions.SetDisassembler(Disassembler::DisassembleRange(
2003           target_sp->GetArchitecture(), nullptr, flavor_string,
2004           target_sp->GetDisassemblyCPU(), target_sp->GetDisassemblyFeatures(),
2005           *target_sp, range, force_live_memory));
2006     }
2007   }
2008   return sb_instructions;
2009 }
2010 
GetInstructions(lldb::SBAddress base_addr,const void * buf,size_t size)2011 lldb::SBInstructionList SBTarget::GetInstructions(lldb::SBAddress base_addr,
2012                                                   const void *buf,
2013                                                   size_t size) {
2014   LLDB_INSTRUMENT_VA(this, base_addr, buf, size);
2015 
2016   return GetInstructionsWithFlavor(base_addr, nullptr, buf, size);
2017 }
2018 
2019 lldb::SBInstructionList
GetInstructionsWithFlavor(lldb::SBAddress base_addr,const char * flavor_string,const void * buf,size_t size)2020 SBTarget::GetInstructionsWithFlavor(lldb::SBAddress base_addr,
2021                                     const char *flavor_string, const void *buf,
2022                                     size_t size) {
2023   LLDB_INSTRUMENT_VA(this, base_addr, flavor_string, buf, size);
2024 
2025   SBInstructionList sb_instructions;
2026 
2027   if (TargetSP target_sp = GetSP()) {
2028     Address addr;
2029 
2030     if (base_addr.get())
2031       addr = *base_addr.get();
2032 
2033     constexpr bool data_from_file = true;
2034     if (!flavor_string || flavor_string[0] == '\0') {
2035       // FIXME - we don't have the mechanism in place to do per-architecture
2036       // settings.  But since we know that for now we only support flavors on
2037       // x86 & x86_64,
2038       const llvm::Triple::ArchType arch =
2039           target_sp->GetArchitecture().GetTriple().getArch();
2040       if (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64)
2041         flavor_string = target_sp->GetDisassemblyFlavor();
2042     }
2043 
2044     sb_instructions.SetDisassembler(Disassembler::DisassembleBytes(
2045         target_sp->GetArchitecture(), nullptr, flavor_string,
2046         target_sp->GetDisassemblyCPU(), target_sp->GetDisassemblyFeatures(),
2047         addr, buf, size, UINT32_MAX, data_from_file));
2048   }
2049 
2050   return sb_instructions;
2051 }
2052 
GetInstructions(lldb::addr_t base_addr,const void * buf,size_t size)2053 lldb::SBInstructionList SBTarget::GetInstructions(lldb::addr_t base_addr,
2054                                                   const void *buf,
2055                                                   size_t size) {
2056   LLDB_INSTRUMENT_VA(this, base_addr, buf, size);
2057 
2058   return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), nullptr, buf,
2059                                    size);
2060 }
2061 
2062 lldb::SBInstructionList
GetInstructionsWithFlavor(lldb::addr_t base_addr,const char * flavor_string,const void * buf,size_t size)2063 SBTarget::GetInstructionsWithFlavor(lldb::addr_t base_addr,
2064                                     const char *flavor_string, const void *buf,
2065                                     size_t size) {
2066   LLDB_INSTRUMENT_VA(this, base_addr, flavor_string, buf, size);
2067 
2068   return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), flavor_string,
2069                                    buf, size);
2070 }
2071 
SetSectionLoadAddress(lldb::SBSection section,lldb::addr_t section_base_addr)2072 SBError SBTarget::SetSectionLoadAddress(lldb::SBSection section,
2073                                         lldb::addr_t section_base_addr) {
2074   LLDB_INSTRUMENT_VA(this, section, section_base_addr);
2075 
2076   SBError sb_error;
2077   if (TargetSP target_sp = GetSP()) {
2078     if (!section.IsValid()) {
2079       sb_error.SetErrorStringWithFormat("invalid section");
2080     } else {
2081       SectionSP section_sp(section.GetSP());
2082       if (section_sp) {
2083         if (section_sp->IsThreadSpecific()) {
2084           sb_error.SetErrorString(
2085               "thread specific sections are not yet supported");
2086         } else {
2087           ProcessSP process_sp(target_sp->GetProcessSP());
2088           if (target_sp->SetSectionLoadAddress(section_sp, section_base_addr)) {
2089             ModuleSP module_sp(section_sp->GetModule());
2090             if (module_sp) {
2091               ModuleList module_list;
2092               module_list.Append(module_sp);
2093               target_sp->ModulesDidLoad(module_list);
2094             }
2095             // Flush info in the process (stack frames, etc)
2096             if (process_sp)
2097               process_sp->Flush();
2098           }
2099         }
2100       }
2101     }
2102   } else {
2103     sb_error.SetErrorString("invalid target");
2104   }
2105   return sb_error;
2106 }
2107 
ClearSectionLoadAddress(lldb::SBSection section)2108 SBError SBTarget::ClearSectionLoadAddress(lldb::SBSection section) {
2109   LLDB_INSTRUMENT_VA(this, section);
2110 
2111   SBError sb_error;
2112 
2113   if (TargetSP target_sp = GetSP()) {
2114     if (!section.IsValid()) {
2115       sb_error.SetErrorStringWithFormat("invalid section");
2116     } else {
2117       SectionSP section_sp(section.GetSP());
2118       if (section_sp) {
2119         ProcessSP process_sp(target_sp->GetProcessSP());
2120         if (target_sp->SetSectionUnloaded(section_sp)) {
2121           ModuleSP module_sp(section_sp->GetModule());
2122           if (module_sp) {
2123             ModuleList module_list;
2124             module_list.Append(module_sp);
2125             target_sp->ModulesDidUnload(module_list, false);
2126           }
2127           // Flush info in the process (stack frames, etc)
2128           if (process_sp)
2129             process_sp->Flush();
2130         }
2131       } else {
2132         sb_error.SetErrorStringWithFormat("invalid section");
2133       }
2134     }
2135   } else {
2136     sb_error.SetErrorStringWithFormat("invalid target");
2137   }
2138   return sb_error;
2139 }
2140 
SetModuleLoadAddress(lldb::SBModule module,int64_t slide_offset)2141 SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module,
2142                                        int64_t slide_offset) {
2143   LLDB_INSTRUMENT_VA(this, module, slide_offset);
2144 
2145   if (slide_offset < 0) {
2146     SBError sb_error;
2147     sb_error.SetErrorStringWithFormat("slide must be positive");
2148     return sb_error;
2149   }
2150 
2151   return SetModuleLoadAddress(module, static_cast<uint64_t>(slide_offset));
2152 }
2153 
SetModuleLoadAddress(lldb::SBModule module,uint64_t slide_offset)2154 SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module,
2155                                                uint64_t slide_offset) {
2156 
2157   SBError sb_error;
2158 
2159   if (TargetSP target_sp = GetSP()) {
2160     ModuleSP module_sp(module.GetSP());
2161     if (module_sp) {
2162       bool changed = false;
2163       if (module_sp->SetLoadAddress(*target_sp, slide_offset, true, changed)) {
2164         // The load was successful, make sure that at least some sections
2165         // changed before we notify that our module was loaded.
2166         if (changed) {
2167           ModuleList module_list;
2168           module_list.Append(module_sp);
2169           target_sp->ModulesDidLoad(module_list);
2170           // Flush info in the process (stack frames, etc)
2171           ProcessSP process_sp(target_sp->GetProcessSP());
2172           if (process_sp)
2173             process_sp->Flush();
2174         }
2175       }
2176     } else {
2177       sb_error.SetErrorStringWithFormat("invalid module");
2178     }
2179 
2180   } else {
2181     sb_error.SetErrorStringWithFormat("invalid target");
2182   }
2183   return sb_error;
2184 }
2185 
ClearModuleLoadAddress(lldb::SBModule module)2186 SBError SBTarget::ClearModuleLoadAddress(lldb::SBModule module) {
2187   LLDB_INSTRUMENT_VA(this, module);
2188 
2189   SBError sb_error;
2190 
2191   char path[PATH_MAX];
2192   if (TargetSP target_sp = GetSP()) {
2193     ModuleSP module_sp(module.GetSP());
2194     if (module_sp) {
2195       ObjectFile *objfile = module_sp->GetObjectFile();
2196       if (objfile) {
2197         SectionList *section_list = objfile->GetSectionList();
2198         if (section_list) {
2199           ProcessSP process_sp(target_sp->GetProcessSP());
2200 
2201           bool changed = false;
2202           const size_t num_sections = section_list->GetSize();
2203           for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
2204             SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
2205             if (section_sp)
2206               changed |= target_sp->SetSectionUnloaded(section_sp);
2207           }
2208           if (changed) {
2209             ModuleList module_list;
2210             module_list.Append(module_sp);
2211             target_sp->ModulesDidUnload(module_list, false);
2212             // Flush info in the process (stack frames, etc)
2213             ProcessSP process_sp(target_sp->GetProcessSP());
2214             if (process_sp)
2215               process_sp->Flush();
2216           }
2217         } else {
2218           module_sp->GetFileSpec().GetPath(path, sizeof(path));
2219           sb_error.SetErrorStringWithFormat("no sections in object file '%s'",
2220                                             path);
2221         }
2222       } else {
2223         module_sp->GetFileSpec().GetPath(path, sizeof(path));
2224         sb_error.SetErrorStringWithFormat("no object file for module '%s'",
2225                                           path);
2226       }
2227     } else {
2228       sb_error.SetErrorStringWithFormat("invalid module");
2229     }
2230   } else {
2231     sb_error.SetErrorStringWithFormat("invalid target");
2232   }
2233   return sb_error;
2234 }
2235 
FindSymbols(const char * name,lldb::SymbolType symbol_type)2236 lldb::SBSymbolContextList SBTarget::FindSymbols(const char *name,
2237                                                 lldb::SymbolType symbol_type) {
2238   LLDB_INSTRUMENT_VA(this, name, symbol_type);
2239 
2240   SBSymbolContextList sb_sc_list;
2241   if (name && name[0]) {
2242     if (TargetSP target_sp = GetSP()) {
2243       target_sp->GetImages().FindSymbolsWithNameAndType(
2244           ConstString(name), symbol_type, *sb_sc_list);
2245     }
2246   }
2247   return sb_sc_list;
2248 }
2249 
EvaluateExpression(const char * expr)2250 lldb::SBValue SBTarget::EvaluateExpression(const char *expr) {
2251   LLDB_INSTRUMENT_VA(this, expr);
2252 
2253   if (TargetSP target_sp = GetSP()) {
2254     SBExpressionOptions options;
2255     lldb::DynamicValueType fetch_dynamic_value =
2256         target_sp->GetPreferDynamicValue();
2257     options.SetFetchDynamicValue(fetch_dynamic_value);
2258     options.SetUnwindOnError(true);
2259     return EvaluateExpression(expr, options);
2260   }
2261   return SBValue();
2262 }
2263 
EvaluateExpression(const char * expr,const SBExpressionOptions & options)2264 lldb::SBValue SBTarget::EvaluateExpression(const char *expr,
2265                                            const SBExpressionOptions &options) {
2266   LLDB_INSTRUMENT_VA(this, expr, options);
2267 
2268   Log *expr_log = GetLog(LLDBLog::Expressions);
2269   SBValue expr_result;
2270   ValueObjectSP expr_value_sp;
2271   if (TargetSP target_sp = GetSP()) {
2272     StackFrame *frame = nullptr;
2273     if (expr == nullptr || expr[0] == '\0')
2274       return expr_result;
2275 
2276     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
2277     ExecutionContext exe_ctx(m_opaque_sp.get());
2278 
2279     frame = exe_ctx.GetFramePtr();
2280     Target *target = exe_ctx.GetTargetPtr();
2281     Process *process = exe_ctx.GetProcessPtr();
2282 
2283     if (target) {
2284       // If we have a process, make sure to lock the runlock:
2285       if (process) {
2286         Process::StopLocker stop_locker;
2287         if (stop_locker.TryLock(&process->GetRunLock())) {
2288           target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());
2289         } else {
2290           Status error;
2291           error = Status::FromErrorString("can't evaluate expressions when the "
2292                                           "process is running.");
2293           expr_value_sp =
2294               ValueObjectConstResult::Create(nullptr, std::move(error));
2295         }
2296       } else {
2297         target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());
2298       }
2299 
2300       expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue());
2301     }
2302   }
2303   LLDB_LOGF(expr_log,
2304             "** [SBTarget::EvaluateExpression] Expression result is "
2305             "%s, summary %s **",
2306             expr_result.GetValue(), expr_result.GetSummary());
2307   return expr_result;
2308 }
2309 
GetStackRedZoneSize()2310 lldb::addr_t SBTarget::GetStackRedZoneSize() {
2311   LLDB_INSTRUMENT_VA(this);
2312 
2313   if (TargetSP target_sp = GetSP()) {
2314     ABISP abi_sp;
2315     ProcessSP process_sp(target_sp->GetProcessSP());
2316     if (process_sp)
2317       abi_sp = process_sp->GetABI();
2318     else
2319       abi_sp = ABI::FindPlugin(ProcessSP(), target_sp->GetArchitecture());
2320     if (abi_sp)
2321       return abi_sp->GetRedZoneSize();
2322   }
2323   return 0;
2324 }
2325 
IsLoaded(const SBModule & module) const2326 bool SBTarget::IsLoaded(const SBModule &module) const {
2327   LLDB_INSTRUMENT_VA(this, module);
2328 
2329   if (TargetSP target_sp = GetSP()) {
2330     ModuleSP module_sp(module.GetSP());
2331     if (module_sp)
2332       return module_sp->IsLoadedInTarget(target_sp.get());
2333   }
2334   return false;
2335 }
2336 
GetLaunchInfo() const2337 lldb::SBLaunchInfo SBTarget::GetLaunchInfo() const {
2338   LLDB_INSTRUMENT_VA(this);
2339 
2340   lldb::SBLaunchInfo launch_info(nullptr);
2341   if (TargetSP target_sp = GetSP())
2342     launch_info.set_ref(m_opaque_sp->GetProcessLaunchInfo());
2343   return launch_info;
2344 }
2345 
SetLaunchInfo(const lldb::SBLaunchInfo & launch_info)2346 void SBTarget::SetLaunchInfo(const lldb::SBLaunchInfo &launch_info) {
2347   LLDB_INSTRUMENT_VA(this, launch_info);
2348 
2349   if (TargetSP target_sp = GetSP())
2350     m_opaque_sp->SetProcessLaunchInfo(launch_info.ref());
2351 }
2352 
GetEnvironment()2353 SBEnvironment SBTarget::GetEnvironment() {
2354   LLDB_INSTRUMENT_VA(this);
2355 
2356   if (TargetSP target_sp = GetSP())
2357     return SBEnvironment(target_sp->GetEnvironment());
2358 
2359   return SBEnvironment();
2360 }
2361 
GetTrace()2362 lldb::SBTrace SBTarget::GetTrace() {
2363   LLDB_INSTRUMENT_VA(this);
2364 
2365   if (TargetSP target_sp = GetSP())
2366     return SBTrace(target_sp->GetTrace());
2367 
2368   return SBTrace();
2369 }
2370 
CreateTrace(lldb::SBError & error)2371 lldb::SBTrace SBTarget::CreateTrace(lldb::SBError &error) {
2372   LLDB_INSTRUMENT_VA(this, error);
2373 
2374   error.Clear();
2375   if (TargetSP target_sp = GetSP()) {
2376     if (llvm::Expected<lldb::TraceSP> trace_sp = target_sp->CreateTrace()) {
2377       return SBTrace(*trace_sp);
2378     } else {
2379       error.SetErrorString(llvm::toString(trace_sp.takeError()).c_str());
2380     }
2381   } else {
2382     error.SetErrorString("missing target");
2383   }
2384   return SBTrace();
2385 }
2386 
GetAPIMutex() const2387 lldb::SBMutex SBTarget::GetAPIMutex() const {
2388   LLDB_INSTRUMENT_VA(this);
2389 
2390   if (TargetSP target_sp = GetSP())
2391     return lldb::SBMutex(target_sp);
2392   return lldb::SBMutex();
2393 }
2394