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