blob: ee7eab71c6a686ceea18d9f5b21cc0b095751f92 [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"
27#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000028#include "lldb/Core/Module.h"
29#include "lldb/Core/ModuleSpec.h"
30#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"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Core/StreamString.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000035#include "lldb/Core/Timer.h"
36#include "lldb/Core/ValueObject.h"
Sean Callanan66810412015-10-19 23:11:07 +000037#include "lldb/Expression/REPL.h"
Jim Ingham151c0322015-09-15 21:13:50 +000038#include "lldb/Expression/UserExpression.h"
Zachary Turner10687b02014-10-20 17:46:43 +000039#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Host/Host.h"
Jim Ingham9575d842011-03-11 03:53:59 +000041#include "lldb/Interpreter/CommandInterpreter.h"
42#include "lldb/Interpreter/CommandReturnObject.h"
Johnny Chenb90827e2012-06-04 23:19:54 +000043#include "lldb/Interpreter/OptionGroupWatchpoint.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000044#include "lldb/Interpreter/OptionValues.h"
45#include "lldb/Interpreter/Property.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000046#include "lldb/Symbol/ClangASTContext.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000047#include "lldb/Symbol/Function.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000048#include "lldb/Symbol/ObjectFile.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000049#include "lldb/Symbol/Symbol.h"
Jim Ingham151c0322015-09-15 21:13:50 +000050#include "lldb/Target/Language.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000051#include "lldb/Target/LanguageRuntime.h"
52#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/Process.h"
Greg Claytond5944cd2013-12-06 01:12:00 +000054#include "lldb/Target/SectionLoadList.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000055#include "lldb/Target/StackFrame.h"
Jason Molendaeef51062013-11-05 03:57:19 +000056#include "lldb/Target/SystemRuntime.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000057#include "lldb/Target/Target.h"
Jim Ingham9575d842011-03-11 03:53:59 +000058#include "lldb/Target/Thread.h"
59#include "lldb/Target/ThreadSpec.h"
Sean Callanan9a6940c2015-10-21 00:36:34 +000060#include "lldb/Utility/LLDBAssert.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061
62using namespace lldb;
63using namespace lldb_private;
64
Kate Stoneb9c1b512016-09-06 20:57:50 +000065ConstString &Target::GetStaticBroadcasterClass() {
66 static ConstString class_name("lldb.target");
67 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000068}
69
Kate Stoneb9c1b512016-09-06 20:57:50 +000070Target::Target(Debugger &debugger, const ArchSpec &target_arch,
71 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000072 : TargetProperties(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +000073 Broadcaster(debugger.GetBroadcasterManager(),
74 Target::GetStaticBroadcasterClass().AsCString()),
75 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
76 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
77 m_breakpoint_list(false), m_internal_breakpoint_list(true),
78 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
79 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
80 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
81 m_valid(true), m_suppress_stop_hooks(false),
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000082 m_is_dummy_target(is_dummy_target)
Jim Ingham893c9322014-11-22 01:42:44 +000083
Chris Lattner30fdc8d2010-06-08 16:52:24 +000084{
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
86 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
87 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
88 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
89 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +000090
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 CheckInWithManager();
Greg Claytoncfd1ace2010-10-31 03:01:06 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
94 if (log)
95 log->Printf("%p Target::Target()", static_cast<void *>(this));
96 if (m_arch.IsValid()) {
97 LogIfAnyCategoriesSet(
98 LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)",
99 m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
100 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000101}
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103Target::~Target() {
104 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
105 if (log)
106 log->Printf("%p Target::~Target()", static_cast<void *>(this));
107 DeleteCurrentProcess();
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000108}
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110void Target::PrimeFromDummyTarget(Target *target) {
111 if (!target)
112 return;
Jim Ingham893c9322014-11-22 01:42:44 +0000113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 m_stop_hooks = target->m_stop_hooks;
115
116 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
117 if (breakpoint_sp->IsInternal())
118 continue;
119
120 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
121 AddBreakpoint(new_bp, false);
122 }
Jim Ingham893c9322014-11-22 01:42:44 +0000123}
124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
126 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
127 if (description_level != lldb::eDescriptionLevelBrief) {
128 s->Indent();
129 s->PutCString("Target\n");
130 s->IndentMore();
131 m_images.Dump(s);
132 m_breakpoint_list.Dump(s);
133 m_internal_breakpoint_list.Dump(s);
134 s->IndentLess();
135 } else {
136 Module *exe_module = GetExecutableModulePointer();
137 if (exe_module)
138 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
Caroline Ticeceb6b132010-10-26 03:11:13 +0000139 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 s->PutCString("No executable module.");
141 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000142}
143
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144void Target::CleanupProcess() {
145 // Do any cleanup of the target we need to do between process instances.
146 // NB It is better to do this before destroying the process in case the
147 // clean up needs some help from the process.
148 m_breakpoint_list.ClearAllBreakpointSites();
149 m_internal_breakpoint_list.ClearAllBreakpointSites();
150 // Disable watchpoints just on the debugger side.
151 std::unique_lock<std::recursive_mutex> lock;
152 this->GetWatchpointList().GetListMutex(lock);
153 DisableAllWatchpoints(false);
154 ClearAllWatchpointHitCounts();
155 ClearAllWatchpointHistoricValues();
Greg Clayton90ba8112012-12-05 00:16:59 +0000156}
157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158void Target::DeleteCurrentProcess() {
159 if (m_process_sp) {
Greg Claytond5944cd2013-12-06 01:12:00 +0000160 m_section_load_history.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 if (m_process_sp->IsAlive())
162 m_process_sp->Destroy(false);
163
164 m_process_sp->Finalize();
165
166 CleanupProcess();
167
168 m_process_sp.reset();
169 }
Greg Clayton3418c852011-08-10 02:10:13 +0000170}
171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
173 const char *plugin_name,
174 const FileSpec *crash_file) {
175 DeleteCurrentProcess();
176 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
177 listener_sp, crash_file);
178 return m_process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
182
183lldb::REPLSP Target::GetREPL(Error &err, lldb::LanguageType language,
184 const char *repl_options, bool can_create) {
185 if (language == eLanguageTypeUnknown) {
186 std::set<LanguageType> repl_languages;
187
188 Language::GetLanguagesSupportingREPLs(repl_languages);
189
190 if (repl_languages.size() == 1) {
191 language = *repl_languages.begin();
192 } else if (repl_languages.size() == 0) {
193 err.SetErrorStringWithFormat(
194 "LLDB isn't configured with REPL support for any languages.");
195 return REPLSP();
196 } else {
197 err.SetErrorStringWithFormat(
198 "Multiple possible REPL languages. Please specify a language.");
199 return REPLSP();
200 }
201 }
202
203 REPLMap::iterator pos = m_repl_map.find(language);
204
205 if (pos != m_repl_map.end()) {
206 return pos->second;
207 }
208
209 if (!can_create) {
210 err.SetErrorStringWithFormat(
211 "Couldn't find an existing REPL for %s, and can't create a new one",
212 Language::GetNameForLanguageType(language));
213 return lldb::REPLSP();
214 }
215
216 Debugger *const debugger = nullptr;
217 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
218
219 if (ret) {
220 m_repl_map[language] = ret;
221 return m_repl_map[language];
222 }
223
224 if (err.Success()) {
225 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
226 Language::GetNameForLanguageType(language));
227 }
228
229 return lldb::REPLSP();
230}
231
232void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
233 lldbassert(!m_repl_map.count(language));
234
235 m_repl_map[language] = repl_sp;
236}
237
238void Target::Destroy() {
239 std::lock_guard<std::recursive_mutex> guard(m_mutex);
240 m_valid = false;
241 DeleteCurrentProcess();
242 m_platform_sp.reset();
243 m_arch.Clear();
244 ClearModules(true);
245 m_section_load_history.Clear();
246 const bool notify = false;
247 m_breakpoint_list.RemoveAll(notify);
248 m_internal_breakpoint_list.RemoveAll(notify);
249 m_last_created_breakpoint.reset();
250 m_last_created_watchpoint.reset();
251 m_search_filter_sp.reset();
252 m_image_search_paths.Clear(notify);
253 m_stop_hooks.clear();
254 m_stop_hook_next_id = 0;
255 m_suppress_stop_hooks = false;
256}
257
258BreakpointList &Target::GetBreakpointList(bool internal) {
259 if (internal)
260 return m_internal_breakpoint_list;
261 else
262 return m_breakpoint_list;
263}
264
265const BreakpointList &Target::GetBreakpointList(bool internal) const {
266 if (internal)
267 return m_internal_breakpoint_list;
268 else
269 return m_breakpoint_list;
270}
271
272BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
273 BreakpointSP bp_sp;
274
275 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
276 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
277 else
278 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
279
280 return bp_sp;
281}
282
283BreakpointSP Target::CreateSourceRegexBreakpoint(
284 const FileSpecList *containingModules,
285 const FileSpecList *source_file_spec_list,
286 const std::unordered_set<std::string> &function_names,
287 RegularExpression &source_regex, bool internal, bool hardware,
288 LazyBool move_to_nearest_code) {
289 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
290 containingModules, source_file_spec_list));
291 if (move_to_nearest_code == eLazyBoolCalculate)
292 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
293 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
294 nullptr, source_regex, function_names,
295 !static_cast<bool>(move_to_nearest_code)));
296
297 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
298}
299
300BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
301 const FileSpec &file, uint32_t line_no,
302 lldb::addr_t offset,
303 LazyBool check_inlines,
304 LazyBool skip_prologue, bool internal,
305 bool hardware,
306 LazyBool move_to_nearest_code) {
307 FileSpec remapped_file;
308 ConstString remapped_path;
309 if (GetSourcePathMap().ReverseRemapPath(ConstString(file.GetPath().c_str()),
310 remapped_path))
311 remapped_file.SetFile(remapped_path.AsCString(), true);
312 else
313 remapped_file = file;
314
315 if (check_inlines == eLazyBoolCalculate) {
316 const InlineStrategy inline_strategy = GetInlineStrategy();
317 switch (inline_strategy) {
318 case eInlineBreakpointsNever:
319 check_inlines = eLazyBoolNo;
320 break;
321
322 case eInlineBreakpointsHeaders:
323 if (remapped_file.IsSourceImplementationFile())
324 check_inlines = eLazyBoolNo;
325 else
326 check_inlines = eLazyBoolYes;
327 break;
328
329 case eInlineBreakpointsAlways:
330 check_inlines = eLazyBoolYes;
331 break;
332 }
333 }
334 SearchFilterSP filter_sp;
335 if (check_inlines == eLazyBoolNo) {
336 // Not checking for inlines, we are looking only for matching compile units
337 FileSpecList compile_unit_list;
338 compile_unit_list.Append(remapped_file);
339 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
340 &compile_unit_list);
341 } else {
342 filter_sp = GetSearchFilterForModuleList(containingModules);
343 }
344 if (skip_prologue == eLazyBoolCalculate)
345 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
346 if (move_to_nearest_code == eLazyBoolCalculate)
347 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
348
349 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
350 nullptr, remapped_file, line_no, offset, check_inlines, skip_prologue,
351 !static_cast<bool>(move_to_nearest_code)));
352 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
353}
354
355BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
356 bool hardware) {
357 Address so_addr;
358
359 // Check for any reason we want to move this breakpoint to other address.
360 addr = GetBreakableLoadAddress(addr);
361
362 // Attempt to resolve our load address if possible, though it is ok if
363 // it doesn't resolve to section/offset.
364
365 // Try and resolve as a load address if possible
366 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
367 if (!so_addr.IsValid()) {
368 // The address didn't resolve, so just set this as an absolute address
369 so_addr.SetOffset(addr);
370 }
371 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
372 return bp_sp;
373}
374
375BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
376 bool hardware) {
377 SearchFilterSP filter_sp(
378 new SearchFilterForUnconstrainedSearches(shared_from_this()));
379 BreakpointResolverSP resolver_sp(
380 new BreakpointResolverAddress(nullptr, addr));
381 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
382}
383
384lldb::BreakpointSP
385Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
386 const FileSpec *file_spec,
387 bool request_hardware) {
388 SearchFilterSP filter_sp(
389 new SearchFilterForUnconstrainedSearches(shared_from_this()));
390 BreakpointResolverSP resolver_sp(
391 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
392 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
393 false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394}
395
396BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397Target::CreateBreakpoint(const FileSpecList *containingModules,
398 const FileSpecList *containingSourceFiles,
399 const char *func_name, uint32_t func_name_type_mask,
400 LanguageType language, lldb::addr_t offset,
401 LazyBool skip_prologue, bool internal, bool hardware) {
402 BreakpointSP bp_sp;
403 if (func_name) {
404 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
405 containingModules, containingSourceFiles));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406
Greg Clayton03da4cc2013-04-19 21:31:16 +0000407 if (skip_prologue == eLazyBoolCalculate)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
409 if (language == lldb::eLanguageTypeUnknown)
410 language = GetLanguage();
411
412 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
413 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
414 offset, skip_prologue));
415 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
416 }
417 return bp_sp;
418}
419
420lldb::BreakpointSP
421Target::CreateBreakpoint(const FileSpecList *containingModules,
422 const FileSpecList *containingSourceFiles,
423 const std::vector<std::string> &func_names,
424 uint32_t func_name_type_mask, LanguageType language,
425 lldb::addr_t offset, LazyBool skip_prologue,
426 bool internal, bool hardware) {
427 BreakpointSP bp_sp;
428 size_t num_names = func_names.size();
429 if (num_names > 0) {
430 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
431 containingModules, containingSourceFiles));
432
433 if (skip_prologue == eLazyBoolCalculate)
434 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
435 if (language == lldb::eLanguageTypeUnknown)
436 language = GetLanguage();
437
438 BreakpointResolverSP resolver_sp(
439 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
440 language, offset, skip_prologue));
441 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
442 }
443 return bp_sp;
444}
445
446BreakpointSP Target::CreateBreakpoint(
447 const FileSpecList *containingModules,
448 const FileSpecList *containingSourceFiles, const char *func_names[],
449 size_t num_names, uint32_t func_name_type_mask, LanguageType language,
450 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
451 BreakpointSP bp_sp;
452 if (num_names > 0) {
453 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
454 containingModules, containingSourceFiles));
455
456 if (skip_prologue == eLazyBoolCalculate) {
457 if (offset == 0)
Greg Clayton03da4cc2013-04-19 21:31:16 +0000458 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 else
460 skip_prologue = eLazyBoolNo;
Greg Clayton1b72fcb2010-08-24 00:45:41 +0000461 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 if (language == lldb::eLanguageTypeUnknown)
463 language = GetLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000464
Kate Stoneb9c1b512016-09-06 20:57:50 +0000465 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
466 nullptr, func_names, num_names, func_name_type_mask, language, offset,
467 skip_prologue));
468 resolver_sp->SetOffset(offset);
469 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
470 }
471 return bp_sp;
Jim Ingham133e0fb2012-03-03 02:05:11 +0000472}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000473
474SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475Target::GetSearchFilterForModule(const FileSpec *containingModule) {
476 SearchFilterSP filter_sp;
477 if (containingModule != nullptr) {
478 // TODO: We should look into sharing module based search filters
479 // across many breakpoints like we do for the simple target based one
480 filter_sp.reset(
481 new SearchFilterByModule(shared_from_this(), *containingModule));
482 } else {
483 if (!m_search_filter_sp)
484 m_search_filter_sp.reset(
485 new SearchFilterForUnconstrainedSearches(shared_from_this()));
486 filter_sp = m_search_filter_sp;
487 }
488 return filter_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489}
490
Jim Ingham969795f2011-09-21 01:17:13 +0000491SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
493 SearchFilterSP filter_sp;
494 if (containingModules && containingModules->GetSize() != 0) {
495 // TODO: We should look into sharing module based search filters
496 // across many breakpoints like we do for the simple target based one
497 filter_sp.reset(
498 new SearchFilterByModuleList(shared_from_this(), *containingModules));
499 } else {
500 if (!m_search_filter_sp)
501 m_search_filter_sp.reset(
502 new SearchFilterForUnconstrainedSearches(shared_from_this()));
503 filter_sp = m_search_filter_sp;
504 }
505 return filter_sp;
Jim Ingham969795f2011-09-21 01:17:13 +0000506}
507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
509 const FileSpecList *containingModules,
510 const FileSpecList *containingSourceFiles) {
511 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
512 return GetSearchFilterForModuleList(containingModules);
513
514 SearchFilterSP filter_sp;
515 if (containingModules == nullptr) {
516 // We could make a special "CU List only SearchFilter". Better yet was if
517 // these could be composable,
518 // but that will take a little reworking.
519
520 filter_sp.reset(new SearchFilterByModuleListAndCU(
521 shared_from_this(), FileSpecList(), *containingSourceFiles));
522 } else {
523 filter_sp.reset(new SearchFilterByModuleListAndCU(
524 shared_from_this(), *containingModules, *containingSourceFiles));
525 }
526 return filter_sp;
Jim Ingham87df91b2011-09-23 00:54:11 +0000527}
528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529BreakpointSP Target::CreateFuncRegexBreakpoint(
530 const FileSpecList *containingModules,
531 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
532 lldb::LanguageType requested_language, LazyBool skip_prologue,
533 bool internal, bool hardware) {
534 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
535 containingModules, containingSourceFiles));
536 bool skip = (skip_prologue == eLazyBoolCalculate)
537 ? GetSkipPrologue()
538 : static_cast<bool>(skip_prologue);
539 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
540 nullptr, func_regex, requested_language, 0, skip));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543}
544
Jim Ingham219ba192012-03-05 04:47:34 +0000545lldb::BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
547 bool catch_bp, bool throw_bp, bool internal,
548 Args *additional_args, Error *error) {
549 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
550 *this, language, catch_bp, throw_bp, internal);
551 if (exc_bkpt_sp && additional_args) {
552 Breakpoint::BreakpointPreconditionSP precondition_sp =
553 exc_bkpt_sp->GetPrecondition();
554 if (precondition_sp && additional_args) {
555 if (error)
556 *error = precondition_sp->ConfigurePrecondition(*additional_args);
557 else
558 precondition_sp->ConfigurePrecondition(*additional_args);
Jim Inghama72b31c2015-04-22 19:42:18 +0000559 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 }
561 return exc_bkpt_sp;
Jim Ingham219ba192012-03-05 04:47:34 +0000562}
Jim Inghama72b31c2015-04-22 19:42:18 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
565 BreakpointResolverSP &resolver_sp,
566 bool internal, bool request_hardware,
567 bool resolve_indirect_symbols) {
568 BreakpointSP bp_sp;
569 if (filter_sp && resolver_sp) {
570 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, request_hardware,
571 resolve_indirect_symbols));
572 resolver_sp->SetBreakpoint(bp_sp.get());
573 AddBreakpoint(bp_sp, internal);
574 }
575 return bp_sp;
Jim Ingham33df7cd2014-12-06 01:28:03 +0000576}
577
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
579 if (!bp_sp)
580 return;
581 if (internal)
582 m_internal_breakpoint_list.Add(bp_sp, false);
583 else
584 m_breakpoint_list.Add(bp_sp, true);
Jim Ingham33df7cd2014-12-06 01:28:03 +0000585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
587 if (log) {
588 StreamString s;
589 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
590 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
591 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
592 }
Jim Ingham33df7cd2014-12-06 01:28:03 +0000593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 bp_sp->ResolveBreakpoint();
Jim Ingham33df7cd2014-12-06 01:28:03 +0000595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 if (!internal) {
597 m_last_created_breakpoint = bp_sp;
598 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599}
600
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601bool Target::ProcessIsValid() {
602 return (m_process_sp && m_process_sp->IsAlive());
Johnny Chen86364b42011-09-20 23:28:55 +0000603}
604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605static bool CheckIfWatchpointsExhausted(Target *target, Error &error) {
606 uint32_t num_supported_hardware_watchpoints;
607 Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(
608 num_supported_hardware_watchpoints);
609 if (num_supported_hardware_watchpoints == 0) {
610 error.SetErrorStringWithFormat(
611 "Target supports (%u) hardware watchpoint slots.\n",
612 num_supported_hardware_watchpoints);
613 return false;
614 }
615 return true;
Johnny Chenb90827e2012-06-04 23:19:54 +0000616}
617
Johnny Chen01a67862011-10-14 00:42:25 +0000618// See also Watchpoint::SetWatchpointType(uint32_t type) and
Johnny Chenab9ee762011-09-14 00:26:03 +0000619// the OptionGroupWatchpoint::WatchType enum type.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
621 const CompilerType *type, uint32_t kind,
622 Error &error) {
623 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
624 if (log)
625 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
626 " type = %u)\n",
627 __FUNCTION__, addr, (uint64_t)size, kind);
Johnny Chen0c406372011-09-14 20:23:45 +0000628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 WatchpointSP wp_sp;
630 if (!ProcessIsValid()) {
631 error.SetErrorString("process is not alive");
Johnny Chen01a67862011-10-14 00:42:25 +0000632 return wp_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 }
Johnny Chen887062a2011-09-12 23:38:44 +0000634
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
636 if (size == 0)
637 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
640 return wp_sp;
641 }
642
643 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
644 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
645 }
646
647 if (!CheckIfWatchpointsExhausted(this, error))
648 return wp_sp;
649
650 // Currently we only support one watchpoint per address, with total number
651 // of watchpoints limited by the hardware which the inferior is running on.
652
653 // Grab the list mutex while doing operations.
654 const bool notify = false; // Don't notify about all the state changes we do
655 // on creating the watchpoint.
656 std::unique_lock<std::recursive_mutex> lock;
657 this->GetWatchpointList().GetListMutex(lock);
658 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
659 if (matched_sp) {
660 size_t old_size = matched_sp->GetByteSize();
661 uint32_t old_type =
662 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
663 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
664 // Return the existing watchpoint if both size and type match.
665 if (size == old_size && kind == old_type) {
666 wp_sp = matched_sp;
667 wp_sp->SetEnabled(false, notify);
668 } else {
669 // Nil the matched watchpoint; we will be creating a new one.
670 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
671 m_watchpoint_list.Remove(matched_sp->GetID(), true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000672 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 }
674
675 if (!wp_sp) {
676 wp_sp.reset(new Watchpoint(*this, addr, size, type));
677 wp_sp->SetWatchpointType(kind, notify);
678 m_watchpoint_list.Add(wp_sp, true);
679 }
680
681 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
682 if (log)
683 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
684 __FUNCTION__, error.Success() ? "succeeded" : "failed",
685 wp_sp->GetID());
686
687 if (error.Fail()) {
688 // Enabling the watchpoint on the device side failed.
689 // Remove the said watchpoint from the list maintained by the target
690 // instance.
691 m_watchpoint_list.Remove(wp_sp->GetID(), true);
692 // See if we could provide more helpful error message.
693 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
694 error.SetErrorStringWithFormat(
695 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
696
697 wp_sp.reset();
698 } else
699 m_last_created_watchpoint = wp_sp;
700 return wp_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701}
702
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703void Target::RemoveAllBreakpoints(bool internal_also) {
704 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
705 if (log)
706 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
707 internal_also ? "yes" : "no");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 m_breakpoint_list.RemoveAll(true);
710 if (internal_also)
711 m_internal_breakpoint_list.RemoveAll(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 m_last_created_breakpoint.reset();
714}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716void Target::DisableAllBreakpoints(bool internal_also) {
717 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
718 if (log)
719 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
720 internal_also ? "yes" : "no");
721
722 m_breakpoint_list.SetEnabledAll(false);
723 if (internal_also)
724 m_internal_breakpoint_list.SetEnabledAll(false);
725}
726
727void Target::EnableAllBreakpoints(bool internal_also) {
728 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
729 if (log)
730 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
731 internal_also ? "yes" : "no");
732
733 m_breakpoint_list.SetEnabledAll(true);
734 if (internal_also)
735 m_internal_breakpoint_list.SetEnabledAll(true);
736}
737
738bool Target::RemoveBreakpointByID(break_id_t break_id) {
739 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
740 if (log)
741 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
742 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
743
744 if (DisableBreakpointByID(break_id)) {
745 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
746 m_internal_breakpoint_list.Remove(break_id, false);
747 else {
748 if (m_last_created_breakpoint) {
749 if (m_last_created_breakpoint->GetID() == break_id)
750 m_last_created_breakpoint.reset();
751 }
752 m_breakpoint_list.Remove(break_id, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000753 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 return true;
755 }
756 return false;
757}
758
759bool Target::DisableBreakpointByID(break_id_t break_id) {
760 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
761 if (log)
762 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
763 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
764
765 BreakpointSP bp_sp;
766
767 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
768 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
769 else
770 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
771 if (bp_sp) {
772 bp_sp->SetEnabled(false);
773 return true;
774 }
775 return false;
776}
777
778bool Target::EnableBreakpointByID(break_id_t break_id) {
779 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
780 if (log)
781 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
782 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
783
784 BreakpointSP bp_sp;
785
786 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
787 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
788 else
789 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
790
791 if (bp_sp) {
792 bp_sp->SetEnabled(true);
793 return true;
794 }
795 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796}
797
Jim Ingham01f16662016-09-14 19:07:35 +0000798Error Target::SerializeBreakpointsToFile(const FileSpec &file,
Jim Ingham2d3628e2016-09-22 23:42:42 +0000799 const BreakpointIDList &bp_ids,
800 bool append) {
Jim Ingham01f16662016-09-14 19:07:35 +0000801 Error error;
802
803 if (!file) {
804 error.SetErrorString("Invalid FileSpec.");
805 return error;
806 }
807
808 std::string path(file.GetPath());
Jim Ingham2d3628e2016-09-22 23:42:42 +0000809 StructuredData::ObjectSP input_data_sp;
810
811 StructuredData::ArraySP break_store_sp;
812 StructuredData::Array *break_store_ptr = nullptr;
813
814 if (append) {
815 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
816 if (error.Success()) {
817 break_store_ptr = input_data_sp->GetAsArray();
818 if (!break_store_ptr) {
819 error.SetErrorStringWithFormat(
820 "Tried to append to invalid input file %s", path.c_str());
821 return error;
822 }
823 }
824 }
825
826 if (!break_store_ptr) {
827 break_store_sp.reset(new StructuredData::Array());
828 break_store_ptr = break_store_sp.get();
829 }
830
Jim Ingham01f16662016-09-14 19:07:35 +0000831 StreamFile out_file(path.c_str(),
832 File::OpenOptions::eOpenOptionTruncate |
833 File::OpenOptions::eOpenOptionWrite |
834 File::OpenOptions::eOpenOptionCanCreate |
835 File::OpenOptions::eOpenOptionCloseOnExec,
836 lldb::eFilePermissionsFileDefault);
837 if (!out_file.GetFile().IsValid()) {
838 error.SetErrorStringWithFormat("Unable to open output file: %s.",
839 path.c_str());
840 return error;
841 }
842
843 std::unique_lock<std::recursive_mutex> lock;
844 GetBreakpointList().GetListMutex(lock);
845
Jim Ingham01f16662016-09-14 19:07:35 +0000846 if (bp_ids.GetSize() == 0) {
847 const BreakpointList &breakpoints = GetBreakpointList();
848
849 size_t num_breakpoints = breakpoints.GetSize();
850 for (size_t i = 0; i < num_breakpoints; i++) {
851 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
852 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
853 // If a breakpoint can't serialize it, just ignore it for now:
854 if (bkpt_save_sp)
Jim Ingham2d3628e2016-09-22 23:42:42 +0000855 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +0000856 }
857 } else {
858
859 std::unordered_set<lldb::break_id_t> processed_bkpts;
860 const size_t count = bp_ids.GetSize();
861 for (size_t i = 0; i < count; ++i) {
862 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
863 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
864
865 if (bp_id != LLDB_INVALID_BREAK_ID) {
866 // Only do each breakpoint once:
867 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
868 insert_result = processed_bkpts.insert(bp_id);
869 if (!insert_result.second)
870 continue;
871
872 Breakpoint *bp = GetBreakpointByID(bp_id).get();
873 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
874 // If the user explicitly asked to serialize a breakpoint, and we
875 // can't, then
876 // raise an error:
877 if (!bkpt_save_sp) {
878 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
879 bp_id);
880 return error;
881 }
Jim Ingham2d3628e2016-09-22 23:42:42 +0000882 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +0000883 }
884 }
885 }
886
Jim Ingham2d3628e2016-09-22 23:42:42 +0000887 break_store_ptr->Dump(out_file, false);
Jim Ingham01f16662016-09-14 19:07:35 +0000888 out_file.PutChar('\n');
889 return error;
890}
891
892Error Target::CreateBreakpointsFromFile(const FileSpec &file,
893 BreakpointIDList &new_bps) {
Jim Ingham3acdf382016-09-22 22:20:28 +0000894 std::vector<std::string> no_names;
895 return CreateBreakpointsFromFile(file, no_names, new_bps);
896}
897
898Error Target::CreateBreakpointsFromFile(const FileSpec &file,
899 std::vector<std::string> &names,
900 BreakpointIDList &new_bps) {
Jim Ingham01f16662016-09-14 19:07:35 +0000901 std::unique_lock<std::recursive_mutex> lock;
902 GetBreakpointList().GetListMutex(lock);
903
904 Error error;
905 StructuredData::ObjectSP input_data_sp =
906 StructuredData::ParseJSONFromFile(file, error);
907 if (!error.Success()) {
908 return error;
909 } else if (!input_data_sp || !input_data_sp->IsValid()) {
910 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
911 file.GetPath().c_str());
912 return error;
913 }
914
915 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
916 if (!bkpt_array) {
917 error.SetErrorStringWithFormat(
918 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
919 return error;
920 }
921
922 size_t num_bkpts = bkpt_array->GetSize();
Jim Ingham3acdf382016-09-22 22:20:28 +0000923 size_t num_names = names.size();
924
Jim Ingham01f16662016-09-14 19:07:35 +0000925 for (size_t i = 0; i < num_bkpts; i++) {
926 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
927 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
928 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
929 if (!bkpt_dict) {
930 error.SetErrorStringWithFormat(
931 "Invalid breakpoint data for element %zu from input file: %s.", i,
932 file.GetPath().c_str());
933 return error;
934 }
935 StructuredData::ObjectSP bkpt_data_sp =
936 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
Jim Ingham3acdf382016-09-22 22:20:28 +0000937 if (num_names &&
938 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
939 continue;
940
Jim Ingham01f16662016-09-14 19:07:35 +0000941 BreakpointSP bkpt_sp =
942 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
943 if (!error.Success()) {
944 error.SetErrorStringWithFormat(
945 "Error restoring breakpoint %zu from %s: %s.", i,
946 file.GetPath().c_str(), error.AsCString());
947 return error;
948 }
949 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
950 }
951 return error;
952}
953
Johnny Chenedf50372011-09-23 21:21:43 +0000954// The flag 'end_to_end', default to true, signifies that the operation is
955// performed end to end, for both the debugger and the debuggee.
956
Johnny Chen01a67862011-10-14 00:42:25 +0000957// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
958// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959bool Target::RemoveAllWatchpoints(bool end_to_end) {
960 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
961 if (log)
962 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +0000963
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 if (!end_to_end) {
965 m_watchpoint_list.RemoveAll(true);
966 return true;
967 }
Johnny Chenedf50372011-09-23 21:21:43 +0000968
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +0000970
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 if (!ProcessIsValid())
972 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000973
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 size_t num_watchpoints = m_watchpoint_list.GetSize();
975 for (size_t i = 0; i < num_watchpoints; ++i) {
976 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
977 if (!wp_sp)
978 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000979
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
981 if (rc.Fail())
982 return false;
983 }
984 m_watchpoint_list.RemoveAll(true);
985 m_last_created_watchpoint.reset();
986 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +0000987}
988
Johnny Chen01a67862011-10-14 00:42:25 +0000989// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
990// end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991bool Target::DisableAllWatchpoints(bool end_to_end) {
992 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
993 if (log)
994 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +0000995
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 if (!end_to_end) {
997 m_watchpoint_list.SetEnabledAll(false);
998 return true;
999 }
Johnny Chenedf50372011-09-23 21:21:43 +00001000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 if (!ProcessIsValid())
1004 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001005
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 size_t num_watchpoints = m_watchpoint_list.GetSize();
1007 for (size_t i = 0; i < num_watchpoints; ++i) {
1008 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1009 if (!wp_sp)
1010 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1013 if (rc.Fail())
1014 return false;
1015 }
1016 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001017}
1018
Johnny Chen01a67862011-10-14 00:42:25 +00001019// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
1020// end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021bool Target::EnableAllWatchpoints(bool end_to_end) {
1022 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1023 if (log)
1024 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001025
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 if (!end_to_end) {
1027 m_watchpoint_list.SetEnabledAll(true);
1028 return true;
1029 }
Johnny Chenedf50372011-09-23 21:21:43 +00001030
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001032
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 if (!ProcessIsValid())
1034 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 size_t num_watchpoints = m_watchpoint_list.GetSize();
1037 for (size_t i = 0; i < num_watchpoints; ++i) {
1038 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1039 if (!wp_sp)
1040 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001041
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1043 if (rc.Fail())
1044 return false;
1045 }
1046 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001047}
1048
Johnny Chena4d6bc92012-02-25 06:44:30 +00001049// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050bool Target::ClearAllWatchpointHitCounts() {
1051 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1052 if (log)
1053 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chena4d6bc92012-02-25 06:44:30 +00001054
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 size_t num_watchpoints = m_watchpoint_list.GetSize();
1056 for (size_t i = 0; i < num_watchpoints; ++i) {
1057 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1058 if (!wp_sp)
1059 return false;
Johnny Chena4d6bc92012-02-25 06:44:30 +00001060
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 wp_sp->ResetHitCount();
1062 }
1063 return true; // Success!
Johnny Chena4d6bc92012-02-25 06:44:30 +00001064}
1065
Enrico Granata5e3fe042015-02-11 00:37:54 +00001066// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067bool Target::ClearAllWatchpointHistoricValues() {
1068 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1069 if (log)
1070 log->Printf("Target::%s\n", __FUNCTION__);
1071
1072 size_t num_watchpoints = m_watchpoint_list.GetSize();
1073 for (size_t i = 0; i < num_watchpoints; ++i) {
1074 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1075 if (!wp_sp)
1076 return false;
1077
1078 wp_sp->ResetHistoricValues();
1079 }
1080 return true; // Success!
Enrico Granata5e3fe042015-02-11 00:37:54 +00001081}
1082
Johnny Chen01a67862011-10-14 00:42:25 +00001083// Assumption: Caller holds the list mutex lock for m_watchpoint_list
Johnny Chen6cc60e82011-10-05 21:35:46 +00001084// during these operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1086 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1087 if (log)
1088 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001089
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 if (!ProcessIsValid())
1091 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001092
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 size_t num_watchpoints = m_watchpoint_list.GetSize();
1094 for (size_t i = 0; i < num_watchpoints; ++i) {
1095 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1096 if (!wp_sp)
1097 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001098
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 wp_sp->SetIgnoreCount(ignore_count);
1100 }
1101 return true; // Success!
Johnny Chen6cc60e82011-10-05 21:35:46 +00001102}
1103
Johnny Chen01a67862011-10-14 00:42:25 +00001104// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1106 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1107 if (log)
1108 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001109
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001111 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112
1113 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1114 if (wp_sp) {
1115 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1116 if (rc.Success())
1117 return true;
1118
1119 // Else, fallthrough.
1120 }
1121 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001122}
1123
Johnny Chen01a67862011-10-14 00:42:25 +00001124// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1126 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1127 if (log)
1128 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001129
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001131 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132
1133 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1134 if (wp_sp) {
1135 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1136 if (rc.Success())
1137 return true;
1138
1139 // Else, fallthrough.
1140 }
1141 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001142}
1143
Johnny Chen01a67862011-10-14 00:42:25 +00001144// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1146 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1147 if (log)
1148 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001149
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1151 if (watch_to_remove_sp == m_last_created_watchpoint)
1152 m_last_created_watchpoint.reset();
1153
1154 if (DisableWatchpointByID(watch_id)) {
1155 m_watchpoint_list.Remove(watch_id, true);
1156 return true;
1157 }
1158 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001159}
1160
Johnny Chen01a67862011-10-14 00:42:25 +00001161// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1163 uint32_t ignore_count) {
1164 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1165 if (log)
1166 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001167
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 if (!ProcessIsValid())
Johnny Chen6cc60e82011-10-05 21:35:46 +00001169 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170
1171 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1172 if (wp_sp) {
1173 wp_sp->SetIgnoreCount(ignore_count);
1174 return true;
1175 }
1176 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001177}
1178
Kate Stoneb9c1b512016-09-06 20:57:50 +00001179ModuleSP Target::GetExecutableModule() {
1180 // search for the first executable in the module list
1181 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1182 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1183 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1184 if (obj == nullptr)
1185 continue;
1186 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1187 return module_sp;
1188 }
1189 // as fall back return the first module loaded
1190 return m_images.GetModuleAtIndex(0);
Greg Claytonaa149cb2011-08-11 02:48:45 +00001191}
1192
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193Module *Target::GetExecutableModulePointer() {
1194 return GetExecutableModule().get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195}
1196
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1198 Target *target) {
1199 Error error;
1200 StreamString feedback_stream;
1201 if (module_sp &&
1202 !module_sp->LoadScriptingResourceInTarget(target, error,
1203 &feedback_stream)) {
1204 if (error.AsCString())
1205 target->GetDebugger().GetErrorFile()->Printf(
1206 "unable to load scripting data for module %s - error reported was "
1207 "%s\n",
1208 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1209 error.AsCString());
1210 }
1211 if (feedback_stream.GetSize())
1212 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1213 feedback_stream.GetData());
Enrico Granata17598482012-11-08 02:22:02 +00001214}
1215
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216void Target::ClearModules(bool delete_locations) {
1217 ModulesDidUnload(m_images, delete_locations);
1218 m_section_load_history.Clear();
1219 m_images.Clear();
1220 m_scratch_type_system_map.Clear();
1221 m_ast_importer_sp.reset();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001222}
1223
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224void Target::DidExec() {
1225 // When a process exec's we need to know about it so we can do some cleanup.
1226 m_breakpoint_list.RemoveInvalidLocations(m_arch);
1227 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
Greg Claytonb35db632013-11-09 00:03:31 +00001228}
1229
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230void Target::SetExecutableModule(ModuleSP &executable_sp,
1231 bool get_dependent_files) {
1232 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1233 ClearModules(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001234
Kate Stoneb9c1b512016-09-06 20:57:50 +00001235 if (executable_sp) {
1236 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
1237 "Target::SetExecutableModule (executable = '%s')",
1238 executable_sp->GetFileSpec().GetPath().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001239
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 m_images.Append(executable_sp); // The first image is our executable file
Jason Molendae1b68ad2012-12-05 00:25:49 +00001241
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 // If we haven't set an architecture yet, reset our architecture based on
1243 // what we found in the executable module.
1244 if (!m_arch.IsValid()) {
1245 m_arch = executable_sp->GetArchitecture();
1246 if (log)
1247 log->Printf("Target::SetExecutableModule setting architecture to %s "
1248 "(%s) based on executable file",
1249 m_arch.GetArchitectureName(),
1250 m_arch.GetTriple().getTriple().c_str());
Jason Molendadad8af42015-11-10 04:11:37 +00001251 }
1252
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 FileSpecList dependent_files;
1254 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001255
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 if (executable_objfile && get_dependent_files) {
1257 executable_objfile->GetDependentModules(dependent_files);
1258 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1259 FileSpec dependent_file_spec(
1260 dependent_files.GetFileSpecPointerAtIndex(i));
1261 FileSpec platform_dependent_file_spec;
Greg Clayton67cc0632012-08-22 17:17:09 +00001262 if (m_platform_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1264 platform_dependent_file_spec);
1265 else
1266 platform_dependent_file_spec = dependent_file_spec;
1267
1268 ModuleSpec module_spec(platform_dependent_file_spec, m_arch);
1269 ModuleSP image_module_sp(GetSharedModule(module_spec));
1270 if (image_module_sp) {
1271 ObjectFile *objfile = image_module_sp->GetObjectFile();
1272 if (objfile)
1273 objfile->GetDependentModules(dependent_files);
1274 }
1275 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001276 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001278}
1279
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280bool Target::SetArchitecture(const ArchSpec &arch_spec) {
1281 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1282 bool missing_local_arch = !m_arch.IsValid();
1283 bool replace_local_arch = true;
1284 bool compatible_local_arch = false;
1285 ArchSpec other(arch_spec);
Greg Claytone72dfb32012-02-24 01:59:29 +00001286
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 if (!missing_local_arch) {
1288 if (m_arch.IsCompatibleMatch(arch_spec)) {
1289 other.MergeFrom(m_arch);
1290
1291 if (m_arch.IsCompatibleMatch(other)) {
1292 compatible_local_arch = true;
1293 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1294 env_changed;
1295
1296 m_arch.PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1297 os_changed, os_ver_changed, env_changed);
1298
1299 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1300 replace_local_arch = false;
1301 }
1302 }
1303 }
1304
1305 if (compatible_local_arch || missing_local_arch) {
1306 // If we haven't got a valid arch spec, or the architectures are compatible
1307 // update the architecture, unless the one we already have is more specified
1308 if (replace_local_arch)
1309 m_arch = other;
1310 if (log)
1311 log->Printf("Target::SetArchitecture set architecture to %s (%s)",
1312 m_arch.GetArchitectureName(),
1313 m_arch.GetTriple().getTriple().c_str());
1314 return true;
1315 }
1316
1317 // If we have an executable file, try to reset the executable to the desired
1318 // architecture
1319 if (log)
1320 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1321 arch_spec.GetArchitectureName(),
1322 arch_spec.GetTriple().getTriple().c_str());
1323 m_arch = other;
1324 ModuleSP executable_sp = GetExecutableModule();
1325
1326 ClearModules(true);
1327 // Need to do something about unsetting breakpoints.
1328
1329 if (executable_sp) {
1330 if (log)
1331 log->Printf("Target::SetArchitecture Trying to select executable file "
1332 "architecture %s (%s)",
1333 arch_spec.GetArchitectureName(),
1334 arch_spec.GetTriple().getTriple().c_str());
1335 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1336 Error error = ModuleList::GetSharedModule(module_spec, executable_sp,
1337 &GetExecutableSearchPaths(),
1338 nullptr, nullptr);
1339
1340 if (!error.Fail() && executable_sp) {
1341 SetExecutableModule(executable_sp, true);
1342 return true;
1343 }
1344 }
1345 return false;
Greg Claytondb598232011-01-07 01:57:07 +00001346}
1347
Kate Stoneb9c1b512016-09-06 20:57:50 +00001348bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1349 if (arch_spec.IsValid()) {
1350 if (m_arch.IsCompatibleMatch(arch_spec)) {
1351 // The current target arch is compatible with "arch_spec", see if we
1352 // can improve our current architecture using bits from "arch_spec"
Greg Claytonc749eb82011-07-11 05:12:02 +00001353
Kate Stoneb9c1b512016-09-06 20:57:50 +00001354 // Merge bits from arch_spec into "merged_arch" and set our architecture
1355 ArchSpec merged_arch(m_arch);
1356 merged_arch.MergeFrom(arch_spec);
1357 return SetArchitecture(merged_arch);
1358 } else {
1359 // The new architecture is different, we just need to replace it
1360 return SetArchitecture(arch_spec);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001361 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 }
1363 return false;
1364}
Greg Claytonc749eb82011-07-11 05:12:02 +00001365
Kate Stoneb9c1b512016-09-06 20:57:50 +00001366void Target::WillClearList(const ModuleList &module_list) {}
1367
1368void Target::ModuleAdded(const ModuleList &module_list,
1369 const ModuleSP &module_sp) {
1370 // A module is being added to this target for the first time
1371 if (m_valid) {
1372 ModuleList my_module_list;
1373 my_module_list.Append(module_sp);
1374 LoadScriptingResourceForModule(module_sp, this);
1375 ModulesDidLoad(my_module_list);
1376 }
1377}
1378
1379void Target::ModuleRemoved(const ModuleList &module_list,
1380 const ModuleSP &module_sp) {
1381 // A module is being removed from this target.
1382 if (m_valid) {
1383 ModuleList my_module_list;
1384 my_module_list.Append(module_sp);
1385 ModulesDidUnload(my_module_list, false);
1386 }
1387}
1388
1389void Target::ModuleUpdated(const ModuleList &module_list,
1390 const ModuleSP &old_module_sp,
1391 const ModuleSP &new_module_sp) {
1392 // A module is replacing an already added module
1393 if (m_valid) {
1394 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1395 new_module_sp);
1396 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1397 old_module_sp, new_module_sp);
1398 }
1399}
1400
1401void Target::ModulesDidLoad(ModuleList &module_list) {
1402 if (m_valid && module_list.GetSize()) {
1403 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1404 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1405 if (m_process_sp) {
1406 m_process_sp->ModulesDidLoad(module_list);
1407 }
1408 BroadcastEvent(eBroadcastBitModulesLoaded,
1409 new TargetEventData(this->shared_from_this(), module_list));
1410 }
1411}
1412
1413void Target::SymbolsDidLoad(ModuleList &module_list) {
1414 if (m_valid && module_list.GetSize()) {
1415 if (m_process_sp) {
1416 LanguageRuntime *runtime =
1417 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1418 if (runtime) {
1419 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1420 objc_runtime->SymbolsDidLoad(module_list);
1421 }
1422 }
1423
1424 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1425 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1426 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1427 new TargetEventData(this->shared_from_this(), module_list));
1428 }
1429}
1430
1431void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1432 if (m_valid && module_list.GetSize()) {
1433 UnloadModuleSections(module_list);
1434 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1435 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1436 delete_locations);
1437 BroadcastEvent(eBroadcastBitModulesUnloaded,
1438 new TargetEventData(this->shared_from_this(), module_list));
1439 }
1440}
1441
1442bool Target::ModuleIsExcludedForUnconstrainedSearches(
1443 const FileSpec &module_file_spec) {
1444 if (GetBreakpointsConsultPlatformAvoidList()) {
1445 ModuleList matchingModules;
1446 ModuleSpec module_spec(module_file_spec);
1447 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1448
1449 // If there is more than one module for this file spec, only return true if
1450 // ALL the modules are on the
1451 // black list.
1452 if (num_modules > 0) {
1453 for (size_t i = 0; i < num_modules; i++) {
1454 if (!ModuleIsExcludedForUnconstrainedSearches(
1455 matchingModules.GetModuleAtIndex(i)))
1456 return false;
1457 }
1458 return true;
1459 }
1460 }
1461 return false;
1462}
1463
1464bool Target::ModuleIsExcludedForUnconstrainedSearches(
1465 const lldb::ModuleSP &module_sp) {
1466 if (GetBreakpointsConsultPlatformAvoidList()) {
1467 if (m_platform_sp)
1468 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1469 module_sp);
1470 }
1471 return false;
1472}
1473
1474size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1475 size_t dst_len, Error &error) {
1476 SectionSP section_sp(addr.GetSection());
1477 if (section_sp) {
1478 // If the contents of this section are encrypted, the on-disk file is
1479 // unusable. Read only from live memory.
1480 if (section_sp->IsEncrypted()) {
1481 error.SetErrorString("section is encrypted");
1482 return 0;
1483 }
1484 ModuleSP module_sp(section_sp->GetModule());
1485 if (module_sp) {
1486 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1487 if (objfile) {
1488 size_t bytes_read = objfile->ReadSectionData(
1489 section_sp.get(), addr.GetOffset(), dst, dst_len);
Greg Claytondb598232011-01-07 01:57:07 +00001490 if (bytes_read > 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001492 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493 error.SetErrorStringWithFormat("error reading data from section %s",
1494 section_sp->GetName().GetCString());
1495 } else
1496 error.SetErrorString("address isn't from a object file");
1497 } else
1498 error.SetErrorString("address isn't in a module");
1499 } else
1500 error.SetErrorString("address doesn't contain a section that points to a "
1501 "section in a object file");
1502
1503 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504}
1505
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1507 void *dst, size_t dst_len, Error &error,
1508 lldb::addr_t *load_addr_ptr) {
1509 error.Clear();
1510
1511 // if we end up reading this from process memory, we will fill this
1512 // with the actual load address
1513 if (load_addr_ptr)
1514 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1515
1516 size_t bytes_read = 0;
1517
1518 addr_t load_addr = LLDB_INVALID_ADDRESS;
1519 addr_t file_addr = LLDB_INVALID_ADDRESS;
1520 Address resolved_addr;
1521 if (!addr.IsSectionOffset()) {
1522 SectionLoadList &section_load_list = GetSectionLoadList();
1523 if (section_load_list.IsEmpty()) {
1524 // No sections are loaded, so we must assume we are not running
1525 // yet and anything we are given is a file address.
1526 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1527 // offset is the file address
1528 m_images.ResolveFileAddress(file_addr, resolved_addr);
1529 } else {
1530 // We have at least one section loaded. This can be because
1531 // we have manually loaded some sections with "target modules load ..."
1532 // or because we have have a live process that has sections loaded
1533 // through the dynamic loader
1534 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1535 // offset is the load address
1536 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1537 }
1538 }
1539 if (!resolved_addr.IsValid())
1540 resolved_addr = addr;
1541
1542 if (prefer_file_cache) {
1543 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1544 if (bytes_read > 0)
1545 return bytes_read;
1546 }
1547
1548 if (ProcessIsValid()) {
1549 if (load_addr == LLDB_INVALID_ADDRESS)
1550 load_addr = resolved_addr.GetLoadAddress(this);
1551
1552 if (load_addr == LLDB_INVALID_ADDRESS) {
1553 ModuleSP addr_module_sp(resolved_addr.GetModule());
1554 if (addr_module_sp && addr_module_sp->GetFileSpec())
1555 error.SetErrorStringWithFormat(
1556 "%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1557 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
1558 resolved_addr.GetFileAddress(),
1559 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknonw>"));
1560 else
1561 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1562 resolved_addr.GetFileAddress());
1563 } else {
1564 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1565 if (bytes_read != dst_len) {
1566 if (error.Success()) {
1567 if (bytes_read == 0)
1568 error.SetErrorStringWithFormat(
1569 "read memory from 0x%" PRIx64 " failed", load_addr);
1570 else
1571 error.SetErrorStringWithFormat(
1572 "only %" PRIu64 " of %" PRIu64
1573 " bytes were read from memory at 0x%" PRIx64,
1574 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1575 }
1576 }
1577 if (bytes_read) {
1578 if (load_addr_ptr)
1579 *load_addr_ptr = load_addr;
1580 return bytes_read;
1581 }
1582 // If the address is not section offset we have an address that
1583 // doesn't resolve to any address in any currently loaded shared
1584 // libraries and we failed to read memory so there isn't anything
1585 // more we can do. If it is section offset, we might be able to
1586 // read cached memory from the object file.
1587 if (!resolved_addr.IsSectionOffset())
1588 return 0;
1589 }
1590 }
1591
1592 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1593 // If we didn't already try and read from the object file cache, then
1594 // try it after failing to read from the process.
1595 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1596 }
1597 return 0;
1598}
1599
1600size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1601 Error &error) {
1602 char buf[256];
1603 out_str.clear();
1604 addr_t curr_addr = addr.GetLoadAddress(this);
1605 Address address(addr);
1606 while (1) {
1607 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1608 if (length == 0)
1609 break;
1610 out_str.append(buf, length);
1611 // If we got "length - 1" bytes, we didn't get the whole C string, we
1612 // need to read some more characters
1613 if (length == sizeof(buf) - 1)
1614 curr_addr += length;
1615 else
1616 break;
1617 address = Address(curr_addr);
1618 }
1619 return out_str.size();
1620}
1621
1622size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1623 size_t dst_max_len, Error &result_error) {
1624 size_t total_cstr_len = 0;
1625 if (dst && dst_max_len) {
1626 result_error.Clear();
1627 // NULL out everything just to be safe
1628 memset(dst, 0, dst_max_len);
1629 Error error;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001630 addr_t curr_addr = addr.GetLoadAddress(this);
1631 Address address(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632
1633 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't
1634 // think this really needs to be tied to the memory cache subsystem's
1635 // cache line size, so leave this as a fixed constant.
1636 const size_t cache_line_size = 512;
1637
1638 size_t bytes_left = dst_max_len - 1;
1639 char *curr_dst = dst;
1640
1641 while (bytes_left > 0) {
1642 addr_t cache_line_bytes_left =
1643 cache_line_size - (curr_addr % cache_line_size);
1644 addr_t bytes_to_read =
1645 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1646 size_t bytes_read =
1647 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1648
1649 if (bytes_read == 0) {
1650 result_error = error;
1651 dst[total_cstr_len] = '\0';
1652 break;
1653 }
1654 const size_t len = strlen(curr_dst);
1655
1656 total_cstr_len += len;
1657
1658 if (len < bytes_to_read)
1659 break;
1660
1661 curr_dst += bytes_read;
1662 curr_addr += bytes_read;
1663 bytes_left -= bytes_read;
1664 address = Address(curr_addr);
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001665 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 } else {
1667 if (dst == nullptr)
1668 result_error.SetErrorString("invalid arguments");
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001669 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001670 result_error.Clear();
1671 }
1672 return total_cstr_len;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001673}
1674
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1676 bool prefer_file_cache,
1677 uint32_t byte_size, bool is_signed,
1678 Scalar &scalar, Error &error) {
1679 uint64_t uval;
1680
1681 if (byte_size <= sizeof(uval)) {
1682 size_t bytes_read =
1683 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1684 if (bytes_read == byte_size) {
1685 DataExtractor data(&uval, sizeof(uval), m_arch.GetByteOrder(),
1686 m_arch.GetAddressByteSize());
1687 lldb::offset_t offset = 0;
1688 if (byte_size <= 4)
1689 scalar = data.GetMaxU32(&offset, byte_size);
1690 else
1691 scalar = data.GetMaxU64(&offset, byte_size);
1692
1693 if (is_signed)
1694 scalar.SignExtend(byte_size * 8);
1695 return bytes_read;
1696 }
1697 } else {
1698 error.SetErrorStringWithFormat(
1699 "byte size of %u is too large for integer scalar type", byte_size);
1700 }
1701 return 0;
1702}
1703
1704uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1705 bool prefer_file_cache,
1706 size_t integer_byte_size,
1707 uint64_t fail_value,
1708 Error &error) {
1709 Scalar scalar;
1710 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1711 false, scalar, error))
1712 return scalar.ULongLong(fail_value);
1713 return fail_value;
1714}
1715
1716bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1717 Error &error, Address &pointer_addr) {
1718 Scalar scalar;
1719 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1720 m_arch.GetAddressByteSize(), false, scalar,
1721 error)) {
1722 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1723 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1724 SectionLoadList &section_load_list = GetSectionLoadList();
1725 if (section_load_list.IsEmpty()) {
1726 // No sections are loaded, so we must assume we are not running
1727 // yet and anything we are given is a file address.
1728 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1729 } else {
1730 // We have at least one section loaded. This can be because
1731 // we have manually loaded some sections with "target modules load ..."
1732 // or because we have have a live process that has sections loaded
1733 // through the dynamic loader
1734 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1735 }
1736 // We weren't able to resolve the pointer value, so just return
1737 // an address with no section
1738 if (!pointer_addr.IsValid())
1739 pointer_addr.SetOffset(pointer_vm_addr);
1740 return true;
1741 }
1742 }
1743 return false;
1744}
1745
1746ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
1747 Error *error_ptr) {
1748 ModuleSP module_sp;
1749
1750 Error error;
1751
1752 // First see if we already have this module in our module list. If we do,
1753 // then we're done, we don't need
1754 // to consult the shared modules list. But only do this if we are passed a
1755 // UUID.
1756
1757 if (module_spec.GetUUID().IsValid())
1758 module_sp = m_images.FindFirstModule(module_spec);
1759
1760 if (!module_sp) {
1761 ModuleSP old_module_sp; // This will get filled in if we have a new version
1762 // of the library
1763 bool did_create_module = false;
1764
1765 // If there are image search path entries, try to use them first to acquire
1766 // a suitable image.
1767 if (m_image_search_paths.GetSize()) {
1768 ModuleSpec transformed_spec(module_spec);
1769 if (m_image_search_paths.RemapPath(
1770 module_spec.GetFileSpec().GetDirectory(),
1771 transformed_spec.GetFileSpec().GetDirectory())) {
1772 transformed_spec.GetFileSpec().GetFilename() =
1773 module_spec.GetFileSpec().GetFilename();
1774 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1775 &GetExecutableSearchPaths(),
1776 &old_module_sp, &did_create_module);
1777 }
1778 }
1779
1780 if (!module_sp) {
1781 // If we have a UUID, we can check our global shared module list in case
1782 // we already have it. If we don't have a valid UUID, then we can't since
1783 // the path in "module_spec" will be a platform path, and we will need to
1784 // let the platform find that file. For example, we could be asking for
1785 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1786 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1787 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1788 // cache.
1789 if (module_spec.GetUUID().IsValid()) {
1790 // We have a UUID, it is OK to check the global module list...
1791 error = ModuleList::GetSharedModule(module_spec, module_sp,
1792 &GetExecutableSearchPaths(),
1793 &old_module_sp, &did_create_module);
1794 }
1795
1796 if (!module_sp) {
1797 // The platform is responsible for finding and caching an appropriate
1798 // module in the shared module cache.
1799 if (m_platform_sp) {
1800 error = m_platform_sp->GetSharedModule(
1801 module_spec, m_process_sp.get(), module_sp,
1802 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
1803 } else {
1804 error.SetErrorString("no platform is currently set");
Greg Claytond16e1e52011-07-12 17:06:17 +00001805 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001807 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001808
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809 // We found a module that wasn't in our target list. Let's make sure that
1810 // there wasn't an equivalent
1811 // module in the list already, and if there was, let's remove it.
1812 if (module_sp) {
1813 ObjectFile *objfile = module_sp->GetObjectFile();
1814 if (objfile) {
1815 switch (objfile->GetType()) {
1816 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
1817 /// a program's execution state
1818 case ObjectFile::eTypeExecutable: /// A normal executable
1819 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
1820 /// executable
1821 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1822 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
1823 /// used during execution
1824 break;
1825 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
1826 /// debug information
1827 if (error_ptr)
1828 error_ptr->SetErrorString("debug info files aren't valid target "
1829 "modules, please specify an executable");
1830 return ModuleSP();
1831 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
1832 /// against but not used for
1833 /// execution
1834 if (error_ptr)
1835 error_ptr->SetErrorString("stub libraries aren't valid target "
1836 "modules, please specify an executable");
1837 return ModuleSP();
1838 default:
1839 if (error_ptr)
1840 error_ptr->SetErrorString(
1841 "unsupported file type, please specify an executable");
1842 return ModuleSP();
Greg Claytond16e1e52011-07-12 17:06:17 +00001843 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844 // GetSharedModule is not guaranteed to find the old shared module, for
1845 // instance
1846 // in the common case where you pass in the UUID, it is only going to
1847 // find the one
1848 // module matching the UUID. In fact, it has no good way to know what
1849 // the "old module"
1850 // relevant to this target is, since there might be many copies of a
1851 // module with this file spec
1852 // in various running debug sessions, but only one of them will belong
1853 // to this target.
1854 // So let's remove the UUID from the module list, and look in the
1855 // target's module list.
1856 // Only do this if there is SOMETHING else in the module spec...
1857 if (!old_module_sp) {
1858 if (module_spec.GetUUID().IsValid() &&
1859 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
1860 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
1861 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1862 module_spec_copy.GetUUID().Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001863
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864 ModuleList found_modules;
1865 size_t num_found =
1866 m_images.FindModules(module_spec_copy, found_modules);
1867 if (num_found == 1) {
1868 old_module_sp = found_modules.GetModuleAtIndex(0);
Jim Ingham4a94c912012-05-17 18:38:42 +00001869 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001870 }
Greg Claytonb69bb2e2012-04-27 00:58:27 +00001871 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001872
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873 if (old_module_sp &&
1874 m_images.GetIndexForModule(old_module_sp.get()) !=
1875 LLDB_INVALID_INDEX32) {
1876 m_images.ReplaceModule(old_module_sp, module_sp);
1877 Module *old_module_ptr = old_module_sp.get();
1878 old_module_sp.reset();
1879 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
1880 } else
1881 m_images.Append(module_sp);
1882 } else
1883 module_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001884 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001885 }
1886 if (error_ptr)
1887 *error_ptr = error;
1888 return module_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889}
1890
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891TargetSP Target::CalculateTarget() { return shared_from_this(); }
1892
1893ProcessSP Target::CalculateProcess() { return m_process_sp; }
1894
1895ThreadSP Target::CalculateThread() { return ThreadSP(); }
1896
1897StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
1898
1899void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1900 exe_ctx.Clear();
1901 exe_ctx.SetTargetPtr(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902}
1903
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904PathMappingList &Target::GetImageSearchPathList() {
1905 return m_image_search_paths;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001906}
1907
Kate Stoneb9c1b512016-09-06 20:57:50 +00001908void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
1909 void *baton) {
1910 Target *target = (Target *)baton;
1911 ModuleSP exe_module_sp(target->GetExecutableModule());
1912 if (exe_module_sp)
1913 target->SetExecutableModule(exe_module_sp, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001914}
1915
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916TypeSystem *Target::GetScratchTypeSystemForLanguage(Error *error,
1917 lldb::LanguageType language,
1918 bool create_on_demand) {
1919 if (!m_valid)
1920 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 if (error) {
1923 error->Clear();
1924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001925
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
1927 // assembly code
1928 || language == eLanguageTypeUnknown) {
1929 std::set<lldb::LanguageType> languages_for_types;
1930 std::set<lldb::LanguageType> languages_for_expressions;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001931
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
1933 languages_for_expressions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001934
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 if (languages_for_expressions.count(eLanguageTypeC)) {
1936 language = eLanguageTypeC; // LLDB's default. Override by setting the
1937 // target language.
1938 } else {
1939 if (languages_for_expressions.empty()) {
Greg Clayton5beec212015-10-08 21:04:34 +00001940 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 } else {
1942 language = *languages_for_expressions.begin();
1943 }
Sean Callanana994b0b2015-10-02 18:40:30 +00001944 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001945 }
Sean Callananb92bd752015-10-01 16:28:02 +00001946
Kate Stoneb9c1b512016-09-06 20:57:50 +00001947 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
1948 create_on_demand);
Sean Callananb92bd752015-10-01 16:28:02 +00001949}
1950
1951PersistentExpressionState *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
1953 TypeSystem *type_system =
1954 GetScratchTypeSystemForLanguage(nullptr, language, true);
1955
1956 if (type_system) {
1957 return type_system->GetPersistentExpressionState();
1958 } else {
1959 return nullptr;
1960 }
Jim Ingham151c0322015-09-15 21:13:50 +00001961}
1962
Kate Stoneb9c1b512016-09-06 20:57:50 +00001963UserExpression *Target::GetUserExpressionForLanguage(
1964 const char *expr, const char *expr_prefix, lldb::LanguageType language,
1965 Expression::ResultType desired_type,
1966 const EvaluateExpressionOptions &options, Error &error) {
1967 Error type_system_error;
1968
1969 TypeSystem *type_system =
1970 GetScratchTypeSystemForLanguage(&type_system_error, language);
1971 UserExpression *user_expr = nullptr;
1972
1973 if (!type_system) {
1974 error.SetErrorStringWithFormat(
1975 "Could not find type system for language %s: %s",
1976 Language::GetNameForLanguageType(language),
1977 type_system_error.AsCString());
1978 return nullptr;
1979 }
1980
1981 user_expr = type_system->GetUserExpression(expr, expr_prefix, language,
1982 desired_type, options);
1983 if (!user_expr)
1984 error.SetErrorStringWithFormat(
1985 "Could not create an expression for language %s",
1986 Language::GetNameForLanguageType(language));
1987
1988 return user_expr;
Jim Ingham151c0322015-09-15 21:13:50 +00001989}
1990
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991FunctionCaller *Target::GetFunctionCallerForLanguage(
1992 lldb::LanguageType language, const CompilerType &return_type,
1993 const Address &function_address, const ValueList &arg_value_list,
1994 const char *name, Error &error) {
1995 Error type_system_error;
1996 TypeSystem *type_system =
1997 GetScratchTypeSystemForLanguage(&type_system_error, language);
1998 FunctionCaller *persistent_fn = nullptr;
1999
2000 if (!type_system) {
2001 error.SetErrorStringWithFormat(
2002 "Could not find type system for language %s: %s",
2003 Language::GetNameForLanguageType(language),
2004 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002005 return persistent_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 }
2007
2008 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2009 arg_value_list, name);
2010 if (!persistent_fn)
2011 error.SetErrorStringWithFormat(
2012 "Could not create an expression for language %s",
2013 Language::GetNameForLanguageType(language));
2014
2015 return persistent_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002016}
2017
2018UtilityFunction *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019Target::GetUtilityFunctionForLanguage(const char *text,
2020 lldb::LanguageType language,
2021 const char *name, Error &error) {
2022 Error type_system_error;
2023 TypeSystem *type_system =
2024 GetScratchTypeSystemForLanguage(&type_system_error, language);
2025 UtilityFunction *utility_fn = nullptr;
2026
2027 if (!type_system) {
2028 error.SetErrorStringWithFormat(
2029 "Could not find type system for language %s: %s",
2030 Language::GetNameForLanguageType(language),
2031 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002032 return utility_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002033 }
2034
2035 utility_fn = type_system->GetUtilityFunction(text, name);
2036 if (!utility_fn)
2037 error.SetErrorStringWithFormat(
2038 "Could not create an expression for language %s",
2039 Language::GetNameForLanguageType(language));
2040
2041 return utility_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002042}
2043
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2045 if (m_valid) {
2046 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2047 nullptr, eLanguageTypeC, create_on_demand))
2048 return llvm::dyn_cast<ClangASTContext>(type_system);
2049 }
2050 return nullptr;
2051}
2052
2053ClangASTImporterSP Target::GetClangASTImporter() {
2054 if (m_valid) {
2055 if (!m_ast_importer_sp) {
2056 m_ast_importer_sp.reset(new ClangASTImporter());
Sean Callanan4bf80d52011-11-15 22:27:19 +00002057 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002058 return m_ast_importer_sp;
2059 }
2060 return ClangASTImporterSP();
Sean Callananb92bd752015-10-01 16:28:02 +00002061}
2062
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2064
2065void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2066
2067FileSpecList Target::GetDefaultExecutableSearchPaths() {
2068 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2069 if (properties_sp)
2070 return properties_sp->GetExecutableSearchPaths();
2071 return FileSpecList();
Sean Callanan686b2312011-11-16 18:20:47 +00002072}
2073
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2075 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2076 if (properties_sp)
2077 return properties_sp->GetDebugFileSearchPaths();
2078 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002079}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002080
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2082 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2083 if (properties_sp)
2084 return properties_sp->GetClangModuleSearchPaths();
2085 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002086}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002087
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088ArchSpec Target::GetDefaultArchitecture() {
2089 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2090 if (properties_sp)
2091 return properties_sp->GetDefaultArchitecture();
2092 return ArchSpec();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002093}
2094
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2096 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2097 if (properties_sp) {
2098 LogIfAnyCategoriesSet(
2099 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2100 "default architecture to %s (%s)",
2101 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2102 return properties_sp->SetDefaultArchitecture(arch);
2103 }
Michael Sartaina7499c92013-07-01 19:45:50 +00002104}
2105
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2107 const SymbolContext *sc_ptr) {
2108 // The target can either exist in the "process" of ExecutionContext, or in
2109 // the "target_sp" member of SymbolContext. This accessor helper function
2110 // will get the target from one of these locations.
2111
2112 Target *target = nullptr;
2113 if (sc_ptr != nullptr)
2114 target = sc_ptr->target_sp.get();
2115 if (target == nullptr && exe_ctx_ptr)
2116 target = exe_ctx_ptr->GetTargetPtr();
2117 return target;
Sean Callanan85054342015-04-03 15:39:47 +00002118}
2119
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120ExpressionResults Target::EvaluateExpression(
2121 const char *expr_cstr, ExecutionContextScope *exe_scope,
2122 lldb::ValueObjectSP &result_valobj_sp,
2123 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2124 result_valobj_sp.reset();
Caroline Ticedaccaa92010-09-20 20:44:43 +00002125
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 ExpressionResults execution_results = eExpressionSetupError;
Caroline Ticedaccaa92010-09-20 20:44:43 +00002127
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 if (expr_cstr == nullptr || expr_cstr[0] == '\0')
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002129 return execution_results;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002130
2131 // We shouldn't run stop hooks in expressions.
2132 // Be sure to reset this if you return anywhere within this function.
2133 bool old_suppress_value = m_suppress_stop_hooks;
2134 m_suppress_stop_hooks = true;
2135
2136 ExecutionContext exe_ctx;
2137
2138 if (exe_scope) {
2139 exe_scope->CalculateExecutionContext(exe_ctx);
2140 } else if (m_process_sp) {
2141 m_process_sp->CalculateExecutionContext(exe_ctx);
2142 } else {
2143 CalculateExecutionContext(exe_ctx);
2144 }
2145
2146 // Make sure we aren't just trying to see the value of a persistent
2147 // variable (something like "$0")
2148 lldb::ExpressionVariableSP persistent_var_sp;
2149 // Only check for persistent variables the expression starts with a '$'
2150 if (expr_cstr[0] == '$')
2151 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2152 ->GetPersistentExpressionState()
2153 ->GetVariable(expr_cstr);
2154
2155 if (persistent_var_sp) {
2156 result_valobj_sp = persistent_var_sp->GetValueObject();
2157 execution_results = eExpressionCompleted;
2158 } else {
2159 const char *prefix = GetExpressionPrefixContentsAsCString();
2160 Error error;
2161 execution_results = UserExpression::Evaluate(
2162 exe_ctx, options, expr_cstr, prefix, result_valobj_sp, error,
2163 0, // Line Number
2164 fixed_expression);
2165 }
2166
2167 m_suppress_stop_hooks = old_suppress_value;
2168
2169 return execution_results;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002170}
2171
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002172lldb::ExpressionVariableSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173Target::GetPersistentVariable(const ConstString &name) {
2174 lldb::ExpressionVariableSP variable_sp;
2175 m_scratch_type_system_map.ForEach(
2176 [this, name, &variable_sp](TypeSystem *type_system) -> bool {
2177 if (PersistentExpressionState *persistent_state =
2178 type_system->GetPersistentExpressionState()) {
2179 variable_sp = persistent_state->GetVariable(name);
Greg Clayton5beec212015-10-08 21:04:34 +00002180
Kate Stoneb9c1b512016-09-06 20:57:50 +00002181 if (variable_sp)
2182 return false; // Stop iterating the ForEach
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002183 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 return true; // Keep iterating the ForEach
2185 });
2186 return variable_sp;
Zachary Turner32abc6e2015-03-03 19:23:09 +00002187}
2188
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2190 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2191
2192 m_scratch_type_system_map.ForEach(
2193 [this, name, &address](TypeSystem *type_system) -> bool {
2194 if (PersistentExpressionState *persistent_state =
2195 type_system->GetPersistentExpressionState()) {
2196 address = persistent_state->LookupSymbol(name);
2197 if (address != LLDB_INVALID_ADDRESS)
2198 return false; // Stop iterating the ForEach
Sean Callananb92bd752015-10-01 16:28:02 +00002199 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 return true; // Keep iterating the ForEach
2201 });
2202 return address;
Sean Callananb92bd752015-10-01 16:28:02 +00002203}
2204
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2206 AddressClass addr_class) const {
2207 addr_t code_addr = load_addr;
2208 switch (m_arch.GetMachine()) {
2209 case llvm::Triple::mips:
2210 case llvm::Triple::mipsel:
2211 case llvm::Triple::mips64:
2212 case llvm::Triple::mips64el:
2213 switch (addr_class) {
2214 case eAddressClassData:
2215 case eAddressClassDebug:
2216 return LLDB_INVALID_ADDRESS;
Jaydeep Patil44d07fc2015-09-22 06:36:56 +00002217
Kate Stoneb9c1b512016-09-06 20:57:50 +00002218 case eAddressClassUnknown:
2219 case eAddressClassInvalid:
2220 case eAddressClassCode:
2221 case eAddressClassCodeAlternateISA:
2222 case eAddressClassRuntime:
2223 if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2224 code_addr |= 1ull;
2225 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002226 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002228
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 case llvm::Triple::arm:
2230 case llvm::Triple::thumb:
2231 switch (addr_class) {
2232 case eAddressClassData:
2233 case eAddressClassDebug:
2234 return LLDB_INVALID_ADDRESS;
2235
2236 case eAddressClassUnknown:
2237 case eAddressClassInvalid:
2238 case eAddressClassCode:
2239 case eAddressClassCodeAlternateISA:
2240 case eAddressClassRuntime:
2241 // Check if bit zero it no set?
2242 if ((code_addr & 1ull) == 0) {
2243 // Bit zero isn't set, check if the address is a multiple of 2?
2244 if (code_addr & 2ull) {
2245 // The address is a multiple of 2 so it must be thumb, set bit zero
2246 code_addr |= 1ull;
2247 } else if (addr_class == eAddressClassCodeAlternateISA) {
2248 // We checked the address and the address claims to be the alternate
2249 // ISA
2250 // which means thumb, so set bit zero.
2251 code_addr |= 1ull;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002253 }
2254 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002255 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 break;
2257
2258 default:
2259 break;
2260 }
2261 return code_addr;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002262}
2263
Kate Stoneb9c1b512016-09-06 20:57:50 +00002264lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2265 AddressClass addr_class) const {
2266 addr_t opcode_addr = load_addr;
2267 switch (m_arch.GetMachine()) {
2268 case llvm::Triple::mips:
2269 case llvm::Triple::mipsel:
2270 case llvm::Triple::mips64:
2271 case llvm::Triple::mips64el:
2272 case llvm::Triple::arm:
2273 case llvm::Triple::thumb:
2274 switch (addr_class) {
2275 case eAddressClassData:
2276 case eAddressClassDebug:
2277 return LLDB_INVALID_ADDRESS;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002278
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279 case eAddressClassInvalid:
2280 case eAddressClassUnknown:
2281 case eAddressClassCode:
2282 case eAddressClassCodeAlternateISA:
2283 case eAddressClassRuntime:
2284 opcode_addr &= ~(1ull);
2285 break;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 break;
2288
2289 default:
2290 break;
2291 }
2292 return opcode_addr;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002293}
2294
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2296 addr_t breakable_addr = addr;
2297 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Greg Clayton9585fbf2013-03-19 00:20:55 +00002298
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 switch (m_arch.GetMachine()) {
2300 default:
2301 break;
2302 case llvm::Triple::mips:
2303 case llvm::Triple::mipsel:
2304 case llvm::Triple::mips64:
2305 case llvm::Triple::mips64el: {
2306 addr_t function_start = 0;
2307 addr_t current_offset = 0;
2308 uint32_t loop_count = 0;
2309 Address resolved_addr;
2310 uint32_t arch_flags = m_arch.GetFlags();
2311 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2312 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2313 SectionLoadList &section_load_list = GetSectionLoadList();
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002314
Kate Stoneb9c1b512016-09-06 20:57:50 +00002315 if (section_load_list.IsEmpty())
2316 // No sections are loaded, so we must assume we are not running yet
2317 // and need to operate only on file address.
2318 m_images.ResolveFileAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002319 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 section_load_list.ResolveLoadAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002321
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322 // Get the function boundaries to make sure we don't scan back before the
2323 // beginning of the current function.
2324 ModuleSP temp_addr_module_sp(resolved_addr.GetModule());
2325 if (temp_addr_module_sp) {
2326 SymbolContext sc;
2327 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2328 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr,
2329 resolve_scope, sc);
2330 Address sym_addr;
2331 if (sc.function)
2332 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2333 else if (sc.symbol)
2334 sym_addr = sc.symbol->GetAddress();
2335
2336 function_start = sym_addr.GetLoadAddress(this);
2337 if (function_start == LLDB_INVALID_ADDRESS)
2338 function_start = sym_addr.GetFileAddress();
2339
2340 if (function_start)
2341 current_offset = addr - function_start;
2342 }
2343
2344 // If breakpoint address is start of function then we dont have to do
2345 // anything.
2346 if (current_offset == 0)
2347 return breakable_addr;
Greg Claytond5944cd2013-12-06 01:12:00 +00002348 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002349 loop_count = current_offset / 2;
Greg Claytond5944cd2013-12-06 01:12:00 +00002350
Kate Stoneb9c1b512016-09-06 20:57:50 +00002351 if (loop_count > 3) {
2352 // Scan previous 6 bytes
2353 if (IsMips16 | IsMicromips)
2354 loop_count = 3;
2355 // For mips-only, instructions are always 4 bytes, so scan previous 4
2356 // bytes only.
2357 else
2358 loop_count = 2;
Greg Clayton6b32f1e2013-12-18 02:06:45 +00002359 }
2360
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 // Create Disassembler Instance
2362 lldb::DisassemblerSP disasm_sp(
2363 Disassembler::FindPlugin(m_arch, nullptr, nullptr));
Todd Fiala75f47c32014-10-11 21:42:09 +00002364
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365 ExecutionContext exe_ctx;
2366 CalculateExecutionContext(exe_ctx);
2367 InstructionList instruction_list;
2368 InstructionSP prev_insn;
2369 bool prefer_file_cache = true; // Read from file
2370 uint32_t inst_to_choose = 0;
2371
2372 for (uint32_t i = 1; i <= loop_count; i++) {
2373 // Adjust the address to read from.
2374 resolved_addr.Slide(-2);
2375 AddressRange range(resolved_addr, i * 2);
2376 uint32_t insn_size = 0;
2377
2378 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2379
2380 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2381 if (num_insns) {
2382 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2383 insn_size = prev_insn->GetOpcode().GetByteSize();
2384 if (i == 1 && insn_size == 2) {
2385 // This looks like a valid 2-byte instruction (but it could be a part
2386 // of upper 4 byte instruction).
2387 instruction_list.Append(prev_insn);
2388 inst_to_choose = 1;
2389 } else if (i == 2) {
2390 // Here we may get one 4-byte instruction or two 2-byte instructions.
2391 if (num_insns == 2) {
2392 // Looks like there are two 2-byte instructions above our breakpoint
2393 // target address.
2394 // Now the upper 2-byte instruction is either a valid 2-byte
2395 // instruction or could be a part of it's upper 4-byte instruction.
2396 // In both cases we don't care because in this case lower 2-byte
2397 // instruction is definitely a valid instruction
2398 // and whatever i=1 iteration has found out is true.
2399 inst_to_choose = 1;
2400 break;
2401 } else if (insn_size == 4) {
2402 // This instruction claims its a valid 4-byte instruction. But it
2403 // could be a part of it's upper 4-byte instruction.
2404 // Lets try scanning upper 2 bytes to verify this.
2405 instruction_list.Append(prev_insn);
2406 inst_to_choose = 2;
2407 }
2408 } else if (i == 3) {
2409 if (insn_size == 4)
2410 // FIXME: We reached here that means instruction at [target - 4] has
2411 // already claimed to be a 4-byte instruction,
2412 // and now instruction at [target - 6] is also claiming that it's a
2413 // 4-byte instruction. This can not be true.
2414 // In this case we can not decide the valid previous instruction so
2415 // we let lldb set the breakpoint at the address given by user.
2416 inst_to_choose = 0;
2417 else
2418 // This is straight-forward
2419 inst_to_choose = 2;
2420 break;
Greg Claytonb09c5382013-12-13 17:20:18 +00002421 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 } else {
2423 // Decode failed, bytes do not form a valid instruction. So whatever
2424 // previous iteration has found out is true.
2425 if (i > 1) {
2426 inst_to_choose = i - 1;
2427 break;
2428 }
2429 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002430 }
Todd Fiala015d8182014-07-22 23:41:36 +00002431
Kate Stoneb9c1b512016-09-06 20:57:50 +00002432 // Check if we are able to find any valid instruction.
2433 if (inst_to_choose) {
2434 if (inst_to_choose > instruction_list.GetSize())
2435 inst_to_choose--;
2436 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2437
2438 if (prev_insn->HasDelaySlot()) {
2439 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2440 // Adjust the breakable address
2441 breakable_addr = addr - shift_size;
Todd Fialaac33cc92014-10-09 01:02:08 +00002442 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 log->Printf("Target::%s Breakpoint at 0x%8.8" PRIx64
2444 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n",
2445 __FUNCTION__, addr, breakable_addr);
2446 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002447 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002448 break;
2449 }
2450 }
2451 return breakable_addr;
2452}
2453
2454SourceManager &Target::GetSourceManager() {
2455 if (!m_source_manager_ap)
2456 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2457 return *m_source_manager_ap;
2458}
2459
2460ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2461 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2462 // we can make it
2463 // per-target
2464
2465 {
2466 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2467
2468 if (!m_clang_modules_decl_vendor_ap) {
2469 m_clang_modules_decl_vendor_ap.reset(
2470 ClangModulesDeclVendor::Create(*this));
2471 }
2472 }
2473
2474 return m_clang_modules_decl_vendor_ap.get();
2475}
2476
2477Target::StopHookSP Target::CreateStopHook() {
2478 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2479 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2480 m_stop_hooks[new_uid] = stop_hook_sp;
2481 return stop_hook_sp;
2482}
2483
2484bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2485 size_t num_removed = m_stop_hooks.erase(user_id);
2486 return (num_removed != 0);
2487}
2488
2489void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2490
2491Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2492 StopHookSP found_hook;
2493
2494 StopHookCollection::iterator specified_hook_iter;
2495 specified_hook_iter = m_stop_hooks.find(user_id);
2496 if (specified_hook_iter != m_stop_hooks.end())
2497 found_hook = (*specified_hook_iter).second;
2498 return found_hook;
2499}
2500
2501bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2502 bool active_state) {
2503 StopHookCollection::iterator specified_hook_iter;
2504 specified_hook_iter = m_stop_hooks.find(user_id);
2505 if (specified_hook_iter == m_stop_hooks.end())
2506 return false;
2507
2508 (*specified_hook_iter).second->SetIsActive(active_state);
2509 return true;
2510}
2511
2512void Target::SetAllStopHooksActiveState(bool active_state) {
2513 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2514 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2515 (*pos).second->SetIsActive(active_state);
2516 }
2517}
2518
2519void Target::RunStopHooks() {
2520 if (m_suppress_stop_hooks)
2521 return;
2522
2523 if (!m_process_sp)
2524 return;
2525
2526 // <rdar://problem/12027563> make sure we check that we are not stopped
2527 // because of us running a user expression
2528 // since in that case we do not want to run the stop-hooks
2529 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2530 return;
2531
2532 if (m_stop_hooks.empty())
2533 return;
2534
2535 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2536
2537 // If there aren't any active stop hooks, don't bother either:
2538 bool any_active_hooks = false;
2539 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2540 if ((*pos).second->IsActive()) {
2541 any_active_hooks = true;
2542 break;
2543 }
2544 }
2545 if (!any_active_hooks)
2546 return;
2547
2548 CommandReturnObject result;
2549
2550 std::vector<ExecutionContext> exc_ctx_with_reasons;
2551 std::vector<SymbolContext> sym_ctx_with_reasons;
2552
2553 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2554 size_t num_threads = cur_threadlist.GetSize();
2555 for (size_t i = 0; i < num_threads; i++) {
2556 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2557 if (cur_thread_sp->ThreadStoppedForAReason()) {
2558 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2559 exc_ctx_with_reasons.push_back(ExecutionContext(
2560 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2561 sym_ctx_with_reasons.push_back(
2562 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2563 }
2564 }
2565
2566 // If no threads stopped for a reason, don't run the stop-hooks.
2567 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2568 if (num_exe_ctx == 0)
2569 return;
2570
2571 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2572 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2573
2574 bool keep_going = true;
2575 bool hooks_ran = false;
2576 bool print_hook_header = (m_stop_hooks.size() != 1);
2577 bool print_thread_header = (num_exe_ctx != 1);
2578
2579 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2580 // result.Clear();
2581 StopHookSP cur_hook_sp = (*pos).second;
2582 if (!cur_hook_sp->IsActive())
2583 continue;
2584
2585 bool any_thread_matched = false;
2586 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2587 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2588 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2589 sym_ctx_with_reasons[i])) &&
2590 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2591 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2592 exc_ctx_with_reasons[i].GetThreadRef()))) {
2593 if (!hooks_ran) {
2594 hooks_ran = true;
2595 }
2596 if (print_hook_header && !any_thread_matched) {
2597 const char *cmd =
2598 (cur_hook_sp->GetCommands().GetSize() == 1
2599 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2600 : nullptr);
2601 if (cmd)
2602 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2603 cur_hook_sp->GetID(), cmd);
2604 else
2605 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2606 cur_hook_sp->GetID());
2607 any_thread_matched = true;
2608 }
2609
2610 if (print_thread_header)
2611 result.AppendMessageWithFormat(
2612 "-- Thread %d\n",
2613 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2614
2615 CommandInterpreterRunOptions options;
2616 options.SetStopOnContinue(true);
2617 options.SetStopOnError(true);
2618 options.SetEchoCommands(false);
2619 options.SetPrintResults(true);
2620 options.SetAddToHistory(false);
2621
2622 GetDebugger().GetCommandInterpreter().HandleCommands(
2623 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2624 result);
2625
2626 // If the command started the target going again, we should bag out of
2627 // running the stop hooks.
2628 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2629 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2630 result.AppendMessageWithFormat("Aborting stop hooks, hook %" PRIu64
2631 " set the program running.",
2632 cur_hook_sp->GetID());
2633 keep_going = false;
2634 }
2635 }
2636 }
2637 }
2638
2639 result.GetImmediateOutputStream()->Flush();
2640 result.GetImmediateErrorStream()->Flush();
2641}
2642
2643const TargetPropertiesSP &Target::GetGlobalProperties() {
2644 // NOTE: intentional leak so we don't crash if global destructor chain gets
2645 // called as other threads still use the result of this function
2646 static TargetPropertiesSP *g_settings_sp_ptr = nullptr;
2647 static std::once_flag g_once_flag;
2648 std::call_once(g_once_flag, []() {
2649 g_settings_sp_ptr = new TargetPropertiesSP(new TargetProperties(nullptr));
2650 });
2651 return *g_settings_sp_ptr;
2652}
2653
2654Error Target::Install(ProcessLaunchInfo *launch_info) {
2655 Error error;
2656 PlatformSP platform_sp(GetPlatform());
2657 if (platform_sp) {
2658 if (platform_sp->IsRemote()) {
2659 if (platform_sp->IsConnected()) {
2660 // Install all files that have an install path, and always install the
2661 // main executable when connected to a remote platform
2662 const ModuleList &modules = GetImages();
2663 const size_t num_images = modules.GetSize();
2664 for (size_t idx = 0; idx < num_images; ++idx) {
2665 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2666 if (module_sp) {
2667 const bool is_main_executable = module_sp == GetExecutableModule();
2668 FileSpec local_file(module_sp->GetFileSpec());
2669 if (local_file) {
2670 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2671 if (!remote_file) {
2672 if (is_main_executable) // TODO: add setting for always
2673 // installing main executable???
2674 {
2675 // Always install the main executable
2676 remote_file = platform_sp->GetRemoteWorkingDirectory();
2677 remote_file.AppendPathComponent(
2678 module_sp->GetFileSpec().GetFilename().GetCString());
2679 }
2680 }
2681 if (remote_file) {
2682 error = platform_sp->Install(local_file, remote_file);
2683 if (error.Success()) {
2684 module_sp->SetPlatformFileSpec(remote_file);
2685 if (is_main_executable) {
2686 platform_sp->SetFilePermissions(remote_file, 0700);
2687 if (launch_info)
2688 launch_info->SetExecutableFile(remote_file, false);
2689 }
2690 } else
2691 break;
2692 }
2693 }
2694 }
2695 }
2696 }
2697 }
2698 }
2699 return error;
2700}
2701
2702bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2703 uint32_t stop_id) {
2704 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2705}
2706
2707bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2708 Address &resolved_addr) {
2709 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2710}
2711
2712bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2713 addr_t new_section_load_addr,
2714 bool warn_multiple) {
2715 const addr_t old_section_load_addr =
2716 m_section_load_history.GetSectionLoadAddress(
2717 SectionLoadHistory::eStopIDNow, section_sp);
2718 if (old_section_load_addr != new_section_load_addr) {
2719 uint32_t stop_id = 0;
2720 ProcessSP process_sp(GetProcessSP());
2721 if (process_sp)
2722 stop_id = process_sp->GetStopID();
Greg Claytonb09c5382013-12-13 17:20:18 +00002723 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002724 stop_id = m_section_load_history.GetLastStopID();
2725 if (m_section_load_history.SetSectionLoadAddress(
2726 stop_id, section_sp, new_section_load_addr, warn_multiple))
2727 return true; // Return true if the section load address was changed...
2728 }
2729 return false; // Return false to indicate nothing changed
2730}
Todd Fialaac33cc92014-10-09 01:02:08 +00002731
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2733 size_t section_unload_count = 0;
2734 size_t num_modules = module_list.GetSize();
2735 for (size_t i = 0; i < num_modules; ++i) {
2736 section_unload_count +=
2737 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2738 }
2739 return section_unload_count;
2740}
Todd Fiala015d8182014-07-22 23:41:36 +00002741
Kate Stoneb9c1b512016-09-06 20:57:50 +00002742size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2743 uint32_t stop_id = 0;
2744 ProcessSP process_sp(GetProcessSP());
2745 if (process_sp)
2746 stop_id = process_sp->GetStopID();
2747 else
2748 stop_id = m_section_load_history.GetLastStopID();
2749 SectionList *sections = module_sp->GetSectionList();
2750 size_t section_unload_count = 0;
2751 if (sections) {
2752 const uint32_t num_sections = sections->GetNumSections(0);
2753 for (uint32_t i = 0; i < num_sections; ++i) {
2754 section_unload_count += m_section_load_history.SetSectionUnloaded(
2755 stop_id, sections->GetSectionAtIndex(i));
Greg Claytonb09c5382013-12-13 17:20:18 +00002756 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002757 }
2758 return section_unload_count;
2759}
2760
2761bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2762 uint32_t stop_id = 0;
2763 ProcessSP process_sp(GetProcessSP());
2764 if (process_sp)
2765 stop_id = process_sp->GetStopID();
2766 else
2767 stop_id = m_section_load_history.GetLastStopID();
2768 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2769}
2770
2771bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2772 addr_t load_addr) {
2773 uint32_t stop_id = 0;
2774 ProcessSP process_sp(GetProcessSP());
2775 if (process_sp)
2776 stop_id = process_sp->GetStopID();
2777 else
2778 stop_id = m_section_load_history.GetLastStopID();
2779 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2780 load_addr);
2781}
2782
2783void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2784
2785Error Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2786 Error error;
2787 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2788
2789 if (log)
2790 log->Printf("Target::%s() called for %s", __FUNCTION__,
2791 launch_info.GetExecutableFile().GetPath().c_str());
2792
2793 StateType state = eStateInvalid;
2794
2795 // Scope to temporarily get the process state in case someone has manually
2796 // remotely connected already to a process and we can skip the platform
2797 // launching.
2798 {
2799 ProcessSP process_sp(GetProcessSP());
2800
2801 if (process_sp) {
2802 state = process_sp->GetState();
2803 if (log)
2804 log->Printf(
2805 "Target::%s the process exists, and its current state is %s",
2806 __FUNCTION__, StateAsCString(state));
2807 } else {
2808 if (log)
2809 log->Printf("Target::%s the process instance doesn't currently exist.",
2810 __FUNCTION__);
2811 }
2812 }
2813
2814 launch_info.GetFlags().Set(eLaunchFlagDebug);
2815
2816 // Get the value of synchronous execution here. If you wait till after you
2817 // have started to
2818 // run, then you could have hit a breakpoint, whose command might switch the
2819 // value, and
2820 // then you'll pick up that incorrect value.
2821 Debugger &debugger = GetDebugger();
2822 const bool synchronous_execution =
2823 debugger.GetCommandInterpreter().GetSynchronous();
2824
2825 PlatformSP platform_sp(GetPlatform());
2826
2827 // Finalize the file actions, and if none were given, default to opening
2828 // up a pseudo terminal
2829 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2830 if (log)
2831 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2832 "default_to_use_pty=%s",
2833 __FUNCTION__, platform_sp ? "true" : "false",
2834 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2835 : "n/a",
2836 default_to_use_pty ? "true" : "false");
2837
2838 launch_info.FinalizeFileActions(this, default_to_use_pty);
2839
2840 if (state == eStateConnected) {
2841 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2842 error.SetErrorString(
2843 "can't launch in tty when launching through a remote connection");
2844 return error;
2845 }
2846 }
2847
2848 if (!launch_info.GetArchitecture().IsValid())
2849 launch_info.GetArchitecture() = GetArchitecture();
2850
2851 // If we're not already connected to the process, and if we have a platform
2852 // that can launch a process for debugging, go ahead and do that here.
2853 if (state != eStateConnected && platform_sp &&
2854 platform_sp->CanDebugProcess()) {
2855 if (log)
2856 log->Printf("Target::%s asking the platform to debug the process",
2857 __FUNCTION__);
2858
2859 // Get a weak pointer to the previous process if we have one
2860 ProcessWP process_wp;
2861 if (m_process_sp)
2862 process_wp = m_process_sp;
2863 m_process_sp =
2864 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2865
2866 // Cleanup the old process since someone might still have a strong
2867 // reference to this process and we would like to allow it to cleanup
2868 // as much as it can without the object being destroyed. We try to
2869 // lock the shared pointer and if that works, then someone else still
2870 // has a strong reference to the process.
2871
2872 ProcessSP old_process_sp(process_wp.lock());
2873 if (old_process_sp)
2874 old_process_sp->Finalize();
2875 } else {
2876 if (log)
2877 log->Printf("Target::%s the platform doesn't know how to debug a "
2878 "process, getting a process plugin to do this for us.",
2879 __FUNCTION__);
2880
2881 if (state == eStateConnected) {
2882 assert(m_process_sp);
2883 } else {
2884 // Use a Process plugin to construct the process.
2885 const char *plugin_name = launch_info.GetProcessPluginName();
2886 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
2887 nullptr);
Greg Claytonb09c5382013-12-13 17:20:18 +00002888 }
2889
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 // Since we didn't have a platform launch the process, launch it here.
2891 if (m_process_sp)
2892 error = m_process_sp->Launch(launch_info);
2893 }
2894
2895 if (!m_process_sp) {
Greg Claytonb09c5382013-12-13 17:20:18 +00002896 if (error.Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002897 error.SetErrorString("failed to launch or debug process");
Greg Claytonb09c5382013-12-13 17:20:18 +00002898 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002899 }
2900
2901 if (error.Success()) {
2902 if (synchronous_execution ||
2903 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2904 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2905 if (!hijack_listener_sp) {
2906 hijack_listener_sp =
2907 Listener::MakeListener("lldb.Target.Launch.hijack");
2908 launch_info.SetHijackListener(hijack_listener_sp);
2909 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2910 }
2911
2912 StateType state = m_process_sp->WaitForProcessToStop(
2913 std::chrono::microseconds(0), nullptr, false, hijack_listener_sp,
2914 nullptr);
2915
2916 if (state == eStateStopped) {
2917 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2918 if (synchronous_execution) {
2919 error = m_process_sp->PrivateResume();
2920 if (error.Success()) {
2921 state = m_process_sp->WaitForProcessToStop(
2922 std::chrono::microseconds(0), nullptr, true,
2923 hijack_listener_sp, stream);
2924 const bool must_be_alive =
2925 false; // eStateExited is ok, so this must be false
2926 if (!StateIsStoppedState(state, must_be_alive)) {
2927 error.SetErrorStringWithFormat("process isn't stopped: %s",
2928 StateAsCString(state));
2929 }
2930 }
2931 } else {
2932 m_process_sp->RestoreProcessEvents();
2933 error = m_process_sp->PrivateResume();
2934 }
2935 if (!error.Success()) {
2936 Error error2;
2937 error2.SetErrorStringWithFormat(
2938 "process resume at entry point failed: %s", error.AsCString());
2939 error = error2;
2940 }
2941 }
2942 } else if (state == eStateExited) {
2943 bool with_shell = !!launch_info.GetShell();
2944 const int exit_status = m_process_sp->GetExitStatus();
2945 const char *exit_desc = m_process_sp->GetExitDescription();
2946#define LAUNCH_SHELL_MESSAGE \
2947 "\n'r' and 'run' are aliases that default to launching through a " \
2948 "shell.\nTry launching without going through a shell by using 'process " \
2949 "launch'."
2950 if (exit_desc && exit_desc[0]) {
2951 if (with_shell)
2952 error.SetErrorStringWithFormat(
2953 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2954 exit_status, exit_desc);
2955 else
2956 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2957 exit_status, exit_desc);
2958 } else {
2959 if (with_shell)
2960 error.SetErrorStringWithFormat(
2961 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2962 exit_status);
2963 else
2964 error.SetErrorStringWithFormat("process exited with status %i",
2965 exit_status);
2966 }
2967 } else {
2968 error.SetErrorStringWithFormat(
2969 "initial process state wasn't stopped: %s", StateAsCString(state));
2970 }
2971 }
2972 m_process_sp->RestoreProcessEvents();
2973 } else {
2974 Error error2;
2975 error2.SetErrorStringWithFormat("process launch failed: %s",
2976 error.AsCString());
2977 error = error2;
2978 }
2979 return error;
Greg Claytonb09c5382013-12-13 17:20:18 +00002980}
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002981
Kate Stoneb9c1b512016-09-06 20:57:50 +00002982Error Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2983 auto state = eStateInvalid;
2984 auto process_sp = GetProcessSP();
2985 if (process_sp) {
2986 state = process_sp->GetState();
2987 if (process_sp->IsAlive() && state != eStateConnected) {
2988 if (state == eStateAttaching)
2989 return Error("process attach is in progress");
2990 return Error("a process is already being debugged");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002991 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002992 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002993
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 const ModuleSP old_exec_module_sp = GetExecutableModule();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002995
Kate Stoneb9c1b512016-09-06 20:57:50 +00002996 // If no process info was specified, then use the target executable
2997 // name as the process to attach to by default
2998 if (!attach_info.ProcessInfoSpecified()) {
2999 if (old_exec_module_sp)
3000 attach_info.GetExecutableFile().GetFilename() =
3001 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003002
Kate Stoneb9c1b512016-09-06 20:57:50 +00003003 if (!attach_info.ProcessInfoSpecified()) {
3004 return Error("no process specified, create a target with a file, or "
3005 "specify the --pid or --name");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003006 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003007 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003008
Kate Stoneb9c1b512016-09-06 20:57:50 +00003009 const auto platform_sp =
3010 GetDebugger().GetPlatformList().GetSelectedPlatform();
3011 ListenerSP hijack_listener_sp;
3012 const bool async = attach_info.GetAsync();
3013 if (!async) {
3014 hijack_listener_sp =
3015 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3016 attach_info.SetHijackListener(hijack_listener_sp);
3017 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003018
Kate Stoneb9c1b512016-09-06 20:57:50 +00003019 Error error;
3020 if (state != eStateConnected && platform_sp != nullptr &&
3021 platform_sp->CanDebugProcess()) {
3022 SetPlatform(platform_sp);
3023 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3024 } else {
3025 if (state != eStateConnected) {
3026 const char *plugin_name = attach_info.GetProcessPluginName();
3027 process_sp =
3028 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3029 plugin_name, nullptr);
3030 if (process_sp == nullptr) {
3031 error.SetErrorStringWithFormat(
3032 "failed to create process using plugin %s",
3033 (plugin_name) ? plugin_name : "null");
3034 return error;
3035 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003036 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 if (hijack_listener_sp)
3038 process_sp->HijackProcessEvents(hijack_listener_sp);
3039 error = process_sp->Attach(attach_info);
3040 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003041
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 if (error.Success() && process_sp) {
3043 if (async) {
3044 process_sp->RestoreProcessEvents();
3045 } else {
3046 state = process_sp->WaitForProcessToStop(
3047 std::chrono::microseconds(0), nullptr, false,
3048 attach_info.GetHijackListener(), stream);
3049 process_sp->RestoreProcessEvents();
3050
3051 if (state != eStateStopped) {
3052 const char *exit_desc = process_sp->GetExitDescription();
3053 if (exit_desc)
3054 error.SetErrorStringWithFormat("%s", exit_desc);
Greg Claytone75e5d82015-10-20 00:14:20 +00003055 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 error.SetErrorString(
3057 "process did not stop (no such process or permission problem?)");
3058 process_sp->Destroy(false);
3059 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003060 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061 }
3062 return error;
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003063}
3064
Jim Ingham9575d842011-03-11 03:53:59 +00003065//--------------------------------------------------------------
Greg Claytonfbb76342013-11-20 21:07:01 +00003066// Target::StopHook
Jim Ingham9575d842011-03-11 03:53:59 +00003067//--------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3069 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3070 m_thread_spec_ap(), m_active(true) {}
3071
3072Target::StopHook::StopHook(const StopHook &rhs)
3073 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3074 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3075 m_thread_spec_ap(), m_active(rhs.m_active) {
3076 if (rhs.m_thread_spec_ap)
3077 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
Jim Ingham9575d842011-03-11 03:53:59 +00003078}
3079
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003080Target::StopHook::~StopHook() = default;
Jim Ingham9575d842011-03-11 03:53:59 +00003081
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3083 m_specifier_sp.reset(specifier);
Zachary Turner32abc6e2015-03-03 19:23:09 +00003084}
3085
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3087 m_thread_spec_ap.reset(specifier);
Jim Ingham9575d842011-03-11 03:53:59 +00003088}
Jim Ingham9575d842011-03-11 03:53:59 +00003089
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090void Target::StopHook::GetDescription(Stream *s,
3091 lldb::DescriptionLevel level) const {
3092 int indent_level = s->GetIndentLevel();
Jim Ingham9575d842011-03-11 03:53:59 +00003093
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 s->SetIndentLevel(indent_level + 2);
3095
3096 s->Printf("Hook: %" PRIu64 "\n", GetID());
3097 if (m_active)
3098 s->Indent("State: enabled\n");
3099 else
3100 s->Indent("State: disabled\n");
3101
3102 if (m_specifier_sp) {
3103 s->Indent();
3104 s->PutCString("Specifier:\n");
3105 s->SetIndentLevel(indent_level + 4);
3106 m_specifier_sp->GetDescription(s, level);
Jim Ingham9575d842011-03-11 03:53:59 +00003107 s->SetIndentLevel(indent_level + 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 }
Jim Ingham9575d842011-03-11 03:53:59 +00003109
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 if (m_thread_spec_ap) {
3111 StreamString tmp;
3112 s->Indent("Thread:\n");
3113 m_thread_spec_ap->GetDescription(&tmp, level);
3114 s->SetIndentLevel(indent_level + 4);
3115 s->Indent(tmp.GetData());
3116 s->PutCString("\n");
3117 s->SetIndentLevel(indent_level + 2);
3118 }
Jim Ingham9575d842011-03-11 03:53:59 +00003119
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 s->Indent("Commands: \n");
3121 s->SetIndentLevel(indent_level + 4);
3122 uint32_t num_commands = m_commands.GetSize();
3123 for (uint32_t i = 0; i < num_commands; i++) {
3124 s->Indent(m_commands.GetStringAtIndex(i));
3125 s->PutCString("\n");
3126 }
3127 s->SetIndentLevel(indent_level);
Jim Ingham9575d842011-03-11 03:53:59 +00003128}
3129
Greg Clayton67cc0632012-08-22 17:17:09 +00003130//--------------------------------------------------------------
3131// class TargetProperties
3132//--------------------------------------------------------------
3133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3135 {eNoDynamicValues, "no-dynamic-values",
3136 "Don't calculate the dynamic type of values"},
3137 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3138 "even if you have to run the target."},
3139 {eDynamicDontRunTarget, "no-run-target",
3140 "Calculate the dynamic type of values, but don't run the target."},
3141 {0, nullptr, nullptr}};
Caroline Ticedaccaa92010-09-20 20:44:43 +00003142
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3144 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3145 "locations (fastest). This setting "
3146 "should only be used if you know that "
3147 "no inlining occurs in your programs."},
3148 {eInlineBreakpointsHeaders, "headers",
3149 "Only check for inline breakpoint locations when setting breakpoints in "
3150 "header files, but not when setting breakpoint in implementation source "
3151 "files (default)."},
3152 {eInlineBreakpointsAlways, "always",
3153 "Always look for inline breakpoint locations when setting file and line "
3154 "breakpoints (slower but most accurate)."},
3155 {0, nullptr, nullptr}};
Greg Clayton1f746072012-08-29 21:13:06 +00003156
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157typedef enum x86DisassemblyFlavor {
3158 eX86DisFlavorDefault,
3159 eX86DisFlavorIntel,
3160 eX86DisFlavorATT
Jim Ingham0f063ba2013-03-02 00:26:47 +00003161} x86DisassemblyFlavor;
3162
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3164 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3165 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3166 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3167 {0, nullptr, nullptr}};
3168
3169static OptionEnumValueElement g_hex_immediate_style_values[] = {
3170 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3171 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3172 {0, nullptr, nullptr}};
3173
3174static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3175 {eLoadScriptFromSymFileTrue, "true",
3176 "Load debug scripts inside symbol files"},
3177 {eLoadScriptFromSymFileFalse, "false",
3178 "Do not load debug scripts inside symbol files."},
3179 {eLoadScriptFromSymFileWarn, "warn",
3180 "Warn about debug scripts inside symbol files but do not load them."},
3181 {0, nullptr, nullptr}};
3182
3183static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3184 {eLoadCWDlldbinitTrue, "true",
3185 "Load .lldbinit files from current directory"},
3186 {eLoadCWDlldbinitFalse, "false",
3187 "Do not load .lldbinit files from current directory"},
3188 {eLoadCWDlldbinitWarn, "warn",
3189 "Warn about loading .lldbinit files from current directory"},
3190 {0, nullptr, nullptr}};
3191
3192static OptionEnumValueElement g_memory_module_load_level_values[] = {
3193 {eMemoryModuleLoadLevelMinimal, "minimal",
3194 "Load minimal information when loading modules from memory. Currently "
3195 "this setting loads sections only."},
3196 {eMemoryModuleLoadLevelPartial, "partial",
3197 "Load partial information when loading modules from memory. Currently "
3198 "this setting loads sections and function bounds."},
3199 {eMemoryModuleLoadLevelComplete, "complete",
3200 "Load complete information when loading modules from memory. Currently "
3201 "this setting loads sections and all symbols."},
3202 {0, nullptr, nullptr}};
3203
3204static PropertyDefinition g_properties[] = {
3205 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3206 "Default architecture to choose, when there's a choice."},
3207 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3208 nullptr, "Move breakpoints to nearest code."},
3209 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3210 nullptr, nullptr,
3211 "The language to use when interpreting expressions entered in commands."},
3212 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3213 "Path to a file containing expressions to be prepended to all "
3214 "expressions."},
3215 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3216 eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3217 "Should printed values be shown as their dynamic value."},
3218 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3219 nullptr, "Should synthetic values be used by default whenever available."},
3220 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3221 "Skip function prologues when setting breakpoints by name."},
3222 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3223 "Source path remappings are used to track the change of location between "
3224 "a source file when built, and "
3225 "where it exists on the current system. It consists of an array of "
3226 "duples, the first element of each duple is "
3227 "some part (starting at the root) of the path to the file when it was "
3228 "built, "
3229 "and the second is where the remainder of the original build hierarchy is "
3230 "rooted on the local system. "
3231 "Each element of the array is checked in order and the first one that "
3232 "results in a match wins."},
3233 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3234 nullptr, "Executable search paths to use when locating executable files "
3235 "whose paths don't match the local file system."},
3236 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3237 nullptr, nullptr,
3238 "List of directories to be searched when locating debug symbol files."},
3239 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3240 nullptr, nullptr,
3241 "List of directories to be searched when locating modules for Clang."},
3242 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3243 nullptr, nullptr,
3244 "Automatically load Clang modules referred to by the program."},
3245 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3246 nullptr, "Automatically apply fix-it hints to expressions."},
3247 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3248 nullptr, "Print the fixed expression text."},
3249 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3250 nullptr, "Maximum number of children to expand in any level of depth."},
3251 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3252 nullptr, nullptr,
3253 "Maximum number of characters to show when using %s in summary strings."},
3254 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3255 nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3256 "--force must be specified."},
3257 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3258 true, nullptr, nullptr, "Consult the platform module avoid list when "
3259 "setting non-module specific breakpoints."},
3260 {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3261 "The first argument passed to the program in the argument array which can "
3262 "be different from the executable itself."},
3263 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3264 "A list containing all the arguments to be passed to the executable when "
3265 "it is run. Note that this does NOT include the argv[0] which is in "
3266 "target.arg0."},
3267 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3268 nullptr, nullptr, "A list of all the environment variables to be passed "
3269 "to the executable's environment, and their values."},
3270 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3271 "Inherit the environment from the process that is running LLDB."},
3272 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3273 "The file/path to be used by the executable program for reading its "
3274 "standard input."},
3275 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3276 "The file/path to be used by the executable program for writing its "
3277 "standard output."},
3278 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3279 "The file/path to be used by the executable program for writing its "
3280 "standard error."},
3281 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3282 nullptr, "debugserver will detach (rather than killing) a process if it "
3283 "loses connection with lldb."},
3284 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3285 "Disable Address Space Layout Randomization (ASLR)"},
3286 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3287 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3288 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3289 eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3290 "The strategy to use when settings breakpoints by file and line. "
3291 "Breakpoint locations can end up being inlined by the compiler, so that a "
3292 "compile unit 'a.c' might contain an inlined function from another source "
3293 "file. "
3294 "Usually this is limited to breakpoint locations from inlined functions "
3295 "from header or other include files, or more accurately "
3296 "non-implementation source files. "
3297 "Sometimes code might #include implementation files and cause inlined "
3298 "breakpoint locations in inlined implementation files. "
3299 "Always checking for inlined breakpoint locations can be expensive "
3300 "(memory and time), so if you have a project with many headers "
3301 "and find that setting breakpoints is slow, then you can change this "
3302 "setting to headers. "
3303 "This setting allows you to control exactly which strategy is used when "
3304 "setting "
3305 "file and line breakpoints."},
3306 // FIXME: This is the wrong way to do per-architecture settings, but we
3307 // don't have a general per architecture settings system in place yet.
3308 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3309 eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3310 "The default disassembly flavor to use for x86 or x86-64 targets."},
3311 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3312 nullptr, "Show immediates in disassembly as hexadecimal."},
3313 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3314 Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3315 "Which style to use for printing hexadecimal disassembly values."},
3316 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3317 nullptr, "Use a fast stepping algorithm based on running from branch to "
3318 "branch rather than instruction single-stepping."},
3319 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3320 eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3321 "Allow LLDB to load scripting resources embedded in symbol files when "
3322 "available."},
3323 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3324 nullptr, g_load_current_working_dir_lldbinit_values,
3325 "Allow LLDB to .lldbinit files from the current directory automatically."},
3326 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3327 eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3328 "Loading modules from memory can be slow as reading the symbol tables and "
3329 "other data can take a long time depending on your connection to the "
3330 "debug target. "
3331 "This setting helps users control how much information gets loaded when "
3332 "loading modules from memory."
3333 "'complete' is the default value for this setting which will load all "
3334 "sections and symbols by reading them from memory (slowest, most "
3335 "accurate). "
3336 "'partial' will load sections and attempt to find function bounds without "
3337 "downloading the symbol table (faster, still accurate, missing symbol "
3338 "names). "
3339 "'minimal' is the fastest setting and will load section data with no "
3340 "symbols, but should rarely be used as stack frames in these memory "
3341 "regions will be inaccurate and not provide any context (fastest). "},
3342 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3343 nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3344 "the host system supports executable specific crash log "
3345 "strings and this setting is set to true."},
3346 {"trap-handler-names", OptionValue::eTypeArray, true,
3347 OptionValue::eTypeString, nullptr, nullptr,
3348 "A list of trap handler function names, e.g. a common Unix user process "
3349 "one is _sigtramp."},
3350 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3351 nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3352 "support the operation of a language's runtime "
3353 "support."},
3354 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3355 "Disable lock-step debugging, instead control threads independently."},
3356 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3357
3358enum {
3359 ePropertyDefaultArch,
3360 ePropertyMoveToNearestCode,
3361 ePropertyLanguage,
3362 ePropertyExprPrefix,
3363 ePropertyPreferDynamic,
3364 ePropertyEnableSynthetic,
3365 ePropertySkipPrologue,
3366 ePropertySourceMap,
3367 ePropertyExecutableSearchPaths,
3368 ePropertyDebugFileSearchPaths,
3369 ePropertyClangModuleSearchPaths,
3370 ePropertyAutoImportClangModules,
3371 ePropertyAutoApplyFixIts,
3372 ePropertyNotifyAboutFixIts,
3373 ePropertyMaxChildrenCount,
3374 ePropertyMaxSummaryLength,
3375 ePropertyMaxMemReadSize,
3376 ePropertyBreakpointUseAvoidList,
3377 ePropertyArg0,
3378 ePropertyRunArgs,
3379 ePropertyEnvVars,
3380 ePropertyInheritEnv,
3381 ePropertyInputPath,
3382 ePropertyOutputPath,
3383 ePropertyErrorPath,
3384 ePropertyDetachOnError,
3385 ePropertyDisableASLR,
3386 ePropertyDisableSTDIO,
3387 ePropertyInlineStrategy,
3388 ePropertyDisassemblyFlavor,
3389 ePropertyUseHexImmediates,
3390 ePropertyHexImmediateStyle,
3391 ePropertyUseFastStepping,
3392 ePropertyLoadScriptFromSymbolFile,
3393 ePropertyLoadCWDlldbinitFile,
3394 ePropertyMemoryModuleLoadLevel,
3395 ePropertyDisplayExpressionsInCrashlogs,
3396 ePropertyTrapHandlerNames,
3397 ePropertyDisplayRuntimeSupportValues,
3398 ePropertyNonStopModeEnabled,
3399 ePropertyExperimental
Jim Ingham0f063ba2013-03-02 00:26:47 +00003400};
3401
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402class TargetOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +00003403public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003404 TargetOptionValueProperties(const ConstString &name)
3405 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
Caroline Ticedaccaa92010-09-20 20:44:43 +00003406
Kate Stoneb9c1b512016-09-06 20:57:50 +00003407 // This constructor is used when creating TargetOptionValueProperties when it
3408 // is part of a new lldb_private::Target instance. It will copy all current
3409 // global property values as needed
3410 TargetOptionValueProperties(Target *target,
3411 const TargetPropertiesSP &target_properties_sp)
3412 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3413 m_target(target), m_got_host_env(false) {}
Greg Clayton67cc0632012-08-22 17:17:09 +00003414
Kate Stoneb9c1b512016-09-06 20:57:50 +00003415 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3416 bool will_modify,
3417 uint32_t idx) const override {
3418 // When getting the value for a key from the target options, we will always
3419 // try and grab the setting from the current target if there is one. Else we
3420 // just
3421 // use the one from this instance.
3422 if (idx == ePropertyEnvVars)
3423 GetHostEnvironmentIfNeeded();
3424
3425 if (exe_ctx) {
3426 Target *target = exe_ctx->GetTargetPtr();
3427 if (target) {
3428 TargetOptionValueProperties *target_properties =
3429 static_cast<TargetOptionValueProperties *>(
3430 target->GetValueProperties().get());
3431 if (this != target_properties)
3432 return target_properties->ProtectedGetPropertyAtIndex(idx);
3433 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003434 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003435 return ProtectedGetPropertyAtIndex(idx);
3436 }
3437
3438 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3439
Greg Clayton67cc0632012-08-22 17:17:09 +00003440protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003441 void GetHostEnvironmentIfNeeded() const {
3442 if (!m_got_host_env) {
3443 if (m_target) {
3444 m_got_host_env = true;
3445 const uint32_t idx = ePropertyInheritEnv;
3446 if (GetPropertyAtIndexAsBoolean(
3447 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3448 PlatformSP platform_sp(m_target->GetPlatform());
3449 if (platform_sp) {
3450 StringList env;
3451 if (platform_sp->GetEnvironment(env)) {
3452 OptionValueDictionary *env_dict =
3453 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3454 ePropertyEnvVars);
3455 if (env_dict) {
3456 const bool can_replace = false;
3457 const size_t envc = env.GetSize();
3458 for (size_t idx = 0; idx < envc; idx++) {
3459 const char *env_entry = env.GetStringAtIndex(idx);
3460 if (env_entry) {
3461 const char *equal_pos = ::strchr(env_entry, '=');
3462 ConstString key;
3463 // It is ok to have environment variables with no values
3464 const char *value = nullptr;
3465 if (equal_pos) {
3466 key.SetCStringWithLength(env_entry,
3467 equal_pos - env_entry);
3468 if (equal_pos[1])
3469 value = equal_pos + 1;
3470 } else {
3471 key.SetCString(env_entry);
Greg Clayton67cc0632012-08-22 17:17:09 +00003472 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003473 // Don't allow existing keys to be replaced with ones we get
3474 // from the platform environment
3475 env_dict->SetValueForKey(
3476 key, OptionValueSP(new OptionValueString(value)),
3477 can_replace);
3478 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003479 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003480 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003481 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003482 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003484 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 }
3487 Target *m_target;
3488 mutable bool m_got_host_env;
Greg Clayton67cc0632012-08-22 17:17:09 +00003489};
3490
Greg Claytonfbb76342013-11-20 21:07:01 +00003491//----------------------------------------------------------------------
3492// TargetProperties
3493//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494static PropertyDefinition g_experimental_properties[]{
3495 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3496 nullptr,
3497 "If true, inject local variables explicitly into the expression text. "
3498 "This will fix symbol resolution when there are name collisions between "
3499 "ivars and local variables. "
3500 "But it can make expressions run much more slowly."},
3501 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Jim Inghambed67792016-07-07 18:25:48 +00003502
Kate Stoneb9c1b512016-09-06 20:57:50 +00003503enum { ePropertyInjectLocalVars = 0 };
Jim Inghambed67792016-07-07 18:25:48 +00003504
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505class TargetExperimentalOptionValueProperties : public OptionValueProperties {
Jim Inghambed67792016-07-07 18:25:48 +00003506public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003507 TargetExperimentalOptionValueProperties()
3508 : OptionValueProperties(
3509 ConstString(Properties::GetExperimentalSettingsName())) {}
Jim Inghambed67792016-07-07 18:25:48 +00003510};
3511
Kate Stoneb9c1b512016-09-06 20:57:50 +00003512TargetExperimentalProperties::TargetExperimentalProperties()
3513 : Properties(OptionValuePropertiesSP(
3514 new TargetExperimentalOptionValueProperties())) {
3515 m_collection_sp->Initialize(g_experimental_properties);
Jim Inghambed67792016-07-07 18:25:48 +00003516}
3517
3518//----------------------------------------------------------------------
3519// TargetProperties
3520//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003521TargetProperties::TargetProperties(Target *target)
3522 : Properties(), m_launch_info() {
3523 if (target) {
3524 m_collection_sp.reset(
3525 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
Ilia K8f37ca52015-02-13 14:31:06 +00003526
Kate Stoneb9c1b512016-09-06 20:57:50 +00003527 // Set callbacks to update launch_info whenever "settins set" updated any of
3528 // these properties
3529 m_collection_sp->SetValueChangedCallback(
3530 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3531 m_collection_sp->SetValueChangedCallback(
3532 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3533 m_collection_sp->SetValueChangedCallback(
3534 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3535 m_collection_sp->SetValueChangedCallback(
3536 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3537 this);
3538 m_collection_sp->SetValueChangedCallback(
3539 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3540 this);
3541 m_collection_sp->SetValueChangedCallback(
3542 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3543 this);
3544 m_collection_sp->SetValueChangedCallback(
3545 ePropertyDetachOnError,
3546 TargetProperties::DetachOnErrorValueChangedCallback, this);
3547 m_collection_sp->SetValueChangedCallback(
3548 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3549 this);
3550 m_collection_sp->SetValueChangedCallback(
3551 ePropertyDisableSTDIO,
3552 TargetProperties::DisableSTDIOValueChangedCallback, this);
Jim Inghambed67792016-07-07 18:25:48 +00003553
Kate Stoneb9c1b512016-09-06 20:57:50 +00003554 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3555 m_collection_sp->AppendProperty(
3556 ConstString(Properties::GetExperimentalSettingsName()),
3557 ConstString("Experimental settings - setting these won't produce "
3558 "errors if the setting is not present."),
3559 true, m_experimental_properties_up->GetValueProperties());
Jim Inghambed67792016-07-07 18:25:48 +00003560
Kate Stoneb9c1b512016-09-06 20:57:50 +00003561 // Update m_launch_info once it was created
3562 Arg0ValueChangedCallback(this, nullptr);
3563 RunArgsValueChangedCallback(this, nullptr);
3564 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3565 // Target::GetPlatform()
3566 InputPathValueChangedCallback(this, nullptr);
3567 OutputPathValueChangedCallback(this, nullptr);
3568 ErrorPathValueChangedCallback(this, nullptr);
3569 DetachOnErrorValueChangedCallback(this, nullptr);
3570 DisableASLRValueChangedCallback(this, nullptr);
3571 DisableSTDIOValueChangedCallback(this, nullptr);
3572 } else {
3573 m_collection_sp.reset(
3574 new TargetOptionValueProperties(ConstString("target")));
3575 m_collection_sp->Initialize(g_properties);
3576 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3577 m_collection_sp->AppendProperty(
3578 ConstString(Properties::GetExperimentalSettingsName()),
3579 ConstString("Experimental settings - setting these won't produce "
3580 "errors if the setting is not present."),
3581 true, m_experimental_properties_up->GetValueProperties());
3582 m_collection_sp->AppendProperty(
3583 ConstString("process"), ConstString("Settings specific to processes."),
3584 true, Process::GetGlobalProperties()->GetValueProperties());
3585 }
Caroline Ticedaccaa92010-09-20 20:44:43 +00003586}
3587
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003588TargetProperties::~TargetProperties() = default;
3589
Kate Stoneb9c1b512016-09-06 20:57:50 +00003590bool TargetProperties::GetInjectLocalVariables(
3591 ExecutionContext *exe_ctx) const {
3592 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3593 exe_ctx, false, ePropertyExperimental);
3594 OptionValueProperties *exp_values =
3595 exp_property->GetValue()->GetAsProperties();
3596 if (exp_values)
3597 return exp_values->GetPropertyAtIndexAsBoolean(
3598 exe_ctx, ePropertyInjectLocalVars, true);
3599 else
3600 return true;
Jim Inghambed67792016-07-07 18:25:48 +00003601}
3602
Kate Stoneb9c1b512016-09-06 20:57:50 +00003603void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3604 bool b) {
3605 const Property *exp_property =
3606 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3607 OptionValueProperties *exp_values =
3608 exp_property->GetValue()->GetAsProperties();
3609 if (exp_values)
3610 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3611 true);
Jim Inghambed67792016-07-07 18:25:48 +00003612}
3613
Kate Stoneb9c1b512016-09-06 20:57:50 +00003614ArchSpec TargetProperties::GetDefaultArchitecture() const {
3615 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3616 nullptr, ePropertyDefaultArch);
3617 if (value)
3618 return value->GetCurrentValue();
3619 return ArchSpec();
Greg Clayton67cc0632012-08-22 17:17:09 +00003620}
3621
Kate Stoneb9c1b512016-09-06 20:57:50 +00003622void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3623 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3624 nullptr, ePropertyDefaultArch);
3625 if (value)
3626 return value->SetCurrentValue(arch, true);
Greg Clayton67cc0632012-08-22 17:17:09 +00003627}
3628
Kate Stoneb9c1b512016-09-06 20:57:50 +00003629bool TargetProperties::GetMoveToNearestCode() const {
3630 const uint32_t idx = ePropertyMoveToNearestCode;
3631 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3632 nullptr, idx, g_properties[idx].default_uint_value != 0);
Ilia K055ad9b2015-05-18 13:41:01 +00003633}
3634
Kate Stoneb9c1b512016-09-06 20:57:50 +00003635lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3636 const uint32_t idx = ePropertyPreferDynamic;
3637 return (lldb::DynamicValueType)
3638 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3639 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003640}
3641
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3643 const uint32_t idx = ePropertyPreferDynamic;
3644 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
Greg Clayton15484402015-05-15 18:40:24 +00003645}
3646
Kate Stoneb9c1b512016-09-06 20:57:50 +00003647bool TargetProperties::GetDisableASLR() const {
3648 const uint32_t idx = ePropertyDisableASLR;
3649 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3650 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003651}
3652
Kate Stoneb9c1b512016-09-06 20:57:50 +00003653void TargetProperties::SetDisableASLR(bool b) {
3654 const uint32_t idx = ePropertyDisableASLR;
3655 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003656}
3657
Kate Stoneb9c1b512016-09-06 20:57:50 +00003658bool TargetProperties::GetDetachOnError() const {
3659 const uint32_t idx = ePropertyDetachOnError;
3660 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3661 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham106d0282014-06-25 02:32:56 +00003662}
3663
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664void TargetProperties::SetDetachOnError(bool b) {
3665 const uint32_t idx = ePropertyDetachOnError;
3666 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Jim Ingham106d0282014-06-25 02:32:56 +00003667}
3668
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669bool TargetProperties::GetDisableSTDIO() const {
3670 const uint32_t idx = ePropertyDisableSTDIO;
3671 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3672 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003673}
3674
Kate Stoneb9c1b512016-09-06 20:57:50 +00003675void TargetProperties::SetDisableSTDIO(bool b) {
3676 const uint32_t idx = ePropertyDisableSTDIO;
3677 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003678}
3679
Kate Stoneb9c1b512016-09-06 20:57:50 +00003680const char *TargetProperties::GetDisassemblyFlavor() const {
3681 const uint32_t idx = ePropertyDisassemblyFlavor;
3682 const char *return_value;
3683
3684 x86DisassemblyFlavor flavor_value =
3685 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3686 nullptr, idx, g_properties[idx].default_uint_value);
3687 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3688 return return_value;
Jim Ingham0f063ba2013-03-02 00:26:47 +00003689}
3690
Kate Stoneb9c1b512016-09-06 20:57:50 +00003691InlineStrategy TargetProperties::GetInlineStrategy() const {
3692 const uint32_t idx = ePropertyInlineStrategy;
3693 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3694 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton1f746072012-08-29 21:13:06 +00003695}
3696
Kate Stoneb9c1b512016-09-06 20:57:50 +00003697const char *TargetProperties::GetArg0() const {
3698 const uint32_t idx = ePropertyArg0;
3699 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, nullptr);
Greg Clayton45392552012-10-17 22:57:12 +00003700}
3701
Kate Stoneb9c1b512016-09-06 20:57:50 +00003702void TargetProperties::SetArg0(const char *arg) {
3703 const uint32_t idx = ePropertyArg0;
Zachary Turner514d8cd2016-09-23 18:06:53 +00003704 m_collection_sp->SetPropertyAtIndexAsString(
3705 nullptr, idx, llvm::StringRef::withNullAsEmpty(arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003706 m_launch_info.SetArg0(arg);
Greg Clayton45392552012-10-17 22:57:12 +00003707}
3708
Kate Stoneb9c1b512016-09-06 20:57:50 +00003709bool TargetProperties::GetRunArguments(Args &args) const {
3710 const uint32_t idx = ePropertyRunArgs;
3711 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +00003712}
3713
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714void TargetProperties::SetRunArguments(const Args &args) {
3715 const uint32_t idx = ePropertyRunArgs;
3716 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3717 m_launch_info.GetArguments() = args;
Greg Clayton67cc0632012-08-22 17:17:09 +00003718}
3719
Kate Stoneb9c1b512016-09-06 20:57:50 +00003720size_t TargetProperties::GetEnvironmentAsArgs(Args &env) const {
3721 const uint32_t idx = ePropertyEnvVars;
3722 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
Greg Clayton67cc0632012-08-22 17:17:09 +00003723}
3724
Kate Stoneb9c1b512016-09-06 20:57:50 +00003725void TargetProperties::SetEnvironmentFromArgs(const Args &env) {
3726 const uint32_t idx = ePropertyEnvVars;
3727 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, env);
3728 m_launch_info.GetEnvironmentEntries() = env;
Ilia K8f37ca52015-02-13 14:31:06 +00003729}
3730
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731bool TargetProperties::GetSkipPrologue() const {
3732 const uint32_t idx = ePropertySkipPrologue;
3733 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3734 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003735}
3736
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737PathMappingList &TargetProperties::GetSourcePathMap() const {
3738 const uint32_t idx = ePropertySourceMap;
3739 OptionValuePathMappings *option_value =
3740 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3741 false, idx);
3742 assert(option_value);
3743 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003744}
3745
Kate Stoneb9c1b512016-09-06 20:57:50 +00003746FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3747 const uint32_t idx = ePropertyExecutableSearchPaths;
3748 OptionValueFileSpecList *option_value =
3749 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3750 false, idx);
3751 assert(option_value);
3752 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003753}
3754
Kate Stoneb9c1b512016-09-06 20:57:50 +00003755FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3756 const uint32_t idx = ePropertyDebugFileSearchPaths;
3757 OptionValueFileSpecList *option_value =
3758 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3759 false, idx);
3760 assert(option_value);
3761 return option_value->GetCurrentValue();
Michael Sartaina7499c92013-07-01 19:45:50 +00003762}
3763
Kate Stoneb9c1b512016-09-06 20:57:50 +00003764FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3765 const uint32_t idx = ePropertyClangModuleSearchPaths;
3766 OptionValueFileSpecList *option_value =
3767 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3768 false, idx);
3769 assert(option_value);
3770 return option_value->GetCurrentValue();
Sean Callanan85054342015-04-03 15:39:47 +00003771}
3772
Kate Stoneb9c1b512016-09-06 20:57:50 +00003773bool TargetProperties::GetEnableAutoImportClangModules() const {
3774 const uint32_t idx = ePropertyAutoImportClangModules;
3775 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3776 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callananf0c5aeb2015-04-20 16:31:29 +00003777}
3778
Kate Stoneb9c1b512016-09-06 20:57:50 +00003779bool TargetProperties::GetEnableAutoApplyFixIts() const {
3780 const uint32_t idx = ePropertyAutoApplyFixIts;
3781 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3782 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghama1e541b2016-03-25 01:57:14 +00003783}
3784
Kate Stoneb9c1b512016-09-06 20:57:50 +00003785bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3786 const uint32_t idx = ePropertyNotifyAboutFixIts;
3787 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3788 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghame5ee6f02016-03-29 22:00:08 +00003789}
3790
Kate Stoneb9c1b512016-09-06 20:57:50 +00003791bool TargetProperties::GetEnableSyntheticValue() const {
3792 const uint32_t idx = ePropertyEnableSynthetic;
3793 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3794 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003795}
3796
Kate Stoneb9c1b512016-09-06 20:57:50 +00003797uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3798 const uint32_t idx = ePropertyMaxChildrenCount;
3799 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3800 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003801}
3802
Kate Stoneb9c1b512016-09-06 20:57:50 +00003803uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3804 const uint32_t idx = ePropertyMaxSummaryLength;
3805 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3806 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003807}
3808
Kate Stoneb9c1b512016-09-06 20:57:50 +00003809uint32_t TargetProperties::GetMaximumMemReadSize() const {
3810 const uint32_t idx = ePropertyMaxMemReadSize;
3811 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3812 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granatad325bf92013-06-04 22:54:16 +00003813}
3814
Kate Stoneb9c1b512016-09-06 20:57:50 +00003815FileSpec TargetProperties::GetStandardInputPath() const {
3816 const uint32_t idx = ePropertyInputPath;
3817 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003818}
3819
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003820void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003821 const uint32_t idx = ePropertyInputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003822 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003823}
3824
Kate Stoneb9c1b512016-09-06 20:57:50 +00003825FileSpec TargetProperties::GetStandardOutputPath() const {
3826 const uint32_t idx = ePropertyOutputPath;
3827 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003828}
3829
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003830void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003831 const uint32_t idx = ePropertyOutputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003832 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003833}
3834
Kate Stoneb9c1b512016-09-06 20:57:50 +00003835FileSpec TargetProperties::GetStandardErrorPath() const {
3836 const uint32_t idx = ePropertyErrorPath;
3837 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003838}
3839
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003840void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3841 const uint32_t idx = ePropertyErrorPath;
3842 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3843}
3844
Kate Stoneb9c1b512016-09-06 20:57:50 +00003845LanguageType TargetProperties::GetLanguage() const {
3846 OptionValueLanguage *value =
3847 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3848 nullptr, ePropertyLanguage);
3849 if (value)
3850 return value->GetCurrentValue();
3851 return LanguageType();
Dawn Perchik23b1dec2015-07-21 22:05:07 +00003852}
3853
Kate Stoneb9c1b512016-09-06 20:57:50 +00003854const char *TargetProperties::GetExpressionPrefixContentsAsCString() {
3855 const uint32_t idx = ePropertyExprPrefix;
3856 OptionValueFileSpec *file =
3857 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3858 idx);
3859 if (file) {
3860 const bool null_terminate = true;
3861 DataBufferSP data_sp(file->GetFileContents(null_terminate));
3862 if (data_sp)
3863 return (const char *)data_sp->GetBytes();
3864 }
3865 return nullptr;
Greg Clayton6920b522012-08-22 18:39:03 +00003866}
3867
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3869 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3870 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3871 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003872}
3873
Kate Stoneb9c1b512016-09-06 20:57:50 +00003874bool TargetProperties::GetUseHexImmediates() const {
3875 const uint32_t idx = ePropertyUseHexImmediates;
3876 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3877 nullptr, idx, g_properties[idx].default_uint_value != 0);
Daniel Malead79ae052013-08-07 21:54:09 +00003878}
3879
Kate Stoneb9c1b512016-09-06 20:57:50 +00003880bool TargetProperties::GetUseFastStepping() const {
3881 const uint32_t idx = ePropertyUseFastStepping;
3882 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3883 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham17d023f2013-03-13 17:58:04 +00003884}
3885
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3887 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3888 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3889 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Claytonfb6621e2013-12-06 21:59:52 +00003890}
3891
Kate Stoneb9c1b512016-09-06 20:57:50 +00003892LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3893 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3894 return (LoadScriptFromSymFile)
3895 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3896 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granata2ea43cd2013-05-13 17:03:52 +00003897}
3898
Kate Stoneb9c1b512016-09-06 20:57:50 +00003899LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3900 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3901 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3902 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molenda878ae012016-02-19 00:05:17 +00003903}
3904
Kate Stoneb9c1b512016-09-06 20:57:50 +00003905Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3906 const uint32_t idx = ePropertyHexImmediateStyle;
3907 return (Disassembler::HexImmediateStyle)
3908 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3909 nullptr, idx, g_properties[idx].default_uint_value);
Daniel Malead79ae052013-08-07 21:54:09 +00003910}
3911
Kate Stoneb9c1b512016-09-06 20:57:50 +00003912MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3913 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3914 return (MemoryModuleLoadLevel)
3915 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3916 nullptr, idx, g_properties[idx].default_uint_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00003917}
3918
Kate Stoneb9c1b512016-09-06 20:57:50 +00003919bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3920 const uint32_t idx = ePropertyTrapHandlerNames;
3921 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003922}
Greg Claytonfd814c52013-08-13 01:42:25 +00003923
Kate Stoneb9c1b512016-09-06 20:57:50 +00003924void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3925 const uint32_t idx = ePropertyTrapHandlerNames;
3926 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003927}
Greg Clayton67cc0632012-08-22 17:17:09 +00003928
Kate Stoneb9c1b512016-09-06 20:57:50 +00003929bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3930 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3931 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Enrico Granata560558e2015-02-11 02:35:39 +00003932}
3933
Kate Stoneb9c1b512016-09-06 20:57:50 +00003934void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3935 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3936 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granata560558e2015-02-11 02:35:39 +00003937}
3938
Kate Stoneb9c1b512016-09-06 20:57:50 +00003939bool TargetProperties::GetNonStopModeEnabled() const {
3940 const uint32_t idx = ePropertyNonStopModeEnabled;
3941 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Ewan Crawford78baa192015-05-13 09:18:18 +00003942}
3943
Kate Stoneb9c1b512016-09-06 20:57:50 +00003944void TargetProperties::SetNonStopModeEnabled(bool b) {
3945 const uint32_t idx = ePropertyNonStopModeEnabled;
3946 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00003947}
3948
Kate Stoneb9c1b512016-09-06 20:57:50 +00003949const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3950 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3951 return m_launch_info;
Ilia K8f37ca52015-02-13 14:31:06 +00003952}
3953
Kate Stoneb9c1b512016-09-06 20:57:50 +00003954void TargetProperties::SetProcessLaunchInfo(
3955 const ProcessLaunchInfo &launch_info) {
3956 m_launch_info = launch_info;
3957 SetArg0(launch_info.GetArg0());
3958 SetRunArguments(launch_info.GetArguments());
3959 SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
3960 const FileAction *input_file_action =
3961 launch_info.GetFileActionForFD(STDIN_FILENO);
3962 if (input_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003963 SetStandardInputPath(input_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003964 }
3965 const FileAction *output_file_action =
3966 launch_info.GetFileActionForFD(STDOUT_FILENO);
3967 if (output_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003968 SetStandardOutputPath(output_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969 }
3970 const FileAction *error_file_action =
3971 launch_info.GetFileActionForFD(STDERR_FILENO);
3972 if (error_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003973 SetStandardErrorPath(error_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003974 }
3975 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3976 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3977 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
Ilia K8f37ca52015-02-13 14:31:06 +00003978}
3979
Kate Stoneb9c1b512016-09-06 20:57:50 +00003980void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
3981 OptionValue *) {
3982 TargetProperties *this_ =
3983 reinterpret_cast<TargetProperties *>(target_property_ptr);
3984 this_->m_launch_info.SetArg0(this_->GetArg0());
Ilia K8f37ca52015-02-13 14:31:06 +00003985}
3986
Kate Stoneb9c1b512016-09-06 20:57:50 +00003987void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
3988 OptionValue *) {
3989 TargetProperties *this_ =
3990 reinterpret_cast<TargetProperties *>(target_property_ptr);
3991 Args args;
3992 if (this_->GetRunArguments(args))
3993 this_->m_launch_info.GetArguments() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00003994}
3995
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
3997 OptionValue *) {
3998 TargetProperties *this_ =
3999 reinterpret_cast<TargetProperties *>(target_property_ptr);
4000 Args args;
4001 if (this_->GetEnvironmentAsArgs(args))
4002 this_->m_launch_info.GetEnvironmentEntries() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00004003}
4004
Kate Stoneb9c1b512016-09-06 20:57:50 +00004005void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4006 OptionValue *) {
4007 TargetProperties *this_ =
4008 reinterpret_cast<TargetProperties *>(target_property_ptr);
4009 this_->m_launch_info.AppendOpenFileAction(
4010 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
Ilia K8f37ca52015-02-13 14:31:06 +00004011}
4012
Kate Stoneb9c1b512016-09-06 20:57:50 +00004013void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4014 OptionValue *) {
4015 TargetProperties *this_ =
4016 reinterpret_cast<TargetProperties *>(target_property_ptr);
4017 this_->m_launch_info.AppendOpenFileAction(
4018 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004019}
4020
Kate Stoneb9c1b512016-09-06 20:57:50 +00004021void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4022 OptionValue *) {
4023 TargetProperties *this_ =
4024 reinterpret_cast<TargetProperties *>(target_property_ptr);
4025 this_->m_launch_info.AppendOpenFileAction(
4026 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004027}
4028
Kate Stoneb9c1b512016-09-06 20:57:50 +00004029void TargetProperties::DetachOnErrorValueChangedCallback(
4030 void *target_property_ptr, OptionValue *) {
4031 TargetProperties *this_ =
4032 reinterpret_cast<TargetProperties *>(target_property_ptr);
4033 if (this_->GetDetachOnError())
4034 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4035 else
4036 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
Ilia K8f37ca52015-02-13 14:31:06 +00004037}
4038
Kate Stoneb9c1b512016-09-06 20:57:50 +00004039void TargetProperties::DisableASLRValueChangedCallback(
4040 void *target_property_ptr, OptionValue *) {
4041 TargetProperties *this_ =
4042 reinterpret_cast<TargetProperties *>(target_property_ptr);
4043 if (this_->GetDisableASLR())
4044 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4045 else
4046 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
Ilia K8f37ca52015-02-13 14:31:06 +00004047}
4048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049void TargetProperties::DisableSTDIOValueChangedCallback(
4050 void *target_property_ptr, OptionValue *) {
4051 TargetProperties *this_ =
4052 reinterpret_cast<TargetProperties *>(target_property_ptr);
4053 if (this_->GetDisableSTDIO())
4054 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4055 else
4056 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
Ilia K8f37ca52015-02-13 14:31:06 +00004057}
Ilia Keb2c19a2015-03-10 21:59:55 +00004058
4059//----------------------------------------------------------------------
4060// Target::TargetEventData
4061//----------------------------------------------------------------------
4062
Kate Stoneb9c1b512016-09-06 20:57:50 +00004063Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4064 : EventData(), m_target_sp(target_sp), m_module_list() {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004065
Kate Stoneb9c1b512016-09-06 20:57:50 +00004066Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4067 const ModuleList &module_list)
4068 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004069
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004070Target::TargetEventData::~TargetEventData() = default;
Ilia Keb2c19a2015-03-10 21:59:55 +00004071
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072const ConstString &Target::TargetEventData::GetFlavorString() {
4073 static ConstString g_flavor("Target::TargetEventData");
4074 return g_flavor;
Ilia Keb2c19a2015-03-10 21:59:55 +00004075}
4076
Kate Stoneb9c1b512016-09-06 20:57:50 +00004077void Target::TargetEventData::Dump(Stream *s) const {
4078 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4079 if (i != 0)
4080 *s << ", ";
4081 m_module_list.GetModuleAtIndex(i)->GetDescription(
4082 s, lldb::eDescriptionLevelBrief);
4083 }
Ilia Keb2c19a2015-03-10 21:59:55 +00004084}
4085
4086const Target::TargetEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004087Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4088 if (event_ptr) {
4089 const EventData *event_data = event_ptr->GetData();
4090 if (event_data &&
4091 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4092 return static_cast<const TargetEventData *>(event_ptr->GetData());
4093 }
4094 return nullptr;
Ilia Keb2c19a2015-03-10 21:59:55 +00004095}
4096
Kate Stoneb9c1b512016-09-06 20:57:50 +00004097TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4098 TargetSP target_sp;
4099 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4100 if (event_data)
4101 target_sp = event_data->m_target_sp;
4102 return target_sp;
Ilia Keb2c19a2015-03-10 21:59:55 +00004103}
4104
4105ModuleList
Kate Stoneb9c1b512016-09-06 20:57:50 +00004106Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4107 ModuleList module_list;
4108 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4109 if (event_data)
4110 module_list = event_data->m_module_list;
4111 return module_list;
Ilia Keb2c19a2015-03-10 21:59:55 +00004112}