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