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