blob: 84890e0b5cfba2ae63ccbe53daa42ab25904499f [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Target.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
Pavel Labath181b8232018-12-14 15:59:49 +000010#include "lldb/Target/Target.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000011#include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
12#include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
13#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
Jim Ingham01f16662016-09-14 19:07:35 +000014#include "lldb/Breakpoint/BreakpointIDList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015#include "lldb/Breakpoint/BreakpointResolver.h"
16#include "lldb/Breakpoint/BreakpointResolverAddress.h"
17#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
Jim Ingham969795f2011-09-21 01:17:13 +000018#include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Breakpoint/BreakpointResolverName.h"
Jim Ingham3815e702018-09-13 21:35:32 +000020#include "lldb/Breakpoint/BreakpointResolverScripted.h"
Johnny Chen01a67862011-10-14 00:42:25 +000021#include "lldb/Breakpoint/Watchpoint.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000022#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
24#include "lldb/Core/ModuleSpec.h"
Pavel Labath13e37d42017-10-25 21:05:31 +000025#include "lldb/Core/PluginManager.h"
Jim Ingham3815e702018-09-13 21:35:32 +000026#include "lldb/Core/SearchFilter.h"
Pavel Labath181b8232018-12-14 15:59:49 +000027#include "lldb/Core/Section.h"
Greg Clayton9585fbf2013-03-19 00:20:55 +000028#include "lldb/Core/SourceManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000029#include "lldb/Core/StreamFile.h"
Jim Ingham3815e702018-09-13 21:35:32 +000030#include "lldb/Core/StructuredDataImpl.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000031#include "lldb/Core/ValueObject.h"
Sean Callanan66810412015-10-19 23:11:07 +000032#include "lldb/Expression/REPL.h"
Jim Ingham151c0322015-09-15 21:13:50 +000033#include "lldb/Expression/UserExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Host/Host.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000035#include "lldb/Host/PosixApi.h"
Jim Ingham9575d842011-03-11 03:53:59 +000036#include "lldb/Interpreter/CommandInterpreter.h"
37#include "lldb/Interpreter/CommandReturnObject.h"
Johnny Chenb90827e2012-06-04 23:19:54 +000038#include "lldb/Interpreter/OptionGroupWatchpoint.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000039#include "lldb/Interpreter/OptionValues.h"
40#include "lldb/Interpreter/Property.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000041#include "lldb/Symbol/ClangASTContext.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000042#include "lldb/Symbol/Function.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000043#include "lldb/Symbol/ObjectFile.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000044#include "lldb/Symbol/Symbol.h"
Jim Ingham151c0322015-09-15 21:13:50 +000045#include "lldb/Target/Language.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000046#include "lldb/Target/LanguageRuntime.h"
47#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Target/Process.h"
Greg Claytond5944cd2013-12-06 01:12:00 +000049#include "lldb/Target/SectionLoadList.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000050#include "lldb/Target/StackFrame.h"
Jason Molendaeef51062013-11-05 03:57:19 +000051#include "lldb/Target/SystemRuntime.h"
Jim Ingham9575d842011-03-11 03:53:59 +000052#include "lldb/Target/Thread.h"
53#include "lldb/Target/ThreadSpec.h"
Pavel Labath181b8232018-12-14 15:59:49 +000054#include "lldb/Utility/Event.h"
Zachary Turner5713a052017-03-22 18:40:07 +000055#include "lldb/Utility/FileSpec.h"
Sean Callanan9a6940c2015-10-21 00:36:34 +000056#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000057#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000058#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000059#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000060#include "lldb/Utility/Timer.h"
Pavel Labath181b8232018-12-14 15:59:49 +000061#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062
63using namespace lldb;
64using namespace lldb_private;
65
Pavel Labath43d35412016-12-06 11:24:51 +000066constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
67
Pavel Labath13e37d42017-10-25 21:05:31 +000068Target::Arch::Arch(const ArchSpec &spec)
69 : m_spec(spec),
70 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
71
72const Target::Arch& Target::Arch::operator=(const ArchSpec &spec) {
73 m_spec = spec;
74 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
75 return *this;
76}
77
Kate Stoneb9c1b512016-09-06 20:57:50 +000078ConstString &Target::GetStaticBroadcasterClass() {
79 static ConstString class_name("lldb.target");
80 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000081}
82
Kate Stoneb9c1b512016-09-06 20:57:50 +000083Target::Target(Debugger &debugger, const ArchSpec &target_arch,
84 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000085 : TargetProperties(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 Broadcaster(debugger.GetBroadcasterManager(),
87 Target::GetStaticBroadcasterClass().AsCString()),
88 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
Davide Italiano24fff242018-04-13 18:02:39 +000089 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
90 m_breakpoint_list(false), m_internal_breakpoint_list(true),
91 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
92 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
93 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
94 m_valid(true), m_suppress_stop_hooks(false),
95 m_is_dummy_target(is_dummy_target),
96 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
Jim Ingham893c9322014-11-22 01:42:44 +000097
Chris Lattner30fdc8d2010-06-08 16:52:24 +000098{
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
100 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
101 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
102 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
103 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 CheckInWithManager();
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
108 if (log)
109 log->Printf("%p Target::Target()", static_cast<void *>(this));
Pavel Labath13e37d42017-10-25 21:05:31 +0000110 if (target_arch.IsValid()) {
111 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET,
112 "Target::Target created with architecture %s (%s)",
113 target_arch.GetArchitectureName(),
114 target_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000116}
117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118Target::~Target() {
119 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
120 if (log)
121 log->Printf("%p Target::~Target()", static_cast<void *>(this));
122 DeleteCurrentProcess();
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000123}
124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125void Target::PrimeFromDummyTarget(Target *target) {
126 if (!target)
127 return;
Jim Ingham893c9322014-11-22 01:42:44 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 m_stop_hooks = target->m_stop_hooks;
130
131 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
132 if (breakpoint_sp->IsInternal())
133 continue;
134
135 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
136 AddBreakpoint(new_bp, false);
137 }
Jim Inghamb842f2e2017-09-14 20:22:49 +0000138
139 for (auto bp_name_entry : target->m_breakpoint_names)
140 {
141
142 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
143 AddBreakpointName(new_bp_name);
144 }
Jim Ingham893c9322014-11-22 01:42:44 +0000145}
146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
148 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
149 if (description_level != lldb::eDescriptionLevelBrief) {
150 s->Indent();
151 s->PutCString("Target\n");
152 s->IndentMore();
153 m_images.Dump(s);
154 m_breakpoint_list.Dump(s);
155 m_internal_breakpoint_list.Dump(s);
156 s->IndentLess();
157 } else {
158 Module *exe_module = GetExecutableModulePointer();
159 if (exe_module)
160 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
Caroline Ticeceb6b132010-10-26 03:11:13 +0000161 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 s->PutCString("No executable module.");
163 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000164}
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166void Target::CleanupProcess() {
167 // Do any cleanup of the target we need to do between process instances.
168 // NB It is better to do this before destroying the process in case the
169 // clean up needs some help from the process.
170 m_breakpoint_list.ClearAllBreakpointSites();
171 m_internal_breakpoint_list.ClearAllBreakpointSites();
172 // Disable watchpoints just on the debugger side.
173 std::unique_lock<std::recursive_mutex> lock;
174 this->GetWatchpointList().GetListMutex(lock);
175 DisableAllWatchpoints(false);
176 ClearAllWatchpointHitCounts();
177 ClearAllWatchpointHistoricValues();
Greg Clayton90ba8112012-12-05 00:16:59 +0000178}
179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180void Target::DeleteCurrentProcess() {
181 if (m_process_sp) {
Greg Claytond5944cd2013-12-06 01:12:00 +0000182 m_section_load_history.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 if (m_process_sp->IsAlive())
184 m_process_sp->Destroy(false);
185
186 m_process_sp->Finalize();
187
188 CleanupProcess();
189
190 m_process_sp.reset();
191 }
Greg Clayton3418c852011-08-10 02:10:13 +0000192}
193
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
Zachary Turner31659452016-11-17 21:15:14 +0000195 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 const FileSpec *crash_file) {
Pavel Labathcb8c6992019-01-07 10:59:57 +0000197 if (!listener_sp)
198 listener_sp = GetDebugger().GetListener();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 DeleteCurrentProcess();
200 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
201 listener_sp, crash_file);
202 return m_process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
206
Zachary Turner97206d52017-05-12 04:51:55 +0000207lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 const char *repl_options, bool can_create) {
209 if (language == eLanguageTypeUnknown) {
210 std::set<LanguageType> repl_languages;
211
212 Language::GetLanguagesSupportingREPLs(repl_languages);
213
214 if (repl_languages.size() == 1) {
215 language = *repl_languages.begin();
216 } else if (repl_languages.size() == 0) {
217 err.SetErrorStringWithFormat(
218 "LLDB isn't configured with REPL support for any languages.");
219 return REPLSP();
220 } else {
221 err.SetErrorStringWithFormat(
222 "Multiple possible REPL languages. Please specify a language.");
223 return REPLSP();
224 }
225 }
226
227 REPLMap::iterator pos = m_repl_map.find(language);
228
229 if (pos != m_repl_map.end()) {
230 return pos->second;
231 }
232
233 if (!can_create) {
234 err.SetErrorStringWithFormat(
235 "Couldn't find an existing REPL for %s, and can't create a new one",
236 Language::GetNameForLanguageType(language));
237 return lldb::REPLSP();
238 }
239
240 Debugger *const debugger = nullptr;
241 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
242
243 if (ret) {
244 m_repl_map[language] = ret;
245 return m_repl_map[language];
246 }
247
248 if (err.Success()) {
249 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
250 Language::GetNameForLanguageType(language));
251 }
252
253 return lldb::REPLSP();
254}
255
256void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
257 lldbassert(!m_repl_map.count(language));
258
259 m_repl_map[language] = repl_sp;
260}
261
262void Target::Destroy() {
263 std::lock_guard<std::recursive_mutex> guard(m_mutex);
264 m_valid = false;
265 DeleteCurrentProcess();
266 m_platform_sp.reset();
Pavel Labath13e37d42017-10-25 21:05:31 +0000267 m_arch = ArchSpec();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 ClearModules(true);
269 m_section_load_history.Clear();
270 const bool notify = false;
271 m_breakpoint_list.RemoveAll(notify);
272 m_internal_breakpoint_list.RemoveAll(notify);
273 m_last_created_breakpoint.reset();
274 m_last_created_watchpoint.reset();
275 m_search_filter_sp.reset();
276 m_image_search_paths.Clear(notify);
277 m_stop_hooks.clear();
278 m_stop_hook_next_id = 0;
279 m_suppress_stop_hooks = false;
280}
281
282BreakpointList &Target::GetBreakpointList(bool internal) {
283 if (internal)
284 return m_internal_breakpoint_list;
285 else
286 return m_breakpoint_list;
287}
288
289const BreakpointList &Target::GetBreakpointList(bool internal) const {
290 if (internal)
291 return m_internal_breakpoint_list;
292 else
293 return m_breakpoint_list;
294}
295
296BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
297 BreakpointSP bp_sp;
298
299 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
300 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
301 else
302 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
303
304 return bp_sp;
305}
306
307BreakpointSP Target::CreateSourceRegexBreakpoint(
308 const FileSpecList *containingModules,
309 const FileSpecList *source_file_spec_list,
310 const std::unordered_set<std::string> &function_names,
311 RegularExpression &source_regex, bool internal, bool hardware,
312 LazyBool move_to_nearest_code) {
313 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
314 containingModules, source_file_spec_list));
315 if (move_to_nearest_code == eLazyBoolCalculate)
316 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
317 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
318 nullptr, source_regex, function_names,
319 !static_cast<bool>(move_to_nearest_code)));
320
321 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
322}
323
324BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
325 const FileSpec &file, uint32_t line_no,
Adrian Prantl431b1582018-08-30 15:11:00 +0000326 uint32_t column, lldb::addr_t offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 LazyBool check_inlines,
328 LazyBool skip_prologue, bool internal,
329 bool hardware,
330 LazyBool move_to_nearest_code) {
331 FileSpec remapped_file;
Greg Clayton86188d82018-05-21 14:14:36 +0000332 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 remapped_file = file;
334
335 if (check_inlines == eLazyBoolCalculate) {
336 const InlineStrategy inline_strategy = GetInlineStrategy();
337 switch (inline_strategy) {
338 case eInlineBreakpointsNever:
339 check_inlines = eLazyBoolNo;
340 break;
341
342 case eInlineBreakpointsHeaders:
343 if (remapped_file.IsSourceImplementationFile())
344 check_inlines = eLazyBoolNo;
345 else
346 check_inlines = eLazyBoolYes;
347 break;
348
349 case eInlineBreakpointsAlways:
350 check_inlines = eLazyBoolYes;
351 break;
352 }
353 }
354 SearchFilterSP filter_sp;
355 if (check_inlines == eLazyBoolNo) {
356 // Not checking for inlines, we are looking only for matching compile units
357 FileSpecList compile_unit_list;
358 compile_unit_list.Append(remapped_file);
359 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
360 &compile_unit_list);
361 } else {
362 filter_sp = GetSearchFilterForModuleList(containingModules);
363 }
364 if (skip_prologue == eLazyBoolCalculate)
365 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
366 if (move_to_nearest_code == eLazyBoolCalculate)
367 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
368
369 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
Adrian Prantl431b1582018-08-30 15:11:00 +0000370 nullptr, remapped_file, line_no, column, offset, check_inlines,
371 skip_prologue, !static_cast<bool>(move_to_nearest_code)));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
373}
374
375BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
376 bool hardware) {
377 Address so_addr;
378
379 // Check for any reason we want to move this breakpoint to other address.
380 addr = GetBreakableLoadAddress(addr);
381
Adrian Prantl05097242018-04-30 16:49:04 +0000382 // Attempt to resolve our load address if possible, though it is ok if it
383 // doesn't resolve to section/offset.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384
385 // Try and resolve as a load address if possible
386 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
387 if (!so_addr.IsValid()) {
388 // The address didn't resolve, so just set this as an absolute address
389 so_addr.SetOffset(addr);
390 }
391 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
392 return bp_sp;
393}
394
395BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
396 bool hardware) {
397 SearchFilterSP filter_sp(
398 new SearchFilterForUnconstrainedSearches(shared_from_this()));
399 BreakpointResolverSP resolver_sp(
400 new BreakpointResolverAddress(nullptr, addr));
401 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
402}
403
404lldb::BreakpointSP
405Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
406 const FileSpec *file_spec,
407 bool request_hardware) {
408 SearchFilterSP filter_sp(
409 new SearchFilterForUnconstrainedSearches(shared_from_this()));
410 BreakpointResolverSP resolver_sp(
411 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
412 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
413 false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000414}
415
Zachary Turner117b1fa2018-10-25 20:45:40 +0000416BreakpointSP Target::CreateBreakpoint(
417 const FileSpecList *containingModules,
418 const FileSpecList *containingSourceFiles, const char *func_name,
419 FunctionNameType func_name_type_mask, LanguageType language,
420 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 BreakpointSP bp_sp;
422 if (func_name) {
423 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
424 containingModules, containingSourceFiles));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000425
Greg Clayton03da4cc2013-04-19 21:31:16 +0000426 if (skip_prologue == eLazyBoolCalculate)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
428 if (language == lldb::eLanguageTypeUnknown)
429 language = GetLanguage();
430
431 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
432 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
433 offset, skip_prologue));
434 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
435 }
436 return bp_sp;
437}
438
439lldb::BreakpointSP
440Target::CreateBreakpoint(const FileSpecList *containingModules,
441 const FileSpecList *containingSourceFiles,
442 const std::vector<std::string> &func_names,
Zachary Turner117b1fa2018-10-25 20:45:40 +0000443 FunctionNameType func_name_type_mask,
444 LanguageType language, lldb::addr_t offset,
445 LazyBool skip_prologue, bool internal, bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 BreakpointSP bp_sp;
447 size_t num_names = func_names.size();
448 if (num_names > 0) {
449 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
450 containingModules, containingSourceFiles));
451
452 if (skip_prologue == eLazyBoolCalculate)
453 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
454 if (language == lldb::eLanguageTypeUnknown)
455 language = GetLanguage();
456
457 BreakpointResolverSP resolver_sp(
458 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
459 language, offset, skip_prologue));
460 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
461 }
462 return bp_sp;
463}
464
Zachary Turner117b1fa2018-10-25 20:45:40 +0000465BreakpointSP
466Target::CreateBreakpoint(const FileSpecList *containingModules,
467 const FileSpecList *containingSourceFiles,
468 const char *func_names[], size_t num_names,
469 FunctionNameType func_name_type_mask,
470 LanguageType language, lldb::addr_t offset,
471 LazyBool skip_prologue, bool internal, bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 BreakpointSP bp_sp;
473 if (num_names > 0) {
474 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
475 containingModules, containingSourceFiles));
476
477 if (skip_prologue == eLazyBoolCalculate) {
478 if (offset == 0)
Greg Clayton03da4cc2013-04-19 21:31:16 +0000479 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 else
481 skip_prologue = eLazyBoolNo;
Greg Clayton1b72fcb2010-08-24 00:45:41 +0000482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 if (language == lldb::eLanguageTypeUnknown)
484 language = GetLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
487 nullptr, func_names, num_names, func_name_type_mask, language, offset,
488 skip_prologue));
489 resolver_sp->SetOffset(offset);
490 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
491 }
492 return bp_sp;
Jim Ingham133e0fb2012-03-03 02:05:11 +0000493}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000494
495SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496Target::GetSearchFilterForModule(const FileSpec *containingModule) {
497 SearchFilterSP filter_sp;
498 if (containingModule != nullptr) {
499 // TODO: We should look into sharing module based search filters
500 // across many breakpoints like we do for the simple target based one
501 filter_sp.reset(
502 new SearchFilterByModule(shared_from_this(), *containingModule));
503 } else {
504 if (!m_search_filter_sp)
505 m_search_filter_sp.reset(
506 new SearchFilterForUnconstrainedSearches(shared_from_this()));
507 filter_sp = m_search_filter_sp;
508 }
509 return filter_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510}
511
Jim Ingham969795f2011-09-21 01:17:13 +0000512SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
514 SearchFilterSP filter_sp;
515 if (containingModules && containingModules->GetSize() != 0) {
516 // TODO: We should look into sharing module based search filters
517 // across many breakpoints like we do for the simple target based one
518 filter_sp.reset(
519 new SearchFilterByModuleList(shared_from_this(), *containingModules));
520 } else {
521 if (!m_search_filter_sp)
522 m_search_filter_sp.reset(
523 new SearchFilterForUnconstrainedSearches(shared_from_this()));
524 filter_sp = m_search_filter_sp;
525 }
526 return filter_sp;
Jim Ingham969795f2011-09-21 01:17:13 +0000527}
528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
530 const FileSpecList *containingModules,
531 const FileSpecList *containingSourceFiles) {
532 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
533 return GetSearchFilterForModuleList(containingModules);
534
535 SearchFilterSP filter_sp;
536 if (containingModules == nullptr) {
537 // We could make a special "CU List only SearchFilter". Better yet was if
Adrian Prantl05097242018-04-30 16:49:04 +0000538 // these could be composable, but that will take a little reworking.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539
540 filter_sp.reset(new SearchFilterByModuleListAndCU(
541 shared_from_this(), FileSpecList(), *containingSourceFiles));
542 } else {
543 filter_sp.reset(new SearchFilterByModuleListAndCU(
544 shared_from_this(), *containingModules, *containingSourceFiles));
545 }
546 return filter_sp;
Jim Ingham87df91b2011-09-23 00:54:11 +0000547}
548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549BreakpointSP Target::CreateFuncRegexBreakpoint(
550 const FileSpecList *containingModules,
551 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
552 lldb::LanguageType requested_language, LazyBool skip_prologue,
553 bool internal, bool hardware) {
554 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
555 containingModules, containingSourceFiles));
556 bool skip = (skip_prologue == eLazyBoolCalculate)
557 ? GetSkipPrologue()
558 : static_cast<bool>(skip_prologue);
559 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
560 nullptr, func_regex, requested_language, 0, skip));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000563}
564
Jim Ingham219ba192012-03-05 04:47:34 +0000565lldb::BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
567 bool catch_bp, bool throw_bp, bool internal,
Zachary Turner97206d52017-05-12 04:51:55 +0000568 Args *additional_args, Status *error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
570 *this, language, catch_bp, throw_bp, internal);
571 if (exc_bkpt_sp && additional_args) {
572 Breakpoint::BreakpointPreconditionSP precondition_sp =
573 exc_bkpt_sp->GetPrecondition();
574 if (precondition_sp && additional_args) {
575 if (error)
576 *error = precondition_sp->ConfigurePrecondition(*additional_args);
577 else
578 precondition_sp->ConfigurePrecondition(*additional_args);
Jim Inghama72b31c2015-04-22 19:42:18 +0000579 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
581 return exc_bkpt_sp;
Jim Ingham219ba192012-03-05 04:47:34 +0000582}
Jim Inghama72b31c2015-04-22 19:42:18 +0000583
Jim Ingham3815e702018-09-13 21:35:32 +0000584lldb::BreakpointSP
585Target::CreateScriptedBreakpoint(const llvm::StringRef class_name,
586 const FileSpecList *containingModules,
587 const FileSpecList *containingSourceFiles,
588 bool internal,
589 bool request_hardware,
590 StructuredData::ObjectSP extra_args_sp,
591 Status *creation_error)
592{
593 SearchFilterSP filter_sp;
594
595 lldb::SearchDepth depth = lldb::eSearchDepthTarget;
596 bool has_files = containingSourceFiles && containingSourceFiles->GetSize() > 0;
597 bool has_modules = containingModules && containingModules->GetSize() > 0;
598
599 if (has_files && has_modules) {
600 filter_sp = GetSearchFilterForModuleAndCUList(
601 containingModules, containingSourceFiles);
602 } else if (has_files) {
603 filter_sp = GetSearchFilterForModuleAndCUList(
604 nullptr, containingSourceFiles);
605 } else if (has_modules) {
606 filter_sp = GetSearchFilterForModuleList(containingModules);
607 } else {
608 filter_sp.reset(new SearchFilterForUnconstrainedSearches(shared_from_this()));
609 }
610
611 StructuredDataImpl *extra_args_impl = new StructuredDataImpl();
612 if (extra_args_sp)
613 extra_args_impl->SetObjectSP(extra_args_sp);
614
615 BreakpointResolverSP resolver_sp(new
616 BreakpointResolverScripted(nullptr, class_name,
617 depth,
618 extra_args_impl,
619 *GetDebugger().GetCommandInterpreter()
620 .GetScriptInterpreter()));
621 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
622
623}
624
625
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
627 BreakpointResolverSP &resolver_sp,
628 bool internal, bool request_hardware,
629 bool resolve_indirect_symbols) {
630 BreakpointSP bp_sp;
631 if (filter_sp && resolver_sp) {
Jonas Devliegheree103ae92018-11-15 01:18:15 +0000632 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
633 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 resolve_indirect_symbols));
635 resolver_sp->SetBreakpoint(bp_sp.get());
636 AddBreakpoint(bp_sp, internal);
637 }
638 return bp_sp;
Jim Ingham33df7cd2014-12-06 01:28:03 +0000639}
640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
642 if (!bp_sp)
643 return;
644 if (internal)
645 m_internal_breakpoint_list.Add(bp_sp, false);
646 else
647 m_breakpoint_list.Add(bp_sp, true);
Jim Ingham33df7cd2014-12-06 01:28:03 +0000648
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
650 if (log) {
651 StreamString s;
652 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
653 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
654 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
655 }
Jim Ingham33df7cd2014-12-06 01:28:03 +0000656
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 bp_sp->ResolveBreakpoint();
Jim Ingham33df7cd2014-12-06 01:28:03 +0000658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 if (!internal) {
660 m_last_created_breakpoint = bp_sp;
661 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662}
663
Jim Inghamb842f2e2017-09-14 20:22:49 +0000664void Target::AddNameToBreakpoint(BreakpointID &id,
665 const char *name,
666 Status &error)
667 {
668 BreakpointSP bp_sp
669 = m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
670 if (!bp_sp)
671 {
672 StreamString s;
673 id.GetDescription(&s, eDescriptionLevelBrief);
674 error.SetErrorStringWithFormat("Could not find breakpoint %s",
675 s.GetData());
676 return;
677 }
678 AddNameToBreakpoint(bp_sp, name, error);
679 }
680
681void Target::AddNameToBreakpoint(BreakpointSP &bp_sp,
682 const char *name,
683 Status &error)
684 {
685 if (!bp_sp)
686 return;
687
688 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
689 if (!bp_name)
690 return;
691
692 bp_name->ConfigureBreakpoint(bp_sp);
693 bp_sp->AddName(name);
694 }
695
696void Target::AddBreakpointName(BreakpointName *bp_name) {
697 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
698}
699
700BreakpointName *Target::FindBreakpointName(const ConstString &name,
701 bool can_create,
702 Status &error)
703{
704 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
705 if (!error.Success())
706 return nullptr;
707
708 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
709 if (iter == m_breakpoint_names.end()) {
710 if (!can_create)
711 {
712 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
713 "can_create is false.", name.AsCString());
714 return nullptr;
715 }
716
717 iter = m_breakpoint_names.insert(std::make_pair(name,
718 new BreakpointName(name)))
719 .first;
720 }
721 return (iter->second);
722}
723
724void
725Target::DeleteBreakpointName(const ConstString &name)
726{
727 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
728
729 if (iter != m_breakpoint_names.end()) {
730 const char *name_cstr = name.AsCString();
731 m_breakpoint_names.erase(iter);
732 for (auto bp_sp : m_breakpoint_list.Breakpoints())
733 bp_sp->RemoveName(name_cstr);
734 }
735}
736
737void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
738 const ConstString &name)
739{
740 bp_sp->RemoveName(name.AsCString());
741}
742
743void Target::ConfigureBreakpointName(BreakpointName &bp_name,
744 const BreakpointOptions &new_options,
745 const BreakpointName::Permissions &new_permissions)
746{
747 bp_name.GetOptions().CopyOverSetOptions(new_options);
748 bp_name.GetPermissions().MergeInto(new_permissions);
749 ApplyNameToBreakpoints(bp_name);
750}
751
752void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
753 BreakpointList bkpts_with_name(false);
754 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString(),
755 bkpts_with_name);
756
757 for (auto bp_sp : bkpts_with_name.Breakpoints())
758 bp_name.ConfigureBreakpoint(bp_sp);
759}
760
761void Target::GetBreakpointNames(std::vector<std::string> &names)
762{
763 names.clear();
764 for (auto bp_name : m_breakpoint_names) {
765 names.push_back(bp_name.first.AsCString());
766 }
767 std::sort(names.begin(), names.end());
768}
769
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770bool Target::ProcessIsValid() {
771 return (m_process_sp && m_process_sp->IsAlive());
Johnny Chen86364b42011-09-20 23:28:55 +0000772}
773
Jason Molendac0e793d2018-11-09 22:33:26 +0000774static bool CheckIfWatchpointsSupported(Target *target, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 uint32_t num_supported_hardware_watchpoints;
Zachary Turner97206d52017-05-12 04:51:55 +0000776 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 num_supported_hardware_watchpoints);
Jason Molendac0e793d2018-11-09 22:33:26 +0000778
779 // If unable to determine the # of watchpoints available,
780 // assume they are supported.
781 if (rc.Fail())
782 return true;
783
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 if (num_supported_hardware_watchpoints == 0) {
785 error.SetErrorStringWithFormat(
786 "Target supports (%u) hardware watchpoint slots.\n",
787 num_supported_hardware_watchpoints);
788 return false;
789 }
790 return true;
Johnny Chenb90827e2012-06-04 23:19:54 +0000791}
792
Adrian Prantl05097242018-04-30 16:49:04 +0000793// See also Watchpoint::SetWatchpointType(uint32_t type) and the
794// OptionGroupWatchpoint::WatchType enum type.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
796 const CompilerType *type, uint32_t kind,
Zachary Turner97206d52017-05-12 04:51:55 +0000797 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
799 if (log)
800 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
801 " type = %u)\n",
802 __FUNCTION__, addr, (uint64_t)size, kind);
Johnny Chen0c406372011-09-14 20:23:45 +0000803
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 WatchpointSP wp_sp;
805 if (!ProcessIsValid()) {
806 error.SetErrorString("process is not alive");
Johnny Chen01a67862011-10-14 00:42:25 +0000807 return wp_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 }
Johnny Chen887062a2011-09-12 23:38:44 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
811 if (size == 0)
812 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
815 return wp_sp;
816 }
817
818 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
819 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
820 }
821
Jason Molendac0e793d2018-11-09 22:33:26 +0000822 if (!CheckIfWatchpointsSupported(this, error))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 return wp_sp;
824
Adrian Prantl05097242018-04-30 16:49:04 +0000825 // Currently we only support one watchpoint per address, with total number of
826 // watchpoints limited by the hardware which the inferior is running on.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827
828 // Grab the list mutex while doing operations.
829 const bool notify = false; // Don't notify about all the state changes we do
830 // on creating the watchpoint.
831 std::unique_lock<std::recursive_mutex> lock;
832 this->GetWatchpointList().GetListMutex(lock);
833 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
834 if (matched_sp) {
835 size_t old_size = matched_sp->GetByteSize();
836 uint32_t old_type =
837 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
838 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
839 // Return the existing watchpoint if both size and type match.
840 if (size == old_size && kind == old_type) {
841 wp_sp = matched_sp;
842 wp_sp->SetEnabled(false, notify);
843 } else {
844 // Nil the matched watchpoint; we will be creating a new one.
845 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
846 m_watchpoint_list.Remove(matched_sp->GetID(), true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 }
849
850 if (!wp_sp) {
851 wp_sp.reset(new Watchpoint(*this, addr, size, type));
852 wp_sp->SetWatchpointType(kind, notify);
853 m_watchpoint_list.Add(wp_sp, true);
854 }
855
856 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
857 if (log)
858 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
859 __FUNCTION__, error.Success() ? "succeeded" : "failed",
860 wp_sp->GetID());
861
862 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000863 // Enabling the watchpoint on the device side failed. Remove the said
864 // watchpoint from the list maintained by the target instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 m_watchpoint_list.Remove(wp_sp->GetID(), true);
866 // See if we could provide more helpful error message.
867 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
868 error.SetErrorStringWithFormat(
869 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
870
871 wp_sp.reset();
872 } else
873 m_last_created_watchpoint = wp_sp;
874 return wp_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000875}
876
Jim Inghamb842f2e2017-09-14 20:22:49 +0000877void Target::RemoveAllowedBreakpoints ()
878{
879 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
880 if (log)
881 log->Printf("Target::%s \n", __FUNCTION__);
882
883 m_breakpoint_list.RemoveAllowed(true);
884
885 m_last_created_breakpoint.reset();
886}
887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888void Target::RemoveAllBreakpoints(bool internal_also) {
889 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
890 if (log)
891 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
892 internal_also ? "yes" : "no");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 m_breakpoint_list.RemoveAll(true);
895 if (internal_also)
896 m_internal_breakpoint_list.RemoveAll(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 m_last_created_breakpoint.reset();
899}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901void Target::DisableAllBreakpoints(bool internal_also) {
902 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
903 if (log)
904 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
905 internal_also ? "yes" : "no");
906
907 m_breakpoint_list.SetEnabledAll(false);
908 if (internal_also)
909 m_internal_breakpoint_list.SetEnabledAll(false);
910}
911
Jim Inghamb842f2e2017-09-14 20:22:49 +0000912void Target::DisableAllowedBreakpoints() {
913 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
914 if (log)
915 log->Printf("Target::%s", __FUNCTION__);
916
917 m_breakpoint_list.SetEnabledAllowed(false);
918}
919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920void Target::EnableAllBreakpoints(bool internal_also) {
921 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
922 if (log)
923 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
924 internal_also ? "yes" : "no");
925
926 m_breakpoint_list.SetEnabledAll(true);
927 if (internal_also)
928 m_internal_breakpoint_list.SetEnabledAll(true);
929}
930
Jim Inghamb842f2e2017-09-14 20:22:49 +0000931void Target::EnableAllowedBreakpoints() {
932 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
933 if (log)
934 log->Printf("Target::%s", __FUNCTION__);
935
936 m_breakpoint_list.SetEnabledAllowed(true);
937}
938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939bool Target::RemoveBreakpointByID(break_id_t break_id) {
940 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
941 if (log)
942 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
943 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
944
945 if (DisableBreakpointByID(break_id)) {
946 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
947 m_internal_breakpoint_list.Remove(break_id, false);
948 else {
949 if (m_last_created_breakpoint) {
950 if (m_last_created_breakpoint->GetID() == break_id)
951 m_last_created_breakpoint.reset();
952 }
953 m_breakpoint_list.Remove(break_id, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 return true;
956 }
957 return false;
958}
959
960bool Target::DisableBreakpointByID(break_id_t break_id) {
961 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
962 if (log)
963 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
964 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
965
966 BreakpointSP bp_sp;
967
968 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
969 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
970 else
971 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
972 if (bp_sp) {
973 bp_sp->SetEnabled(false);
974 return true;
975 }
976 return false;
977}
978
979bool Target::EnableBreakpointByID(break_id_t break_id) {
980 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
981 if (log)
982 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
983 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
984
985 BreakpointSP bp_sp;
986
987 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
988 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
989 else
990 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
991
992 if (bp_sp) {
993 bp_sp->SetEnabled(true);
994 return true;
995 }
996 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997}
998
Zachary Turner97206d52017-05-12 04:51:55 +0000999Status Target::SerializeBreakpointsToFile(const FileSpec &file,
1000 const BreakpointIDList &bp_ids,
1001 bool append) {
1002 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +00001003
1004 if (!file) {
1005 error.SetErrorString("Invalid FileSpec.");
1006 return error;
1007 }
1008
1009 std::string path(file.GetPath());
Jim Ingham2d3628e2016-09-22 23:42:42 +00001010 StructuredData::ObjectSP input_data_sp;
1011
1012 StructuredData::ArraySP break_store_sp;
1013 StructuredData::Array *break_store_ptr = nullptr;
1014
1015 if (append) {
1016 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1017 if (error.Success()) {
1018 break_store_ptr = input_data_sp->GetAsArray();
1019 if (!break_store_ptr) {
1020 error.SetErrorStringWithFormat(
1021 "Tried to append to invalid input file %s", path.c_str());
1022 return error;
1023 }
1024 }
1025 }
1026
1027 if (!break_store_ptr) {
1028 break_store_sp.reset(new StructuredData::Array());
1029 break_store_ptr = break_store_sp.get();
1030 }
1031
Jim Ingham01f16662016-09-14 19:07:35 +00001032 StreamFile out_file(path.c_str(),
1033 File::OpenOptions::eOpenOptionTruncate |
1034 File::OpenOptions::eOpenOptionWrite |
1035 File::OpenOptions::eOpenOptionCanCreate |
1036 File::OpenOptions::eOpenOptionCloseOnExec,
1037 lldb::eFilePermissionsFileDefault);
1038 if (!out_file.GetFile().IsValid()) {
1039 error.SetErrorStringWithFormat("Unable to open output file: %s.",
1040 path.c_str());
1041 return error;
1042 }
1043
1044 std::unique_lock<std::recursive_mutex> lock;
1045 GetBreakpointList().GetListMutex(lock);
1046
Jim Ingham01f16662016-09-14 19:07:35 +00001047 if (bp_ids.GetSize() == 0) {
1048 const BreakpointList &breakpoints = GetBreakpointList();
1049
1050 size_t num_breakpoints = breakpoints.GetSize();
1051 for (size_t i = 0; i < num_breakpoints; i++) {
1052 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1053 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1054 // If a breakpoint can't serialize it, just ignore it for now:
1055 if (bkpt_save_sp)
Jim Ingham2d3628e2016-09-22 23:42:42 +00001056 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +00001057 }
1058 } else {
1059
1060 std::unordered_set<lldb::break_id_t> processed_bkpts;
1061 const size_t count = bp_ids.GetSize();
1062 for (size_t i = 0; i < count; ++i) {
1063 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1064 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1065
1066 if (bp_id != LLDB_INVALID_BREAK_ID) {
1067 // Only do each breakpoint once:
1068 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1069 insert_result = processed_bkpts.insert(bp_id);
1070 if (!insert_result.second)
1071 continue;
1072
1073 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1074 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1075 // If the user explicitly asked to serialize a breakpoint, and we
Adrian Prantl05097242018-04-30 16:49:04 +00001076 // can't, then raise an error:
Jim Ingham01f16662016-09-14 19:07:35 +00001077 if (!bkpt_save_sp) {
1078 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1079 bp_id);
1080 return error;
1081 }
Jim Ingham2d3628e2016-09-22 23:42:42 +00001082 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +00001083 }
1084 }
1085 }
1086
Jim Ingham2d3628e2016-09-22 23:42:42 +00001087 break_store_ptr->Dump(out_file, false);
Jim Ingham01f16662016-09-14 19:07:35 +00001088 out_file.PutChar('\n');
1089 return error;
1090}
1091
Zachary Turner97206d52017-05-12 04:51:55 +00001092Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1093 BreakpointIDList &new_bps) {
Jim Ingham3acdf382016-09-22 22:20:28 +00001094 std::vector<std::string> no_names;
1095 return CreateBreakpointsFromFile(file, no_names, new_bps);
1096}
1097
Zachary Turner97206d52017-05-12 04:51:55 +00001098Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1099 std::vector<std::string> &names,
1100 BreakpointIDList &new_bps) {
Jim Ingham01f16662016-09-14 19:07:35 +00001101 std::unique_lock<std::recursive_mutex> lock;
1102 GetBreakpointList().GetListMutex(lock);
1103
Zachary Turner97206d52017-05-12 04:51:55 +00001104 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +00001105 StructuredData::ObjectSP input_data_sp =
1106 StructuredData::ParseJSONFromFile(file, error);
1107 if (!error.Success()) {
1108 return error;
1109 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1110 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1111 file.GetPath().c_str());
1112 return error;
1113 }
1114
1115 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1116 if (!bkpt_array) {
1117 error.SetErrorStringWithFormat(
1118 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1119 return error;
1120 }
1121
1122 size_t num_bkpts = bkpt_array->GetSize();
Jim Ingham3acdf382016-09-22 22:20:28 +00001123 size_t num_names = names.size();
1124
Jim Ingham01f16662016-09-14 19:07:35 +00001125 for (size_t i = 0; i < num_bkpts; i++) {
1126 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1127 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1128 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1129 if (!bkpt_dict) {
1130 error.SetErrorStringWithFormat(
1131 "Invalid breakpoint data for element %zu from input file: %s.", i,
1132 file.GetPath().c_str());
1133 return error;
1134 }
1135 StructuredData::ObjectSP bkpt_data_sp =
1136 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
Jim Ingham3acdf382016-09-22 22:20:28 +00001137 if (num_names &&
1138 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1139 continue;
1140
Jim Ingham01f16662016-09-14 19:07:35 +00001141 BreakpointSP bkpt_sp =
1142 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1143 if (!error.Success()) {
1144 error.SetErrorStringWithFormat(
1145 "Error restoring breakpoint %zu from %s: %s.", i,
1146 file.GetPath().c_str(), error.AsCString());
1147 return error;
1148 }
1149 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1150 }
1151 return error;
1152}
1153
Johnny Chenedf50372011-09-23 21:21:43 +00001154// The flag 'end_to_end', default to true, signifies that the operation is
1155// performed end to end, for both the debugger and the debuggee.
1156
Johnny Chen01a67862011-10-14 00:42:25 +00001157// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1158// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159bool Target::RemoveAllWatchpoints(bool end_to_end) {
1160 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1161 if (log)
1162 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001163
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 if (!end_to_end) {
1165 m_watchpoint_list.RemoveAll(true);
1166 return true;
1167 }
Johnny Chenedf50372011-09-23 21:21:43 +00001168
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001170
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 if (!ProcessIsValid())
1172 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001173
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 size_t num_watchpoints = m_watchpoint_list.GetSize();
1175 for (size_t i = 0; i < num_watchpoints; ++i) {
1176 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1177 if (!wp_sp)
1178 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001179
Zachary Turner97206d52017-05-12 04:51:55 +00001180 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 if (rc.Fail())
1182 return false;
1183 }
1184 m_watchpoint_list.RemoveAll(true);
1185 m_last_created_watchpoint.reset();
1186 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001187}
1188
Adrian Prantl05097242018-04-30 16:49:04 +00001189// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1190// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191bool Target::DisableAllWatchpoints(bool end_to_end) {
1192 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1193 if (log)
1194 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001195
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 if (!end_to_end) {
1197 m_watchpoint_list.SetEnabledAll(false);
1198 return true;
1199 }
Johnny Chenedf50372011-09-23 21:21:43 +00001200
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001202
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 if (!ProcessIsValid())
1204 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001205
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 size_t num_watchpoints = m_watchpoint_list.GetSize();
1207 for (size_t i = 0; i < num_watchpoints; ++i) {
1208 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1209 if (!wp_sp)
1210 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001211
Zachary Turner97206d52017-05-12 04:51:55 +00001212 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 if (rc.Fail())
1214 return false;
1215 }
1216 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001217}
1218
Adrian Prantl05097242018-04-30 16:49:04 +00001219// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1220// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221bool Target::EnableAllWatchpoints(bool end_to_end) {
1222 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1223 if (log)
1224 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001225
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 if (!end_to_end) {
1227 m_watchpoint_list.SetEnabledAll(true);
1228 return true;
1229 }
Johnny Chenedf50372011-09-23 21:21:43 +00001230
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (!ProcessIsValid())
1234 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 size_t num_watchpoints = m_watchpoint_list.GetSize();
1237 for (size_t i = 0; i < num_watchpoints; ++i) {
1238 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1239 if (!wp_sp)
1240 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001241
Zachary Turner97206d52017-05-12 04:51:55 +00001242 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 if (rc.Fail())
1244 return false;
1245 }
1246 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001247}
1248
Johnny Chena4d6bc92012-02-25 06:44:30 +00001249// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250bool Target::ClearAllWatchpointHitCounts() {
1251 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1252 if (log)
1253 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chena4d6bc92012-02-25 06:44:30 +00001254
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 size_t num_watchpoints = m_watchpoint_list.GetSize();
1256 for (size_t i = 0; i < num_watchpoints; ++i) {
1257 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1258 if (!wp_sp)
1259 return false;
Johnny Chena4d6bc92012-02-25 06:44:30 +00001260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 wp_sp->ResetHitCount();
1262 }
1263 return true; // Success!
Johnny Chena4d6bc92012-02-25 06:44:30 +00001264}
1265
Enrico Granata5e3fe042015-02-11 00:37:54 +00001266// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267bool Target::ClearAllWatchpointHistoricValues() {
1268 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1269 if (log)
1270 log->Printf("Target::%s\n", __FUNCTION__);
1271
1272 size_t num_watchpoints = m_watchpoint_list.GetSize();
1273 for (size_t i = 0; i < num_watchpoints; ++i) {
1274 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1275 if (!wp_sp)
1276 return false;
1277
1278 wp_sp->ResetHistoricValues();
1279 }
1280 return true; // Success!
Enrico Granata5e3fe042015-02-11 00:37:54 +00001281}
1282
Adrian Prantl05097242018-04-30 16:49:04 +00001283// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1284// these operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1286 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1287 if (log)
1288 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001289
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 if (!ProcessIsValid())
1291 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001292
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 size_t num_watchpoints = m_watchpoint_list.GetSize();
1294 for (size_t i = 0; i < num_watchpoints; ++i) {
1295 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1296 if (!wp_sp)
1297 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 wp_sp->SetIgnoreCount(ignore_count);
1300 }
1301 return true; // Success!
Johnny Chen6cc60e82011-10-05 21:35:46 +00001302}
1303
Johnny Chen01a67862011-10-14 00:42:25 +00001304// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1306 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1307 if (log)
1308 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001309
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001311 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312
1313 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1314 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001315 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 if (rc.Success())
1317 return true;
1318
1319 // Else, fallthrough.
1320 }
1321 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001322}
1323
Johnny Chen01a67862011-10-14 00:42:25 +00001324// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1326 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1327 if (log)
1328 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001329
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001331 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332
1333 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1334 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001335 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 if (rc.Success())
1337 return true;
1338
1339 // Else, fallthrough.
1340 }
1341 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001342}
1343
Johnny Chen01a67862011-10-14 00:42:25 +00001344// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1346 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1347 if (log)
1348 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001349
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1351 if (watch_to_remove_sp == m_last_created_watchpoint)
1352 m_last_created_watchpoint.reset();
1353
1354 if (DisableWatchpointByID(watch_id)) {
1355 m_watchpoint_list.Remove(watch_id, true);
1356 return true;
1357 }
1358 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001359}
1360
Johnny Chen01a67862011-10-14 00:42:25 +00001361// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1363 uint32_t ignore_count) {
1364 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1365 if (log)
1366 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001367
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 if (!ProcessIsValid())
Johnny Chen6cc60e82011-10-05 21:35:46 +00001369 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370
1371 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1372 if (wp_sp) {
1373 wp_sp->SetIgnoreCount(ignore_count);
1374 return true;
1375 }
1376 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001377}
1378
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379ModuleSP Target::GetExecutableModule() {
1380 // search for the first executable in the module list
1381 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1382 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1383 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1384 if (obj == nullptr)
1385 continue;
1386 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1387 return module_sp;
1388 }
1389 // as fall back return the first module loaded
1390 return m_images.GetModuleAtIndex(0);
Greg Claytonaa149cb2011-08-11 02:48:45 +00001391}
1392
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393Module *Target::GetExecutableModulePointer() {
1394 return GetExecutableModule().get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395}
1396
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1398 Target *target) {
Zachary Turner97206d52017-05-12 04:51:55 +00001399 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 StreamString feedback_stream;
1401 if (module_sp &&
1402 !module_sp->LoadScriptingResourceInTarget(target, error,
1403 &feedback_stream)) {
1404 if (error.AsCString())
1405 target->GetDebugger().GetErrorFile()->Printf(
1406 "unable to load scripting data for module %s - error reported was "
1407 "%s\n",
1408 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1409 error.AsCString());
1410 }
1411 if (feedback_stream.GetSize())
1412 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1413 feedback_stream.GetData());
Enrico Granata17598482012-11-08 02:22:02 +00001414}
1415
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416void Target::ClearModules(bool delete_locations) {
1417 ModulesDidUnload(m_images, delete_locations);
1418 m_section_load_history.Clear();
1419 m_images.Clear();
1420 m_scratch_type_system_map.Clear();
1421 m_ast_importer_sp.reset();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001422}
1423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424void Target::DidExec() {
1425 // When a process exec's we need to know about it so we can do some cleanup.
Pavel Labath13e37d42017-10-25 21:05:31 +00001426 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1427 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
Greg Claytonb35db632013-11-09 00:03:31 +00001428}
1429
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430void Target::SetExecutableModule(ModuleSP &executable_sp,
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001431 LoadDependentFiles load_dependent_files) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1433 ClearModules(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435 if (executable_sp) {
Pavel Labathf9d16472017-05-15 13:02:37 +00001436 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1437 Timer scoped_timer(func_cat,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 "Target::SetExecutableModule (executable = '%s')",
1439 executable_sp->GetFileSpec().GetPath().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001440
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 m_images.Append(executable_sp); // The first image is our executable file
Jason Molendae1b68ad2012-12-05 00:25:49 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 // If we haven't set an architecture yet, reset our architecture based on
1444 // what we found in the executable module.
Pavel Labath13e37d42017-10-25 21:05:31 +00001445 if (!m_arch.GetSpec().IsValid()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 m_arch = executable_sp->GetArchitecture();
Pavel Labath13e37d42017-10-25 21:05:31 +00001447 LLDB_LOG(log,
1448 "setting architecture to {0} ({1}) based on executable file",
1449 m_arch.GetSpec().GetArchitectureName(),
1450 m_arch.GetSpec().GetTriple().getTriple());
Jason Molendadad8af42015-11-10 04:11:37 +00001451 }
1452
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 FileSpecList dependent_files;
1454 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001455 bool load_dependents = true;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001456 switch (load_dependent_files) {
1457 case eLoadDependentsDefault:
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001458 load_dependents = executable_sp->IsExecutable();
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001459 break;
1460 case eLoadDependentsYes:
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001461 load_dependents = true;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001462 break;
1463 case eLoadDependentsNo:
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001464 load_dependents = false;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001465 break;
1466 }
Greg Clayton095eeaa2013-11-05 23:28:00 +00001467
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001468 if (executable_objfile && load_dependents) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 executable_objfile->GetDependentModules(dependent_files);
1470 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1471 FileSpec dependent_file_spec(
1472 dependent_files.GetFileSpecPointerAtIndex(i));
1473 FileSpec platform_dependent_file_spec;
Greg Clayton67cc0632012-08-22 17:17:09 +00001474 if (m_platform_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1476 platform_dependent_file_spec);
1477 else
1478 platform_dependent_file_spec = dependent_file_spec;
1479
Pavel Labath13e37d42017-10-25 21:05:31 +00001480 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 ModuleSP image_module_sp(GetSharedModule(module_spec));
1482 if (image_module_sp) {
1483 ObjectFile *objfile = image_module_sp->GetObjectFile();
1484 if (objfile)
1485 objfile->GetDependentModules(dependent_files);
1486 }
1487 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001488 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001490}
1491
Greg Clayton19c8f392018-08-06 16:56:10 +00001492bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
Pavel Labath13e37d42017-10-25 21:05:31 +00001494 bool missing_local_arch = !m_arch.GetSpec().IsValid();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001495 bool replace_local_arch = true;
1496 bool compatible_local_arch = false;
1497 ArchSpec other(arch_spec);
Greg Claytone72dfb32012-02-24 01:59:29 +00001498
Greg Clayton19c8f392018-08-06 16:56:10 +00001499 // Changing the architecture might mean that the currently selected platform
1500 // isn't compatible. Set the platform correctly if we are asked to do so,
1501 // otherwise assume the user will set the platform manually.
1502 if (set_platform) {
1503 if (other.IsValid()) {
1504 auto platform_sp = GetPlatform();
1505 if (!platform_sp ||
1506 !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1507 ArchSpec platform_arch;
1508 auto arch_platform_sp =
1509 Platform::GetPlatformForArchitecture(other, &platform_arch);
1510 if (arch_platform_sp) {
1511 SetPlatform(arch_platform_sp);
1512 if (platform_arch.IsValid())
1513 other = platform_arch;
1514 }
1515 }
1516 }
1517 }
1518
Kate Stoneb9c1b512016-09-06 20:57:50 +00001519 if (!missing_local_arch) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001520 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1521 other.MergeFrom(m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001522
Pavel Labath13e37d42017-10-25 21:05:31 +00001523 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524 compatible_local_arch = true;
1525 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1526 env_changed;
1527
Pavel Labath13e37d42017-10-25 21:05:31 +00001528 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001529 os_changed, os_ver_changed, env_changed);
1530
1531 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1532 replace_local_arch = false;
1533 }
1534 }
1535 }
1536
1537 if (compatible_local_arch || missing_local_arch) {
1538 // If we haven't got a valid arch spec, or the architectures are compatible
Adrian Prantl05097242018-04-30 16:49:04 +00001539 // update the architecture, unless the one we already have is more
1540 // specified
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 if (replace_local_arch)
1542 m_arch = other;
Pavel Labath13e37d42017-10-25 21:05:31 +00001543 LLDB_LOG(log, "set architecture to {0} ({1})",
1544 m_arch.GetSpec().GetArchitectureName(),
1545 m_arch.GetSpec().GetTriple().getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 return true;
1547 }
1548
1549 // If we have an executable file, try to reset the executable to the desired
1550 // architecture
1551 if (log)
1552 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1553 arch_spec.GetArchitectureName(),
1554 arch_spec.GetTriple().getTriple().c_str());
1555 m_arch = other;
1556 ModuleSP executable_sp = GetExecutableModule();
1557
1558 ClearModules(true);
1559 // Need to do something about unsetting breakpoints.
1560
1561 if (executable_sp) {
1562 if (log)
1563 log->Printf("Target::SetArchitecture Trying to select executable file "
1564 "architecture %s (%s)",
1565 arch_spec.GetArchitectureName(),
1566 arch_spec.GetTriple().getTriple().c_str());
1567 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
Zachary Turner97206d52017-05-12 04:51:55 +00001568 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1569 &GetExecutableSearchPaths(),
1570 nullptr, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001571
1572 if (!error.Fail() && executable_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001573 SetExecutableModule(executable_sp, eLoadDependentsYes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574 return true;
1575 }
1576 }
1577 return false;
Greg Claytondb598232011-01-07 01:57:07 +00001578}
1579
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
Jason Molendadf9f7962018-10-23 23:45:56 +00001581 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 if (arch_spec.IsValid()) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001583 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001584 // The current target arch is compatible with "arch_spec", see if we can
1585 // improve our current architecture using bits from "arch_spec"
Greg Claytonc749eb82011-07-11 05:12:02 +00001586
Jason Molendadf9f7962018-10-23 23:45:56 +00001587 if (log)
1588 log->Printf("Target::MergeArchitecture target has arch %s, merging with "
1589 "arch %s",
1590 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1591 arch_spec.GetTriple().getTriple().c_str());
1592
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 // Merge bits from arch_spec into "merged_arch" and set our architecture
Pavel Labath13e37d42017-10-25 21:05:31 +00001594 ArchSpec merged_arch(m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 merged_arch.MergeFrom(arch_spec);
1596 return SetArchitecture(merged_arch);
1597 } else {
1598 // The new architecture is different, we just need to replace it
1599 return SetArchitecture(arch_spec);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001600 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601 }
1602 return false;
1603}
Greg Claytonc749eb82011-07-11 05:12:02 +00001604
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605void Target::WillClearList(const ModuleList &module_list) {}
1606
1607void Target::ModuleAdded(const ModuleList &module_list,
1608 const ModuleSP &module_sp) {
1609 // A module is being added to this target for the first time
1610 if (m_valid) {
1611 ModuleList my_module_list;
1612 my_module_list.Append(module_sp);
1613 LoadScriptingResourceForModule(module_sp, this);
1614 ModulesDidLoad(my_module_list);
1615 }
1616}
1617
1618void Target::ModuleRemoved(const ModuleList &module_list,
1619 const ModuleSP &module_sp) {
1620 // A module is being removed from this target.
1621 if (m_valid) {
1622 ModuleList my_module_list;
1623 my_module_list.Append(module_sp);
1624 ModulesDidUnload(my_module_list, false);
1625 }
1626}
1627
1628void Target::ModuleUpdated(const ModuleList &module_list,
1629 const ModuleSP &old_module_sp,
1630 const ModuleSP &new_module_sp) {
1631 // A module is replacing an already added module
1632 if (m_valid) {
1633 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1634 new_module_sp);
1635 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1636 old_module_sp, new_module_sp);
1637 }
1638}
1639
1640void Target::ModulesDidLoad(ModuleList &module_list) {
1641 if (m_valid && module_list.GetSize()) {
1642 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1643 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1644 if (m_process_sp) {
1645 m_process_sp->ModulesDidLoad(module_list);
1646 }
1647 BroadcastEvent(eBroadcastBitModulesLoaded,
1648 new TargetEventData(this->shared_from_this(), module_list));
1649 }
1650}
1651
1652void Target::SymbolsDidLoad(ModuleList &module_list) {
1653 if (m_valid && module_list.GetSize()) {
1654 if (m_process_sp) {
1655 LanguageRuntime *runtime =
1656 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1657 if (runtime) {
1658 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1659 objc_runtime->SymbolsDidLoad(module_list);
1660 }
1661 }
1662
1663 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1664 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1665 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1666 new TargetEventData(this->shared_from_this(), module_list));
1667 }
1668}
1669
1670void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1671 if (m_valid && module_list.GetSize()) {
1672 UnloadModuleSections(module_list);
1673 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1674 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1675 delete_locations);
1676 BroadcastEvent(eBroadcastBitModulesUnloaded,
1677 new TargetEventData(this->shared_from_this(), module_list));
1678 }
1679}
1680
1681bool Target::ModuleIsExcludedForUnconstrainedSearches(
1682 const FileSpec &module_file_spec) {
1683 if (GetBreakpointsConsultPlatformAvoidList()) {
1684 ModuleList matchingModules;
1685 ModuleSpec module_spec(module_file_spec);
1686 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1687
1688 // If there is more than one module for this file spec, only return true if
1689 // ALL the modules are on the
1690 // black list.
1691 if (num_modules > 0) {
1692 for (size_t i = 0; i < num_modules; i++) {
1693 if (!ModuleIsExcludedForUnconstrainedSearches(
1694 matchingModules.GetModuleAtIndex(i)))
1695 return false;
1696 }
1697 return true;
1698 }
1699 }
1700 return false;
1701}
1702
1703bool Target::ModuleIsExcludedForUnconstrainedSearches(
1704 const lldb::ModuleSP &module_sp) {
1705 if (GetBreakpointsConsultPlatformAvoidList()) {
1706 if (m_platform_sp)
1707 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1708 module_sp);
1709 }
1710 return false;
1711}
1712
1713size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001714 size_t dst_len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 SectionSP section_sp(addr.GetSection());
1716 if (section_sp) {
1717 // If the contents of this section are encrypted, the on-disk file is
1718 // unusable. Read only from live memory.
1719 if (section_sp->IsEncrypted()) {
1720 error.SetErrorString("section is encrypted");
1721 return 0;
1722 }
1723 ModuleSP module_sp(section_sp->GetModule());
1724 if (module_sp) {
1725 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1726 if (objfile) {
1727 size_t bytes_read = objfile->ReadSectionData(
1728 section_sp.get(), addr.GetOffset(), dst, dst_len);
Greg Claytondb598232011-01-07 01:57:07 +00001729 if (bytes_read > 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001731 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732 error.SetErrorStringWithFormat("error reading data from section %s",
1733 section_sp->GetName().GetCString());
1734 } else
1735 error.SetErrorString("address isn't from a object file");
1736 } else
1737 error.SetErrorString("address isn't in a module");
1738 } else
1739 error.SetErrorString("address doesn't contain a section that points to a "
1740 "section in a object file");
1741
1742 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001743}
1744
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001746 void *dst, size_t dst_len, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747 lldb::addr_t *load_addr_ptr) {
1748 error.Clear();
1749
Adrian Prantl05097242018-04-30 16:49:04 +00001750 // if we end up reading this from process memory, we will fill this with the
1751 // actual load address
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 if (load_addr_ptr)
1753 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1754
1755 size_t bytes_read = 0;
1756
1757 addr_t load_addr = LLDB_INVALID_ADDRESS;
1758 addr_t file_addr = LLDB_INVALID_ADDRESS;
1759 Address resolved_addr;
1760 if (!addr.IsSectionOffset()) {
1761 SectionLoadList &section_load_list = GetSectionLoadList();
1762 if (section_load_list.IsEmpty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001763 // No sections are loaded, so we must assume we are not running yet and
1764 // anything we are given is a file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1766 // offset is the file address
1767 m_images.ResolveFileAddress(file_addr, resolved_addr);
1768 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001769 // We have at least one section loaded. This can be because we have
1770 // manually loaded some sections with "target modules load ..." or
1771 // because we have have a live process that has sections loaded through
1772 // the dynamic loader
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1774 // offset is the load address
1775 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1776 }
1777 }
1778 if (!resolved_addr.IsValid())
1779 resolved_addr = addr;
1780
1781 if (prefer_file_cache) {
1782 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1783 if (bytes_read > 0)
1784 return bytes_read;
1785 }
1786
1787 if (ProcessIsValid()) {
1788 if (load_addr == LLDB_INVALID_ADDRESS)
1789 load_addr = resolved_addr.GetLoadAddress(this);
1790
1791 if (load_addr == LLDB_INVALID_ADDRESS) {
1792 ModuleSP addr_module_sp(resolved_addr.GetModule());
1793 if (addr_module_sp && addr_module_sp->GetFileSpec())
Zachary Turner827d5d72016-12-16 04:27:00 +00001794 error.SetErrorStringWithFormatv(
1795 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1796 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 else
1798 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1799 resolved_addr.GetFileAddress());
1800 } else {
1801 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1802 if (bytes_read != dst_len) {
1803 if (error.Success()) {
1804 if (bytes_read == 0)
1805 error.SetErrorStringWithFormat(
1806 "read memory from 0x%" PRIx64 " failed", load_addr);
1807 else
1808 error.SetErrorStringWithFormat(
1809 "only %" PRIu64 " of %" PRIu64
1810 " bytes were read from memory at 0x%" PRIx64,
1811 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1812 }
1813 }
1814 if (bytes_read) {
1815 if (load_addr_ptr)
1816 *load_addr_ptr = load_addr;
1817 return bytes_read;
1818 }
Adrian Prantl05097242018-04-30 16:49:04 +00001819 // If the address is not section offset we have an address that doesn't
1820 // resolve to any address in any currently loaded shared libraries and we
1821 // failed to read memory so there isn't anything more we can do. If it is
1822 // section offset, we might be able to read cached memory from the object
1823 // file.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824 if (!resolved_addr.IsSectionOffset())
1825 return 0;
1826 }
1827 }
1828
1829 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001830 // If we didn't already try and read from the object file cache, then try
1831 // it after failing to read from the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001832 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1833 }
1834 return 0;
1835}
1836
1837size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001838 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001839 char buf[256];
1840 out_str.clear();
1841 addr_t curr_addr = addr.GetLoadAddress(this);
1842 Address address(addr);
1843 while (1) {
1844 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1845 if (length == 0)
1846 break;
1847 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00001848 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1849 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850 if (length == sizeof(buf) - 1)
1851 curr_addr += length;
1852 else
1853 break;
1854 address = Address(curr_addr);
1855 }
1856 return out_str.size();
1857}
1858
1859size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001860 size_t dst_max_len, Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001861 size_t total_cstr_len = 0;
1862 if (dst && dst_max_len) {
1863 result_error.Clear();
1864 // NULL out everything just to be safe
1865 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00001866 Status error;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001867 addr_t curr_addr = addr.GetLoadAddress(this);
1868 Address address(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001869
Adrian Prantl05097242018-04-30 16:49:04 +00001870 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1871 // this really needs to be tied to the memory cache subsystem's cache line
1872 // size, so leave this as a fixed constant.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873 const size_t cache_line_size = 512;
1874
1875 size_t bytes_left = dst_max_len - 1;
1876 char *curr_dst = dst;
1877
1878 while (bytes_left > 0) {
1879 addr_t cache_line_bytes_left =
1880 cache_line_size - (curr_addr % cache_line_size);
1881 addr_t bytes_to_read =
1882 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1883 size_t bytes_read =
1884 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1885
1886 if (bytes_read == 0) {
1887 result_error = error;
1888 dst[total_cstr_len] = '\0';
1889 break;
1890 }
1891 const size_t len = strlen(curr_dst);
1892
1893 total_cstr_len += len;
1894
1895 if (len < bytes_to_read)
1896 break;
1897
1898 curr_dst += bytes_read;
1899 curr_addr += bytes_read;
1900 bytes_left -= bytes_read;
1901 address = Address(curr_addr);
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001902 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 } else {
1904 if (dst == nullptr)
1905 result_error.SetErrorString("invalid arguments");
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001906 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907 result_error.Clear();
1908 }
1909 return total_cstr_len;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001910}
1911
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1913 bool prefer_file_cache,
1914 uint32_t byte_size, bool is_signed,
Zachary Turner97206d52017-05-12 04:51:55 +00001915 Scalar &scalar, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916 uint64_t uval;
1917
1918 if (byte_size <= sizeof(uval)) {
1919 size_t bytes_read =
1920 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1921 if (bytes_read == byte_size) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001922 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1923 m_arch.GetSpec().GetAddressByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924 lldb::offset_t offset = 0;
1925 if (byte_size <= 4)
1926 scalar = data.GetMaxU32(&offset, byte_size);
1927 else
1928 scalar = data.GetMaxU64(&offset, byte_size);
1929
1930 if (is_signed)
1931 scalar.SignExtend(byte_size * 8);
1932 return bytes_read;
1933 }
1934 } else {
1935 error.SetErrorStringWithFormat(
1936 "byte size of %u is too large for integer scalar type", byte_size);
1937 }
1938 return 0;
1939}
1940
1941uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1942 bool prefer_file_cache,
1943 size_t integer_byte_size,
1944 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00001945 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 Scalar scalar;
1947 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1948 false, scalar, error))
1949 return scalar.ULongLong(fail_value);
1950 return fail_value;
1951}
1952
1953bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001954 Status &error, Address &pointer_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 Scalar scalar;
1956 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
Pavel Labath13e37d42017-10-25 21:05:31 +00001957 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 error)) {
1959 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1960 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1961 SectionLoadList &section_load_list = GetSectionLoadList();
1962 if (section_load_list.IsEmpty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001963 // No sections are loaded, so we must assume we are not running yet and
1964 // anything we are given is a file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1966 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001967 // We have at least one section loaded. This can be because we have
1968 // manually loaded some sections with "target modules load ..." or
1969 // because we have have a live process that has sections loaded through
1970 // the dynamic loader
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1972 }
Adrian Prantl05097242018-04-30 16:49:04 +00001973 // We weren't able to resolve the pointer value, so just return an
1974 // address with no section
Kate Stoneb9c1b512016-09-06 20:57:50 +00001975 if (!pointer_addr.IsValid())
1976 pointer_addr.SetOffset(pointer_vm_addr);
1977 return true;
1978 }
1979 }
1980 return false;
1981}
1982
1983ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
Zachary Turner97206d52017-05-12 04:51:55 +00001984 Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985 ModuleSP module_sp;
1986
Zachary Turner97206d52017-05-12 04:51:55 +00001987 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988
1989 // First see if we already have this module in our module list. If we do,
Adrian Prantl05097242018-04-30 16:49:04 +00001990 // then we're done, we don't need to consult the shared modules list. But
1991 // only do this if we are passed a UUID.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992
1993 if (module_spec.GetUUID().IsValid())
1994 module_sp = m_images.FindFirstModule(module_spec);
1995
1996 if (!module_sp) {
1997 ModuleSP old_module_sp; // This will get filled in if we have a new version
1998 // of the library
1999 bool did_create_module = false;
2000
2001 // If there are image search path entries, try to use them first to acquire
2002 // a suitable image.
2003 if (m_image_search_paths.GetSize()) {
2004 ModuleSpec transformed_spec(module_spec);
2005 if (m_image_search_paths.RemapPath(
2006 module_spec.GetFileSpec().GetDirectory(),
2007 transformed_spec.GetFileSpec().GetDirectory())) {
2008 transformed_spec.GetFileSpec().GetFilename() =
2009 module_spec.GetFileSpec().GetFilename();
2010 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2011 &GetExecutableSearchPaths(),
2012 &old_module_sp, &did_create_module);
2013 }
2014 }
2015
2016 if (!module_sp) {
2017 // If we have a UUID, we can check our global shared module list in case
2018 // we already have it. If we don't have a valid UUID, then we can't since
2019 // the path in "module_spec" will be a platform path, and we will need to
2020 // let the platform find that file. For example, we could be asking for
2021 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2022 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2023 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2024 // cache.
2025 if (module_spec.GetUUID().IsValid()) {
2026 // We have a UUID, it is OK to check the global module list...
2027 error = ModuleList::GetSharedModule(module_spec, module_sp,
2028 &GetExecutableSearchPaths(),
2029 &old_module_sp, &did_create_module);
2030 }
2031
2032 if (!module_sp) {
2033 // The platform is responsible for finding and caching an appropriate
2034 // module in the shared module cache.
2035 if (m_platform_sp) {
2036 error = m_platform_sp->GetSharedModule(
2037 module_spec, m_process_sp.get(), module_sp,
2038 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
2039 } else {
2040 error.SetErrorString("no platform is currently set");
Greg Claytond16e1e52011-07-12 17:06:17 +00002041 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042 }
Greg Claytond16e1e52011-07-12 17:06:17 +00002043 }
Greg Claytond16e1e52011-07-12 17:06:17 +00002044
Kate Stoneb9c1b512016-09-06 20:57:50 +00002045 // We found a module that wasn't in our target list. Let's make sure that
Adrian Prantl05097242018-04-30 16:49:04 +00002046 // there wasn't an equivalent module in the list already, and if there was,
2047 // let's remove it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048 if (module_sp) {
2049 ObjectFile *objfile = module_sp->GetObjectFile();
2050 if (objfile) {
2051 switch (objfile->GetType()) {
2052 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2053 /// a program's execution state
2054 case ObjectFile::eTypeExecutable: /// A normal executable
2055 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2056 /// executable
2057 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2058 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2059 /// used during execution
2060 break;
2061 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2062 /// debug information
2063 if (error_ptr)
2064 error_ptr->SetErrorString("debug info files aren't valid target "
2065 "modules, please specify an executable");
2066 return ModuleSP();
2067 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2068 /// against but not used for
2069 /// execution
2070 if (error_ptr)
2071 error_ptr->SetErrorString("stub libraries aren't valid target "
2072 "modules, please specify an executable");
2073 return ModuleSP();
2074 default:
2075 if (error_ptr)
2076 error_ptr->SetErrorString(
2077 "unsupported file type, please specify an executable");
2078 return ModuleSP();
Greg Claytond16e1e52011-07-12 17:06:17 +00002079 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 // GetSharedModule is not guaranteed to find the old shared module, for
Adrian Prantl05097242018-04-30 16:49:04 +00002081 // instance in the common case where you pass in the UUID, it is only
2082 // going to find the one module matching the UUID. In fact, it has no
2083 // good way to know what the "old module" relevant to this target is,
2084 // since there might be many copies of a module with this file spec in
2085 // various running debug sessions, but only one of them will belong to
2086 // this target. So let's remove the UUID from the module list, and look
2087 // in the target's module list. Only do this if there is SOMETHING else
2088 // in the module spec...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 if (!old_module_sp) {
2090 if (module_spec.GetUUID().IsValid() &&
2091 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2092 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2093 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2094 module_spec_copy.GetUUID().Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096 ModuleList found_modules;
2097 size_t num_found =
2098 m_images.FindModules(module_spec_copy, found_modules);
2099 if (num_found == 1) {
2100 old_module_sp = found_modules.GetModuleAtIndex(0);
Jim Ingham4a94c912012-05-17 18:38:42 +00002101 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 }
Greg Claytonb69bb2e2012-04-27 00:58:27 +00002103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104
Jim Ingham7fca8c02017-04-28 00:51:06 +00002105 // Preload symbols outside of any lock, so hopefully we can do this for
2106 // each library in parallel.
2107 if (GetPreloadSymbols())
2108 module_sp->PreloadSymbols();
2109
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110 if (old_module_sp &&
2111 m_images.GetIndexForModule(old_module_sp.get()) !=
2112 LLDB_INVALID_INDEX32) {
2113 m_images.ReplaceModule(old_module_sp, module_sp);
2114 Module *old_module_ptr = old_module_sp.get();
2115 old_module_sp.reset();
2116 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2117 } else
2118 m_images.Append(module_sp);
2119 } else
2120 module_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122 }
2123 if (error_ptr)
2124 *error_ptr = error;
2125 return module_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126}
2127
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128TargetSP Target::CalculateTarget() { return shared_from_this(); }
2129
2130ProcessSP Target::CalculateProcess() { return m_process_sp; }
2131
2132ThreadSP Target::CalculateThread() { return ThreadSP(); }
2133
2134StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2135
2136void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2137 exe_ctx.Clear();
2138 exe_ctx.SetTargetPtr(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139}
2140
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141PathMappingList &Target::GetImageSearchPathList() {
2142 return m_image_search_paths;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143}
2144
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2146 void *baton) {
2147 Target *target = (Target *)baton;
2148 ModuleSP exe_module_sp(target->GetExecutableModule());
2149 if (exe_module_sp)
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00002150 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002151}
2152
Zachary Turner97206d52017-05-12 04:51:55 +00002153TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002154 lldb::LanguageType language,
2155 bool create_on_demand) {
2156 if (!m_valid)
2157 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 if (error) {
2160 error->Clear();
2161 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2164 // assembly code
2165 || language == eLanguageTypeUnknown) {
2166 std::set<lldb::LanguageType> languages_for_types;
2167 std::set<lldb::LanguageType> languages_for_expressions;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2170 languages_for_expressions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 if (languages_for_expressions.count(eLanguageTypeC)) {
2173 language = eLanguageTypeC; // LLDB's default. Override by setting the
2174 // target language.
2175 } else {
2176 if (languages_for_expressions.empty()) {
Greg Clayton5beec212015-10-08 21:04:34 +00002177 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 } else {
2179 language = *languages_for_expressions.begin();
2180 }
Sean Callanana994b0b2015-10-02 18:40:30 +00002181 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 }
Sean Callananb92bd752015-10-01 16:28:02 +00002183
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2185 create_on_demand);
Sean Callananb92bd752015-10-01 16:28:02 +00002186}
2187
2188PersistentExpressionState *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2190 TypeSystem *type_system =
2191 GetScratchTypeSystemForLanguage(nullptr, language, true);
2192
2193 if (type_system) {
2194 return type_system->GetPersistentExpressionState();
2195 } else {
2196 return nullptr;
2197 }
Jim Ingham151c0322015-09-15 21:13:50 +00002198}
2199
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200UserExpression *Target::GetUserExpressionForLanguage(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002201 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 Expression::ResultType desired_type,
Zachary Turner97206d52017-05-12 04:51:55 +00002203 const EvaluateExpressionOptions &options, Status &error) {
2204 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205
2206 TypeSystem *type_system =
2207 GetScratchTypeSystemForLanguage(&type_system_error, language);
2208 UserExpression *user_expr = nullptr;
2209
2210 if (!type_system) {
2211 error.SetErrorStringWithFormat(
2212 "Could not find type system for language %s: %s",
2213 Language::GetNameForLanguageType(language),
2214 type_system_error.AsCString());
2215 return nullptr;
2216 }
2217
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002218 user_expr = type_system->GetUserExpression(expr, prefix, language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 desired_type, options);
2220 if (!user_expr)
2221 error.SetErrorStringWithFormat(
2222 "Could not create an expression for language %s",
2223 Language::GetNameForLanguageType(language));
2224
2225 return user_expr;
Jim Ingham151c0322015-09-15 21:13:50 +00002226}
2227
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228FunctionCaller *Target::GetFunctionCallerForLanguage(
2229 lldb::LanguageType language, const CompilerType &return_type,
2230 const Address &function_address, const ValueList &arg_value_list,
Zachary Turner97206d52017-05-12 04:51:55 +00002231 const char *name, Status &error) {
2232 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 TypeSystem *type_system =
2234 GetScratchTypeSystemForLanguage(&type_system_error, language);
2235 FunctionCaller *persistent_fn = nullptr;
2236
2237 if (!type_system) {
2238 error.SetErrorStringWithFormat(
2239 "Could not find type system for language %s: %s",
2240 Language::GetNameForLanguageType(language),
2241 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002242 return persistent_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 }
2244
2245 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2246 arg_value_list, name);
2247 if (!persistent_fn)
2248 error.SetErrorStringWithFormat(
2249 "Could not create an expression for language %s",
2250 Language::GetNameForLanguageType(language));
2251
2252 return persistent_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002253}
2254
2255UtilityFunction *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256Target::GetUtilityFunctionForLanguage(const char *text,
2257 lldb::LanguageType language,
Zachary Turner97206d52017-05-12 04:51:55 +00002258 const char *name, Status &error) {
2259 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002260 TypeSystem *type_system =
2261 GetScratchTypeSystemForLanguage(&type_system_error, language);
2262 UtilityFunction *utility_fn = nullptr;
2263
2264 if (!type_system) {
2265 error.SetErrorStringWithFormat(
2266 "Could not find type system for language %s: %s",
2267 Language::GetNameForLanguageType(language),
2268 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002269 return utility_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270 }
2271
2272 utility_fn = type_system->GetUtilityFunction(text, name);
2273 if (!utility_fn)
2274 error.SetErrorStringWithFormat(
2275 "Could not create an expression for language %s",
2276 Language::GetNameForLanguageType(language));
2277
2278 return utility_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002279}
2280
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2282 if (m_valid) {
2283 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2284 nullptr, eLanguageTypeC, create_on_demand))
2285 return llvm::dyn_cast<ClangASTContext>(type_system);
2286 }
2287 return nullptr;
2288}
2289
2290ClangASTImporterSP Target::GetClangASTImporter() {
2291 if (m_valid) {
2292 if (!m_ast_importer_sp) {
2293 m_ast_importer_sp.reset(new ClangASTImporter());
Sean Callanan4bf80d52011-11-15 22:27:19 +00002294 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295 return m_ast_importer_sp;
2296 }
2297 return ClangASTImporterSP();
Sean Callananb92bd752015-10-01 16:28:02 +00002298}
2299
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2301
2302void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2303
2304FileSpecList Target::GetDefaultExecutableSearchPaths() {
2305 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2306 if (properties_sp)
2307 return properties_sp->GetExecutableSearchPaths();
2308 return FileSpecList();
Sean Callanan686b2312011-11-16 18:20:47 +00002309}
2310
Kate Stoneb9c1b512016-09-06 20:57:50 +00002311FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2312 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2313 if (properties_sp)
2314 return properties_sp->GetDebugFileSearchPaths();
2315 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002316}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002317
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2319 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2320 if (properties_sp)
2321 return properties_sp->GetClangModuleSearchPaths();
2322 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002323}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002324
Kate Stoneb9c1b512016-09-06 20:57:50 +00002325ArchSpec Target::GetDefaultArchitecture() {
2326 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2327 if (properties_sp)
2328 return properties_sp->GetDefaultArchitecture();
2329 return ArchSpec();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002330}
2331
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2333 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2334 if (properties_sp) {
2335 LogIfAnyCategoriesSet(
2336 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2337 "default architecture to %s (%s)",
2338 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2339 return properties_sp->SetDefaultArchitecture(arch);
2340 }
Michael Sartaina7499c92013-07-01 19:45:50 +00002341}
2342
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2344 const SymbolContext *sc_ptr) {
2345 // The target can either exist in the "process" of ExecutionContext, or in
2346 // the "target_sp" member of SymbolContext. This accessor helper function
2347 // will get the target from one of these locations.
2348
2349 Target *target = nullptr;
2350 if (sc_ptr != nullptr)
2351 target = sc_ptr->target_sp.get();
2352 if (target == nullptr && exe_ctx_ptr)
2353 target = exe_ctx_ptr->GetTargetPtr();
2354 return target;
Sean Callanan85054342015-04-03 15:39:47 +00002355}
2356
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357ExpressionResults Target::EvaluateExpression(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002358 llvm::StringRef expr, ExecutionContextScope *exe_scope,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 lldb::ValueObjectSP &result_valobj_sp,
2360 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2361 result_valobj_sp.reset();
Caroline Ticedaccaa92010-09-20 20:44:43 +00002362
Kate Stoneb9c1b512016-09-06 20:57:50 +00002363 ExpressionResults execution_results = eExpressionSetupError;
Caroline Ticedaccaa92010-09-20 20:44:43 +00002364
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002365 if (expr.empty())
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002366 return execution_results;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367
Adrian Prantl05097242018-04-30 16:49:04 +00002368 // We shouldn't run stop hooks in expressions. Be sure to reset this if you
2369 // return anywhere within this function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002370 bool old_suppress_value = m_suppress_stop_hooks;
2371 m_suppress_stop_hooks = true;
2372
2373 ExecutionContext exe_ctx;
2374
2375 if (exe_scope) {
2376 exe_scope->CalculateExecutionContext(exe_ctx);
2377 } else if (m_process_sp) {
2378 m_process_sp->CalculateExecutionContext(exe_ctx);
2379 } else {
2380 CalculateExecutionContext(exe_ctx);
2381 }
2382
Adrian Prantl05097242018-04-30 16:49:04 +00002383 // Make sure we aren't just trying to see the value of a persistent variable
2384 // (something like "$0")
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385 lldb::ExpressionVariableSP persistent_var_sp;
2386 // Only check for persistent variables the expression starts with a '$'
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002387 if (expr[0] == '$')
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2389 ->GetPersistentExpressionState()
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002390 ->GetVariable(expr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002391
2392 if (persistent_var_sp) {
2393 result_valobj_sp = persistent_var_sp->GetValueObject();
2394 execution_results = eExpressionCompleted;
2395 } else {
Pavel Labath50251fc2017-12-21 10:54:30 +00002396 llvm::StringRef prefix = GetExpressionPrefixContents();
Zachary Turner97206d52017-05-12 04:51:55 +00002397 Status error;
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002398 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2399 result_valobj_sp, error,
2400 0, // Line Number
2401 fixed_expression);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 }
2403
2404 m_suppress_stop_hooks = old_suppress_value;
2405
2406 return execution_results;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002407}
2408
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002409lldb::ExpressionVariableSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410Target::GetPersistentVariable(const ConstString &name) {
2411 lldb::ExpressionVariableSP variable_sp;
2412 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002413 [name, &variable_sp](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 if (PersistentExpressionState *persistent_state =
2415 type_system->GetPersistentExpressionState()) {
2416 variable_sp = persistent_state->GetVariable(name);
Greg Clayton5beec212015-10-08 21:04:34 +00002417
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 if (variable_sp)
2419 return false; // Stop iterating the ForEach
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002420 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002421 return true; // Keep iterating the ForEach
2422 });
2423 return variable_sp;
Zachary Turner32abc6e2015-03-03 19:23:09 +00002424}
2425
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2427 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2428
2429 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002430 [name, &address](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002431 if (PersistentExpressionState *persistent_state =
2432 type_system->GetPersistentExpressionState()) {
2433 address = persistent_state->LookupSymbol(name);
2434 if (address != LLDB_INVALID_ADDRESS)
2435 return false; // Stop iterating the ForEach
Sean Callananb92bd752015-10-01 16:28:02 +00002436 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002437 return true; // Keep iterating the ForEach
2438 });
2439 return address;
Sean Callananb92bd752015-10-01 16:28:02 +00002440}
2441
Kate Stoneb9c1b512016-09-06 20:57:50 +00002442lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2443 AddressClass addr_class) const {
Tatyana Krasnukha7aa9e7b2018-09-21 18:56:44 +00002444 auto arch_plugin = GetArchitecturePlugin();
2445 return arch_plugin ?
2446 arch_plugin->GetCallableLoadAddress(load_addr, addr_class) : load_addr;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002447}
2448
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2450 AddressClass addr_class) const {
Tatyana Krasnukha7aa9e7b2018-09-21 18:56:44 +00002451 auto arch_plugin = GetArchitecturePlugin();
2452 return arch_plugin ?
2453 arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class) : load_addr;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002454}
2455
Kate Stoneb9c1b512016-09-06 20:57:50 +00002456lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
Tatyana Krasnukha7aa9e7b2018-09-21 18:56:44 +00002457 auto arch_plugin = GetArchitecturePlugin();
2458 return arch_plugin ?
2459 arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002460}
2461
2462SourceManager &Target::GetSourceManager() {
2463 if (!m_source_manager_ap)
2464 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2465 return *m_source_manager_ap;
2466}
2467
2468ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2469 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2470 // we can make it
2471 // per-target
2472
2473 {
2474 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2475
2476 if (!m_clang_modules_decl_vendor_ap) {
2477 m_clang_modules_decl_vendor_ap.reset(
2478 ClangModulesDeclVendor::Create(*this));
2479 }
2480 }
2481
2482 return m_clang_modules_decl_vendor_ap.get();
2483}
2484
2485Target::StopHookSP Target::CreateStopHook() {
2486 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2487 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2488 m_stop_hooks[new_uid] = stop_hook_sp;
2489 return stop_hook_sp;
2490}
2491
2492bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2493 size_t num_removed = m_stop_hooks.erase(user_id);
2494 return (num_removed != 0);
2495}
2496
2497void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2498
2499Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2500 StopHookSP found_hook;
2501
2502 StopHookCollection::iterator specified_hook_iter;
2503 specified_hook_iter = m_stop_hooks.find(user_id);
2504 if (specified_hook_iter != m_stop_hooks.end())
2505 found_hook = (*specified_hook_iter).second;
2506 return found_hook;
2507}
2508
2509bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2510 bool active_state) {
2511 StopHookCollection::iterator specified_hook_iter;
2512 specified_hook_iter = m_stop_hooks.find(user_id);
2513 if (specified_hook_iter == m_stop_hooks.end())
2514 return false;
2515
2516 (*specified_hook_iter).second->SetIsActive(active_state);
2517 return true;
2518}
2519
2520void Target::SetAllStopHooksActiveState(bool active_state) {
2521 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2522 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2523 (*pos).second->SetIsActive(active_state);
2524 }
2525}
2526
2527void Target::RunStopHooks() {
2528 if (m_suppress_stop_hooks)
2529 return;
2530
2531 if (!m_process_sp)
2532 return;
Jim Ingham45816d62017-12-05 02:34:05 +00002533
2534 // Somebody might have restarted the process:
2535 if (m_process_sp->GetState() != eStateStopped)
2536 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002537
2538 // <rdar://problem/12027563> make sure we check that we are not stopped
Adrian Prantl05097242018-04-30 16:49:04 +00002539 // because of us running a user expression since in that case we do not want
2540 // to run the stop-hooks
Kate Stoneb9c1b512016-09-06 20:57:50 +00002541 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2542 return;
2543
2544 if (m_stop_hooks.empty())
2545 return;
2546
2547 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2548
2549 // If there aren't any active stop hooks, don't bother either:
2550 bool any_active_hooks = false;
2551 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2552 if ((*pos).second->IsActive()) {
2553 any_active_hooks = true;
2554 break;
2555 }
2556 }
2557 if (!any_active_hooks)
2558 return;
2559
2560 CommandReturnObject result;
2561
2562 std::vector<ExecutionContext> exc_ctx_with_reasons;
2563 std::vector<SymbolContext> sym_ctx_with_reasons;
2564
2565 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2566 size_t num_threads = cur_threadlist.GetSize();
2567 for (size_t i = 0; i < num_threads; i++) {
2568 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2569 if (cur_thread_sp->ThreadStoppedForAReason()) {
2570 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2571 exc_ctx_with_reasons.push_back(ExecutionContext(
2572 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2573 sym_ctx_with_reasons.push_back(
2574 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2575 }
2576 }
2577
2578 // If no threads stopped for a reason, don't run the stop-hooks.
2579 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2580 if (num_exe_ctx == 0)
2581 return;
2582
2583 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2584 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2585
2586 bool keep_going = true;
2587 bool hooks_ran = false;
2588 bool print_hook_header = (m_stop_hooks.size() != 1);
2589 bool print_thread_header = (num_exe_ctx != 1);
2590
2591 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2592 // result.Clear();
2593 StopHookSP cur_hook_sp = (*pos).second;
2594 if (!cur_hook_sp->IsActive())
2595 continue;
2596
2597 bool any_thread_matched = false;
2598 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2599 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2600 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2601 sym_ctx_with_reasons[i])) &&
2602 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2603 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2604 exc_ctx_with_reasons[i].GetThreadRef()))) {
2605 if (!hooks_ran) {
2606 hooks_ran = true;
2607 }
2608 if (print_hook_header && !any_thread_matched) {
2609 const char *cmd =
2610 (cur_hook_sp->GetCommands().GetSize() == 1
2611 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2612 : nullptr);
2613 if (cmd)
2614 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2615 cur_hook_sp->GetID(), cmd);
2616 else
2617 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2618 cur_hook_sp->GetID());
2619 any_thread_matched = true;
2620 }
2621
2622 if (print_thread_header)
2623 result.AppendMessageWithFormat(
2624 "-- Thread %d\n",
2625 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2626
2627 CommandInterpreterRunOptions options;
2628 options.SetStopOnContinue(true);
2629 options.SetStopOnError(true);
2630 options.SetEchoCommands(false);
2631 options.SetPrintResults(true);
2632 options.SetAddToHistory(false);
2633
2634 GetDebugger().GetCommandInterpreter().HandleCommands(
2635 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2636 result);
2637
2638 // If the command started the target going again, we should bag out of
2639 // running the stop hooks.
2640 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2641 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
Jim Ingham45816d62017-12-05 02:34:05 +00002642 // But only complain if there were more stop hooks to do:
2643 StopHookCollection::iterator tmp = pos;
2644 if (++tmp != end)
2645 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2646 " set the program running.\n",
2647 cur_hook_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648 keep_going = false;
2649 }
2650 }
2651 }
2652 }
2653
2654 result.GetImmediateOutputStream()->Flush();
2655 result.GetImmediateErrorStream()->Flush();
2656}
2657
2658const TargetPropertiesSP &Target::GetGlobalProperties() {
2659 // NOTE: intentional leak so we don't crash if global destructor chain gets
2660 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +00002661 static TargetPropertiesSP *g_settings_sp_ptr =
2662 new TargetPropertiesSP(new TargetProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002663 return *g_settings_sp_ptr;
2664}
2665
Zachary Turner97206d52017-05-12 04:51:55 +00002666Status Target::Install(ProcessLaunchInfo *launch_info) {
2667 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002668 PlatformSP platform_sp(GetPlatform());
2669 if (platform_sp) {
2670 if (platform_sp->IsRemote()) {
2671 if (platform_sp->IsConnected()) {
2672 // Install all files that have an install path, and always install the
2673 // main executable when connected to a remote platform
2674 const ModuleList &modules = GetImages();
2675 const size_t num_images = modules.GetSize();
2676 for (size_t idx = 0; idx < num_images; ++idx) {
2677 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2678 if (module_sp) {
2679 const bool is_main_executable = module_sp == GetExecutableModule();
2680 FileSpec local_file(module_sp->GetFileSpec());
2681 if (local_file) {
2682 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2683 if (!remote_file) {
2684 if (is_main_executable) // TODO: add setting for always
2685 // installing main executable???
2686 {
2687 // Always install the main executable
2688 remote_file = platform_sp->GetRemoteWorkingDirectory();
2689 remote_file.AppendPathComponent(
2690 module_sp->GetFileSpec().GetFilename().GetCString());
2691 }
2692 }
2693 if (remote_file) {
2694 error = platform_sp->Install(local_file, remote_file);
2695 if (error.Success()) {
2696 module_sp->SetPlatformFileSpec(remote_file);
2697 if (is_main_executable) {
2698 platform_sp->SetFilePermissions(remote_file, 0700);
2699 if (launch_info)
2700 launch_info->SetExecutableFile(remote_file, false);
2701 }
2702 } else
2703 break;
2704 }
2705 }
2706 }
2707 }
2708 }
2709 }
2710 }
2711 return error;
2712}
2713
2714bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2715 uint32_t stop_id) {
2716 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2717}
2718
2719bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2720 Address &resolved_addr) {
2721 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2722}
2723
2724bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2725 addr_t new_section_load_addr,
2726 bool warn_multiple) {
2727 const addr_t old_section_load_addr =
2728 m_section_load_history.GetSectionLoadAddress(
2729 SectionLoadHistory::eStopIDNow, section_sp);
2730 if (old_section_load_addr != new_section_load_addr) {
2731 uint32_t stop_id = 0;
2732 ProcessSP process_sp(GetProcessSP());
2733 if (process_sp)
2734 stop_id = process_sp->GetStopID();
Greg Claytonb09c5382013-12-13 17:20:18 +00002735 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002736 stop_id = m_section_load_history.GetLastStopID();
2737 if (m_section_load_history.SetSectionLoadAddress(
2738 stop_id, section_sp, new_section_load_addr, warn_multiple))
2739 return true; // Return true if the section load address was changed...
2740 }
2741 return false; // Return false to indicate nothing changed
2742}
Todd Fialaac33cc92014-10-09 01:02:08 +00002743
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2745 size_t section_unload_count = 0;
2746 size_t num_modules = module_list.GetSize();
2747 for (size_t i = 0; i < num_modules; ++i) {
2748 section_unload_count +=
2749 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2750 }
2751 return section_unload_count;
2752}
Todd Fiala015d8182014-07-22 23:41:36 +00002753
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2755 uint32_t stop_id = 0;
2756 ProcessSP process_sp(GetProcessSP());
2757 if (process_sp)
2758 stop_id = process_sp->GetStopID();
2759 else
2760 stop_id = m_section_load_history.GetLastStopID();
2761 SectionList *sections = module_sp->GetSectionList();
2762 size_t section_unload_count = 0;
2763 if (sections) {
2764 const uint32_t num_sections = sections->GetNumSections(0);
2765 for (uint32_t i = 0; i < num_sections; ++i) {
2766 section_unload_count += m_section_load_history.SetSectionUnloaded(
2767 stop_id, sections->GetSectionAtIndex(i));
Greg Claytonb09c5382013-12-13 17:20:18 +00002768 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002769 }
2770 return section_unload_count;
2771}
2772
2773bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2774 uint32_t stop_id = 0;
2775 ProcessSP process_sp(GetProcessSP());
2776 if (process_sp)
2777 stop_id = process_sp->GetStopID();
2778 else
2779 stop_id = m_section_load_history.GetLastStopID();
2780 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2781}
2782
2783bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2784 addr_t load_addr) {
2785 uint32_t stop_id = 0;
2786 ProcessSP process_sp(GetProcessSP());
2787 if (process_sp)
2788 stop_id = process_sp->GetStopID();
2789 else
2790 stop_id = m_section_load_history.GetLastStopID();
2791 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2792 load_addr);
2793}
2794
2795void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2796
Zachary Turner97206d52017-05-12 04:51:55 +00002797Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2798 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2800
2801 if (log)
2802 log->Printf("Target::%s() called for %s", __FUNCTION__,
2803 launch_info.GetExecutableFile().GetPath().c_str());
2804
2805 StateType state = eStateInvalid;
2806
2807 // Scope to temporarily get the process state in case someone has manually
2808 // remotely connected already to a process and we can skip the platform
2809 // launching.
2810 {
2811 ProcessSP process_sp(GetProcessSP());
2812
2813 if (process_sp) {
2814 state = process_sp->GetState();
2815 if (log)
2816 log->Printf(
2817 "Target::%s the process exists, and its current state is %s",
2818 __FUNCTION__, StateAsCString(state));
2819 } else {
2820 if (log)
2821 log->Printf("Target::%s the process instance doesn't currently exist.",
2822 __FUNCTION__);
2823 }
2824 }
2825
2826 launch_info.GetFlags().Set(eLaunchFlagDebug);
2827
2828 // Get the value of synchronous execution here. If you wait till after you
Adrian Prantl05097242018-04-30 16:49:04 +00002829 // have started to run, then you could have hit a breakpoint, whose command
2830 // might switch the value, and then you'll pick up that incorrect value.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 Debugger &debugger = GetDebugger();
2832 const bool synchronous_execution =
2833 debugger.GetCommandInterpreter().GetSynchronous();
2834
2835 PlatformSP platform_sp(GetPlatform());
2836
Adrian Prantl05097242018-04-30 16:49:04 +00002837 // Finalize the file actions, and if none were given, default to opening up a
2838 // pseudo terminal
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2840 if (log)
2841 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2842 "default_to_use_pty=%s",
2843 __FUNCTION__, platform_sp ? "true" : "false",
2844 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2845 : "n/a",
2846 default_to_use_pty ? "true" : "false");
2847
2848 launch_info.FinalizeFileActions(this, default_to_use_pty);
2849
2850 if (state == eStateConnected) {
2851 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2852 error.SetErrorString(
2853 "can't launch in tty when launching through a remote connection");
2854 return error;
2855 }
2856 }
2857
2858 if (!launch_info.GetArchitecture().IsValid())
2859 launch_info.GetArchitecture() = GetArchitecture();
2860
2861 // If we're not already connected to the process, and if we have a platform
2862 // that can launch a process for debugging, go ahead and do that here.
2863 if (state != eStateConnected && platform_sp &&
2864 platform_sp->CanDebugProcess()) {
2865 if (log)
2866 log->Printf("Target::%s asking the platform to debug the process",
2867 __FUNCTION__);
2868
Jim Ingham362d0222018-12-18 01:49:02 +00002869 // If there was a previous process, delete it before we make the new one.
2870 // One subtle point, we delete the process before we release the reference
2871 // to m_process_sp. That way even if we are the last owner, the process
2872 // will get Finalized before it gets destroyed.
2873 DeleteCurrentProcess();
2874
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 m_process_sp =
2876 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2877
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 } else {
2879 if (log)
2880 log->Printf("Target::%s the platform doesn't know how to debug a "
2881 "process, getting a process plugin to do this for us.",
2882 __FUNCTION__);
2883
2884 if (state == eStateConnected) {
2885 assert(m_process_sp);
2886 } else {
2887 // Use a Process plugin to construct the process.
2888 const char *plugin_name = launch_info.GetProcessPluginName();
Pavel Labathcb8c6992019-01-07 10:59:57 +00002889 CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
Greg Claytonb09c5382013-12-13 17:20:18 +00002890 }
2891
Kate Stoneb9c1b512016-09-06 20:57:50 +00002892 // Since we didn't have a platform launch the process, launch it here.
2893 if (m_process_sp)
2894 error = m_process_sp->Launch(launch_info);
2895 }
2896
2897 if (!m_process_sp) {
Greg Claytonb09c5382013-12-13 17:20:18 +00002898 if (error.Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 error.SetErrorString("failed to launch or debug process");
Greg Claytonb09c5382013-12-13 17:20:18 +00002900 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002901 }
2902
2903 if (error.Success()) {
2904 if (synchronous_execution ||
2905 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2906 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2907 if (!hijack_listener_sp) {
2908 hijack_listener_sp =
2909 Listener::MakeListener("lldb.Target.Launch.hijack");
2910 launch_info.SetHijackListener(hijack_listener_sp);
2911 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2912 }
2913
2914 StateType state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002915 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002916
2917 if (state == eStateStopped) {
2918 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2919 if (synchronous_execution) {
2920 error = m_process_sp->PrivateResume();
2921 if (error.Success()) {
2922 state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002923 llvm::None, nullptr, true, hijack_listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002924 const bool must_be_alive =
2925 false; // eStateExited is ok, so this must be false
2926 if (!StateIsStoppedState(state, must_be_alive)) {
2927 error.SetErrorStringWithFormat("process isn't stopped: %s",
2928 StateAsCString(state));
2929 }
2930 }
2931 } else {
2932 m_process_sp->RestoreProcessEvents();
2933 error = m_process_sp->PrivateResume();
2934 }
2935 if (!error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +00002936 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002937 error2.SetErrorStringWithFormat(
2938 "process resume at entry point failed: %s", error.AsCString());
2939 error = error2;
2940 }
2941 }
2942 } else if (state == eStateExited) {
2943 bool with_shell = !!launch_info.GetShell();
2944 const int exit_status = m_process_sp->GetExitStatus();
2945 const char *exit_desc = m_process_sp->GetExitDescription();
2946#define LAUNCH_SHELL_MESSAGE \
2947 "\n'r' and 'run' are aliases that default to launching through a " \
2948 "shell.\nTry launching without going through a shell by using 'process " \
2949 "launch'."
2950 if (exit_desc && exit_desc[0]) {
2951 if (with_shell)
2952 error.SetErrorStringWithFormat(
2953 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2954 exit_status, exit_desc);
2955 else
2956 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2957 exit_status, exit_desc);
2958 } else {
2959 if (with_shell)
2960 error.SetErrorStringWithFormat(
2961 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2962 exit_status);
2963 else
2964 error.SetErrorStringWithFormat("process exited with status %i",
2965 exit_status);
2966 }
2967 } else {
2968 error.SetErrorStringWithFormat(
2969 "initial process state wasn't stopped: %s", StateAsCString(state));
2970 }
2971 }
2972 m_process_sp->RestoreProcessEvents();
2973 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00002974 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002975 error2.SetErrorStringWithFormat("process launch failed: %s",
2976 error.AsCString());
2977 error = error2;
2978 }
2979 return error;
Greg Claytonb09c5382013-12-13 17:20:18 +00002980}
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002981
Zachary Turner97206d52017-05-12 04:51:55 +00002982Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002983 auto state = eStateInvalid;
2984 auto process_sp = GetProcessSP();
2985 if (process_sp) {
2986 state = process_sp->GetState();
2987 if (process_sp->IsAlive() && state != eStateConnected) {
2988 if (state == eStateAttaching)
Zachary Turner97206d52017-05-12 04:51:55 +00002989 return Status("process attach is in progress");
2990 return Status("a process is already being debugged");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002991 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002993
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 const ModuleSP old_exec_module_sp = GetExecutableModule();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002995
Adrian Prantl05097242018-04-30 16:49:04 +00002996 // If no process info was specified, then use the target executable name as
2997 // the process to attach to by default
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 if (!attach_info.ProcessInfoSpecified()) {
2999 if (old_exec_module_sp)
3000 attach_info.GetExecutableFile().GetFilename() =
3001 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003002
Kate Stoneb9c1b512016-09-06 20:57:50 +00003003 if (!attach_info.ProcessInfoSpecified()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003004 return Status("no process specified, create a target with a file, or "
3005 "specify the --pid or --name");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003006 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003008
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 const auto platform_sp =
3010 GetDebugger().GetPlatformList().GetSelectedPlatform();
3011 ListenerSP hijack_listener_sp;
3012 const bool async = attach_info.GetAsync();
3013 if (!async) {
3014 hijack_listener_sp =
3015 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3016 attach_info.SetHijackListener(hijack_listener_sp);
3017 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003018
Zachary Turner97206d52017-05-12 04:51:55 +00003019 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020 if (state != eStateConnected && platform_sp != nullptr &&
3021 platform_sp->CanDebugProcess()) {
3022 SetPlatform(platform_sp);
3023 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3024 } else {
3025 if (state != eStateConnected) {
3026 const char *plugin_name = attach_info.GetProcessPluginName();
3027 process_sp =
3028 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3029 plugin_name, nullptr);
3030 if (process_sp == nullptr) {
3031 error.SetErrorStringWithFormat(
3032 "failed to create process using plugin %s",
3033 (plugin_name) ? plugin_name : "null");
3034 return error;
3035 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003036 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 if (hijack_listener_sp)
3038 process_sp->HijackProcessEvents(hijack_listener_sp);
3039 error = process_sp->Attach(attach_info);
3040 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003041
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 if (error.Success() && process_sp) {
3043 if (async) {
3044 process_sp->RestoreProcessEvents();
3045 } else {
3046 state = process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003047 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003048 process_sp->RestoreProcessEvents();
3049
3050 if (state != eStateStopped) {
3051 const char *exit_desc = process_sp->GetExitDescription();
3052 if (exit_desc)
3053 error.SetErrorStringWithFormat("%s", exit_desc);
Greg Claytone75e5d82015-10-20 00:14:20 +00003054 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055 error.SetErrorString(
3056 "process did not stop (no such process or permission problem?)");
3057 process_sp->Destroy(false);
3058 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003059 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003060 }
3061 return error;
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003062}
3063
Jim Ingham9575d842011-03-11 03:53:59 +00003064//--------------------------------------------------------------
Greg Claytonfbb76342013-11-20 21:07:01 +00003065// Target::StopHook
Jim Ingham9575d842011-03-11 03:53:59 +00003066//--------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003067Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3068 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3069 m_thread_spec_ap(), m_active(true) {}
3070
3071Target::StopHook::StopHook(const StopHook &rhs)
3072 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3073 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3074 m_thread_spec_ap(), m_active(rhs.m_active) {
3075 if (rhs.m_thread_spec_ap)
3076 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
Jim Ingham9575d842011-03-11 03:53:59 +00003077}
3078
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003079Target::StopHook::~StopHook() = default;
Jim Ingham9575d842011-03-11 03:53:59 +00003080
Kate Stoneb9c1b512016-09-06 20:57:50 +00003081void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3082 m_specifier_sp.reset(specifier);
Zachary Turner32abc6e2015-03-03 19:23:09 +00003083}
3084
Kate Stoneb9c1b512016-09-06 20:57:50 +00003085void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3086 m_thread_spec_ap.reset(specifier);
Jim Ingham9575d842011-03-11 03:53:59 +00003087}
Jim Ingham9575d842011-03-11 03:53:59 +00003088
Kate Stoneb9c1b512016-09-06 20:57:50 +00003089void Target::StopHook::GetDescription(Stream *s,
3090 lldb::DescriptionLevel level) const {
3091 int indent_level = s->GetIndentLevel();
Jim Ingham9575d842011-03-11 03:53:59 +00003092
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 s->SetIndentLevel(indent_level + 2);
3094
3095 s->Printf("Hook: %" PRIu64 "\n", GetID());
3096 if (m_active)
3097 s->Indent("State: enabled\n");
3098 else
3099 s->Indent("State: disabled\n");
3100
3101 if (m_specifier_sp) {
3102 s->Indent();
3103 s->PutCString("Specifier:\n");
3104 s->SetIndentLevel(indent_level + 4);
3105 m_specifier_sp->GetDescription(s, level);
Jim Ingham9575d842011-03-11 03:53:59 +00003106 s->SetIndentLevel(indent_level + 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107 }
Jim Ingham9575d842011-03-11 03:53:59 +00003108
Kate Stoneb9c1b512016-09-06 20:57:50 +00003109 if (m_thread_spec_ap) {
3110 StreamString tmp;
3111 s->Indent("Thread:\n");
3112 m_thread_spec_ap->GetDescription(&tmp, level);
3113 s->SetIndentLevel(indent_level + 4);
Zachary Turnerc1564272016-11-16 21:15:24 +00003114 s->Indent(tmp.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 s->PutCString("\n");
3116 s->SetIndentLevel(indent_level + 2);
3117 }
Jim Ingham9575d842011-03-11 03:53:59 +00003118
Kate Stoneb9c1b512016-09-06 20:57:50 +00003119 s->Indent("Commands: \n");
3120 s->SetIndentLevel(indent_level + 4);
3121 uint32_t num_commands = m_commands.GetSize();
3122 for (uint32_t i = 0; i < num_commands; i++) {
3123 s->Indent(m_commands.GetStringAtIndex(i));
3124 s->PutCString("\n");
3125 }
3126 s->SetIndentLevel(indent_level);
Jim Ingham9575d842011-03-11 03:53:59 +00003127}
3128
Greg Clayton67cc0632012-08-22 17:17:09 +00003129//--------------------------------------------------------------
3130// class TargetProperties
3131//--------------------------------------------------------------
3132
Jonas Devliegheree103ae92018-11-15 01:18:15 +00003133// clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003134static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135 {eNoDynamicValues, "no-dynamic-values",
3136 "Don't calculate the dynamic type of values"},
3137 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3138 "even if you have to run the target."},
3139 {eDynamicDontRunTarget, "no-run-target",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003140 "Calculate the dynamic type of values, but don't run the target."} };
Caroline Ticedaccaa92010-09-20 20:44:43 +00003141
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003142OptionEnumValues lldb_private::GetDynamicValueTypes() {
3143 return OptionEnumValues(g_dynamic_value_types);
3144}
3145
3146static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3148 "locations (fastest). This setting "
3149 "should only be used if you know that "
3150 "no inlining occurs in your programs."},
3151 {eInlineBreakpointsHeaders, "headers",
3152 "Only check for inline breakpoint locations when setting breakpoints in "
3153 "header files, but not when setting breakpoint in implementation source "
3154 "files (default)."},
3155 {eInlineBreakpointsAlways, "always",
3156 "Always look for inline breakpoint locations when setting file and line "
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003157 "breakpoints (slower but most accurate)."} };
Greg Clayton1f746072012-08-29 21:13:06 +00003158
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159typedef enum x86DisassemblyFlavor {
3160 eX86DisFlavorDefault,
3161 eX86DisFlavorIntel,
3162 eX86DisFlavorATT
Jim Ingham0f063ba2013-03-02 00:26:47 +00003163} x86DisassemblyFlavor;
3164
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003165static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003166 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3167 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003168 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003169
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003170static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003171 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003172 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003173
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003174static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 {eLoadScriptFromSymFileTrue, "true",
3176 "Load debug scripts inside symbol files"},
3177 {eLoadScriptFromSymFileFalse, "false",
3178 "Do not load debug scripts inside symbol files."},
3179 {eLoadScriptFromSymFileWarn, "warn",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003180 "Warn about debug scripts inside symbol files but do not load them."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003181
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003182static constexpr
3183OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003184 {eLoadCWDlldbinitTrue, "true",
3185 "Load .lldbinit files from current directory"},
3186 {eLoadCWDlldbinitFalse, "false",
3187 "Do not load .lldbinit files from current directory"},
3188 {eLoadCWDlldbinitWarn, "warn",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003189 "Warn about loading .lldbinit files from current directory"} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003190
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003191static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003192 {eMemoryModuleLoadLevelMinimal, "minimal",
3193 "Load minimal information when loading modules from memory. Currently "
3194 "this setting loads sections only."},
3195 {eMemoryModuleLoadLevelPartial, "partial",
3196 "Load partial information when loading modules from memory. Currently "
3197 "this setting loads sections and function bounds."},
3198 {eMemoryModuleLoadLevelComplete, "complete",
3199 "Load complete information when loading modules from memory. Currently "
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003200 "this setting loads sections and all symbols."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003201
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003202static constexpr PropertyDefinition g_properties[] = {
3203 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003204 "Default architecture to choose, when there's a choice."},
3205 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003206 {}, "Move breakpoints to nearest code."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003207 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003208 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003209 "The language to use when interpreting expressions entered in commands."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003210 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 "Path to a file containing expressions to be prepended to all "
3212 "expressions."},
3213 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003214 eDynamicDontRunTarget, nullptr, OptionEnumValues(g_dynamic_value_types),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 "Should printed values be shown as their dynamic value."},
3216 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003217 {}, "Should synthetic values be used by default whenever available."},
3218 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003219 "Skip function prologues when setting breakpoints by name."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003220 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221 "Source path remappings are used to track the change of location between "
3222 "a source file when built, and "
3223 "where it exists on the current system. It consists of an array of "
3224 "duples, the first element of each duple is "
3225 "some part (starting at the root) of the path to the file when it was "
3226 "built, "
3227 "and the second is where the remainder of the original build hierarchy is "
3228 "rooted on the local system. "
3229 "Each element of the array is checked in order and the first one that "
3230 "results in a match wins."},
3231 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003232 {}, "Executable search paths to use when locating executable files "
3233 "whose paths don't match the local file system."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003235 nullptr, {},
Jan Kratochvil4c993ce2019-01-03 23:11:06 +00003236 "List of directories to be searched when locating debug symbol files. "
3237 "See also symbols.enable-external-lookup."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003239 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003240 "List of directories to be searched when locating modules for Clang."},
3241 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003242 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 "Automatically load Clang modules referred to by the program."},
3244 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003245 {}, "Automatically apply fix-it hints to expressions."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003246 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003247 {}, "Print the fixed expression text."},
Sean Callanan5deb06e2016-09-26 20:18:51 +00003248 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003249 {}, "Save intermediate object files generated by the LLVM JIT"},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003251 {}, "Maximum number of children to expand in any level of depth."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003252 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003253 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003254 "Maximum number of characters to show when using %s in summary strings."},
3255 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003256 {}, "Maximum number of bytes that 'memory read' will fetch before "
3257 "--force must be specified."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003258 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003259 true, nullptr, {}, "Consult the platform module avoid list when "
3260 "setting non-module specific breakpoints."},
3261 {"arg0", OptionValue::eTypeString, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003262 "The first argument passed to the program in the argument array which can "
3263 "be different from the executable itself."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003264 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 "A list containing all the arguments to be passed to the executable when "
3266 "it is run. Note that this does NOT include the argv[0] which is in "
3267 "target.arg0."},
3268 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003269 nullptr, {}, "A list of all the environment variables to be passed "
3270 "to the executable's environment, and their values."},
3271 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003272 "Inherit the environment from the process that is running LLDB."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003273 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274 "The file/path to be used by the executable program for reading its "
3275 "standard input."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003276 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277 "The file/path to be used by the executable program for writing its "
3278 "standard output."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003279 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003280 "The file/path to be used by the executable program for writing its "
3281 "standard error."},
3282 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003283 {}, "debugserver will detach (rather than killing) a process if it "
Kate Stoneb9c1b512016-09-06 20:57:50 +00003284 "loses connection with lldb."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003285 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, {},
Jim Ingham7fca8c02017-04-28 00:51:06 +00003286 "Enable loading of symbol tables before they are needed."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003287 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288 "Disable Address Space Layout Randomization (ASLR)"},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003289 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003290 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3291 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003292 eInlineBreakpointsAlways, nullptr,
3293 OptionEnumValues(g_inline_breakpoint_enums),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003294 "The strategy to use when settings breakpoints by file and line. "
3295 "Breakpoint locations can end up being inlined by the compiler, so that a "
3296 "compile unit 'a.c' might contain an inlined function from another source "
3297 "file. "
3298 "Usually this is limited to breakpoint locations from inlined functions "
3299 "from header or other include files, or more accurately "
3300 "non-implementation source files. "
3301 "Sometimes code might #include implementation files and cause inlined "
3302 "breakpoint locations in inlined implementation files. "
3303 "Always checking for inlined breakpoint locations can be expensive "
3304 "(memory and time), so if you have a project with many headers "
3305 "and find that setting breakpoints is slow, then you can change this "
3306 "setting to headers. "
3307 "This setting allows you to control exactly which strategy is used when "
3308 "setting "
3309 "file and line breakpoints."},
3310 // FIXME: This is the wrong way to do per-architecture settings, but we
3311 // don't have a general per architecture settings system in place yet.
3312 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003313 eX86DisFlavorDefault, nullptr,
3314 OptionEnumValues(g_x86_dis_flavor_value_types),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003315 "The default disassembly flavor to use for x86 or x86-64 targets."},
3316 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003317 {}, "Show immediates in disassembly as hexadecimal."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003318 {"hex-immediate-style", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003319 Disassembler::eHexStyleC, nullptr,
3320 OptionEnumValues(g_hex_immediate_style_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003321 "Which style to use for printing hexadecimal disassembly values."},
3322 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003323 {}, "Use a fast stepping algorithm based on running from branch to "
3324 "branch rather than instruction single-stepping."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003325 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003326 eLoadScriptFromSymFileWarn, nullptr,
3327 OptionEnumValues(g_load_script_from_sym_file_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003328 "Allow LLDB to load scripting resources embedded in symbol files when "
3329 "available."},
3330 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003331 nullptr, OptionEnumValues(g_load_current_working_dir_lldbinit_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003332 "Allow LLDB to .lldbinit files from the current directory automatically."},
3333 {"memory-module-load-level", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003334 eMemoryModuleLoadLevelComplete, nullptr,
3335 OptionEnumValues(g_memory_module_load_level_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003336 "Loading modules from memory can be slow as reading the symbol tables and "
3337 "other data can take a long time depending on your connection to the "
3338 "debug target. "
3339 "This setting helps users control how much information gets loaded when "
3340 "loading modules from memory."
3341 "'complete' is the default value for this setting which will load all "
3342 "sections and symbols by reading them from memory (slowest, most "
3343 "accurate). "
3344 "'partial' will load sections and attempt to find function bounds without "
3345 "downloading the symbol table (faster, still accurate, missing symbol "
3346 "names). "
3347 "'minimal' is the fastest setting and will load section data with no "
3348 "symbols, but should rarely be used as stack frames in these memory "
3349 "regions will be inaccurate and not provide any context (fastest). "},
3350 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003351 nullptr, {}, "Expressions that crash will show up in crash logs if "
3352 "the host system supports executable specific crash log "
3353 "strings and this setting is set to true."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003354 {"trap-handler-names", OptionValue::eTypeArray, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003355 OptionValue::eTypeString, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003356 "A list of trap handler function names, e.g. a common Unix user process "
3357 "one is _sigtramp."},
3358 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003359 nullptr, {}, "If true, LLDB will show variables that are meant to "
3360 "support the operation of a language's runtime support."},
Kuba Mracek4c7f5d52018-12-20 23:38:19 +00003361 {"display-recognized-arguments", OptionValue::eTypeBoolean, false, false,
3362 nullptr, {}, "Show recognized arguments in variable listings by default."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003363 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, {},
Jonas Devliegheree103ae92018-11-15 01:18:15 +00003364 "Disable lock-step debugging, instead control threads independently."},
3365 {"require-hardware-breakpoint", OptionValue::eTypeBoolean, false, 0,
3366 nullptr, {}, "Require all breakpoints to be hardware breakpoints."}};
3367// clang-format on
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368
3369enum {
3370 ePropertyDefaultArch,
3371 ePropertyMoveToNearestCode,
3372 ePropertyLanguage,
3373 ePropertyExprPrefix,
3374 ePropertyPreferDynamic,
3375 ePropertyEnableSynthetic,
3376 ePropertySkipPrologue,
3377 ePropertySourceMap,
3378 ePropertyExecutableSearchPaths,
3379 ePropertyDebugFileSearchPaths,
3380 ePropertyClangModuleSearchPaths,
3381 ePropertyAutoImportClangModules,
3382 ePropertyAutoApplyFixIts,
3383 ePropertyNotifyAboutFixIts,
Sean Callanan5deb06e2016-09-26 20:18:51 +00003384 ePropertySaveObjects,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003385 ePropertyMaxChildrenCount,
3386 ePropertyMaxSummaryLength,
3387 ePropertyMaxMemReadSize,
3388 ePropertyBreakpointUseAvoidList,
3389 ePropertyArg0,
3390 ePropertyRunArgs,
3391 ePropertyEnvVars,
3392 ePropertyInheritEnv,
3393 ePropertyInputPath,
3394 ePropertyOutputPath,
3395 ePropertyErrorPath,
3396 ePropertyDetachOnError,
Jim Ingham7fca8c02017-04-28 00:51:06 +00003397 ePropertyPreloadSymbols,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003398 ePropertyDisableASLR,
3399 ePropertyDisableSTDIO,
3400 ePropertyInlineStrategy,
3401 ePropertyDisassemblyFlavor,
3402 ePropertyUseHexImmediates,
3403 ePropertyHexImmediateStyle,
3404 ePropertyUseFastStepping,
3405 ePropertyLoadScriptFromSymbolFile,
3406 ePropertyLoadCWDlldbinitFile,
3407 ePropertyMemoryModuleLoadLevel,
3408 ePropertyDisplayExpressionsInCrashlogs,
3409 ePropertyTrapHandlerNames,
3410 ePropertyDisplayRuntimeSupportValues,
Kuba Mracek4c7f5d52018-12-20 23:38:19 +00003411 ePropertyDisplayRecognizedArguments,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003412 ePropertyNonStopModeEnabled,
Jonas Devliegheree103ae92018-11-15 01:18:15 +00003413 ePropertyRequireHardwareBreakpoints,
3414 ePropertyExperimental,
Jim Ingham0f063ba2013-03-02 00:26:47 +00003415};
3416
Kate Stoneb9c1b512016-09-06 20:57:50 +00003417class TargetOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +00003418public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 TargetOptionValueProperties(const ConstString &name)
3420 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
Caroline Ticedaccaa92010-09-20 20:44:43 +00003421
Kate Stoneb9c1b512016-09-06 20:57:50 +00003422 // This constructor is used when creating TargetOptionValueProperties when it
3423 // is part of a new lldb_private::Target instance. It will copy all current
3424 // global property values as needed
3425 TargetOptionValueProperties(Target *target,
3426 const TargetPropertiesSP &target_properties_sp)
3427 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3428 m_target(target), m_got_host_env(false) {}
Greg Clayton67cc0632012-08-22 17:17:09 +00003429
Kate Stoneb9c1b512016-09-06 20:57:50 +00003430 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3431 bool will_modify,
3432 uint32_t idx) const override {
3433 // When getting the value for a key from the target options, we will always
Adrian Prantl05097242018-04-30 16:49:04 +00003434 // try and grab the setting from the current target if there is one. Else
3435 // we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003436 if (idx == ePropertyEnvVars)
3437 GetHostEnvironmentIfNeeded();
3438
3439 if (exe_ctx) {
3440 Target *target = exe_ctx->GetTargetPtr();
3441 if (target) {
3442 TargetOptionValueProperties *target_properties =
3443 static_cast<TargetOptionValueProperties *>(
3444 target->GetValueProperties().get());
3445 if (this != target_properties)
3446 return target_properties->ProtectedGetPropertyAtIndex(idx);
3447 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003448 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003449 return ProtectedGetPropertyAtIndex(idx);
3450 }
3451
3452 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3453
Greg Clayton67cc0632012-08-22 17:17:09 +00003454protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003455 void GetHostEnvironmentIfNeeded() const {
3456 if (!m_got_host_env) {
3457 if (m_target) {
3458 m_got_host_env = true;
3459 const uint32_t idx = ePropertyInheritEnv;
3460 if (GetPropertyAtIndexAsBoolean(
3461 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3462 PlatformSP platform_sp(m_target->GetPlatform());
3463 if (platform_sp) {
Pavel Labath62930e52018-01-10 11:57:31 +00003464 Environment env = platform_sp->GetEnvironment();
3465 OptionValueDictionary *env_dict =
3466 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3467 ePropertyEnvVars);
3468 if (env_dict) {
3469 const bool can_replace = false;
3470 for (const auto &KV : env) {
3471 // Don't allow existing keys to be replaced with ones we get
3472 // from the platform environment
3473 env_dict->SetValueForKey(
3474 ConstString(KV.first()),
3475 OptionValueSP(new OptionValueString(KV.second.c_str())),
3476 can_replace);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003477 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003480 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003483 }
3484 Target *m_target;
3485 mutable bool m_got_host_env;
Greg Clayton67cc0632012-08-22 17:17:09 +00003486};
3487
Greg Claytonfbb76342013-11-20 21:07:01 +00003488//----------------------------------------------------------------------
3489// TargetProperties
3490//----------------------------------------------------------------------
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003491static constexpr PropertyDefinition g_experimental_properties[]{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003492 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003493 {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494 "If true, inject local variables explicitly into the expression text. "
3495 "This will fix symbol resolution when there are name collisions between "
3496 "ivars and local variables. "
3497 "But it can make expressions run much more slowly."},
Sean Callanan68e44232017-09-28 20:20:25 +00003498 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukhae40db052018-09-27 07:11:58 +00003499 {}, "If true, use Clang's modern type lookup infrastructure."}};
Jim Inghambed67792016-07-07 18:25:48 +00003500
Sean Callanan68e44232017-09-28 20:20:25 +00003501enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
Jim Inghambed67792016-07-07 18:25:48 +00003502
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503class TargetExperimentalOptionValueProperties : public OptionValueProperties {
Jim Inghambed67792016-07-07 18:25:48 +00003504public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505 TargetExperimentalOptionValueProperties()
3506 : OptionValueProperties(
3507 ConstString(Properties::GetExperimentalSettingsName())) {}
Jim Inghambed67792016-07-07 18:25:48 +00003508};
3509
Kate Stoneb9c1b512016-09-06 20:57:50 +00003510TargetExperimentalProperties::TargetExperimentalProperties()
3511 : Properties(OptionValuePropertiesSP(
3512 new TargetExperimentalOptionValueProperties())) {
3513 m_collection_sp->Initialize(g_experimental_properties);
Jim Inghambed67792016-07-07 18:25:48 +00003514}
3515
3516//----------------------------------------------------------------------
3517// TargetProperties
3518//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519TargetProperties::TargetProperties(Target *target)
3520 : Properties(), m_launch_info() {
3521 if (target) {
3522 m_collection_sp.reset(
3523 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
Ilia K8f37ca52015-02-13 14:31:06 +00003524
Adrian Prantl05097242018-04-30 16:49:04 +00003525 // Set callbacks to update launch_info whenever "settins set" updated any
3526 // of these properties
Kate Stoneb9c1b512016-09-06 20:57:50 +00003527 m_collection_sp->SetValueChangedCallback(
3528 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3529 m_collection_sp->SetValueChangedCallback(
3530 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3531 m_collection_sp->SetValueChangedCallback(
3532 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3533 m_collection_sp->SetValueChangedCallback(
3534 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3535 this);
3536 m_collection_sp->SetValueChangedCallback(
3537 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3538 this);
3539 m_collection_sp->SetValueChangedCallback(
3540 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3541 this);
3542 m_collection_sp->SetValueChangedCallback(
3543 ePropertyDetachOnError,
3544 TargetProperties::DetachOnErrorValueChangedCallback, this);
3545 m_collection_sp->SetValueChangedCallback(
3546 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3547 this);
3548 m_collection_sp->SetValueChangedCallback(
3549 ePropertyDisableSTDIO,
3550 TargetProperties::DisableSTDIOValueChangedCallback, this);
Jim Inghambed67792016-07-07 18:25:48 +00003551
Kate Stoneb9c1b512016-09-06 20:57:50 +00003552 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3553 m_collection_sp->AppendProperty(
3554 ConstString(Properties::GetExperimentalSettingsName()),
3555 ConstString("Experimental settings - setting these won't produce "
3556 "errors if the setting is not present."),
3557 true, m_experimental_properties_up->GetValueProperties());
Jim Inghambed67792016-07-07 18:25:48 +00003558
Kate Stoneb9c1b512016-09-06 20:57:50 +00003559 // Update m_launch_info once it was created
3560 Arg0ValueChangedCallback(this, nullptr);
3561 RunArgsValueChangedCallback(this, nullptr);
3562 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3563 // Target::GetPlatform()
3564 InputPathValueChangedCallback(this, nullptr);
3565 OutputPathValueChangedCallback(this, nullptr);
3566 ErrorPathValueChangedCallback(this, nullptr);
3567 DetachOnErrorValueChangedCallback(this, nullptr);
3568 DisableASLRValueChangedCallback(this, nullptr);
3569 DisableSTDIOValueChangedCallback(this, nullptr);
3570 } else {
3571 m_collection_sp.reset(
3572 new TargetOptionValueProperties(ConstString("target")));
3573 m_collection_sp->Initialize(g_properties);
3574 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3575 m_collection_sp->AppendProperty(
3576 ConstString(Properties::GetExperimentalSettingsName()),
3577 ConstString("Experimental settings - setting these won't produce "
3578 "errors if the setting is not present."),
3579 true, m_experimental_properties_up->GetValueProperties());
3580 m_collection_sp->AppendProperty(
3581 ConstString("process"), ConstString("Settings specific to processes."),
3582 true, Process::GetGlobalProperties()->GetValueProperties());
3583 }
Caroline Ticedaccaa92010-09-20 20:44:43 +00003584}
3585
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003586TargetProperties::~TargetProperties() = default;
3587
Kate Stoneb9c1b512016-09-06 20:57:50 +00003588bool TargetProperties::GetInjectLocalVariables(
3589 ExecutionContext *exe_ctx) const {
3590 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3591 exe_ctx, false, ePropertyExperimental);
3592 OptionValueProperties *exp_values =
3593 exp_property->GetValue()->GetAsProperties();
3594 if (exp_values)
3595 return exp_values->GetPropertyAtIndexAsBoolean(
3596 exe_ctx, ePropertyInjectLocalVars, true);
3597 else
3598 return true;
Jim Inghambed67792016-07-07 18:25:48 +00003599}
3600
Kate Stoneb9c1b512016-09-06 20:57:50 +00003601void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3602 bool b) {
3603 const Property *exp_property =
3604 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3605 OptionValueProperties *exp_values =
3606 exp_property->GetValue()->GetAsProperties();
3607 if (exp_values)
3608 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3609 true);
Jim Inghambed67792016-07-07 18:25:48 +00003610}
3611
Sean Callanan68e44232017-09-28 20:20:25 +00003612bool TargetProperties::GetUseModernTypeLookup() const {
3613 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3614 nullptr, false, ePropertyExperimental);
3615 OptionValueProperties *exp_values =
3616 exp_property->GetValue()->GetAsProperties();
3617 if (exp_values)
3618 return exp_values->GetPropertyAtIndexAsBoolean(
3619 nullptr, ePropertyUseModernTypeLookup, true);
3620 else
3621 return true;
3622}
3623
Kate Stoneb9c1b512016-09-06 20:57:50 +00003624ArchSpec TargetProperties::GetDefaultArchitecture() const {
3625 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3626 nullptr, ePropertyDefaultArch);
3627 if (value)
3628 return value->GetCurrentValue();
3629 return ArchSpec();
Greg Clayton67cc0632012-08-22 17:17:09 +00003630}
3631
Kate Stoneb9c1b512016-09-06 20:57:50 +00003632void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3633 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3634 nullptr, ePropertyDefaultArch);
3635 if (value)
3636 return value->SetCurrentValue(arch, true);
Greg Clayton67cc0632012-08-22 17:17:09 +00003637}
3638
Kate Stoneb9c1b512016-09-06 20:57:50 +00003639bool TargetProperties::GetMoveToNearestCode() const {
3640 const uint32_t idx = ePropertyMoveToNearestCode;
3641 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3642 nullptr, idx, g_properties[idx].default_uint_value != 0);
Ilia K055ad9b2015-05-18 13:41:01 +00003643}
3644
Kate Stoneb9c1b512016-09-06 20:57:50 +00003645lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3646 const uint32_t idx = ePropertyPreferDynamic;
3647 return (lldb::DynamicValueType)
3648 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3649 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003650}
3651
Kate Stoneb9c1b512016-09-06 20:57:50 +00003652bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3653 const uint32_t idx = ePropertyPreferDynamic;
3654 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
Greg Clayton15484402015-05-15 18:40:24 +00003655}
3656
Jim Ingham7fca8c02017-04-28 00:51:06 +00003657bool TargetProperties::GetPreloadSymbols() const {
3658 const uint32_t idx = ePropertyPreloadSymbols;
3659 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3660 nullptr, idx, g_properties[idx].default_uint_value != 0);
3661}
3662
3663void TargetProperties::SetPreloadSymbols(bool b) {
3664 const uint32_t idx = ePropertyPreloadSymbols;
3665 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3666}
3667
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668bool TargetProperties::GetDisableASLR() const {
3669 const uint32_t idx = ePropertyDisableASLR;
3670 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3671 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003672}
3673
Kate Stoneb9c1b512016-09-06 20:57:50 +00003674void TargetProperties::SetDisableASLR(bool b) {
3675 const uint32_t idx = ePropertyDisableASLR;
3676 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003677}
3678
Kate Stoneb9c1b512016-09-06 20:57:50 +00003679bool TargetProperties::GetDetachOnError() const {
3680 const uint32_t idx = ePropertyDetachOnError;
3681 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3682 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham106d0282014-06-25 02:32:56 +00003683}
3684
Kate Stoneb9c1b512016-09-06 20:57:50 +00003685void TargetProperties::SetDetachOnError(bool b) {
3686 const uint32_t idx = ePropertyDetachOnError;
3687 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Jim Ingham106d0282014-06-25 02:32:56 +00003688}
3689
Kate Stoneb9c1b512016-09-06 20:57:50 +00003690bool TargetProperties::GetDisableSTDIO() const {
3691 const uint32_t idx = ePropertyDisableSTDIO;
3692 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3693 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003694}
3695
Kate Stoneb9c1b512016-09-06 20:57:50 +00003696void TargetProperties::SetDisableSTDIO(bool b) {
3697 const uint32_t idx = ePropertyDisableSTDIO;
3698 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003699}
3700
Kate Stoneb9c1b512016-09-06 20:57:50 +00003701const char *TargetProperties::GetDisassemblyFlavor() const {
3702 const uint32_t idx = ePropertyDisassemblyFlavor;
3703 const char *return_value;
3704
3705 x86DisassemblyFlavor flavor_value =
3706 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3707 nullptr, idx, g_properties[idx].default_uint_value);
3708 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3709 return return_value;
Jim Ingham0f063ba2013-03-02 00:26:47 +00003710}
3711
Kate Stoneb9c1b512016-09-06 20:57:50 +00003712InlineStrategy TargetProperties::GetInlineStrategy() const {
3713 const uint32_t idx = ePropertyInlineStrategy;
3714 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3715 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton1f746072012-08-29 21:13:06 +00003716}
3717
Zachary Turner31d97a52016-11-17 18:08:12 +00003718llvm::StringRef TargetProperties::GetArg0() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003719 const uint32_t idx = ePropertyArg0;
Zachary Turner31d97a52016-11-17 18:08:12 +00003720 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
Greg Clayton45392552012-10-17 22:57:12 +00003721}
3722
Zachary Turner31d97a52016-11-17 18:08:12 +00003723void TargetProperties::SetArg0(llvm::StringRef arg) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003724 const uint32_t idx = ePropertyArg0;
Zachary Turner514d8cd2016-09-23 18:06:53 +00003725 m_collection_sp->SetPropertyAtIndexAsString(
Zachary Turner31d97a52016-11-17 18:08:12 +00003726 nullptr, idx, arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003727 m_launch_info.SetArg0(arg);
Greg Clayton45392552012-10-17 22:57:12 +00003728}
3729
Kate Stoneb9c1b512016-09-06 20:57:50 +00003730bool TargetProperties::GetRunArguments(Args &args) const {
3731 const uint32_t idx = ePropertyRunArgs;
3732 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +00003733}
3734
Kate Stoneb9c1b512016-09-06 20:57:50 +00003735void TargetProperties::SetRunArguments(const Args &args) {
3736 const uint32_t idx = ePropertyRunArgs;
3737 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3738 m_launch_info.GetArguments() = args;
Greg Clayton67cc0632012-08-22 17:17:09 +00003739}
3740
Pavel Labath62930e52018-01-10 11:57:31 +00003741Environment TargetProperties::GetEnvironment() const {
3742 // TODO: Get rid of the Args intermediate step
3743 Args env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003744 const uint32_t idx = ePropertyEnvVars;
Pavel Labath62930e52018-01-10 11:57:31 +00003745 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3746 return Environment(env);
Greg Clayton67cc0632012-08-22 17:17:09 +00003747}
3748
Pavel Labath62930e52018-01-10 11:57:31 +00003749void TargetProperties::SetEnvironment(Environment env) {
3750 // TODO: Get rid of the Args intermediate step
Kate Stoneb9c1b512016-09-06 20:57:50 +00003751 const uint32_t idx = ePropertyEnvVars;
Pavel Labath62930e52018-01-10 11:57:31 +00003752 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3753 m_launch_info.GetEnvironment() = std::move(env);
Ilia K8f37ca52015-02-13 14:31:06 +00003754}
3755
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756bool TargetProperties::GetSkipPrologue() const {
3757 const uint32_t idx = ePropertySkipPrologue;
3758 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3759 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003760}
3761
Kate Stoneb9c1b512016-09-06 20:57:50 +00003762PathMappingList &TargetProperties::GetSourcePathMap() const {
3763 const uint32_t idx = ePropertySourceMap;
3764 OptionValuePathMappings *option_value =
3765 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3766 false, idx);
3767 assert(option_value);
3768 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003769}
3770
Kate Stoneb9c1b512016-09-06 20:57:50 +00003771FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3772 const uint32_t idx = ePropertyExecutableSearchPaths;
3773 OptionValueFileSpecList *option_value =
3774 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3775 false, idx);
3776 assert(option_value);
3777 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003778}
3779
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3781 const uint32_t idx = ePropertyDebugFileSearchPaths;
3782 OptionValueFileSpecList *option_value =
3783 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3784 false, idx);
3785 assert(option_value);
3786 return option_value->GetCurrentValue();
Michael Sartaina7499c92013-07-01 19:45:50 +00003787}
3788
Kate Stoneb9c1b512016-09-06 20:57:50 +00003789FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3790 const uint32_t idx = ePropertyClangModuleSearchPaths;
3791 OptionValueFileSpecList *option_value =
3792 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3793 false, idx);
3794 assert(option_value);
3795 return option_value->GetCurrentValue();
Sean Callanan85054342015-04-03 15:39:47 +00003796}
3797
Kate Stoneb9c1b512016-09-06 20:57:50 +00003798bool TargetProperties::GetEnableAutoImportClangModules() const {
3799 const uint32_t idx = ePropertyAutoImportClangModules;
3800 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3801 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callananf0c5aeb2015-04-20 16:31:29 +00003802}
3803
Kate Stoneb9c1b512016-09-06 20:57:50 +00003804bool TargetProperties::GetEnableAutoApplyFixIts() const {
3805 const uint32_t idx = ePropertyAutoApplyFixIts;
3806 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3807 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghama1e541b2016-03-25 01:57:14 +00003808}
3809
Kate Stoneb9c1b512016-09-06 20:57:50 +00003810bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3811 const uint32_t idx = ePropertyNotifyAboutFixIts;
3812 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3813 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghame5ee6f02016-03-29 22:00:08 +00003814}
3815
Sean Callanan5deb06e2016-09-26 20:18:51 +00003816bool TargetProperties::GetEnableSaveObjects() const {
3817 const uint32_t idx = ePropertySaveObjects;
3818 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3819 nullptr, idx, g_properties[idx].default_uint_value != 0);
3820}
3821
Kate Stoneb9c1b512016-09-06 20:57:50 +00003822bool TargetProperties::GetEnableSyntheticValue() const {
3823 const uint32_t idx = ePropertyEnableSynthetic;
3824 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3825 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003826}
3827
Kate Stoneb9c1b512016-09-06 20:57:50 +00003828uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3829 const uint32_t idx = ePropertyMaxChildrenCount;
3830 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3831 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003832}
3833
Kate Stoneb9c1b512016-09-06 20:57:50 +00003834uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3835 const uint32_t idx = ePropertyMaxSummaryLength;
3836 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3837 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003838}
3839
Kate Stoneb9c1b512016-09-06 20:57:50 +00003840uint32_t TargetProperties::GetMaximumMemReadSize() const {
3841 const uint32_t idx = ePropertyMaxMemReadSize;
3842 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3843 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granatad325bf92013-06-04 22:54:16 +00003844}
3845
Kate Stoneb9c1b512016-09-06 20:57:50 +00003846FileSpec TargetProperties::GetStandardInputPath() const {
3847 const uint32_t idx = ePropertyInputPath;
3848 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003849}
3850
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003851void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003852 const uint32_t idx = ePropertyInputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003853 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003854}
3855
Kate Stoneb9c1b512016-09-06 20:57:50 +00003856FileSpec TargetProperties::GetStandardOutputPath() const {
3857 const uint32_t idx = ePropertyOutputPath;
3858 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003859}
3860
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003861void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003862 const uint32_t idx = ePropertyOutputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003863 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003864}
3865
Kate Stoneb9c1b512016-09-06 20:57:50 +00003866FileSpec TargetProperties::GetStandardErrorPath() const {
3867 const uint32_t idx = ePropertyErrorPath;
3868 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003869}
3870
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003871void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3872 const uint32_t idx = ePropertyErrorPath;
3873 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3874}
3875
Kate Stoneb9c1b512016-09-06 20:57:50 +00003876LanguageType TargetProperties::GetLanguage() const {
3877 OptionValueLanguage *value =
3878 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3879 nullptr, ePropertyLanguage);
3880 if (value)
3881 return value->GetCurrentValue();
3882 return LanguageType();
Dawn Perchik23b1dec2015-07-21 22:05:07 +00003883}
3884
Pavel Labath50251fc2017-12-21 10:54:30 +00003885llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886 const uint32_t idx = ePropertyExprPrefix;
3887 OptionValueFileSpec *file =
3888 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3889 idx);
3890 if (file) {
Pavel Labath50251fc2017-12-21 10:54:30 +00003891 DataBufferSP data_sp(file->GetFileContents());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892 if (data_sp)
Pavel Labath50251fc2017-12-21 10:54:30 +00003893 return llvm::StringRef(
3894 reinterpret_cast<const char *>(data_sp->GetBytes()),
3895 data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003896 }
Pavel Labath50251fc2017-12-21 10:54:30 +00003897 return "";
Greg Clayton6920b522012-08-22 18:39:03 +00003898}
3899
Kate Stoneb9c1b512016-09-06 20:57:50 +00003900bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3901 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3902 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3903 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003904}
3905
Kate Stoneb9c1b512016-09-06 20:57:50 +00003906bool TargetProperties::GetUseHexImmediates() const {
3907 const uint32_t idx = ePropertyUseHexImmediates;
3908 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3909 nullptr, idx, g_properties[idx].default_uint_value != 0);
Daniel Malead79ae052013-08-07 21:54:09 +00003910}
3911
Kate Stoneb9c1b512016-09-06 20:57:50 +00003912bool TargetProperties::GetUseFastStepping() const {
3913 const uint32_t idx = ePropertyUseFastStepping;
3914 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3915 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham17d023f2013-03-13 17:58:04 +00003916}
3917
Kate Stoneb9c1b512016-09-06 20:57:50 +00003918bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3919 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3920 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3921 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Claytonfb6621e2013-12-06 21:59:52 +00003922}
3923
Kate Stoneb9c1b512016-09-06 20:57:50 +00003924LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3925 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3926 return (LoadScriptFromSymFile)
3927 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3928 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granata2ea43cd2013-05-13 17:03:52 +00003929}
3930
Kate Stoneb9c1b512016-09-06 20:57:50 +00003931LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3932 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3933 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3934 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molenda878ae012016-02-19 00:05:17 +00003935}
3936
Kate Stoneb9c1b512016-09-06 20:57:50 +00003937Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3938 const uint32_t idx = ePropertyHexImmediateStyle;
3939 return (Disassembler::HexImmediateStyle)
3940 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3941 nullptr, idx, g_properties[idx].default_uint_value);
Daniel Malead79ae052013-08-07 21:54:09 +00003942}
3943
Kate Stoneb9c1b512016-09-06 20:57:50 +00003944MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3945 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3946 return (MemoryModuleLoadLevel)
3947 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3948 nullptr, idx, g_properties[idx].default_uint_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00003949}
3950
Kate Stoneb9c1b512016-09-06 20:57:50 +00003951bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3952 const uint32_t idx = ePropertyTrapHandlerNames;
3953 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003954}
Greg Claytonfd814c52013-08-13 01:42:25 +00003955
Kate Stoneb9c1b512016-09-06 20:57:50 +00003956void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3957 const uint32_t idx = ePropertyTrapHandlerNames;
3958 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003959}
Greg Clayton67cc0632012-08-22 17:17:09 +00003960
Kate Stoneb9c1b512016-09-06 20:57:50 +00003961bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3962 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3963 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Enrico Granata560558e2015-02-11 02:35:39 +00003964}
3965
Kate Stoneb9c1b512016-09-06 20:57:50 +00003966void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3967 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3968 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granata560558e2015-02-11 02:35:39 +00003969}
3970
Kuba Mracek4c7f5d52018-12-20 23:38:19 +00003971bool TargetProperties::GetDisplayRecognizedArguments() const {
3972 const uint32_t idx = ePropertyDisplayRecognizedArguments;
3973 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3974}
3975
3976void TargetProperties::SetDisplayRecognizedArguments(bool b) {
3977 const uint32_t idx = ePropertyDisplayRecognizedArguments;
3978 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3979}
3980
Kate Stoneb9c1b512016-09-06 20:57:50 +00003981bool TargetProperties::GetNonStopModeEnabled() const {
3982 const uint32_t idx = ePropertyNonStopModeEnabled;
3983 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Ewan Crawford78baa192015-05-13 09:18:18 +00003984}
3985
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986void TargetProperties::SetNonStopModeEnabled(bool b) {
3987 const uint32_t idx = ePropertyNonStopModeEnabled;
3988 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00003989}
3990
Kate Stoneb9c1b512016-09-06 20:57:50 +00003991const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3992 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3993 return m_launch_info;
Ilia K8f37ca52015-02-13 14:31:06 +00003994}
3995
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996void TargetProperties::SetProcessLaunchInfo(
3997 const ProcessLaunchInfo &launch_info) {
3998 m_launch_info = launch_info;
3999 SetArg0(launch_info.GetArg0());
4000 SetRunArguments(launch_info.GetArguments());
Pavel Labath62930e52018-01-10 11:57:31 +00004001 SetEnvironment(launch_info.GetEnvironment());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004002 const FileAction *input_file_action =
4003 launch_info.GetFileActionForFD(STDIN_FILENO);
4004 if (input_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004005 SetStandardInputPath(input_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004006 }
4007 const FileAction *output_file_action =
4008 launch_info.GetFileActionForFD(STDOUT_FILENO);
4009 if (output_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004010 SetStandardOutputPath(output_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004011 }
4012 const FileAction *error_file_action =
4013 launch_info.GetFileActionForFD(STDERR_FILENO);
4014 if (error_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004015 SetStandardErrorPath(error_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004016 }
4017 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4018 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4019 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
Ilia K8f37ca52015-02-13 14:31:06 +00004020}
4021
Jonas Devliegheree103ae92018-11-15 01:18:15 +00004022bool TargetProperties::GetRequireHardwareBreakpoints() const {
4023 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4024 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4025 nullptr, idx, g_properties[idx].default_uint_value != 0);
4026}
4027
4028void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4029 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4030 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4031}
4032
Kate Stoneb9c1b512016-09-06 20:57:50 +00004033void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4034 OptionValue *) {
4035 TargetProperties *this_ =
4036 reinterpret_cast<TargetProperties *>(target_property_ptr);
4037 this_->m_launch_info.SetArg0(this_->GetArg0());
Ilia K8f37ca52015-02-13 14:31:06 +00004038}
4039
Kate Stoneb9c1b512016-09-06 20:57:50 +00004040void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4041 OptionValue *) {
4042 TargetProperties *this_ =
4043 reinterpret_cast<TargetProperties *>(target_property_ptr);
4044 Args args;
4045 if (this_->GetRunArguments(args))
4046 this_->m_launch_info.GetArguments() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00004047}
4048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4050 OptionValue *) {
4051 TargetProperties *this_ =
4052 reinterpret_cast<TargetProperties *>(target_property_ptr);
Pavel Labath62930e52018-01-10 11:57:31 +00004053 this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
Ilia K8f37ca52015-02-13 14:31:06 +00004054}
4055
Kate Stoneb9c1b512016-09-06 20:57:50 +00004056void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4057 OptionValue *) {
4058 TargetProperties *this_ =
4059 reinterpret_cast<TargetProperties *>(target_property_ptr);
4060 this_->m_launch_info.AppendOpenFileAction(
4061 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
Ilia K8f37ca52015-02-13 14:31:06 +00004062}
4063
Kate Stoneb9c1b512016-09-06 20:57:50 +00004064void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4065 OptionValue *) {
4066 TargetProperties *this_ =
4067 reinterpret_cast<TargetProperties *>(target_property_ptr);
4068 this_->m_launch_info.AppendOpenFileAction(
4069 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004070}
4071
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4073 OptionValue *) {
4074 TargetProperties *this_ =
4075 reinterpret_cast<TargetProperties *>(target_property_ptr);
4076 this_->m_launch_info.AppendOpenFileAction(
4077 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004078}
4079
Kate Stoneb9c1b512016-09-06 20:57:50 +00004080void TargetProperties::DetachOnErrorValueChangedCallback(
4081 void *target_property_ptr, OptionValue *) {
4082 TargetProperties *this_ =
4083 reinterpret_cast<TargetProperties *>(target_property_ptr);
4084 if (this_->GetDetachOnError())
4085 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4086 else
4087 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
Ilia K8f37ca52015-02-13 14:31:06 +00004088}
4089
Kate Stoneb9c1b512016-09-06 20:57:50 +00004090void TargetProperties::DisableASLRValueChangedCallback(
4091 void *target_property_ptr, OptionValue *) {
4092 TargetProperties *this_ =
4093 reinterpret_cast<TargetProperties *>(target_property_ptr);
4094 if (this_->GetDisableASLR())
4095 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4096 else
4097 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
Ilia K8f37ca52015-02-13 14:31:06 +00004098}
4099
Kate Stoneb9c1b512016-09-06 20:57:50 +00004100void TargetProperties::DisableSTDIOValueChangedCallback(
4101 void *target_property_ptr, OptionValue *) {
4102 TargetProperties *this_ =
4103 reinterpret_cast<TargetProperties *>(target_property_ptr);
4104 if (this_->GetDisableSTDIO())
4105 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4106 else
4107 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
Ilia K8f37ca52015-02-13 14:31:06 +00004108}
Ilia Keb2c19a2015-03-10 21:59:55 +00004109
4110//----------------------------------------------------------------------
4111// Target::TargetEventData
4112//----------------------------------------------------------------------
4113
Kate Stoneb9c1b512016-09-06 20:57:50 +00004114Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4115 : EventData(), m_target_sp(target_sp), m_module_list() {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004116
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4118 const ModuleList &module_list)
4119 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004120
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004121Target::TargetEventData::~TargetEventData() = default;
Ilia Keb2c19a2015-03-10 21:59:55 +00004122
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123const ConstString &Target::TargetEventData::GetFlavorString() {
4124 static ConstString g_flavor("Target::TargetEventData");
4125 return g_flavor;
Ilia Keb2c19a2015-03-10 21:59:55 +00004126}
4127
Kate Stoneb9c1b512016-09-06 20:57:50 +00004128void Target::TargetEventData::Dump(Stream *s) const {
4129 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4130 if (i != 0)
4131 *s << ", ";
4132 m_module_list.GetModuleAtIndex(i)->GetDescription(
4133 s, lldb::eDescriptionLevelBrief);
4134 }
Ilia Keb2c19a2015-03-10 21:59:55 +00004135}
4136
4137const Target::TargetEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004138Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4139 if (event_ptr) {
4140 const EventData *event_data = event_ptr->GetData();
4141 if (event_data &&
4142 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4143 return static_cast<const TargetEventData *>(event_ptr->GetData());
4144 }
4145 return nullptr;
Ilia Keb2c19a2015-03-10 21:59:55 +00004146}
4147
Kate Stoneb9c1b512016-09-06 20:57:50 +00004148TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4149 TargetSP target_sp;
4150 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4151 if (event_data)
4152 target_sp = event_data->m_target_sp;
4153 return target_sp;
Ilia Keb2c19a2015-03-10 21:59:55 +00004154}
4155
4156ModuleList
Kate Stoneb9c1b512016-09-06 20:57:50 +00004157Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4158 ModuleList module_list;
4159 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4160 if (event_data)
4161 module_list = event_data->m_module_list;
4162 return module_list;
Ilia Keb2c19a2015-03-10 21:59:55 +00004163}