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(), NULL, &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   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
665 
666   SBBreakpoint sb_bp;
667   TargetSP target_sp(GetSP());
668   if (target_sp && line != 0) {
669     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
670 
671     const LazyBool check_inlines = eLazyBoolCalculate;
672     const LazyBool skip_prologue = eLazyBoolCalculate;
673     const bool internal = false;
674     const bool hardware = false;
675     const LazyBool move_to_nearest_code = eLazyBoolCalculate;
676     *sb_bp = target_sp->CreateBreakpoint(NULL, *sb_file_spec, line, offset,
677                                          check_inlines, skip_prologue, internal,
678                                          hardware, move_to_nearest_code);
679   }
680 
681   if (log) {
682     SBStream sstr;
683     sb_bp.GetDescription(sstr);
684     char path[PATH_MAX];
685     sb_file_spec->GetPath(path, sizeof(path));
686     log->Printf("SBTarget(%p)::BreakpointCreateByLocation ( %s:%u ) => "
687                 "SBBreakpoint(%p): %s",
688                 static_cast<void *>(target_sp.get()), path, line,
689                 static_cast<void *>(sb_bp.get()), sstr.GetData());
690   }
691 
692   return sb_bp;
693 }
694 
695 SBBreakpoint SBTarget::BreakpointCreateByName(const char *symbol_name,
696                                               const char *module_name) {
697   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
698 
699   SBBreakpoint sb_bp;
700   TargetSP target_sp(GetSP());
701   if (target_sp.get()) {
702     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
703 
704     const bool internal = false;
705     const bool hardware = false;
706     const LazyBool skip_prologue = eLazyBoolCalculate;
707     const lldb::addr_t offset = 0;
708     if (module_name && module_name[0]) {
709       FileSpecList module_spec_list;
710       module_spec_list.Append(FileSpec(module_name, false));
711       *sb_bp = target_sp->CreateBreakpoint(
712           &module_spec_list, NULL, symbol_name, eFunctionNameTypeAuto,
713           eLanguageTypeUnknown, offset, skip_prologue, internal, hardware);
714     } else {
715       *sb_bp = target_sp->CreateBreakpoint(
716           NULL, NULL, symbol_name, eFunctionNameTypeAuto, eLanguageTypeUnknown,
717           offset, skip_prologue, internal, hardware);
718     }
719   }
720 
721   if (log)
722     log->Printf("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", "
723                 "module=\"%s\") => SBBreakpoint(%p)",
724                 static_cast<void *>(target_sp.get()), symbol_name, module_name,
725                 static_cast<void *>(sb_bp.get()));
726 
727   return sb_bp;
728 }
729 
730 lldb::SBBreakpoint
731 SBTarget::BreakpointCreateByName(const char *symbol_name,
732                                  const SBFileSpecList &module_list,
733                                  const SBFileSpecList &comp_unit_list) {
734   uint32_t name_type_mask = eFunctionNameTypeAuto;
735   return BreakpointCreateByName(symbol_name, name_type_mask,
736                                 eLanguageTypeUnknown, module_list,
737                                 comp_unit_list);
738 }
739 
740 lldb::SBBreakpoint SBTarget::BreakpointCreateByName(
741     const char *symbol_name, uint32_t name_type_mask,
742     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
743   return BreakpointCreateByName(symbol_name, name_type_mask,
744                                 eLanguageTypeUnknown, module_list,
745                                 comp_unit_list);
746 }
747 
748 lldb::SBBreakpoint SBTarget::BreakpointCreateByName(
749     const char *symbol_name, uint32_t name_type_mask,
750     LanguageType symbol_language, const SBFileSpecList &module_list,
751     const SBFileSpecList &comp_unit_list) {
752   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
753 
754   SBBreakpoint sb_bp;
755   TargetSP target_sp(GetSP());
756   if (target_sp && symbol_name && symbol_name[0]) {
757     const bool internal = false;
758     const bool hardware = false;
759     const LazyBool skip_prologue = eLazyBoolCalculate;
760     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
761     *sb_bp = target_sp->CreateBreakpoint(
762         module_list.get(), comp_unit_list.get(), symbol_name, name_type_mask,
763         symbol_language, 0, skip_prologue, internal, hardware);
764   }
765 
766   if (log)
767     log->Printf("SBTarget(%p)::BreakpointCreateByName (symbol=\"%s\", "
768                 "name_type: %d) => SBBreakpoint(%p)",
769                 static_cast<void *>(target_sp.get()), symbol_name,
770                 name_type_mask, static_cast<void *>(sb_bp.get()));
771 
772   return sb_bp;
773 }
774 
775 lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(
776     const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,
777     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
778   return BreakpointCreateByNames(symbol_names, num_names, name_type_mask,
779                                  eLanguageTypeUnknown, module_list,
780                                  comp_unit_list);
781 }
782 
783 lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(
784     const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,
785     LanguageType symbol_language, const SBFileSpecList &module_list,
786     const SBFileSpecList &comp_unit_list) {
787   return BreakpointCreateByNames(symbol_names, num_names, name_type_mask,
788                                  eLanguageTypeUnknown, 0, module_list,
789                                  comp_unit_list);
790 }
791 
792 lldb::SBBreakpoint SBTarget::BreakpointCreateByNames(
793     const char *symbol_names[], uint32_t num_names, uint32_t name_type_mask,
794     LanguageType symbol_language, lldb::addr_t offset,
795     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
796   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
797 
798   SBBreakpoint sb_bp;
799   TargetSP target_sp(GetSP());
800   if (target_sp && num_names > 0) {
801     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
802     const bool internal = false;
803     const bool hardware = false;
804     const LazyBool skip_prologue = eLazyBoolCalculate;
805     *sb_bp = target_sp->CreateBreakpoint(
806         module_list.get(), comp_unit_list.get(), symbol_names, num_names,
807         name_type_mask, symbol_language, offset, skip_prologue, internal,
808         hardware);
809   }
810 
811   if (log) {
812     log->Printf("SBTarget(%p)::BreakpointCreateByName (symbols={",
813                 static_cast<void *>(target_sp.get()));
814     for (uint32_t i = 0; i < num_names; i++) {
815       char sep;
816       if (i < num_names - 1)
817         sep = ',';
818       else
819         sep = '}';
820       if (symbol_names[i] != NULL)
821         log->Printf("\"%s\"%c ", symbol_names[i], sep);
822       else
823         log->Printf("\"<NULL>\"%c ", sep);
824     }
825     log->Printf("name_type: %d) => SBBreakpoint(%p)", name_type_mask,
826                 static_cast<void *>(sb_bp.get()));
827   }
828 
829   return sb_bp;
830 }
831 
832 SBBreakpoint SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex,
833                                                const char *module_name) {
834   SBFileSpecList module_spec_list;
835   SBFileSpecList comp_unit_list;
836   if (module_name && module_name[0]) {
837     module_spec_list.Append(FileSpec(module_name, false));
838   }
839   return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown,
840                                  module_spec_list, comp_unit_list);
841 }
842 
843 lldb::SBBreakpoint
844 SBTarget::BreakpointCreateByRegex(const char *symbol_name_regex,
845                                   const SBFileSpecList &module_list,
846                                   const SBFileSpecList &comp_unit_list) {
847   return BreakpointCreateByRegex(symbol_name_regex, eLanguageTypeUnknown,
848                                  module_list, comp_unit_list);
849 }
850 
851 lldb::SBBreakpoint SBTarget::BreakpointCreateByRegex(
852     const char *symbol_name_regex, LanguageType symbol_language,
853     const SBFileSpecList &module_list, const SBFileSpecList &comp_unit_list) {
854   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
855 
856   SBBreakpoint sb_bp;
857   TargetSP target_sp(GetSP());
858   if (target_sp && symbol_name_regex && symbol_name_regex[0]) {
859     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
860     RegularExpression regexp(symbol_name_regex);
861     const bool internal = false;
862     const bool hardware = false;
863     const LazyBool skip_prologue = eLazyBoolCalculate;
864 
865     *sb_bp = target_sp->CreateFuncRegexBreakpoint(
866         module_list.get(), comp_unit_list.get(), regexp, symbol_language,
867         skip_prologue, internal, hardware);
868   }
869 
870   if (log)
871     log->Printf("SBTarget(%p)::BreakpointCreateByRegex (symbol_regex=\"%s\") "
872                 "=> SBBreakpoint(%p)",
873                 static_cast<void *>(target_sp.get()), symbol_name_regex,
874                 static_cast<void *>(sb_bp.get()));
875 
876   return sb_bp;
877 }
878 
879 SBBreakpoint SBTarget::BreakpointCreateByAddress(addr_t address) {
880   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
881 
882   SBBreakpoint sb_bp;
883   TargetSP target_sp(GetSP());
884   if (target_sp) {
885     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
886     const bool hardware = false;
887     *sb_bp = target_sp->CreateBreakpoint(address, false, hardware);
888   }
889 
890   if (log)
891     log->Printf("SBTarget(%p)::BreakpointCreateByAddress (address=%" PRIu64
892                 ") => SBBreakpoint(%p)",
893                 static_cast<void *>(target_sp.get()),
894                 static_cast<uint64_t>(address),
895                 static_cast<void *>(sb_bp.get()));
896 
897   return sb_bp;
898 }
899 
900 SBBreakpoint SBTarget::BreakpointCreateBySBAddress(SBAddress &sb_address) {
901   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
902 
903   SBBreakpoint sb_bp;
904   TargetSP target_sp(GetSP());
905   if (!sb_address.IsValid()) {
906     if (log)
907       log->Printf("SBTarget(%p)::BreakpointCreateBySBAddress called with "
908                   "invalid address",
909                   static_cast<void *>(target_sp.get()));
910     return sb_bp;
911   }
912 
913   if (target_sp) {
914     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
915     const bool hardware = false;
916     *sb_bp = target_sp->CreateBreakpoint(sb_address.ref(), false, hardware);
917   }
918 
919   if (log) {
920     SBStream s;
921     sb_address.GetDescription(s);
922     log->Printf("SBTarget(%p)::BreakpointCreateBySBAddress (address=%s) => "
923                 "SBBreakpoint(%p)",
924                 static_cast<void *>(target_sp.get()), s.GetData(),
925                 static_cast<void *>(sb_bp.get()));
926   }
927 
928   return sb_bp;
929 }
930 
931 lldb::SBBreakpoint
932 SBTarget::BreakpointCreateBySourceRegex(const char *source_regex,
933                                         const lldb::SBFileSpec &source_file,
934                                         const char *module_name) {
935   SBFileSpecList module_spec_list;
936 
937   if (module_name && module_name[0]) {
938     module_spec_list.Append(FileSpec(module_name, false));
939   }
940 
941   SBFileSpecList source_file_list;
942   if (source_file.IsValid()) {
943     source_file_list.Append(source_file);
944   }
945 
946   return BreakpointCreateBySourceRegex(source_regex, module_spec_list,
947                                        source_file_list);
948 }
949 
950 lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(
951     const char *source_regex, const SBFileSpecList &module_list,
952     const lldb::SBFileSpecList &source_file_list) {
953   return BreakpointCreateBySourceRegex(source_regex, module_list,
954                                        source_file_list, SBStringList());
955 }
956 
957 lldb::SBBreakpoint SBTarget::BreakpointCreateBySourceRegex(
958     const char *source_regex, const SBFileSpecList &module_list,
959     const lldb::SBFileSpecList &source_file_list,
960     const SBStringList &func_names) {
961   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
962 
963   SBBreakpoint sb_bp;
964   TargetSP target_sp(GetSP());
965   if (target_sp && source_regex && source_regex[0]) {
966     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
967     const bool hardware = false;
968     const LazyBool move_to_nearest_code = eLazyBoolCalculate;
969     RegularExpression regexp(source_regex);
970     std::unordered_set<std::string> func_names_set;
971     for (size_t i = 0; i < func_names.GetSize(); i++) {
972       func_names_set.insert(func_names.GetStringAtIndex(i));
973     }
974 
975     *sb_bp = target_sp->CreateSourceRegexBreakpoint(
976         module_list.get(), source_file_list.get(), func_names_set, regexp,
977         false, hardware, move_to_nearest_code);
978   }
979 
980   if (log)
981     log->Printf("SBTarget(%p)::BreakpointCreateByRegex (source_regex=\"%s\") "
982                 "=> SBBreakpoint(%p)",
983                 static_cast<void *>(target_sp.get()), source_regex,
984                 static_cast<void *>(sb_bp.get()));
985 
986   return sb_bp;
987 }
988 
989 lldb::SBBreakpoint
990 SBTarget::BreakpointCreateForException(lldb::LanguageType language,
991                                        bool catch_bp, bool throw_bp) {
992   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
993 
994   SBBreakpoint sb_bp;
995   TargetSP target_sp(GetSP());
996   if (target_sp) {
997     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
998     const bool hardware = false;
999     *sb_bp = target_sp->CreateExceptionBreakpoint(language, catch_bp, throw_bp,
1000                                                   hardware);
1001   }
1002 
1003   if (log)
1004     log->Printf("SBTarget(%p)::BreakpointCreateByRegex (Language: %s, catch: "
1005                 "%s throw: %s) => SBBreakpoint(%p)",
1006                 static_cast<void *>(target_sp.get()),
1007                 Language::GetNameForLanguageType(language),
1008                 catch_bp ? "on" : "off", throw_bp ? "on" : "off",
1009                 static_cast<void *>(sb_bp.get()));
1010 
1011   return sb_bp;
1012 }
1013 
1014 uint32_t SBTarget::GetNumBreakpoints() const {
1015   TargetSP target_sp(GetSP());
1016   if (target_sp) {
1017     // The breakpoint list is thread safe, no need to lock
1018     return target_sp->GetBreakpointList().GetSize();
1019   }
1020   return 0;
1021 }
1022 
1023 SBBreakpoint SBTarget::GetBreakpointAtIndex(uint32_t idx) const {
1024   SBBreakpoint sb_breakpoint;
1025   TargetSP target_sp(GetSP());
1026   if (target_sp) {
1027     // The breakpoint list is thread safe, no need to lock
1028     *sb_breakpoint = target_sp->GetBreakpointList().GetBreakpointAtIndex(idx);
1029   }
1030   return sb_breakpoint;
1031 }
1032 
1033 bool SBTarget::BreakpointDelete(break_id_t bp_id) {
1034   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1035 
1036   bool result = false;
1037   TargetSP target_sp(GetSP());
1038   if (target_sp) {
1039     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1040     result = target_sp->RemoveBreakpointByID(bp_id);
1041   }
1042 
1043   if (log)
1044     log->Printf("SBTarget(%p)::BreakpointDelete (bp_id=%d) => %i",
1045                 static_cast<void *>(target_sp.get()),
1046                 static_cast<uint32_t>(bp_id), result);
1047 
1048   return result;
1049 }
1050 
1051 SBBreakpoint SBTarget::FindBreakpointByID(break_id_t bp_id) {
1052   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1053 
1054   SBBreakpoint sb_breakpoint;
1055   TargetSP target_sp(GetSP());
1056   if (target_sp && bp_id != LLDB_INVALID_BREAK_ID) {
1057     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1058     *sb_breakpoint = target_sp->GetBreakpointByID(bp_id);
1059   }
1060 
1061   if (log)
1062     log->Printf(
1063         "SBTarget(%p)::FindBreakpointByID (bp_id=%d) => SBBreakpoint(%p)",
1064         static_cast<void *>(target_sp.get()), static_cast<uint32_t>(bp_id),
1065         static_cast<void *>(sb_breakpoint.get()));
1066 
1067   return sb_breakpoint;
1068 }
1069 
1070 bool SBTarget::EnableAllBreakpoints() {
1071   TargetSP target_sp(GetSP());
1072   if (target_sp) {
1073     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1074     target_sp->EnableAllBreakpoints();
1075     return true;
1076   }
1077   return false;
1078 }
1079 
1080 bool SBTarget::DisableAllBreakpoints() {
1081   TargetSP target_sp(GetSP());
1082   if (target_sp) {
1083     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1084     target_sp->DisableAllBreakpoints();
1085     return true;
1086   }
1087   return false;
1088 }
1089 
1090 bool SBTarget::DeleteAllBreakpoints() {
1091   TargetSP target_sp(GetSP());
1092   if (target_sp) {
1093     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1094     target_sp->RemoveAllBreakpoints();
1095     return true;
1096   }
1097   return false;
1098 }
1099 
1100 uint32_t SBTarget::GetNumWatchpoints() const {
1101   TargetSP target_sp(GetSP());
1102   if (target_sp) {
1103     // The watchpoint list is thread safe, no need to lock
1104     return target_sp->GetWatchpointList().GetSize();
1105   }
1106   return 0;
1107 }
1108 
1109 SBWatchpoint SBTarget::GetWatchpointAtIndex(uint32_t idx) const {
1110   SBWatchpoint sb_watchpoint;
1111   TargetSP target_sp(GetSP());
1112   if (target_sp) {
1113     // The watchpoint list is thread safe, no need to lock
1114     sb_watchpoint.SetSP(target_sp->GetWatchpointList().GetByIndex(idx));
1115   }
1116   return sb_watchpoint;
1117 }
1118 
1119 bool SBTarget::DeleteWatchpoint(watch_id_t wp_id) {
1120   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1121 
1122   bool result = false;
1123   TargetSP target_sp(GetSP());
1124   if (target_sp) {
1125     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1126     std::unique_lock<std::recursive_mutex> lock;
1127     target_sp->GetWatchpointList().GetListMutex(lock);
1128     result = target_sp->RemoveWatchpointByID(wp_id);
1129   }
1130 
1131   if (log)
1132     log->Printf("SBTarget(%p)::WatchpointDelete (wp_id=%d) => %i",
1133                 static_cast<void *>(target_sp.get()),
1134                 static_cast<uint32_t>(wp_id), result);
1135 
1136   return result;
1137 }
1138 
1139 SBWatchpoint SBTarget::FindWatchpointByID(lldb::watch_id_t wp_id) {
1140   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1141 
1142   SBWatchpoint sb_watchpoint;
1143   lldb::WatchpointSP watchpoint_sp;
1144   TargetSP target_sp(GetSP());
1145   if (target_sp && wp_id != LLDB_INVALID_WATCH_ID) {
1146     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1147     std::unique_lock<std::recursive_mutex> lock;
1148     target_sp->GetWatchpointList().GetListMutex(lock);
1149     watchpoint_sp = target_sp->GetWatchpointList().FindByID(wp_id);
1150     sb_watchpoint.SetSP(watchpoint_sp);
1151   }
1152 
1153   if (log)
1154     log->Printf(
1155         "SBTarget(%p)::FindWatchpointByID (bp_id=%d) => SBWatchpoint(%p)",
1156         static_cast<void *>(target_sp.get()), static_cast<uint32_t>(wp_id),
1157         static_cast<void *>(watchpoint_sp.get()));
1158 
1159   return sb_watchpoint;
1160 }
1161 
1162 lldb::SBWatchpoint SBTarget::WatchAddress(lldb::addr_t addr, size_t size,
1163                                           bool read, bool write,
1164                                           SBError &error) {
1165   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1166 
1167   SBWatchpoint sb_watchpoint;
1168   lldb::WatchpointSP watchpoint_sp;
1169   TargetSP target_sp(GetSP());
1170   if (target_sp && (read || write) && addr != LLDB_INVALID_ADDRESS &&
1171       size > 0) {
1172     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1173     uint32_t watch_type = 0;
1174     if (read)
1175       watch_type |= LLDB_WATCH_TYPE_READ;
1176     if (write)
1177       watch_type |= LLDB_WATCH_TYPE_WRITE;
1178     if (watch_type == 0) {
1179       error.SetErrorString(
1180           "Can't create a watchpoint that is neither read nor write.");
1181       return sb_watchpoint;
1182     }
1183 
1184     // Target::CreateWatchpoint() is thread safe.
1185     Error cw_error;
1186     // This API doesn't take in a type, so we can't figure out what it is.
1187     CompilerType *type = NULL;
1188     watchpoint_sp =
1189         target_sp->CreateWatchpoint(addr, size, type, watch_type, cw_error);
1190     error.SetError(cw_error);
1191     sb_watchpoint.SetSP(watchpoint_sp);
1192   }
1193 
1194   if (log)
1195     log->Printf("SBTarget(%p)::WatchAddress (addr=0x%" PRIx64
1196                 ", 0x%u) => SBWatchpoint(%p)",
1197                 static_cast<void *>(target_sp.get()), addr,
1198                 static_cast<uint32_t>(size),
1199                 static_cast<void *>(watchpoint_sp.get()));
1200 
1201   return sb_watchpoint;
1202 }
1203 
1204 bool SBTarget::EnableAllWatchpoints() {
1205   TargetSP target_sp(GetSP());
1206   if (target_sp) {
1207     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1208     std::unique_lock<std::recursive_mutex> lock;
1209     target_sp->GetWatchpointList().GetListMutex(lock);
1210     target_sp->EnableAllWatchpoints();
1211     return true;
1212   }
1213   return false;
1214 }
1215 
1216 bool SBTarget::DisableAllWatchpoints() {
1217   TargetSP target_sp(GetSP());
1218   if (target_sp) {
1219     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1220     std::unique_lock<std::recursive_mutex> lock;
1221     target_sp->GetWatchpointList().GetListMutex(lock);
1222     target_sp->DisableAllWatchpoints();
1223     return true;
1224   }
1225   return false;
1226 }
1227 
1228 SBValue SBTarget::CreateValueFromAddress(const char *name, SBAddress addr,
1229                                          SBType type) {
1230   SBValue sb_value;
1231   lldb::ValueObjectSP new_value_sp;
1232   if (IsValid() && name && *name && addr.IsValid() && type.IsValid()) {
1233     lldb::addr_t load_addr(addr.GetLoadAddress(*this));
1234     ExecutionContext exe_ctx(
1235         ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));
1236     CompilerType ast_type(type.GetSP()->GetCompilerType(true));
1237     new_value_sp = ValueObject::CreateValueObjectFromAddress(name, load_addr,
1238                                                              exe_ctx, ast_type);
1239   }
1240   sb_value.SetSP(new_value_sp);
1241   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1242   if (log) {
1243     if (new_value_sp)
1244       log->Printf("SBTarget(%p)::CreateValueFromAddress => \"%s\"",
1245                   static_cast<void *>(m_opaque_sp.get()),
1246                   new_value_sp->GetName().AsCString());
1247     else
1248       log->Printf("SBTarget(%p)::CreateValueFromAddress => NULL",
1249                   static_cast<void *>(m_opaque_sp.get()));
1250   }
1251   return sb_value;
1252 }
1253 
1254 lldb::SBValue SBTarget::CreateValueFromData(const char *name, lldb::SBData data,
1255                                             lldb::SBType type) {
1256   SBValue sb_value;
1257   lldb::ValueObjectSP new_value_sp;
1258   if (IsValid() && name && *name && data.IsValid() && type.IsValid()) {
1259     DataExtractorSP extractor(*data);
1260     ExecutionContext exe_ctx(
1261         ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));
1262     CompilerType ast_type(type.GetSP()->GetCompilerType(true));
1263     new_value_sp = ValueObject::CreateValueObjectFromData(name, *extractor,
1264                                                           exe_ctx, ast_type);
1265   }
1266   sb_value.SetSP(new_value_sp);
1267   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1268   if (log) {
1269     if (new_value_sp)
1270       log->Printf("SBTarget(%p)::CreateValueFromData => \"%s\"",
1271                   static_cast<void *>(m_opaque_sp.get()),
1272                   new_value_sp->GetName().AsCString());
1273     else
1274       log->Printf("SBTarget(%p)::CreateValueFromData => NULL",
1275                   static_cast<void *>(m_opaque_sp.get()));
1276   }
1277   return sb_value;
1278 }
1279 
1280 lldb::SBValue SBTarget::CreateValueFromExpression(const char *name,
1281                                                   const char *expr) {
1282   SBValue sb_value;
1283   lldb::ValueObjectSP new_value_sp;
1284   if (IsValid() && name && *name && expr && *expr) {
1285     ExecutionContext exe_ctx(
1286         ExecutionContextRef(ExecutionContext(m_opaque_sp.get(), false)));
1287     new_value_sp =
1288         ValueObject::CreateValueObjectFromExpression(name, expr, exe_ctx);
1289   }
1290   sb_value.SetSP(new_value_sp);
1291   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1292   if (log) {
1293     if (new_value_sp)
1294       log->Printf("SBTarget(%p)::CreateValueFromExpression => \"%s\"",
1295                   static_cast<void *>(m_opaque_sp.get()),
1296                   new_value_sp->GetName().AsCString());
1297     else
1298       log->Printf("SBTarget(%p)::CreateValueFromExpression => NULL",
1299                   static_cast<void *>(m_opaque_sp.get()));
1300   }
1301   return sb_value;
1302 }
1303 
1304 bool SBTarget::DeleteAllWatchpoints() {
1305   TargetSP target_sp(GetSP());
1306   if (target_sp) {
1307     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
1308     std::unique_lock<std::recursive_mutex> lock;
1309     target_sp->GetWatchpointList().GetListMutex(lock);
1310     target_sp->RemoveAllWatchpoints();
1311     return true;
1312   }
1313   return false;
1314 }
1315 
1316 lldb::SBModule SBTarget::AddModule(const char *path, const char *triple,
1317                                    const char *uuid_cstr) {
1318   return AddModule(path, triple, uuid_cstr, NULL);
1319 }
1320 
1321 lldb::SBModule SBTarget::AddModule(const char *path, const char *triple,
1322                                    const char *uuid_cstr, const char *symfile) {
1323   lldb::SBModule sb_module;
1324   TargetSP target_sp(GetSP());
1325   if (target_sp) {
1326     ModuleSpec module_spec;
1327     if (path)
1328       module_spec.GetFileSpec().SetFile(path, false);
1329 
1330     if (uuid_cstr)
1331       module_spec.GetUUID().SetFromCString(uuid_cstr);
1332 
1333     if (triple)
1334       module_spec.GetArchitecture().SetTriple(triple,
1335                                               target_sp->GetPlatform().get());
1336     else
1337       module_spec.GetArchitecture() = target_sp->GetArchitecture();
1338 
1339     if (symfile)
1340       module_spec.GetSymbolFileSpec().SetFile(symfile, false);
1341 
1342     sb_module.SetSP(target_sp->GetSharedModule(module_spec));
1343   }
1344   return sb_module;
1345 }
1346 
1347 lldb::SBModule SBTarget::AddModule(const SBModuleSpec &module_spec) {
1348   lldb::SBModule sb_module;
1349   TargetSP target_sp(GetSP());
1350   if (target_sp)
1351     sb_module.SetSP(target_sp->GetSharedModule(*module_spec.m_opaque_ap));
1352   return sb_module;
1353 }
1354 
1355 bool SBTarget::AddModule(lldb::SBModule &module) {
1356   TargetSP target_sp(GetSP());
1357   if (target_sp) {
1358     target_sp->GetImages().AppendIfNeeded(module.GetSP());
1359     return true;
1360   }
1361   return false;
1362 }
1363 
1364 uint32_t SBTarget::GetNumModules() const {
1365   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1366 
1367   uint32_t num = 0;
1368   TargetSP target_sp(GetSP());
1369   if (target_sp) {
1370     // The module list is thread safe, no need to lock
1371     num = target_sp->GetImages().GetSize();
1372   }
1373 
1374   if (log)
1375     log->Printf("SBTarget(%p)::GetNumModules () => %d",
1376                 static_cast<void *>(target_sp.get()), num);
1377 
1378   return num;
1379 }
1380 
1381 void SBTarget::Clear() {
1382   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1383 
1384   if (log)
1385     log->Printf("SBTarget(%p)::Clear ()",
1386                 static_cast<void *>(m_opaque_sp.get()));
1387 
1388   m_opaque_sp.reset();
1389 }
1390 
1391 SBModule SBTarget::FindModule(const SBFileSpec &sb_file_spec) {
1392   SBModule sb_module;
1393   TargetSP target_sp(GetSP());
1394   if (target_sp && sb_file_spec.IsValid()) {
1395     ModuleSpec module_spec(*sb_file_spec);
1396     // The module list is thread safe, no need to lock
1397     sb_module.SetSP(target_sp->GetImages().FindFirstModule(module_spec));
1398   }
1399   return sb_module;
1400 }
1401 
1402 lldb::ByteOrder SBTarget::GetByteOrder() {
1403   TargetSP target_sp(GetSP());
1404   if (target_sp)
1405     return target_sp->GetArchitecture().GetByteOrder();
1406   return eByteOrderInvalid;
1407 }
1408 
1409 const char *SBTarget::GetTriple() {
1410   TargetSP target_sp(GetSP());
1411   if (target_sp) {
1412     std::string triple(target_sp->GetArchitecture().GetTriple().str());
1413     // Unique the string so we don't run into ownership issues since
1414     // the const strings put the string into the string pool once and
1415     // the strings never comes out
1416     ConstString const_triple(triple.c_str());
1417     return const_triple.GetCString();
1418   }
1419   return NULL;
1420 }
1421 
1422 uint32_t SBTarget::GetDataByteSize() {
1423   TargetSP target_sp(GetSP());
1424   if (target_sp) {
1425     return target_sp->GetArchitecture().GetDataByteSize();
1426   }
1427   return 0;
1428 }
1429 
1430 uint32_t SBTarget::GetCodeByteSize() {
1431   TargetSP target_sp(GetSP());
1432   if (target_sp) {
1433     return target_sp->GetArchitecture().GetCodeByteSize();
1434   }
1435   return 0;
1436 }
1437 
1438 uint32_t SBTarget::GetAddressByteSize() {
1439   TargetSP target_sp(GetSP());
1440   if (target_sp)
1441     return target_sp->GetArchitecture().GetAddressByteSize();
1442   return sizeof(void *);
1443 }
1444 
1445 SBModule SBTarget::GetModuleAtIndex(uint32_t idx) {
1446   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1447 
1448   SBModule sb_module;
1449   ModuleSP module_sp;
1450   TargetSP target_sp(GetSP());
1451   if (target_sp) {
1452     // The module list is thread safe, no need to lock
1453     module_sp = target_sp->GetImages().GetModuleAtIndex(idx);
1454     sb_module.SetSP(module_sp);
1455   }
1456 
1457   if (log)
1458     log->Printf("SBTarget(%p)::GetModuleAtIndex (idx=%d) => SBModule(%p)",
1459                 static_cast<void *>(target_sp.get()), idx,
1460                 static_cast<void *>(module_sp.get()));
1461 
1462   return sb_module;
1463 }
1464 
1465 bool SBTarget::RemoveModule(lldb::SBModule module) {
1466   TargetSP target_sp(GetSP());
1467   if (target_sp)
1468     return target_sp->GetImages().Remove(module.GetSP());
1469   return false;
1470 }
1471 
1472 SBBroadcaster SBTarget::GetBroadcaster() const {
1473   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
1474 
1475   TargetSP target_sp(GetSP());
1476   SBBroadcaster broadcaster(target_sp.get(), false);
1477 
1478   if (log)
1479     log->Printf("SBTarget(%p)::GetBroadcaster () => SBBroadcaster(%p)",
1480                 static_cast<void *>(target_sp.get()),
1481                 static_cast<void *>(broadcaster.get()));
1482 
1483   return broadcaster;
1484 }
1485 
1486 bool SBTarget::GetDescription(SBStream &description,
1487                               lldb::DescriptionLevel description_level) {
1488   Stream &strm = description.ref();
1489 
1490   TargetSP target_sp(GetSP());
1491   if (target_sp) {
1492     target_sp->Dump(&strm, description_level);
1493   } else
1494     strm.PutCString("No value");
1495 
1496   return true;
1497 }
1498 
1499 lldb::SBSymbolContextList SBTarget::FindFunctions(const char *name,
1500                                                   uint32_t name_type_mask) {
1501   lldb::SBSymbolContextList sb_sc_list;
1502   if (name && name[0]) {
1503     TargetSP target_sp(GetSP());
1504     if (target_sp) {
1505       const bool symbols_ok = true;
1506       const bool inlines_ok = true;
1507       const bool append = true;
1508       target_sp->GetImages().FindFunctions(ConstString(name), name_type_mask,
1509                                            symbols_ok, inlines_ok, append,
1510                                            *sb_sc_list);
1511     }
1512   }
1513   return sb_sc_list;
1514 }
1515 
1516 lldb::SBSymbolContextList SBTarget::FindGlobalFunctions(const char *name,
1517                                                         uint32_t max_matches,
1518                                                         MatchType matchtype) {
1519   lldb::SBSymbolContextList sb_sc_list;
1520   if (name && name[0]) {
1521     TargetSP target_sp(GetSP());
1522     if (target_sp) {
1523       std::string regexstr;
1524       switch (matchtype) {
1525       case eMatchTypeRegex:
1526         target_sp->GetImages().FindFunctions(RegularExpression(name), true,
1527                                              true, true, *sb_sc_list);
1528         break;
1529       case eMatchTypeStartsWith:
1530         regexstr = llvm::Regex::escape(name) + ".*";
1531         target_sp->GetImages().FindFunctions(
1532             RegularExpression(regexstr.c_str()), true, true, true, *sb_sc_list);
1533         break;
1534       default:
1535         target_sp->GetImages().FindFunctions(ConstString(name),
1536                                              eFunctionNameTypeAny, true, true,
1537                                              true, *sb_sc_list);
1538         break;
1539       }
1540     }
1541   }
1542   return sb_sc_list;
1543 }
1544 
1545 lldb::SBType SBTarget::FindFirstType(const char *typename_cstr) {
1546   TargetSP target_sp(GetSP());
1547   if (typename_cstr && typename_cstr[0] && target_sp) {
1548     ConstString const_typename(typename_cstr);
1549     SymbolContext sc;
1550     const bool exact_match = false;
1551 
1552     const ModuleList &module_list = target_sp->GetImages();
1553     size_t count = module_list.GetSize();
1554     for (size_t idx = 0; idx < count; idx++) {
1555       ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1556       if (module_sp) {
1557         TypeSP type_sp(
1558             module_sp->FindFirstType(sc, const_typename, exact_match));
1559         if (type_sp)
1560           return SBType(type_sp);
1561       }
1562     }
1563 
1564     // Didn't find the type in the symbols; try the Objective-C runtime
1565     // if one is installed
1566 
1567     ProcessSP process_sp(target_sp->GetProcessSP());
1568 
1569     if (process_sp) {
1570       ObjCLanguageRuntime *objc_language_runtime =
1571           process_sp->GetObjCLanguageRuntime();
1572 
1573       if (objc_language_runtime) {
1574         DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor();
1575 
1576         if (objc_decl_vendor) {
1577           std::vector<clang::NamedDecl *> decls;
1578 
1579           if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) {
1580             if (CompilerType type = ClangASTContext::GetTypeForDecl(decls[0])) {
1581               return SBType(type);
1582             }
1583           }
1584         }
1585       }
1586     }
1587 
1588     // No matches, search for basic typename matches
1589     ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext();
1590     if (clang_ast)
1591       return SBType(ClangASTContext::GetBasicType(clang_ast->getASTContext(),
1592                                                   const_typename));
1593   }
1594   return SBType();
1595 }
1596 
1597 SBType SBTarget::GetBasicType(lldb::BasicType type) {
1598   TargetSP target_sp(GetSP());
1599   if (target_sp) {
1600     ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext();
1601     if (clang_ast)
1602       return SBType(
1603           ClangASTContext::GetBasicType(clang_ast->getASTContext(), type));
1604   }
1605   return SBType();
1606 }
1607 
1608 lldb::SBTypeList SBTarget::FindTypes(const char *typename_cstr) {
1609   SBTypeList sb_type_list;
1610   TargetSP target_sp(GetSP());
1611   if (typename_cstr && typename_cstr[0] && target_sp) {
1612     ModuleList &images = target_sp->GetImages();
1613     ConstString const_typename(typename_cstr);
1614     bool exact_match = false;
1615     SymbolContext sc;
1616     TypeList type_list;
1617     llvm::DenseSet<SymbolFile *> searched_symbol_files;
1618     uint32_t num_matches =
1619         images.FindTypes(sc, const_typename, exact_match, UINT32_MAX,
1620                          searched_symbol_files, type_list);
1621 
1622     if (num_matches > 0) {
1623       for (size_t idx = 0; idx < num_matches; idx++) {
1624         TypeSP type_sp(type_list.GetTypeAtIndex(idx));
1625         if (type_sp)
1626           sb_type_list.Append(SBType(type_sp));
1627       }
1628     }
1629 
1630     // Try the Objective-C runtime if one is installed
1631 
1632     ProcessSP process_sp(target_sp->GetProcessSP());
1633 
1634     if (process_sp) {
1635       ObjCLanguageRuntime *objc_language_runtime =
1636           process_sp->GetObjCLanguageRuntime();
1637 
1638       if (objc_language_runtime) {
1639         DeclVendor *objc_decl_vendor = objc_language_runtime->GetDeclVendor();
1640 
1641         if (objc_decl_vendor) {
1642           std::vector<clang::NamedDecl *> decls;
1643 
1644           if (objc_decl_vendor->FindDecls(const_typename, true, 1, decls) > 0) {
1645             for (clang::NamedDecl *decl : decls) {
1646               if (CompilerType type = ClangASTContext::GetTypeForDecl(decl)) {
1647                 sb_type_list.Append(SBType(type));
1648               }
1649             }
1650           }
1651         }
1652       }
1653     }
1654 
1655     if (sb_type_list.GetSize() == 0) {
1656       // No matches, search for basic typename matches
1657       ClangASTContext *clang_ast = target_sp->GetScratchClangASTContext();
1658       if (clang_ast)
1659         sb_type_list.Append(SBType(ClangASTContext::GetBasicType(
1660             clang_ast->getASTContext(), const_typename)));
1661     }
1662   }
1663   return sb_type_list;
1664 }
1665 
1666 SBValueList SBTarget::FindGlobalVariables(const char *name,
1667                                           uint32_t max_matches) {
1668   SBValueList sb_value_list;
1669 
1670   TargetSP target_sp(GetSP());
1671   if (name && target_sp) {
1672     VariableList variable_list;
1673     const bool append = true;
1674     const uint32_t match_count = target_sp->GetImages().FindGlobalVariables(
1675         ConstString(name), append, max_matches, variable_list);
1676 
1677     if (match_count > 0) {
1678       ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get();
1679       if (exe_scope == NULL)
1680         exe_scope = target_sp.get();
1681       for (uint32_t i = 0; i < match_count; ++i) {
1682         lldb::ValueObjectSP valobj_sp(ValueObjectVariable::Create(
1683             exe_scope, variable_list.GetVariableAtIndex(i)));
1684         if (valobj_sp)
1685           sb_value_list.Append(SBValue(valobj_sp));
1686       }
1687     }
1688   }
1689 
1690   return sb_value_list;
1691 }
1692 
1693 SBValueList SBTarget::FindGlobalVariables(const char *name,
1694                                           uint32_t max_matches,
1695                                           MatchType matchtype) {
1696   SBValueList sb_value_list;
1697 
1698   TargetSP target_sp(GetSP());
1699   if (name && target_sp) {
1700     VariableList variable_list;
1701     const bool append = true;
1702 
1703     std::string regexstr;
1704     uint32_t match_count;
1705     switch (matchtype) {
1706     case eMatchTypeNormal:
1707       match_count = target_sp->GetImages().FindGlobalVariables(
1708           ConstString(name), append, max_matches, variable_list);
1709       break;
1710     case eMatchTypeRegex:
1711       match_count = target_sp->GetImages().FindGlobalVariables(
1712           RegularExpression(name), append, max_matches, variable_list);
1713       break;
1714     case eMatchTypeStartsWith:
1715       regexstr = llvm::Regex::escape(name) + ".*";
1716       match_count = target_sp->GetImages().FindGlobalVariables(
1717           RegularExpression(regexstr.c_str()), append, max_matches,
1718           variable_list);
1719       break;
1720     }
1721 
1722     if (match_count > 0) {
1723       ExecutionContextScope *exe_scope = target_sp->GetProcessSP().get();
1724       if (exe_scope == NULL)
1725         exe_scope = target_sp.get();
1726       for (uint32_t i = 0; i < match_count; ++i) {
1727         lldb::ValueObjectSP valobj_sp(ValueObjectVariable::Create(
1728             exe_scope, variable_list.GetVariableAtIndex(i)));
1729         if (valobj_sp)
1730           sb_value_list.Append(SBValue(valobj_sp));
1731       }
1732     }
1733   }
1734 
1735   return sb_value_list;
1736 }
1737 
1738 lldb::SBValue SBTarget::FindFirstGlobalVariable(const char *name) {
1739   SBValueList sb_value_list(FindGlobalVariables(name, 1));
1740   if (sb_value_list.IsValid() && sb_value_list.GetSize() > 0)
1741     return sb_value_list.GetValueAtIndex(0);
1742   return SBValue();
1743 }
1744 
1745 SBSourceManager SBTarget::GetSourceManager() {
1746   SBSourceManager source_manager(*this);
1747   return source_manager;
1748 }
1749 
1750 lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr,
1751                                                    uint32_t count) {
1752   return ReadInstructions(base_addr, count, NULL);
1753 }
1754 
1755 lldb::SBInstructionList SBTarget::ReadInstructions(lldb::SBAddress base_addr,
1756                                                    uint32_t count,
1757                                                    const char *flavor_string) {
1758   SBInstructionList sb_instructions;
1759 
1760   TargetSP target_sp(GetSP());
1761   if (target_sp) {
1762     Address *addr_ptr = base_addr.get();
1763 
1764     if (addr_ptr) {
1765       DataBufferHeap data(
1766           target_sp->GetArchitecture().GetMaximumOpcodeByteSize() * count, 0);
1767       bool prefer_file_cache = false;
1768       lldb_private::Error error;
1769       lldb::addr_t load_addr = LLDB_INVALID_ADDRESS;
1770       const size_t bytes_read =
1771           target_sp->ReadMemory(*addr_ptr, prefer_file_cache, data.GetBytes(),
1772                                 data.GetByteSize(), error, &load_addr);
1773       const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
1774       sb_instructions.SetDisassembler(Disassembler::DisassembleBytes(
1775           target_sp->GetArchitecture(), NULL, flavor_string, *addr_ptr,
1776           data.GetBytes(), bytes_read, count, data_from_file));
1777     }
1778   }
1779 
1780   return sb_instructions;
1781 }
1782 
1783 lldb::SBInstructionList SBTarget::GetInstructions(lldb::SBAddress base_addr,
1784                                                   const void *buf,
1785                                                   size_t size) {
1786   return GetInstructionsWithFlavor(base_addr, NULL, buf, size);
1787 }
1788 
1789 lldb::SBInstructionList
1790 SBTarget::GetInstructionsWithFlavor(lldb::SBAddress base_addr,
1791                                     const char *flavor_string, const void *buf,
1792                                     size_t size) {
1793   SBInstructionList sb_instructions;
1794 
1795   TargetSP target_sp(GetSP());
1796   if (target_sp) {
1797     Address addr;
1798 
1799     if (base_addr.get())
1800       addr = *base_addr.get();
1801 
1802     const bool data_from_file = true;
1803 
1804     sb_instructions.SetDisassembler(Disassembler::DisassembleBytes(
1805         target_sp->GetArchitecture(), NULL, flavor_string, addr, buf, size,
1806         UINT32_MAX, data_from_file));
1807   }
1808 
1809   return sb_instructions;
1810 }
1811 
1812 lldb::SBInstructionList SBTarget::GetInstructions(lldb::addr_t base_addr,
1813                                                   const void *buf,
1814                                                   size_t size) {
1815   return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), NULL, buf,
1816                                    size);
1817 }
1818 
1819 lldb::SBInstructionList
1820 SBTarget::GetInstructionsWithFlavor(lldb::addr_t base_addr,
1821                                     const char *flavor_string, const void *buf,
1822                                     size_t size) {
1823   return GetInstructionsWithFlavor(ResolveLoadAddress(base_addr), flavor_string,
1824                                    buf, size);
1825 }
1826 
1827 SBError SBTarget::SetSectionLoadAddress(lldb::SBSection section,
1828                                         lldb::addr_t section_base_addr) {
1829   SBError sb_error;
1830   TargetSP target_sp(GetSP());
1831   if (target_sp) {
1832     if (!section.IsValid()) {
1833       sb_error.SetErrorStringWithFormat("invalid section");
1834     } else {
1835       SectionSP section_sp(section.GetSP());
1836       if (section_sp) {
1837         if (section_sp->IsThreadSpecific()) {
1838           sb_error.SetErrorString(
1839               "thread specific sections are not yet supported");
1840         } else {
1841           ProcessSP process_sp(target_sp->GetProcessSP());
1842           if (target_sp->SetSectionLoadAddress(section_sp, section_base_addr)) {
1843             ModuleSP module_sp(section_sp->GetModule());
1844             if (module_sp) {
1845               ModuleList module_list;
1846               module_list.Append(module_sp);
1847               target_sp->ModulesDidLoad(module_list);
1848             }
1849             // Flush info in the process (stack frames, etc)
1850             if (process_sp)
1851               process_sp->Flush();
1852           }
1853         }
1854       }
1855     }
1856   } else {
1857     sb_error.SetErrorString("invalid target");
1858   }
1859   return sb_error;
1860 }
1861 
1862 SBError SBTarget::ClearSectionLoadAddress(lldb::SBSection section) {
1863   SBError sb_error;
1864 
1865   TargetSP target_sp(GetSP());
1866   if (target_sp) {
1867     if (!section.IsValid()) {
1868       sb_error.SetErrorStringWithFormat("invalid section");
1869     } else {
1870       SectionSP section_sp(section.GetSP());
1871       if (section_sp) {
1872         ProcessSP process_sp(target_sp->GetProcessSP());
1873         if (target_sp->SetSectionUnloaded(section_sp)) {
1874           ModuleSP module_sp(section_sp->GetModule());
1875           if (module_sp) {
1876             ModuleList module_list;
1877             module_list.Append(module_sp);
1878             target_sp->ModulesDidUnload(module_list, false);
1879           }
1880           // Flush info in the process (stack frames, etc)
1881           if (process_sp)
1882             process_sp->Flush();
1883         }
1884       } else {
1885         sb_error.SetErrorStringWithFormat("invalid section");
1886       }
1887     }
1888   } else {
1889     sb_error.SetErrorStringWithFormat("invalid target");
1890   }
1891   return sb_error;
1892 }
1893 
1894 SBError SBTarget::SetModuleLoadAddress(lldb::SBModule module,
1895                                        int64_t slide_offset) {
1896   SBError sb_error;
1897 
1898   TargetSP target_sp(GetSP());
1899   if (target_sp) {
1900     ModuleSP module_sp(module.GetSP());
1901     if (module_sp) {
1902       bool changed = false;
1903       if (module_sp->SetLoadAddress(*target_sp, slide_offset, true, changed)) {
1904         // The load was successful, make sure that at least some sections
1905         // changed before we notify that our module was loaded.
1906         if (changed) {
1907           ModuleList module_list;
1908           module_list.Append(module_sp);
1909           target_sp->ModulesDidLoad(module_list);
1910           // Flush info in the process (stack frames, etc)
1911           ProcessSP process_sp(target_sp->GetProcessSP());
1912           if (process_sp)
1913             process_sp->Flush();
1914         }
1915       }
1916     } else {
1917       sb_error.SetErrorStringWithFormat("invalid module");
1918     }
1919 
1920   } else {
1921     sb_error.SetErrorStringWithFormat("invalid target");
1922   }
1923   return sb_error;
1924 }
1925 
1926 SBError SBTarget::ClearModuleLoadAddress(lldb::SBModule module) {
1927   SBError sb_error;
1928 
1929   char path[PATH_MAX];
1930   TargetSP target_sp(GetSP());
1931   if (target_sp) {
1932     ModuleSP module_sp(module.GetSP());
1933     if (module_sp) {
1934       ObjectFile *objfile = module_sp->GetObjectFile();
1935       if (objfile) {
1936         SectionList *section_list = objfile->GetSectionList();
1937         if (section_list) {
1938           ProcessSP process_sp(target_sp->GetProcessSP());
1939 
1940           bool changed = false;
1941           const size_t num_sections = section_list->GetSize();
1942           for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
1943             SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
1944             if (section_sp)
1945               changed |= target_sp->SetSectionUnloaded(section_sp);
1946           }
1947           if (changed) {
1948             ModuleList module_list;
1949             module_list.Append(module_sp);
1950             target_sp->ModulesDidUnload(module_list, false);
1951             // Flush info in the process (stack frames, etc)
1952             ProcessSP process_sp(target_sp->GetProcessSP());
1953             if (process_sp)
1954               process_sp->Flush();
1955           }
1956         } else {
1957           module_sp->GetFileSpec().GetPath(path, sizeof(path));
1958           sb_error.SetErrorStringWithFormat("no sections in object file '%s'",
1959                                             path);
1960         }
1961       } else {
1962         module_sp->GetFileSpec().GetPath(path, sizeof(path));
1963         sb_error.SetErrorStringWithFormat("no object file for module '%s'",
1964                                           path);
1965       }
1966     } else {
1967       sb_error.SetErrorStringWithFormat("invalid module");
1968     }
1969   } else {
1970     sb_error.SetErrorStringWithFormat("invalid target");
1971   }
1972   return sb_error;
1973 }
1974 
1975 lldb::SBSymbolContextList SBTarget::FindSymbols(const char *name,
1976                                                 lldb::SymbolType symbol_type) {
1977   SBSymbolContextList sb_sc_list;
1978   if (name && name[0]) {
1979     TargetSP target_sp(GetSP());
1980     if (target_sp) {
1981       bool append = true;
1982       target_sp->GetImages().FindSymbolsWithNameAndType(
1983           ConstString(name), symbol_type, *sb_sc_list, append);
1984     }
1985   }
1986   return sb_sc_list;
1987 }
1988 
1989 lldb::SBValue SBTarget::EvaluateExpression(const char *expr) {
1990   TargetSP target_sp(GetSP());
1991   if (!target_sp)
1992     return SBValue();
1993 
1994   SBExpressionOptions options;
1995   lldb::DynamicValueType fetch_dynamic_value =
1996       target_sp->GetPreferDynamicValue();
1997   options.SetFetchDynamicValue(fetch_dynamic_value);
1998   options.SetUnwindOnError(true);
1999   return EvaluateExpression(expr, options);
2000 }
2001 
2002 lldb::SBValue SBTarget::EvaluateExpression(const char *expr,
2003                                            const SBExpressionOptions &options) {
2004   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_API));
2005 #if !defined(LLDB_DISABLE_PYTHON)
2006   Log *expr_log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
2007 #endif
2008   SBValue expr_result;
2009   ExpressionResults exe_results = eExpressionSetupError;
2010   ValueObjectSP expr_value_sp;
2011   TargetSP target_sp(GetSP());
2012   StackFrame *frame = NULL;
2013   if (target_sp) {
2014     if (expr == NULL || expr[0] == '\0') {
2015       if (log)
2016         log->Printf(
2017             "SBTarget::EvaluateExpression called with an empty expression");
2018       return expr_result;
2019     }
2020 
2021     std::lock_guard<std::recursive_mutex> guard(target_sp->GetAPIMutex());
2022     ExecutionContext exe_ctx(m_opaque_sp.get());
2023 
2024     if (log)
2025       log->Printf("SBTarget()::EvaluateExpression (expr=\"%s\")...", expr);
2026 
2027     frame = exe_ctx.GetFramePtr();
2028     Target *target = exe_ctx.GetTargetPtr();
2029 
2030     if (target) {
2031 #ifdef LLDB_CONFIGURATION_DEBUG
2032       StreamString frame_description;
2033       if (frame)
2034         frame->DumpUsingSettingsFormat(&frame_description);
2035       Host::SetCrashDescriptionWithFormat(
2036           "SBTarget::EvaluateExpression (expr = \"%s\", fetch_dynamic_value = "
2037           "%u) %s",
2038           expr, options.GetFetchDynamicValue(),
2039           frame_description.GetString().c_str());
2040 #endif
2041       exe_results =
2042           target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());
2043 
2044       expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue());
2045 #ifdef LLDB_CONFIGURATION_DEBUG
2046       Host::SetCrashDescription(NULL);
2047 #endif
2048     } else {
2049       if (log)
2050         log->Printf("SBTarget::EvaluateExpression () => error: could not "
2051                     "reconstruct frame object for this SBTarget.");
2052     }
2053   }
2054 #ifndef LLDB_DISABLE_PYTHON
2055   if (expr_log)
2056     expr_log->Printf("** [SBTarget::EvaluateExpression] Expression result is "
2057                      "%s, summary %s **",
2058                      expr_result.GetValue(), expr_result.GetSummary());
2059 
2060   if (log)
2061     log->Printf("SBTarget(%p)::EvaluateExpression (expr=\"%s\") => SBValue(%p) "
2062                 "(execution result=%d)",
2063                 static_cast<void *>(frame), expr,
2064                 static_cast<void *>(expr_value_sp.get()), exe_results);
2065 #endif
2066 
2067   return expr_result;
2068 }
2069 
2070 lldb::addr_t SBTarget::GetStackRedZoneSize() {
2071   TargetSP target_sp(GetSP());
2072   if (target_sp) {
2073     ABISP abi_sp;
2074     ProcessSP process_sp(target_sp->GetProcessSP());
2075     if (process_sp)
2076       abi_sp = process_sp->GetABI();
2077     else
2078       abi_sp = ABI::FindPlugin(target_sp->GetArchitecture());
2079     if (abi_sp)
2080       return abi_sp->GetRedZoneSize();
2081   }
2082   return 0;
2083 }
2084 
2085 lldb::SBLaunchInfo SBTarget::GetLaunchInfo() const {
2086   lldb::SBLaunchInfo launch_info(NULL);
2087   TargetSP target_sp(GetSP());
2088   if (target_sp)
2089     launch_info.ref() = m_opaque_sp->GetProcessLaunchInfo();
2090   return launch_info;
2091 }
2092 
2093 void SBTarget::SetLaunchInfo(const lldb::SBLaunchInfo &launch_info) {
2094   TargetSP target_sp(GetSP());
2095   if (target_sp)
2096     m_opaque_sp->SetProcessLaunchInfo(launch_info.ref());
2097 }
2098