blob: 83a4b35f070d4bdd3f3e037fe8e0d274cd9a5d26 [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"
Johnny Chen01a67862011-10-14 00:42:25 +000024#include "lldb/Breakpoint/Watchpoint.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000025#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Core/Event.h"
Greg Clayton1f746072012-08-29 21:13:06 +000027#include "lldb/Core/Module.h"
28#include "lldb/Core/ModuleSpec.h"
Pavel Labath13e37d42017-10-25 21:05:31 +000029#include "lldb/Core/PluginManager.h"
Greg Clayton1f746072012-08-29 21:13:06 +000030#include "lldb/Core/Section.h"
Greg Clayton9585fbf2013-03-19 00:20:55 +000031#include "lldb/Core/SourceManager.h"
Greg Claytonb09c5382013-12-13 17:20:18 +000032#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000033#include "lldb/Core/StreamFile.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000034#include "lldb/Core/ValueObject.h"
Sean Callanan66810412015-10-19 23:11:07 +000035#include "lldb/Expression/REPL.h"
Jim Ingham151c0322015-09-15 21:13:50 +000036#include "lldb/Expression/UserExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Host/Host.h"
Pavel Labathb6dbe9a2017-07-18 13:14:01 +000038#include "lldb/Host/PosixApi.h"
Jim Ingham9575d842011-03-11 03:53:59 +000039#include "lldb/Interpreter/CommandInterpreter.h"
40#include "lldb/Interpreter/CommandReturnObject.h"
Johnny Chenb90827e2012-06-04 23:19:54 +000041#include "lldb/Interpreter/OptionGroupWatchpoint.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000042#include "lldb/Interpreter/OptionValues.h"
43#include "lldb/Interpreter/Property.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000044#include "lldb/Symbol/ClangASTContext.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000045#include "lldb/Symbol/Function.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000046#include "lldb/Symbol/ObjectFile.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000047#include "lldb/Symbol/Symbol.h"
Jim Ingham151c0322015-09-15 21:13:50 +000048#include "lldb/Target/Language.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000049#include "lldb/Target/LanguageRuntime.h"
50#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051#include "lldb/Target/Process.h"
Greg Claytond5944cd2013-12-06 01:12:00 +000052#include "lldb/Target/SectionLoadList.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000053#include "lldb/Target/StackFrame.h"
Jason Molendaeef51062013-11-05 03:57:19 +000054#include "lldb/Target/SystemRuntime.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000055#include "lldb/Target/Target.h"
Jim Ingham9575d842011-03-11 03:53:59 +000056#include "lldb/Target/Thread.h"
57#include "lldb/Target/ThreadSpec.h"
Zachary Turner5713a052017-03-22 18:40:07 +000058#include "lldb/Utility/FileSpec.h"
Sean Callanan9a6940c2015-10-21 00:36:34 +000059#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000060#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000061#include "lldb/Utility/StreamString.h"
Pavel Labath38d06322017-06-29 14:32:17 +000062#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063
64using namespace lldb;
65using namespace lldb_private;
66
Pavel Labath43d35412016-12-06 11:24:51 +000067constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
68
Pavel Labath13e37d42017-10-25 21:05:31 +000069Target::Arch::Arch(const ArchSpec &spec)
70 : m_spec(spec),
71 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
72
73const Target::Arch& Target::Arch::operator=(const ArchSpec &spec) {
74 m_spec = spec;
75 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
76 return *this;
77}
78
Kate Stoneb9c1b512016-09-06 20:57:50 +000079ConstString &Target::GetStaticBroadcasterClass() {
80 static ConstString class_name("lldb.target");
81 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000082}
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084Target::Target(Debugger &debugger, const ArchSpec &target_arch,
85 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000086 : TargetProperties(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 Broadcaster(debugger.GetBroadcasterManager(),
88 Target::GetStaticBroadcasterClass().AsCString()),
89 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
Davide Italiano24fff242018-04-13 18:02:39 +000090 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
91 m_breakpoint_list(false), m_internal_breakpoint_list(true),
92 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
93 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
94 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
95 m_valid(true), m_suppress_stop_hooks(false),
96 m_is_dummy_target(is_dummy_target),
97 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
Jim Ingham893c9322014-11-22 01:42:44 +000098
Chris Lattner30fdc8d2010-06-08 16:52:24 +000099{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
101 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
102 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
103 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
104 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 CheckInWithManager();
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
109 if (log)
110 log->Printf("%p Target::Target()", static_cast<void *>(this));
Pavel Labath13e37d42017-10-25 21:05:31 +0000111 if (target_arch.IsValid()) {
112 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET,
113 "Target::Target created with architecture %s (%s)",
114 target_arch.GetArchitectureName(),
115 target_arch.GetTriple().getTriple().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000117}
118
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119Target::~Target() {
120 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
121 if (log)
122 log->Printf("%p Target::~Target()", static_cast<void *>(this));
123 DeleteCurrentProcess();
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000124}
125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126void Target::PrimeFromDummyTarget(Target *target) {
127 if (!target)
128 return;
Jim Ingham893c9322014-11-22 01:42:44 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 m_stop_hooks = target->m_stop_hooks;
131
132 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
133 if (breakpoint_sp->IsInternal())
134 continue;
135
136 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
137 AddBreakpoint(new_bp, false);
138 }
Jim Inghamb842f2e2017-09-14 20:22:49 +0000139
140 for (auto bp_name_entry : target->m_breakpoint_names)
141 {
142
143 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
144 AddBreakpointName(new_bp_name);
145 }
Jim Ingham893c9322014-11-22 01:42:44 +0000146}
147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
149 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
150 if (description_level != lldb::eDescriptionLevelBrief) {
151 s->Indent();
152 s->PutCString("Target\n");
153 s->IndentMore();
154 m_images.Dump(s);
155 m_breakpoint_list.Dump(s);
156 m_internal_breakpoint_list.Dump(s);
157 s->IndentLess();
158 } else {
159 Module *exe_module = GetExecutableModulePointer();
160 if (exe_module)
161 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
Caroline Ticeceb6b132010-10-26 03:11:13 +0000162 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 s->PutCString("No executable module.");
164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000165}
166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167void Target::CleanupProcess() {
168 // Do any cleanup of the target we need to do between process instances.
169 // NB It is better to do this before destroying the process in case the
170 // clean up needs some help from the process.
171 m_breakpoint_list.ClearAllBreakpointSites();
172 m_internal_breakpoint_list.ClearAllBreakpointSites();
173 // Disable watchpoints just on the debugger side.
174 std::unique_lock<std::recursive_mutex> lock;
175 this->GetWatchpointList().GetListMutex(lock);
176 DisableAllWatchpoints(false);
177 ClearAllWatchpointHitCounts();
178 ClearAllWatchpointHistoricValues();
Greg Clayton90ba8112012-12-05 00:16:59 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181void Target::DeleteCurrentProcess() {
182 if (m_process_sp) {
Greg Claytond5944cd2013-12-06 01:12:00 +0000183 m_section_load_history.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184 if (m_process_sp->IsAlive())
185 m_process_sp->Destroy(false);
186
187 m_process_sp->Finalize();
188
189 CleanupProcess();
190
191 m_process_sp.reset();
192 }
Greg Clayton3418c852011-08-10 02:10:13 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
Zachary Turner31659452016-11-17 21:15:14 +0000196 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 const FileSpec *crash_file) {
198 DeleteCurrentProcess();
199 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
200 listener_sp, crash_file);
201 return m_process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202}
203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
205
Zachary Turner97206d52017-05-12 04:51:55 +0000206lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 const char *repl_options, bool can_create) {
208 if (language == eLanguageTypeUnknown) {
209 std::set<LanguageType> repl_languages;
210
211 Language::GetLanguagesSupportingREPLs(repl_languages);
212
213 if (repl_languages.size() == 1) {
214 language = *repl_languages.begin();
215 } else if (repl_languages.size() == 0) {
216 err.SetErrorStringWithFormat(
217 "LLDB isn't configured with REPL support for any languages.");
218 return REPLSP();
219 } else {
220 err.SetErrorStringWithFormat(
221 "Multiple possible REPL languages. Please specify a language.");
222 return REPLSP();
223 }
224 }
225
226 REPLMap::iterator pos = m_repl_map.find(language);
227
228 if (pos != m_repl_map.end()) {
229 return pos->second;
230 }
231
232 if (!can_create) {
233 err.SetErrorStringWithFormat(
234 "Couldn't find an existing REPL for %s, and can't create a new one",
235 Language::GetNameForLanguageType(language));
236 return lldb::REPLSP();
237 }
238
239 Debugger *const debugger = nullptr;
240 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
241
242 if (ret) {
243 m_repl_map[language] = ret;
244 return m_repl_map[language];
245 }
246
247 if (err.Success()) {
248 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
249 Language::GetNameForLanguageType(language));
250 }
251
252 return lldb::REPLSP();
253}
254
255void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
256 lldbassert(!m_repl_map.count(language));
257
258 m_repl_map[language] = repl_sp;
259}
260
261void Target::Destroy() {
262 std::lock_guard<std::recursive_mutex> guard(m_mutex);
263 m_valid = false;
264 DeleteCurrentProcess();
265 m_platform_sp.reset();
Pavel Labath13e37d42017-10-25 21:05:31 +0000266 m_arch = ArchSpec();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 ClearModules(true);
268 m_section_load_history.Clear();
269 const bool notify = false;
270 m_breakpoint_list.RemoveAll(notify);
271 m_internal_breakpoint_list.RemoveAll(notify);
272 m_last_created_breakpoint.reset();
273 m_last_created_watchpoint.reset();
274 m_search_filter_sp.reset();
275 m_image_search_paths.Clear(notify);
276 m_stop_hooks.clear();
277 m_stop_hook_next_id = 0;
278 m_suppress_stop_hooks = false;
279}
280
281BreakpointList &Target::GetBreakpointList(bool internal) {
282 if (internal)
283 return m_internal_breakpoint_list;
284 else
285 return m_breakpoint_list;
286}
287
288const BreakpointList &Target::GetBreakpointList(bool internal) const {
289 if (internal)
290 return m_internal_breakpoint_list;
291 else
292 return m_breakpoint_list;
293}
294
295BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
296 BreakpointSP bp_sp;
297
298 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
299 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
300 else
301 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
302
303 return bp_sp;
304}
305
306BreakpointSP Target::CreateSourceRegexBreakpoint(
307 const FileSpecList *containingModules,
308 const FileSpecList *source_file_spec_list,
309 const std::unordered_set<std::string> &function_names,
310 RegularExpression &source_regex, bool internal, bool hardware,
311 LazyBool move_to_nearest_code) {
312 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
313 containingModules, source_file_spec_list));
314 if (move_to_nearest_code == eLazyBoolCalculate)
315 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
316 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
317 nullptr, source_regex, function_names,
318 !static_cast<bool>(move_to_nearest_code)));
319
320 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
321}
322
323BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
324 const FileSpec &file, uint32_t line_no,
325 lldb::addr_t offset,
326 LazyBool check_inlines,
327 LazyBool skip_prologue, bool internal,
328 bool hardware,
329 LazyBool move_to_nearest_code) {
330 FileSpec remapped_file;
Greg Clayton86188d82018-05-21 14:14:36 +0000331 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 remapped_file = file;
333
334 if (check_inlines == eLazyBoolCalculate) {
335 const InlineStrategy inline_strategy = GetInlineStrategy();
336 switch (inline_strategy) {
337 case eInlineBreakpointsNever:
338 check_inlines = eLazyBoolNo;
339 break;
340
341 case eInlineBreakpointsHeaders:
342 if (remapped_file.IsSourceImplementationFile())
343 check_inlines = eLazyBoolNo;
344 else
345 check_inlines = eLazyBoolYes;
346 break;
347
348 case eInlineBreakpointsAlways:
349 check_inlines = eLazyBoolYes;
350 break;
351 }
352 }
353 SearchFilterSP filter_sp;
354 if (check_inlines == eLazyBoolNo) {
355 // Not checking for inlines, we are looking only for matching compile units
356 FileSpecList compile_unit_list;
357 compile_unit_list.Append(remapped_file);
358 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
359 &compile_unit_list);
360 } else {
361 filter_sp = GetSearchFilterForModuleList(containingModules);
362 }
363 if (skip_prologue == eLazyBoolCalculate)
364 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
365 if (move_to_nearest_code == eLazyBoolCalculate)
366 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
367
368 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
369 nullptr, remapped_file, line_no, offset, check_inlines, skip_prologue,
370 !static_cast<bool>(move_to_nearest_code)));
371 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
372}
373
374BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
375 bool hardware) {
376 Address so_addr;
377
378 // Check for any reason we want to move this breakpoint to other address.
379 addr = GetBreakableLoadAddress(addr);
380
Adrian Prantl05097242018-04-30 16:49:04 +0000381 // Attempt to resolve our load address if possible, though it is ok if it
382 // doesn't resolve to section/offset.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383
384 // Try and resolve as a load address if possible
385 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
386 if (!so_addr.IsValid()) {
387 // The address didn't resolve, so just set this as an absolute address
388 so_addr.SetOffset(addr);
389 }
390 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
391 return bp_sp;
392}
393
394BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
395 bool hardware) {
396 SearchFilterSP filter_sp(
397 new SearchFilterForUnconstrainedSearches(shared_from_this()));
398 BreakpointResolverSP resolver_sp(
399 new BreakpointResolverAddress(nullptr, addr));
400 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
401}
402
403lldb::BreakpointSP
404Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
405 const FileSpec *file_spec,
406 bool request_hardware) {
407 SearchFilterSP filter_sp(
408 new SearchFilterForUnconstrainedSearches(shared_from_this()));
409 BreakpointResolverSP resolver_sp(
410 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
411 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
412 false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000413}
414
415BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416Target::CreateBreakpoint(const FileSpecList *containingModules,
417 const FileSpecList *containingSourceFiles,
418 const char *func_name, uint32_t func_name_type_mask,
419 LanguageType language, lldb::addr_t offset,
420 LazyBool skip_prologue, bool internal, bool hardware) {
421 BreakpointSP bp_sp;
422 if (func_name) {
423 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
424 containingModules, containingSourceFiles));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000425
Greg Clayton03da4cc2013-04-19 21:31:16 +0000426 if (skip_prologue == eLazyBoolCalculate)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
428 if (language == lldb::eLanguageTypeUnknown)
429 language = GetLanguage();
430
431 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
432 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
433 offset, skip_prologue));
434 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
435 }
436 return bp_sp;
437}
438
439lldb::BreakpointSP
440Target::CreateBreakpoint(const FileSpecList *containingModules,
441 const FileSpecList *containingSourceFiles,
442 const std::vector<std::string> &func_names,
443 uint32_t func_name_type_mask, LanguageType language,
444 lldb::addr_t offset, LazyBool skip_prologue,
445 bool internal, bool hardware) {
446 BreakpointSP bp_sp;
447 size_t num_names = func_names.size();
448 if (num_names > 0) {
449 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
450 containingModules, containingSourceFiles));
451
452 if (skip_prologue == eLazyBoolCalculate)
453 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
454 if (language == lldb::eLanguageTypeUnknown)
455 language = GetLanguage();
456
457 BreakpointResolverSP resolver_sp(
458 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
459 language, offset, skip_prologue));
460 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
461 }
462 return bp_sp;
463}
464
465BreakpointSP Target::CreateBreakpoint(
466 const FileSpecList *containingModules,
467 const FileSpecList *containingSourceFiles, const char *func_names[],
468 size_t num_names, uint32_t func_name_type_mask, LanguageType language,
469 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
470 BreakpointSP bp_sp;
471 if (num_names > 0) {
472 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
473 containingModules, containingSourceFiles));
474
475 if (skip_prologue == eLazyBoolCalculate) {
476 if (offset == 0)
Greg Clayton03da4cc2013-04-19 21:31:16 +0000477 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 else
479 skip_prologue = eLazyBoolNo;
Greg Clayton1b72fcb2010-08-24 00:45:41 +0000480 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 if (language == lldb::eLanguageTypeUnknown)
482 language = GetLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
485 nullptr, func_names, num_names, func_name_type_mask, language, offset,
486 skip_prologue));
487 resolver_sp->SetOffset(offset);
488 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
489 }
490 return bp_sp;
Jim Ingham133e0fb2012-03-03 02:05:11 +0000491}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000492
493SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494Target::GetSearchFilterForModule(const FileSpec *containingModule) {
495 SearchFilterSP filter_sp;
496 if (containingModule != nullptr) {
497 // TODO: We should look into sharing module based search filters
498 // across many breakpoints like we do for the simple target based one
499 filter_sp.reset(
500 new SearchFilterByModule(shared_from_this(), *containingModule));
501 } else {
502 if (!m_search_filter_sp)
503 m_search_filter_sp.reset(
504 new SearchFilterForUnconstrainedSearches(shared_from_this()));
505 filter_sp = m_search_filter_sp;
506 }
507 return filter_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000508}
509
Jim Ingham969795f2011-09-21 01:17:13 +0000510SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
512 SearchFilterSP filter_sp;
513 if (containingModules && containingModules->GetSize() != 0) {
514 // TODO: We should look into sharing module based search filters
515 // across many breakpoints like we do for the simple target based one
516 filter_sp.reset(
517 new SearchFilterByModuleList(shared_from_this(), *containingModules));
518 } else {
519 if (!m_search_filter_sp)
520 m_search_filter_sp.reset(
521 new SearchFilterForUnconstrainedSearches(shared_from_this()));
522 filter_sp = m_search_filter_sp;
523 }
524 return filter_sp;
Jim Ingham969795f2011-09-21 01:17:13 +0000525}
526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
528 const FileSpecList *containingModules,
529 const FileSpecList *containingSourceFiles) {
530 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
531 return GetSearchFilterForModuleList(containingModules);
532
533 SearchFilterSP filter_sp;
534 if (containingModules == nullptr) {
535 // We could make a special "CU List only SearchFilter". Better yet was if
Adrian Prantl05097242018-04-30 16:49:04 +0000536 // these could be composable, but that will take a little reworking.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537
538 filter_sp.reset(new SearchFilterByModuleListAndCU(
539 shared_from_this(), FileSpecList(), *containingSourceFiles));
540 } else {
541 filter_sp.reset(new SearchFilterByModuleListAndCU(
542 shared_from_this(), *containingModules, *containingSourceFiles));
543 }
544 return filter_sp;
Jim Ingham87df91b2011-09-23 00:54:11 +0000545}
546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547BreakpointSP Target::CreateFuncRegexBreakpoint(
548 const FileSpecList *containingModules,
549 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
550 lldb::LanguageType requested_language, LazyBool skip_prologue,
551 bool internal, bool hardware) {
552 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
553 containingModules, containingSourceFiles));
554 bool skip = (skip_prologue == eLazyBoolCalculate)
555 ? GetSkipPrologue()
556 : static_cast<bool>(skip_prologue);
557 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
558 nullptr, func_regex, requested_language, 0, skip));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000561}
562
Jim Ingham219ba192012-03-05 04:47:34 +0000563lldb::BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
565 bool catch_bp, bool throw_bp, bool internal,
Zachary Turner97206d52017-05-12 04:51:55 +0000566 Args *additional_args, Status *error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
568 *this, language, catch_bp, throw_bp, internal);
569 if (exc_bkpt_sp && additional_args) {
570 Breakpoint::BreakpointPreconditionSP precondition_sp =
571 exc_bkpt_sp->GetPrecondition();
572 if (precondition_sp && additional_args) {
573 if (error)
574 *error = precondition_sp->ConfigurePrecondition(*additional_args);
575 else
576 precondition_sp->ConfigurePrecondition(*additional_args);
Jim Inghama72b31c2015-04-22 19:42:18 +0000577 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 }
579 return exc_bkpt_sp;
Jim Ingham219ba192012-03-05 04:47:34 +0000580}
Jim Inghama72b31c2015-04-22 19:42:18 +0000581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
583 BreakpointResolverSP &resolver_sp,
584 bool internal, bool request_hardware,
585 bool resolve_indirect_symbols) {
586 BreakpointSP bp_sp;
587 if (filter_sp && resolver_sp) {
588 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, request_hardware,
589 resolve_indirect_symbols));
590 resolver_sp->SetBreakpoint(bp_sp.get());
591 AddBreakpoint(bp_sp, internal);
592 }
593 return bp_sp;
Jim Ingham33df7cd2014-12-06 01:28:03 +0000594}
595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
597 if (!bp_sp)
598 return;
599 if (internal)
600 m_internal_breakpoint_list.Add(bp_sp, false);
601 else
602 m_breakpoint_list.Add(bp_sp, true);
Jim Ingham33df7cd2014-12-06 01:28:03 +0000603
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
605 if (log) {
606 StreamString s;
607 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
608 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
609 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
610 }
Jim Ingham33df7cd2014-12-06 01:28:03 +0000611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 bp_sp->ResolveBreakpoint();
Jim Ingham33df7cd2014-12-06 01:28:03 +0000613
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 if (!internal) {
615 m_last_created_breakpoint = bp_sp;
616 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000617}
618
Jim Inghamb842f2e2017-09-14 20:22:49 +0000619void Target::AddNameToBreakpoint(BreakpointID &id,
620 const char *name,
621 Status &error)
622 {
623 BreakpointSP bp_sp
624 = m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
625 if (!bp_sp)
626 {
627 StreamString s;
628 id.GetDescription(&s, eDescriptionLevelBrief);
629 error.SetErrorStringWithFormat("Could not find breakpoint %s",
630 s.GetData());
631 return;
632 }
633 AddNameToBreakpoint(bp_sp, name, error);
634 }
635
636void Target::AddNameToBreakpoint(BreakpointSP &bp_sp,
637 const char *name,
638 Status &error)
639 {
640 if (!bp_sp)
641 return;
642
643 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
644 if (!bp_name)
645 return;
646
647 bp_name->ConfigureBreakpoint(bp_sp);
648 bp_sp->AddName(name);
649 }
650
651void Target::AddBreakpointName(BreakpointName *bp_name) {
652 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
653}
654
655BreakpointName *Target::FindBreakpointName(const ConstString &name,
656 bool can_create,
657 Status &error)
658{
659 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
660 if (!error.Success())
661 return nullptr;
662
663 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
664 if (iter == m_breakpoint_names.end()) {
665 if (!can_create)
666 {
667 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
668 "can_create is false.", name.AsCString());
669 return nullptr;
670 }
671
672 iter = m_breakpoint_names.insert(std::make_pair(name,
673 new BreakpointName(name)))
674 .first;
675 }
676 return (iter->second);
677}
678
679void
680Target::DeleteBreakpointName(const ConstString &name)
681{
682 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
683
684 if (iter != m_breakpoint_names.end()) {
685 const char *name_cstr = name.AsCString();
686 m_breakpoint_names.erase(iter);
687 for (auto bp_sp : m_breakpoint_list.Breakpoints())
688 bp_sp->RemoveName(name_cstr);
689 }
690}
691
692void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
693 const ConstString &name)
694{
695 bp_sp->RemoveName(name.AsCString());
696}
697
698void Target::ConfigureBreakpointName(BreakpointName &bp_name,
699 const BreakpointOptions &new_options,
700 const BreakpointName::Permissions &new_permissions)
701{
702 bp_name.GetOptions().CopyOverSetOptions(new_options);
703 bp_name.GetPermissions().MergeInto(new_permissions);
704 ApplyNameToBreakpoints(bp_name);
705}
706
707void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
708 BreakpointList bkpts_with_name(false);
709 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString(),
710 bkpts_with_name);
711
712 for (auto bp_sp : bkpts_with_name.Breakpoints())
713 bp_name.ConfigureBreakpoint(bp_sp);
714}
715
716void Target::GetBreakpointNames(std::vector<std::string> &names)
717{
718 names.clear();
719 for (auto bp_name : m_breakpoint_names) {
720 names.push_back(bp_name.first.AsCString());
721 }
722 std::sort(names.begin(), names.end());
723}
724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725bool Target::ProcessIsValid() {
726 return (m_process_sp && m_process_sp->IsAlive());
Johnny Chen86364b42011-09-20 23:28:55 +0000727}
728
Zachary Turner97206d52017-05-12 04:51:55 +0000729static bool CheckIfWatchpointsExhausted(Target *target, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 uint32_t num_supported_hardware_watchpoints;
Zachary Turner97206d52017-05-12 04:51:55 +0000731 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 num_supported_hardware_watchpoints);
733 if (num_supported_hardware_watchpoints == 0) {
734 error.SetErrorStringWithFormat(
735 "Target supports (%u) hardware watchpoint slots.\n",
736 num_supported_hardware_watchpoints);
737 return false;
738 }
739 return true;
Johnny Chenb90827e2012-06-04 23:19:54 +0000740}
741
Adrian Prantl05097242018-04-30 16:49:04 +0000742// See also Watchpoint::SetWatchpointType(uint32_t type) and the
743// OptionGroupWatchpoint::WatchType enum type.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
745 const CompilerType *type, uint32_t kind,
Zachary Turner97206d52017-05-12 04:51:55 +0000746 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
748 if (log)
749 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
750 " type = %u)\n",
751 __FUNCTION__, addr, (uint64_t)size, kind);
Johnny Chen0c406372011-09-14 20:23:45 +0000752
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 WatchpointSP wp_sp;
754 if (!ProcessIsValid()) {
755 error.SetErrorString("process is not alive");
Johnny Chen01a67862011-10-14 00:42:25 +0000756 return wp_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 }
Johnny Chen887062a2011-09-12 23:38:44 +0000758
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
760 if (size == 0)
761 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
764 return wp_sp;
765 }
766
767 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
768 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
769 }
770
771 if (!CheckIfWatchpointsExhausted(this, error))
772 return wp_sp;
773
Adrian Prantl05097242018-04-30 16:49:04 +0000774 // Currently we only support one watchpoint per address, with total number of
775 // watchpoints limited by the hardware which the inferior is running on.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776
777 // Grab the list mutex while doing operations.
778 const bool notify = false; // Don't notify about all the state changes we do
779 // on creating the watchpoint.
780 std::unique_lock<std::recursive_mutex> lock;
781 this->GetWatchpointList().GetListMutex(lock);
782 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
783 if (matched_sp) {
784 size_t old_size = matched_sp->GetByteSize();
785 uint32_t old_type =
786 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
787 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
788 // Return the existing watchpoint if both size and type match.
789 if (size == old_size && kind == old_type) {
790 wp_sp = matched_sp;
791 wp_sp->SetEnabled(false, notify);
792 } else {
793 // Nil the matched watchpoint; we will be creating a new one.
794 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
795 m_watchpoint_list.Remove(matched_sp->GetID(), true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 }
798
799 if (!wp_sp) {
800 wp_sp.reset(new Watchpoint(*this, addr, size, type));
801 wp_sp->SetWatchpointType(kind, notify);
802 m_watchpoint_list.Add(wp_sp, true);
803 }
804
805 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
806 if (log)
807 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
808 __FUNCTION__, error.Success() ? "succeeded" : "failed",
809 wp_sp->GetID());
810
811 if (error.Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000812 // Enabling the watchpoint on the device side failed. Remove the said
813 // watchpoint from the list maintained by the target instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 m_watchpoint_list.Remove(wp_sp->GetID(), true);
815 // See if we could provide more helpful error message.
816 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
817 error.SetErrorStringWithFormat(
818 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
819
820 wp_sp.reset();
821 } else
822 m_last_created_watchpoint = wp_sp;
823 return wp_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824}
825
Jim Inghamb842f2e2017-09-14 20:22:49 +0000826void Target::RemoveAllowedBreakpoints ()
827{
828 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
829 if (log)
830 log->Printf("Target::%s \n", __FUNCTION__);
831
832 m_breakpoint_list.RemoveAllowed(true);
833
834 m_last_created_breakpoint.reset();
835}
836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837void Target::RemoveAllBreakpoints(bool internal_also) {
838 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
839 if (log)
840 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
841 internal_also ? "yes" : "no");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 m_breakpoint_list.RemoveAll(true);
844 if (internal_also)
845 m_internal_breakpoint_list.RemoveAll(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 m_last_created_breakpoint.reset();
848}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850void Target::DisableAllBreakpoints(bool internal_also) {
851 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
852 if (log)
853 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
854 internal_also ? "yes" : "no");
855
856 m_breakpoint_list.SetEnabledAll(false);
857 if (internal_also)
858 m_internal_breakpoint_list.SetEnabledAll(false);
859}
860
Jim Inghamb842f2e2017-09-14 20:22:49 +0000861void Target::DisableAllowedBreakpoints() {
862 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
863 if (log)
864 log->Printf("Target::%s", __FUNCTION__);
865
866 m_breakpoint_list.SetEnabledAllowed(false);
867}
868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869void Target::EnableAllBreakpoints(bool internal_also) {
870 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
871 if (log)
872 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
873 internal_also ? "yes" : "no");
874
875 m_breakpoint_list.SetEnabledAll(true);
876 if (internal_also)
877 m_internal_breakpoint_list.SetEnabledAll(true);
878}
879
Jim Inghamb842f2e2017-09-14 20:22:49 +0000880void Target::EnableAllowedBreakpoints() {
881 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
882 if (log)
883 log->Printf("Target::%s", __FUNCTION__);
884
885 m_breakpoint_list.SetEnabledAllowed(true);
886}
887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888bool Target::RemoveBreakpointByID(break_id_t break_id) {
889 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
890 if (log)
891 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
892 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
893
894 if (DisableBreakpointByID(break_id)) {
895 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
896 m_internal_breakpoint_list.Remove(break_id, false);
897 else {
898 if (m_last_created_breakpoint) {
899 if (m_last_created_breakpoint->GetID() == break_id)
900 m_last_created_breakpoint.reset();
901 }
902 m_breakpoint_list.Remove(break_id, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 return true;
905 }
906 return false;
907}
908
909bool Target::DisableBreakpointByID(break_id_t break_id) {
910 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
911 if (log)
912 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
913 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
914
915 BreakpointSP bp_sp;
916
917 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
918 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
919 else
920 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
921 if (bp_sp) {
922 bp_sp->SetEnabled(false);
923 return true;
924 }
925 return false;
926}
927
928bool Target::EnableBreakpointByID(break_id_t break_id) {
929 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
930 if (log)
931 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
932 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
933
934 BreakpointSP bp_sp;
935
936 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
937 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
938 else
939 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
940
941 if (bp_sp) {
942 bp_sp->SetEnabled(true);
943 return true;
944 }
945 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946}
947
Zachary Turner97206d52017-05-12 04:51:55 +0000948Status Target::SerializeBreakpointsToFile(const FileSpec &file,
949 const BreakpointIDList &bp_ids,
950 bool append) {
951 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +0000952
953 if (!file) {
954 error.SetErrorString("Invalid FileSpec.");
955 return error;
956 }
957
958 std::string path(file.GetPath());
Jim Ingham2d3628e2016-09-22 23:42:42 +0000959 StructuredData::ObjectSP input_data_sp;
960
961 StructuredData::ArraySP break_store_sp;
962 StructuredData::Array *break_store_ptr = nullptr;
963
964 if (append) {
965 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
966 if (error.Success()) {
967 break_store_ptr = input_data_sp->GetAsArray();
968 if (!break_store_ptr) {
969 error.SetErrorStringWithFormat(
970 "Tried to append to invalid input file %s", path.c_str());
971 return error;
972 }
973 }
974 }
975
976 if (!break_store_ptr) {
977 break_store_sp.reset(new StructuredData::Array());
978 break_store_ptr = break_store_sp.get();
979 }
980
Jim Ingham01f16662016-09-14 19:07:35 +0000981 StreamFile out_file(path.c_str(),
982 File::OpenOptions::eOpenOptionTruncate |
983 File::OpenOptions::eOpenOptionWrite |
984 File::OpenOptions::eOpenOptionCanCreate |
985 File::OpenOptions::eOpenOptionCloseOnExec,
986 lldb::eFilePermissionsFileDefault);
987 if (!out_file.GetFile().IsValid()) {
988 error.SetErrorStringWithFormat("Unable to open output file: %s.",
989 path.c_str());
990 return error;
991 }
992
993 std::unique_lock<std::recursive_mutex> lock;
994 GetBreakpointList().GetListMutex(lock);
995
Jim Ingham01f16662016-09-14 19:07:35 +0000996 if (bp_ids.GetSize() == 0) {
997 const BreakpointList &breakpoints = GetBreakpointList();
998
999 size_t num_breakpoints = breakpoints.GetSize();
1000 for (size_t i = 0; i < num_breakpoints; i++) {
1001 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1002 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1003 // If a breakpoint can't serialize it, just ignore it for now:
1004 if (bkpt_save_sp)
Jim Ingham2d3628e2016-09-22 23:42:42 +00001005 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +00001006 }
1007 } else {
1008
1009 std::unordered_set<lldb::break_id_t> processed_bkpts;
1010 const size_t count = bp_ids.GetSize();
1011 for (size_t i = 0; i < count; ++i) {
1012 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1013 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1014
1015 if (bp_id != LLDB_INVALID_BREAK_ID) {
1016 // Only do each breakpoint once:
1017 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1018 insert_result = processed_bkpts.insert(bp_id);
1019 if (!insert_result.second)
1020 continue;
1021
1022 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1023 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1024 // If the user explicitly asked to serialize a breakpoint, and we
Adrian Prantl05097242018-04-30 16:49:04 +00001025 // can't, then raise an error:
Jim Ingham01f16662016-09-14 19:07:35 +00001026 if (!bkpt_save_sp) {
1027 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1028 bp_id);
1029 return error;
1030 }
Jim Ingham2d3628e2016-09-22 23:42:42 +00001031 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +00001032 }
1033 }
1034 }
1035
Jim Ingham2d3628e2016-09-22 23:42:42 +00001036 break_store_ptr->Dump(out_file, false);
Jim Ingham01f16662016-09-14 19:07:35 +00001037 out_file.PutChar('\n');
1038 return error;
1039}
1040
Zachary Turner97206d52017-05-12 04:51:55 +00001041Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1042 BreakpointIDList &new_bps) {
Jim Ingham3acdf382016-09-22 22:20:28 +00001043 std::vector<std::string> no_names;
1044 return CreateBreakpointsFromFile(file, no_names, new_bps);
1045}
1046
Zachary Turner97206d52017-05-12 04:51:55 +00001047Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1048 std::vector<std::string> &names,
1049 BreakpointIDList &new_bps) {
Jim Ingham01f16662016-09-14 19:07:35 +00001050 std::unique_lock<std::recursive_mutex> lock;
1051 GetBreakpointList().GetListMutex(lock);
1052
Zachary Turner97206d52017-05-12 04:51:55 +00001053 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +00001054 StructuredData::ObjectSP input_data_sp =
1055 StructuredData::ParseJSONFromFile(file, error);
1056 if (!error.Success()) {
1057 return error;
1058 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1059 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1060 file.GetPath().c_str());
1061 return error;
1062 }
1063
1064 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1065 if (!bkpt_array) {
1066 error.SetErrorStringWithFormat(
1067 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1068 return error;
1069 }
1070
1071 size_t num_bkpts = bkpt_array->GetSize();
Jim Ingham3acdf382016-09-22 22:20:28 +00001072 size_t num_names = names.size();
1073
Jim Ingham01f16662016-09-14 19:07:35 +00001074 for (size_t i = 0; i < num_bkpts; i++) {
1075 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1076 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1077 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1078 if (!bkpt_dict) {
1079 error.SetErrorStringWithFormat(
1080 "Invalid breakpoint data for element %zu from input file: %s.", i,
1081 file.GetPath().c_str());
1082 return error;
1083 }
1084 StructuredData::ObjectSP bkpt_data_sp =
1085 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
Jim Ingham3acdf382016-09-22 22:20:28 +00001086 if (num_names &&
1087 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1088 continue;
1089
Jim Ingham01f16662016-09-14 19:07:35 +00001090 BreakpointSP bkpt_sp =
1091 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1092 if (!error.Success()) {
1093 error.SetErrorStringWithFormat(
1094 "Error restoring breakpoint %zu from %s: %s.", i,
1095 file.GetPath().c_str(), error.AsCString());
1096 return error;
1097 }
1098 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1099 }
1100 return error;
1101}
1102
Johnny Chenedf50372011-09-23 21:21:43 +00001103// The flag 'end_to_end', default to true, signifies that the operation is
1104// performed end to end, for both the debugger and the debuggee.
1105
Johnny Chen01a67862011-10-14 00:42:25 +00001106// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1107// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108bool Target::RemoveAllWatchpoints(bool end_to_end) {
1109 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1110 if (log)
1111 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001112
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 if (!end_to_end) {
1114 m_watchpoint_list.RemoveAll(true);
1115 return true;
1116 }
Johnny Chenedf50372011-09-23 21:21:43 +00001117
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001119
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 if (!ProcessIsValid())
1121 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001122
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 size_t num_watchpoints = m_watchpoint_list.GetSize();
1124 for (size_t i = 0; i < num_watchpoints; ++i) {
1125 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1126 if (!wp_sp)
1127 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001128
Zachary Turner97206d52017-05-12 04:51:55 +00001129 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (rc.Fail())
1131 return false;
1132 }
1133 m_watchpoint_list.RemoveAll(true);
1134 m_last_created_watchpoint.reset();
1135 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001136}
1137
Adrian Prantl05097242018-04-30 16:49:04 +00001138// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1139// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140bool Target::DisableAllWatchpoints(bool end_to_end) {
1141 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1142 if (log)
1143 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001144
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 if (!end_to_end) {
1146 m_watchpoint_list.SetEnabledAll(false);
1147 return true;
1148 }
Johnny Chenedf50372011-09-23 21:21:43 +00001149
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001151
Kate Stoneb9c1b512016-09-06 20:57:50 +00001152 if (!ProcessIsValid())
1153 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001154
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 size_t num_watchpoints = m_watchpoint_list.GetSize();
1156 for (size_t i = 0; i < num_watchpoints; ++i) {
1157 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1158 if (!wp_sp)
1159 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001160
Zachary Turner97206d52017-05-12 04:51:55 +00001161 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162 if (rc.Fail())
1163 return false;
1164 }
1165 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001166}
1167
Adrian Prantl05097242018-04-30 16:49:04 +00001168// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1169// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170bool Target::EnableAllWatchpoints(bool end_to_end) {
1171 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1172 if (log)
1173 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001174
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 if (!end_to_end) {
1176 m_watchpoint_list.SetEnabledAll(true);
1177 return true;
1178 }
Johnny Chenedf50372011-09-23 21:21:43 +00001179
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 if (!ProcessIsValid())
1183 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001184
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 size_t num_watchpoints = m_watchpoint_list.GetSize();
1186 for (size_t i = 0; i < num_watchpoints; ++i) {
1187 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1188 if (!wp_sp)
1189 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001190
Zachary Turner97206d52017-05-12 04:51:55 +00001191 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 if (rc.Fail())
1193 return false;
1194 }
1195 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001196}
1197
Johnny Chena4d6bc92012-02-25 06:44:30 +00001198// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199bool Target::ClearAllWatchpointHitCounts() {
1200 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1201 if (log)
1202 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chena4d6bc92012-02-25 06:44:30 +00001203
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 size_t num_watchpoints = m_watchpoint_list.GetSize();
1205 for (size_t i = 0; i < num_watchpoints; ++i) {
1206 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1207 if (!wp_sp)
1208 return false;
Johnny Chena4d6bc92012-02-25 06:44:30 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 wp_sp->ResetHitCount();
1211 }
1212 return true; // Success!
Johnny Chena4d6bc92012-02-25 06:44:30 +00001213}
1214
Enrico Granata5e3fe042015-02-11 00:37:54 +00001215// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216bool Target::ClearAllWatchpointHistoricValues() {
1217 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1218 if (log)
1219 log->Printf("Target::%s\n", __FUNCTION__);
1220
1221 size_t num_watchpoints = m_watchpoint_list.GetSize();
1222 for (size_t i = 0; i < num_watchpoints; ++i) {
1223 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1224 if (!wp_sp)
1225 return false;
1226
1227 wp_sp->ResetHistoricValues();
1228 }
1229 return true; // Success!
Enrico Granata5e3fe042015-02-11 00:37:54 +00001230}
1231
Adrian Prantl05097242018-04-30 16:49:04 +00001232// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1233// these operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1235 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1236 if (log)
1237 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001238
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 if (!ProcessIsValid())
1240 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001241
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 size_t num_watchpoints = m_watchpoint_list.GetSize();
1243 for (size_t i = 0; i < num_watchpoints; ++i) {
1244 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1245 if (!wp_sp)
1246 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001247
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 wp_sp->SetIgnoreCount(ignore_count);
1249 }
1250 return true; // Success!
Johnny Chen6cc60e82011-10-05 21:35:46 +00001251}
1252
Johnny Chen01a67862011-10-14 00:42:25 +00001253// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1255 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1256 if (log)
1257 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001258
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001260 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261
1262 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1263 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001264 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 if (rc.Success())
1266 return true;
1267
1268 // Else, fallthrough.
1269 }
1270 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001271}
1272
Johnny Chen01a67862011-10-14 00:42:25 +00001273// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1275 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1276 if (log)
1277 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001278
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001280 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281
1282 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1283 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001284 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 if (rc.Success())
1286 return true;
1287
1288 // Else, fallthrough.
1289 }
1290 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001291}
1292
Johnny Chen01a67862011-10-14 00:42:25 +00001293// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1295 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1296 if (log)
1297 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1300 if (watch_to_remove_sp == m_last_created_watchpoint)
1301 m_last_created_watchpoint.reset();
1302
1303 if (DisableWatchpointByID(watch_id)) {
1304 m_watchpoint_list.Remove(watch_id, true);
1305 return true;
1306 }
1307 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001308}
1309
Johnny Chen01a67862011-10-14 00:42:25 +00001310// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1312 uint32_t ignore_count) {
1313 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1314 if (log)
1315 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 if (!ProcessIsValid())
Johnny Chen6cc60e82011-10-05 21:35:46 +00001318 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319
1320 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1321 if (wp_sp) {
1322 wp_sp->SetIgnoreCount(ignore_count);
1323 return true;
1324 }
1325 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001326}
1327
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328ModuleSP Target::GetExecutableModule() {
1329 // search for the first executable in the module list
1330 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1331 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1332 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1333 if (obj == nullptr)
1334 continue;
1335 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1336 return module_sp;
1337 }
1338 // as fall back return the first module loaded
1339 return m_images.GetModuleAtIndex(0);
Greg Claytonaa149cb2011-08-11 02:48:45 +00001340}
1341
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342Module *Target::GetExecutableModulePointer() {
1343 return GetExecutableModule().get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001344}
1345
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1347 Target *target) {
Zachary Turner97206d52017-05-12 04:51:55 +00001348 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349 StreamString feedback_stream;
1350 if (module_sp &&
1351 !module_sp->LoadScriptingResourceInTarget(target, error,
1352 &feedback_stream)) {
1353 if (error.AsCString())
1354 target->GetDebugger().GetErrorFile()->Printf(
1355 "unable to load scripting data for module %s - error reported was "
1356 "%s\n",
1357 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1358 error.AsCString());
1359 }
1360 if (feedback_stream.GetSize())
1361 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1362 feedback_stream.GetData());
Enrico Granata17598482012-11-08 02:22:02 +00001363}
1364
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365void Target::ClearModules(bool delete_locations) {
1366 ModulesDidUnload(m_images, delete_locations);
1367 m_section_load_history.Clear();
1368 m_images.Clear();
1369 m_scratch_type_system_map.Clear();
1370 m_ast_importer_sp.reset();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001371}
1372
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373void Target::DidExec() {
1374 // When a process exec's we need to know about it so we can do some cleanup.
Pavel Labath13e37d42017-10-25 21:05:31 +00001375 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1376 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
Greg Claytonb35db632013-11-09 00:03:31 +00001377}
1378
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379void Target::SetExecutableModule(ModuleSP &executable_sp,
1380 bool get_dependent_files) {
1381 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1382 ClearModules(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 if (executable_sp) {
Pavel Labathf9d16472017-05-15 13:02:37 +00001385 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1386 Timer scoped_timer(func_cat,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 "Target::SetExecutableModule (executable = '%s')",
1388 executable_sp->GetFileSpec().GetPath().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001389
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 m_images.Append(executable_sp); // The first image is our executable file
Jason Molendae1b68ad2012-12-05 00:25:49 +00001391
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392 // If we haven't set an architecture yet, reset our architecture based on
1393 // what we found in the executable module.
Pavel Labath13e37d42017-10-25 21:05:31 +00001394 if (!m_arch.GetSpec().IsValid()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 m_arch = executable_sp->GetArchitecture();
Pavel Labath13e37d42017-10-25 21:05:31 +00001396 LLDB_LOG(log,
1397 "setting architecture to {0} ({1}) based on executable file",
1398 m_arch.GetSpec().GetArchitectureName(),
1399 m_arch.GetSpec().GetTriple().getTriple());
Jason Molendadad8af42015-11-10 04:11:37 +00001400 }
1401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 FileSpecList dependent_files;
1403 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001404
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 if (executable_objfile && get_dependent_files) {
1406 executable_objfile->GetDependentModules(dependent_files);
1407 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1408 FileSpec dependent_file_spec(
1409 dependent_files.GetFileSpecPointerAtIndex(i));
1410 FileSpec platform_dependent_file_spec;
Greg Clayton67cc0632012-08-22 17:17:09 +00001411 if (m_platform_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001412 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1413 platform_dependent_file_spec);
1414 else
1415 platform_dependent_file_spec = dependent_file_spec;
1416
Pavel Labath13e37d42017-10-25 21:05:31 +00001417 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 ModuleSP image_module_sp(GetSharedModule(module_spec));
1419 if (image_module_sp) {
1420 ObjectFile *objfile = image_module_sp->GetObjectFile();
1421 if (objfile)
1422 objfile->GetDependentModules(dependent_files);
1423 }
1424 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001425 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001427}
1428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429bool Target::SetArchitecture(const ArchSpec &arch_spec) {
1430 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
Pavel Labath13e37d42017-10-25 21:05:31 +00001431 bool missing_local_arch = !m_arch.GetSpec().IsValid();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 bool replace_local_arch = true;
1433 bool compatible_local_arch = false;
1434 ArchSpec other(arch_spec);
Greg Claytone72dfb32012-02-24 01:59:29 +00001435
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 if (!missing_local_arch) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001437 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1438 other.MergeFrom(m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439
Pavel Labath13e37d42017-10-25 21:05:31 +00001440 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 compatible_local_arch = true;
1442 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1443 env_changed;
1444
Pavel Labath13e37d42017-10-25 21:05:31 +00001445 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 os_changed, os_ver_changed, env_changed);
1447
1448 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1449 replace_local_arch = false;
1450 }
1451 }
1452 }
1453
1454 if (compatible_local_arch || missing_local_arch) {
1455 // If we haven't got a valid arch spec, or the architectures are compatible
Adrian Prantl05097242018-04-30 16:49:04 +00001456 // update the architecture, unless the one we already have is more
1457 // specified
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 if (replace_local_arch)
1459 m_arch = other;
Pavel Labath13e37d42017-10-25 21:05:31 +00001460 LLDB_LOG(log, "set architecture to {0} ({1})",
1461 m_arch.GetSpec().GetArchitectureName(),
1462 m_arch.GetSpec().GetTriple().getTriple());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 return true;
1464 }
1465
1466 // If we have an executable file, try to reset the executable to the desired
1467 // architecture
1468 if (log)
1469 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1470 arch_spec.GetArchitectureName(),
1471 arch_spec.GetTriple().getTriple().c_str());
1472 m_arch = other;
1473 ModuleSP executable_sp = GetExecutableModule();
1474
1475 ClearModules(true);
1476 // Need to do something about unsetting breakpoints.
1477
1478 if (executable_sp) {
1479 if (log)
1480 log->Printf("Target::SetArchitecture Trying to select executable file "
1481 "architecture %s (%s)",
1482 arch_spec.GetArchitectureName(),
1483 arch_spec.GetTriple().getTriple().c_str());
1484 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
Zachary Turner97206d52017-05-12 04:51:55 +00001485 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1486 &GetExecutableSearchPaths(),
1487 nullptr, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001488
1489 if (!error.Fail() && executable_sp) {
1490 SetExecutableModule(executable_sp, true);
1491 return true;
1492 }
1493 }
1494 return false;
Greg Claytondb598232011-01-07 01:57:07 +00001495}
1496
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1498 if (arch_spec.IsValid()) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001499 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001500 // The current target arch is compatible with "arch_spec", see if we can
1501 // improve our current architecture using bits from "arch_spec"
Greg Claytonc749eb82011-07-11 05:12:02 +00001502
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503 // Merge bits from arch_spec into "merged_arch" and set our architecture
Pavel Labath13e37d42017-10-25 21:05:31 +00001504 ArchSpec merged_arch(m_arch.GetSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 merged_arch.MergeFrom(arch_spec);
1506 return SetArchitecture(merged_arch);
1507 } else {
1508 // The new architecture is different, we just need to replace it
1509 return SetArchitecture(arch_spec);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001510 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 }
1512 return false;
1513}
Greg Claytonc749eb82011-07-11 05:12:02 +00001514
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515void Target::WillClearList(const ModuleList &module_list) {}
1516
1517void Target::ModuleAdded(const ModuleList &module_list,
1518 const ModuleSP &module_sp) {
1519 // A module is being added to this target for the first time
1520 if (m_valid) {
1521 ModuleList my_module_list;
1522 my_module_list.Append(module_sp);
1523 LoadScriptingResourceForModule(module_sp, this);
1524 ModulesDidLoad(my_module_list);
1525 }
1526}
1527
1528void Target::ModuleRemoved(const ModuleList &module_list,
1529 const ModuleSP &module_sp) {
1530 // A module is being removed from this target.
1531 if (m_valid) {
1532 ModuleList my_module_list;
1533 my_module_list.Append(module_sp);
1534 ModulesDidUnload(my_module_list, false);
1535 }
1536}
1537
1538void Target::ModuleUpdated(const ModuleList &module_list,
1539 const ModuleSP &old_module_sp,
1540 const ModuleSP &new_module_sp) {
1541 // A module is replacing an already added module
1542 if (m_valid) {
1543 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1544 new_module_sp);
1545 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1546 old_module_sp, new_module_sp);
1547 }
1548}
1549
1550void Target::ModulesDidLoad(ModuleList &module_list) {
1551 if (m_valid && module_list.GetSize()) {
1552 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1553 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1554 if (m_process_sp) {
1555 m_process_sp->ModulesDidLoad(module_list);
1556 }
1557 BroadcastEvent(eBroadcastBitModulesLoaded,
1558 new TargetEventData(this->shared_from_this(), module_list));
1559 }
1560}
1561
1562void Target::SymbolsDidLoad(ModuleList &module_list) {
1563 if (m_valid && module_list.GetSize()) {
1564 if (m_process_sp) {
1565 LanguageRuntime *runtime =
1566 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1567 if (runtime) {
1568 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1569 objc_runtime->SymbolsDidLoad(module_list);
1570 }
1571 }
1572
1573 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1574 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1575 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1576 new TargetEventData(this->shared_from_this(), module_list));
1577 }
1578}
1579
1580void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1581 if (m_valid && module_list.GetSize()) {
1582 UnloadModuleSections(module_list);
1583 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1584 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1585 delete_locations);
1586 BroadcastEvent(eBroadcastBitModulesUnloaded,
1587 new TargetEventData(this->shared_from_this(), module_list));
1588 }
1589}
1590
1591bool Target::ModuleIsExcludedForUnconstrainedSearches(
1592 const FileSpec &module_file_spec) {
1593 if (GetBreakpointsConsultPlatformAvoidList()) {
1594 ModuleList matchingModules;
1595 ModuleSpec module_spec(module_file_spec);
1596 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1597
1598 // If there is more than one module for this file spec, only return true if
1599 // ALL the modules are on the
1600 // black list.
1601 if (num_modules > 0) {
1602 for (size_t i = 0; i < num_modules; i++) {
1603 if (!ModuleIsExcludedForUnconstrainedSearches(
1604 matchingModules.GetModuleAtIndex(i)))
1605 return false;
1606 }
1607 return true;
1608 }
1609 }
1610 return false;
1611}
1612
1613bool Target::ModuleIsExcludedForUnconstrainedSearches(
1614 const lldb::ModuleSP &module_sp) {
1615 if (GetBreakpointsConsultPlatformAvoidList()) {
1616 if (m_platform_sp)
1617 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1618 module_sp);
1619 }
1620 return false;
1621}
1622
1623size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001624 size_t dst_len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 SectionSP section_sp(addr.GetSection());
1626 if (section_sp) {
1627 // If the contents of this section are encrypted, the on-disk file is
1628 // unusable. Read only from live memory.
1629 if (section_sp->IsEncrypted()) {
1630 error.SetErrorString("section is encrypted");
1631 return 0;
1632 }
1633 ModuleSP module_sp(section_sp->GetModule());
1634 if (module_sp) {
1635 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1636 if (objfile) {
1637 size_t bytes_read = objfile->ReadSectionData(
1638 section_sp.get(), addr.GetOffset(), dst, dst_len);
Greg Claytondb598232011-01-07 01:57:07 +00001639 if (bytes_read > 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001641 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 error.SetErrorStringWithFormat("error reading data from section %s",
1643 section_sp->GetName().GetCString());
1644 } else
1645 error.SetErrorString("address isn't from a object file");
1646 } else
1647 error.SetErrorString("address isn't in a module");
1648 } else
1649 error.SetErrorString("address doesn't contain a section that points to a "
1650 "section in a object file");
1651
1652 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001653}
1654
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001656 void *dst, size_t dst_len, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 lldb::addr_t *load_addr_ptr) {
1658 error.Clear();
1659
Adrian Prantl05097242018-04-30 16:49:04 +00001660 // if we end up reading this from process memory, we will fill this with the
1661 // actual load address
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 if (load_addr_ptr)
1663 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1664
1665 size_t bytes_read = 0;
1666
1667 addr_t load_addr = LLDB_INVALID_ADDRESS;
1668 addr_t file_addr = LLDB_INVALID_ADDRESS;
1669 Address resolved_addr;
1670 if (!addr.IsSectionOffset()) {
1671 SectionLoadList &section_load_list = GetSectionLoadList();
1672 if (section_load_list.IsEmpty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001673 // No sections are loaded, so we must assume we are not running yet and
1674 // anything we are given is a file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1676 // offset is the file address
1677 m_images.ResolveFileAddress(file_addr, resolved_addr);
1678 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001679 // We have at least one section loaded. This can be because we have
1680 // manually loaded some sections with "target modules load ..." or
1681 // because we have have a live process that has sections loaded through
1682 // the dynamic loader
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1684 // offset is the load address
1685 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1686 }
1687 }
1688 if (!resolved_addr.IsValid())
1689 resolved_addr = addr;
1690
1691 if (prefer_file_cache) {
1692 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1693 if (bytes_read > 0)
1694 return bytes_read;
1695 }
1696
1697 if (ProcessIsValid()) {
1698 if (load_addr == LLDB_INVALID_ADDRESS)
1699 load_addr = resolved_addr.GetLoadAddress(this);
1700
1701 if (load_addr == LLDB_INVALID_ADDRESS) {
1702 ModuleSP addr_module_sp(resolved_addr.GetModule());
1703 if (addr_module_sp && addr_module_sp->GetFileSpec())
Zachary Turner827d5d72016-12-16 04:27:00 +00001704 error.SetErrorStringWithFormatv(
1705 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1706 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 else
1708 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1709 resolved_addr.GetFileAddress());
1710 } else {
1711 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1712 if (bytes_read != dst_len) {
1713 if (error.Success()) {
1714 if (bytes_read == 0)
1715 error.SetErrorStringWithFormat(
1716 "read memory from 0x%" PRIx64 " failed", load_addr);
1717 else
1718 error.SetErrorStringWithFormat(
1719 "only %" PRIu64 " of %" PRIu64
1720 " bytes were read from memory at 0x%" PRIx64,
1721 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1722 }
1723 }
1724 if (bytes_read) {
1725 if (load_addr_ptr)
1726 *load_addr_ptr = load_addr;
1727 return bytes_read;
1728 }
Adrian Prantl05097242018-04-30 16:49:04 +00001729 // If the address is not section offset we have an address that doesn't
1730 // resolve to any address in any currently loaded shared libraries and we
1731 // failed to read memory so there isn't anything more we can do. If it is
1732 // section offset, we might be able to read cached memory from the object
1733 // file.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734 if (!resolved_addr.IsSectionOffset())
1735 return 0;
1736 }
1737 }
1738
1739 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001740 // If we didn't already try and read from the object file cache, then try
1741 // it after failing to read from the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1743 }
1744 return 0;
1745}
1746
1747size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001748 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 char buf[256];
1750 out_str.clear();
1751 addr_t curr_addr = addr.GetLoadAddress(this);
1752 Address address(addr);
1753 while (1) {
1754 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1755 if (length == 0)
1756 break;
1757 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00001758 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1759 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 if (length == sizeof(buf) - 1)
1761 curr_addr += length;
1762 else
1763 break;
1764 address = Address(curr_addr);
1765 }
1766 return out_str.size();
1767}
1768
1769size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001770 size_t dst_max_len, Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771 size_t total_cstr_len = 0;
1772 if (dst && dst_max_len) {
1773 result_error.Clear();
1774 // NULL out everything just to be safe
1775 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00001776 Status error;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001777 addr_t curr_addr = addr.GetLoadAddress(this);
1778 Address address(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001779
Adrian Prantl05097242018-04-30 16:49:04 +00001780 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1781 // this really needs to be tied to the memory cache subsystem's cache line
1782 // size, so leave this as a fixed constant.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783 const size_t cache_line_size = 512;
1784
1785 size_t bytes_left = dst_max_len - 1;
1786 char *curr_dst = dst;
1787
1788 while (bytes_left > 0) {
1789 addr_t cache_line_bytes_left =
1790 cache_line_size - (curr_addr % cache_line_size);
1791 addr_t bytes_to_read =
1792 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1793 size_t bytes_read =
1794 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1795
1796 if (bytes_read == 0) {
1797 result_error = error;
1798 dst[total_cstr_len] = '\0';
1799 break;
1800 }
1801 const size_t len = strlen(curr_dst);
1802
1803 total_cstr_len += len;
1804
1805 if (len < bytes_to_read)
1806 break;
1807
1808 curr_dst += bytes_read;
1809 curr_addr += bytes_read;
1810 bytes_left -= bytes_read;
1811 address = Address(curr_addr);
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001812 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 } else {
1814 if (dst == nullptr)
1815 result_error.SetErrorString("invalid arguments");
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001816 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001817 result_error.Clear();
1818 }
1819 return total_cstr_len;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001820}
1821
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1823 bool prefer_file_cache,
1824 uint32_t byte_size, bool is_signed,
Zachary Turner97206d52017-05-12 04:51:55 +00001825 Scalar &scalar, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 uint64_t uval;
1827
1828 if (byte_size <= sizeof(uval)) {
1829 size_t bytes_read =
1830 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1831 if (bytes_read == byte_size) {
Pavel Labath13e37d42017-10-25 21:05:31 +00001832 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1833 m_arch.GetSpec().GetAddressByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001834 lldb::offset_t offset = 0;
1835 if (byte_size <= 4)
1836 scalar = data.GetMaxU32(&offset, byte_size);
1837 else
1838 scalar = data.GetMaxU64(&offset, byte_size);
1839
1840 if (is_signed)
1841 scalar.SignExtend(byte_size * 8);
1842 return bytes_read;
1843 }
1844 } else {
1845 error.SetErrorStringWithFormat(
1846 "byte size of %u is too large for integer scalar type", byte_size);
1847 }
1848 return 0;
1849}
1850
1851uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1852 bool prefer_file_cache,
1853 size_t integer_byte_size,
1854 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00001855 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856 Scalar scalar;
1857 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1858 false, scalar, error))
1859 return scalar.ULongLong(fail_value);
1860 return fail_value;
1861}
1862
1863bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001864 Status &error, Address &pointer_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 Scalar scalar;
1866 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
Pavel Labath13e37d42017-10-25 21:05:31 +00001867 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868 error)) {
1869 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1870 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1871 SectionLoadList &section_load_list = GetSectionLoadList();
1872 if (section_load_list.IsEmpty()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001873 // No sections are loaded, so we must assume we are not running yet and
1874 // anything we are given is a file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1876 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00001877 // We have at least one section loaded. This can be because we have
1878 // manually loaded some sections with "target modules load ..." or
1879 // because we have have a live process that has sections loaded through
1880 // the dynamic loader
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1882 }
Adrian Prantl05097242018-04-30 16:49:04 +00001883 // We weren't able to resolve the pointer value, so just return an
1884 // address with no section
Kate Stoneb9c1b512016-09-06 20:57:50 +00001885 if (!pointer_addr.IsValid())
1886 pointer_addr.SetOffset(pointer_vm_addr);
1887 return true;
1888 }
1889 }
1890 return false;
1891}
1892
1893ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
Zachary Turner97206d52017-05-12 04:51:55 +00001894 Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001895 ModuleSP module_sp;
1896
Zachary Turner97206d52017-05-12 04:51:55 +00001897 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898
1899 // First see if we already have this module in our module list. If we do,
Adrian Prantl05097242018-04-30 16:49:04 +00001900 // then we're done, we don't need to consult the shared modules list. But
1901 // only do this if we are passed a UUID.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902
1903 if (module_spec.GetUUID().IsValid())
1904 module_sp = m_images.FindFirstModule(module_spec);
1905
1906 if (!module_sp) {
1907 ModuleSP old_module_sp; // This will get filled in if we have a new version
1908 // of the library
1909 bool did_create_module = false;
1910
1911 // If there are image search path entries, try to use them first to acquire
1912 // a suitable image.
1913 if (m_image_search_paths.GetSize()) {
1914 ModuleSpec transformed_spec(module_spec);
1915 if (m_image_search_paths.RemapPath(
1916 module_spec.GetFileSpec().GetDirectory(),
1917 transformed_spec.GetFileSpec().GetDirectory())) {
1918 transformed_spec.GetFileSpec().GetFilename() =
1919 module_spec.GetFileSpec().GetFilename();
1920 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1921 &GetExecutableSearchPaths(),
1922 &old_module_sp, &did_create_module);
1923 }
1924 }
1925
1926 if (!module_sp) {
1927 // If we have a UUID, we can check our global shared module list in case
1928 // we already have it. If we don't have a valid UUID, then we can't since
1929 // the path in "module_spec" will be a platform path, and we will need to
1930 // let the platform find that file. For example, we could be asking for
1931 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1932 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1933 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1934 // cache.
1935 if (module_spec.GetUUID().IsValid()) {
1936 // We have a UUID, it is OK to check the global module list...
1937 error = ModuleList::GetSharedModule(module_spec, module_sp,
1938 &GetExecutableSearchPaths(),
1939 &old_module_sp, &did_create_module);
1940 }
1941
1942 if (!module_sp) {
1943 // The platform is responsible for finding and caching an appropriate
1944 // module in the shared module cache.
1945 if (m_platform_sp) {
1946 error = m_platform_sp->GetSharedModule(
1947 module_spec, m_process_sp.get(), module_sp,
1948 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
1949 } else {
1950 error.SetErrorString("no platform is currently set");
Greg Claytond16e1e52011-07-12 17:06:17 +00001951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001953 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001954
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 // We found a module that wasn't in our target list. Let's make sure that
Adrian Prantl05097242018-04-30 16:49:04 +00001956 // there wasn't an equivalent module in the list already, and if there was,
1957 // let's remove it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958 if (module_sp) {
1959 ObjectFile *objfile = module_sp->GetObjectFile();
1960 if (objfile) {
1961 switch (objfile->GetType()) {
1962 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
1963 /// a program's execution state
1964 case ObjectFile::eTypeExecutable: /// A normal executable
1965 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
1966 /// executable
1967 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1968 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
1969 /// used during execution
1970 break;
1971 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
1972 /// debug information
1973 if (error_ptr)
1974 error_ptr->SetErrorString("debug info files aren't valid target "
1975 "modules, please specify an executable");
1976 return ModuleSP();
1977 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
1978 /// against but not used for
1979 /// execution
1980 if (error_ptr)
1981 error_ptr->SetErrorString("stub libraries aren't valid target "
1982 "modules, please specify an executable");
1983 return ModuleSP();
1984 default:
1985 if (error_ptr)
1986 error_ptr->SetErrorString(
1987 "unsupported file type, please specify an executable");
1988 return ModuleSP();
Greg Claytond16e1e52011-07-12 17:06:17 +00001989 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001990 // GetSharedModule is not guaranteed to find the old shared module, for
Adrian Prantl05097242018-04-30 16:49:04 +00001991 // instance in the common case where you pass in the UUID, it is only
1992 // going to find the one module matching the UUID. In fact, it has no
1993 // good way to know what the "old module" relevant to this target is,
1994 // since there might be many copies of a module with this file spec in
1995 // various running debug sessions, but only one of them will belong to
1996 // this target. So let's remove the UUID from the module list, and look
1997 // in the target's module list. Only do this if there is SOMETHING else
1998 // in the module spec...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 if (!old_module_sp) {
2000 if (module_spec.GetUUID().IsValid() &&
2001 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2002 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2003 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2004 module_spec_copy.GetUUID().Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 ModuleList found_modules;
2007 size_t num_found =
2008 m_images.FindModules(module_spec_copy, found_modules);
2009 if (num_found == 1) {
2010 old_module_sp = found_modules.GetModuleAtIndex(0);
Jim Ingham4a94c912012-05-17 18:38:42 +00002011 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002012 }
Greg Claytonb69bb2e2012-04-27 00:58:27 +00002013 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014
Jim Ingham7fca8c02017-04-28 00:51:06 +00002015 // Preload symbols outside of any lock, so hopefully we can do this for
2016 // each library in parallel.
2017 if (GetPreloadSymbols())
2018 module_sp->PreloadSymbols();
2019
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 if (old_module_sp &&
2021 m_images.GetIndexForModule(old_module_sp.get()) !=
2022 LLDB_INVALID_INDEX32) {
2023 m_images.ReplaceModule(old_module_sp, module_sp);
2024 Module *old_module_ptr = old_module_sp.get();
2025 old_module_sp.reset();
2026 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2027 } else
2028 m_images.Append(module_sp);
2029 } else
2030 module_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002032 }
2033 if (error_ptr)
2034 *error_ptr = error;
2035 return module_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036}
2037
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038TargetSP Target::CalculateTarget() { return shared_from_this(); }
2039
2040ProcessSP Target::CalculateProcess() { return m_process_sp; }
2041
2042ThreadSP Target::CalculateThread() { return ThreadSP(); }
2043
2044StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2045
2046void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2047 exe_ctx.Clear();
2048 exe_ctx.SetTargetPtr(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002049}
2050
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051PathMappingList &Target::GetImageSearchPathList() {
2052 return m_image_search_paths;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053}
2054
Kate Stoneb9c1b512016-09-06 20:57:50 +00002055void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2056 void *baton) {
2057 Target *target = (Target *)baton;
2058 ModuleSP exe_module_sp(target->GetExecutableModule());
2059 if (exe_module_sp)
2060 target->SetExecutableModule(exe_module_sp, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061}
2062
Zachary Turner97206d52017-05-12 04:51:55 +00002063TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002064 lldb::LanguageType language,
2065 bool create_on_demand) {
2066 if (!m_valid)
2067 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068
Kate Stoneb9c1b512016-09-06 20:57:50 +00002069 if (error) {
2070 error->Clear();
2071 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002072
Kate Stoneb9c1b512016-09-06 20:57:50 +00002073 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2074 // assembly code
2075 || language == eLanguageTypeUnknown) {
2076 std::set<lldb::LanguageType> languages_for_types;
2077 std::set<lldb::LanguageType> languages_for_expressions;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2080 languages_for_expressions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082 if (languages_for_expressions.count(eLanguageTypeC)) {
2083 language = eLanguageTypeC; // LLDB's default. Override by setting the
2084 // target language.
2085 } else {
2086 if (languages_for_expressions.empty()) {
Greg Clayton5beec212015-10-08 21:04:34 +00002087 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088 } else {
2089 language = *languages_for_expressions.begin();
2090 }
Sean Callanana994b0b2015-10-02 18:40:30 +00002091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002092 }
Sean Callananb92bd752015-10-01 16:28:02 +00002093
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2095 create_on_demand);
Sean Callananb92bd752015-10-01 16:28:02 +00002096}
2097
2098PersistentExpressionState *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2100 TypeSystem *type_system =
2101 GetScratchTypeSystemForLanguage(nullptr, language, true);
2102
2103 if (type_system) {
2104 return type_system->GetPersistentExpressionState();
2105 } else {
2106 return nullptr;
2107 }
Jim Ingham151c0322015-09-15 21:13:50 +00002108}
2109
Kate Stoneb9c1b512016-09-06 20:57:50 +00002110UserExpression *Target::GetUserExpressionForLanguage(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002111 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 Expression::ResultType desired_type,
Zachary Turner97206d52017-05-12 04:51:55 +00002113 const EvaluateExpressionOptions &options, Status &error) {
2114 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115
2116 TypeSystem *type_system =
2117 GetScratchTypeSystemForLanguage(&type_system_error, language);
2118 UserExpression *user_expr = nullptr;
2119
2120 if (!type_system) {
2121 error.SetErrorStringWithFormat(
2122 "Could not find type system for language %s: %s",
2123 Language::GetNameForLanguageType(language),
2124 type_system_error.AsCString());
2125 return nullptr;
2126 }
2127
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002128 user_expr = type_system->GetUserExpression(expr, prefix, language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 desired_type, options);
2130 if (!user_expr)
2131 error.SetErrorStringWithFormat(
2132 "Could not create an expression for language %s",
2133 Language::GetNameForLanguageType(language));
2134
2135 return user_expr;
Jim Ingham151c0322015-09-15 21:13:50 +00002136}
2137
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138FunctionCaller *Target::GetFunctionCallerForLanguage(
2139 lldb::LanguageType language, const CompilerType &return_type,
2140 const Address &function_address, const ValueList &arg_value_list,
Zachary Turner97206d52017-05-12 04:51:55 +00002141 const char *name, Status &error) {
2142 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 TypeSystem *type_system =
2144 GetScratchTypeSystemForLanguage(&type_system_error, language);
2145 FunctionCaller *persistent_fn = nullptr;
2146
2147 if (!type_system) {
2148 error.SetErrorStringWithFormat(
2149 "Could not find type system for language %s: %s",
2150 Language::GetNameForLanguageType(language),
2151 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002152 return persistent_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002153 }
2154
2155 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2156 arg_value_list, name);
2157 if (!persistent_fn)
2158 error.SetErrorStringWithFormat(
2159 "Could not create an expression for language %s",
2160 Language::GetNameForLanguageType(language));
2161
2162 return persistent_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002163}
2164
2165UtilityFunction *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166Target::GetUtilityFunctionForLanguage(const char *text,
2167 lldb::LanguageType language,
Zachary Turner97206d52017-05-12 04:51:55 +00002168 const char *name, Status &error) {
2169 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002170 TypeSystem *type_system =
2171 GetScratchTypeSystemForLanguage(&type_system_error, language);
2172 UtilityFunction *utility_fn = nullptr;
2173
2174 if (!type_system) {
2175 error.SetErrorStringWithFormat(
2176 "Could not find type system for language %s: %s",
2177 Language::GetNameForLanguageType(language),
2178 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002179 return utility_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 }
2181
2182 utility_fn = type_system->GetUtilityFunction(text, name);
2183 if (!utility_fn)
2184 error.SetErrorStringWithFormat(
2185 "Could not create an expression for language %s",
2186 Language::GetNameForLanguageType(language));
2187
2188 return utility_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002189}
2190
Kate Stoneb9c1b512016-09-06 20:57:50 +00002191ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2192 if (m_valid) {
2193 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2194 nullptr, eLanguageTypeC, create_on_demand))
2195 return llvm::dyn_cast<ClangASTContext>(type_system);
2196 }
2197 return nullptr;
2198}
2199
2200ClangASTImporterSP Target::GetClangASTImporter() {
2201 if (m_valid) {
2202 if (!m_ast_importer_sp) {
2203 m_ast_importer_sp.reset(new ClangASTImporter());
Sean Callanan4bf80d52011-11-15 22:27:19 +00002204 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 return m_ast_importer_sp;
2206 }
2207 return ClangASTImporterSP();
Sean Callananb92bd752015-10-01 16:28:02 +00002208}
2209
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2211
2212void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2213
2214FileSpecList Target::GetDefaultExecutableSearchPaths() {
2215 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2216 if (properties_sp)
2217 return properties_sp->GetExecutableSearchPaths();
2218 return FileSpecList();
Sean Callanan686b2312011-11-16 18:20:47 +00002219}
2220
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2222 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2223 if (properties_sp)
2224 return properties_sp->GetDebugFileSearchPaths();
2225 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002226}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002227
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2229 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2230 if (properties_sp)
2231 return properties_sp->GetClangModuleSearchPaths();
2232 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002233}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002234
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235ArchSpec Target::GetDefaultArchitecture() {
2236 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2237 if (properties_sp)
2238 return properties_sp->GetDefaultArchitecture();
2239 return ArchSpec();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002240}
2241
Kate Stoneb9c1b512016-09-06 20:57:50 +00002242void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2243 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2244 if (properties_sp) {
2245 LogIfAnyCategoriesSet(
2246 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2247 "default architecture to %s (%s)",
2248 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2249 return properties_sp->SetDefaultArchitecture(arch);
2250 }
Michael Sartaina7499c92013-07-01 19:45:50 +00002251}
2252
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2254 const SymbolContext *sc_ptr) {
2255 // The target can either exist in the "process" of ExecutionContext, or in
2256 // the "target_sp" member of SymbolContext. This accessor helper function
2257 // will get the target from one of these locations.
2258
2259 Target *target = nullptr;
2260 if (sc_ptr != nullptr)
2261 target = sc_ptr->target_sp.get();
2262 if (target == nullptr && exe_ctx_ptr)
2263 target = exe_ctx_ptr->GetTargetPtr();
2264 return target;
Sean Callanan85054342015-04-03 15:39:47 +00002265}
2266
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267ExpressionResults Target::EvaluateExpression(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002268 llvm::StringRef expr, ExecutionContextScope *exe_scope,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002269 lldb::ValueObjectSP &result_valobj_sp,
2270 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2271 result_valobj_sp.reset();
Caroline Ticedaccaa92010-09-20 20:44:43 +00002272
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 ExpressionResults execution_results = eExpressionSetupError;
Caroline Ticedaccaa92010-09-20 20:44:43 +00002274
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002275 if (expr.empty())
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002276 return execution_results;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277
Adrian Prantl05097242018-04-30 16:49:04 +00002278 // We shouldn't run stop hooks in expressions. Be sure to reset this if you
2279 // return anywhere within this function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280 bool old_suppress_value = m_suppress_stop_hooks;
2281 m_suppress_stop_hooks = true;
2282
2283 ExecutionContext exe_ctx;
2284
2285 if (exe_scope) {
2286 exe_scope->CalculateExecutionContext(exe_ctx);
2287 } else if (m_process_sp) {
2288 m_process_sp->CalculateExecutionContext(exe_ctx);
2289 } else {
2290 CalculateExecutionContext(exe_ctx);
2291 }
2292
Adrian Prantl05097242018-04-30 16:49:04 +00002293 // Make sure we aren't just trying to see the value of a persistent variable
2294 // (something like "$0")
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295 lldb::ExpressionVariableSP persistent_var_sp;
2296 // Only check for persistent variables the expression starts with a '$'
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002297 if (expr[0] == '$')
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2299 ->GetPersistentExpressionState()
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002300 ->GetVariable(expr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301
2302 if (persistent_var_sp) {
2303 result_valobj_sp = persistent_var_sp->GetValueObject();
2304 execution_results = eExpressionCompleted;
2305 } else {
Pavel Labath50251fc2017-12-21 10:54:30 +00002306 llvm::StringRef prefix = GetExpressionPrefixContents();
Zachary Turner97206d52017-05-12 04:51:55 +00002307 Status error;
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002308 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2309 result_valobj_sp, error,
2310 0, // Line Number
2311 fixed_expression);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312 }
2313
2314 m_suppress_stop_hooks = old_suppress_value;
2315
2316 return execution_results;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002317}
2318
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002319lldb::ExpressionVariableSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320Target::GetPersistentVariable(const ConstString &name) {
2321 lldb::ExpressionVariableSP variable_sp;
2322 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002323 [name, &variable_sp](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 if (PersistentExpressionState *persistent_state =
2325 type_system->GetPersistentExpressionState()) {
2326 variable_sp = persistent_state->GetVariable(name);
Greg Clayton5beec212015-10-08 21:04:34 +00002327
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 if (variable_sp)
2329 return false; // Stop iterating the ForEach
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002330 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002331 return true; // Keep iterating the ForEach
2332 });
2333 return variable_sp;
Zachary Turner32abc6e2015-03-03 19:23:09 +00002334}
2335
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2337 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2338
2339 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002340 [name, &address](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 if (PersistentExpressionState *persistent_state =
2342 type_system->GetPersistentExpressionState()) {
2343 address = persistent_state->LookupSymbol(name);
2344 if (address != LLDB_INVALID_ADDRESS)
2345 return false; // Stop iterating the ForEach
Sean Callananb92bd752015-10-01 16:28:02 +00002346 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002347 return true; // Keep iterating the ForEach
2348 });
2349 return address;
Sean Callananb92bd752015-10-01 16:28:02 +00002350}
2351
Kate Stoneb9c1b512016-09-06 20:57:50 +00002352lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2353 AddressClass addr_class) const {
2354 addr_t code_addr = load_addr;
Pavel Labath13e37d42017-10-25 21:05:31 +00002355 switch (m_arch.GetSpec().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002356 case llvm::Triple::mips:
2357 case llvm::Triple::mipsel:
2358 case llvm::Triple::mips64:
2359 case llvm::Triple::mips64el:
2360 switch (addr_class) {
2361 case eAddressClassData:
2362 case eAddressClassDebug:
2363 return LLDB_INVALID_ADDRESS;
Jaydeep Patil44d07fc2015-09-22 06:36:56 +00002364
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365 case eAddressClassUnknown:
2366 case eAddressClassInvalid:
2367 case eAddressClassCode:
2368 case eAddressClassCodeAlternateISA:
2369 case eAddressClassRuntime:
2370 if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2371 code_addr |= 1ull;
2372 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002373 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002374 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002375
Kate Stoneb9c1b512016-09-06 20:57:50 +00002376 case llvm::Triple::arm:
2377 case llvm::Triple::thumb:
2378 switch (addr_class) {
2379 case eAddressClassData:
2380 case eAddressClassDebug:
2381 return LLDB_INVALID_ADDRESS;
2382
2383 case eAddressClassUnknown:
2384 case eAddressClassInvalid:
2385 case eAddressClassCode:
2386 case eAddressClassCodeAlternateISA:
2387 case eAddressClassRuntime:
2388 // Check if bit zero it no set?
2389 if ((code_addr & 1ull) == 0) {
2390 // Bit zero isn't set, check if the address is a multiple of 2?
2391 if (code_addr & 2ull) {
2392 // The address is a multiple of 2 so it must be thumb, set bit zero
2393 code_addr |= 1ull;
2394 } else if (addr_class == eAddressClassCodeAlternateISA) {
2395 // We checked the address and the address claims to be the alternate
Adrian Prantl05097242018-04-30 16:49:04 +00002396 // ISA which means thumb, so set bit zero.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397 code_addr |= 1ull;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002398 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399 }
2400 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002401 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 break;
2403
2404 default:
2405 break;
2406 }
2407 return code_addr;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002408}
2409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2411 AddressClass addr_class) const {
2412 addr_t opcode_addr = load_addr;
Pavel Labath13e37d42017-10-25 21:05:31 +00002413 switch (m_arch.GetSpec().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002414 case llvm::Triple::mips:
2415 case llvm::Triple::mipsel:
2416 case llvm::Triple::mips64:
2417 case llvm::Triple::mips64el:
2418 case llvm::Triple::arm:
2419 case llvm::Triple::thumb:
2420 switch (addr_class) {
2421 case eAddressClassData:
2422 case eAddressClassDebug:
2423 return LLDB_INVALID_ADDRESS;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002424
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 case eAddressClassInvalid:
2426 case eAddressClassUnknown:
2427 case eAddressClassCode:
2428 case eAddressClassCodeAlternateISA:
2429 case eAddressClassRuntime:
2430 opcode_addr &= ~(1ull);
2431 break;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002432 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002433 break;
2434
2435 default:
2436 break;
2437 }
2438 return opcode_addr;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002439}
2440
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2442 addr_t breakable_addr = addr;
2443 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Greg Clayton9585fbf2013-03-19 00:20:55 +00002444
Pavel Labath13e37d42017-10-25 21:05:31 +00002445 switch (m_arch.GetSpec().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002446 default:
2447 break;
2448 case llvm::Triple::mips:
2449 case llvm::Triple::mipsel:
2450 case llvm::Triple::mips64:
2451 case llvm::Triple::mips64el: {
2452 addr_t function_start = 0;
2453 addr_t current_offset = 0;
2454 uint32_t loop_count = 0;
2455 Address resolved_addr;
Pavel Labath13e37d42017-10-25 21:05:31 +00002456 uint32_t arch_flags = m_arch.GetSpec().GetFlags();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002457 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2458 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2459 SectionLoadList &section_load_list = GetSectionLoadList();
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002460
Kate Stoneb9c1b512016-09-06 20:57:50 +00002461 if (section_load_list.IsEmpty())
Adrian Prantl05097242018-04-30 16:49:04 +00002462 // No sections are loaded, so we must assume we are not running yet and
2463 // need to operate only on file address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 m_images.ResolveFileAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002465 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002466 section_load_list.ResolveLoadAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002467
Kate Stoneb9c1b512016-09-06 20:57:50 +00002468 // Get the function boundaries to make sure we don't scan back before the
2469 // beginning of the current function.
2470 ModuleSP temp_addr_module_sp(resolved_addr.GetModule());
2471 if (temp_addr_module_sp) {
2472 SymbolContext sc;
2473 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2474 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr,
2475 resolve_scope, sc);
2476 Address sym_addr;
2477 if (sc.function)
2478 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2479 else if (sc.symbol)
2480 sym_addr = sc.symbol->GetAddress();
2481
2482 function_start = sym_addr.GetLoadAddress(this);
2483 if (function_start == LLDB_INVALID_ADDRESS)
2484 function_start = sym_addr.GetFileAddress();
2485
2486 if (function_start)
2487 current_offset = addr - function_start;
2488 }
2489
2490 // If breakpoint address is start of function then we dont have to do
2491 // anything.
2492 if (current_offset == 0)
2493 return breakable_addr;
Greg Claytond5944cd2013-12-06 01:12:00 +00002494 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002495 loop_count = current_offset / 2;
Greg Claytond5944cd2013-12-06 01:12:00 +00002496
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497 if (loop_count > 3) {
2498 // Scan previous 6 bytes
2499 if (IsMips16 | IsMicromips)
2500 loop_count = 3;
2501 // For mips-only, instructions are always 4 bytes, so scan previous 4
2502 // bytes only.
2503 else
2504 loop_count = 2;
Greg Clayton6b32f1e2013-12-18 02:06:45 +00002505 }
2506
Kate Stoneb9c1b512016-09-06 20:57:50 +00002507 // Create Disassembler Instance
2508 lldb::DisassemblerSP disasm_sp(
Pavel Labath13e37d42017-10-25 21:05:31 +00002509 Disassembler::FindPlugin(m_arch.GetSpec(), nullptr, nullptr));
Todd Fiala75f47c32014-10-11 21:42:09 +00002510
Kate Stoneb9c1b512016-09-06 20:57:50 +00002511 ExecutionContext exe_ctx;
2512 CalculateExecutionContext(exe_ctx);
2513 InstructionList instruction_list;
2514 InstructionSP prev_insn;
2515 bool prefer_file_cache = true; // Read from file
2516 uint32_t inst_to_choose = 0;
2517
2518 for (uint32_t i = 1; i <= loop_count; i++) {
2519 // Adjust the address to read from.
2520 resolved_addr.Slide(-2);
2521 AddressRange range(resolved_addr, i * 2);
2522 uint32_t insn_size = 0;
2523
2524 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2525
2526 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2527 if (num_insns) {
2528 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2529 insn_size = prev_insn->GetOpcode().GetByteSize();
2530 if (i == 1 && insn_size == 2) {
2531 // This looks like a valid 2-byte instruction (but it could be a part
2532 // of upper 4 byte instruction).
2533 instruction_list.Append(prev_insn);
2534 inst_to_choose = 1;
2535 } else if (i == 2) {
2536 // Here we may get one 4-byte instruction or two 2-byte instructions.
2537 if (num_insns == 2) {
Adrian Prantl05097242018-04-30 16:49:04 +00002538 // Looks like there are two 2-byte instructions above our
2539 // breakpoint target address. Now the upper 2-byte instruction is
2540 // either a valid 2-byte instruction or could be a part of it's
2541 // upper 4-byte instruction. In both cases we don't care because in
2542 // this case lower 2-byte instruction is definitely a valid
2543 // instruction and whatever i=1 iteration has found out is true.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 inst_to_choose = 1;
2545 break;
2546 } else if (insn_size == 4) {
2547 // This instruction claims its a valid 4-byte instruction. But it
Adrian Prantl05097242018-04-30 16:49:04 +00002548 // could be a part of it's upper 4-byte instruction. Lets try
2549 // scanning upper 2 bytes to verify this.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002550 instruction_list.Append(prev_insn);
2551 inst_to_choose = 2;
2552 }
2553 } else if (i == 3) {
2554 if (insn_size == 4)
2555 // FIXME: We reached here that means instruction at [target - 4] has
Adrian Prantl05097242018-04-30 16:49:04 +00002556 // already claimed to be a 4-byte instruction, and now instruction
2557 // at [target - 6] is also claiming that it's a 4-byte instruction.
2558 // This can not be true. In this case we can not decide the valid
2559 // previous instruction so we let lldb set the breakpoint at the
2560 // address given by user.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002561 inst_to_choose = 0;
2562 else
2563 // This is straight-forward
2564 inst_to_choose = 2;
2565 break;
Greg Claytonb09c5382013-12-13 17:20:18 +00002566 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002567 } else {
2568 // Decode failed, bytes do not form a valid instruction. So whatever
2569 // previous iteration has found out is true.
2570 if (i > 1) {
2571 inst_to_choose = i - 1;
2572 break;
2573 }
2574 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002575 }
Todd Fiala015d8182014-07-22 23:41:36 +00002576
Kate Stoneb9c1b512016-09-06 20:57:50 +00002577 // Check if we are able to find any valid instruction.
2578 if (inst_to_choose) {
2579 if (inst_to_choose > instruction_list.GetSize())
2580 inst_to_choose--;
2581 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2582
2583 if (prev_insn->HasDelaySlot()) {
2584 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2585 // Adjust the breakable address
2586 breakable_addr = addr - shift_size;
Todd Fialaac33cc92014-10-09 01:02:08 +00002587 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588 log->Printf("Target::%s Breakpoint at 0x%8.8" PRIx64
2589 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n",
2590 __FUNCTION__, addr, breakable_addr);
2591 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002592 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002593 break;
2594 }
2595 }
2596 return breakable_addr;
2597}
2598
2599SourceManager &Target::GetSourceManager() {
2600 if (!m_source_manager_ap)
2601 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2602 return *m_source_manager_ap;
2603}
2604
2605ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2606 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2607 // we can make it
2608 // per-target
2609
2610 {
2611 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2612
2613 if (!m_clang_modules_decl_vendor_ap) {
2614 m_clang_modules_decl_vendor_ap.reset(
2615 ClangModulesDeclVendor::Create(*this));
2616 }
2617 }
2618
2619 return m_clang_modules_decl_vendor_ap.get();
2620}
2621
2622Target::StopHookSP Target::CreateStopHook() {
2623 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2624 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2625 m_stop_hooks[new_uid] = stop_hook_sp;
2626 return stop_hook_sp;
2627}
2628
2629bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2630 size_t num_removed = m_stop_hooks.erase(user_id);
2631 return (num_removed != 0);
2632}
2633
2634void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2635
2636Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2637 StopHookSP found_hook;
2638
2639 StopHookCollection::iterator specified_hook_iter;
2640 specified_hook_iter = m_stop_hooks.find(user_id);
2641 if (specified_hook_iter != m_stop_hooks.end())
2642 found_hook = (*specified_hook_iter).second;
2643 return found_hook;
2644}
2645
2646bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2647 bool active_state) {
2648 StopHookCollection::iterator specified_hook_iter;
2649 specified_hook_iter = m_stop_hooks.find(user_id);
2650 if (specified_hook_iter == m_stop_hooks.end())
2651 return false;
2652
2653 (*specified_hook_iter).second->SetIsActive(active_state);
2654 return true;
2655}
2656
2657void Target::SetAllStopHooksActiveState(bool active_state) {
2658 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2659 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2660 (*pos).second->SetIsActive(active_state);
2661 }
2662}
2663
2664void Target::RunStopHooks() {
2665 if (m_suppress_stop_hooks)
2666 return;
2667
2668 if (!m_process_sp)
2669 return;
Jim Ingham45816d62017-12-05 02:34:05 +00002670
2671 // Somebody might have restarted the process:
2672 if (m_process_sp->GetState() != eStateStopped)
2673 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002674
2675 // <rdar://problem/12027563> make sure we check that we are not stopped
Adrian Prantl05097242018-04-30 16:49:04 +00002676 // because of us running a user expression since in that case we do not want
2677 // to run the stop-hooks
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2679 return;
2680
2681 if (m_stop_hooks.empty())
2682 return;
2683
2684 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2685
2686 // If there aren't any active stop hooks, don't bother either:
2687 bool any_active_hooks = false;
2688 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2689 if ((*pos).second->IsActive()) {
2690 any_active_hooks = true;
2691 break;
2692 }
2693 }
2694 if (!any_active_hooks)
2695 return;
2696
2697 CommandReturnObject result;
2698
2699 std::vector<ExecutionContext> exc_ctx_with_reasons;
2700 std::vector<SymbolContext> sym_ctx_with_reasons;
2701
2702 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2703 size_t num_threads = cur_threadlist.GetSize();
2704 for (size_t i = 0; i < num_threads; i++) {
2705 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2706 if (cur_thread_sp->ThreadStoppedForAReason()) {
2707 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2708 exc_ctx_with_reasons.push_back(ExecutionContext(
2709 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2710 sym_ctx_with_reasons.push_back(
2711 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2712 }
2713 }
2714
2715 // If no threads stopped for a reason, don't run the stop-hooks.
2716 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2717 if (num_exe_ctx == 0)
2718 return;
2719
2720 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2721 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2722
2723 bool keep_going = true;
2724 bool hooks_ran = false;
2725 bool print_hook_header = (m_stop_hooks.size() != 1);
2726 bool print_thread_header = (num_exe_ctx != 1);
2727
2728 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2729 // result.Clear();
2730 StopHookSP cur_hook_sp = (*pos).second;
2731 if (!cur_hook_sp->IsActive())
2732 continue;
2733
2734 bool any_thread_matched = false;
2735 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2736 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2737 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2738 sym_ctx_with_reasons[i])) &&
2739 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2740 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2741 exc_ctx_with_reasons[i].GetThreadRef()))) {
2742 if (!hooks_ran) {
2743 hooks_ran = true;
2744 }
2745 if (print_hook_header && !any_thread_matched) {
2746 const char *cmd =
2747 (cur_hook_sp->GetCommands().GetSize() == 1
2748 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2749 : nullptr);
2750 if (cmd)
2751 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2752 cur_hook_sp->GetID(), cmd);
2753 else
2754 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2755 cur_hook_sp->GetID());
2756 any_thread_matched = true;
2757 }
2758
2759 if (print_thread_header)
2760 result.AppendMessageWithFormat(
2761 "-- Thread %d\n",
2762 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2763
2764 CommandInterpreterRunOptions options;
2765 options.SetStopOnContinue(true);
2766 options.SetStopOnError(true);
2767 options.SetEchoCommands(false);
2768 options.SetPrintResults(true);
2769 options.SetAddToHistory(false);
2770
2771 GetDebugger().GetCommandInterpreter().HandleCommands(
2772 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2773 result);
2774
2775 // If the command started the target going again, we should bag out of
2776 // running the stop hooks.
2777 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2778 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
Jim Ingham45816d62017-12-05 02:34:05 +00002779 // But only complain if there were more stop hooks to do:
2780 StopHookCollection::iterator tmp = pos;
2781 if (++tmp != end)
2782 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2783 " set the program running.\n",
2784 cur_hook_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 keep_going = false;
2786 }
2787 }
2788 }
2789 }
2790
2791 result.GetImmediateOutputStream()->Flush();
2792 result.GetImmediateErrorStream()->Flush();
2793}
2794
2795const TargetPropertiesSP &Target::GetGlobalProperties() {
2796 // NOTE: intentional leak so we don't crash if global destructor chain gets
2797 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +00002798 static TargetPropertiesSP *g_settings_sp_ptr =
2799 new TargetPropertiesSP(new TargetProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 return *g_settings_sp_ptr;
2801}
2802
Zachary Turner97206d52017-05-12 04:51:55 +00002803Status Target::Install(ProcessLaunchInfo *launch_info) {
2804 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 PlatformSP platform_sp(GetPlatform());
2806 if (platform_sp) {
2807 if (platform_sp->IsRemote()) {
2808 if (platform_sp->IsConnected()) {
2809 // Install all files that have an install path, and always install the
2810 // main executable when connected to a remote platform
2811 const ModuleList &modules = GetImages();
2812 const size_t num_images = modules.GetSize();
2813 for (size_t idx = 0; idx < num_images; ++idx) {
2814 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2815 if (module_sp) {
2816 const bool is_main_executable = module_sp == GetExecutableModule();
2817 FileSpec local_file(module_sp->GetFileSpec());
2818 if (local_file) {
2819 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2820 if (!remote_file) {
2821 if (is_main_executable) // TODO: add setting for always
2822 // installing main executable???
2823 {
2824 // Always install the main executable
2825 remote_file = platform_sp->GetRemoteWorkingDirectory();
2826 remote_file.AppendPathComponent(
2827 module_sp->GetFileSpec().GetFilename().GetCString());
2828 }
2829 }
2830 if (remote_file) {
2831 error = platform_sp->Install(local_file, remote_file);
2832 if (error.Success()) {
2833 module_sp->SetPlatformFileSpec(remote_file);
2834 if (is_main_executable) {
2835 platform_sp->SetFilePermissions(remote_file, 0700);
2836 if (launch_info)
2837 launch_info->SetExecutableFile(remote_file, false);
2838 }
2839 } else
2840 break;
2841 }
2842 }
2843 }
2844 }
2845 }
2846 }
2847 }
2848 return error;
2849}
2850
2851bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2852 uint32_t stop_id) {
2853 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2854}
2855
2856bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2857 Address &resolved_addr) {
2858 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2859}
2860
2861bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2862 addr_t new_section_load_addr,
2863 bool warn_multiple) {
2864 const addr_t old_section_load_addr =
2865 m_section_load_history.GetSectionLoadAddress(
2866 SectionLoadHistory::eStopIDNow, section_sp);
2867 if (old_section_load_addr != new_section_load_addr) {
2868 uint32_t stop_id = 0;
2869 ProcessSP process_sp(GetProcessSP());
2870 if (process_sp)
2871 stop_id = process_sp->GetStopID();
Greg Claytonb09c5382013-12-13 17:20:18 +00002872 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002873 stop_id = m_section_load_history.GetLastStopID();
2874 if (m_section_load_history.SetSectionLoadAddress(
2875 stop_id, section_sp, new_section_load_addr, warn_multiple))
2876 return true; // Return true if the section load address was changed...
2877 }
2878 return false; // Return false to indicate nothing changed
2879}
Todd Fialaac33cc92014-10-09 01:02:08 +00002880
Kate Stoneb9c1b512016-09-06 20:57:50 +00002881size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2882 size_t section_unload_count = 0;
2883 size_t num_modules = module_list.GetSize();
2884 for (size_t i = 0; i < num_modules; ++i) {
2885 section_unload_count +=
2886 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2887 }
2888 return section_unload_count;
2889}
Todd Fiala015d8182014-07-22 23:41:36 +00002890
Kate Stoneb9c1b512016-09-06 20:57:50 +00002891size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2892 uint32_t stop_id = 0;
2893 ProcessSP process_sp(GetProcessSP());
2894 if (process_sp)
2895 stop_id = process_sp->GetStopID();
2896 else
2897 stop_id = m_section_load_history.GetLastStopID();
2898 SectionList *sections = module_sp->GetSectionList();
2899 size_t section_unload_count = 0;
2900 if (sections) {
2901 const uint32_t num_sections = sections->GetNumSections(0);
2902 for (uint32_t i = 0; i < num_sections; ++i) {
2903 section_unload_count += m_section_load_history.SetSectionUnloaded(
2904 stop_id, sections->GetSectionAtIndex(i));
Greg Claytonb09c5382013-12-13 17:20:18 +00002905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002906 }
2907 return section_unload_count;
2908}
2909
2910bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2911 uint32_t stop_id = 0;
2912 ProcessSP process_sp(GetProcessSP());
2913 if (process_sp)
2914 stop_id = process_sp->GetStopID();
2915 else
2916 stop_id = m_section_load_history.GetLastStopID();
2917 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2918}
2919
2920bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2921 addr_t load_addr) {
2922 uint32_t stop_id = 0;
2923 ProcessSP process_sp(GetProcessSP());
2924 if (process_sp)
2925 stop_id = process_sp->GetStopID();
2926 else
2927 stop_id = m_section_load_history.GetLastStopID();
2928 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2929 load_addr);
2930}
2931
2932void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2933
Zachary Turner97206d52017-05-12 04:51:55 +00002934Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2935 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2937
2938 if (log)
2939 log->Printf("Target::%s() called for %s", __FUNCTION__,
2940 launch_info.GetExecutableFile().GetPath().c_str());
2941
2942 StateType state = eStateInvalid;
2943
2944 // Scope to temporarily get the process state in case someone has manually
2945 // remotely connected already to a process and we can skip the platform
2946 // launching.
2947 {
2948 ProcessSP process_sp(GetProcessSP());
2949
2950 if (process_sp) {
2951 state = process_sp->GetState();
2952 if (log)
2953 log->Printf(
2954 "Target::%s the process exists, and its current state is %s",
2955 __FUNCTION__, StateAsCString(state));
2956 } else {
2957 if (log)
2958 log->Printf("Target::%s the process instance doesn't currently exist.",
2959 __FUNCTION__);
2960 }
2961 }
2962
2963 launch_info.GetFlags().Set(eLaunchFlagDebug);
2964
2965 // Get the value of synchronous execution here. If you wait till after you
Adrian Prantl05097242018-04-30 16:49:04 +00002966 // have started to run, then you could have hit a breakpoint, whose command
2967 // might switch the value, and then you'll pick up that incorrect value.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002968 Debugger &debugger = GetDebugger();
2969 const bool synchronous_execution =
2970 debugger.GetCommandInterpreter().GetSynchronous();
2971
2972 PlatformSP platform_sp(GetPlatform());
2973
Adrian Prantl05097242018-04-30 16:49:04 +00002974 // Finalize the file actions, and if none were given, default to opening up a
2975 // pseudo terminal
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2977 if (log)
2978 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2979 "default_to_use_pty=%s",
2980 __FUNCTION__, platform_sp ? "true" : "false",
2981 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2982 : "n/a",
2983 default_to_use_pty ? "true" : "false");
2984
2985 launch_info.FinalizeFileActions(this, default_to_use_pty);
2986
2987 if (state == eStateConnected) {
2988 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2989 error.SetErrorString(
2990 "can't launch in tty when launching through a remote connection");
2991 return error;
2992 }
2993 }
2994
2995 if (!launch_info.GetArchitecture().IsValid())
2996 launch_info.GetArchitecture() = GetArchitecture();
2997
2998 // If we're not already connected to the process, and if we have a platform
2999 // that can launch a process for debugging, go ahead and do that here.
3000 if (state != eStateConnected && platform_sp &&
3001 platform_sp->CanDebugProcess()) {
3002 if (log)
3003 log->Printf("Target::%s asking the platform to debug the process",
3004 __FUNCTION__);
3005
3006 // Get a weak pointer to the previous process if we have one
3007 ProcessWP process_wp;
3008 if (m_process_sp)
3009 process_wp = m_process_sp;
3010 m_process_sp =
3011 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
3012
3013 // Cleanup the old process since someone might still have a strong
Adrian Prantl05097242018-04-30 16:49:04 +00003014 // reference to this process and we would like to allow it to cleanup as
3015 // much as it can without the object being destroyed. We try to lock the
3016 // shared pointer and if that works, then someone else still has a strong
3017 // reference to the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003018
3019 ProcessSP old_process_sp(process_wp.lock());
3020 if (old_process_sp)
3021 old_process_sp->Finalize();
3022 } else {
3023 if (log)
3024 log->Printf("Target::%s the platform doesn't know how to debug a "
3025 "process, getting a process plugin to do this for us.",
3026 __FUNCTION__);
3027
3028 if (state == eStateConnected) {
3029 assert(m_process_sp);
3030 } else {
3031 // Use a Process plugin to construct the process.
3032 const char *plugin_name = launch_info.GetProcessPluginName();
3033 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
3034 nullptr);
Greg Claytonb09c5382013-12-13 17:20:18 +00003035 }
3036
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 // Since we didn't have a platform launch the process, launch it here.
3038 if (m_process_sp)
3039 error = m_process_sp->Launch(launch_info);
3040 }
3041
3042 if (!m_process_sp) {
Greg Claytonb09c5382013-12-13 17:20:18 +00003043 if (error.Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00003044 error.SetErrorString("failed to launch or debug process");
Greg Claytonb09c5382013-12-13 17:20:18 +00003045 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 }
3047
3048 if (error.Success()) {
3049 if (synchronous_execution ||
3050 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3051 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
3052 if (!hijack_listener_sp) {
3053 hijack_listener_sp =
3054 Listener::MakeListener("lldb.Target.Launch.hijack");
3055 launch_info.SetHijackListener(hijack_listener_sp);
3056 m_process_sp->HijackProcessEvents(hijack_listener_sp);
3057 }
3058
3059 StateType state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003060 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061
3062 if (state == eStateStopped) {
3063 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3064 if (synchronous_execution) {
3065 error = m_process_sp->PrivateResume();
3066 if (error.Success()) {
3067 state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003068 llvm::None, nullptr, true, hijack_listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003069 const bool must_be_alive =
3070 false; // eStateExited is ok, so this must be false
3071 if (!StateIsStoppedState(state, must_be_alive)) {
3072 error.SetErrorStringWithFormat("process isn't stopped: %s",
3073 StateAsCString(state));
3074 }
3075 }
3076 } else {
3077 m_process_sp->RestoreProcessEvents();
3078 error = m_process_sp->PrivateResume();
3079 }
3080 if (!error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003081 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082 error2.SetErrorStringWithFormat(
3083 "process resume at entry point failed: %s", error.AsCString());
3084 error = error2;
3085 }
3086 }
3087 } else if (state == eStateExited) {
3088 bool with_shell = !!launch_info.GetShell();
3089 const int exit_status = m_process_sp->GetExitStatus();
3090 const char *exit_desc = m_process_sp->GetExitDescription();
3091#define LAUNCH_SHELL_MESSAGE \
3092 "\n'r' and 'run' are aliases that default to launching through a " \
3093 "shell.\nTry launching without going through a shell by using 'process " \
3094 "launch'."
3095 if (exit_desc && exit_desc[0]) {
3096 if (with_shell)
3097 error.SetErrorStringWithFormat(
3098 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
3099 exit_status, exit_desc);
3100 else
3101 error.SetErrorStringWithFormat("process exited with status %i (%s)",
3102 exit_status, exit_desc);
3103 } else {
3104 if (with_shell)
3105 error.SetErrorStringWithFormat(
3106 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
3107 exit_status);
3108 else
3109 error.SetErrorStringWithFormat("process exited with status %i",
3110 exit_status);
3111 }
3112 } else {
3113 error.SetErrorStringWithFormat(
3114 "initial process state wasn't stopped: %s", StateAsCString(state));
3115 }
3116 }
3117 m_process_sp->RestoreProcessEvents();
3118 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00003119 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 error2.SetErrorStringWithFormat("process launch failed: %s",
3121 error.AsCString());
3122 error = error2;
3123 }
3124 return error;
Greg Claytonb09c5382013-12-13 17:20:18 +00003125}
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003126
Zachary Turner97206d52017-05-12 04:51:55 +00003127Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003128 auto state = eStateInvalid;
3129 auto process_sp = GetProcessSP();
3130 if (process_sp) {
3131 state = process_sp->GetState();
3132 if (process_sp->IsAlive() && state != eStateConnected) {
3133 if (state == eStateAttaching)
Zachary Turner97206d52017-05-12 04:51:55 +00003134 return Status("process attach is in progress");
3135 return Status("a process is already being debugged");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003136 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003138
Kate Stoneb9c1b512016-09-06 20:57:50 +00003139 const ModuleSP old_exec_module_sp = GetExecutableModule();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003140
Adrian Prantl05097242018-04-30 16:49:04 +00003141 // If no process info was specified, then use the target executable name as
3142 // the process to attach to by default
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143 if (!attach_info.ProcessInfoSpecified()) {
3144 if (old_exec_module_sp)
3145 attach_info.GetExecutableFile().GetFilename() =
3146 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003147
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 if (!attach_info.ProcessInfoSpecified()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003149 return Status("no process specified, create a target with a file, or "
3150 "specify the --pid or --name");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003151 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003153
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 const auto platform_sp =
3155 GetDebugger().GetPlatformList().GetSelectedPlatform();
3156 ListenerSP hijack_listener_sp;
3157 const bool async = attach_info.GetAsync();
3158 if (!async) {
3159 hijack_listener_sp =
3160 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3161 attach_info.SetHijackListener(hijack_listener_sp);
3162 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003163
Zachary Turner97206d52017-05-12 04:51:55 +00003164 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003165 if (state != eStateConnected && platform_sp != nullptr &&
3166 platform_sp->CanDebugProcess()) {
3167 SetPlatform(platform_sp);
3168 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3169 } else {
3170 if (state != eStateConnected) {
3171 const char *plugin_name = attach_info.GetProcessPluginName();
3172 process_sp =
3173 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3174 plugin_name, nullptr);
3175 if (process_sp == nullptr) {
3176 error.SetErrorStringWithFormat(
3177 "failed to create process using plugin %s",
3178 (plugin_name) ? plugin_name : "null");
3179 return error;
3180 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003181 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003182 if (hijack_listener_sp)
3183 process_sp->HijackProcessEvents(hijack_listener_sp);
3184 error = process_sp->Attach(attach_info);
3185 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003186
Kate Stoneb9c1b512016-09-06 20:57:50 +00003187 if (error.Success() && process_sp) {
3188 if (async) {
3189 process_sp->RestoreProcessEvents();
3190 } else {
3191 state = process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003192 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003193 process_sp->RestoreProcessEvents();
3194
3195 if (state != eStateStopped) {
3196 const char *exit_desc = process_sp->GetExitDescription();
3197 if (exit_desc)
3198 error.SetErrorStringWithFormat("%s", exit_desc);
Greg Claytone75e5d82015-10-20 00:14:20 +00003199 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200 error.SetErrorString(
3201 "process did not stop (no such process or permission problem?)");
3202 process_sp->Destroy(false);
3203 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003204 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003205 }
3206 return error;
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003207}
3208
Jim Ingham9575d842011-03-11 03:53:59 +00003209//--------------------------------------------------------------
Greg Claytonfbb76342013-11-20 21:07:01 +00003210// Target::StopHook
Jim Ingham9575d842011-03-11 03:53:59 +00003211//--------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003212Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3213 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3214 m_thread_spec_ap(), m_active(true) {}
3215
3216Target::StopHook::StopHook(const StopHook &rhs)
3217 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3218 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3219 m_thread_spec_ap(), m_active(rhs.m_active) {
3220 if (rhs.m_thread_spec_ap)
3221 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
Jim Ingham9575d842011-03-11 03:53:59 +00003222}
3223
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003224Target::StopHook::~StopHook() = default;
Jim Ingham9575d842011-03-11 03:53:59 +00003225
Kate Stoneb9c1b512016-09-06 20:57:50 +00003226void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3227 m_specifier_sp.reset(specifier);
Zachary Turner32abc6e2015-03-03 19:23:09 +00003228}
3229
Kate Stoneb9c1b512016-09-06 20:57:50 +00003230void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3231 m_thread_spec_ap.reset(specifier);
Jim Ingham9575d842011-03-11 03:53:59 +00003232}
Jim Ingham9575d842011-03-11 03:53:59 +00003233
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234void Target::StopHook::GetDescription(Stream *s,
3235 lldb::DescriptionLevel level) const {
3236 int indent_level = s->GetIndentLevel();
Jim Ingham9575d842011-03-11 03:53:59 +00003237
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 s->SetIndentLevel(indent_level + 2);
3239
3240 s->Printf("Hook: %" PRIu64 "\n", GetID());
3241 if (m_active)
3242 s->Indent("State: enabled\n");
3243 else
3244 s->Indent("State: disabled\n");
3245
3246 if (m_specifier_sp) {
3247 s->Indent();
3248 s->PutCString("Specifier:\n");
3249 s->SetIndentLevel(indent_level + 4);
3250 m_specifier_sp->GetDescription(s, level);
Jim Ingham9575d842011-03-11 03:53:59 +00003251 s->SetIndentLevel(indent_level + 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003252 }
Jim Ingham9575d842011-03-11 03:53:59 +00003253
Kate Stoneb9c1b512016-09-06 20:57:50 +00003254 if (m_thread_spec_ap) {
3255 StreamString tmp;
3256 s->Indent("Thread:\n");
3257 m_thread_spec_ap->GetDescription(&tmp, level);
3258 s->SetIndentLevel(indent_level + 4);
Zachary Turnerc1564272016-11-16 21:15:24 +00003259 s->Indent(tmp.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003260 s->PutCString("\n");
3261 s->SetIndentLevel(indent_level + 2);
3262 }
Jim Ingham9575d842011-03-11 03:53:59 +00003263
Kate Stoneb9c1b512016-09-06 20:57:50 +00003264 s->Indent("Commands: \n");
3265 s->SetIndentLevel(indent_level + 4);
3266 uint32_t num_commands = m_commands.GetSize();
3267 for (uint32_t i = 0; i < num_commands; i++) {
3268 s->Indent(m_commands.GetStringAtIndex(i));
3269 s->PutCString("\n");
3270 }
3271 s->SetIndentLevel(indent_level);
Jim Ingham9575d842011-03-11 03:53:59 +00003272}
3273
Greg Clayton67cc0632012-08-22 17:17:09 +00003274//--------------------------------------------------------------
3275// class TargetProperties
3276//--------------------------------------------------------------
3277
Kate Stoneb9c1b512016-09-06 20:57:50 +00003278OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3279 {eNoDynamicValues, "no-dynamic-values",
3280 "Don't calculate the dynamic type of values"},
3281 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3282 "even if you have to run the target."},
3283 {eDynamicDontRunTarget, "no-run-target",
3284 "Calculate the dynamic type of values, but don't run the target."},
3285 {0, nullptr, nullptr}};
Caroline Ticedaccaa92010-09-20 20:44:43 +00003286
Kate Stoneb9c1b512016-09-06 20:57:50 +00003287static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3288 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3289 "locations (fastest). This setting "
3290 "should only be used if you know that "
3291 "no inlining occurs in your programs."},
3292 {eInlineBreakpointsHeaders, "headers",
3293 "Only check for inline breakpoint locations when setting breakpoints in "
3294 "header files, but not when setting breakpoint in implementation source "
3295 "files (default)."},
3296 {eInlineBreakpointsAlways, "always",
3297 "Always look for inline breakpoint locations when setting file and line "
3298 "breakpoints (slower but most accurate)."},
3299 {0, nullptr, nullptr}};
Greg Clayton1f746072012-08-29 21:13:06 +00003300
Kate Stoneb9c1b512016-09-06 20:57:50 +00003301typedef enum x86DisassemblyFlavor {
3302 eX86DisFlavorDefault,
3303 eX86DisFlavorIntel,
3304 eX86DisFlavorATT
Jim Ingham0f063ba2013-03-02 00:26:47 +00003305} x86DisassemblyFlavor;
3306
Kate Stoneb9c1b512016-09-06 20:57:50 +00003307static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3308 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3309 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3310 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3311 {0, nullptr, nullptr}};
3312
3313static OptionEnumValueElement g_hex_immediate_style_values[] = {
3314 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3315 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3316 {0, nullptr, nullptr}};
3317
3318static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3319 {eLoadScriptFromSymFileTrue, "true",
3320 "Load debug scripts inside symbol files"},
3321 {eLoadScriptFromSymFileFalse, "false",
3322 "Do not load debug scripts inside symbol files."},
3323 {eLoadScriptFromSymFileWarn, "warn",
3324 "Warn about debug scripts inside symbol files but do not load them."},
3325 {0, nullptr, nullptr}};
3326
3327static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3328 {eLoadCWDlldbinitTrue, "true",
3329 "Load .lldbinit files from current directory"},
3330 {eLoadCWDlldbinitFalse, "false",
3331 "Do not load .lldbinit files from current directory"},
3332 {eLoadCWDlldbinitWarn, "warn",
3333 "Warn about loading .lldbinit files from current directory"},
3334 {0, nullptr, nullptr}};
3335
3336static OptionEnumValueElement g_memory_module_load_level_values[] = {
3337 {eMemoryModuleLoadLevelMinimal, "minimal",
3338 "Load minimal information when loading modules from memory. Currently "
3339 "this setting loads sections only."},
3340 {eMemoryModuleLoadLevelPartial, "partial",
3341 "Load partial information when loading modules from memory. Currently "
3342 "this setting loads sections and function bounds."},
3343 {eMemoryModuleLoadLevelComplete, "complete",
3344 "Load complete information when loading modules from memory. Currently "
3345 "this setting loads sections and all symbols."},
3346 {0, nullptr, nullptr}};
3347
3348static PropertyDefinition g_properties[] = {
3349 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3350 "Default architecture to choose, when there's a choice."},
3351 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3352 nullptr, "Move breakpoints to nearest code."},
3353 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3354 nullptr, nullptr,
3355 "The language to use when interpreting expressions entered in commands."},
3356 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3357 "Path to a file containing expressions to be prepended to all "
3358 "expressions."},
3359 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3360 eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3361 "Should printed values be shown as their dynamic value."},
3362 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3363 nullptr, "Should synthetic values be used by default whenever available."},
3364 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3365 "Skip function prologues when setting breakpoints by name."},
3366 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3367 "Source path remappings are used to track the change of location between "
3368 "a source file when built, and "
3369 "where it exists on the current system. It consists of an array of "
3370 "duples, the first element of each duple is "
3371 "some part (starting at the root) of the path to the file when it was "
3372 "built, "
3373 "and the second is where the remainder of the original build hierarchy is "
3374 "rooted on the local system. "
3375 "Each element of the array is checked in order and the first one that "
3376 "results in a match wins."},
3377 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3378 nullptr, "Executable search paths to use when locating executable files "
3379 "whose paths don't match the local file system."},
3380 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3381 nullptr, nullptr,
3382 "List of directories to be searched when locating debug symbol files."},
3383 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3384 nullptr, nullptr,
3385 "List of directories to be searched when locating modules for Clang."},
3386 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3387 nullptr, nullptr,
3388 "Automatically load Clang modules referred to by the program."},
3389 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3390 nullptr, "Automatically apply fix-it hints to expressions."},
3391 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3392 nullptr, "Print the fixed expression text."},
Sean Callanan5deb06e2016-09-26 20:18:51 +00003393 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3394 nullptr, "Save intermediate object files generated by the LLVM JIT"},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003395 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3396 nullptr, "Maximum number of children to expand in any level of depth."},
3397 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3398 nullptr, nullptr,
3399 "Maximum number of characters to show when using %s in summary strings."},
3400 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3401 nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3402 "--force must be specified."},
3403 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3404 true, nullptr, nullptr, "Consult the platform module avoid list when "
3405 "setting non-module specific breakpoints."},
3406 {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3407 "The first argument passed to the program in the argument array which can "
3408 "be different from the executable itself."},
3409 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3410 "A list containing all the arguments to be passed to the executable when "
3411 "it is run. Note that this does NOT include the argv[0] which is in "
3412 "target.arg0."},
3413 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3414 nullptr, nullptr, "A list of all the environment variables to be passed "
3415 "to the executable's environment, and their values."},
3416 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3417 "Inherit the environment from the process that is running LLDB."},
3418 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3419 "The file/path to be used by the executable program for reading its "
3420 "standard input."},
3421 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3422 "The file/path to be used by the executable program for writing its "
3423 "standard output."},
3424 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3425 "The file/path to be used by the executable program for writing its "
3426 "standard error."},
3427 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3428 nullptr, "debugserver will detach (rather than killing) a process if it "
3429 "loses connection with lldb."},
Jim Ingham7fca8c02017-04-28 00:51:06 +00003430 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3431 "Enable loading of symbol tables before they are needed."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003432 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3433 "Disable Address Space Layout Randomization (ASLR)"},
3434 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3435 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3436 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3437 eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3438 "The strategy to use when settings breakpoints by file and line. "
3439 "Breakpoint locations can end up being inlined by the compiler, so that a "
3440 "compile unit 'a.c' might contain an inlined function from another source "
3441 "file. "
3442 "Usually this is limited to breakpoint locations from inlined functions "
3443 "from header or other include files, or more accurately "
3444 "non-implementation source files. "
3445 "Sometimes code might #include implementation files and cause inlined "
3446 "breakpoint locations in inlined implementation files. "
3447 "Always checking for inlined breakpoint locations can be expensive "
3448 "(memory and time), so if you have a project with many headers "
3449 "and find that setting breakpoints is slow, then you can change this "
3450 "setting to headers. "
3451 "This setting allows you to control exactly which strategy is used when "
3452 "setting "
3453 "file and line breakpoints."},
3454 // FIXME: This is the wrong way to do per-architecture settings, but we
3455 // don't have a general per architecture settings system in place yet.
3456 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3457 eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3458 "The default disassembly flavor to use for x86 or x86-64 targets."},
3459 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3460 nullptr, "Show immediates in disassembly as hexadecimal."},
3461 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3462 Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3463 "Which style to use for printing hexadecimal disassembly values."},
3464 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3465 nullptr, "Use a fast stepping algorithm based on running from branch to "
3466 "branch rather than instruction single-stepping."},
3467 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3468 eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3469 "Allow LLDB to load scripting resources embedded in symbol files when "
3470 "available."},
3471 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3472 nullptr, g_load_current_working_dir_lldbinit_values,
3473 "Allow LLDB to .lldbinit files from the current directory automatically."},
3474 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3475 eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3476 "Loading modules from memory can be slow as reading the symbol tables and "
3477 "other data can take a long time depending on your connection to the "
3478 "debug target. "
3479 "This setting helps users control how much information gets loaded when "
3480 "loading modules from memory."
3481 "'complete' is the default value for this setting which will load all "
3482 "sections and symbols by reading them from memory (slowest, most "
3483 "accurate). "
3484 "'partial' will load sections and attempt to find function bounds without "
3485 "downloading the symbol table (faster, still accurate, missing symbol "
3486 "names). "
3487 "'minimal' is the fastest setting and will load section data with no "
3488 "symbols, but should rarely be used as stack frames in these memory "
3489 "regions will be inaccurate and not provide any context (fastest). "},
3490 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3491 nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3492 "the host system supports executable specific crash log "
3493 "strings and this setting is set to true."},
3494 {"trap-handler-names", OptionValue::eTypeArray, true,
3495 OptionValue::eTypeString, nullptr, nullptr,
3496 "A list of trap handler function names, e.g. a common Unix user process "
3497 "one is _sigtramp."},
3498 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3499 nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3500 "support the operation of a language's runtime "
3501 "support."},
3502 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3503 "Disable lock-step debugging, instead control threads independently."},
3504 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3505
3506enum {
3507 ePropertyDefaultArch,
3508 ePropertyMoveToNearestCode,
3509 ePropertyLanguage,
3510 ePropertyExprPrefix,
3511 ePropertyPreferDynamic,
3512 ePropertyEnableSynthetic,
3513 ePropertySkipPrologue,
3514 ePropertySourceMap,
3515 ePropertyExecutableSearchPaths,
3516 ePropertyDebugFileSearchPaths,
3517 ePropertyClangModuleSearchPaths,
3518 ePropertyAutoImportClangModules,
3519 ePropertyAutoApplyFixIts,
3520 ePropertyNotifyAboutFixIts,
Sean Callanan5deb06e2016-09-26 20:18:51 +00003521 ePropertySaveObjects,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003522 ePropertyMaxChildrenCount,
3523 ePropertyMaxSummaryLength,
3524 ePropertyMaxMemReadSize,
3525 ePropertyBreakpointUseAvoidList,
3526 ePropertyArg0,
3527 ePropertyRunArgs,
3528 ePropertyEnvVars,
3529 ePropertyInheritEnv,
3530 ePropertyInputPath,
3531 ePropertyOutputPath,
3532 ePropertyErrorPath,
3533 ePropertyDetachOnError,
Jim Ingham7fca8c02017-04-28 00:51:06 +00003534 ePropertyPreloadSymbols,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003535 ePropertyDisableASLR,
3536 ePropertyDisableSTDIO,
3537 ePropertyInlineStrategy,
3538 ePropertyDisassemblyFlavor,
3539 ePropertyUseHexImmediates,
3540 ePropertyHexImmediateStyle,
3541 ePropertyUseFastStepping,
3542 ePropertyLoadScriptFromSymbolFile,
3543 ePropertyLoadCWDlldbinitFile,
3544 ePropertyMemoryModuleLoadLevel,
3545 ePropertyDisplayExpressionsInCrashlogs,
3546 ePropertyTrapHandlerNames,
3547 ePropertyDisplayRuntimeSupportValues,
3548 ePropertyNonStopModeEnabled,
3549 ePropertyExperimental
Jim Ingham0f063ba2013-03-02 00:26:47 +00003550};
3551
Kate Stoneb9c1b512016-09-06 20:57:50 +00003552class TargetOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +00003553public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003554 TargetOptionValueProperties(const ConstString &name)
3555 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
Caroline Ticedaccaa92010-09-20 20:44:43 +00003556
Kate Stoneb9c1b512016-09-06 20:57:50 +00003557 // This constructor is used when creating TargetOptionValueProperties when it
3558 // is part of a new lldb_private::Target instance. It will copy all current
3559 // global property values as needed
3560 TargetOptionValueProperties(Target *target,
3561 const TargetPropertiesSP &target_properties_sp)
3562 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3563 m_target(target), m_got_host_env(false) {}
Greg Clayton67cc0632012-08-22 17:17:09 +00003564
Kate Stoneb9c1b512016-09-06 20:57:50 +00003565 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3566 bool will_modify,
3567 uint32_t idx) const override {
3568 // When getting the value for a key from the target options, we will always
Adrian Prantl05097242018-04-30 16:49:04 +00003569 // try and grab the setting from the current target if there is one. Else
3570 // we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003571 if (idx == ePropertyEnvVars)
3572 GetHostEnvironmentIfNeeded();
3573
3574 if (exe_ctx) {
3575 Target *target = exe_ctx->GetTargetPtr();
3576 if (target) {
3577 TargetOptionValueProperties *target_properties =
3578 static_cast<TargetOptionValueProperties *>(
3579 target->GetValueProperties().get());
3580 if (this != target_properties)
3581 return target_properties->ProtectedGetPropertyAtIndex(idx);
3582 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003584 return ProtectedGetPropertyAtIndex(idx);
3585 }
3586
3587 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3588
Greg Clayton67cc0632012-08-22 17:17:09 +00003589protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003590 void GetHostEnvironmentIfNeeded() const {
3591 if (!m_got_host_env) {
3592 if (m_target) {
3593 m_got_host_env = true;
3594 const uint32_t idx = ePropertyInheritEnv;
3595 if (GetPropertyAtIndexAsBoolean(
3596 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3597 PlatformSP platform_sp(m_target->GetPlatform());
3598 if (platform_sp) {
Pavel Labath62930e52018-01-10 11:57:31 +00003599 Environment env = platform_sp->GetEnvironment();
3600 OptionValueDictionary *env_dict =
3601 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3602 ePropertyEnvVars);
3603 if (env_dict) {
3604 const bool can_replace = false;
3605 for (const auto &KV : env) {
3606 // Don't allow existing keys to be replaced with ones we get
3607 // from the platform environment
3608 env_dict->SetValueForKey(
3609 ConstString(KV.first()),
3610 OptionValueSP(new OptionValueString(KV.second.c_str())),
3611 can_replace);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003612 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003613 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003614 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003616 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003617 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003618 }
3619 Target *m_target;
3620 mutable bool m_got_host_env;
Greg Clayton67cc0632012-08-22 17:17:09 +00003621};
3622
Greg Claytonfbb76342013-11-20 21:07:01 +00003623//----------------------------------------------------------------------
3624// TargetProperties
3625//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003626static PropertyDefinition g_experimental_properties[]{
3627 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3628 nullptr,
3629 "If true, inject local variables explicitly into the expression text. "
3630 "This will fix symbol resolution when there are name collisions between "
3631 "ivars and local variables. "
3632 "But it can make expressions run much more slowly."},
Sean Callanan68e44232017-09-28 20:20:25 +00003633 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
3634 nullptr, "If true, use Clang's modern type lookup infrastructure."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003635 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Jim Inghambed67792016-07-07 18:25:48 +00003636
Sean Callanan68e44232017-09-28 20:20:25 +00003637enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
Jim Inghambed67792016-07-07 18:25:48 +00003638
Kate Stoneb9c1b512016-09-06 20:57:50 +00003639class TargetExperimentalOptionValueProperties : public OptionValueProperties {
Jim Inghambed67792016-07-07 18:25:48 +00003640public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003641 TargetExperimentalOptionValueProperties()
3642 : OptionValueProperties(
3643 ConstString(Properties::GetExperimentalSettingsName())) {}
Jim Inghambed67792016-07-07 18:25:48 +00003644};
3645
Kate Stoneb9c1b512016-09-06 20:57:50 +00003646TargetExperimentalProperties::TargetExperimentalProperties()
3647 : Properties(OptionValuePropertiesSP(
3648 new TargetExperimentalOptionValueProperties())) {
3649 m_collection_sp->Initialize(g_experimental_properties);
Jim Inghambed67792016-07-07 18:25:48 +00003650}
3651
3652//----------------------------------------------------------------------
3653// TargetProperties
3654//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003655TargetProperties::TargetProperties(Target *target)
3656 : Properties(), m_launch_info() {
3657 if (target) {
3658 m_collection_sp.reset(
3659 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
Ilia K8f37ca52015-02-13 14:31:06 +00003660
Adrian Prantl05097242018-04-30 16:49:04 +00003661 // Set callbacks to update launch_info whenever "settins set" updated any
3662 // of these properties
Kate Stoneb9c1b512016-09-06 20:57:50 +00003663 m_collection_sp->SetValueChangedCallback(
3664 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3665 m_collection_sp->SetValueChangedCallback(
3666 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3667 m_collection_sp->SetValueChangedCallback(
3668 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3669 m_collection_sp->SetValueChangedCallback(
3670 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3671 this);
3672 m_collection_sp->SetValueChangedCallback(
3673 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3674 this);
3675 m_collection_sp->SetValueChangedCallback(
3676 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3677 this);
3678 m_collection_sp->SetValueChangedCallback(
3679 ePropertyDetachOnError,
3680 TargetProperties::DetachOnErrorValueChangedCallback, this);
3681 m_collection_sp->SetValueChangedCallback(
3682 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3683 this);
3684 m_collection_sp->SetValueChangedCallback(
3685 ePropertyDisableSTDIO,
3686 TargetProperties::DisableSTDIOValueChangedCallback, this);
Jim Inghambed67792016-07-07 18:25:48 +00003687
Kate Stoneb9c1b512016-09-06 20:57:50 +00003688 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3689 m_collection_sp->AppendProperty(
3690 ConstString(Properties::GetExperimentalSettingsName()),
3691 ConstString("Experimental settings - setting these won't produce "
3692 "errors if the setting is not present."),
3693 true, m_experimental_properties_up->GetValueProperties());
Jim Inghambed67792016-07-07 18:25:48 +00003694
Kate Stoneb9c1b512016-09-06 20:57:50 +00003695 // Update m_launch_info once it was created
3696 Arg0ValueChangedCallback(this, nullptr);
3697 RunArgsValueChangedCallback(this, nullptr);
3698 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3699 // Target::GetPlatform()
3700 InputPathValueChangedCallback(this, nullptr);
3701 OutputPathValueChangedCallback(this, nullptr);
3702 ErrorPathValueChangedCallback(this, nullptr);
3703 DetachOnErrorValueChangedCallback(this, nullptr);
3704 DisableASLRValueChangedCallback(this, nullptr);
3705 DisableSTDIOValueChangedCallback(this, nullptr);
3706 } else {
3707 m_collection_sp.reset(
3708 new TargetOptionValueProperties(ConstString("target")));
3709 m_collection_sp->Initialize(g_properties);
3710 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3711 m_collection_sp->AppendProperty(
3712 ConstString(Properties::GetExperimentalSettingsName()),
3713 ConstString("Experimental settings - setting these won't produce "
3714 "errors if the setting is not present."),
3715 true, m_experimental_properties_up->GetValueProperties());
3716 m_collection_sp->AppendProperty(
3717 ConstString("process"), ConstString("Settings specific to processes."),
3718 true, Process::GetGlobalProperties()->GetValueProperties());
3719 }
Caroline Ticedaccaa92010-09-20 20:44:43 +00003720}
3721
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003722TargetProperties::~TargetProperties() = default;
3723
Kate Stoneb9c1b512016-09-06 20:57:50 +00003724bool TargetProperties::GetInjectLocalVariables(
3725 ExecutionContext *exe_ctx) const {
3726 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3727 exe_ctx, false, ePropertyExperimental);
3728 OptionValueProperties *exp_values =
3729 exp_property->GetValue()->GetAsProperties();
3730 if (exp_values)
3731 return exp_values->GetPropertyAtIndexAsBoolean(
3732 exe_ctx, ePropertyInjectLocalVars, true);
3733 else
3734 return true;
Jim Inghambed67792016-07-07 18:25:48 +00003735}
3736
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3738 bool b) {
3739 const Property *exp_property =
3740 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3741 OptionValueProperties *exp_values =
3742 exp_property->GetValue()->GetAsProperties();
3743 if (exp_values)
3744 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3745 true);
Jim Inghambed67792016-07-07 18:25:48 +00003746}
3747
Sean Callanan68e44232017-09-28 20:20:25 +00003748bool TargetProperties::GetUseModernTypeLookup() const {
3749 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3750 nullptr, false, ePropertyExperimental);
3751 OptionValueProperties *exp_values =
3752 exp_property->GetValue()->GetAsProperties();
3753 if (exp_values)
3754 return exp_values->GetPropertyAtIndexAsBoolean(
3755 nullptr, ePropertyUseModernTypeLookup, true);
3756 else
3757 return true;
3758}
3759
Kate Stoneb9c1b512016-09-06 20:57:50 +00003760ArchSpec TargetProperties::GetDefaultArchitecture() const {
3761 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3762 nullptr, ePropertyDefaultArch);
3763 if (value)
3764 return value->GetCurrentValue();
3765 return ArchSpec();
Greg Clayton67cc0632012-08-22 17:17:09 +00003766}
3767
Kate Stoneb9c1b512016-09-06 20:57:50 +00003768void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3769 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3770 nullptr, ePropertyDefaultArch);
3771 if (value)
3772 return value->SetCurrentValue(arch, true);
Greg Clayton67cc0632012-08-22 17:17:09 +00003773}
3774
Kate Stoneb9c1b512016-09-06 20:57:50 +00003775bool TargetProperties::GetMoveToNearestCode() const {
3776 const uint32_t idx = ePropertyMoveToNearestCode;
3777 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3778 nullptr, idx, g_properties[idx].default_uint_value != 0);
Ilia K055ad9b2015-05-18 13:41:01 +00003779}
3780
Kate Stoneb9c1b512016-09-06 20:57:50 +00003781lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3782 const uint32_t idx = ePropertyPreferDynamic;
3783 return (lldb::DynamicValueType)
3784 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3785 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003786}
3787
Kate Stoneb9c1b512016-09-06 20:57:50 +00003788bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3789 const uint32_t idx = ePropertyPreferDynamic;
3790 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
Greg Clayton15484402015-05-15 18:40:24 +00003791}
3792
Jim Ingham7fca8c02017-04-28 00:51:06 +00003793bool TargetProperties::GetPreloadSymbols() const {
3794 const uint32_t idx = ePropertyPreloadSymbols;
3795 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3796 nullptr, idx, g_properties[idx].default_uint_value != 0);
3797}
3798
3799void TargetProperties::SetPreloadSymbols(bool b) {
3800 const uint32_t idx = ePropertyPreloadSymbols;
3801 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3802}
3803
Kate Stoneb9c1b512016-09-06 20:57:50 +00003804bool TargetProperties::GetDisableASLR() const {
3805 const uint32_t idx = ePropertyDisableASLR;
3806 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3807 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003808}
3809
Kate Stoneb9c1b512016-09-06 20:57:50 +00003810void TargetProperties::SetDisableASLR(bool b) {
3811 const uint32_t idx = ePropertyDisableASLR;
3812 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003813}
3814
Kate Stoneb9c1b512016-09-06 20:57:50 +00003815bool TargetProperties::GetDetachOnError() const {
3816 const uint32_t idx = ePropertyDetachOnError;
3817 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3818 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham106d0282014-06-25 02:32:56 +00003819}
3820
Kate Stoneb9c1b512016-09-06 20:57:50 +00003821void TargetProperties::SetDetachOnError(bool b) {
3822 const uint32_t idx = ePropertyDetachOnError;
3823 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Jim Ingham106d0282014-06-25 02:32:56 +00003824}
3825
Kate Stoneb9c1b512016-09-06 20:57:50 +00003826bool TargetProperties::GetDisableSTDIO() const {
3827 const uint32_t idx = ePropertyDisableSTDIO;
3828 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3829 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003830}
3831
Kate Stoneb9c1b512016-09-06 20:57:50 +00003832void TargetProperties::SetDisableSTDIO(bool b) {
3833 const uint32_t idx = ePropertyDisableSTDIO;
3834 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003835}
3836
Kate Stoneb9c1b512016-09-06 20:57:50 +00003837const char *TargetProperties::GetDisassemblyFlavor() const {
3838 const uint32_t idx = ePropertyDisassemblyFlavor;
3839 const char *return_value;
3840
3841 x86DisassemblyFlavor flavor_value =
3842 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3843 nullptr, idx, g_properties[idx].default_uint_value);
3844 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3845 return return_value;
Jim Ingham0f063ba2013-03-02 00:26:47 +00003846}
3847
Kate Stoneb9c1b512016-09-06 20:57:50 +00003848InlineStrategy TargetProperties::GetInlineStrategy() const {
3849 const uint32_t idx = ePropertyInlineStrategy;
3850 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3851 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton1f746072012-08-29 21:13:06 +00003852}
3853
Zachary Turner31d97a52016-11-17 18:08:12 +00003854llvm::StringRef TargetProperties::GetArg0() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003855 const uint32_t idx = ePropertyArg0;
Zachary Turner31d97a52016-11-17 18:08:12 +00003856 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
Greg Clayton45392552012-10-17 22:57:12 +00003857}
3858
Zachary Turner31d97a52016-11-17 18:08:12 +00003859void TargetProperties::SetArg0(llvm::StringRef arg) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003860 const uint32_t idx = ePropertyArg0;
Zachary Turner514d8cd2016-09-23 18:06:53 +00003861 m_collection_sp->SetPropertyAtIndexAsString(
Zachary Turner31d97a52016-11-17 18:08:12 +00003862 nullptr, idx, arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003863 m_launch_info.SetArg0(arg);
Greg Clayton45392552012-10-17 22:57:12 +00003864}
3865
Kate Stoneb9c1b512016-09-06 20:57:50 +00003866bool TargetProperties::GetRunArguments(Args &args) const {
3867 const uint32_t idx = ePropertyRunArgs;
3868 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +00003869}
3870
Kate Stoneb9c1b512016-09-06 20:57:50 +00003871void TargetProperties::SetRunArguments(const Args &args) {
3872 const uint32_t idx = ePropertyRunArgs;
3873 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3874 m_launch_info.GetArguments() = args;
Greg Clayton67cc0632012-08-22 17:17:09 +00003875}
3876
Pavel Labath62930e52018-01-10 11:57:31 +00003877Environment TargetProperties::GetEnvironment() const {
3878 // TODO: Get rid of the Args intermediate step
3879 Args env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880 const uint32_t idx = ePropertyEnvVars;
Pavel Labath62930e52018-01-10 11:57:31 +00003881 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3882 return Environment(env);
Greg Clayton67cc0632012-08-22 17:17:09 +00003883}
3884
Pavel Labath62930e52018-01-10 11:57:31 +00003885void TargetProperties::SetEnvironment(Environment env) {
3886 // TODO: Get rid of the Args intermediate step
Kate Stoneb9c1b512016-09-06 20:57:50 +00003887 const uint32_t idx = ePropertyEnvVars;
Pavel Labath62930e52018-01-10 11:57:31 +00003888 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3889 m_launch_info.GetEnvironment() = std::move(env);
Ilia K8f37ca52015-02-13 14:31:06 +00003890}
3891
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892bool TargetProperties::GetSkipPrologue() const {
3893 const uint32_t idx = ePropertySkipPrologue;
3894 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3895 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003896}
3897
Kate Stoneb9c1b512016-09-06 20:57:50 +00003898PathMappingList &TargetProperties::GetSourcePathMap() const {
3899 const uint32_t idx = ePropertySourceMap;
3900 OptionValuePathMappings *option_value =
3901 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3902 false, idx);
3903 assert(option_value);
3904 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003905}
3906
Kate Stoneb9c1b512016-09-06 20:57:50 +00003907FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3908 const uint32_t idx = ePropertyExecutableSearchPaths;
3909 OptionValueFileSpecList *option_value =
3910 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3911 false, idx);
3912 assert(option_value);
3913 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003914}
3915
Kate Stoneb9c1b512016-09-06 20:57:50 +00003916FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3917 const uint32_t idx = ePropertyDebugFileSearchPaths;
3918 OptionValueFileSpecList *option_value =
3919 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3920 false, idx);
3921 assert(option_value);
3922 return option_value->GetCurrentValue();
Michael Sartaina7499c92013-07-01 19:45:50 +00003923}
3924
Kate Stoneb9c1b512016-09-06 20:57:50 +00003925FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3926 const uint32_t idx = ePropertyClangModuleSearchPaths;
3927 OptionValueFileSpecList *option_value =
3928 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3929 false, idx);
3930 assert(option_value);
3931 return option_value->GetCurrentValue();
Sean Callanan85054342015-04-03 15:39:47 +00003932}
3933
Kate Stoneb9c1b512016-09-06 20:57:50 +00003934bool TargetProperties::GetEnableAutoImportClangModules() const {
3935 const uint32_t idx = ePropertyAutoImportClangModules;
3936 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3937 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callananf0c5aeb2015-04-20 16:31:29 +00003938}
3939
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940bool TargetProperties::GetEnableAutoApplyFixIts() const {
3941 const uint32_t idx = ePropertyAutoApplyFixIts;
3942 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3943 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghama1e541b2016-03-25 01:57:14 +00003944}
3945
Kate Stoneb9c1b512016-09-06 20:57:50 +00003946bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3947 const uint32_t idx = ePropertyNotifyAboutFixIts;
3948 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3949 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghame5ee6f02016-03-29 22:00:08 +00003950}
3951
Sean Callanan5deb06e2016-09-26 20:18:51 +00003952bool TargetProperties::GetEnableSaveObjects() const {
3953 const uint32_t idx = ePropertySaveObjects;
3954 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3955 nullptr, idx, g_properties[idx].default_uint_value != 0);
3956}
3957
Kate Stoneb9c1b512016-09-06 20:57:50 +00003958bool TargetProperties::GetEnableSyntheticValue() const {
3959 const uint32_t idx = ePropertyEnableSynthetic;
3960 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3961 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003962}
3963
Kate Stoneb9c1b512016-09-06 20:57:50 +00003964uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3965 const uint32_t idx = ePropertyMaxChildrenCount;
3966 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3967 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003968}
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3971 const uint32_t idx = ePropertyMaxSummaryLength;
3972 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3973 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003974}
3975
Kate Stoneb9c1b512016-09-06 20:57:50 +00003976uint32_t TargetProperties::GetMaximumMemReadSize() const {
3977 const uint32_t idx = ePropertyMaxMemReadSize;
3978 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3979 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granatad325bf92013-06-04 22:54:16 +00003980}
3981
Kate Stoneb9c1b512016-09-06 20:57:50 +00003982FileSpec TargetProperties::GetStandardInputPath() const {
3983 const uint32_t idx = ePropertyInputPath;
3984 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003985}
3986
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003987void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988 const uint32_t idx = ePropertyInputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003989 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003990}
3991
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992FileSpec TargetProperties::GetStandardOutputPath() const {
3993 const uint32_t idx = ePropertyOutputPath;
3994 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003995}
3996
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003997void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 const uint32_t idx = ePropertyOutputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003999 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00004000}
4001
Kate Stoneb9c1b512016-09-06 20:57:50 +00004002FileSpec TargetProperties::GetStandardErrorPath() const {
4003 const uint32_t idx = ePropertyErrorPath;
4004 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00004005}
4006
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004007void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4008 const uint32_t idx = ePropertyErrorPath;
4009 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4010}
4011
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012LanguageType TargetProperties::GetLanguage() const {
4013 OptionValueLanguage *value =
4014 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4015 nullptr, ePropertyLanguage);
4016 if (value)
4017 return value->GetCurrentValue();
4018 return LanguageType();
Dawn Perchik23b1dec2015-07-21 22:05:07 +00004019}
4020
Pavel Labath50251fc2017-12-21 10:54:30 +00004021llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004022 const uint32_t idx = ePropertyExprPrefix;
4023 OptionValueFileSpec *file =
4024 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4025 idx);
4026 if (file) {
Pavel Labath50251fc2017-12-21 10:54:30 +00004027 DataBufferSP data_sp(file->GetFileContents());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004028 if (data_sp)
Pavel Labath50251fc2017-12-21 10:54:30 +00004029 return llvm::StringRef(
4030 reinterpret_cast<const char *>(data_sp->GetBytes()),
4031 data_sp->GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004032 }
Pavel Labath50251fc2017-12-21 10:54:30 +00004033 return "";
Greg Clayton6920b522012-08-22 18:39:03 +00004034}
4035
Kate Stoneb9c1b512016-09-06 20:57:50 +00004036bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4037 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4038 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4039 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00004040}
4041
Kate Stoneb9c1b512016-09-06 20:57:50 +00004042bool TargetProperties::GetUseHexImmediates() const {
4043 const uint32_t idx = ePropertyUseHexImmediates;
4044 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4045 nullptr, idx, g_properties[idx].default_uint_value != 0);
Daniel Malead79ae052013-08-07 21:54:09 +00004046}
4047
Kate Stoneb9c1b512016-09-06 20:57:50 +00004048bool TargetProperties::GetUseFastStepping() const {
4049 const uint32_t idx = ePropertyUseFastStepping;
4050 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4051 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham17d023f2013-03-13 17:58:04 +00004052}
4053
Kate Stoneb9c1b512016-09-06 20:57:50 +00004054bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4055 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4056 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4057 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Claytonfb6621e2013-12-06 21:59:52 +00004058}
4059
Kate Stoneb9c1b512016-09-06 20:57:50 +00004060LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4061 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4062 return (LoadScriptFromSymFile)
4063 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4064 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granata2ea43cd2013-05-13 17:03:52 +00004065}
4066
Kate Stoneb9c1b512016-09-06 20:57:50 +00004067LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4068 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4069 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4070 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molenda878ae012016-02-19 00:05:17 +00004071}
4072
Kate Stoneb9c1b512016-09-06 20:57:50 +00004073Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4074 const uint32_t idx = ePropertyHexImmediateStyle;
4075 return (Disassembler::HexImmediateStyle)
4076 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4077 nullptr, idx, g_properties[idx].default_uint_value);
Daniel Malead79ae052013-08-07 21:54:09 +00004078}
4079
Kate Stoneb9c1b512016-09-06 20:57:50 +00004080MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4081 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4082 return (MemoryModuleLoadLevel)
4083 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4084 nullptr, idx, g_properties[idx].default_uint_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00004085}
4086
Kate Stoneb9c1b512016-09-06 20:57:50 +00004087bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4088 const uint32_t idx = ePropertyTrapHandlerNames;
4089 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00004090}
Greg Claytonfd814c52013-08-13 01:42:25 +00004091
Kate Stoneb9c1b512016-09-06 20:57:50 +00004092void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4093 const uint32_t idx = ePropertyTrapHandlerNames;
4094 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00004095}
Greg Clayton67cc0632012-08-22 17:17:09 +00004096
Kate Stoneb9c1b512016-09-06 20:57:50 +00004097bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4098 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4099 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Enrico Granata560558e2015-02-11 02:35:39 +00004100}
4101
Kate Stoneb9c1b512016-09-06 20:57:50 +00004102void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4103 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4104 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granata560558e2015-02-11 02:35:39 +00004105}
4106
Kate Stoneb9c1b512016-09-06 20:57:50 +00004107bool TargetProperties::GetNonStopModeEnabled() const {
4108 const uint32_t idx = ePropertyNonStopModeEnabled;
4109 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Ewan Crawford78baa192015-05-13 09:18:18 +00004110}
4111
Kate Stoneb9c1b512016-09-06 20:57:50 +00004112void TargetProperties::SetNonStopModeEnabled(bool b) {
4113 const uint32_t idx = ePropertyNonStopModeEnabled;
4114 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00004115}
4116
Kate Stoneb9c1b512016-09-06 20:57:50 +00004117const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4118 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4119 return m_launch_info;
Ilia K8f37ca52015-02-13 14:31:06 +00004120}
4121
Kate Stoneb9c1b512016-09-06 20:57:50 +00004122void TargetProperties::SetProcessLaunchInfo(
4123 const ProcessLaunchInfo &launch_info) {
4124 m_launch_info = launch_info;
4125 SetArg0(launch_info.GetArg0());
4126 SetRunArguments(launch_info.GetArguments());
Pavel Labath62930e52018-01-10 11:57:31 +00004127 SetEnvironment(launch_info.GetEnvironment());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004128 const FileAction *input_file_action =
4129 launch_info.GetFileActionForFD(STDIN_FILENO);
4130 if (input_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004131 SetStandardInputPath(input_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004132 }
4133 const FileAction *output_file_action =
4134 launch_info.GetFileActionForFD(STDOUT_FILENO);
4135 if (output_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004136 SetStandardOutputPath(output_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004137 }
4138 const FileAction *error_file_action =
4139 launch_info.GetFileActionForFD(STDERR_FILENO);
4140 if (error_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00004141 SetStandardErrorPath(error_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004142 }
4143 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4144 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4145 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
Ilia K8f37ca52015-02-13 14:31:06 +00004146}
4147
Kate Stoneb9c1b512016-09-06 20:57:50 +00004148void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4149 OptionValue *) {
4150 TargetProperties *this_ =
4151 reinterpret_cast<TargetProperties *>(target_property_ptr);
4152 this_->m_launch_info.SetArg0(this_->GetArg0());
Ilia K8f37ca52015-02-13 14:31:06 +00004153}
4154
Kate Stoneb9c1b512016-09-06 20:57:50 +00004155void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4156 OptionValue *) {
4157 TargetProperties *this_ =
4158 reinterpret_cast<TargetProperties *>(target_property_ptr);
4159 Args args;
4160 if (this_->GetRunArguments(args))
4161 this_->m_launch_info.GetArguments() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00004162}
4163
Kate Stoneb9c1b512016-09-06 20:57:50 +00004164void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4165 OptionValue *) {
4166 TargetProperties *this_ =
4167 reinterpret_cast<TargetProperties *>(target_property_ptr);
Pavel Labath62930e52018-01-10 11:57:31 +00004168 this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
Ilia K8f37ca52015-02-13 14:31:06 +00004169}
4170
Kate Stoneb9c1b512016-09-06 20:57:50 +00004171void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4172 OptionValue *) {
4173 TargetProperties *this_ =
4174 reinterpret_cast<TargetProperties *>(target_property_ptr);
4175 this_->m_launch_info.AppendOpenFileAction(
4176 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
Ilia K8f37ca52015-02-13 14:31:06 +00004177}
4178
Kate Stoneb9c1b512016-09-06 20:57:50 +00004179void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4180 OptionValue *) {
4181 TargetProperties *this_ =
4182 reinterpret_cast<TargetProperties *>(target_property_ptr);
4183 this_->m_launch_info.AppendOpenFileAction(
4184 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004185}
4186
Kate Stoneb9c1b512016-09-06 20:57:50 +00004187void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4188 OptionValue *) {
4189 TargetProperties *this_ =
4190 reinterpret_cast<TargetProperties *>(target_property_ptr);
4191 this_->m_launch_info.AppendOpenFileAction(
4192 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004193}
4194
Kate Stoneb9c1b512016-09-06 20:57:50 +00004195void TargetProperties::DetachOnErrorValueChangedCallback(
4196 void *target_property_ptr, OptionValue *) {
4197 TargetProperties *this_ =
4198 reinterpret_cast<TargetProperties *>(target_property_ptr);
4199 if (this_->GetDetachOnError())
4200 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4201 else
4202 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
Ilia K8f37ca52015-02-13 14:31:06 +00004203}
4204
Kate Stoneb9c1b512016-09-06 20:57:50 +00004205void TargetProperties::DisableASLRValueChangedCallback(
4206 void *target_property_ptr, OptionValue *) {
4207 TargetProperties *this_ =
4208 reinterpret_cast<TargetProperties *>(target_property_ptr);
4209 if (this_->GetDisableASLR())
4210 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4211 else
4212 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
Ilia K8f37ca52015-02-13 14:31:06 +00004213}
4214
Kate Stoneb9c1b512016-09-06 20:57:50 +00004215void TargetProperties::DisableSTDIOValueChangedCallback(
4216 void *target_property_ptr, OptionValue *) {
4217 TargetProperties *this_ =
4218 reinterpret_cast<TargetProperties *>(target_property_ptr);
4219 if (this_->GetDisableSTDIO())
4220 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4221 else
4222 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
Ilia K8f37ca52015-02-13 14:31:06 +00004223}
Ilia Keb2c19a2015-03-10 21:59:55 +00004224
4225//----------------------------------------------------------------------
4226// Target::TargetEventData
4227//----------------------------------------------------------------------
4228
Kate Stoneb9c1b512016-09-06 20:57:50 +00004229Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4230 : EventData(), m_target_sp(target_sp), m_module_list() {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004231
Kate Stoneb9c1b512016-09-06 20:57:50 +00004232Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4233 const ModuleList &module_list)
4234 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004235
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004236Target::TargetEventData::~TargetEventData() = default;
Ilia Keb2c19a2015-03-10 21:59:55 +00004237
Kate Stoneb9c1b512016-09-06 20:57:50 +00004238const ConstString &Target::TargetEventData::GetFlavorString() {
4239 static ConstString g_flavor("Target::TargetEventData");
4240 return g_flavor;
Ilia Keb2c19a2015-03-10 21:59:55 +00004241}
4242
Kate Stoneb9c1b512016-09-06 20:57:50 +00004243void Target::TargetEventData::Dump(Stream *s) const {
4244 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4245 if (i != 0)
4246 *s << ", ";
4247 m_module_list.GetModuleAtIndex(i)->GetDescription(
4248 s, lldb::eDescriptionLevelBrief);
4249 }
Ilia Keb2c19a2015-03-10 21:59:55 +00004250}
4251
4252const Target::TargetEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004253Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4254 if (event_ptr) {
4255 const EventData *event_data = event_ptr->GetData();
4256 if (event_data &&
4257 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4258 return static_cast<const TargetEventData *>(event_ptr->GetData());
4259 }
4260 return nullptr;
Ilia Keb2c19a2015-03-10 21:59:55 +00004261}
4262
Kate Stoneb9c1b512016-09-06 20:57:50 +00004263TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4264 TargetSP target_sp;
4265 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4266 if (event_data)
4267 target_sp = event_data->m_target_sp;
4268 return target_sp;
Ilia Keb2c19a2015-03-10 21:59:55 +00004269}
4270
4271ModuleList
Kate Stoneb9c1b512016-09-06 20:57:50 +00004272Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4273 ModuleList module_list;
4274 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4275 if (event_data)
4276 module_list = event_data->m_module_list;
4277 return module_list;
Ilia Keb2c19a2015-03-10 21:59:55 +00004278}