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