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