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