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