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