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