blob: 8ba121d0c9bca6979bad1ec5e210ee678c157553 [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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010// C Includes
11// C++ Includes
Greg Clayton04df8ee2016-02-26 19:38:18 +000012#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// Other libraries and framework includes
14// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
16#include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
17#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
Jim Ingham01f16662016-09-14 19:07:35 +000018#include "lldb/Breakpoint/BreakpointIDList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Breakpoint/BreakpointResolver.h"
20#include "lldb/Breakpoint/BreakpointResolverAddress.h"
21#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
Jim Ingham969795f2011-09-21 01:17:13 +000022#include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Breakpoint/BreakpointResolverName.h"
Jim Ingham3815e702018-09-13 21:35:32 +000024#include "lldb/Breakpoint/BreakpointResolverScripted.h"
Johnny Chen01a67862011-10-14 00:42:25 +000025#include "lldb/Breakpoint/Watchpoint.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000026#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Core/Event.h"
Greg Clayton1f746072012-08-29 21:13:06 +000028#include "lldb/Core/Module.h"
29#include "lldb/Core/ModuleSpec.h"
Pavel Labath13e37d42017-10-25 21:05:31 +000030#include "lldb/Core/PluginManager.h"
Greg Clayton1f746072012-08-29 21:13:06 +000031#include "lldb/Core/Section.h"
Jim Ingham3815e702018-09-13 21:35:32 +000032#include "lldb/Core/SearchFilter.h"
Greg Clayton9585fbf2013-03-19 00:20:55 +000033#include "lldb/Core/SourceManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000034#include "lldb/Core/StreamFile.h"
Jim Ingham3815e702018-09-13 21:35:32 +000035#include "lldb/Core/StructuredDataImpl.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000036#include "lldb/Core/ValueObject.h"
Sean Callanan66810412015-10-19 23:11:07 +000037#include "lldb/Expression/REPL.h"
Jim Ingham151c0322015-09-15 21:13:50 +000038#include "lldb/Expression/UserExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Host/Host.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000040#include "lldb/Host/PosixApi.h"
Jim Ingham9575d842011-03-11 03:53:59 +000041#include "lldb/Interpreter/CommandInterpreter.h"
42#include "lldb/Interpreter/CommandReturnObject.h"
Johnny Chenb90827e2012-06-04 23:19:54 +000043#include "lldb/Interpreter/OptionGroupWatchpoint.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000044#include "lldb/Interpreter/OptionValues.h"
45#include "lldb/Interpreter/Property.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000046#include "lldb/Symbol/ClangASTContext.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000047#include "lldb/Symbol/Function.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000048#include "lldb/Symbol/ObjectFile.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000049#include "lldb/Symbol/Symbol.h"
Jim Ingham151c0322015-09-15 21:13:50 +000050#include "lldb/Target/Language.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000051#include "lldb/Target/LanguageRuntime.h"
52#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/Process.h"
Greg Claytond5944cd2013-12-06 01:12:00 +000054#include "lldb/Target/SectionLoadList.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000055#include "lldb/Target/StackFrame.h"
Jason Molendaeef51062013-11-05 03:57:19 +000056#include "lldb/Target/SystemRuntime.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000057#include "lldb/Target/Target.h"
Jim Ingham9575d842011-03-11 03:53:59 +000058#include "lldb/Target/Thread.h"
59#include "lldb/Target/ThreadSpec.h"
Zachary Turner5713a052017-03-22 18:40:07 +000060#include "lldb/Utility/FileSpec.h"
Sean Callanan9a6940c2015-10-21 00:36:34 +000061#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000062#include "lldb/Utility/Log.h"
Pavel Labathd821c992018-08-07 11:07:21 +000063#include "lldb/Utility/State.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000064#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000065#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
67using namespace lldb;
68using namespace lldb_private;
69
Pavel Labath43d35412016-12-06 11:24:51 +000070constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
71
Pavel Labath13e37d42017-10-25 21:05:31 +000072Target::Arch::Arch(const ArchSpec &spec)
73 : m_spec(spec),
74 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
75
76const Target::Arch& Target::Arch::operator=(const ArchSpec &spec) {
77 m_spec = spec;
78 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
79 return *this;
80}
81
Kate Stoneb9c1b512016-09-06 20:57:50 +000082ConstString &Target::GetStaticBroadcasterClass() {
83 static ConstString class_name("lldb.target");
84 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000085}
86
Kate Stoneb9c1b512016-09-06 20:57:50 +000087Target::Target(Debugger &debugger, const ArchSpec &target_arch,
88 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000089 : TargetProperties(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 Broadcaster(debugger.GetBroadcasterManager(),
91 Target::GetStaticBroadcasterClass().AsCString()),
92 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
Davide Italiano24fff242018-04-13 18:02:39 +000093 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
94 m_breakpoint_list(false), m_internal_breakpoint_list(true),
95 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
96 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
97 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
98 m_valid(true), m_suppress_stop_hooks(false),
99 m_is_dummy_target(is_dummy_target),
100 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
Jim Ingham893c9322014-11-22 01:42:44 +0000101
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000102{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
104 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
105 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
106 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
107 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 CheckInWithManager();
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
112 if (log)
113 log->Printf("%p Target::Target()", static_cast<void *>(this));
Pavel Labath13e37d42017-10-25 21:05:31 +0000114 if (target_arch.IsValid()) {
115 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET,
116 "Target::Target created with architecture %s (%s)",
117 target_arch.GetArchitectureName(),
118 target_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000120}
121
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122Target::~Target() {
123 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
124 if (log)
125 log->Printf("%p Target::~Target()", static_cast<void *>(this));
126 DeleteCurrentProcess();
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000127}
128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129void Target::PrimeFromDummyTarget(Target *target) {
130 if (!target)
131 return;
Jim Ingham893c9322014-11-22 01:42:44 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 m_stop_hooks = target->m_stop_hooks;
134
135 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
136 if (breakpoint_sp->IsInternal())
137 continue;
138
139 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
140 AddBreakpoint(new_bp, false);
141 }
Jim Inghamb842f2e2017-09-14 20:22:49 +0000142
143 for (auto bp_name_entry : target->m_breakpoint_names)
144 {
145
146 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
147 AddBreakpointName(new_bp_name);
148 }
Jim Ingham893c9322014-11-22 01:42:44 +0000149}
150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
152 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
153 if (description_level != lldb::eDescriptionLevelBrief) {
154 s->Indent();
155 s->PutCString("Target\n");
156 s->IndentMore();
157 m_images.Dump(s);
158 m_breakpoint_list.Dump(s);
159 m_internal_breakpoint_list.Dump(s);
160 s->IndentLess();
161 } else {
162 Module *exe_module = GetExecutableModulePointer();
163 if (exe_module)
164 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
Caroline Ticeceb6b132010-10-26 03:11:13 +0000165 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 s->PutCString("No executable module.");
167 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170void Target::CleanupProcess() {
171 // Do any cleanup of the target we need to do between process instances.
172 // NB It is better to do this before destroying the process in case the
173 // clean up needs some help from the process.
174 m_breakpoint_list.ClearAllBreakpointSites();
175 m_internal_breakpoint_list.ClearAllBreakpointSites();
176 // Disable watchpoints just on the debugger side.
177 std::unique_lock<std::recursive_mutex> lock;
178 this->GetWatchpointList().GetListMutex(lock);
179 DisableAllWatchpoints(false);
180 ClearAllWatchpointHitCounts();
181 ClearAllWatchpointHistoricValues();
Greg Clayton90ba8112012-12-05 00:16:59 +0000182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184void Target::DeleteCurrentProcess() {
185 if (m_process_sp) {
Greg Claytond5944cd2013-12-06 01:12:00 +0000186 m_section_load_history.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187 if (m_process_sp->IsAlive())
188 m_process_sp->Destroy(false);
189
190 m_process_sp->Finalize();
191
192 CleanupProcess();
193
194 m_process_sp.reset();
195 }
Greg Clayton3418c852011-08-10 02:10:13 +0000196}
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
Zachary Turner31659452016-11-17 21:15:14 +0000199 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 const FileSpec *crash_file) {
201 DeleteCurrentProcess();
202 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
203 listener_sp, crash_file);
204 return m_process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000205}
206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
208
Zachary Turner97206d52017-05-12 04:51:55 +0000209lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 const char *repl_options, bool can_create) {
211 if (language == eLanguageTypeUnknown) {
212 std::set<LanguageType> repl_languages;
213
214 Language::GetLanguagesSupportingREPLs(repl_languages);
215
216 if (repl_languages.size() == 1) {
217 language = *repl_languages.begin();
218 } else if (repl_languages.size() == 0) {
219 err.SetErrorStringWithFormat(
220 "LLDB isn't configured with REPL support for any languages.");
221 return REPLSP();
222 } else {
223 err.SetErrorStringWithFormat(
224 "Multiple possible REPL languages. Please specify a language.");
225 return REPLSP();
226 }
227 }
228
229 REPLMap::iterator pos = m_repl_map.find(language);
230
231 if (pos != m_repl_map.end()) {
232 return pos->second;
233 }
234
235 if (!can_create) {
236 err.SetErrorStringWithFormat(
237 "Couldn't find an existing REPL for %s, and can't create a new one",
238 Language::GetNameForLanguageType(language));
239 return lldb::REPLSP();
240 }
241
242 Debugger *const debugger = nullptr;
243 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
244
245 if (ret) {
246 m_repl_map[language] = ret;
247 return m_repl_map[language];
248 }
249
250 if (err.Success()) {
251 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
252 Language::GetNameForLanguageType(language));
253 }
254
255 return lldb::REPLSP();
256}
257
258void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
259 lldbassert(!m_repl_map.count(language));
260
261 m_repl_map[language] = repl_sp;
262}
263
264void Target::Destroy() {
265 std::lock_guard<std::recursive_mutex> guard(m_mutex);
266 m_valid = false;
267 DeleteCurrentProcess();
268 m_platform_sp.reset();
Pavel Labath13e37d42017-10-25 21:05:31 +0000269 m_arch = ArchSpec();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 ClearModules(true);
271 m_section_load_history.Clear();
272 const bool notify = false;
273 m_breakpoint_list.RemoveAll(notify);
274 m_internal_breakpoint_list.RemoveAll(notify);
275 m_last_created_breakpoint.reset();
276 m_last_created_watchpoint.reset();
277 m_search_filter_sp.reset();
278 m_image_search_paths.Clear(notify);
279 m_stop_hooks.clear();
280 m_stop_hook_next_id = 0;
281 m_suppress_stop_hooks = false;
282}
283
284BreakpointList &Target::GetBreakpointList(bool internal) {
285 if (internal)
286 return m_internal_breakpoint_list;
287 else
288 return m_breakpoint_list;
289}
290
291const BreakpointList &Target::GetBreakpointList(bool internal) const {
292 if (internal)
293 return m_internal_breakpoint_list;
294 else
295 return m_breakpoint_list;
296}
297
298BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
299 BreakpointSP bp_sp;
300
301 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
302 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
303 else
304 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
305
306 return bp_sp;
307}
308
309BreakpointSP Target::CreateSourceRegexBreakpoint(
310 const FileSpecList *containingModules,
311 const FileSpecList *source_file_spec_list,
312 const std::unordered_set<std::string> &function_names,
313 RegularExpression &source_regex, bool internal, bool hardware,
314 LazyBool move_to_nearest_code) {
315 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
316 containingModules, source_file_spec_list));
317 if (move_to_nearest_code == eLazyBoolCalculate)
318 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
319 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
320 nullptr, source_regex, function_names,
321 !static_cast<bool>(move_to_nearest_code)));
322
323 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
324}
325
326BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
327 const FileSpec &file, uint32_t line_no,
Adrian Prantl431b1582018-08-30 15:11:00 +0000328 uint32_t column, lldb::addr_t offset,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 LazyBool check_inlines,
330 LazyBool skip_prologue, bool internal,
331 bool hardware,
332 LazyBool move_to_nearest_code) {
333 FileSpec remapped_file;
Greg Clayton86188d82018-05-21 14:14:36 +0000334 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 remapped_file = file;
336
337 if (check_inlines == eLazyBoolCalculate) {
338 const InlineStrategy inline_strategy = GetInlineStrategy();
339 switch (inline_strategy) {
340 case eInlineBreakpointsNever:
341 check_inlines = eLazyBoolNo;
342 break;
343
344 case eInlineBreakpointsHeaders:
345 if (remapped_file.IsSourceImplementationFile())
346 check_inlines = eLazyBoolNo;
347 else
348 check_inlines = eLazyBoolYes;
349 break;
350
351 case eInlineBreakpointsAlways:
352 check_inlines = eLazyBoolYes;
353 break;
354 }
355 }
356 SearchFilterSP filter_sp;
357 if (check_inlines == eLazyBoolNo) {
358 // Not checking for inlines, we are looking only for matching compile units
359 FileSpecList compile_unit_list;
360 compile_unit_list.Append(remapped_file);
361 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
362 &compile_unit_list);
363 } else {
364 filter_sp = GetSearchFilterForModuleList(containingModules);
365 }
366 if (skip_prologue == eLazyBoolCalculate)
367 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
368 if (move_to_nearest_code == eLazyBoolCalculate)
369 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
370
371 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
Adrian Prantl431b1582018-08-30 15:11:00 +0000372 nullptr, remapped_file, line_no, column, offset, check_inlines,
373 skip_prologue, !static_cast<bool>(move_to_nearest_code)));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
375}
376
377BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
378 bool hardware) {
379 Address so_addr;
380
381 // Check for any reason we want to move this breakpoint to other address.
382 addr = GetBreakableLoadAddress(addr);
383
Adrian Prantl05097242018-04-30 16:49:04 +0000384 // Attempt to resolve our load address if possible, though it is ok if it
385 // doesn't resolve to section/offset.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386
387 // Try and resolve as a load address if possible
388 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
389 if (!so_addr.IsValid()) {
390 // The address didn't resolve, so just set this as an absolute address
391 so_addr.SetOffset(addr);
392 }
393 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
394 return bp_sp;
395}
396
397BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
398 bool hardware) {
399 SearchFilterSP filter_sp(
400 new SearchFilterForUnconstrainedSearches(shared_from_this()));
401 BreakpointResolverSP resolver_sp(
402 new BreakpointResolverAddress(nullptr, addr));
403 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
404}
405
406lldb::BreakpointSP
407Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
408 const FileSpec *file_spec,
409 bool request_hardware) {
410 SearchFilterSP filter_sp(
411 new SearchFilterForUnconstrainedSearches(shared_from_this()));
412 BreakpointResolverSP resolver_sp(
413 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
414 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
415 false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416}
417
418BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419Target::CreateBreakpoint(const FileSpecList *containingModules,
420 const FileSpecList *containingSourceFiles,
421 const char *func_name, uint32_t func_name_type_mask,
422 LanguageType language, lldb::addr_t offset,
423 LazyBool skip_prologue, bool internal, bool hardware) {
424 BreakpointSP bp_sp;
425 if (func_name) {
426 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
427 containingModules, containingSourceFiles));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428
Greg Clayton03da4cc2013-04-19 21:31:16 +0000429 if (skip_prologue == eLazyBoolCalculate)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
431 if (language == lldb::eLanguageTypeUnknown)
432 language = GetLanguage();
433
434 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
435 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
436 offset, skip_prologue));
437 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
438 }
439 return bp_sp;
440}
441
442lldb::BreakpointSP
443Target::CreateBreakpoint(const FileSpecList *containingModules,
444 const FileSpecList *containingSourceFiles,
445 const std::vector<std::string> &func_names,
446 uint32_t func_name_type_mask, LanguageType language,
447 lldb::addr_t offset, LazyBool skip_prologue,
448 bool internal, bool hardware) {
449 BreakpointSP bp_sp;
450 size_t num_names = func_names.size();
451 if (num_names > 0) {
452 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
453 containingModules, containingSourceFiles));
454
455 if (skip_prologue == eLazyBoolCalculate)
456 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
457 if (language == lldb::eLanguageTypeUnknown)
458 language = GetLanguage();
459
460 BreakpointResolverSP resolver_sp(
461 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
462 language, offset, skip_prologue));
463 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
464 }
465 return bp_sp;
466}
467
468BreakpointSP Target::CreateBreakpoint(
469 const FileSpecList *containingModules,
470 const FileSpecList *containingSourceFiles, const char *func_names[],
471 size_t num_names, uint32_t func_name_type_mask, LanguageType language,
472 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
473 BreakpointSP bp_sp;
474 if (num_names > 0) {
475 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
476 containingModules, containingSourceFiles));
477
478 if (skip_prologue == eLazyBoolCalculate) {
479 if (offset == 0)
Greg Clayton03da4cc2013-04-19 21:31:16 +0000480 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 else
482 skip_prologue = eLazyBoolNo;
Greg Clayton1b72fcb2010-08-24 00:45:41 +0000483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 if (language == lldb::eLanguageTypeUnknown)
485 language = GetLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
488 nullptr, func_names, num_names, func_name_type_mask, language, offset,
489 skip_prologue));
490 resolver_sp->SetOffset(offset);
491 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
492 }
493 return bp_sp;
Jim Ingham133e0fb2012-03-03 02:05:11 +0000494}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000495
496SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497Target::GetSearchFilterForModule(const FileSpec *containingModule) {
498 SearchFilterSP filter_sp;
499 if (containingModule != nullptr) {
500 // TODO: We should look into sharing module based search filters
501 // across many breakpoints like we do for the simple target based one
502 filter_sp.reset(
503 new SearchFilterByModule(shared_from_this(), *containingModule));
504 } else {
505 if (!m_search_filter_sp)
506 m_search_filter_sp.reset(
507 new SearchFilterForUnconstrainedSearches(shared_from_this()));
508 filter_sp = m_search_filter_sp;
509 }
510 return filter_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000511}
512
Jim Ingham969795f2011-09-21 01:17:13 +0000513SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
515 SearchFilterSP filter_sp;
516 if (containingModules && containingModules->GetSize() != 0) {
517 // TODO: We should look into sharing module based search filters
518 // across many breakpoints like we do for the simple target based one
519 filter_sp.reset(
520 new SearchFilterByModuleList(shared_from_this(), *containingModules));
521 } else {
522 if (!m_search_filter_sp)
523 m_search_filter_sp.reset(
524 new SearchFilterForUnconstrainedSearches(shared_from_this()));
525 filter_sp = m_search_filter_sp;
526 }
527 return filter_sp;
Jim Ingham969795f2011-09-21 01:17:13 +0000528}
529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
531 const FileSpecList *containingModules,
532 const FileSpecList *containingSourceFiles) {
533 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
534 return GetSearchFilterForModuleList(containingModules);
535
536 SearchFilterSP filter_sp;
537 if (containingModules == nullptr) {
538 // We could make a special "CU List only SearchFilter". Better yet was if
Adrian Prantl05097242018-04-30 16:49:04 +0000539 // these could be composable, but that will take a little reworking.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540
541 filter_sp.reset(new SearchFilterByModuleListAndCU(
542 shared_from_this(), FileSpecList(), *containingSourceFiles));
543 } else {
544 filter_sp.reset(new SearchFilterByModuleListAndCU(
545 shared_from_this(), *containingModules, *containingSourceFiles));
546 }
547 return filter_sp;
Jim Ingham87df91b2011-09-23 00:54:11 +0000548}
549
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550BreakpointSP Target::CreateFuncRegexBreakpoint(
551 const FileSpecList *containingModules,
552 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
553 lldb::LanguageType requested_language, LazyBool skip_prologue,
554 bool internal, bool hardware) {
555 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
556 containingModules, containingSourceFiles));
557 bool skip = (skip_prologue == eLazyBoolCalculate)
558 ? GetSkipPrologue()
559 : static_cast<bool>(skip_prologue);
560 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
561 nullptr, func_regex, requested_language, 0, skip));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000564}
565
Jim Ingham219ba192012-03-05 04:47:34 +0000566lldb::BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
568 bool catch_bp, bool throw_bp, bool internal,
Zachary Turner97206d52017-05-12 04:51:55 +0000569 Args *additional_args, Status *error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
571 *this, language, catch_bp, throw_bp, internal);
572 if (exc_bkpt_sp && additional_args) {
573 Breakpoint::BreakpointPreconditionSP precondition_sp =
574 exc_bkpt_sp->GetPrecondition();
575 if (precondition_sp && additional_args) {
576 if (error)
577 *error = precondition_sp->ConfigurePrecondition(*additional_args);
578 else
579 precondition_sp->ConfigurePrecondition(*additional_args);
Jim Inghama72b31c2015-04-22 19:42:18 +0000580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 }
582 return exc_bkpt_sp;
Jim Ingham219ba192012-03-05 04:47:34 +0000583}
Jim Inghama72b31c2015-04-22 19:42:18 +0000584
Jim Ingham3815e702018-09-13 21:35:32 +0000585lldb::BreakpointSP
586Target::CreateScriptedBreakpoint(const llvm::StringRef class_name,
587 const FileSpecList *containingModules,
588 const FileSpecList *containingSourceFiles,
589 bool internal,
590 bool request_hardware,
591 StructuredData::ObjectSP extra_args_sp,
592 Status *creation_error)
593{
594 SearchFilterSP filter_sp;
595
596 lldb::SearchDepth depth = lldb::eSearchDepthTarget;
597 bool has_files = containingSourceFiles && containingSourceFiles->GetSize() > 0;
598 bool has_modules = containingModules && containingModules->GetSize() > 0;
599
600 if (has_files && has_modules) {
601 filter_sp = GetSearchFilterForModuleAndCUList(
602 containingModules, containingSourceFiles);
603 } else if (has_files) {
604 filter_sp = GetSearchFilterForModuleAndCUList(
605 nullptr, containingSourceFiles);
606 } else if (has_modules) {
607 filter_sp = GetSearchFilterForModuleList(containingModules);
608 } else {
609 filter_sp.reset(new SearchFilterForUnconstrainedSearches(shared_from_this()));
610 }
611
612 StructuredDataImpl *extra_args_impl = new StructuredDataImpl();
613 if (extra_args_sp)
614 extra_args_impl->SetObjectSP(extra_args_sp);
615
616 BreakpointResolverSP resolver_sp(new
617 BreakpointResolverScripted(nullptr, class_name,
618 depth,
619 extra_args_impl,
620 *GetDebugger().GetCommandInterpreter()
621 .GetScriptInterpreter()));
622 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
623
624}
625
626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
628 BreakpointResolverSP &resolver_sp,
629 bool internal, bool request_hardware,
630 bool resolve_indirect_symbols) {
631 BreakpointSP bp_sp;
632 if (filter_sp && resolver_sp) {
633 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, request_hardware,
634 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
Zachary Turner97206d52017-05-12 04:51:55 +0000774static bool CheckIfWatchpointsExhausted(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);
778 if (num_supported_hardware_watchpoints == 0) {
779 error.SetErrorStringWithFormat(
780 "Target supports (%u) hardware watchpoint slots.\n",
781 num_supported_hardware_watchpoints);
782 return false;
783 }
784 return true;
Johnny Chenb90827e2012-06-04 23:19:54 +0000785}
786
Adrian Prantl05097242018-04-30 16:49:04 +0000787// See also Watchpoint::SetWatchpointType(uint32_t type) and the
788// OptionGroupWatchpoint::WatchType enum type.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
790 const CompilerType *type, uint32_t kind,
Zachary Turner97206d52017-05-12 04:51:55 +0000791 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
793 if (log)
794 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
795 " type = %u)\n",
796 __FUNCTION__, addr, (uint64_t)size, kind);
Johnny Chen0c406372011-09-14 20:23:45 +0000797
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 WatchpointSP wp_sp;
799 if (!ProcessIsValid()) {
800 error.SetErrorString("process is not alive");
Johnny Chen01a67862011-10-14 00:42:25 +0000801 return wp_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 }
Johnny Chen887062a2011-09-12 23:38:44 +0000803
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
805 if (size == 0)
806 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
809 return wp_sp;
810 }
811
812 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
813 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
814 }
815
816 if (!CheckIfWatchpointsExhausted(this, error))
817 return wp_sp;
818
Adrian Prantl05097242018-04-30 16:49:04 +0000819 // Currently we only support one watchpoint per address, with total number of
820 // watchpoints limited by the hardware which the inferior is running on.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821
822 // Grab the list mutex while doing operations.
823 const bool notify = false; // Don't notify about all the state changes we do
824 // on creating the watchpoint.
825 std::unique_lock<std::recursive_mutex> lock;
826 this->GetWatchpointList().GetListMutex(lock);
827 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
828 if (matched_sp) {
829 size_t old_size = matched_sp->GetByteSize();
830 uint32_t old_type =
831 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
832 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
833 // Return the existing watchpoint if both size and type match.
834 if (size == old_size && kind == old_type) {
835 wp_sp = matched_sp;
836 wp_sp->SetEnabled(false, notify);
837 } else {
838 // Nil the matched watchpoint; we will be creating a new one.
839 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
840 m_watchpoint_list.Remove(matched_sp->GetID(), true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 }
843
844 if (!wp_sp) {
845 wp_sp.reset(new Watchpoint(*this, addr, size, type));
846 wp_sp->SetWatchpointType(kind, notify);
847 m_watchpoint_list.Add(wp_sp, true);
848 }
849
850 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
851 if (log)
852 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
853 __FUNCTION__, error.Success() ? "succeeded" : "failed",
854 wp_sp->GetID());
855
856 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000857 // Enabling the watchpoint on the device side failed. Remove the said
858 // watchpoint from the list maintained by the target instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 m_watchpoint_list.Remove(wp_sp->GetID(), true);
860 // See if we could provide more helpful error message.
861 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
862 error.SetErrorStringWithFormat(
863 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
864
865 wp_sp.reset();
866 } else
867 m_last_created_watchpoint = wp_sp;
868 return wp_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869}
870
Jim Inghamb842f2e2017-09-14 20:22:49 +0000871void Target::RemoveAllowedBreakpoints ()
872{
873 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
874 if (log)
875 log->Printf("Target::%s \n", __FUNCTION__);
876
877 m_breakpoint_list.RemoveAllowed(true);
878
879 m_last_created_breakpoint.reset();
880}
881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882void Target::RemoveAllBreakpoints(bool internal_also) {
883 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
884 if (log)
885 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
886 internal_also ? "yes" : "no");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 m_breakpoint_list.RemoveAll(true);
889 if (internal_also)
890 m_internal_breakpoint_list.RemoveAll(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 m_last_created_breakpoint.reset();
893}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895void Target::DisableAllBreakpoints(bool internal_also) {
896 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
897 if (log)
898 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
899 internal_also ? "yes" : "no");
900
901 m_breakpoint_list.SetEnabledAll(false);
902 if (internal_also)
903 m_internal_breakpoint_list.SetEnabledAll(false);
904}
905
Jim Inghamb842f2e2017-09-14 20:22:49 +0000906void Target::DisableAllowedBreakpoints() {
907 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
908 if (log)
909 log->Printf("Target::%s", __FUNCTION__);
910
911 m_breakpoint_list.SetEnabledAllowed(false);
912}
913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914void Target::EnableAllBreakpoints(bool internal_also) {
915 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
916 if (log)
917 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
918 internal_also ? "yes" : "no");
919
920 m_breakpoint_list.SetEnabledAll(true);
921 if (internal_also)
922 m_internal_breakpoint_list.SetEnabledAll(true);
923}
924
Jim Inghamb842f2e2017-09-14 20:22:49 +0000925void Target::EnableAllowedBreakpoints() {
926 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
927 if (log)
928 log->Printf("Target::%s", __FUNCTION__);
929
930 m_breakpoint_list.SetEnabledAllowed(true);
931}
932
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933bool Target::RemoveBreakpointByID(break_id_t break_id) {
934 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
935 if (log)
936 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
937 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
938
939 if (DisableBreakpointByID(break_id)) {
940 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
941 m_internal_breakpoint_list.Remove(break_id, false);
942 else {
943 if (m_last_created_breakpoint) {
944 if (m_last_created_breakpoint->GetID() == break_id)
945 m_last_created_breakpoint.reset();
946 }
947 m_breakpoint_list.Remove(break_id, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000948 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 return true;
950 }
951 return false;
952}
953
954bool Target::DisableBreakpointByID(break_id_t break_id) {
955 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
956 if (log)
957 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
958 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
959
960 BreakpointSP bp_sp;
961
962 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
963 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
964 else
965 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
966 if (bp_sp) {
967 bp_sp->SetEnabled(false);
968 return true;
969 }
970 return false;
971}
972
973bool Target::EnableBreakpointByID(break_id_t break_id) {
974 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
975 if (log)
976 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
977 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
978
979 BreakpointSP bp_sp;
980
981 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
982 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
983 else
984 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
985
986 if (bp_sp) {
987 bp_sp->SetEnabled(true);
988 return true;
989 }
990 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991}
992
Zachary Turner97206d52017-05-12 04:51:55 +0000993Status Target::SerializeBreakpointsToFile(const FileSpec &file,
994 const BreakpointIDList &bp_ids,
995 bool append) {
996 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +0000997
998 if (!file) {
999 error.SetErrorString("Invalid FileSpec.");
1000 return error;
1001 }
1002
1003 std::string path(file.GetPath());
Jim Ingham2d3628e2016-09-22 23:42:42 +00001004 StructuredData::ObjectSP input_data_sp;
1005
1006 StructuredData::ArraySP break_store_sp;
1007 StructuredData::Array *break_store_ptr = nullptr;
1008
1009 if (append) {
1010 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1011 if (error.Success()) {
1012 break_store_ptr = input_data_sp->GetAsArray();
1013 if (!break_store_ptr) {
1014 error.SetErrorStringWithFormat(
1015 "Tried to append to invalid input file %s", path.c_str());
1016 return error;
1017 }
1018 }
1019 }
1020
1021 if (!break_store_ptr) {
1022 break_store_sp.reset(new StructuredData::Array());
1023 break_store_ptr = break_store_sp.get();
1024 }
1025
Jim Ingham01f16662016-09-14 19:07:35 +00001026 StreamFile out_file(path.c_str(),
1027 File::OpenOptions::eOpenOptionTruncate |
1028 File::OpenOptions::eOpenOptionWrite |
1029 File::OpenOptions::eOpenOptionCanCreate |
1030 File::OpenOptions::eOpenOptionCloseOnExec,
1031 lldb::eFilePermissionsFileDefault);
1032 if (!out_file.GetFile().IsValid()) {
1033 error.SetErrorStringWithFormat("Unable to open output file: %s.",
1034 path.c_str());
1035 return error;
1036 }
1037
1038 std::unique_lock<std::recursive_mutex> lock;
1039 GetBreakpointList().GetListMutex(lock);
1040
Jim Ingham01f16662016-09-14 19:07:35 +00001041 if (bp_ids.GetSize() == 0) {
1042 const BreakpointList &breakpoints = GetBreakpointList();
1043
1044 size_t num_breakpoints = breakpoints.GetSize();
1045 for (size_t i = 0; i < num_breakpoints; i++) {
1046 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1047 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1048 // If a breakpoint can't serialize it, just ignore it for now:
1049 if (bkpt_save_sp)
Jim Ingham2d3628e2016-09-22 23:42:42 +00001050 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +00001051 }
1052 } else {
1053
1054 std::unordered_set<lldb::break_id_t> processed_bkpts;
1055 const size_t count = bp_ids.GetSize();
1056 for (size_t i = 0; i < count; ++i) {
1057 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1058 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1059
1060 if (bp_id != LLDB_INVALID_BREAK_ID) {
1061 // Only do each breakpoint once:
1062 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1063 insert_result = processed_bkpts.insert(bp_id);
1064 if (!insert_result.second)
1065 continue;
1066
1067 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1068 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1069 // If the user explicitly asked to serialize a breakpoint, and we
Adrian Prantl05097242018-04-30 16:49:04 +00001070 // can't, then raise an error:
Jim Ingham01f16662016-09-14 19:07:35 +00001071 if (!bkpt_save_sp) {
1072 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1073 bp_id);
1074 return error;
1075 }
Jim Ingham2d3628e2016-09-22 23:42:42 +00001076 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +00001077 }
1078 }
1079 }
1080
Jim Ingham2d3628e2016-09-22 23:42:42 +00001081 break_store_ptr->Dump(out_file, false);
Jim Ingham01f16662016-09-14 19:07:35 +00001082 out_file.PutChar('\n');
1083 return error;
1084}
1085
Zachary Turner97206d52017-05-12 04:51:55 +00001086Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1087 BreakpointIDList &new_bps) {
Jim Ingham3acdf382016-09-22 22:20:28 +00001088 std::vector<std::string> no_names;
1089 return CreateBreakpointsFromFile(file, no_names, new_bps);
1090}
1091
Zachary Turner97206d52017-05-12 04:51:55 +00001092Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1093 std::vector<std::string> &names,
1094 BreakpointIDList &new_bps) {
Jim Ingham01f16662016-09-14 19:07:35 +00001095 std::unique_lock<std::recursive_mutex> lock;
1096 GetBreakpointList().GetListMutex(lock);
1097
Zachary Turner97206d52017-05-12 04:51:55 +00001098 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +00001099 StructuredData::ObjectSP input_data_sp =
1100 StructuredData::ParseJSONFromFile(file, error);
1101 if (!error.Success()) {
1102 return error;
1103 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1104 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1105 file.GetPath().c_str());
1106 return error;
1107 }
1108
1109 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1110 if (!bkpt_array) {
1111 error.SetErrorStringWithFormat(
1112 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1113 return error;
1114 }
1115
1116 size_t num_bkpts = bkpt_array->GetSize();
Jim Ingham3acdf382016-09-22 22:20:28 +00001117 size_t num_names = names.size();
1118
Jim Ingham01f16662016-09-14 19:07:35 +00001119 for (size_t i = 0; i < num_bkpts; i++) {
1120 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1121 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1122 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1123 if (!bkpt_dict) {
1124 error.SetErrorStringWithFormat(
1125 "Invalid breakpoint data for element %zu from input file: %s.", i,
1126 file.GetPath().c_str());
1127 return error;
1128 }
1129 StructuredData::ObjectSP bkpt_data_sp =
1130 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
Jim Ingham3acdf382016-09-22 22:20:28 +00001131 if (num_names &&
1132 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1133 continue;
1134
Jim Ingham01f16662016-09-14 19:07:35 +00001135 BreakpointSP bkpt_sp =
1136 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1137 if (!error.Success()) {
1138 error.SetErrorStringWithFormat(
1139 "Error restoring breakpoint %zu from %s: %s.", i,
1140 file.GetPath().c_str(), error.AsCString());
1141 return error;
1142 }
1143 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1144 }
1145 return error;
1146}
1147
Johnny Chenedf50372011-09-23 21:21:43 +00001148// The flag 'end_to_end', default to true, signifies that the operation is
1149// performed end to end, for both the debugger and the debuggee.
1150
Johnny Chen01a67862011-10-14 00:42:25 +00001151// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1152// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153bool Target::RemoveAllWatchpoints(bool end_to_end) {
1154 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1155 if (log)
1156 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001157
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158 if (!end_to_end) {
1159 m_watchpoint_list.RemoveAll(true);
1160 return true;
1161 }
Johnny Chenedf50372011-09-23 21:21:43 +00001162
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001164
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 if (!ProcessIsValid())
1166 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001167
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 size_t num_watchpoints = m_watchpoint_list.GetSize();
1169 for (size_t i = 0; i < num_watchpoints; ++i) {
1170 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1171 if (!wp_sp)
1172 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001173
Zachary Turner97206d52017-05-12 04:51:55 +00001174 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 if (rc.Fail())
1176 return false;
1177 }
1178 m_watchpoint_list.RemoveAll(true);
1179 m_last_created_watchpoint.reset();
1180 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001181}
1182
Adrian Prantl05097242018-04-30 16:49:04 +00001183// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1184// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185bool Target::DisableAllWatchpoints(bool end_to_end) {
1186 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1187 if (log)
1188 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001189
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 if (!end_to_end) {
1191 m_watchpoint_list.SetEnabledAll(false);
1192 return true;
1193 }
Johnny Chenedf50372011-09-23 21:21:43 +00001194
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001196
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 if (!ProcessIsValid())
1198 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001199
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 size_t num_watchpoints = m_watchpoint_list.GetSize();
1201 for (size_t i = 0; i < num_watchpoints; ++i) {
1202 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1203 if (!wp_sp)
1204 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001205
Zachary Turner97206d52017-05-12 04:51:55 +00001206 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 if (rc.Fail())
1208 return false;
1209 }
1210 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001211}
1212
Adrian Prantl05097242018-04-30 16:49:04 +00001213// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1214// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215bool Target::EnableAllWatchpoints(bool end_to_end) {
1216 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1217 if (log)
1218 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (!end_to_end) {
1221 m_watchpoint_list.SetEnabledAll(true);
1222 return true;
1223 }
Johnny Chenedf50372011-09-23 21:21:43 +00001224
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001226
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 if (!ProcessIsValid())
1228 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001229
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 size_t num_watchpoints = m_watchpoint_list.GetSize();
1231 for (size_t i = 0; i < num_watchpoints; ++i) {
1232 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1233 if (!wp_sp)
1234 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001235
Zachary Turner97206d52017-05-12 04:51:55 +00001236 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 if (rc.Fail())
1238 return false;
1239 }
1240 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001241}
1242
Johnny Chena4d6bc92012-02-25 06:44:30 +00001243// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244bool Target::ClearAllWatchpointHitCounts() {
1245 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1246 if (log)
1247 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chena4d6bc92012-02-25 06:44:30 +00001248
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 size_t num_watchpoints = m_watchpoint_list.GetSize();
1250 for (size_t i = 0; i < num_watchpoints; ++i) {
1251 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1252 if (!wp_sp)
1253 return false;
Johnny Chena4d6bc92012-02-25 06:44:30 +00001254
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 wp_sp->ResetHitCount();
1256 }
1257 return true; // Success!
Johnny Chena4d6bc92012-02-25 06:44:30 +00001258}
1259
Enrico Granata5e3fe042015-02-11 00:37:54 +00001260// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261bool Target::ClearAllWatchpointHistoricValues() {
1262 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1263 if (log)
1264 log->Printf("Target::%s\n", __FUNCTION__);
1265
1266 size_t num_watchpoints = m_watchpoint_list.GetSize();
1267 for (size_t i = 0; i < num_watchpoints; ++i) {
1268 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1269 if (!wp_sp)
1270 return false;
1271
1272 wp_sp->ResetHistoricValues();
1273 }
1274 return true; // Success!
Enrico Granata5e3fe042015-02-11 00:37:54 +00001275}
1276
Adrian Prantl05097242018-04-30 16:49:04 +00001277// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1278// these operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1280 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1281 if (log)
1282 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001283
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 if (!ProcessIsValid())
1285 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001286
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 size_t num_watchpoints = m_watchpoint_list.GetSize();
1288 for (size_t i = 0; i < num_watchpoints; ++i) {
1289 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1290 if (!wp_sp)
1291 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001292
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 wp_sp->SetIgnoreCount(ignore_count);
1294 }
1295 return true; // Success!
Johnny Chen6cc60e82011-10-05 21:35:46 +00001296}
1297
Johnny Chen01a67862011-10-14 00:42:25 +00001298// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1300 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1301 if (log)
1302 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001303
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001305 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306
1307 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1308 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001309 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 if (rc.Success())
1311 return true;
1312
1313 // Else, fallthrough.
1314 }
1315 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001316}
1317
Johnny Chen01a67862011-10-14 00:42:25 +00001318// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1320 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1321 if (log)
1322 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001323
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001325 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326
1327 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1328 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001329 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 if (rc.Success())
1331 return true;
1332
1333 // Else, fallthrough.
1334 }
1335 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001336}
1337
Johnny Chen01a67862011-10-14 00:42:25 +00001338// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1340 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1341 if (log)
1342 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1345 if (watch_to_remove_sp == m_last_created_watchpoint)
1346 m_last_created_watchpoint.reset();
1347
1348 if (DisableWatchpointByID(watch_id)) {
1349 m_watchpoint_list.Remove(watch_id, true);
1350 return true;
1351 }
1352 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001353}
1354
Johnny Chen01a67862011-10-14 00:42:25 +00001355// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1357 uint32_t ignore_count) {
1358 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1359 if (log)
1360 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001361
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 if (!ProcessIsValid())
Johnny Chen6cc60e82011-10-05 21:35:46 +00001363 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364
1365 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1366 if (wp_sp) {
1367 wp_sp->SetIgnoreCount(ignore_count);
1368 return true;
1369 }
1370 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001371}
1372
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373ModuleSP Target::GetExecutableModule() {
1374 // search for the first executable in the module list
1375 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1376 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1377 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1378 if (obj == nullptr)
1379 continue;
1380 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1381 return module_sp;
1382 }
1383 // as fall back return the first module loaded
1384 return m_images.GetModuleAtIndex(0);
Greg Claytonaa149cb2011-08-11 02:48:45 +00001385}
1386
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387Module *Target::GetExecutableModulePointer() {
1388 return GetExecutableModule().get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001389}
1390
Kate Stoneb9c1b512016-09-06 20:57:50 +00001391static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1392 Target *target) {
Zachary Turner97206d52017-05-12 04:51:55 +00001393 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001394 StreamString feedback_stream;
1395 if (module_sp &&
1396 !module_sp->LoadScriptingResourceInTarget(target, error,
1397 &feedback_stream)) {
1398 if (error.AsCString())
1399 target->GetDebugger().GetErrorFile()->Printf(
1400 "unable to load scripting data for module %s - error reported was "
1401 "%s\n",
1402 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1403 error.AsCString());
1404 }
1405 if (feedback_stream.GetSize())
1406 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1407 feedback_stream.GetData());
Enrico Granata17598482012-11-08 02:22:02 +00001408}
1409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410void Target::ClearModules(bool delete_locations) {
1411 ModulesDidUnload(m_images, delete_locations);
1412 m_section_load_history.Clear();
1413 m_images.Clear();
1414 m_scratch_type_system_map.Clear();
1415 m_ast_importer_sp.reset();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001416}
1417
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418void Target::DidExec() {
1419 // When a process exec's we need to know about it so we can do some cleanup.
Pavel Labath13e37d42017-10-25 21:05:31 +00001420 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1421 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
Greg Claytonb35db632013-11-09 00:03:31 +00001422}
1423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424void Target::SetExecutableModule(ModuleSP &executable_sp,
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001425 LoadDependentFiles load_dependent_files) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1427 ClearModules(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 if (executable_sp) {
Pavel Labathf9d16472017-05-15 13:02:37 +00001430 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1431 Timer scoped_timer(func_cat,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 "Target::SetExecutableModule (executable = '%s')",
1433 executable_sp->GetFileSpec().GetPath().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435 m_images.Append(executable_sp); // The first image is our executable file
Jason Molendae1b68ad2012-12-05 00:25:49 +00001436
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 // If we haven't set an architecture yet, reset our architecture based on
1438 // what we found in the executable module.
Pavel Labath13e37d42017-10-25 21:05:31 +00001439 if (!m_arch.GetSpec().IsValid()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 m_arch = executable_sp->GetArchitecture();
Pavel Labath13e37d42017-10-25 21:05:31 +00001441 LLDB_LOG(log,
1442 "setting architecture to {0} ({1}) based on executable file",
1443 m_arch.GetSpec().GetArchitectureName(),
1444 m_arch.GetSpec().GetTriple().getTriple());
Jason Molendadad8af42015-11-10 04:11:37 +00001445 }
1446
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 FileSpecList dependent_files;
1448 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001449 bool load_dependents = true;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001450 switch (load_dependent_files) {
1451 case eLoadDependentsDefault:
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001452 load_dependents = executable_sp->IsExecutable();
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001453 break;
1454 case eLoadDependentsYes:
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001455 load_dependents = true;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001456 break;
1457 case eLoadDependentsNo:
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001458 load_dependents = false;
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001459 break;
1460 }
Greg Clayton095eeaa2013-11-05 23:28:00 +00001461
Jonas Devlieghere041e68f2018-09-27 06:59:15 +00001462 if (executable_objfile && load_dependents) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 executable_objfile->GetDependentModules(dependent_files);
1464 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1465 FileSpec dependent_file_spec(
1466 dependent_files.GetFileSpecPointerAtIndex(i));
1467 FileSpec platform_dependent_file_spec;
Greg Clayton67cc0632012-08-22 17:17:09 +00001468 if (m_platform_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1470 platform_dependent_file_spec);
1471 else
1472 platform_dependent_file_spec = dependent_file_spec;
1473
Pavel Labath13e37d42017-10-25 21:05:31 +00001474 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475 ModuleSP image_module_sp(GetSharedModule(module_spec));
1476 if (image_module_sp) {
1477 ObjectFile *objfile = image_module_sp->GetObjectFile();
1478 if (objfile)
1479 objfile->GetDependentModules(dependent_files);
1480 }
1481 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001484}
1485
Greg Clayton19c8f392018-08-06 16:56:10 +00001486bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
Pavel Labath13e37d42017-10-25 21:05:31 +00001488 bool missing_local_arch = !m_arch.GetSpec().IsValid();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 bool replace_local_arch = true;
1490 bool compatible_local_arch = false;
1491 ArchSpec other(arch_spec);
Greg Claytone72dfb32012-02-24 01:59:29 +00001492
Greg Clayton19c8f392018-08-06 16:56:10 +00001493 // Changing the architecture might mean that the currently selected platform
1494 // isn't compatible. Set the platform correctly if we are asked to do so,
1495 // otherwise assume the user will set the platform manually.
1496 if (set_platform) {
1497 if (other.IsValid()) {
1498 auto platform_sp = GetPlatform();
1499 if (!platform_sp ||
1500 !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1501 ArchSpec platform_arch;
1502 auto arch_platform_sp =
1503 Platform::GetPlatformForArchitecture(other, &platform_arch);
1504 if (arch_platform_sp) {
1505 SetPlatform(arch_platform_sp);
1506 if (platform_arch.IsValid())
1507 other = platform_arch;
1508 }
1509 }
1510 }
1511 }
1512
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513 if (!missing_local_arch) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001514 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1515 other.MergeFrom(m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516
Pavel Labath13e37d42017-10-25 21:05:31 +00001517 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 compatible_local_arch = true;
1519 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1520 env_changed;
1521
Pavel Labath13e37d42017-10-25 21:05:31 +00001522 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 os_changed, os_ver_changed, env_changed);
1524
1525 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1526 replace_local_arch = false;
1527 }
1528 }
1529 }
1530
1531 if (compatible_local_arch || missing_local_arch) {
1532 // If we haven't got a valid arch spec, or the architectures are compatible
Adrian Prantl05097242018-04-30 16:49:04 +00001533 // update the architecture, unless the one we already have is more
1534 // specified
Kate Stoneb9c1b512016-09-06 20:57:50 +00001535 if (replace_local_arch)
1536 m_arch = other;
Pavel Labath13e37d42017-10-25 21:05:31 +00001537 LLDB_LOG(log, "set architecture to {0} ({1})",
1538 m_arch.GetSpec().GetArchitectureName(),
1539 m_arch.GetSpec().GetTriple().getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001540 return true;
1541 }
1542
1543 // If we have an executable file, try to reset the executable to the desired
1544 // architecture
1545 if (log)
1546 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1547 arch_spec.GetArchitectureName(),
1548 arch_spec.GetTriple().getTriple().c_str());
1549 m_arch = other;
1550 ModuleSP executable_sp = GetExecutableModule();
1551
1552 ClearModules(true);
1553 // Need to do something about unsetting breakpoints.
1554
1555 if (executable_sp) {
1556 if (log)
1557 log->Printf("Target::SetArchitecture Trying to select executable file "
1558 "architecture %s (%s)",
1559 arch_spec.GetArchitectureName(),
1560 arch_spec.GetTriple().getTriple().c_str());
1561 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
Zachary Turner97206d52017-05-12 04:51:55 +00001562 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1563 &GetExecutableSearchPaths(),
1564 nullptr, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565
1566 if (!error.Fail() && executable_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00001567 SetExecutableModule(executable_sp, eLoadDependentsYes);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568 return true;
1569 }
1570 }
1571 return false;
Greg Claytondb598232011-01-07 01:57:07 +00001572}
1573
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1575 if (arch_spec.IsValid()) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001576 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001577 // The current target arch is compatible with "arch_spec", see if we can
1578 // improve our current architecture using bits from "arch_spec"
Greg Claytonc749eb82011-07-11 05:12:02 +00001579
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580 // Merge bits from arch_spec into "merged_arch" and set our architecture
Pavel Labath13e37d42017-10-25 21:05:31 +00001581 ArchSpec merged_arch(m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 merged_arch.MergeFrom(arch_spec);
1583 return SetArchitecture(merged_arch);
1584 } else {
1585 // The new architecture is different, we just need to replace it
1586 return SetArchitecture(arch_spec);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001587 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588 }
1589 return false;
1590}
Greg Claytonc749eb82011-07-11 05:12:02 +00001591
Kate Stoneb9c1b512016-09-06 20:57:50 +00001592void Target::WillClearList(const ModuleList &module_list) {}
1593
1594void Target::ModuleAdded(const ModuleList &module_list,
1595 const ModuleSP &module_sp) {
1596 // A module is being added to this target for the first time
1597 if (m_valid) {
1598 ModuleList my_module_list;
1599 my_module_list.Append(module_sp);
1600 LoadScriptingResourceForModule(module_sp, this);
1601 ModulesDidLoad(my_module_list);
1602 }
1603}
1604
1605void Target::ModuleRemoved(const ModuleList &module_list,
1606 const ModuleSP &module_sp) {
1607 // A module is being removed from this target.
1608 if (m_valid) {
1609 ModuleList my_module_list;
1610 my_module_list.Append(module_sp);
1611 ModulesDidUnload(my_module_list, false);
1612 }
1613}
1614
1615void Target::ModuleUpdated(const ModuleList &module_list,
1616 const ModuleSP &old_module_sp,
1617 const ModuleSP &new_module_sp) {
1618 // A module is replacing an already added module
1619 if (m_valid) {
1620 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1621 new_module_sp);
1622 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1623 old_module_sp, new_module_sp);
1624 }
1625}
1626
1627void Target::ModulesDidLoad(ModuleList &module_list) {
1628 if (m_valid && module_list.GetSize()) {
1629 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1630 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1631 if (m_process_sp) {
1632 m_process_sp->ModulesDidLoad(module_list);
1633 }
1634 BroadcastEvent(eBroadcastBitModulesLoaded,
1635 new TargetEventData(this->shared_from_this(), module_list));
1636 }
1637}
1638
1639void Target::SymbolsDidLoad(ModuleList &module_list) {
1640 if (m_valid && module_list.GetSize()) {
1641 if (m_process_sp) {
1642 LanguageRuntime *runtime =
1643 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1644 if (runtime) {
1645 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1646 objc_runtime->SymbolsDidLoad(module_list);
1647 }
1648 }
1649
1650 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1651 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1652 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1653 new TargetEventData(this->shared_from_this(), module_list));
1654 }
1655}
1656
1657void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1658 if (m_valid && module_list.GetSize()) {
1659 UnloadModuleSections(module_list);
1660 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1661 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1662 delete_locations);
1663 BroadcastEvent(eBroadcastBitModulesUnloaded,
1664 new TargetEventData(this->shared_from_this(), module_list));
1665 }
1666}
1667
1668bool Target::ModuleIsExcludedForUnconstrainedSearches(
1669 const FileSpec &module_file_spec) {
1670 if (GetBreakpointsConsultPlatformAvoidList()) {
1671 ModuleList matchingModules;
1672 ModuleSpec module_spec(module_file_spec);
1673 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1674
1675 // If there is more than one module for this file spec, only return true if
1676 // ALL the modules are on the
1677 // black list.
1678 if (num_modules > 0) {
1679 for (size_t i = 0; i < num_modules; i++) {
1680 if (!ModuleIsExcludedForUnconstrainedSearches(
1681 matchingModules.GetModuleAtIndex(i)))
1682 return false;
1683 }
1684 return true;
1685 }
1686 }
1687 return false;
1688}
1689
1690bool Target::ModuleIsExcludedForUnconstrainedSearches(
1691 const lldb::ModuleSP &module_sp) {
1692 if (GetBreakpointsConsultPlatformAvoidList()) {
1693 if (m_platform_sp)
1694 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1695 module_sp);
1696 }
1697 return false;
1698}
1699
1700size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001701 size_t dst_len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702 SectionSP section_sp(addr.GetSection());
1703 if (section_sp) {
1704 // If the contents of this section are encrypted, the on-disk file is
1705 // unusable. Read only from live memory.
1706 if (section_sp->IsEncrypted()) {
1707 error.SetErrorString("section is encrypted");
1708 return 0;
1709 }
1710 ModuleSP module_sp(section_sp->GetModule());
1711 if (module_sp) {
1712 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1713 if (objfile) {
1714 size_t bytes_read = objfile->ReadSectionData(
1715 section_sp.get(), addr.GetOffset(), dst, dst_len);
Greg Claytondb598232011-01-07 01:57:07 +00001716 if (bytes_read > 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001718 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719 error.SetErrorStringWithFormat("error reading data from section %s",
1720 section_sp->GetName().GetCString());
1721 } else
1722 error.SetErrorString("address isn't from a object file");
1723 } else
1724 error.SetErrorString("address isn't in a module");
1725 } else
1726 error.SetErrorString("address doesn't contain a section that points to a "
1727 "section in a object file");
1728
1729 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001730}
1731
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001733 void *dst, size_t dst_len, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734 lldb::addr_t *load_addr_ptr) {
1735 error.Clear();
1736
Adrian Prantl05097242018-04-30 16:49:04 +00001737 // if we end up reading this from process memory, we will fill this with the
1738 // actual load address
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739 if (load_addr_ptr)
1740 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1741
1742 size_t bytes_read = 0;
1743
1744 addr_t load_addr = LLDB_INVALID_ADDRESS;
1745 addr_t file_addr = LLDB_INVALID_ADDRESS;
1746 Address resolved_addr;
1747 if (!addr.IsSectionOffset()) {
1748 SectionLoadList &section_load_list = GetSectionLoadList();
1749 if (section_load_list.IsEmpty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001750 // No sections are loaded, so we must assume we are not running yet and
1751 // anything we are given is a file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1753 // offset is the file address
1754 m_images.ResolveFileAddress(file_addr, resolved_addr);
1755 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001756 // We have at least one section loaded. This can be because we have
1757 // manually loaded some sections with "target modules load ..." or
1758 // because we have have a live process that has sections loaded through
1759 // the dynamic loader
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1761 // offset is the load address
1762 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1763 }
1764 }
1765 if (!resolved_addr.IsValid())
1766 resolved_addr = addr;
1767
1768 if (prefer_file_cache) {
1769 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1770 if (bytes_read > 0)
1771 return bytes_read;
1772 }
1773
1774 if (ProcessIsValid()) {
1775 if (load_addr == LLDB_INVALID_ADDRESS)
1776 load_addr = resolved_addr.GetLoadAddress(this);
1777
1778 if (load_addr == LLDB_INVALID_ADDRESS) {
1779 ModuleSP addr_module_sp(resolved_addr.GetModule());
1780 if (addr_module_sp && addr_module_sp->GetFileSpec())
Zachary Turner827d5d72016-12-16 04:27:00 +00001781 error.SetErrorStringWithFormatv(
1782 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1783 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 else
1785 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1786 resolved_addr.GetFileAddress());
1787 } else {
1788 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1789 if (bytes_read != dst_len) {
1790 if (error.Success()) {
1791 if (bytes_read == 0)
1792 error.SetErrorStringWithFormat(
1793 "read memory from 0x%" PRIx64 " failed", load_addr);
1794 else
1795 error.SetErrorStringWithFormat(
1796 "only %" PRIu64 " of %" PRIu64
1797 " bytes were read from memory at 0x%" PRIx64,
1798 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1799 }
1800 }
1801 if (bytes_read) {
1802 if (load_addr_ptr)
1803 *load_addr_ptr = load_addr;
1804 return bytes_read;
1805 }
Adrian Prantl05097242018-04-30 16:49:04 +00001806 // If the address is not section offset we have an address that doesn't
1807 // resolve to any address in any currently loaded shared libraries and we
1808 // failed to read memory so there isn't anything more we can do. If it is
1809 // section offset, we might be able to read cached memory from the object
1810 // file.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811 if (!resolved_addr.IsSectionOffset())
1812 return 0;
1813 }
1814 }
1815
1816 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001817 // If we didn't already try and read from the object file cache, then try
1818 // it after failing to read from the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1820 }
1821 return 0;
1822}
1823
1824size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001825 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 char buf[256];
1827 out_str.clear();
1828 addr_t curr_addr = addr.GetLoadAddress(this);
1829 Address address(addr);
1830 while (1) {
1831 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1832 if (length == 0)
1833 break;
1834 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00001835 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1836 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00001837 if (length == sizeof(buf) - 1)
1838 curr_addr += length;
1839 else
1840 break;
1841 address = Address(curr_addr);
1842 }
1843 return out_str.size();
1844}
1845
1846size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001847 size_t dst_max_len, Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001848 size_t total_cstr_len = 0;
1849 if (dst && dst_max_len) {
1850 result_error.Clear();
1851 // NULL out everything just to be safe
1852 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00001853 Status error;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001854 addr_t curr_addr = addr.GetLoadAddress(this);
1855 Address address(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856
Adrian Prantl05097242018-04-30 16:49:04 +00001857 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1858 // this really needs to be tied to the memory cache subsystem's cache line
1859 // size, so leave this as a fixed constant.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001860 const size_t cache_line_size = 512;
1861
1862 size_t bytes_left = dst_max_len - 1;
1863 char *curr_dst = dst;
1864
1865 while (bytes_left > 0) {
1866 addr_t cache_line_bytes_left =
1867 cache_line_size - (curr_addr % cache_line_size);
1868 addr_t bytes_to_read =
1869 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1870 size_t bytes_read =
1871 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1872
1873 if (bytes_read == 0) {
1874 result_error = error;
1875 dst[total_cstr_len] = '\0';
1876 break;
1877 }
1878 const size_t len = strlen(curr_dst);
1879
1880 total_cstr_len += len;
1881
1882 if (len < bytes_to_read)
1883 break;
1884
1885 curr_dst += bytes_read;
1886 curr_addr += bytes_read;
1887 bytes_left -= bytes_read;
1888 address = Address(curr_addr);
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001889 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 } else {
1891 if (dst == nullptr)
1892 result_error.SetErrorString("invalid arguments");
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001893 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894 result_error.Clear();
1895 }
1896 return total_cstr_len;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001897}
1898
Kate Stoneb9c1b512016-09-06 20:57:50 +00001899size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1900 bool prefer_file_cache,
1901 uint32_t byte_size, bool is_signed,
Zachary Turner97206d52017-05-12 04:51:55 +00001902 Scalar &scalar, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903 uint64_t uval;
1904
1905 if (byte_size <= sizeof(uval)) {
1906 size_t bytes_read =
1907 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1908 if (bytes_read == byte_size) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001909 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1910 m_arch.GetSpec().GetAddressByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 lldb::offset_t offset = 0;
1912 if (byte_size <= 4)
1913 scalar = data.GetMaxU32(&offset, byte_size);
1914 else
1915 scalar = data.GetMaxU64(&offset, byte_size);
1916
1917 if (is_signed)
1918 scalar.SignExtend(byte_size * 8);
1919 return bytes_read;
1920 }
1921 } else {
1922 error.SetErrorStringWithFormat(
1923 "byte size of %u is too large for integer scalar type", byte_size);
1924 }
1925 return 0;
1926}
1927
1928uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1929 bool prefer_file_cache,
1930 size_t integer_byte_size,
1931 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00001932 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933 Scalar scalar;
1934 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1935 false, scalar, error))
1936 return scalar.ULongLong(fail_value);
1937 return fail_value;
1938}
1939
1940bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001941 Status &error, Address &pointer_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942 Scalar scalar;
1943 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
Pavel Labath13e37d42017-10-25 21:05:31 +00001944 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001945 error)) {
1946 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1947 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1948 SectionLoadList &section_load_list = GetSectionLoadList();
1949 if (section_load_list.IsEmpty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001950 // No sections are loaded, so we must assume we are not running yet and
1951 // anything we are given is a file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1953 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001954 // We have at least one section loaded. This can be because we have
1955 // manually loaded some sections with "target modules load ..." or
1956 // because we have have a live process that has sections loaded through
1957 // the dynamic loader
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1959 }
Adrian Prantl05097242018-04-30 16:49:04 +00001960 // We weren't able to resolve the pointer value, so just return an
1961 // address with no section
Kate Stoneb9c1b512016-09-06 20:57:50 +00001962 if (!pointer_addr.IsValid())
1963 pointer_addr.SetOffset(pointer_vm_addr);
1964 return true;
1965 }
1966 }
1967 return false;
1968}
1969
1970ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
Zachary Turner97206d52017-05-12 04:51:55 +00001971 Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 ModuleSP module_sp;
1973
Zachary Turner97206d52017-05-12 04:51:55 +00001974 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001975
1976 // First see if we already have this module in our module list. If we do,
Adrian Prantl05097242018-04-30 16:49:04 +00001977 // then we're done, we don't need to consult the shared modules list. But
1978 // only do this if we are passed a UUID.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979
1980 if (module_spec.GetUUID().IsValid())
1981 module_sp = m_images.FindFirstModule(module_spec);
1982
1983 if (!module_sp) {
1984 ModuleSP old_module_sp; // This will get filled in if we have a new version
1985 // of the library
1986 bool did_create_module = false;
1987
1988 // If there are image search path entries, try to use them first to acquire
1989 // a suitable image.
1990 if (m_image_search_paths.GetSize()) {
1991 ModuleSpec transformed_spec(module_spec);
1992 if (m_image_search_paths.RemapPath(
1993 module_spec.GetFileSpec().GetDirectory(),
1994 transformed_spec.GetFileSpec().GetDirectory())) {
1995 transformed_spec.GetFileSpec().GetFilename() =
1996 module_spec.GetFileSpec().GetFilename();
1997 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1998 &GetExecutableSearchPaths(),
1999 &old_module_sp, &did_create_module);
2000 }
2001 }
2002
2003 if (!module_sp) {
2004 // If we have a UUID, we can check our global shared module list in case
2005 // we already have it. If we don't have a valid UUID, then we can't since
2006 // the path in "module_spec" will be a platform path, and we will need to
2007 // let the platform find that file. For example, we could be asking for
2008 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2009 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2010 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2011 // cache.
2012 if (module_spec.GetUUID().IsValid()) {
2013 // We have a UUID, it is OK to check the global module list...
2014 error = ModuleList::GetSharedModule(module_spec, module_sp,
2015 &GetExecutableSearchPaths(),
2016 &old_module_sp, &did_create_module);
2017 }
2018
2019 if (!module_sp) {
2020 // The platform is responsible for finding and caching an appropriate
2021 // module in the shared module cache.
2022 if (m_platform_sp) {
2023 error = m_platform_sp->GetSharedModule(
2024 module_spec, m_process_sp.get(), module_sp,
2025 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
2026 } else {
2027 error.SetErrorString("no platform is currently set");
Greg Claytond16e1e52011-07-12 17:06:17 +00002028 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002029 }
Greg Claytond16e1e52011-07-12 17:06:17 +00002030 }
Greg Claytond16e1e52011-07-12 17:06:17 +00002031
Kate Stoneb9c1b512016-09-06 20:57:50 +00002032 // We found a module that wasn't in our target list. Let's make sure that
Adrian Prantl05097242018-04-30 16:49:04 +00002033 // there wasn't an equivalent module in the list already, and if there was,
2034 // let's remove it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 if (module_sp) {
2036 ObjectFile *objfile = module_sp->GetObjectFile();
2037 if (objfile) {
2038 switch (objfile->GetType()) {
2039 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2040 /// a program's execution state
2041 case ObjectFile::eTypeExecutable: /// A normal executable
2042 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2043 /// executable
2044 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2045 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2046 /// used during execution
2047 break;
2048 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2049 /// debug information
2050 if (error_ptr)
2051 error_ptr->SetErrorString("debug info files aren't valid target "
2052 "modules, please specify an executable");
2053 return ModuleSP();
2054 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2055 /// against but not used for
2056 /// execution
2057 if (error_ptr)
2058 error_ptr->SetErrorString("stub libraries aren't valid target "
2059 "modules, please specify an executable");
2060 return ModuleSP();
2061 default:
2062 if (error_ptr)
2063 error_ptr->SetErrorString(
2064 "unsupported file type, please specify an executable");
2065 return ModuleSP();
Greg Claytond16e1e52011-07-12 17:06:17 +00002066 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067 // GetSharedModule is not guaranteed to find the old shared module, for
Adrian Prantl05097242018-04-30 16:49:04 +00002068 // instance in the common case where you pass in the UUID, it is only
2069 // going to find the one module matching the UUID. In fact, it has no
2070 // good way to know what the "old module" relevant to this target is,
2071 // since there might be many copies of a module with this file spec in
2072 // various running debug sessions, but only one of them will belong to
2073 // this target. So let's remove the UUID from the module list, and look
2074 // in the target's module list. Only do this if there is SOMETHING else
2075 // in the module spec...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076 if (!old_module_sp) {
2077 if (module_spec.GetUUID().IsValid() &&
2078 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2079 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2080 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2081 module_spec_copy.GetUUID().Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002082
Kate Stoneb9c1b512016-09-06 20:57:50 +00002083 ModuleList found_modules;
2084 size_t num_found =
2085 m_images.FindModules(module_spec_copy, found_modules);
2086 if (num_found == 1) {
2087 old_module_sp = found_modules.GetModuleAtIndex(0);
Jim Ingham4a94c912012-05-17 18:38:42 +00002088 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 }
Greg Claytonb69bb2e2012-04-27 00:58:27 +00002090 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002091
Jim Ingham7fca8c02017-04-28 00:51:06 +00002092 // Preload symbols outside of any lock, so hopefully we can do this for
2093 // each library in parallel.
2094 if (GetPreloadSymbols())
2095 module_sp->PreloadSymbols();
2096
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 if (old_module_sp &&
2098 m_images.GetIndexForModule(old_module_sp.get()) !=
2099 LLDB_INVALID_INDEX32) {
2100 m_images.ReplaceModule(old_module_sp, module_sp);
2101 Module *old_module_ptr = old_module_sp.get();
2102 old_module_sp.reset();
2103 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2104 } else
2105 m_images.Append(module_sp);
2106 } else
2107 module_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 }
2110 if (error_ptr)
2111 *error_ptr = error;
2112 return module_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113}
2114
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115TargetSP Target::CalculateTarget() { return shared_from_this(); }
2116
2117ProcessSP Target::CalculateProcess() { return m_process_sp; }
2118
2119ThreadSP Target::CalculateThread() { return ThreadSP(); }
2120
2121StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2122
2123void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2124 exe_ctx.Clear();
2125 exe_ctx.SetTargetPtr(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126}
2127
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128PathMappingList &Target::GetImageSearchPathList() {
2129 return m_image_search_paths;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130}
2131
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2133 void *baton) {
2134 Target *target = (Target *)baton;
2135 ModuleSP exe_module_sp(target->GetExecutableModule());
2136 if (exe_module_sp)
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00002137 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138}
2139
Zachary Turner97206d52017-05-12 04:51:55 +00002140TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 lldb::LanguageType language,
2142 bool create_on_demand) {
2143 if (!m_valid)
2144 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145
Kate Stoneb9c1b512016-09-06 20:57:50 +00002146 if (error) {
2147 error->Clear();
2148 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2151 // assembly code
2152 || language == eLanguageTypeUnknown) {
2153 std::set<lldb::LanguageType> languages_for_types;
2154 std::set<lldb::LanguageType> languages_for_expressions;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2157 languages_for_expressions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 if (languages_for_expressions.count(eLanguageTypeC)) {
2160 language = eLanguageTypeC; // LLDB's default. Override by setting the
2161 // target language.
2162 } else {
2163 if (languages_for_expressions.empty()) {
Greg Clayton5beec212015-10-08 21:04:34 +00002164 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002165 } else {
2166 language = *languages_for_expressions.begin();
2167 }
Sean Callanana994b0b2015-10-02 18:40:30 +00002168 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 }
Sean Callananb92bd752015-10-01 16:28:02 +00002170
Kate Stoneb9c1b512016-09-06 20:57:50 +00002171 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2172 create_on_demand);
Sean Callananb92bd752015-10-01 16:28:02 +00002173}
2174
2175PersistentExpressionState *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2177 TypeSystem *type_system =
2178 GetScratchTypeSystemForLanguage(nullptr, language, true);
2179
2180 if (type_system) {
2181 return type_system->GetPersistentExpressionState();
2182 } else {
2183 return nullptr;
2184 }
Jim Ingham151c0322015-09-15 21:13:50 +00002185}
2186
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187UserExpression *Target::GetUserExpressionForLanguage(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002188 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189 Expression::ResultType desired_type,
Zachary Turner97206d52017-05-12 04:51:55 +00002190 const EvaluateExpressionOptions &options, Status &error) {
2191 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192
2193 TypeSystem *type_system =
2194 GetScratchTypeSystemForLanguage(&type_system_error, language);
2195 UserExpression *user_expr = nullptr;
2196
2197 if (!type_system) {
2198 error.SetErrorStringWithFormat(
2199 "Could not find type system for language %s: %s",
2200 Language::GetNameForLanguageType(language),
2201 type_system_error.AsCString());
2202 return nullptr;
2203 }
2204
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002205 user_expr = type_system->GetUserExpression(expr, prefix, language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206 desired_type, options);
2207 if (!user_expr)
2208 error.SetErrorStringWithFormat(
2209 "Could not create an expression for language %s",
2210 Language::GetNameForLanguageType(language));
2211
2212 return user_expr;
Jim Ingham151c0322015-09-15 21:13:50 +00002213}
2214
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215FunctionCaller *Target::GetFunctionCallerForLanguage(
2216 lldb::LanguageType language, const CompilerType &return_type,
2217 const Address &function_address, const ValueList &arg_value_list,
Zachary Turner97206d52017-05-12 04:51:55 +00002218 const char *name, Status &error) {
2219 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220 TypeSystem *type_system =
2221 GetScratchTypeSystemForLanguage(&type_system_error, language);
2222 FunctionCaller *persistent_fn = nullptr;
2223
2224 if (!type_system) {
2225 error.SetErrorStringWithFormat(
2226 "Could not find type system for language %s: %s",
2227 Language::GetNameForLanguageType(language),
2228 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002229 return persistent_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002230 }
2231
2232 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2233 arg_value_list, name);
2234 if (!persistent_fn)
2235 error.SetErrorStringWithFormat(
2236 "Could not create an expression for language %s",
2237 Language::GetNameForLanguageType(language));
2238
2239 return persistent_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002240}
2241
2242UtilityFunction *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243Target::GetUtilityFunctionForLanguage(const char *text,
2244 lldb::LanguageType language,
Zachary Turner97206d52017-05-12 04:51:55 +00002245 const char *name, Status &error) {
2246 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002247 TypeSystem *type_system =
2248 GetScratchTypeSystemForLanguage(&type_system_error, language);
2249 UtilityFunction *utility_fn = nullptr;
2250
2251 if (!type_system) {
2252 error.SetErrorStringWithFormat(
2253 "Could not find type system for language %s: %s",
2254 Language::GetNameForLanguageType(language),
2255 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002256 return utility_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 }
2258
2259 utility_fn = type_system->GetUtilityFunction(text, name);
2260 if (!utility_fn)
2261 error.SetErrorStringWithFormat(
2262 "Could not create an expression for language %s",
2263 Language::GetNameForLanguageType(language));
2264
2265 return utility_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002266}
2267
Kate Stoneb9c1b512016-09-06 20:57:50 +00002268ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2269 if (m_valid) {
2270 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2271 nullptr, eLanguageTypeC, create_on_demand))
2272 return llvm::dyn_cast<ClangASTContext>(type_system);
2273 }
2274 return nullptr;
2275}
2276
2277ClangASTImporterSP Target::GetClangASTImporter() {
2278 if (m_valid) {
2279 if (!m_ast_importer_sp) {
2280 m_ast_importer_sp.reset(new ClangASTImporter());
Sean Callanan4bf80d52011-11-15 22:27:19 +00002281 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 return m_ast_importer_sp;
2283 }
2284 return ClangASTImporterSP();
Sean Callananb92bd752015-10-01 16:28:02 +00002285}
2286
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2288
2289void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2290
2291FileSpecList Target::GetDefaultExecutableSearchPaths() {
2292 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2293 if (properties_sp)
2294 return properties_sp->GetExecutableSearchPaths();
2295 return FileSpecList();
Sean Callanan686b2312011-11-16 18:20:47 +00002296}
2297
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2299 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2300 if (properties_sp)
2301 return properties_sp->GetDebugFileSearchPaths();
2302 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002303}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002304
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2306 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2307 if (properties_sp)
2308 return properties_sp->GetClangModuleSearchPaths();
2309 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002310}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002311
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312ArchSpec Target::GetDefaultArchitecture() {
2313 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2314 if (properties_sp)
2315 return properties_sp->GetDefaultArchitecture();
2316 return ArchSpec();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002317}
2318
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2320 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2321 if (properties_sp) {
2322 LogIfAnyCategoriesSet(
2323 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2324 "default architecture to %s (%s)",
2325 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2326 return properties_sp->SetDefaultArchitecture(arch);
2327 }
Michael Sartaina7499c92013-07-01 19:45:50 +00002328}
2329
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2331 const SymbolContext *sc_ptr) {
2332 // The target can either exist in the "process" of ExecutionContext, or in
2333 // the "target_sp" member of SymbolContext. This accessor helper function
2334 // will get the target from one of these locations.
2335
2336 Target *target = nullptr;
2337 if (sc_ptr != nullptr)
2338 target = sc_ptr->target_sp.get();
2339 if (target == nullptr && exe_ctx_ptr)
2340 target = exe_ctx_ptr->GetTargetPtr();
2341 return target;
Sean Callanan85054342015-04-03 15:39:47 +00002342}
2343
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344ExpressionResults Target::EvaluateExpression(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002345 llvm::StringRef expr, ExecutionContextScope *exe_scope,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002346 lldb::ValueObjectSP &result_valobj_sp,
2347 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2348 result_valobj_sp.reset();
Caroline Ticedaccaa92010-09-20 20:44:43 +00002349
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 ExpressionResults execution_results = eExpressionSetupError;
Caroline Ticedaccaa92010-09-20 20:44:43 +00002351
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002352 if (expr.empty())
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002353 return execution_results;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354
Adrian Prantl05097242018-04-30 16:49:04 +00002355 // We shouldn't run stop hooks in expressions. Be sure to reset this if you
2356 // return anywhere within this function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 bool old_suppress_value = m_suppress_stop_hooks;
2358 m_suppress_stop_hooks = true;
2359
2360 ExecutionContext exe_ctx;
2361
2362 if (exe_scope) {
2363 exe_scope->CalculateExecutionContext(exe_ctx);
2364 } else if (m_process_sp) {
2365 m_process_sp->CalculateExecutionContext(exe_ctx);
2366 } else {
2367 CalculateExecutionContext(exe_ctx);
2368 }
2369
Adrian Prantl05097242018-04-30 16:49:04 +00002370 // Make sure we aren't just trying to see the value of a persistent variable
2371 // (something like "$0")
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372 lldb::ExpressionVariableSP persistent_var_sp;
2373 // Only check for persistent variables the expression starts with a '$'
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002374 if (expr[0] == '$')
Kate Stoneb9c1b512016-09-06 20:57:50 +00002375 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2376 ->GetPersistentExpressionState()
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002377 ->GetVariable(expr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378
2379 if (persistent_var_sp) {
2380 result_valobj_sp = persistent_var_sp->GetValueObject();
2381 execution_results = eExpressionCompleted;
2382 } else {
Pavel Labath50251fc2017-12-21 10:54:30 +00002383 llvm::StringRef prefix = GetExpressionPrefixContents();
Zachary Turner97206d52017-05-12 04:51:55 +00002384 Status error;
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002385 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2386 result_valobj_sp, error,
2387 0, // Line Number
2388 fixed_expression);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389 }
2390
2391 m_suppress_stop_hooks = old_suppress_value;
2392
2393 return execution_results;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002394}
2395
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002396lldb::ExpressionVariableSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397Target::GetPersistentVariable(const ConstString &name) {
2398 lldb::ExpressionVariableSP variable_sp;
2399 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002400 [name, &variable_sp](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 if (PersistentExpressionState *persistent_state =
2402 type_system->GetPersistentExpressionState()) {
2403 variable_sp = persistent_state->GetVariable(name);
Greg Clayton5beec212015-10-08 21:04:34 +00002404
Kate Stoneb9c1b512016-09-06 20:57:50 +00002405 if (variable_sp)
2406 return false; // Stop iterating the ForEach
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002407 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 return true; // Keep iterating the ForEach
2409 });
2410 return variable_sp;
Zachary Turner32abc6e2015-03-03 19:23:09 +00002411}
2412
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2414 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2415
2416 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002417 [name, &address](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 if (PersistentExpressionState *persistent_state =
2419 type_system->GetPersistentExpressionState()) {
2420 address = persistent_state->LookupSymbol(name);
2421 if (address != LLDB_INVALID_ADDRESS)
2422 return false; // Stop iterating the ForEach
Sean Callananb92bd752015-10-01 16:28:02 +00002423 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424 return true; // Keep iterating the ForEach
2425 });
2426 return address;
Sean Callananb92bd752015-10-01 16:28:02 +00002427}
2428
Kate Stoneb9c1b512016-09-06 20:57:50 +00002429lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2430 AddressClass addr_class) const {
Tatyana Krasnukha7aa9e7b2018-09-21 18:56:44 +00002431 auto arch_plugin = GetArchitecturePlugin();
2432 return arch_plugin ?
2433 arch_plugin->GetCallableLoadAddress(load_addr, addr_class) : load_addr;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002434}
2435
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2437 AddressClass addr_class) const {
Tatyana Krasnukha7aa9e7b2018-09-21 18:56:44 +00002438 auto arch_plugin = GetArchitecturePlugin();
2439 return arch_plugin ?
2440 arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class) : load_addr;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002441}
2442
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
Tatyana Krasnukha7aa9e7b2018-09-21 18:56:44 +00002444 auto arch_plugin = GetArchitecturePlugin();
2445 return arch_plugin ?
2446 arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447}
2448
2449SourceManager &Target::GetSourceManager() {
2450 if (!m_source_manager_ap)
2451 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2452 return *m_source_manager_ap;
2453}
2454
2455ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2456 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2457 // we can make it
2458 // per-target
2459
2460 {
2461 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2462
2463 if (!m_clang_modules_decl_vendor_ap) {
2464 m_clang_modules_decl_vendor_ap.reset(
2465 ClangModulesDeclVendor::Create(*this));
2466 }
2467 }
2468
2469 return m_clang_modules_decl_vendor_ap.get();
2470}
2471
2472Target::StopHookSP Target::CreateStopHook() {
2473 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2474 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2475 m_stop_hooks[new_uid] = stop_hook_sp;
2476 return stop_hook_sp;
2477}
2478
2479bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2480 size_t num_removed = m_stop_hooks.erase(user_id);
2481 return (num_removed != 0);
2482}
2483
2484void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2485
2486Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2487 StopHookSP found_hook;
2488
2489 StopHookCollection::iterator specified_hook_iter;
2490 specified_hook_iter = m_stop_hooks.find(user_id);
2491 if (specified_hook_iter != m_stop_hooks.end())
2492 found_hook = (*specified_hook_iter).second;
2493 return found_hook;
2494}
2495
2496bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2497 bool active_state) {
2498 StopHookCollection::iterator specified_hook_iter;
2499 specified_hook_iter = m_stop_hooks.find(user_id);
2500 if (specified_hook_iter == m_stop_hooks.end())
2501 return false;
2502
2503 (*specified_hook_iter).second->SetIsActive(active_state);
2504 return true;
2505}
2506
2507void Target::SetAllStopHooksActiveState(bool active_state) {
2508 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2509 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2510 (*pos).second->SetIsActive(active_state);
2511 }
2512}
2513
2514void Target::RunStopHooks() {
2515 if (m_suppress_stop_hooks)
2516 return;
2517
2518 if (!m_process_sp)
2519 return;
Jim Ingham45816d62017-12-05 02:34:05 +00002520
2521 // Somebody might have restarted the process:
2522 if (m_process_sp->GetState() != eStateStopped)
2523 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524
2525 // <rdar://problem/12027563> make sure we check that we are not stopped
Adrian Prantl05097242018-04-30 16:49:04 +00002526 // because of us running a user expression since in that case we do not want
2527 // to run the stop-hooks
Kate Stoneb9c1b512016-09-06 20:57:50 +00002528 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2529 return;
2530
2531 if (m_stop_hooks.empty())
2532 return;
2533
2534 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2535
2536 // If there aren't any active stop hooks, don't bother either:
2537 bool any_active_hooks = false;
2538 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2539 if ((*pos).second->IsActive()) {
2540 any_active_hooks = true;
2541 break;
2542 }
2543 }
2544 if (!any_active_hooks)
2545 return;
2546
2547 CommandReturnObject result;
2548
2549 std::vector<ExecutionContext> exc_ctx_with_reasons;
2550 std::vector<SymbolContext> sym_ctx_with_reasons;
2551
2552 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2553 size_t num_threads = cur_threadlist.GetSize();
2554 for (size_t i = 0; i < num_threads; i++) {
2555 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2556 if (cur_thread_sp->ThreadStoppedForAReason()) {
2557 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2558 exc_ctx_with_reasons.push_back(ExecutionContext(
2559 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2560 sym_ctx_with_reasons.push_back(
2561 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2562 }
2563 }
2564
2565 // If no threads stopped for a reason, don't run the stop-hooks.
2566 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2567 if (num_exe_ctx == 0)
2568 return;
2569
2570 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2571 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2572
2573 bool keep_going = true;
2574 bool hooks_ran = false;
2575 bool print_hook_header = (m_stop_hooks.size() != 1);
2576 bool print_thread_header = (num_exe_ctx != 1);
2577
2578 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2579 // result.Clear();
2580 StopHookSP cur_hook_sp = (*pos).second;
2581 if (!cur_hook_sp->IsActive())
2582 continue;
2583
2584 bool any_thread_matched = false;
2585 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2586 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2587 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2588 sym_ctx_with_reasons[i])) &&
2589 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2590 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2591 exc_ctx_with_reasons[i].GetThreadRef()))) {
2592 if (!hooks_ran) {
2593 hooks_ran = true;
2594 }
2595 if (print_hook_header && !any_thread_matched) {
2596 const char *cmd =
2597 (cur_hook_sp->GetCommands().GetSize() == 1
2598 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2599 : nullptr);
2600 if (cmd)
2601 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2602 cur_hook_sp->GetID(), cmd);
2603 else
2604 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2605 cur_hook_sp->GetID());
2606 any_thread_matched = true;
2607 }
2608
2609 if (print_thread_header)
2610 result.AppendMessageWithFormat(
2611 "-- Thread %d\n",
2612 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2613
2614 CommandInterpreterRunOptions options;
2615 options.SetStopOnContinue(true);
2616 options.SetStopOnError(true);
2617 options.SetEchoCommands(false);
2618 options.SetPrintResults(true);
2619 options.SetAddToHistory(false);
2620
2621 GetDebugger().GetCommandInterpreter().HandleCommands(
2622 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2623 result);
2624
2625 // If the command started the target going again, we should bag out of
2626 // running the stop hooks.
2627 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2628 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
Jim Ingham45816d62017-12-05 02:34:05 +00002629 // But only complain if there were more stop hooks to do:
2630 StopHookCollection::iterator tmp = pos;
2631 if (++tmp != end)
2632 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2633 " set the program running.\n",
2634 cur_hook_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002635 keep_going = false;
2636 }
2637 }
2638 }
2639 }
2640
2641 result.GetImmediateOutputStream()->Flush();
2642 result.GetImmediateErrorStream()->Flush();
2643}
2644
2645const TargetPropertiesSP &Target::GetGlobalProperties() {
2646 // NOTE: intentional leak so we don't crash if global destructor chain gets
2647 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +00002648 static TargetPropertiesSP *g_settings_sp_ptr =
2649 new TargetPropertiesSP(new TargetProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002650 return *g_settings_sp_ptr;
2651}
2652
Zachary Turner97206d52017-05-12 04:51:55 +00002653Status Target::Install(ProcessLaunchInfo *launch_info) {
2654 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 PlatformSP platform_sp(GetPlatform());
2656 if (platform_sp) {
2657 if (platform_sp->IsRemote()) {
2658 if (platform_sp->IsConnected()) {
2659 // Install all files that have an install path, and always install the
2660 // main executable when connected to a remote platform
2661 const ModuleList &modules = GetImages();
2662 const size_t num_images = modules.GetSize();
2663 for (size_t idx = 0; idx < num_images; ++idx) {
2664 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2665 if (module_sp) {
2666 const bool is_main_executable = module_sp == GetExecutableModule();
2667 FileSpec local_file(module_sp->GetFileSpec());
2668 if (local_file) {
2669 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2670 if (!remote_file) {
2671 if (is_main_executable) // TODO: add setting for always
2672 // installing main executable???
2673 {
2674 // Always install the main executable
2675 remote_file = platform_sp->GetRemoteWorkingDirectory();
2676 remote_file.AppendPathComponent(
2677 module_sp->GetFileSpec().GetFilename().GetCString());
2678 }
2679 }
2680 if (remote_file) {
2681 error = platform_sp->Install(local_file, remote_file);
2682 if (error.Success()) {
2683 module_sp->SetPlatformFileSpec(remote_file);
2684 if (is_main_executable) {
2685 platform_sp->SetFilePermissions(remote_file, 0700);
2686 if (launch_info)
2687 launch_info->SetExecutableFile(remote_file, false);
2688 }
2689 } else
2690 break;
2691 }
2692 }
2693 }
2694 }
2695 }
2696 }
2697 }
2698 return error;
2699}
2700
2701bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2702 uint32_t stop_id) {
2703 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2704}
2705
2706bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2707 Address &resolved_addr) {
2708 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2709}
2710
2711bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2712 addr_t new_section_load_addr,
2713 bool warn_multiple) {
2714 const addr_t old_section_load_addr =
2715 m_section_load_history.GetSectionLoadAddress(
2716 SectionLoadHistory::eStopIDNow, section_sp);
2717 if (old_section_load_addr != new_section_load_addr) {
2718 uint32_t stop_id = 0;
2719 ProcessSP process_sp(GetProcessSP());
2720 if (process_sp)
2721 stop_id = process_sp->GetStopID();
Greg Claytonb09c5382013-12-13 17:20:18 +00002722 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002723 stop_id = m_section_load_history.GetLastStopID();
2724 if (m_section_load_history.SetSectionLoadAddress(
2725 stop_id, section_sp, new_section_load_addr, warn_multiple))
2726 return true; // Return true if the section load address was changed...
2727 }
2728 return false; // Return false to indicate nothing changed
2729}
Todd Fialaac33cc92014-10-09 01:02:08 +00002730
Kate Stoneb9c1b512016-09-06 20:57:50 +00002731size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2732 size_t section_unload_count = 0;
2733 size_t num_modules = module_list.GetSize();
2734 for (size_t i = 0; i < num_modules; ++i) {
2735 section_unload_count +=
2736 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2737 }
2738 return section_unload_count;
2739}
Todd Fiala015d8182014-07-22 23:41:36 +00002740
Kate Stoneb9c1b512016-09-06 20:57:50 +00002741size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2742 uint32_t stop_id = 0;
2743 ProcessSP process_sp(GetProcessSP());
2744 if (process_sp)
2745 stop_id = process_sp->GetStopID();
2746 else
2747 stop_id = m_section_load_history.GetLastStopID();
2748 SectionList *sections = module_sp->GetSectionList();
2749 size_t section_unload_count = 0;
2750 if (sections) {
2751 const uint32_t num_sections = sections->GetNumSections(0);
2752 for (uint32_t i = 0; i < num_sections; ++i) {
2753 section_unload_count += m_section_load_history.SetSectionUnloaded(
2754 stop_id, sections->GetSectionAtIndex(i));
Greg Claytonb09c5382013-12-13 17:20:18 +00002755 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002756 }
2757 return section_unload_count;
2758}
2759
2760bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2761 uint32_t stop_id = 0;
2762 ProcessSP process_sp(GetProcessSP());
2763 if (process_sp)
2764 stop_id = process_sp->GetStopID();
2765 else
2766 stop_id = m_section_load_history.GetLastStopID();
2767 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2768}
2769
2770bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2771 addr_t load_addr) {
2772 uint32_t stop_id = 0;
2773 ProcessSP process_sp(GetProcessSP());
2774 if (process_sp)
2775 stop_id = process_sp->GetStopID();
2776 else
2777 stop_id = m_section_load_history.GetLastStopID();
2778 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2779 load_addr);
2780}
2781
2782void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2783
Zachary Turner97206d52017-05-12 04:51:55 +00002784Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2785 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2787
2788 if (log)
2789 log->Printf("Target::%s() called for %s", __FUNCTION__,
2790 launch_info.GetExecutableFile().GetPath().c_str());
2791
2792 StateType state = eStateInvalid;
2793
2794 // Scope to temporarily get the process state in case someone has manually
2795 // remotely connected already to a process and we can skip the platform
2796 // launching.
2797 {
2798 ProcessSP process_sp(GetProcessSP());
2799
2800 if (process_sp) {
2801 state = process_sp->GetState();
2802 if (log)
2803 log->Printf(
2804 "Target::%s the process exists, and its current state is %s",
2805 __FUNCTION__, StateAsCString(state));
2806 } else {
2807 if (log)
2808 log->Printf("Target::%s the process instance doesn't currently exist.",
2809 __FUNCTION__);
2810 }
2811 }
2812
2813 launch_info.GetFlags().Set(eLaunchFlagDebug);
2814
2815 // Get the value of synchronous execution here. If you wait till after you
Adrian Prantl05097242018-04-30 16:49:04 +00002816 // have started to run, then you could have hit a breakpoint, whose command
2817 // might switch the value, and then you'll pick up that incorrect value.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818 Debugger &debugger = GetDebugger();
2819 const bool synchronous_execution =
2820 debugger.GetCommandInterpreter().GetSynchronous();
2821
2822 PlatformSP platform_sp(GetPlatform());
2823
Adrian Prantl05097242018-04-30 16:49:04 +00002824 // Finalize the file actions, and if none were given, default to opening up a
2825 // pseudo terminal
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2827 if (log)
2828 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2829 "default_to_use_pty=%s",
2830 __FUNCTION__, platform_sp ? "true" : "false",
2831 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2832 : "n/a",
2833 default_to_use_pty ? "true" : "false");
2834
2835 launch_info.FinalizeFileActions(this, default_to_use_pty);
2836
2837 if (state == eStateConnected) {
2838 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2839 error.SetErrorString(
2840 "can't launch in tty when launching through a remote connection");
2841 return error;
2842 }
2843 }
2844
2845 if (!launch_info.GetArchitecture().IsValid())
2846 launch_info.GetArchitecture() = GetArchitecture();
2847
2848 // If we're not already connected to the process, and if we have a platform
2849 // that can launch a process for debugging, go ahead and do that here.
2850 if (state != eStateConnected && platform_sp &&
2851 platform_sp->CanDebugProcess()) {
2852 if (log)
2853 log->Printf("Target::%s asking the platform to debug the process",
2854 __FUNCTION__);
2855
2856 // Get a weak pointer to the previous process if we have one
2857 ProcessWP process_wp;
2858 if (m_process_sp)
2859 process_wp = m_process_sp;
2860 m_process_sp =
2861 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2862
2863 // Cleanup the old process since someone might still have a strong
Adrian Prantl05097242018-04-30 16:49:04 +00002864 // reference to this process and we would like to allow it to cleanup as
2865 // much as it can without the object being destroyed. We try to lock the
2866 // shared pointer and if that works, then someone else still has a strong
2867 // reference to the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868
2869 ProcessSP old_process_sp(process_wp.lock());
2870 if (old_process_sp)
2871 old_process_sp->Finalize();
2872 } else {
2873 if (log)
2874 log->Printf("Target::%s the platform doesn't know how to debug a "
2875 "process, getting a process plugin to do this for us.",
2876 __FUNCTION__);
2877
2878 if (state == eStateConnected) {
2879 assert(m_process_sp);
2880 } else {
2881 // Use a Process plugin to construct the process.
2882 const char *plugin_name = launch_info.GetProcessPluginName();
2883 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
2884 nullptr);
Greg Claytonb09c5382013-12-13 17:20:18 +00002885 }
2886
Kate Stoneb9c1b512016-09-06 20:57:50 +00002887 // Since we didn't have a platform launch the process, launch it here.
2888 if (m_process_sp)
2889 error = m_process_sp->Launch(launch_info);
2890 }
2891
2892 if (!m_process_sp) {
Greg Claytonb09c5382013-12-13 17:20:18 +00002893 if (error.Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002894 error.SetErrorString("failed to launch or debug process");
Greg Claytonb09c5382013-12-13 17:20:18 +00002895 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002896 }
2897
2898 if (error.Success()) {
2899 if (synchronous_execution ||
2900 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2901 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2902 if (!hijack_listener_sp) {
2903 hijack_listener_sp =
2904 Listener::MakeListener("lldb.Target.Launch.hijack");
2905 launch_info.SetHijackListener(hijack_listener_sp);
2906 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2907 }
2908
2909 StateType state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002910 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002911
2912 if (state == eStateStopped) {
2913 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2914 if (synchronous_execution) {
2915 error = m_process_sp->PrivateResume();
2916 if (error.Success()) {
2917 state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002918 llvm::None, nullptr, true, hijack_listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 const bool must_be_alive =
2920 false; // eStateExited is ok, so this must be false
2921 if (!StateIsStoppedState(state, must_be_alive)) {
2922 error.SetErrorStringWithFormat("process isn't stopped: %s",
2923 StateAsCString(state));
2924 }
2925 }
2926 } else {
2927 m_process_sp->RestoreProcessEvents();
2928 error = m_process_sp->PrivateResume();
2929 }
2930 if (!error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +00002931 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002932 error2.SetErrorStringWithFormat(
2933 "process resume at entry point failed: %s", error.AsCString());
2934 error = error2;
2935 }
2936 }
2937 } else if (state == eStateExited) {
2938 bool with_shell = !!launch_info.GetShell();
2939 const int exit_status = m_process_sp->GetExitStatus();
2940 const char *exit_desc = m_process_sp->GetExitDescription();
2941#define LAUNCH_SHELL_MESSAGE \
2942 "\n'r' and 'run' are aliases that default to launching through a " \
2943 "shell.\nTry launching without going through a shell by using 'process " \
2944 "launch'."
2945 if (exit_desc && exit_desc[0]) {
2946 if (with_shell)
2947 error.SetErrorStringWithFormat(
2948 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2949 exit_status, exit_desc);
2950 else
2951 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2952 exit_status, exit_desc);
2953 } else {
2954 if (with_shell)
2955 error.SetErrorStringWithFormat(
2956 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2957 exit_status);
2958 else
2959 error.SetErrorStringWithFormat("process exited with status %i",
2960 exit_status);
2961 }
2962 } else {
2963 error.SetErrorStringWithFormat(
2964 "initial process state wasn't stopped: %s", StateAsCString(state));
2965 }
2966 }
2967 m_process_sp->RestoreProcessEvents();
2968 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00002969 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 error2.SetErrorStringWithFormat("process launch failed: %s",
2971 error.AsCString());
2972 error = error2;
2973 }
2974 return error;
Greg Claytonb09c5382013-12-13 17:20:18 +00002975}
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002976
Zachary Turner97206d52017-05-12 04:51:55 +00002977Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002978 auto state = eStateInvalid;
2979 auto process_sp = GetProcessSP();
2980 if (process_sp) {
2981 state = process_sp->GetState();
2982 if (process_sp->IsAlive() && state != eStateConnected) {
2983 if (state == eStateAttaching)
Zachary Turner97206d52017-05-12 04:51:55 +00002984 return Status("process attach is in progress");
2985 return Status("a process is already being debugged");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002986 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002988
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989 const ModuleSP old_exec_module_sp = GetExecutableModule();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002990
Adrian Prantl05097242018-04-30 16:49:04 +00002991 // If no process info was specified, then use the target executable name as
2992 // the process to attach to by default
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 if (!attach_info.ProcessInfoSpecified()) {
2994 if (old_exec_module_sp)
2995 attach_info.GetExecutableFile().GetFilename() =
2996 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002997
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 if (!attach_info.ProcessInfoSpecified()) {
Zachary Turner97206d52017-05-12 04:51:55 +00002999 return Status("no process specified, create a target with a file, or "
3000 "specify the --pid or --name");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003001 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003002 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003003
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 const auto platform_sp =
3005 GetDebugger().GetPlatformList().GetSelectedPlatform();
3006 ListenerSP hijack_listener_sp;
3007 const bool async = attach_info.GetAsync();
3008 if (!async) {
3009 hijack_listener_sp =
3010 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3011 attach_info.SetHijackListener(hijack_listener_sp);
3012 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003013
Zachary Turner97206d52017-05-12 04:51:55 +00003014 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 if (state != eStateConnected && platform_sp != nullptr &&
3016 platform_sp->CanDebugProcess()) {
3017 SetPlatform(platform_sp);
3018 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3019 } else {
3020 if (state != eStateConnected) {
3021 const char *plugin_name = attach_info.GetProcessPluginName();
3022 process_sp =
3023 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3024 plugin_name, nullptr);
3025 if (process_sp == nullptr) {
3026 error.SetErrorStringWithFormat(
3027 "failed to create process using plugin %s",
3028 (plugin_name) ? plugin_name : "null");
3029 return error;
3030 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003031 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 if (hijack_listener_sp)
3033 process_sp->HijackProcessEvents(hijack_listener_sp);
3034 error = process_sp->Attach(attach_info);
3035 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003036
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 if (error.Success() && process_sp) {
3038 if (async) {
3039 process_sp->RestoreProcessEvents();
3040 } else {
3041 state = process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003042 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 process_sp->RestoreProcessEvents();
3044
3045 if (state != eStateStopped) {
3046 const char *exit_desc = process_sp->GetExitDescription();
3047 if (exit_desc)
3048 error.SetErrorStringWithFormat("%s", exit_desc);
Greg Claytone75e5d82015-10-20 00:14:20 +00003049 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003050 error.SetErrorString(
3051 "process did not stop (no such process or permission problem?)");
3052 process_sp->Destroy(false);
3053 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003054 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003055 }
3056 return error;
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003057}
3058
Jim Ingham9575d842011-03-11 03:53:59 +00003059//--------------------------------------------------------------
Greg Claytonfbb76342013-11-20 21:07:01 +00003060// Target::StopHook
Jim Ingham9575d842011-03-11 03:53:59 +00003061//--------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003062Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3063 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3064 m_thread_spec_ap(), m_active(true) {}
3065
3066Target::StopHook::StopHook(const StopHook &rhs)
3067 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3068 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3069 m_thread_spec_ap(), m_active(rhs.m_active) {
3070 if (rhs.m_thread_spec_ap)
3071 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
Jim Ingham9575d842011-03-11 03:53:59 +00003072}
3073
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003074Target::StopHook::~StopHook() = default;
Jim Ingham9575d842011-03-11 03:53:59 +00003075
Kate Stoneb9c1b512016-09-06 20:57:50 +00003076void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3077 m_specifier_sp.reset(specifier);
Zachary Turner32abc6e2015-03-03 19:23:09 +00003078}
3079
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3081 m_thread_spec_ap.reset(specifier);
Jim Ingham9575d842011-03-11 03:53:59 +00003082}
Jim Ingham9575d842011-03-11 03:53:59 +00003083
Kate Stoneb9c1b512016-09-06 20:57:50 +00003084void Target::StopHook::GetDescription(Stream *s,
3085 lldb::DescriptionLevel level) const {
3086 int indent_level = s->GetIndentLevel();
Jim Ingham9575d842011-03-11 03:53:59 +00003087
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 s->SetIndentLevel(indent_level + 2);
3089
3090 s->Printf("Hook: %" PRIu64 "\n", GetID());
3091 if (m_active)
3092 s->Indent("State: enabled\n");
3093 else
3094 s->Indent("State: disabled\n");
3095
3096 if (m_specifier_sp) {
3097 s->Indent();
3098 s->PutCString("Specifier:\n");
3099 s->SetIndentLevel(indent_level + 4);
3100 m_specifier_sp->GetDescription(s, level);
Jim Ingham9575d842011-03-11 03:53:59 +00003101 s->SetIndentLevel(indent_level + 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 }
Jim Ingham9575d842011-03-11 03:53:59 +00003103
Kate Stoneb9c1b512016-09-06 20:57:50 +00003104 if (m_thread_spec_ap) {
3105 StreamString tmp;
3106 s->Indent("Thread:\n");
3107 m_thread_spec_ap->GetDescription(&tmp, level);
3108 s->SetIndentLevel(indent_level + 4);
Zachary Turnerc1564272016-11-16 21:15:24 +00003109 s->Indent(tmp.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 s->PutCString("\n");
3111 s->SetIndentLevel(indent_level + 2);
3112 }
Jim Ingham9575d842011-03-11 03:53:59 +00003113
Kate Stoneb9c1b512016-09-06 20:57:50 +00003114 s->Indent("Commands: \n");
3115 s->SetIndentLevel(indent_level + 4);
3116 uint32_t num_commands = m_commands.GetSize();
3117 for (uint32_t i = 0; i < num_commands; i++) {
3118 s->Indent(m_commands.GetStringAtIndex(i));
3119 s->PutCString("\n");
3120 }
3121 s->SetIndentLevel(indent_level);
Jim Ingham9575d842011-03-11 03:53:59 +00003122}
3123
Greg Clayton67cc0632012-08-22 17:17:09 +00003124//--------------------------------------------------------------
3125// class TargetProperties
3126//--------------------------------------------------------------
3127
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003128static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003129 {eNoDynamicValues, "no-dynamic-values",
3130 "Don't calculate the dynamic type of values"},
3131 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3132 "even if you have to run the target."},
3133 {eDynamicDontRunTarget, "no-run-target",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003134 "Calculate the dynamic type of values, but don't run the target."} };
Caroline Ticedaccaa92010-09-20 20:44:43 +00003135
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003136OptionEnumValues lldb_private::GetDynamicValueTypes() {
3137 return OptionEnumValues(g_dynamic_value_types);
3138}
3139
3140static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3142 "locations (fastest). This setting "
3143 "should only be used if you know that "
3144 "no inlining occurs in your programs."},
3145 {eInlineBreakpointsHeaders, "headers",
3146 "Only check for inline breakpoint locations when setting breakpoints in "
3147 "header files, but not when setting breakpoint in implementation source "
3148 "files (default)."},
3149 {eInlineBreakpointsAlways, "always",
3150 "Always look for inline breakpoint locations when setting file and line "
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003151 "breakpoints (slower but most accurate)."} };
Greg Clayton1f746072012-08-29 21:13:06 +00003152
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153typedef enum x86DisassemblyFlavor {
3154 eX86DisFlavorDefault,
3155 eX86DisFlavorIntel,
3156 eX86DisFlavorATT
Jim Ingham0f063ba2013-03-02 00:26:47 +00003157} x86DisassemblyFlavor;
3158
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003159static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003160 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3161 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003162 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003164static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003166 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003167
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003168static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003169 {eLoadScriptFromSymFileTrue, "true",
3170 "Load debug scripts inside symbol files"},
3171 {eLoadScriptFromSymFileFalse, "false",
3172 "Do not load debug scripts inside symbol files."},
3173 {eLoadScriptFromSymFileWarn, "warn",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003174 "Warn about debug scripts inside symbol files but do not load them."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003176static constexpr
3177OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003178 {eLoadCWDlldbinitTrue, "true",
3179 "Load .lldbinit files from current directory"},
3180 {eLoadCWDlldbinitFalse, "false",
3181 "Do not load .lldbinit files from current directory"},
3182 {eLoadCWDlldbinitWarn, "warn",
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003183 "Warn about loading .lldbinit files from current directory"} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003184
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003185static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 {eMemoryModuleLoadLevelMinimal, "minimal",
3187 "Load minimal information when loading modules from memory. Currently "
3188 "this setting loads sections only."},
3189 {eMemoryModuleLoadLevelPartial, "partial",
3190 "Load partial information when loading modules from memory. Currently "
3191 "this setting loads sections and function bounds."},
3192 {eMemoryModuleLoadLevelComplete, "complete",
3193 "Load complete information when loading modules from memory. Currently "
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003194 "this setting loads sections and all symbols."} };
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003196static constexpr PropertyDefinition g_properties[] = {
3197 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003198 "Default architecture to choose, when there's a choice."},
3199 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003200 {}, "Move breakpoints to nearest code."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003201 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003202 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 "The language to use when interpreting expressions entered in commands."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003204 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003205 "Path to a file containing expressions to be prepended to all "
3206 "expressions."},
3207 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003208 eDynamicDontRunTarget, nullptr, OptionEnumValues(g_dynamic_value_types),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003209 "Should printed values be shown as their dynamic value."},
3210 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003211 {}, "Should synthetic values be used by default whenever available."},
3212 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003213 "Skip function prologues when setting breakpoints by name."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003214 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 "Source path remappings are used to track the change of location between "
3216 "a source file when built, and "
3217 "where it exists on the current system. It consists of an array of "
3218 "duples, the first element of each duple is "
3219 "some part (starting at the root) of the path to the file when it was "
3220 "built, "
3221 "and the second is where the remainder of the original build hierarchy is "
3222 "rooted on the local system. "
3223 "Each element of the array is checked in order and the first one that "
3224 "results in a match wins."},
3225 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003226 {}, "Executable search paths to use when locating executable files "
3227 "whose paths don't match the local file system."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003229 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230 "List of directories to be searched when locating debug symbol files."},
3231 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003232 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003233 "List of directories to be searched when locating modules for Clang."},
3234 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003235 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003236 "Automatically load Clang modules referred to by the program."},
3237 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003238 {}, "Automatically apply fix-it hints to expressions."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003239 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003240 {}, "Print the fixed expression text."},
Sean Callanan5deb06e2016-09-26 20:18:51 +00003241 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003242 {}, "Save intermediate object files generated by the LLVM JIT"},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003244 {}, "Maximum number of children to expand in any level of depth."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003245 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003246 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003247 "Maximum number of characters to show when using %s in summary strings."},
3248 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003249 {}, "Maximum number of bytes that 'memory read' will fetch before "
3250 "--force must be specified."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003251 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003252 true, nullptr, {}, "Consult the platform module avoid list when "
3253 "setting non-module specific breakpoints."},
3254 {"arg0", OptionValue::eTypeString, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003255 "The first argument passed to the program in the argument array which can "
3256 "be different from the executable itself."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003257 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003258 "A list containing all the arguments to be passed to the executable when "
3259 "it is run. Note that this does NOT include the argv[0] which is in "
3260 "target.arg0."},
3261 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003262 nullptr, {}, "A list of all the environment variables to be passed "
3263 "to the executable's environment, and their values."},
3264 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003265 "Inherit the environment from the process that is running LLDB."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003266 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003267 "The file/path to be used by the executable program for reading its "
3268 "standard input."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003269 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003270 "The file/path to be used by the executable program for writing its "
3271 "standard output."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003272 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003273 "The file/path to be used by the executable program for writing its "
3274 "standard error."},
3275 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003276 {}, "debugserver will detach (rather than killing) a process if it "
Kate Stoneb9c1b512016-09-06 20:57:50 +00003277 "loses connection with lldb."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003278 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, {},
Jim Ingham7fca8c02017-04-28 00:51:06 +00003279 "Enable loading of symbol tables before they are needed."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003280 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281 "Disable Address Space Layout Randomization (ASLR)"},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003282 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003283 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3284 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003285 eInlineBreakpointsAlways, nullptr,
3286 OptionEnumValues(g_inline_breakpoint_enums),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003287 "The strategy to use when settings breakpoints by file and line. "
3288 "Breakpoint locations can end up being inlined by the compiler, so that a "
3289 "compile unit 'a.c' might contain an inlined function from another source "
3290 "file. "
3291 "Usually this is limited to breakpoint locations from inlined functions "
3292 "from header or other include files, or more accurately "
3293 "non-implementation source files. "
3294 "Sometimes code might #include implementation files and cause inlined "
3295 "breakpoint locations in inlined implementation files. "
3296 "Always checking for inlined breakpoint locations can be expensive "
3297 "(memory and time), so if you have a project with many headers "
3298 "and find that setting breakpoints is slow, then you can change this "
3299 "setting to headers. "
3300 "This setting allows you to control exactly which strategy is used when "
3301 "setting "
3302 "file and line breakpoints."},
3303 // FIXME: This is the wrong way to do per-architecture settings, but we
3304 // don't have a general per architecture settings system in place yet.
3305 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003306 eX86DisFlavorDefault, nullptr,
3307 OptionEnumValues(g_x86_dis_flavor_value_types),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308 "The default disassembly flavor to use for x86 or x86-64 targets."},
3309 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003310 {}, "Show immediates in disassembly as hexadecimal."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311 {"hex-immediate-style", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003312 Disassembler::eHexStyleC, nullptr,
3313 OptionEnumValues(g_hex_immediate_style_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003314 "Which style to use for printing hexadecimal disassembly values."},
3315 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003316 {}, "Use a fast stepping algorithm based on running from branch to "
3317 "branch rather than instruction single-stepping."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003318 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003319 eLoadScriptFromSymFileWarn, nullptr,
3320 OptionEnumValues(g_load_script_from_sym_file_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003321 "Allow LLDB to load scripting resources embedded in symbol files when "
3322 "available."},
3323 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003324 nullptr, OptionEnumValues(g_load_current_working_dir_lldbinit_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003325 "Allow LLDB to .lldbinit files from the current directory automatically."},
3326 {"memory-module-load-level", OptionValue::eTypeEnum, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003327 eMemoryModuleLoadLevelComplete, nullptr,
3328 OptionEnumValues(g_memory_module_load_level_values),
Kate Stoneb9c1b512016-09-06 20:57:50 +00003329 "Loading modules from memory can be slow as reading the symbol tables and "
3330 "other data can take a long time depending on your connection to the "
3331 "debug target. "
3332 "This setting helps users control how much information gets loaded when "
3333 "loading modules from memory."
3334 "'complete' is the default value for this setting which will load all "
3335 "sections and symbols by reading them from memory (slowest, most "
3336 "accurate). "
3337 "'partial' will load sections and attempt to find function bounds without "
3338 "downloading the symbol table (faster, still accurate, missing symbol "
3339 "names). "
3340 "'minimal' is the fastest setting and will load section data with no "
3341 "symbols, but should rarely be used as stack frames in these memory "
3342 "regions will be inaccurate and not provide any context (fastest). "},
3343 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003344 nullptr, {}, "Expressions that crash will show up in crash logs if "
3345 "the host system supports executable specific crash log "
3346 "strings and this setting is set to true."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003347 {"trap-handler-names", OptionValue::eTypeArray, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003348 OptionValue::eTypeString, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003349 "A list of trap handler function names, e.g. a common Unix user process "
3350 "one is _sigtramp."},
3351 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003352 nullptr, {}, "If true, LLDB will show variables that are meant to "
3353 "support the operation of a language's runtime support."},
3354 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003355 "Disable lock-step debugging, instead control threads independently."},
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003356 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, {}, nullptr}};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003357
3358enum {
3359 ePropertyDefaultArch,
3360 ePropertyMoveToNearestCode,
3361 ePropertyLanguage,
3362 ePropertyExprPrefix,
3363 ePropertyPreferDynamic,
3364 ePropertyEnableSynthetic,
3365 ePropertySkipPrologue,
3366 ePropertySourceMap,
3367 ePropertyExecutableSearchPaths,
3368 ePropertyDebugFileSearchPaths,
3369 ePropertyClangModuleSearchPaths,
3370 ePropertyAutoImportClangModules,
3371 ePropertyAutoApplyFixIts,
3372 ePropertyNotifyAboutFixIts,
Sean Callanan5deb06e2016-09-26 20:18:51 +00003373 ePropertySaveObjects,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003374 ePropertyMaxChildrenCount,
3375 ePropertyMaxSummaryLength,
3376 ePropertyMaxMemReadSize,
3377 ePropertyBreakpointUseAvoidList,
3378 ePropertyArg0,
3379 ePropertyRunArgs,
3380 ePropertyEnvVars,
3381 ePropertyInheritEnv,
3382 ePropertyInputPath,
3383 ePropertyOutputPath,
3384 ePropertyErrorPath,
3385 ePropertyDetachOnError,
Jim Ingham7fca8c02017-04-28 00:51:06 +00003386 ePropertyPreloadSymbols,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003387 ePropertyDisableASLR,
3388 ePropertyDisableSTDIO,
3389 ePropertyInlineStrategy,
3390 ePropertyDisassemblyFlavor,
3391 ePropertyUseHexImmediates,
3392 ePropertyHexImmediateStyle,
3393 ePropertyUseFastStepping,
3394 ePropertyLoadScriptFromSymbolFile,
3395 ePropertyLoadCWDlldbinitFile,
3396 ePropertyMemoryModuleLoadLevel,
3397 ePropertyDisplayExpressionsInCrashlogs,
3398 ePropertyTrapHandlerNames,
3399 ePropertyDisplayRuntimeSupportValues,
3400 ePropertyNonStopModeEnabled,
3401 ePropertyExperimental
Jim Ingham0f063ba2013-03-02 00:26:47 +00003402};
3403
Kate Stoneb9c1b512016-09-06 20:57:50 +00003404class TargetOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +00003405public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003406 TargetOptionValueProperties(const ConstString &name)
3407 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
Caroline Ticedaccaa92010-09-20 20:44:43 +00003408
Kate Stoneb9c1b512016-09-06 20:57:50 +00003409 // This constructor is used when creating TargetOptionValueProperties when it
3410 // is part of a new lldb_private::Target instance. It will copy all current
3411 // global property values as needed
3412 TargetOptionValueProperties(Target *target,
3413 const TargetPropertiesSP &target_properties_sp)
3414 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3415 m_target(target), m_got_host_env(false) {}
Greg Clayton67cc0632012-08-22 17:17:09 +00003416
Kate Stoneb9c1b512016-09-06 20:57:50 +00003417 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3418 bool will_modify,
3419 uint32_t idx) const override {
3420 // When getting the value for a key from the target options, we will always
Adrian Prantl05097242018-04-30 16:49:04 +00003421 // try and grab the setting from the current target if there is one. Else
3422 // we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003423 if (idx == ePropertyEnvVars)
3424 GetHostEnvironmentIfNeeded();
3425
3426 if (exe_ctx) {
3427 Target *target = exe_ctx->GetTargetPtr();
3428 if (target) {
3429 TargetOptionValueProperties *target_properties =
3430 static_cast<TargetOptionValueProperties *>(
3431 target->GetValueProperties().get());
3432 if (this != target_properties)
3433 return target_properties->ProtectedGetPropertyAtIndex(idx);
3434 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003435 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003436 return ProtectedGetPropertyAtIndex(idx);
3437 }
3438
3439 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3440
Greg Clayton67cc0632012-08-22 17:17:09 +00003441protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003442 void GetHostEnvironmentIfNeeded() const {
3443 if (!m_got_host_env) {
3444 if (m_target) {
3445 m_got_host_env = true;
3446 const uint32_t idx = ePropertyInheritEnv;
3447 if (GetPropertyAtIndexAsBoolean(
3448 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3449 PlatformSP platform_sp(m_target->GetPlatform());
3450 if (platform_sp) {
Pavel Labath62930e52018-01-10 11:57:31 +00003451 Environment env = platform_sp->GetEnvironment();
3452 OptionValueDictionary *env_dict =
3453 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3454 ePropertyEnvVars);
3455 if (env_dict) {
3456 const bool can_replace = false;
3457 for (const auto &KV : env) {
3458 // Don't allow existing keys to be replaced with ones we get
3459 // from the platform environment
3460 env_dict->SetValueForKey(
3461 ConstString(KV.first()),
3462 OptionValueSP(new OptionValueString(KV.second.c_str())),
3463 can_replace);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003464 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003465 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003466 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003467 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003468 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003469 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003470 }
3471 Target *m_target;
3472 mutable bool m_got_host_env;
Greg Clayton67cc0632012-08-22 17:17:09 +00003473};
3474
Greg Claytonfbb76342013-11-20 21:07:01 +00003475//----------------------------------------------------------------------
3476// TargetProperties
3477//----------------------------------------------------------------------
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003478static constexpr PropertyDefinition g_experimental_properties[]{
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003480 {},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481 "If true, inject local variables explicitly into the expression text. "
3482 "This will fix symbol resolution when there are name collisions between "
3483 "ivars and local variables. "
3484 "But it can make expressions run much more slowly."},
Sean Callanan68e44232017-09-28 20:20:25 +00003485 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00003486 {}, "If true, use Clang's modern type lookup infrastructure."},
3487 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, {}, nullptr}};
Jim Inghambed67792016-07-07 18:25:48 +00003488
Sean Callanan68e44232017-09-28 20:20:25 +00003489enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
Jim Inghambed67792016-07-07 18:25:48 +00003490
Kate Stoneb9c1b512016-09-06 20:57:50 +00003491class TargetExperimentalOptionValueProperties : public OptionValueProperties {
Jim Inghambed67792016-07-07 18:25:48 +00003492public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003493 TargetExperimentalOptionValueProperties()
3494 : OptionValueProperties(
3495 ConstString(Properties::GetExperimentalSettingsName())) {}
Jim Inghambed67792016-07-07 18:25:48 +00003496};
3497
Kate Stoneb9c1b512016-09-06 20:57:50 +00003498TargetExperimentalProperties::TargetExperimentalProperties()
3499 : Properties(OptionValuePropertiesSP(
3500 new TargetExperimentalOptionValueProperties())) {
3501 m_collection_sp->Initialize(g_experimental_properties);
Jim Inghambed67792016-07-07 18:25:48 +00003502}
3503
3504//----------------------------------------------------------------------
3505// TargetProperties
3506//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003507TargetProperties::TargetProperties(Target *target)
3508 : Properties(), m_launch_info() {
3509 if (target) {
3510 m_collection_sp.reset(
3511 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
Ilia K8f37ca52015-02-13 14:31:06 +00003512
Adrian Prantl05097242018-04-30 16:49:04 +00003513 // Set callbacks to update launch_info whenever "settins set" updated any
3514 // of these properties
Kate Stoneb9c1b512016-09-06 20:57:50 +00003515 m_collection_sp->SetValueChangedCallback(
3516 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3517 m_collection_sp->SetValueChangedCallback(
3518 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3519 m_collection_sp->SetValueChangedCallback(
3520 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3521 m_collection_sp->SetValueChangedCallback(
3522 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3523 this);
3524 m_collection_sp->SetValueChangedCallback(
3525 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3526 this);
3527 m_collection_sp->SetValueChangedCallback(
3528 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3529 this);
3530 m_collection_sp->SetValueChangedCallback(
3531 ePropertyDetachOnError,
3532 TargetProperties::DetachOnErrorValueChangedCallback, this);
3533 m_collection_sp->SetValueChangedCallback(
3534 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3535 this);
3536 m_collection_sp->SetValueChangedCallback(
3537 ePropertyDisableSTDIO,
3538 TargetProperties::DisableSTDIOValueChangedCallback, this);
Jim Inghambed67792016-07-07 18:25:48 +00003539
Kate Stoneb9c1b512016-09-06 20:57:50 +00003540 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3541 m_collection_sp->AppendProperty(
3542 ConstString(Properties::GetExperimentalSettingsName()),
3543 ConstString("Experimental settings - setting these won't produce "
3544 "errors if the setting is not present."),
3545 true, m_experimental_properties_up->GetValueProperties());
Jim Inghambed67792016-07-07 18:25:48 +00003546
Kate Stoneb9c1b512016-09-06 20:57:50 +00003547 // Update m_launch_info once it was created
3548 Arg0ValueChangedCallback(this, nullptr);
3549 RunArgsValueChangedCallback(this, nullptr);
3550 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3551 // Target::GetPlatform()
3552 InputPathValueChangedCallback(this, nullptr);
3553 OutputPathValueChangedCallback(this, nullptr);
3554 ErrorPathValueChangedCallback(this, nullptr);
3555 DetachOnErrorValueChangedCallback(this, nullptr);
3556 DisableASLRValueChangedCallback(this, nullptr);
3557 DisableSTDIOValueChangedCallback(this, nullptr);
3558 } else {
3559 m_collection_sp.reset(
3560 new TargetOptionValueProperties(ConstString("target")));
3561 m_collection_sp->Initialize(g_properties);
3562 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3563 m_collection_sp->AppendProperty(
3564 ConstString(Properties::GetExperimentalSettingsName()),
3565 ConstString("Experimental settings - setting these won't produce "
3566 "errors if the setting is not present."),
3567 true, m_experimental_properties_up->GetValueProperties());
3568 m_collection_sp->AppendProperty(
3569 ConstString("process"), ConstString("Settings specific to processes."),
3570 true, Process::GetGlobalProperties()->GetValueProperties());
3571 }
Caroline Ticedaccaa92010-09-20 20:44:43 +00003572}
3573
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003574TargetProperties::~TargetProperties() = default;
3575
Kate Stoneb9c1b512016-09-06 20:57:50 +00003576bool TargetProperties::GetInjectLocalVariables(
3577 ExecutionContext *exe_ctx) const {
3578 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3579 exe_ctx, false, ePropertyExperimental);
3580 OptionValueProperties *exp_values =
3581 exp_property->GetValue()->GetAsProperties();
3582 if (exp_values)
3583 return exp_values->GetPropertyAtIndexAsBoolean(
3584 exe_ctx, ePropertyInjectLocalVars, true);
3585 else
3586 return true;
Jim Inghambed67792016-07-07 18:25:48 +00003587}
3588
Kate Stoneb9c1b512016-09-06 20:57:50 +00003589void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3590 bool b) {
3591 const Property *exp_property =
3592 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3593 OptionValueProperties *exp_values =
3594 exp_property->GetValue()->GetAsProperties();
3595 if (exp_values)
3596 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3597 true);
Jim Inghambed67792016-07-07 18:25:48 +00003598}
3599
Sean Callanan68e44232017-09-28 20:20:25 +00003600bool TargetProperties::GetUseModernTypeLookup() const {
3601 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3602 nullptr, false, ePropertyExperimental);
3603 OptionValueProperties *exp_values =
3604 exp_property->GetValue()->GetAsProperties();
3605 if (exp_values)
3606 return exp_values->GetPropertyAtIndexAsBoolean(
3607 nullptr, ePropertyUseModernTypeLookup, true);
3608 else
3609 return true;
3610}
3611
Kate Stoneb9c1b512016-09-06 20:57:50 +00003612ArchSpec TargetProperties::GetDefaultArchitecture() const {
3613 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3614 nullptr, ePropertyDefaultArch);
3615 if (value)
3616 return value->GetCurrentValue();
3617 return ArchSpec();
Greg Clayton67cc0632012-08-22 17:17:09 +00003618}
3619
Kate Stoneb9c1b512016-09-06 20:57:50 +00003620void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3621 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3622 nullptr, ePropertyDefaultArch);
3623 if (value)
3624 return value->SetCurrentValue(arch, true);
Greg Clayton67cc0632012-08-22 17:17:09 +00003625}
3626
Kate Stoneb9c1b512016-09-06 20:57:50 +00003627bool TargetProperties::GetMoveToNearestCode() const {
3628 const uint32_t idx = ePropertyMoveToNearestCode;
3629 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3630 nullptr, idx, g_properties[idx].default_uint_value != 0);
Ilia K055ad9b2015-05-18 13:41:01 +00003631}
3632
Kate Stoneb9c1b512016-09-06 20:57:50 +00003633lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3634 const uint32_t idx = ePropertyPreferDynamic;
3635 return (lldb::DynamicValueType)
3636 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3637 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003638}
3639
Kate Stoneb9c1b512016-09-06 20:57:50 +00003640bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3641 const uint32_t idx = ePropertyPreferDynamic;
3642 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
Greg Clayton15484402015-05-15 18:40:24 +00003643}
3644
Jim Ingham7fca8c02017-04-28 00:51:06 +00003645bool TargetProperties::GetPreloadSymbols() const {
3646 const uint32_t idx = ePropertyPreloadSymbols;
3647 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3648 nullptr, idx, g_properties[idx].default_uint_value != 0);
3649}
3650
3651void TargetProperties::SetPreloadSymbols(bool b) {
3652 const uint32_t idx = ePropertyPreloadSymbols;
3653 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3654}
3655
Kate Stoneb9c1b512016-09-06 20:57:50 +00003656bool TargetProperties::GetDisableASLR() const {
3657 const uint32_t idx = ePropertyDisableASLR;
3658 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3659 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003660}
3661
Kate Stoneb9c1b512016-09-06 20:57:50 +00003662void TargetProperties::SetDisableASLR(bool b) {
3663 const uint32_t idx = ePropertyDisableASLR;
3664 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003665}
3666
Kate Stoneb9c1b512016-09-06 20:57:50 +00003667bool TargetProperties::GetDetachOnError() const {
3668 const uint32_t idx = ePropertyDetachOnError;
3669 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3670 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham106d0282014-06-25 02:32:56 +00003671}
3672
Kate Stoneb9c1b512016-09-06 20:57:50 +00003673void TargetProperties::SetDetachOnError(bool b) {
3674 const uint32_t idx = ePropertyDetachOnError;
3675 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Jim Ingham106d0282014-06-25 02:32:56 +00003676}
3677
Kate Stoneb9c1b512016-09-06 20:57:50 +00003678bool TargetProperties::GetDisableSTDIO() const {
3679 const uint32_t idx = ePropertyDisableSTDIO;
3680 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3681 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003682}
3683
Kate Stoneb9c1b512016-09-06 20:57:50 +00003684void TargetProperties::SetDisableSTDIO(bool b) {
3685 const uint32_t idx = ePropertyDisableSTDIO;
3686 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003687}
3688
Kate Stoneb9c1b512016-09-06 20:57:50 +00003689const char *TargetProperties::GetDisassemblyFlavor() const {
3690 const uint32_t idx = ePropertyDisassemblyFlavor;
3691 const char *return_value;
3692
3693 x86DisassemblyFlavor flavor_value =
3694 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3695 nullptr, idx, g_properties[idx].default_uint_value);
3696 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3697 return return_value;
Jim Ingham0f063ba2013-03-02 00:26:47 +00003698}
3699
Kate Stoneb9c1b512016-09-06 20:57:50 +00003700InlineStrategy TargetProperties::GetInlineStrategy() const {
3701 const uint32_t idx = ePropertyInlineStrategy;
3702 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3703 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton1f746072012-08-29 21:13:06 +00003704}
3705
Zachary Turner31d97a52016-11-17 18:08:12 +00003706llvm::StringRef TargetProperties::GetArg0() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003707 const uint32_t idx = ePropertyArg0;
Zachary Turner31d97a52016-11-17 18:08:12 +00003708 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
Greg Clayton45392552012-10-17 22:57:12 +00003709}
3710
Zachary Turner31d97a52016-11-17 18:08:12 +00003711void TargetProperties::SetArg0(llvm::StringRef arg) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003712 const uint32_t idx = ePropertyArg0;
Zachary Turner514d8cd2016-09-23 18:06:53 +00003713 m_collection_sp->SetPropertyAtIndexAsString(
Zachary Turner31d97a52016-11-17 18:08:12 +00003714 nullptr, idx, arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 m_launch_info.SetArg0(arg);
Greg Clayton45392552012-10-17 22:57:12 +00003716}
3717
Kate Stoneb9c1b512016-09-06 20:57:50 +00003718bool TargetProperties::GetRunArguments(Args &args) const {
3719 const uint32_t idx = ePropertyRunArgs;
3720 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +00003721}
3722
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723void TargetProperties::SetRunArguments(const Args &args) {
3724 const uint32_t idx = ePropertyRunArgs;
3725 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3726 m_launch_info.GetArguments() = args;
Greg Clayton67cc0632012-08-22 17:17:09 +00003727}
3728
Pavel Labath62930e52018-01-10 11:57:31 +00003729Environment TargetProperties::GetEnvironment() const {
3730 // TODO: Get rid of the Args intermediate step
3731 Args env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003732 const uint32_t idx = ePropertyEnvVars;
Pavel Labath62930e52018-01-10 11:57:31 +00003733 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3734 return Environment(env);
Greg Clayton67cc0632012-08-22 17:17:09 +00003735}
3736
Pavel Labath62930e52018-01-10 11:57:31 +00003737void TargetProperties::SetEnvironment(Environment env) {
3738 // TODO: Get rid of the Args intermediate step
Kate Stoneb9c1b512016-09-06 20:57:50 +00003739 const uint32_t idx = ePropertyEnvVars;
Pavel Labath62930e52018-01-10 11:57:31 +00003740 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3741 m_launch_info.GetEnvironment() = std::move(env);
Ilia K8f37ca52015-02-13 14:31:06 +00003742}
3743
Kate Stoneb9c1b512016-09-06 20:57:50 +00003744bool TargetProperties::GetSkipPrologue() const {
3745 const uint32_t idx = ePropertySkipPrologue;
3746 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3747 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003748}
3749
Kate Stoneb9c1b512016-09-06 20:57:50 +00003750PathMappingList &TargetProperties::GetSourcePathMap() const {
3751 const uint32_t idx = ePropertySourceMap;
3752 OptionValuePathMappings *option_value =
3753 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3754 false, idx);
3755 assert(option_value);
3756 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003757}
3758
Kate Stoneb9c1b512016-09-06 20:57:50 +00003759FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3760 const uint32_t idx = ePropertyExecutableSearchPaths;
3761 OptionValueFileSpecList *option_value =
3762 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3763 false, idx);
3764 assert(option_value);
3765 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003766}
3767
Kate Stoneb9c1b512016-09-06 20:57:50 +00003768FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3769 const uint32_t idx = ePropertyDebugFileSearchPaths;
3770 OptionValueFileSpecList *option_value =
3771 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3772 false, idx);
3773 assert(option_value);
3774 return option_value->GetCurrentValue();
Michael Sartaina7499c92013-07-01 19:45:50 +00003775}
3776
Kate Stoneb9c1b512016-09-06 20:57:50 +00003777FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3778 const uint32_t idx = ePropertyClangModuleSearchPaths;
3779 OptionValueFileSpecList *option_value =
3780 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3781 false, idx);
3782 assert(option_value);
3783 return option_value->GetCurrentValue();
Sean Callanan85054342015-04-03 15:39:47 +00003784}
3785
Kate Stoneb9c1b512016-09-06 20:57:50 +00003786bool TargetProperties::GetEnableAutoImportClangModules() const {
3787 const uint32_t idx = ePropertyAutoImportClangModules;
3788 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3789 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callananf0c5aeb2015-04-20 16:31:29 +00003790}
3791
Kate Stoneb9c1b512016-09-06 20:57:50 +00003792bool TargetProperties::GetEnableAutoApplyFixIts() const {
3793 const uint32_t idx = ePropertyAutoApplyFixIts;
3794 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3795 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghama1e541b2016-03-25 01:57:14 +00003796}
3797
Kate Stoneb9c1b512016-09-06 20:57:50 +00003798bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3799 const uint32_t idx = ePropertyNotifyAboutFixIts;
3800 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3801 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghame5ee6f02016-03-29 22:00:08 +00003802}
3803
Sean Callanan5deb06e2016-09-26 20:18:51 +00003804bool TargetProperties::GetEnableSaveObjects() const {
3805 const uint32_t idx = ePropertySaveObjects;
3806 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3807 nullptr, idx, g_properties[idx].default_uint_value != 0);
3808}
3809
Kate Stoneb9c1b512016-09-06 20:57:50 +00003810bool TargetProperties::GetEnableSyntheticValue() const {
3811 const uint32_t idx = ePropertyEnableSynthetic;
3812 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3813 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003814}
3815
Kate Stoneb9c1b512016-09-06 20:57:50 +00003816uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3817 const uint32_t idx = ePropertyMaxChildrenCount;
3818 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3819 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003820}
3821
Kate Stoneb9c1b512016-09-06 20:57:50 +00003822uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3823 const uint32_t idx = ePropertyMaxSummaryLength;
3824 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3825 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003826}
3827
Kate Stoneb9c1b512016-09-06 20:57:50 +00003828uint32_t TargetProperties::GetMaximumMemReadSize() const {
3829 const uint32_t idx = ePropertyMaxMemReadSize;
3830 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3831 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granatad325bf92013-06-04 22:54:16 +00003832}
3833
Kate Stoneb9c1b512016-09-06 20:57:50 +00003834FileSpec TargetProperties::GetStandardInputPath() const {
3835 const uint32_t idx = ePropertyInputPath;
3836 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003837}
3838
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003839void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003840 const uint32_t idx = ePropertyInputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003841 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003842}
3843
Kate Stoneb9c1b512016-09-06 20:57:50 +00003844FileSpec TargetProperties::GetStandardOutputPath() const {
3845 const uint32_t idx = ePropertyOutputPath;
3846 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003847}
3848
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003849void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003850 const uint32_t idx = ePropertyOutputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003851 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003852}
3853
Kate Stoneb9c1b512016-09-06 20:57:50 +00003854FileSpec TargetProperties::GetStandardErrorPath() const {
3855 const uint32_t idx = ePropertyErrorPath;
3856 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003857}
3858
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003859void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3860 const uint32_t idx = ePropertyErrorPath;
3861 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3862}
3863
Kate Stoneb9c1b512016-09-06 20:57:50 +00003864LanguageType TargetProperties::GetLanguage() const {
3865 OptionValueLanguage *value =
3866 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3867 nullptr, ePropertyLanguage);
3868 if (value)
3869 return value->GetCurrentValue();
3870 return LanguageType();
Dawn Perchik23b1dec2015-07-21 22:05:07 +00003871}
3872
Pavel Labath50251fc2017-12-21 10:54:30 +00003873llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003874 const uint32_t idx = ePropertyExprPrefix;
3875 OptionValueFileSpec *file =
3876 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3877 idx);
3878 if (file) {
Pavel Labath50251fc2017-12-21 10:54:30 +00003879 DataBufferSP data_sp(file->GetFileContents());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880 if (data_sp)
Pavel Labath50251fc2017-12-21 10:54:30 +00003881 return llvm::StringRef(
3882 reinterpret_cast<const char *>(data_sp->GetBytes()),
3883 data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003884 }
Pavel Labath50251fc2017-12-21 10:54:30 +00003885 return "";
Greg Clayton6920b522012-08-22 18:39:03 +00003886}
3887
Kate Stoneb9c1b512016-09-06 20:57:50 +00003888bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3889 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3890 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3891 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003892}
3893
Kate Stoneb9c1b512016-09-06 20:57:50 +00003894bool TargetProperties::GetUseHexImmediates() const {
3895 const uint32_t idx = ePropertyUseHexImmediates;
3896 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3897 nullptr, idx, g_properties[idx].default_uint_value != 0);
Daniel Malead79ae052013-08-07 21:54:09 +00003898}
3899
Kate Stoneb9c1b512016-09-06 20:57:50 +00003900bool TargetProperties::GetUseFastStepping() const {
3901 const uint32_t idx = ePropertyUseFastStepping;
3902 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3903 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham17d023f2013-03-13 17:58:04 +00003904}
3905
Kate Stoneb9c1b512016-09-06 20:57:50 +00003906bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3907 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3908 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3909 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Claytonfb6621e2013-12-06 21:59:52 +00003910}
3911
Kate Stoneb9c1b512016-09-06 20:57:50 +00003912LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3913 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3914 return (LoadScriptFromSymFile)
3915 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3916 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granata2ea43cd2013-05-13 17:03:52 +00003917}
3918
Kate Stoneb9c1b512016-09-06 20:57:50 +00003919LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3920 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3921 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3922 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molenda878ae012016-02-19 00:05:17 +00003923}
3924
Kate Stoneb9c1b512016-09-06 20:57:50 +00003925Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3926 const uint32_t idx = ePropertyHexImmediateStyle;
3927 return (Disassembler::HexImmediateStyle)
3928 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3929 nullptr, idx, g_properties[idx].default_uint_value);
Daniel Malead79ae052013-08-07 21:54:09 +00003930}
3931
Kate Stoneb9c1b512016-09-06 20:57:50 +00003932MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3933 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3934 return (MemoryModuleLoadLevel)
3935 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3936 nullptr, idx, g_properties[idx].default_uint_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00003937}
3938
Kate Stoneb9c1b512016-09-06 20:57:50 +00003939bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3940 const uint32_t idx = ePropertyTrapHandlerNames;
3941 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003942}
Greg Claytonfd814c52013-08-13 01:42:25 +00003943
Kate Stoneb9c1b512016-09-06 20:57:50 +00003944void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3945 const uint32_t idx = ePropertyTrapHandlerNames;
3946 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003947}
Greg Clayton67cc0632012-08-22 17:17:09 +00003948
Kate Stoneb9c1b512016-09-06 20:57:50 +00003949bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3950 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3951 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Enrico Granata560558e2015-02-11 02:35:39 +00003952}
3953
Kate Stoneb9c1b512016-09-06 20:57:50 +00003954void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3955 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3956 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granata560558e2015-02-11 02:35:39 +00003957}
3958
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959bool TargetProperties::GetNonStopModeEnabled() const {
3960 const uint32_t idx = ePropertyNonStopModeEnabled;
3961 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Ewan Crawford78baa192015-05-13 09:18:18 +00003962}
3963
Kate Stoneb9c1b512016-09-06 20:57:50 +00003964void TargetProperties::SetNonStopModeEnabled(bool b) {
3965 const uint32_t idx = ePropertyNonStopModeEnabled;
3966 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00003967}
3968
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3970 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3971 return m_launch_info;
Ilia K8f37ca52015-02-13 14:31:06 +00003972}
3973
Kate Stoneb9c1b512016-09-06 20:57:50 +00003974void TargetProperties::SetProcessLaunchInfo(
3975 const ProcessLaunchInfo &launch_info) {
3976 m_launch_info = launch_info;
3977 SetArg0(launch_info.GetArg0());
3978 SetRunArguments(launch_info.GetArguments());
Pavel Labath62930e52018-01-10 11:57:31 +00003979 SetEnvironment(launch_info.GetEnvironment());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003980 const FileAction *input_file_action =
3981 launch_info.GetFileActionForFD(STDIN_FILENO);
3982 if (input_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003983 SetStandardInputPath(input_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003984 }
3985 const FileAction *output_file_action =
3986 launch_info.GetFileActionForFD(STDOUT_FILENO);
3987 if (output_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003988 SetStandardOutputPath(output_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003989 }
3990 const FileAction *error_file_action =
3991 launch_info.GetFileActionForFD(STDERR_FILENO);
3992 if (error_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003993 SetStandardErrorPath(error_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994 }
3995 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3996 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3997 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
Ilia K8f37ca52015-02-13 14:31:06 +00003998}
3999
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4001 OptionValue *) {
4002 TargetProperties *this_ =
4003 reinterpret_cast<TargetProperties *>(target_property_ptr);
4004 this_->m_launch_info.SetArg0(this_->GetArg0());
Ilia K8f37ca52015-02-13 14:31:06 +00004005}
4006
Kate Stoneb9c1b512016-09-06 20:57:50 +00004007void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4008 OptionValue *) {
4009 TargetProperties *this_ =
4010 reinterpret_cast<TargetProperties *>(target_property_ptr);
4011 Args args;
4012 if (this_->GetRunArguments(args))
4013 this_->m_launch_info.GetArguments() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00004014}
4015
Kate Stoneb9c1b512016-09-06 20:57:50 +00004016void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4017 OptionValue *) {
4018 TargetProperties *this_ =
4019 reinterpret_cast<TargetProperties *>(target_property_ptr);
Pavel Labath62930e52018-01-10 11:57:31 +00004020 this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
Ilia K8f37ca52015-02-13 14:31:06 +00004021}
4022
Kate Stoneb9c1b512016-09-06 20:57:50 +00004023void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4024 OptionValue *) {
4025 TargetProperties *this_ =
4026 reinterpret_cast<TargetProperties *>(target_property_ptr);
4027 this_->m_launch_info.AppendOpenFileAction(
4028 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
Ilia K8f37ca52015-02-13 14:31:06 +00004029}
4030
Kate Stoneb9c1b512016-09-06 20:57:50 +00004031void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4032 OptionValue *) {
4033 TargetProperties *this_ =
4034 reinterpret_cast<TargetProperties *>(target_property_ptr);
4035 this_->m_launch_info.AppendOpenFileAction(
4036 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004037}
4038
Kate Stoneb9c1b512016-09-06 20:57:50 +00004039void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4040 OptionValue *) {
4041 TargetProperties *this_ =
4042 reinterpret_cast<TargetProperties *>(target_property_ptr);
4043 this_->m_launch_info.AppendOpenFileAction(
4044 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004045}
4046
Kate Stoneb9c1b512016-09-06 20:57:50 +00004047void TargetProperties::DetachOnErrorValueChangedCallback(
4048 void *target_property_ptr, OptionValue *) {
4049 TargetProperties *this_ =
4050 reinterpret_cast<TargetProperties *>(target_property_ptr);
4051 if (this_->GetDetachOnError())
4052 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4053 else
4054 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
Ilia K8f37ca52015-02-13 14:31:06 +00004055}
4056
Kate Stoneb9c1b512016-09-06 20:57:50 +00004057void TargetProperties::DisableASLRValueChangedCallback(
4058 void *target_property_ptr, OptionValue *) {
4059 TargetProperties *this_ =
4060 reinterpret_cast<TargetProperties *>(target_property_ptr);
4061 if (this_->GetDisableASLR())
4062 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4063 else
4064 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
Ilia K8f37ca52015-02-13 14:31:06 +00004065}
4066
Kate Stoneb9c1b512016-09-06 20:57:50 +00004067void TargetProperties::DisableSTDIOValueChangedCallback(
4068 void *target_property_ptr, OptionValue *) {
4069 TargetProperties *this_ =
4070 reinterpret_cast<TargetProperties *>(target_property_ptr);
4071 if (this_->GetDisableSTDIO())
4072 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4073 else
4074 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
Ilia K8f37ca52015-02-13 14:31:06 +00004075}
Ilia Keb2c19a2015-03-10 21:59:55 +00004076
4077//----------------------------------------------------------------------
4078// Target::TargetEventData
4079//----------------------------------------------------------------------
4080
Kate Stoneb9c1b512016-09-06 20:57:50 +00004081Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4082 : EventData(), m_target_sp(target_sp), m_module_list() {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004083
Kate Stoneb9c1b512016-09-06 20:57:50 +00004084Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4085 const ModuleList &module_list)
4086 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004087
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004088Target::TargetEventData::~TargetEventData() = default;
Ilia Keb2c19a2015-03-10 21:59:55 +00004089
Kate Stoneb9c1b512016-09-06 20:57:50 +00004090const ConstString &Target::TargetEventData::GetFlavorString() {
4091 static ConstString g_flavor("Target::TargetEventData");
4092 return g_flavor;
Ilia Keb2c19a2015-03-10 21:59:55 +00004093}
4094
Kate Stoneb9c1b512016-09-06 20:57:50 +00004095void Target::TargetEventData::Dump(Stream *s) const {
4096 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4097 if (i != 0)
4098 *s << ", ";
4099 m_module_list.GetModuleAtIndex(i)->GetDescription(
4100 s, lldb::eDescriptionLevelBrief);
4101 }
Ilia Keb2c19a2015-03-10 21:59:55 +00004102}
4103
4104const Target::TargetEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004105Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4106 if (event_ptr) {
4107 const EventData *event_data = event_ptr->GetData();
4108 if (event_data &&
4109 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4110 return static_cast<const TargetEventData *>(event_ptr->GetData());
4111 }
4112 return nullptr;
Ilia Keb2c19a2015-03-10 21:59:55 +00004113}
4114
Kate Stoneb9c1b512016-09-06 20:57:50 +00004115TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4116 TargetSP target_sp;
4117 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4118 if (event_data)
4119 target_sp = event_data->m_target_sp;
4120 return target_sp;
Ilia Keb2c19a2015-03-10 21:59:55 +00004121}
4122
4123ModuleList
Kate Stoneb9c1b512016-09-06 20:57:50 +00004124Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4125 ModuleList module_list;
4126 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4127 if (event_data)
4128 module_list = event_data->m_module_list;
4129 return module_list;
Ilia Keb2c19a2015-03-10 21:59:55 +00004130}