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