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