blob: d73cc84a1561565d8ab4a8ebd1340ca1b8eb4193 [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,
799 const BreakpointIDList &bp_ids) {
800 Error error;
801
802 if (!file) {
803 error.SetErrorString("Invalid FileSpec.");
804 return error;
805 }
806
807 std::string path(file.GetPath());
808 StreamFile out_file(path.c_str(),
809 File::OpenOptions::eOpenOptionTruncate |
810 File::OpenOptions::eOpenOptionWrite |
811 File::OpenOptions::eOpenOptionCanCreate |
812 File::OpenOptions::eOpenOptionCloseOnExec,
813 lldb::eFilePermissionsFileDefault);
814 if (!out_file.GetFile().IsValid()) {
815 error.SetErrorStringWithFormat("Unable to open output file: %s.",
816 path.c_str());
817 return error;
818 }
819
820 std::unique_lock<std::recursive_mutex> lock;
821 GetBreakpointList().GetListMutex(lock);
822
823 StructuredData::ArraySP break_store_sp(new StructuredData::Array());
824 if (bp_ids.GetSize() == 0) {
825 const BreakpointList &breakpoints = GetBreakpointList();
826
827 size_t num_breakpoints = breakpoints.GetSize();
828 for (size_t i = 0; i < num_breakpoints; i++) {
829 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
830 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
831 // If a breakpoint can't serialize it, just ignore it for now:
832 if (bkpt_save_sp)
833 break_store_sp->AddItem(bkpt_save_sp);
834 }
835 } else {
836
837 std::unordered_set<lldb::break_id_t> processed_bkpts;
838 const size_t count = bp_ids.GetSize();
839 for (size_t i = 0; i < count; ++i) {
840 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
841 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
842
843 if (bp_id != LLDB_INVALID_BREAK_ID) {
844 // Only do each breakpoint once:
845 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
846 insert_result = processed_bkpts.insert(bp_id);
847 if (!insert_result.second)
848 continue;
849
850 Breakpoint *bp = GetBreakpointByID(bp_id).get();
851 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
852 // If the user explicitly asked to serialize a breakpoint, and we
853 // can't, then
854 // raise an error:
855 if (!bkpt_save_sp) {
856 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
857 bp_id);
858 return error;
859 }
860 break_store_sp->AddItem(bkpt_save_sp);
861 }
862 }
863 }
864
865 break_store_sp->Dump(out_file, false);
866 out_file.PutChar('\n');
867 return error;
868}
869
870Error Target::CreateBreakpointsFromFile(const FileSpec &file,
871 BreakpointIDList &new_bps) {
Jim Ingham3acdf382016-09-22 22:20:28 +0000872 std::vector<std::string> no_names;
873 return CreateBreakpointsFromFile(file, no_names, new_bps);
874}
875
876Error Target::CreateBreakpointsFromFile(const FileSpec &file,
877 std::vector<std::string> &names,
878 BreakpointIDList &new_bps) {
Jim Ingham01f16662016-09-14 19:07:35 +0000879 std::unique_lock<std::recursive_mutex> lock;
880 GetBreakpointList().GetListMutex(lock);
881
882 Error error;
883 StructuredData::ObjectSP input_data_sp =
884 StructuredData::ParseJSONFromFile(file, error);
885 if (!error.Success()) {
886 return error;
887 } else if (!input_data_sp || !input_data_sp->IsValid()) {
888 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
889 file.GetPath().c_str());
890 return error;
891 }
892
893 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
894 if (!bkpt_array) {
895 error.SetErrorStringWithFormat(
896 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
897 return error;
898 }
899
900 size_t num_bkpts = bkpt_array->GetSize();
Jim Ingham3acdf382016-09-22 22:20:28 +0000901 size_t num_names = names.size();
902
Jim Ingham01f16662016-09-14 19:07:35 +0000903 for (size_t i = 0; i < num_bkpts; i++) {
904 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
905 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
906 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
907 if (!bkpt_dict) {
908 error.SetErrorStringWithFormat(
909 "Invalid breakpoint data for element %zu from input file: %s.", i,
910 file.GetPath().c_str());
911 return error;
912 }
913 StructuredData::ObjectSP bkpt_data_sp =
914 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
Jim Ingham3acdf382016-09-22 22:20:28 +0000915 if (num_names &&
916 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
917 continue;
918
Jim Ingham01f16662016-09-14 19:07:35 +0000919 BreakpointSP bkpt_sp =
920 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
921 if (!error.Success()) {
922 error.SetErrorStringWithFormat(
923 "Error restoring breakpoint %zu from %s: %s.", i,
924 file.GetPath().c_str(), error.AsCString());
925 return error;
926 }
927 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
928 }
929 return error;
930}
931
Johnny Chenedf50372011-09-23 21:21:43 +0000932// The flag 'end_to_end', default to true, signifies that the operation is
933// performed end to end, for both the debugger and the debuggee.
934
Johnny Chen01a67862011-10-14 00:42:25 +0000935// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
936// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937bool Target::RemoveAllWatchpoints(bool end_to_end) {
938 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
939 if (log)
940 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +0000941
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 if (!end_to_end) {
943 m_watchpoint_list.RemoveAll(true);
944 return true;
945 }
Johnny Chenedf50372011-09-23 21:21:43 +0000946
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +0000948
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 if (!ProcessIsValid())
950 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000951
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 size_t num_watchpoints = m_watchpoint_list.GetSize();
953 for (size_t i = 0; i < num_watchpoints; ++i) {
954 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
955 if (!wp_sp)
956 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000957
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
959 if (rc.Fail())
960 return false;
961 }
962 m_watchpoint_list.RemoveAll(true);
963 m_last_created_watchpoint.reset();
964 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +0000965}
966
Johnny Chen01a67862011-10-14 00:42:25 +0000967// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
968// end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969bool Target::DisableAllWatchpoints(bool end_to_end) {
970 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
971 if (log)
972 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +0000973
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 if (!end_to_end) {
975 m_watchpoint_list.SetEnabledAll(false);
976 return true;
977 }
Johnny Chenedf50372011-09-23 21:21:43 +0000978
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +0000980
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 if (!ProcessIsValid())
982 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000983
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 size_t num_watchpoints = m_watchpoint_list.GetSize();
985 for (size_t i = 0; i < num_watchpoints; ++i) {
986 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
987 if (!wp_sp)
988 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
991 if (rc.Fail())
992 return false;
993 }
994 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +0000995}
996
Johnny Chen01a67862011-10-14 00:42:25 +0000997// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
998// end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999bool Target::EnableAllWatchpoints(bool end_to_end) {
1000 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1001 if (log)
1002 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 if (!end_to_end) {
1005 m_watchpoint_list.SetEnabledAll(true);
1006 return true;
1007 }
Johnny Chenedf50372011-09-23 21:21:43 +00001008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001010
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (!ProcessIsValid())
1012 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001013
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 size_t num_watchpoints = m_watchpoint_list.GetSize();
1015 for (size_t i = 0; i < num_watchpoints; ++i) {
1016 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1017 if (!wp_sp)
1018 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001019
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1021 if (rc.Fail())
1022 return false;
1023 }
1024 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001025}
1026
Johnny Chena4d6bc92012-02-25 06:44:30 +00001027// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028bool Target::ClearAllWatchpointHitCounts() {
1029 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1030 if (log)
1031 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chena4d6bc92012-02-25 06:44:30 +00001032
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 size_t num_watchpoints = m_watchpoint_list.GetSize();
1034 for (size_t i = 0; i < num_watchpoints; ++i) {
1035 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1036 if (!wp_sp)
1037 return false;
Johnny Chena4d6bc92012-02-25 06:44:30 +00001038
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039 wp_sp->ResetHitCount();
1040 }
1041 return true; // Success!
Johnny Chena4d6bc92012-02-25 06:44:30 +00001042}
1043
Enrico Granata5e3fe042015-02-11 00:37:54 +00001044// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045bool Target::ClearAllWatchpointHistoricValues() {
1046 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1047 if (log)
1048 log->Printf("Target::%s\n", __FUNCTION__);
1049
1050 size_t num_watchpoints = m_watchpoint_list.GetSize();
1051 for (size_t i = 0; i < num_watchpoints; ++i) {
1052 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1053 if (!wp_sp)
1054 return false;
1055
1056 wp_sp->ResetHistoricValues();
1057 }
1058 return true; // Success!
Enrico Granata5e3fe042015-02-11 00:37:54 +00001059}
1060
Johnny Chen01a67862011-10-14 00:42:25 +00001061// Assumption: Caller holds the list mutex lock for m_watchpoint_list
Johnny Chen6cc60e82011-10-05 21:35:46 +00001062// during these operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1064 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1065 if (log)
1066 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001067
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 if (!ProcessIsValid())
1069 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001070
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 size_t num_watchpoints = m_watchpoint_list.GetSize();
1072 for (size_t i = 0; i < num_watchpoints; ++i) {
1073 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1074 if (!wp_sp)
1075 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 wp_sp->SetIgnoreCount(ignore_count);
1078 }
1079 return true; // Success!
Johnny Chen6cc60e82011-10-05 21:35:46 +00001080}
1081
Johnny Chen01a67862011-10-14 00:42:25 +00001082// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1084 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1085 if (log)
1086 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001087
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001089 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090
1091 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1092 if (wp_sp) {
1093 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1094 if (rc.Success())
1095 return true;
1096
1097 // Else, fallthrough.
1098 }
1099 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001100}
1101
Johnny Chen01a67862011-10-14 00:42:25 +00001102// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1104 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1105 if (log)
1106 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001107
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001109 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110
1111 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1112 if (wp_sp) {
1113 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1114 if (rc.Success())
1115 return true;
1116
1117 // Else, fallthrough.
1118 }
1119 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001120}
1121
Johnny Chen01a67862011-10-14 00:42:25 +00001122// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1124 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1125 if (log)
1126 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001127
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1129 if (watch_to_remove_sp == m_last_created_watchpoint)
1130 m_last_created_watchpoint.reset();
1131
1132 if (DisableWatchpointByID(watch_id)) {
1133 m_watchpoint_list.Remove(watch_id, true);
1134 return true;
1135 }
1136 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001137}
1138
Johnny Chen01a67862011-10-14 00:42:25 +00001139// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1141 uint32_t ignore_count) {
1142 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1143 if (log)
1144 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001145
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 if (!ProcessIsValid())
Johnny Chen6cc60e82011-10-05 21:35:46 +00001147 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148
1149 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1150 if (wp_sp) {
1151 wp_sp->SetIgnoreCount(ignore_count);
1152 return true;
1153 }
1154 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001155}
1156
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157ModuleSP Target::GetExecutableModule() {
1158 // search for the first executable in the module list
1159 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1160 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1161 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1162 if (obj == nullptr)
1163 continue;
1164 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1165 return module_sp;
1166 }
1167 // as fall back return the first module loaded
1168 return m_images.GetModuleAtIndex(0);
Greg Claytonaa149cb2011-08-11 02:48:45 +00001169}
1170
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171Module *Target::GetExecutableModulePointer() {
1172 return GetExecutableModule().get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173}
1174
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1176 Target *target) {
1177 Error error;
1178 StreamString feedback_stream;
1179 if (module_sp &&
1180 !module_sp->LoadScriptingResourceInTarget(target, error,
1181 &feedback_stream)) {
1182 if (error.AsCString())
1183 target->GetDebugger().GetErrorFile()->Printf(
1184 "unable to load scripting data for module %s - error reported was "
1185 "%s\n",
1186 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1187 error.AsCString());
1188 }
1189 if (feedback_stream.GetSize())
1190 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1191 feedback_stream.GetData());
Enrico Granata17598482012-11-08 02:22:02 +00001192}
1193
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194void Target::ClearModules(bool delete_locations) {
1195 ModulesDidUnload(m_images, delete_locations);
1196 m_section_load_history.Clear();
1197 m_images.Clear();
1198 m_scratch_type_system_map.Clear();
1199 m_ast_importer_sp.reset();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001200}
1201
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202void Target::DidExec() {
1203 // When a process exec's we need to know about it so we can do some cleanup.
1204 m_breakpoint_list.RemoveInvalidLocations(m_arch);
1205 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
Greg Claytonb35db632013-11-09 00:03:31 +00001206}
1207
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208void Target::SetExecutableModule(ModuleSP &executable_sp,
1209 bool get_dependent_files) {
1210 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1211 ClearModules(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 if (executable_sp) {
1214 Timer scoped_timer(LLVM_PRETTY_FUNCTION,
1215 "Target::SetExecutableModule (executable = '%s')",
1216 executable_sp->GetFileSpec().GetPath().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 m_images.Append(executable_sp); // The first image is our executable file
Jason Molendae1b68ad2012-12-05 00:25:49 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 // If we haven't set an architecture yet, reset our architecture based on
1221 // what we found in the executable module.
1222 if (!m_arch.IsValid()) {
1223 m_arch = executable_sp->GetArchitecture();
1224 if (log)
1225 log->Printf("Target::SetExecutableModule setting architecture to %s "
1226 "(%s) based on executable file",
1227 m_arch.GetArchitectureName(),
1228 m_arch.GetTriple().getTriple().c_str());
Jason Molendadad8af42015-11-10 04:11:37 +00001229 }
1230
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 FileSpecList dependent_files;
1232 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001233
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234 if (executable_objfile && get_dependent_files) {
1235 executable_objfile->GetDependentModules(dependent_files);
1236 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1237 FileSpec dependent_file_spec(
1238 dependent_files.GetFileSpecPointerAtIndex(i));
1239 FileSpec platform_dependent_file_spec;
Greg Clayton67cc0632012-08-22 17:17:09 +00001240 if (m_platform_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1242 platform_dependent_file_spec);
1243 else
1244 platform_dependent_file_spec = dependent_file_spec;
1245
1246 ModuleSpec module_spec(platform_dependent_file_spec, m_arch);
1247 ModuleSP image_module_sp(GetSharedModule(module_spec));
1248 if (image_module_sp) {
1249 ObjectFile *objfile = image_module_sp->GetObjectFile();
1250 if (objfile)
1251 objfile->GetDependentModules(dependent_files);
1252 }
1253 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001254 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001256}
1257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258bool Target::SetArchitecture(const ArchSpec &arch_spec) {
1259 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1260 bool missing_local_arch = !m_arch.IsValid();
1261 bool replace_local_arch = true;
1262 bool compatible_local_arch = false;
1263 ArchSpec other(arch_spec);
Greg Claytone72dfb32012-02-24 01:59:29 +00001264
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 if (!missing_local_arch) {
1266 if (m_arch.IsCompatibleMatch(arch_spec)) {
1267 other.MergeFrom(m_arch);
1268
1269 if (m_arch.IsCompatibleMatch(other)) {
1270 compatible_local_arch = true;
1271 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1272 env_changed;
1273
1274 m_arch.PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1275 os_changed, os_ver_changed, env_changed);
1276
1277 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1278 replace_local_arch = false;
1279 }
1280 }
1281 }
1282
1283 if (compatible_local_arch || missing_local_arch) {
1284 // If we haven't got a valid arch spec, or the architectures are compatible
1285 // update the architecture, unless the one we already have is more specified
1286 if (replace_local_arch)
1287 m_arch = other;
1288 if (log)
1289 log->Printf("Target::SetArchitecture set architecture to %s (%s)",
1290 m_arch.GetArchitectureName(),
1291 m_arch.GetTriple().getTriple().c_str());
1292 return true;
1293 }
1294
1295 // If we have an executable file, try to reset the executable to the desired
1296 // architecture
1297 if (log)
1298 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1299 arch_spec.GetArchitectureName(),
1300 arch_spec.GetTriple().getTriple().c_str());
1301 m_arch = other;
1302 ModuleSP executable_sp = GetExecutableModule();
1303
1304 ClearModules(true);
1305 // Need to do something about unsetting breakpoints.
1306
1307 if (executable_sp) {
1308 if (log)
1309 log->Printf("Target::SetArchitecture Trying to select executable file "
1310 "architecture %s (%s)",
1311 arch_spec.GetArchitectureName(),
1312 arch_spec.GetTriple().getTriple().c_str());
1313 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1314 Error error = ModuleList::GetSharedModule(module_spec, executable_sp,
1315 &GetExecutableSearchPaths(),
1316 nullptr, nullptr);
1317
1318 if (!error.Fail() && executable_sp) {
1319 SetExecutableModule(executable_sp, true);
1320 return true;
1321 }
1322 }
1323 return false;
Greg Claytondb598232011-01-07 01:57:07 +00001324}
1325
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1327 if (arch_spec.IsValid()) {
1328 if (m_arch.IsCompatibleMatch(arch_spec)) {
1329 // The current target arch is compatible with "arch_spec", see if we
1330 // can improve our current architecture using bits from "arch_spec"
Greg Claytonc749eb82011-07-11 05:12:02 +00001331
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 // Merge bits from arch_spec into "merged_arch" and set our architecture
1333 ArchSpec merged_arch(m_arch);
1334 merged_arch.MergeFrom(arch_spec);
1335 return SetArchitecture(merged_arch);
1336 } else {
1337 // The new architecture is different, we just need to replace it
1338 return SetArchitecture(arch_spec);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001339 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 }
1341 return false;
1342}
Greg Claytonc749eb82011-07-11 05:12:02 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344void Target::WillClearList(const ModuleList &module_list) {}
1345
1346void Target::ModuleAdded(const ModuleList &module_list,
1347 const ModuleSP &module_sp) {
1348 // A module is being added to this target for the first time
1349 if (m_valid) {
1350 ModuleList my_module_list;
1351 my_module_list.Append(module_sp);
1352 LoadScriptingResourceForModule(module_sp, this);
1353 ModulesDidLoad(my_module_list);
1354 }
1355}
1356
1357void Target::ModuleRemoved(const ModuleList &module_list,
1358 const ModuleSP &module_sp) {
1359 // A module is being removed from this target.
1360 if (m_valid) {
1361 ModuleList my_module_list;
1362 my_module_list.Append(module_sp);
1363 ModulesDidUnload(my_module_list, false);
1364 }
1365}
1366
1367void Target::ModuleUpdated(const ModuleList &module_list,
1368 const ModuleSP &old_module_sp,
1369 const ModuleSP &new_module_sp) {
1370 // A module is replacing an already added module
1371 if (m_valid) {
1372 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1373 new_module_sp);
1374 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1375 old_module_sp, new_module_sp);
1376 }
1377}
1378
1379void Target::ModulesDidLoad(ModuleList &module_list) {
1380 if (m_valid && module_list.GetSize()) {
1381 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1382 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1383 if (m_process_sp) {
1384 m_process_sp->ModulesDidLoad(module_list);
1385 }
1386 BroadcastEvent(eBroadcastBitModulesLoaded,
1387 new TargetEventData(this->shared_from_this(), module_list));
1388 }
1389}
1390
1391void Target::SymbolsDidLoad(ModuleList &module_list) {
1392 if (m_valid && module_list.GetSize()) {
1393 if (m_process_sp) {
1394 LanguageRuntime *runtime =
1395 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1396 if (runtime) {
1397 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1398 objc_runtime->SymbolsDidLoad(module_list);
1399 }
1400 }
1401
1402 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1403 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1404 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1405 new TargetEventData(this->shared_from_this(), module_list));
1406 }
1407}
1408
1409void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1410 if (m_valid && module_list.GetSize()) {
1411 UnloadModuleSections(module_list);
1412 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1413 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1414 delete_locations);
1415 BroadcastEvent(eBroadcastBitModulesUnloaded,
1416 new TargetEventData(this->shared_from_this(), module_list));
1417 }
1418}
1419
1420bool Target::ModuleIsExcludedForUnconstrainedSearches(
1421 const FileSpec &module_file_spec) {
1422 if (GetBreakpointsConsultPlatformAvoidList()) {
1423 ModuleList matchingModules;
1424 ModuleSpec module_spec(module_file_spec);
1425 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1426
1427 // If there is more than one module for this file spec, only return true if
1428 // ALL the modules are on the
1429 // black list.
1430 if (num_modules > 0) {
1431 for (size_t i = 0; i < num_modules; i++) {
1432 if (!ModuleIsExcludedForUnconstrainedSearches(
1433 matchingModules.GetModuleAtIndex(i)))
1434 return false;
1435 }
1436 return true;
1437 }
1438 }
1439 return false;
1440}
1441
1442bool Target::ModuleIsExcludedForUnconstrainedSearches(
1443 const lldb::ModuleSP &module_sp) {
1444 if (GetBreakpointsConsultPlatformAvoidList()) {
1445 if (m_platform_sp)
1446 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1447 module_sp);
1448 }
1449 return false;
1450}
1451
1452size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1453 size_t dst_len, Error &error) {
1454 SectionSP section_sp(addr.GetSection());
1455 if (section_sp) {
1456 // If the contents of this section are encrypted, the on-disk file is
1457 // unusable. Read only from live memory.
1458 if (section_sp->IsEncrypted()) {
1459 error.SetErrorString("section is encrypted");
1460 return 0;
1461 }
1462 ModuleSP module_sp(section_sp->GetModule());
1463 if (module_sp) {
1464 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1465 if (objfile) {
1466 size_t bytes_read = objfile->ReadSectionData(
1467 section_sp.get(), addr.GetOffset(), dst, dst_len);
Greg Claytondb598232011-01-07 01:57:07 +00001468 if (bytes_read > 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001470 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001471 error.SetErrorStringWithFormat("error reading data from section %s",
1472 section_sp->GetName().GetCString());
1473 } else
1474 error.SetErrorString("address isn't from a object file");
1475 } else
1476 error.SetErrorString("address isn't in a module");
1477 } else
1478 error.SetErrorString("address doesn't contain a section that points to a "
1479 "section in a object file");
1480
1481 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001482}
1483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1485 void *dst, size_t dst_len, Error &error,
1486 lldb::addr_t *load_addr_ptr) {
1487 error.Clear();
1488
1489 // if we end up reading this from process memory, we will fill this
1490 // with the actual load address
1491 if (load_addr_ptr)
1492 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1493
1494 size_t bytes_read = 0;
1495
1496 addr_t load_addr = LLDB_INVALID_ADDRESS;
1497 addr_t file_addr = LLDB_INVALID_ADDRESS;
1498 Address resolved_addr;
1499 if (!addr.IsSectionOffset()) {
1500 SectionLoadList &section_load_list = GetSectionLoadList();
1501 if (section_load_list.IsEmpty()) {
1502 // No sections are loaded, so we must assume we are not running
1503 // yet and anything we are given is a file address.
1504 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1505 // offset is the file address
1506 m_images.ResolveFileAddress(file_addr, resolved_addr);
1507 } else {
1508 // We have at least one section loaded. This can be because
1509 // we have manually loaded some sections with "target modules load ..."
1510 // or because we have have a live process that has sections loaded
1511 // through the dynamic loader
1512 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1513 // offset is the load address
1514 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1515 }
1516 }
1517 if (!resolved_addr.IsValid())
1518 resolved_addr = addr;
1519
1520 if (prefer_file_cache) {
1521 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1522 if (bytes_read > 0)
1523 return bytes_read;
1524 }
1525
1526 if (ProcessIsValid()) {
1527 if (load_addr == LLDB_INVALID_ADDRESS)
1528 load_addr = resolved_addr.GetLoadAddress(this);
1529
1530 if (load_addr == LLDB_INVALID_ADDRESS) {
1531 ModuleSP addr_module_sp(resolved_addr.GetModule());
1532 if (addr_module_sp && addr_module_sp->GetFileSpec())
1533 error.SetErrorStringWithFormat(
1534 "%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1535 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
1536 resolved_addr.GetFileAddress(),
1537 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknonw>"));
1538 else
1539 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1540 resolved_addr.GetFileAddress());
1541 } else {
1542 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1543 if (bytes_read != dst_len) {
1544 if (error.Success()) {
1545 if (bytes_read == 0)
1546 error.SetErrorStringWithFormat(
1547 "read memory from 0x%" PRIx64 " failed", load_addr);
1548 else
1549 error.SetErrorStringWithFormat(
1550 "only %" PRIu64 " of %" PRIu64
1551 " bytes were read from memory at 0x%" PRIx64,
1552 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1553 }
1554 }
1555 if (bytes_read) {
1556 if (load_addr_ptr)
1557 *load_addr_ptr = load_addr;
1558 return bytes_read;
1559 }
1560 // If the address is not section offset we have an address that
1561 // doesn't resolve to any address in any currently loaded shared
1562 // libraries and we failed to read memory so there isn't anything
1563 // more we can do. If it is section offset, we might be able to
1564 // read cached memory from the object file.
1565 if (!resolved_addr.IsSectionOffset())
1566 return 0;
1567 }
1568 }
1569
1570 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1571 // If we didn't already try and read from the object file cache, then
1572 // try it after failing to read from the process.
1573 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1574 }
1575 return 0;
1576}
1577
1578size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1579 Error &error) {
1580 char buf[256];
1581 out_str.clear();
1582 addr_t curr_addr = addr.GetLoadAddress(this);
1583 Address address(addr);
1584 while (1) {
1585 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1586 if (length == 0)
1587 break;
1588 out_str.append(buf, length);
1589 // If we got "length - 1" bytes, we didn't get the whole C string, we
1590 // need to read some more characters
1591 if (length == sizeof(buf) - 1)
1592 curr_addr += length;
1593 else
1594 break;
1595 address = Address(curr_addr);
1596 }
1597 return out_str.size();
1598}
1599
1600size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1601 size_t dst_max_len, Error &result_error) {
1602 size_t total_cstr_len = 0;
1603 if (dst && dst_max_len) {
1604 result_error.Clear();
1605 // NULL out everything just to be safe
1606 memset(dst, 0, dst_max_len);
1607 Error error;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001608 addr_t curr_addr = addr.GetLoadAddress(this);
1609 Address address(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610
1611 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't
1612 // think this really needs to be tied to the memory cache subsystem's
1613 // cache line size, so leave this as a fixed constant.
1614 const size_t cache_line_size = 512;
1615
1616 size_t bytes_left = dst_max_len - 1;
1617 char *curr_dst = dst;
1618
1619 while (bytes_left > 0) {
1620 addr_t cache_line_bytes_left =
1621 cache_line_size - (curr_addr % cache_line_size);
1622 addr_t bytes_to_read =
1623 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1624 size_t bytes_read =
1625 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1626
1627 if (bytes_read == 0) {
1628 result_error = error;
1629 dst[total_cstr_len] = '\0';
1630 break;
1631 }
1632 const size_t len = strlen(curr_dst);
1633
1634 total_cstr_len += len;
1635
1636 if (len < bytes_to_read)
1637 break;
1638
1639 curr_dst += bytes_read;
1640 curr_addr += bytes_read;
1641 bytes_left -= bytes_read;
1642 address = Address(curr_addr);
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001643 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001644 } else {
1645 if (dst == nullptr)
1646 result_error.SetErrorString("invalid arguments");
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001647 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 result_error.Clear();
1649 }
1650 return total_cstr_len;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001651}
1652
Kate Stoneb9c1b512016-09-06 20:57:50 +00001653size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1654 bool prefer_file_cache,
1655 uint32_t byte_size, bool is_signed,
1656 Scalar &scalar, Error &error) {
1657 uint64_t uval;
1658
1659 if (byte_size <= sizeof(uval)) {
1660 size_t bytes_read =
1661 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1662 if (bytes_read == byte_size) {
1663 DataExtractor data(&uval, sizeof(uval), m_arch.GetByteOrder(),
1664 m_arch.GetAddressByteSize());
1665 lldb::offset_t offset = 0;
1666 if (byte_size <= 4)
1667 scalar = data.GetMaxU32(&offset, byte_size);
1668 else
1669 scalar = data.GetMaxU64(&offset, byte_size);
1670
1671 if (is_signed)
1672 scalar.SignExtend(byte_size * 8);
1673 return bytes_read;
1674 }
1675 } else {
1676 error.SetErrorStringWithFormat(
1677 "byte size of %u is too large for integer scalar type", byte_size);
1678 }
1679 return 0;
1680}
1681
1682uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1683 bool prefer_file_cache,
1684 size_t integer_byte_size,
1685 uint64_t fail_value,
1686 Error &error) {
1687 Scalar scalar;
1688 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1689 false, scalar, error))
1690 return scalar.ULongLong(fail_value);
1691 return fail_value;
1692}
1693
1694bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1695 Error &error, Address &pointer_addr) {
1696 Scalar scalar;
1697 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1698 m_arch.GetAddressByteSize(), false, scalar,
1699 error)) {
1700 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1701 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1702 SectionLoadList &section_load_list = GetSectionLoadList();
1703 if (section_load_list.IsEmpty()) {
1704 // No sections are loaded, so we must assume we are not running
1705 // yet and anything we are given is a file address.
1706 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1707 } else {
1708 // We have at least one section loaded. This can be because
1709 // we have manually loaded some sections with "target modules load ..."
1710 // or because we have have a live process that has sections loaded
1711 // through the dynamic loader
1712 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1713 }
1714 // We weren't able to resolve the pointer value, so just return
1715 // an address with no section
1716 if (!pointer_addr.IsValid())
1717 pointer_addr.SetOffset(pointer_vm_addr);
1718 return true;
1719 }
1720 }
1721 return false;
1722}
1723
1724ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
1725 Error *error_ptr) {
1726 ModuleSP module_sp;
1727
1728 Error error;
1729
1730 // First see if we already have this module in our module list. If we do,
1731 // then we're done, we don't need
1732 // to consult the shared modules list. But only do this if we are passed a
1733 // UUID.
1734
1735 if (module_spec.GetUUID().IsValid())
1736 module_sp = m_images.FindFirstModule(module_spec);
1737
1738 if (!module_sp) {
1739 ModuleSP old_module_sp; // This will get filled in if we have a new version
1740 // of the library
1741 bool did_create_module = false;
1742
1743 // If there are image search path entries, try to use them first to acquire
1744 // a suitable image.
1745 if (m_image_search_paths.GetSize()) {
1746 ModuleSpec transformed_spec(module_spec);
1747 if (m_image_search_paths.RemapPath(
1748 module_spec.GetFileSpec().GetDirectory(),
1749 transformed_spec.GetFileSpec().GetDirectory())) {
1750 transformed_spec.GetFileSpec().GetFilename() =
1751 module_spec.GetFileSpec().GetFilename();
1752 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1753 &GetExecutableSearchPaths(),
1754 &old_module_sp, &did_create_module);
1755 }
1756 }
1757
1758 if (!module_sp) {
1759 // If we have a UUID, we can check our global shared module list in case
1760 // we already have it. If we don't have a valid UUID, then we can't since
1761 // the path in "module_spec" will be a platform path, and we will need to
1762 // let the platform find that file. For example, we could be asking for
1763 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1764 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1765 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1766 // cache.
1767 if (module_spec.GetUUID().IsValid()) {
1768 // We have a UUID, it is OK to check the global module list...
1769 error = ModuleList::GetSharedModule(module_spec, module_sp,
1770 &GetExecutableSearchPaths(),
1771 &old_module_sp, &did_create_module);
1772 }
1773
1774 if (!module_sp) {
1775 // The platform is responsible for finding and caching an appropriate
1776 // module in the shared module cache.
1777 if (m_platform_sp) {
1778 error = m_platform_sp->GetSharedModule(
1779 module_spec, m_process_sp.get(), module_sp,
1780 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
1781 } else {
1782 error.SetErrorString("no platform is currently set");
Greg Claytond16e1e52011-07-12 17:06:17 +00001783 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001785 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001786
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 // We found a module that wasn't in our target list. Let's make sure that
1788 // there wasn't an equivalent
1789 // module in the list already, and if there was, let's remove it.
1790 if (module_sp) {
1791 ObjectFile *objfile = module_sp->GetObjectFile();
1792 if (objfile) {
1793 switch (objfile->GetType()) {
1794 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
1795 /// a program's execution state
1796 case ObjectFile::eTypeExecutable: /// A normal executable
1797 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
1798 /// executable
1799 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1800 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
1801 /// used during execution
1802 break;
1803 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
1804 /// debug information
1805 if (error_ptr)
1806 error_ptr->SetErrorString("debug info files aren't valid target "
1807 "modules, please specify an executable");
1808 return ModuleSP();
1809 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
1810 /// against but not used for
1811 /// execution
1812 if (error_ptr)
1813 error_ptr->SetErrorString("stub libraries aren't valid target "
1814 "modules, please specify an executable");
1815 return ModuleSP();
1816 default:
1817 if (error_ptr)
1818 error_ptr->SetErrorString(
1819 "unsupported file type, please specify an executable");
1820 return ModuleSP();
Greg Claytond16e1e52011-07-12 17:06:17 +00001821 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822 // GetSharedModule is not guaranteed to find the old shared module, for
1823 // instance
1824 // in the common case where you pass in the UUID, it is only going to
1825 // find the one
1826 // module matching the UUID. In fact, it has no good way to know what
1827 // the "old module"
1828 // relevant to this target is, since there might be many copies of a
1829 // module with this file spec
1830 // in various running debug sessions, but only one of them will belong
1831 // to this target.
1832 // So let's remove the UUID from the module list, and look in the
1833 // target's module list.
1834 // Only do this if there is SOMETHING else in the module spec...
1835 if (!old_module_sp) {
1836 if (module_spec.GetUUID().IsValid() &&
1837 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
1838 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
1839 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1840 module_spec_copy.GetUUID().Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 ModuleList found_modules;
1843 size_t num_found =
1844 m_images.FindModules(module_spec_copy, found_modules);
1845 if (num_found == 1) {
1846 old_module_sp = found_modules.GetModuleAtIndex(0);
Jim Ingham4a94c912012-05-17 18:38:42 +00001847 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001848 }
Greg Claytonb69bb2e2012-04-27 00:58:27 +00001849 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851 if (old_module_sp &&
1852 m_images.GetIndexForModule(old_module_sp.get()) !=
1853 LLDB_INVALID_INDEX32) {
1854 m_images.ReplaceModule(old_module_sp, module_sp);
1855 Module *old_module_ptr = old_module_sp.get();
1856 old_module_sp.reset();
1857 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
1858 } else
1859 m_images.Append(module_sp);
1860 } else
1861 module_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001862 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001863 }
1864 if (error_ptr)
1865 *error_ptr = error;
1866 return module_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001867}
1868
Kate Stoneb9c1b512016-09-06 20:57:50 +00001869TargetSP Target::CalculateTarget() { return shared_from_this(); }
1870
1871ProcessSP Target::CalculateProcess() { return m_process_sp; }
1872
1873ThreadSP Target::CalculateThread() { return ThreadSP(); }
1874
1875StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
1876
1877void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1878 exe_ctx.Clear();
1879 exe_ctx.SetTargetPtr(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001880}
1881
Kate Stoneb9c1b512016-09-06 20:57:50 +00001882PathMappingList &Target::GetImageSearchPathList() {
1883 return m_image_search_paths;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001884}
1885
Kate Stoneb9c1b512016-09-06 20:57:50 +00001886void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
1887 void *baton) {
1888 Target *target = (Target *)baton;
1889 ModuleSP exe_module_sp(target->GetExecutableModule());
1890 if (exe_module_sp)
1891 target->SetExecutableModule(exe_module_sp, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001892}
1893
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894TypeSystem *Target::GetScratchTypeSystemForLanguage(Error *error,
1895 lldb::LanguageType language,
1896 bool create_on_demand) {
1897 if (!m_valid)
1898 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001899
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 if (error) {
1901 error->Clear();
1902 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001903
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
1905 // assembly code
1906 || language == eLanguageTypeUnknown) {
1907 std::set<lldb::LanguageType> languages_for_types;
1908 std::set<lldb::LanguageType> languages_for_expressions;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001909
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
1911 languages_for_expressions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001912
Kate Stoneb9c1b512016-09-06 20:57:50 +00001913 if (languages_for_expressions.count(eLanguageTypeC)) {
1914 language = eLanguageTypeC; // LLDB's default. Override by setting the
1915 // target language.
1916 } else {
1917 if (languages_for_expressions.empty()) {
Greg Clayton5beec212015-10-08 21:04:34 +00001918 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 } else {
1920 language = *languages_for_expressions.begin();
1921 }
Sean Callanana994b0b2015-10-02 18:40:30 +00001922 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 }
Sean Callananb92bd752015-10-01 16:28:02 +00001924
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
1926 create_on_demand);
Sean Callananb92bd752015-10-01 16:28:02 +00001927}
1928
1929PersistentExpressionState *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
1931 TypeSystem *type_system =
1932 GetScratchTypeSystemForLanguage(nullptr, language, true);
1933
1934 if (type_system) {
1935 return type_system->GetPersistentExpressionState();
1936 } else {
1937 return nullptr;
1938 }
Jim Ingham151c0322015-09-15 21:13:50 +00001939}
1940
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941UserExpression *Target::GetUserExpressionForLanguage(
1942 const char *expr, const char *expr_prefix, lldb::LanguageType language,
1943 Expression::ResultType desired_type,
1944 const EvaluateExpressionOptions &options, Error &error) {
1945 Error type_system_error;
1946
1947 TypeSystem *type_system =
1948 GetScratchTypeSystemForLanguage(&type_system_error, language);
1949 UserExpression *user_expr = nullptr;
1950
1951 if (!type_system) {
1952 error.SetErrorStringWithFormat(
1953 "Could not find type system for language %s: %s",
1954 Language::GetNameForLanguageType(language),
1955 type_system_error.AsCString());
1956 return nullptr;
1957 }
1958
1959 user_expr = type_system->GetUserExpression(expr, expr_prefix, language,
1960 desired_type, options);
1961 if (!user_expr)
1962 error.SetErrorStringWithFormat(
1963 "Could not create an expression for language %s",
1964 Language::GetNameForLanguageType(language));
1965
1966 return user_expr;
Jim Ingham151c0322015-09-15 21:13:50 +00001967}
1968
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969FunctionCaller *Target::GetFunctionCallerForLanguage(
1970 lldb::LanguageType language, const CompilerType &return_type,
1971 const Address &function_address, const ValueList &arg_value_list,
1972 const char *name, Error &error) {
1973 Error type_system_error;
1974 TypeSystem *type_system =
1975 GetScratchTypeSystemForLanguage(&type_system_error, language);
1976 FunctionCaller *persistent_fn = nullptr;
1977
1978 if (!type_system) {
1979 error.SetErrorStringWithFormat(
1980 "Could not find type system for language %s: %s",
1981 Language::GetNameForLanguageType(language),
1982 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00001983 return persistent_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 }
1985
1986 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
1987 arg_value_list, name);
1988 if (!persistent_fn)
1989 error.SetErrorStringWithFormat(
1990 "Could not create an expression for language %s",
1991 Language::GetNameForLanguageType(language));
1992
1993 return persistent_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00001994}
1995
1996UtilityFunction *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997Target::GetUtilityFunctionForLanguage(const char *text,
1998 lldb::LanguageType language,
1999 const char *name, Error &error) {
2000 Error type_system_error;
2001 TypeSystem *type_system =
2002 GetScratchTypeSystemForLanguage(&type_system_error, language);
2003 UtilityFunction *utility_fn = nullptr;
2004
2005 if (!type_system) {
2006 error.SetErrorStringWithFormat(
2007 "Could not find type system for language %s: %s",
2008 Language::GetNameForLanguageType(language),
2009 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002010 return utility_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002011 }
2012
2013 utility_fn = type_system->GetUtilityFunction(text, name);
2014 if (!utility_fn)
2015 error.SetErrorStringWithFormat(
2016 "Could not create an expression for language %s",
2017 Language::GetNameForLanguageType(language));
2018
2019 return utility_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002020}
2021
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2023 if (m_valid) {
2024 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2025 nullptr, eLanguageTypeC, create_on_demand))
2026 return llvm::dyn_cast<ClangASTContext>(type_system);
2027 }
2028 return nullptr;
2029}
2030
2031ClangASTImporterSP Target::GetClangASTImporter() {
2032 if (m_valid) {
2033 if (!m_ast_importer_sp) {
2034 m_ast_importer_sp.reset(new ClangASTImporter());
Sean Callanan4bf80d52011-11-15 22:27:19 +00002035 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002036 return m_ast_importer_sp;
2037 }
2038 return ClangASTImporterSP();
Sean Callananb92bd752015-10-01 16:28:02 +00002039}
2040
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2042
2043void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2044
2045FileSpecList Target::GetDefaultExecutableSearchPaths() {
2046 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2047 if (properties_sp)
2048 return properties_sp->GetExecutableSearchPaths();
2049 return FileSpecList();
Sean Callanan686b2312011-11-16 18:20:47 +00002050}
2051
Kate Stoneb9c1b512016-09-06 20:57:50 +00002052FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2053 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2054 if (properties_sp)
2055 return properties_sp->GetDebugFileSearchPaths();
2056 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002057}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002058
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2060 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2061 if (properties_sp)
2062 return properties_sp->GetClangModuleSearchPaths();
2063 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002064}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002065
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066ArchSpec Target::GetDefaultArchitecture() {
2067 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2068 if (properties_sp)
2069 return properties_sp->GetDefaultArchitecture();
2070 return ArchSpec();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002071}
2072
Kate Stoneb9c1b512016-09-06 20:57:50 +00002073void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2074 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2075 if (properties_sp) {
2076 LogIfAnyCategoriesSet(
2077 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2078 "default architecture to %s (%s)",
2079 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2080 return properties_sp->SetDefaultArchitecture(arch);
2081 }
Michael Sartaina7499c92013-07-01 19:45:50 +00002082}
2083
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2085 const SymbolContext *sc_ptr) {
2086 // The target can either exist in the "process" of ExecutionContext, or in
2087 // the "target_sp" member of SymbolContext. This accessor helper function
2088 // will get the target from one of these locations.
2089
2090 Target *target = nullptr;
2091 if (sc_ptr != nullptr)
2092 target = sc_ptr->target_sp.get();
2093 if (target == nullptr && exe_ctx_ptr)
2094 target = exe_ctx_ptr->GetTargetPtr();
2095 return target;
Sean Callanan85054342015-04-03 15:39:47 +00002096}
2097
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098ExpressionResults Target::EvaluateExpression(
2099 const char *expr_cstr, ExecutionContextScope *exe_scope,
2100 lldb::ValueObjectSP &result_valobj_sp,
2101 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2102 result_valobj_sp.reset();
Caroline Ticedaccaa92010-09-20 20:44:43 +00002103
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 ExpressionResults execution_results = eExpressionSetupError;
Caroline Ticedaccaa92010-09-20 20:44:43 +00002105
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 if (expr_cstr == nullptr || expr_cstr[0] == '\0')
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002107 return execution_results;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108
2109 // We shouldn't run stop hooks in expressions.
2110 // Be sure to reset this if you return anywhere within this function.
2111 bool old_suppress_value = m_suppress_stop_hooks;
2112 m_suppress_stop_hooks = true;
2113
2114 ExecutionContext exe_ctx;
2115
2116 if (exe_scope) {
2117 exe_scope->CalculateExecutionContext(exe_ctx);
2118 } else if (m_process_sp) {
2119 m_process_sp->CalculateExecutionContext(exe_ctx);
2120 } else {
2121 CalculateExecutionContext(exe_ctx);
2122 }
2123
2124 // Make sure we aren't just trying to see the value of a persistent
2125 // variable (something like "$0")
2126 lldb::ExpressionVariableSP persistent_var_sp;
2127 // Only check for persistent variables the expression starts with a '$'
2128 if (expr_cstr[0] == '$')
2129 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2130 ->GetPersistentExpressionState()
2131 ->GetVariable(expr_cstr);
2132
2133 if (persistent_var_sp) {
2134 result_valobj_sp = persistent_var_sp->GetValueObject();
2135 execution_results = eExpressionCompleted;
2136 } else {
2137 const char *prefix = GetExpressionPrefixContentsAsCString();
2138 Error error;
2139 execution_results = UserExpression::Evaluate(
2140 exe_ctx, options, expr_cstr, prefix, result_valobj_sp, error,
2141 0, // Line Number
2142 fixed_expression);
2143 }
2144
2145 m_suppress_stop_hooks = old_suppress_value;
2146
2147 return execution_results;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002148}
2149
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002150lldb::ExpressionVariableSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151Target::GetPersistentVariable(const ConstString &name) {
2152 lldb::ExpressionVariableSP variable_sp;
2153 m_scratch_type_system_map.ForEach(
2154 [this, name, &variable_sp](TypeSystem *type_system) -> bool {
2155 if (PersistentExpressionState *persistent_state =
2156 type_system->GetPersistentExpressionState()) {
2157 variable_sp = persistent_state->GetVariable(name);
Greg Clayton5beec212015-10-08 21:04:34 +00002158
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 if (variable_sp)
2160 return false; // Stop iterating the ForEach
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002161 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002162 return true; // Keep iterating the ForEach
2163 });
2164 return variable_sp;
Zachary Turner32abc6e2015-03-03 19:23:09 +00002165}
2166
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2168 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2169
2170 m_scratch_type_system_map.ForEach(
2171 [this, name, &address](TypeSystem *type_system) -> bool {
2172 if (PersistentExpressionState *persistent_state =
2173 type_system->GetPersistentExpressionState()) {
2174 address = persistent_state->LookupSymbol(name);
2175 if (address != LLDB_INVALID_ADDRESS)
2176 return false; // Stop iterating the ForEach
Sean Callananb92bd752015-10-01 16:28:02 +00002177 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 return true; // Keep iterating the ForEach
2179 });
2180 return address;
Sean Callananb92bd752015-10-01 16:28:02 +00002181}
2182
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2184 AddressClass addr_class) const {
2185 addr_t code_addr = load_addr;
2186 switch (m_arch.GetMachine()) {
2187 case llvm::Triple::mips:
2188 case llvm::Triple::mipsel:
2189 case llvm::Triple::mips64:
2190 case llvm::Triple::mips64el:
2191 switch (addr_class) {
2192 case eAddressClassData:
2193 case eAddressClassDebug:
2194 return LLDB_INVALID_ADDRESS;
Jaydeep Patil44d07fc2015-09-22 06:36:56 +00002195
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 case eAddressClassUnknown:
2197 case eAddressClassInvalid:
2198 case eAddressClassCode:
2199 case eAddressClassCodeAlternateISA:
2200 case eAddressClassRuntime:
2201 if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2202 code_addr |= 1ull;
2203 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002204 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002206
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207 case llvm::Triple::arm:
2208 case llvm::Triple::thumb:
2209 switch (addr_class) {
2210 case eAddressClassData:
2211 case eAddressClassDebug:
2212 return LLDB_INVALID_ADDRESS;
2213
2214 case eAddressClassUnknown:
2215 case eAddressClassInvalid:
2216 case eAddressClassCode:
2217 case eAddressClassCodeAlternateISA:
2218 case eAddressClassRuntime:
2219 // Check if bit zero it no set?
2220 if ((code_addr & 1ull) == 0) {
2221 // Bit zero isn't set, check if the address is a multiple of 2?
2222 if (code_addr & 2ull) {
2223 // The address is a multiple of 2 so it must be thumb, set bit zero
2224 code_addr |= 1ull;
2225 } else if (addr_class == eAddressClassCodeAlternateISA) {
2226 // We checked the address and the address claims to be the alternate
2227 // ISA
2228 // which means thumb, so set bit zero.
2229 code_addr |= 1ull;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002230 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002231 }
2232 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002233 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 break;
2235
2236 default:
2237 break;
2238 }
2239 return code_addr;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002240}
2241
Kate Stoneb9c1b512016-09-06 20:57:50 +00002242lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2243 AddressClass addr_class) const {
2244 addr_t opcode_addr = load_addr;
2245 switch (m_arch.GetMachine()) {
2246 case llvm::Triple::mips:
2247 case llvm::Triple::mipsel:
2248 case llvm::Triple::mips64:
2249 case llvm::Triple::mips64el:
2250 case llvm::Triple::arm:
2251 case llvm::Triple::thumb:
2252 switch (addr_class) {
2253 case eAddressClassData:
2254 case eAddressClassDebug:
2255 return LLDB_INVALID_ADDRESS;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002256
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 case eAddressClassInvalid:
2258 case eAddressClassUnknown:
2259 case eAddressClassCode:
2260 case eAddressClassCodeAlternateISA:
2261 case eAddressClassRuntime:
2262 opcode_addr &= ~(1ull);
2263 break;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002264 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265 break;
2266
2267 default:
2268 break;
2269 }
2270 return opcode_addr;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002271}
2272
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2274 addr_t breakable_addr = addr;
2275 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Greg Clayton9585fbf2013-03-19 00:20:55 +00002276
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 switch (m_arch.GetMachine()) {
2278 default:
2279 break;
2280 case llvm::Triple::mips:
2281 case llvm::Triple::mipsel:
2282 case llvm::Triple::mips64:
2283 case llvm::Triple::mips64el: {
2284 addr_t function_start = 0;
2285 addr_t current_offset = 0;
2286 uint32_t loop_count = 0;
2287 Address resolved_addr;
2288 uint32_t arch_flags = m_arch.GetFlags();
2289 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2290 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2291 SectionLoadList &section_load_list = GetSectionLoadList();
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002292
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293 if (section_load_list.IsEmpty())
2294 // No sections are loaded, so we must assume we are not running yet
2295 // and need to operate only on file address.
2296 m_images.ResolveFileAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002297 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 section_load_list.ResolveLoadAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002299
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300 // Get the function boundaries to make sure we don't scan back before the
2301 // beginning of the current function.
2302 ModuleSP temp_addr_module_sp(resolved_addr.GetModule());
2303 if (temp_addr_module_sp) {
2304 SymbolContext sc;
2305 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2306 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr,
2307 resolve_scope, sc);
2308 Address sym_addr;
2309 if (sc.function)
2310 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2311 else if (sc.symbol)
2312 sym_addr = sc.symbol->GetAddress();
2313
2314 function_start = sym_addr.GetLoadAddress(this);
2315 if (function_start == LLDB_INVALID_ADDRESS)
2316 function_start = sym_addr.GetFileAddress();
2317
2318 if (function_start)
2319 current_offset = addr - function_start;
2320 }
2321
2322 // If breakpoint address is start of function then we dont have to do
2323 // anything.
2324 if (current_offset == 0)
2325 return breakable_addr;
Greg Claytond5944cd2013-12-06 01:12:00 +00002326 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327 loop_count = current_offset / 2;
Greg Claytond5944cd2013-12-06 01:12:00 +00002328
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329 if (loop_count > 3) {
2330 // Scan previous 6 bytes
2331 if (IsMips16 | IsMicromips)
2332 loop_count = 3;
2333 // For mips-only, instructions are always 4 bytes, so scan previous 4
2334 // bytes only.
2335 else
2336 loop_count = 2;
Greg Clayton6b32f1e2013-12-18 02:06:45 +00002337 }
2338
Kate Stoneb9c1b512016-09-06 20:57:50 +00002339 // Create Disassembler Instance
2340 lldb::DisassemblerSP disasm_sp(
2341 Disassembler::FindPlugin(m_arch, nullptr, nullptr));
Todd Fiala75f47c32014-10-11 21:42:09 +00002342
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343 ExecutionContext exe_ctx;
2344 CalculateExecutionContext(exe_ctx);
2345 InstructionList instruction_list;
2346 InstructionSP prev_insn;
2347 bool prefer_file_cache = true; // Read from file
2348 uint32_t inst_to_choose = 0;
2349
2350 for (uint32_t i = 1; i <= loop_count; i++) {
2351 // Adjust the address to read from.
2352 resolved_addr.Slide(-2);
2353 AddressRange range(resolved_addr, i * 2);
2354 uint32_t insn_size = 0;
2355
2356 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2357
2358 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2359 if (num_insns) {
2360 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2361 insn_size = prev_insn->GetOpcode().GetByteSize();
2362 if (i == 1 && insn_size == 2) {
2363 // This looks like a valid 2-byte instruction (but it could be a part
2364 // of upper 4 byte instruction).
2365 instruction_list.Append(prev_insn);
2366 inst_to_choose = 1;
2367 } else if (i == 2) {
2368 // Here we may get one 4-byte instruction or two 2-byte instructions.
2369 if (num_insns == 2) {
2370 // Looks like there are two 2-byte instructions above our breakpoint
2371 // target address.
2372 // Now the upper 2-byte instruction is either a valid 2-byte
2373 // instruction or could be a part of it's upper 4-byte instruction.
2374 // In both cases we don't care because in this case lower 2-byte
2375 // instruction is definitely a valid instruction
2376 // and whatever i=1 iteration has found out is true.
2377 inst_to_choose = 1;
2378 break;
2379 } else if (insn_size == 4) {
2380 // This instruction claims its a valid 4-byte instruction. But it
2381 // could be a part of it's upper 4-byte instruction.
2382 // Lets try scanning upper 2 bytes to verify this.
2383 instruction_list.Append(prev_insn);
2384 inst_to_choose = 2;
2385 }
2386 } else if (i == 3) {
2387 if (insn_size == 4)
2388 // FIXME: We reached here that means instruction at [target - 4] has
2389 // already claimed to be a 4-byte instruction,
2390 // and now instruction at [target - 6] is also claiming that it's a
2391 // 4-byte instruction. This can not be true.
2392 // In this case we can not decide the valid previous instruction so
2393 // we let lldb set the breakpoint at the address given by user.
2394 inst_to_choose = 0;
2395 else
2396 // This is straight-forward
2397 inst_to_choose = 2;
2398 break;
Greg Claytonb09c5382013-12-13 17:20:18 +00002399 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400 } else {
2401 // Decode failed, bytes do not form a valid instruction. So whatever
2402 // previous iteration has found out is true.
2403 if (i > 1) {
2404 inst_to_choose = i - 1;
2405 break;
2406 }
2407 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002408 }
Todd Fiala015d8182014-07-22 23:41:36 +00002409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 // Check if we are able to find any valid instruction.
2411 if (inst_to_choose) {
2412 if (inst_to_choose > instruction_list.GetSize())
2413 inst_to_choose--;
2414 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2415
2416 if (prev_insn->HasDelaySlot()) {
2417 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2418 // Adjust the breakable address
2419 breakable_addr = addr - shift_size;
Todd Fialaac33cc92014-10-09 01:02:08 +00002420 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002421 log->Printf("Target::%s Breakpoint at 0x%8.8" PRIx64
2422 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n",
2423 __FUNCTION__, addr, breakable_addr);
2424 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002425 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426 break;
2427 }
2428 }
2429 return breakable_addr;
2430}
2431
2432SourceManager &Target::GetSourceManager() {
2433 if (!m_source_manager_ap)
2434 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2435 return *m_source_manager_ap;
2436}
2437
2438ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2439 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2440 // we can make it
2441 // per-target
2442
2443 {
2444 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2445
2446 if (!m_clang_modules_decl_vendor_ap) {
2447 m_clang_modules_decl_vendor_ap.reset(
2448 ClangModulesDeclVendor::Create(*this));
2449 }
2450 }
2451
2452 return m_clang_modules_decl_vendor_ap.get();
2453}
2454
2455Target::StopHookSP Target::CreateStopHook() {
2456 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2457 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2458 m_stop_hooks[new_uid] = stop_hook_sp;
2459 return stop_hook_sp;
2460}
2461
2462bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2463 size_t num_removed = m_stop_hooks.erase(user_id);
2464 return (num_removed != 0);
2465}
2466
2467void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2468
2469Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2470 StopHookSP found_hook;
2471
2472 StopHookCollection::iterator specified_hook_iter;
2473 specified_hook_iter = m_stop_hooks.find(user_id);
2474 if (specified_hook_iter != m_stop_hooks.end())
2475 found_hook = (*specified_hook_iter).second;
2476 return found_hook;
2477}
2478
2479bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2480 bool active_state) {
2481 StopHookCollection::iterator specified_hook_iter;
2482 specified_hook_iter = m_stop_hooks.find(user_id);
2483 if (specified_hook_iter == m_stop_hooks.end())
2484 return false;
2485
2486 (*specified_hook_iter).second->SetIsActive(active_state);
2487 return true;
2488}
2489
2490void Target::SetAllStopHooksActiveState(bool active_state) {
2491 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2492 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2493 (*pos).second->SetIsActive(active_state);
2494 }
2495}
2496
2497void Target::RunStopHooks() {
2498 if (m_suppress_stop_hooks)
2499 return;
2500
2501 if (!m_process_sp)
2502 return;
2503
2504 // <rdar://problem/12027563> make sure we check that we are not stopped
2505 // because of us running a user expression
2506 // since in that case we do not want to run the stop-hooks
2507 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2508 return;
2509
2510 if (m_stop_hooks.empty())
2511 return;
2512
2513 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2514
2515 // If there aren't any active stop hooks, don't bother either:
2516 bool any_active_hooks = false;
2517 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2518 if ((*pos).second->IsActive()) {
2519 any_active_hooks = true;
2520 break;
2521 }
2522 }
2523 if (!any_active_hooks)
2524 return;
2525
2526 CommandReturnObject result;
2527
2528 std::vector<ExecutionContext> exc_ctx_with_reasons;
2529 std::vector<SymbolContext> sym_ctx_with_reasons;
2530
2531 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2532 size_t num_threads = cur_threadlist.GetSize();
2533 for (size_t i = 0; i < num_threads; i++) {
2534 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2535 if (cur_thread_sp->ThreadStoppedForAReason()) {
2536 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2537 exc_ctx_with_reasons.push_back(ExecutionContext(
2538 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2539 sym_ctx_with_reasons.push_back(
2540 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2541 }
2542 }
2543
2544 // If no threads stopped for a reason, don't run the stop-hooks.
2545 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2546 if (num_exe_ctx == 0)
2547 return;
2548
2549 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2550 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2551
2552 bool keep_going = true;
2553 bool hooks_ran = false;
2554 bool print_hook_header = (m_stop_hooks.size() != 1);
2555 bool print_thread_header = (num_exe_ctx != 1);
2556
2557 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2558 // result.Clear();
2559 StopHookSP cur_hook_sp = (*pos).second;
2560 if (!cur_hook_sp->IsActive())
2561 continue;
2562
2563 bool any_thread_matched = false;
2564 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2565 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2566 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2567 sym_ctx_with_reasons[i])) &&
2568 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2569 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2570 exc_ctx_with_reasons[i].GetThreadRef()))) {
2571 if (!hooks_ran) {
2572 hooks_ran = true;
2573 }
2574 if (print_hook_header && !any_thread_matched) {
2575 const char *cmd =
2576 (cur_hook_sp->GetCommands().GetSize() == 1
2577 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2578 : nullptr);
2579 if (cmd)
2580 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2581 cur_hook_sp->GetID(), cmd);
2582 else
2583 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2584 cur_hook_sp->GetID());
2585 any_thread_matched = true;
2586 }
2587
2588 if (print_thread_header)
2589 result.AppendMessageWithFormat(
2590 "-- Thread %d\n",
2591 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2592
2593 CommandInterpreterRunOptions options;
2594 options.SetStopOnContinue(true);
2595 options.SetStopOnError(true);
2596 options.SetEchoCommands(false);
2597 options.SetPrintResults(true);
2598 options.SetAddToHistory(false);
2599
2600 GetDebugger().GetCommandInterpreter().HandleCommands(
2601 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2602 result);
2603
2604 // If the command started the target going again, we should bag out of
2605 // running the stop hooks.
2606 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2607 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2608 result.AppendMessageWithFormat("Aborting stop hooks, hook %" PRIu64
2609 " set the program running.",
2610 cur_hook_sp->GetID());
2611 keep_going = false;
2612 }
2613 }
2614 }
2615 }
2616
2617 result.GetImmediateOutputStream()->Flush();
2618 result.GetImmediateErrorStream()->Flush();
2619}
2620
2621const TargetPropertiesSP &Target::GetGlobalProperties() {
2622 // NOTE: intentional leak so we don't crash if global destructor chain gets
2623 // called as other threads still use the result of this function
2624 static TargetPropertiesSP *g_settings_sp_ptr = nullptr;
2625 static std::once_flag g_once_flag;
2626 std::call_once(g_once_flag, []() {
2627 g_settings_sp_ptr = new TargetPropertiesSP(new TargetProperties(nullptr));
2628 });
2629 return *g_settings_sp_ptr;
2630}
2631
2632Error Target::Install(ProcessLaunchInfo *launch_info) {
2633 Error error;
2634 PlatformSP platform_sp(GetPlatform());
2635 if (platform_sp) {
2636 if (platform_sp->IsRemote()) {
2637 if (platform_sp->IsConnected()) {
2638 // Install all files that have an install path, and always install the
2639 // main executable when connected to a remote platform
2640 const ModuleList &modules = GetImages();
2641 const size_t num_images = modules.GetSize();
2642 for (size_t idx = 0; idx < num_images; ++idx) {
2643 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2644 if (module_sp) {
2645 const bool is_main_executable = module_sp == GetExecutableModule();
2646 FileSpec local_file(module_sp->GetFileSpec());
2647 if (local_file) {
2648 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2649 if (!remote_file) {
2650 if (is_main_executable) // TODO: add setting for always
2651 // installing main executable???
2652 {
2653 // Always install the main executable
2654 remote_file = platform_sp->GetRemoteWorkingDirectory();
2655 remote_file.AppendPathComponent(
2656 module_sp->GetFileSpec().GetFilename().GetCString());
2657 }
2658 }
2659 if (remote_file) {
2660 error = platform_sp->Install(local_file, remote_file);
2661 if (error.Success()) {
2662 module_sp->SetPlatformFileSpec(remote_file);
2663 if (is_main_executable) {
2664 platform_sp->SetFilePermissions(remote_file, 0700);
2665 if (launch_info)
2666 launch_info->SetExecutableFile(remote_file, false);
2667 }
2668 } else
2669 break;
2670 }
2671 }
2672 }
2673 }
2674 }
2675 }
2676 }
2677 return error;
2678}
2679
2680bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2681 uint32_t stop_id) {
2682 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2683}
2684
2685bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2686 Address &resolved_addr) {
2687 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2688}
2689
2690bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2691 addr_t new_section_load_addr,
2692 bool warn_multiple) {
2693 const addr_t old_section_load_addr =
2694 m_section_load_history.GetSectionLoadAddress(
2695 SectionLoadHistory::eStopIDNow, section_sp);
2696 if (old_section_load_addr != new_section_load_addr) {
2697 uint32_t stop_id = 0;
2698 ProcessSP process_sp(GetProcessSP());
2699 if (process_sp)
2700 stop_id = process_sp->GetStopID();
Greg Claytonb09c5382013-12-13 17:20:18 +00002701 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 stop_id = m_section_load_history.GetLastStopID();
2703 if (m_section_load_history.SetSectionLoadAddress(
2704 stop_id, section_sp, new_section_load_addr, warn_multiple))
2705 return true; // Return true if the section load address was changed...
2706 }
2707 return false; // Return false to indicate nothing changed
2708}
Todd Fialaac33cc92014-10-09 01:02:08 +00002709
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2711 size_t section_unload_count = 0;
2712 size_t num_modules = module_list.GetSize();
2713 for (size_t i = 0; i < num_modules; ++i) {
2714 section_unload_count +=
2715 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2716 }
2717 return section_unload_count;
2718}
Todd Fiala015d8182014-07-22 23:41:36 +00002719
Kate Stoneb9c1b512016-09-06 20:57:50 +00002720size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2721 uint32_t stop_id = 0;
2722 ProcessSP process_sp(GetProcessSP());
2723 if (process_sp)
2724 stop_id = process_sp->GetStopID();
2725 else
2726 stop_id = m_section_load_history.GetLastStopID();
2727 SectionList *sections = module_sp->GetSectionList();
2728 size_t section_unload_count = 0;
2729 if (sections) {
2730 const uint32_t num_sections = sections->GetNumSections(0);
2731 for (uint32_t i = 0; i < num_sections; ++i) {
2732 section_unload_count += m_section_load_history.SetSectionUnloaded(
2733 stop_id, sections->GetSectionAtIndex(i));
Greg Claytonb09c5382013-12-13 17:20:18 +00002734 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735 }
2736 return section_unload_count;
2737}
2738
2739bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2740 uint32_t stop_id = 0;
2741 ProcessSP process_sp(GetProcessSP());
2742 if (process_sp)
2743 stop_id = process_sp->GetStopID();
2744 else
2745 stop_id = m_section_load_history.GetLastStopID();
2746 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2747}
2748
2749bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2750 addr_t load_addr) {
2751 uint32_t stop_id = 0;
2752 ProcessSP process_sp(GetProcessSP());
2753 if (process_sp)
2754 stop_id = process_sp->GetStopID();
2755 else
2756 stop_id = m_section_load_history.GetLastStopID();
2757 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2758 load_addr);
2759}
2760
2761void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2762
2763Error Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2764 Error error;
2765 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2766
2767 if (log)
2768 log->Printf("Target::%s() called for %s", __FUNCTION__,
2769 launch_info.GetExecutableFile().GetPath().c_str());
2770
2771 StateType state = eStateInvalid;
2772
2773 // Scope to temporarily get the process state in case someone has manually
2774 // remotely connected already to a process and we can skip the platform
2775 // launching.
2776 {
2777 ProcessSP process_sp(GetProcessSP());
2778
2779 if (process_sp) {
2780 state = process_sp->GetState();
2781 if (log)
2782 log->Printf(
2783 "Target::%s the process exists, and its current state is %s",
2784 __FUNCTION__, StateAsCString(state));
2785 } else {
2786 if (log)
2787 log->Printf("Target::%s the process instance doesn't currently exist.",
2788 __FUNCTION__);
2789 }
2790 }
2791
2792 launch_info.GetFlags().Set(eLaunchFlagDebug);
2793
2794 // Get the value of synchronous execution here. If you wait till after you
2795 // have started to
2796 // run, then you could have hit a breakpoint, whose command might switch the
2797 // value, and
2798 // then you'll pick up that incorrect value.
2799 Debugger &debugger = GetDebugger();
2800 const bool synchronous_execution =
2801 debugger.GetCommandInterpreter().GetSynchronous();
2802
2803 PlatformSP platform_sp(GetPlatform());
2804
2805 // Finalize the file actions, and if none were given, default to opening
2806 // up a pseudo terminal
2807 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2808 if (log)
2809 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2810 "default_to_use_pty=%s",
2811 __FUNCTION__, platform_sp ? "true" : "false",
2812 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2813 : "n/a",
2814 default_to_use_pty ? "true" : "false");
2815
2816 launch_info.FinalizeFileActions(this, default_to_use_pty);
2817
2818 if (state == eStateConnected) {
2819 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2820 error.SetErrorString(
2821 "can't launch in tty when launching through a remote connection");
2822 return error;
2823 }
2824 }
2825
2826 if (!launch_info.GetArchitecture().IsValid())
2827 launch_info.GetArchitecture() = GetArchitecture();
2828
2829 // If we're not already connected to the process, and if we have a platform
2830 // that can launch a process for debugging, go ahead and do that here.
2831 if (state != eStateConnected && platform_sp &&
2832 platform_sp->CanDebugProcess()) {
2833 if (log)
2834 log->Printf("Target::%s asking the platform to debug the process",
2835 __FUNCTION__);
2836
2837 // Get a weak pointer to the previous process if we have one
2838 ProcessWP process_wp;
2839 if (m_process_sp)
2840 process_wp = m_process_sp;
2841 m_process_sp =
2842 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2843
2844 // Cleanup the old process since someone might still have a strong
2845 // reference to this process and we would like to allow it to cleanup
2846 // as much as it can without the object being destroyed. We try to
2847 // lock the shared pointer and if that works, then someone else still
2848 // has a strong reference to the process.
2849
2850 ProcessSP old_process_sp(process_wp.lock());
2851 if (old_process_sp)
2852 old_process_sp->Finalize();
2853 } else {
2854 if (log)
2855 log->Printf("Target::%s the platform doesn't know how to debug a "
2856 "process, getting a process plugin to do this for us.",
2857 __FUNCTION__);
2858
2859 if (state == eStateConnected) {
2860 assert(m_process_sp);
2861 } else {
2862 // Use a Process plugin to construct the process.
2863 const char *plugin_name = launch_info.GetProcessPluginName();
2864 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
2865 nullptr);
Greg Claytonb09c5382013-12-13 17:20:18 +00002866 }
2867
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868 // Since we didn't have a platform launch the process, launch it here.
2869 if (m_process_sp)
2870 error = m_process_sp->Launch(launch_info);
2871 }
2872
2873 if (!m_process_sp) {
Greg Claytonb09c5382013-12-13 17:20:18 +00002874 if (error.Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002875 error.SetErrorString("failed to launch or debug process");
Greg Claytonb09c5382013-12-13 17:20:18 +00002876 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002877 }
2878
2879 if (error.Success()) {
2880 if (synchronous_execution ||
2881 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2882 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2883 if (!hijack_listener_sp) {
2884 hijack_listener_sp =
2885 Listener::MakeListener("lldb.Target.Launch.hijack");
2886 launch_info.SetHijackListener(hijack_listener_sp);
2887 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2888 }
2889
2890 StateType state = m_process_sp->WaitForProcessToStop(
2891 std::chrono::microseconds(0), nullptr, false, hijack_listener_sp,
2892 nullptr);
2893
2894 if (state == eStateStopped) {
2895 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2896 if (synchronous_execution) {
2897 error = m_process_sp->PrivateResume();
2898 if (error.Success()) {
2899 state = m_process_sp->WaitForProcessToStop(
2900 std::chrono::microseconds(0), nullptr, true,
2901 hijack_listener_sp, stream);
2902 const bool must_be_alive =
2903 false; // eStateExited is ok, so this must be false
2904 if (!StateIsStoppedState(state, must_be_alive)) {
2905 error.SetErrorStringWithFormat("process isn't stopped: %s",
2906 StateAsCString(state));
2907 }
2908 }
2909 } else {
2910 m_process_sp->RestoreProcessEvents();
2911 error = m_process_sp->PrivateResume();
2912 }
2913 if (!error.Success()) {
2914 Error error2;
2915 error2.SetErrorStringWithFormat(
2916 "process resume at entry point failed: %s", error.AsCString());
2917 error = error2;
2918 }
2919 }
2920 } else if (state == eStateExited) {
2921 bool with_shell = !!launch_info.GetShell();
2922 const int exit_status = m_process_sp->GetExitStatus();
2923 const char *exit_desc = m_process_sp->GetExitDescription();
2924#define LAUNCH_SHELL_MESSAGE \
2925 "\n'r' and 'run' are aliases that default to launching through a " \
2926 "shell.\nTry launching without going through a shell by using 'process " \
2927 "launch'."
2928 if (exit_desc && exit_desc[0]) {
2929 if (with_shell)
2930 error.SetErrorStringWithFormat(
2931 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2932 exit_status, exit_desc);
2933 else
2934 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2935 exit_status, exit_desc);
2936 } else {
2937 if (with_shell)
2938 error.SetErrorStringWithFormat(
2939 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2940 exit_status);
2941 else
2942 error.SetErrorStringWithFormat("process exited with status %i",
2943 exit_status);
2944 }
2945 } else {
2946 error.SetErrorStringWithFormat(
2947 "initial process state wasn't stopped: %s", StateAsCString(state));
2948 }
2949 }
2950 m_process_sp->RestoreProcessEvents();
2951 } else {
2952 Error error2;
2953 error2.SetErrorStringWithFormat("process launch failed: %s",
2954 error.AsCString());
2955 error = error2;
2956 }
2957 return error;
Greg Claytonb09c5382013-12-13 17:20:18 +00002958}
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002959
Kate Stoneb9c1b512016-09-06 20:57:50 +00002960Error Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2961 auto state = eStateInvalid;
2962 auto process_sp = GetProcessSP();
2963 if (process_sp) {
2964 state = process_sp->GetState();
2965 if (process_sp->IsAlive() && state != eStateConnected) {
2966 if (state == eStateAttaching)
2967 return Error("process attach is in progress");
2968 return Error("a process is already being debugged");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002969 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002970 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002971
Kate Stoneb9c1b512016-09-06 20:57:50 +00002972 const ModuleSP old_exec_module_sp = GetExecutableModule();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002973
Kate Stoneb9c1b512016-09-06 20:57:50 +00002974 // If no process info was specified, then use the target executable
2975 // name as the process to attach to by default
2976 if (!attach_info.ProcessInfoSpecified()) {
2977 if (old_exec_module_sp)
2978 attach_info.GetExecutableFile().GetFilename() =
2979 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002980
Kate Stoneb9c1b512016-09-06 20:57:50 +00002981 if (!attach_info.ProcessInfoSpecified()) {
2982 return Error("no process specified, create a target with a file, or "
2983 "specify the --pid or --name");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002984 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002986
Kate Stoneb9c1b512016-09-06 20:57:50 +00002987 const auto platform_sp =
2988 GetDebugger().GetPlatformList().GetSelectedPlatform();
2989 ListenerSP hijack_listener_sp;
2990 const bool async = attach_info.GetAsync();
2991 if (!async) {
2992 hijack_listener_sp =
2993 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
2994 attach_info.SetHijackListener(hijack_listener_sp);
2995 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002996
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997 Error error;
2998 if (state != eStateConnected && platform_sp != nullptr &&
2999 platform_sp->CanDebugProcess()) {
3000 SetPlatform(platform_sp);
3001 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3002 } else {
3003 if (state != eStateConnected) {
3004 const char *plugin_name = attach_info.GetProcessPluginName();
3005 process_sp =
3006 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3007 plugin_name, nullptr);
3008 if (process_sp == nullptr) {
3009 error.SetErrorStringWithFormat(
3010 "failed to create process using plugin %s",
3011 (plugin_name) ? plugin_name : "null");
3012 return error;
3013 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003015 if (hijack_listener_sp)
3016 process_sp->HijackProcessEvents(hijack_listener_sp);
3017 error = process_sp->Attach(attach_info);
3018 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003019
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020 if (error.Success() && process_sp) {
3021 if (async) {
3022 process_sp->RestoreProcessEvents();
3023 } else {
3024 state = process_sp->WaitForProcessToStop(
3025 std::chrono::microseconds(0), nullptr, false,
3026 attach_info.GetHijackListener(), stream);
3027 process_sp->RestoreProcessEvents();
3028
3029 if (state != eStateStopped) {
3030 const char *exit_desc = process_sp->GetExitDescription();
3031 if (exit_desc)
3032 error.SetErrorStringWithFormat("%s", exit_desc);
Greg Claytone75e5d82015-10-20 00:14:20 +00003033 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003034 error.SetErrorString(
3035 "process did not stop (no such process or permission problem?)");
3036 process_sp->Destroy(false);
3037 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003038 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003039 }
3040 return error;
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003041}
3042
Jim Ingham9575d842011-03-11 03:53:59 +00003043//--------------------------------------------------------------
Greg Claytonfbb76342013-11-20 21:07:01 +00003044// Target::StopHook
Jim Ingham9575d842011-03-11 03:53:59 +00003045//--------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3047 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3048 m_thread_spec_ap(), m_active(true) {}
3049
3050Target::StopHook::StopHook(const StopHook &rhs)
3051 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3052 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3053 m_thread_spec_ap(), m_active(rhs.m_active) {
3054 if (rhs.m_thread_spec_ap)
3055 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
Jim Ingham9575d842011-03-11 03:53:59 +00003056}
3057
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003058Target::StopHook::~StopHook() = default;
Jim Ingham9575d842011-03-11 03:53:59 +00003059
Kate Stoneb9c1b512016-09-06 20:57:50 +00003060void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3061 m_specifier_sp.reset(specifier);
Zachary Turner32abc6e2015-03-03 19:23:09 +00003062}
3063
Kate Stoneb9c1b512016-09-06 20:57:50 +00003064void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3065 m_thread_spec_ap.reset(specifier);
Jim Ingham9575d842011-03-11 03:53:59 +00003066}
Jim Ingham9575d842011-03-11 03:53:59 +00003067
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068void Target::StopHook::GetDescription(Stream *s,
3069 lldb::DescriptionLevel level) const {
3070 int indent_level = s->GetIndentLevel();
Jim Ingham9575d842011-03-11 03:53:59 +00003071
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072 s->SetIndentLevel(indent_level + 2);
3073
3074 s->Printf("Hook: %" PRIu64 "\n", GetID());
3075 if (m_active)
3076 s->Indent("State: enabled\n");
3077 else
3078 s->Indent("State: disabled\n");
3079
3080 if (m_specifier_sp) {
3081 s->Indent();
3082 s->PutCString("Specifier:\n");
3083 s->SetIndentLevel(indent_level + 4);
3084 m_specifier_sp->GetDescription(s, level);
Jim Ingham9575d842011-03-11 03:53:59 +00003085 s->SetIndentLevel(indent_level + 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 }
Jim Ingham9575d842011-03-11 03:53:59 +00003087
Kate Stoneb9c1b512016-09-06 20:57:50 +00003088 if (m_thread_spec_ap) {
3089 StreamString tmp;
3090 s->Indent("Thread:\n");
3091 m_thread_spec_ap->GetDescription(&tmp, level);
3092 s->SetIndentLevel(indent_level + 4);
3093 s->Indent(tmp.GetData());
3094 s->PutCString("\n");
3095 s->SetIndentLevel(indent_level + 2);
3096 }
Jim Ingham9575d842011-03-11 03:53:59 +00003097
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098 s->Indent("Commands: \n");
3099 s->SetIndentLevel(indent_level + 4);
3100 uint32_t num_commands = m_commands.GetSize();
3101 for (uint32_t i = 0; i < num_commands; i++) {
3102 s->Indent(m_commands.GetStringAtIndex(i));
3103 s->PutCString("\n");
3104 }
3105 s->SetIndentLevel(indent_level);
Jim Ingham9575d842011-03-11 03:53:59 +00003106}
3107
Greg Clayton67cc0632012-08-22 17:17:09 +00003108//--------------------------------------------------------------
3109// class TargetProperties
3110//--------------------------------------------------------------
3111
Kate Stoneb9c1b512016-09-06 20:57:50 +00003112OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3113 {eNoDynamicValues, "no-dynamic-values",
3114 "Don't calculate the dynamic type of values"},
3115 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3116 "even if you have to run the target."},
3117 {eDynamicDontRunTarget, "no-run-target",
3118 "Calculate the dynamic type of values, but don't run the target."},
3119 {0, nullptr, nullptr}};
Caroline Ticedaccaa92010-09-20 20:44:43 +00003120
Kate Stoneb9c1b512016-09-06 20:57:50 +00003121static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3122 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3123 "locations (fastest). This setting "
3124 "should only be used if you know that "
3125 "no inlining occurs in your programs."},
3126 {eInlineBreakpointsHeaders, "headers",
3127 "Only check for inline breakpoint locations when setting breakpoints in "
3128 "header files, but not when setting breakpoint in implementation source "
3129 "files (default)."},
3130 {eInlineBreakpointsAlways, "always",
3131 "Always look for inline breakpoint locations when setting file and line "
3132 "breakpoints (slower but most accurate)."},
3133 {0, nullptr, nullptr}};
Greg Clayton1f746072012-08-29 21:13:06 +00003134
Kate Stoneb9c1b512016-09-06 20:57:50 +00003135typedef enum x86DisassemblyFlavor {
3136 eX86DisFlavorDefault,
3137 eX86DisFlavorIntel,
3138 eX86DisFlavorATT
Jim Ingham0f063ba2013-03-02 00:26:47 +00003139} x86DisassemblyFlavor;
3140
Kate Stoneb9c1b512016-09-06 20:57:50 +00003141static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3142 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3143 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3144 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3145 {0, nullptr, nullptr}};
3146
3147static OptionEnumValueElement g_hex_immediate_style_values[] = {
3148 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3149 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3150 {0, nullptr, nullptr}};
3151
3152static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3153 {eLoadScriptFromSymFileTrue, "true",
3154 "Load debug scripts inside symbol files"},
3155 {eLoadScriptFromSymFileFalse, "false",
3156 "Do not load debug scripts inside symbol files."},
3157 {eLoadScriptFromSymFileWarn, "warn",
3158 "Warn about debug scripts inside symbol files but do not load them."},
3159 {0, nullptr, nullptr}};
3160
3161static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3162 {eLoadCWDlldbinitTrue, "true",
3163 "Load .lldbinit files from current directory"},
3164 {eLoadCWDlldbinitFalse, "false",
3165 "Do not load .lldbinit files from current directory"},
3166 {eLoadCWDlldbinitWarn, "warn",
3167 "Warn about loading .lldbinit files from current directory"},
3168 {0, nullptr, nullptr}};
3169
3170static OptionEnumValueElement g_memory_module_load_level_values[] = {
3171 {eMemoryModuleLoadLevelMinimal, "minimal",
3172 "Load minimal information when loading modules from memory. Currently "
3173 "this setting loads sections only."},
3174 {eMemoryModuleLoadLevelPartial, "partial",
3175 "Load partial information when loading modules from memory. Currently "
3176 "this setting loads sections and function bounds."},
3177 {eMemoryModuleLoadLevelComplete, "complete",
3178 "Load complete information when loading modules from memory. Currently "
3179 "this setting loads sections and all symbols."},
3180 {0, nullptr, nullptr}};
3181
3182static PropertyDefinition g_properties[] = {
3183 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3184 "Default architecture to choose, when there's a choice."},
3185 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3186 nullptr, "Move breakpoints to nearest code."},
3187 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3188 nullptr, nullptr,
3189 "The language to use when interpreting expressions entered in commands."},
3190 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3191 "Path to a file containing expressions to be prepended to all "
3192 "expressions."},
3193 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3194 eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3195 "Should printed values be shown as their dynamic value."},
3196 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3197 nullptr, "Should synthetic values be used by default whenever available."},
3198 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3199 "Skip function prologues when setting breakpoints by name."},
3200 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3201 "Source path remappings are used to track the change of location between "
3202 "a source file when built, and "
3203 "where it exists on the current system. It consists of an array of "
3204 "duples, the first element of each duple is "
3205 "some part (starting at the root) of the path to the file when it was "
3206 "built, "
3207 "and the second is where the remainder of the original build hierarchy is "
3208 "rooted on the local system. "
3209 "Each element of the array is checked in order and the first one that "
3210 "results in a match wins."},
3211 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3212 nullptr, "Executable search paths to use when locating executable files "
3213 "whose paths don't match the local file system."},
3214 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3215 nullptr, nullptr,
3216 "List of directories to be searched when locating debug symbol files."},
3217 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3218 nullptr, nullptr,
3219 "List of directories to be searched when locating modules for Clang."},
3220 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3221 nullptr, nullptr,
3222 "Automatically load Clang modules referred to by the program."},
3223 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3224 nullptr, "Automatically apply fix-it hints to expressions."},
3225 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3226 nullptr, "Print the fixed expression text."},
3227 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3228 nullptr, "Maximum number of children to expand in any level of depth."},
3229 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3230 nullptr, nullptr,
3231 "Maximum number of characters to show when using %s in summary strings."},
3232 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3233 nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3234 "--force must be specified."},
3235 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3236 true, nullptr, nullptr, "Consult the platform module avoid list when "
3237 "setting non-module specific breakpoints."},
3238 {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3239 "The first argument passed to the program in the argument array which can "
3240 "be different from the executable itself."},
3241 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3242 "A list containing all the arguments to be passed to the executable when "
3243 "it is run. Note that this does NOT include the argv[0] which is in "
3244 "target.arg0."},
3245 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3246 nullptr, nullptr, "A list of all the environment variables to be passed "
3247 "to the executable's environment, and their values."},
3248 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3249 "Inherit the environment from the process that is running LLDB."},
3250 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3251 "The file/path to be used by the executable program for reading its "
3252 "standard input."},
3253 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3254 "The file/path to be used by the executable program for writing its "
3255 "standard output."},
3256 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3257 "The file/path to be used by the executable program for writing its "
3258 "standard error."},
3259 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3260 nullptr, "debugserver will detach (rather than killing) a process if it "
3261 "loses connection with lldb."},
3262 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3263 "Disable Address Space Layout Randomization (ASLR)"},
3264 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3265 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3266 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3267 eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3268 "The strategy to use when settings breakpoints by file and line. "
3269 "Breakpoint locations can end up being inlined by the compiler, so that a "
3270 "compile unit 'a.c' might contain an inlined function from another source "
3271 "file. "
3272 "Usually this is limited to breakpoint locations from inlined functions "
3273 "from header or other include files, or more accurately "
3274 "non-implementation source files. "
3275 "Sometimes code might #include implementation files and cause inlined "
3276 "breakpoint locations in inlined implementation files. "
3277 "Always checking for inlined breakpoint locations can be expensive "
3278 "(memory and time), so if you have a project with many headers "
3279 "and find that setting breakpoints is slow, then you can change this "
3280 "setting to headers. "
3281 "This setting allows you to control exactly which strategy is used when "
3282 "setting "
3283 "file and line breakpoints."},
3284 // FIXME: This is the wrong way to do per-architecture settings, but we
3285 // don't have a general per architecture settings system in place yet.
3286 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3287 eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3288 "The default disassembly flavor to use for x86 or x86-64 targets."},
3289 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3290 nullptr, "Show immediates in disassembly as hexadecimal."},
3291 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3292 Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3293 "Which style to use for printing hexadecimal disassembly values."},
3294 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3295 nullptr, "Use a fast stepping algorithm based on running from branch to "
3296 "branch rather than instruction single-stepping."},
3297 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3298 eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3299 "Allow LLDB to load scripting resources embedded in symbol files when "
3300 "available."},
3301 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3302 nullptr, g_load_current_working_dir_lldbinit_values,
3303 "Allow LLDB to .lldbinit files from the current directory automatically."},
3304 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3305 eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3306 "Loading modules from memory can be slow as reading the symbol tables and "
3307 "other data can take a long time depending on your connection to the "
3308 "debug target. "
3309 "This setting helps users control how much information gets loaded when "
3310 "loading modules from memory."
3311 "'complete' is the default value for this setting which will load all "
3312 "sections and symbols by reading them from memory (slowest, most "
3313 "accurate). "
3314 "'partial' will load sections and attempt to find function bounds without "
3315 "downloading the symbol table (faster, still accurate, missing symbol "
3316 "names). "
3317 "'minimal' is the fastest setting and will load section data with no "
3318 "symbols, but should rarely be used as stack frames in these memory "
3319 "regions will be inaccurate and not provide any context (fastest). "},
3320 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3321 nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3322 "the host system supports executable specific crash log "
3323 "strings and this setting is set to true."},
3324 {"trap-handler-names", OptionValue::eTypeArray, true,
3325 OptionValue::eTypeString, nullptr, nullptr,
3326 "A list of trap handler function names, e.g. a common Unix user process "
3327 "one is _sigtramp."},
3328 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3329 nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3330 "support the operation of a language's runtime "
3331 "support."},
3332 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3333 "Disable lock-step debugging, instead control threads independently."},
3334 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3335
3336enum {
3337 ePropertyDefaultArch,
3338 ePropertyMoveToNearestCode,
3339 ePropertyLanguage,
3340 ePropertyExprPrefix,
3341 ePropertyPreferDynamic,
3342 ePropertyEnableSynthetic,
3343 ePropertySkipPrologue,
3344 ePropertySourceMap,
3345 ePropertyExecutableSearchPaths,
3346 ePropertyDebugFileSearchPaths,
3347 ePropertyClangModuleSearchPaths,
3348 ePropertyAutoImportClangModules,
3349 ePropertyAutoApplyFixIts,
3350 ePropertyNotifyAboutFixIts,
3351 ePropertyMaxChildrenCount,
3352 ePropertyMaxSummaryLength,
3353 ePropertyMaxMemReadSize,
3354 ePropertyBreakpointUseAvoidList,
3355 ePropertyArg0,
3356 ePropertyRunArgs,
3357 ePropertyEnvVars,
3358 ePropertyInheritEnv,
3359 ePropertyInputPath,
3360 ePropertyOutputPath,
3361 ePropertyErrorPath,
3362 ePropertyDetachOnError,
3363 ePropertyDisableASLR,
3364 ePropertyDisableSTDIO,
3365 ePropertyInlineStrategy,
3366 ePropertyDisassemblyFlavor,
3367 ePropertyUseHexImmediates,
3368 ePropertyHexImmediateStyle,
3369 ePropertyUseFastStepping,
3370 ePropertyLoadScriptFromSymbolFile,
3371 ePropertyLoadCWDlldbinitFile,
3372 ePropertyMemoryModuleLoadLevel,
3373 ePropertyDisplayExpressionsInCrashlogs,
3374 ePropertyTrapHandlerNames,
3375 ePropertyDisplayRuntimeSupportValues,
3376 ePropertyNonStopModeEnabled,
3377 ePropertyExperimental
Jim Ingham0f063ba2013-03-02 00:26:47 +00003378};
3379
Kate Stoneb9c1b512016-09-06 20:57:50 +00003380class TargetOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +00003381public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003382 TargetOptionValueProperties(const ConstString &name)
3383 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
Caroline Ticedaccaa92010-09-20 20:44:43 +00003384
Kate Stoneb9c1b512016-09-06 20:57:50 +00003385 // This constructor is used when creating TargetOptionValueProperties when it
3386 // is part of a new lldb_private::Target instance. It will copy all current
3387 // global property values as needed
3388 TargetOptionValueProperties(Target *target,
3389 const TargetPropertiesSP &target_properties_sp)
3390 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3391 m_target(target), m_got_host_env(false) {}
Greg Clayton67cc0632012-08-22 17:17:09 +00003392
Kate Stoneb9c1b512016-09-06 20:57:50 +00003393 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3394 bool will_modify,
3395 uint32_t idx) const override {
3396 // When getting the value for a key from the target options, we will always
3397 // try and grab the setting from the current target if there is one. Else we
3398 // just
3399 // use the one from this instance.
3400 if (idx == ePropertyEnvVars)
3401 GetHostEnvironmentIfNeeded();
3402
3403 if (exe_ctx) {
3404 Target *target = exe_ctx->GetTargetPtr();
3405 if (target) {
3406 TargetOptionValueProperties *target_properties =
3407 static_cast<TargetOptionValueProperties *>(
3408 target->GetValueProperties().get());
3409 if (this != target_properties)
3410 return target_properties->ProtectedGetPropertyAtIndex(idx);
3411 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003412 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003413 return ProtectedGetPropertyAtIndex(idx);
3414 }
3415
3416 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3417
Greg Clayton67cc0632012-08-22 17:17:09 +00003418protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003419 void GetHostEnvironmentIfNeeded() const {
3420 if (!m_got_host_env) {
3421 if (m_target) {
3422 m_got_host_env = true;
3423 const uint32_t idx = ePropertyInheritEnv;
3424 if (GetPropertyAtIndexAsBoolean(
3425 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3426 PlatformSP platform_sp(m_target->GetPlatform());
3427 if (platform_sp) {
3428 StringList env;
3429 if (platform_sp->GetEnvironment(env)) {
3430 OptionValueDictionary *env_dict =
3431 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3432 ePropertyEnvVars);
3433 if (env_dict) {
3434 const bool can_replace = false;
3435 const size_t envc = env.GetSize();
3436 for (size_t idx = 0; idx < envc; idx++) {
3437 const char *env_entry = env.GetStringAtIndex(idx);
3438 if (env_entry) {
3439 const char *equal_pos = ::strchr(env_entry, '=');
3440 ConstString key;
3441 // It is ok to have environment variables with no values
3442 const char *value = nullptr;
3443 if (equal_pos) {
3444 key.SetCStringWithLength(env_entry,
3445 equal_pos - env_entry);
3446 if (equal_pos[1])
3447 value = equal_pos + 1;
3448 } else {
3449 key.SetCString(env_entry);
Greg Clayton67cc0632012-08-22 17:17:09 +00003450 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003451 // Don't allow existing keys to be replaced with ones we get
3452 // from the platform environment
3453 env_dict->SetValueForKey(
3454 key, OptionValueSP(new OptionValueString(value)),
3455 can_replace);
3456 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003457 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003458 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003459 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003460 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003461 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003462 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003463 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003464 }
3465 Target *m_target;
3466 mutable bool m_got_host_env;
Greg Clayton67cc0632012-08-22 17:17:09 +00003467};
3468
Greg Claytonfbb76342013-11-20 21:07:01 +00003469//----------------------------------------------------------------------
3470// TargetProperties
3471//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003472static PropertyDefinition g_experimental_properties[]{
3473 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3474 nullptr,
3475 "If true, inject local variables explicitly into the expression text. "
3476 "This will fix symbol resolution when there are name collisions between "
3477 "ivars and local variables. "
3478 "But it can make expressions run much more slowly."},
3479 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Jim Inghambed67792016-07-07 18:25:48 +00003480
Kate Stoneb9c1b512016-09-06 20:57:50 +00003481enum { ePropertyInjectLocalVars = 0 };
Jim Inghambed67792016-07-07 18:25:48 +00003482
Kate Stoneb9c1b512016-09-06 20:57:50 +00003483class TargetExperimentalOptionValueProperties : public OptionValueProperties {
Jim Inghambed67792016-07-07 18:25:48 +00003484public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003485 TargetExperimentalOptionValueProperties()
3486 : OptionValueProperties(
3487 ConstString(Properties::GetExperimentalSettingsName())) {}
Jim Inghambed67792016-07-07 18:25:48 +00003488};
3489
Kate Stoneb9c1b512016-09-06 20:57:50 +00003490TargetExperimentalProperties::TargetExperimentalProperties()
3491 : Properties(OptionValuePropertiesSP(
3492 new TargetExperimentalOptionValueProperties())) {
3493 m_collection_sp->Initialize(g_experimental_properties);
Jim Inghambed67792016-07-07 18:25:48 +00003494}
3495
3496//----------------------------------------------------------------------
3497// TargetProperties
3498//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003499TargetProperties::TargetProperties(Target *target)
3500 : Properties(), m_launch_info() {
3501 if (target) {
3502 m_collection_sp.reset(
3503 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
Ilia K8f37ca52015-02-13 14:31:06 +00003504
Kate Stoneb9c1b512016-09-06 20:57:50 +00003505 // Set callbacks to update launch_info whenever "settins set" updated any of
3506 // these properties
3507 m_collection_sp->SetValueChangedCallback(
3508 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3509 m_collection_sp->SetValueChangedCallback(
3510 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3511 m_collection_sp->SetValueChangedCallback(
3512 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3513 m_collection_sp->SetValueChangedCallback(
3514 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3515 this);
3516 m_collection_sp->SetValueChangedCallback(
3517 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3518 this);
3519 m_collection_sp->SetValueChangedCallback(
3520 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3521 this);
3522 m_collection_sp->SetValueChangedCallback(
3523 ePropertyDetachOnError,
3524 TargetProperties::DetachOnErrorValueChangedCallback, this);
3525 m_collection_sp->SetValueChangedCallback(
3526 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3527 this);
3528 m_collection_sp->SetValueChangedCallback(
3529 ePropertyDisableSTDIO,
3530 TargetProperties::DisableSTDIOValueChangedCallback, this);
Jim Inghambed67792016-07-07 18:25:48 +00003531
Kate Stoneb9c1b512016-09-06 20:57:50 +00003532 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3533 m_collection_sp->AppendProperty(
3534 ConstString(Properties::GetExperimentalSettingsName()),
3535 ConstString("Experimental settings - setting these won't produce "
3536 "errors if the setting is not present."),
3537 true, m_experimental_properties_up->GetValueProperties());
Jim Inghambed67792016-07-07 18:25:48 +00003538
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539 // Update m_launch_info once it was created
3540 Arg0ValueChangedCallback(this, nullptr);
3541 RunArgsValueChangedCallback(this, nullptr);
3542 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3543 // Target::GetPlatform()
3544 InputPathValueChangedCallback(this, nullptr);
3545 OutputPathValueChangedCallback(this, nullptr);
3546 ErrorPathValueChangedCallback(this, nullptr);
3547 DetachOnErrorValueChangedCallback(this, nullptr);
3548 DisableASLRValueChangedCallback(this, nullptr);
3549 DisableSTDIOValueChangedCallback(this, nullptr);
3550 } else {
3551 m_collection_sp.reset(
3552 new TargetOptionValueProperties(ConstString("target")));
3553 m_collection_sp->Initialize(g_properties);
3554 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());
3560 m_collection_sp->AppendProperty(
3561 ConstString("process"), ConstString("Settings specific to processes."),
3562 true, Process::GetGlobalProperties()->GetValueProperties());
3563 }
Caroline Ticedaccaa92010-09-20 20:44:43 +00003564}
3565
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003566TargetProperties::~TargetProperties() = default;
3567
Kate Stoneb9c1b512016-09-06 20:57:50 +00003568bool TargetProperties::GetInjectLocalVariables(
3569 ExecutionContext *exe_ctx) const {
3570 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3571 exe_ctx, false, ePropertyExperimental);
3572 OptionValueProperties *exp_values =
3573 exp_property->GetValue()->GetAsProperties();
3574 if (exp_values)
3575 return exp_values->GetPropertyAtIndexAsBoolean(
3576 exe_ctx, ePropertyInjectLocalVars, true);
3577 else
3578 return true;
Jim Inghambed67792016-07-07 18:25:48 +00003579}
3580
Kate Stoneb9c1b512016-09-06 20:57:50 +00003581void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3582 bool b) {
3583 const Property *exp_property =
3584 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3585 OptionValueProperties *exp_values =
3586 exp_property->GetValue()->GetAsProperties();
3587 if (exp_values)
3588 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3589 true);
Jim Inghambed67792016-07-07 18:25:48 +00003590}
3591
Kate Stoneb9c1b512016-09-06 20:57:50 +00003592ArchSpec TargetProperties::GetDefaultArchitecture() const {
3593 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3594 nullptr, ePropertyDefaultArch);
3595 if (value)
3596 return value->GetCurrentValue();
3597 return ArchSpec();
Greg Clayton67cc0632012-08-22 17:17:09 +00003598}
3599
Kate Stoneb9c1b512016-09-06 20:57:50 +00003600void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3601 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3602 nullptr, ePropertyDefaultArch);
3603 if (value)
3604 return value->SetCurrentValue(arch, true);
Greg Clayton67cc0632012-08-22 17:17:09 +00003605}
3606
Kate Stoneb9c1b512016-09-06 20:57:50 +00003607bool TargetProperties::GetMoveToNearestCode() const {
3608 const uint32_t idx = ePropertyMoveToNearestCode;
3609 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3610 nullptr, idx, g_properties[idx].default_uint_value != 0);
Ilia K055ad9b2015-05-18 13:41:01 +00003611}
3612
Kate Stoneb9c1b512016-09-06 20:57:50 +00003613lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3614 const uint32_t idx = ePropertyPreferDynamic;
3615 return (lldb::DynamicValueType)
3616 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3617 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003618}
3619
Kate Stoneb9c1b512016-09-06 20:57:50 +00003620bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3621 const uint32_t idx = ePropertyPreferDynamic;
3622 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
Greg Clayton15484402015-05-15 18:40:24 +00003623}
3624
Kate Stoneb9c1b512016-09-06 20:57:50 +00003625bool TargetProperties::GetDisableASLR() const {
3626 const uint32_t idx = ePropertyDisableASLR;
3627 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3628 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003629}
3630
Kate Stoneb9c1b512016-09-06 20:57:50 +00003631void TargetProperties::SetDisableASLR(bool b) {
3632 const uint32_t idx = ePropertyDisableASLR;
3633 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003634}
3635
Kate Stoneb9c1b512016-09-06 20:57:50 +00003636bool TargetProperties::GetDetachOnError() const {
3637 const uint32_t idx = ePropertyDetachOnError;
3638 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3639 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham106d0282014-06-25 02:32:56 +00003640}
3641
Kate Stoneb9c1b512016-09-06 20:57:50 +00003642void TargetProperties::SetDetachOnError(bool b) {
3643 const uint32_t idx = ePropertyDetachOnError;
3644 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Jim Ingham106d0282014-06-25 02:32:56 +00003645}
3646
Kate Stoneb9c1b512016-09-06 20:57:50 +00003647bool TargetProperties::GetDisableSTDIO() const {
3648 const uint32_t idx = ePropertyDisableSTDIO;
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::SetDisableSTDIO(bool b) {
3654 const uint32_t idx = ePropertyDisableSTDIO;
3655 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003656}
3657
Kate Stoneb9c1b512016-09-06 20:57:50 +00003658const char *TargetProperties::GetDisassemblyFlavor() const {
3659 const uint32_t idx = ePropertyDisassemblyFlavor;
3660 const char *return_value;
3661
3662 x86DisassemblyFlavor flavor_value =
3663 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3664 nullptr, idx, g_properties[idx].default_uint_value);
3665 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3666 return return_value;
Jim Ingham0f063ba2013-03-02 00:26:47 +00003667}
3668
Kate Stoneb9c1b512016-09-06 20:57:50 +00003669InlineStrategy TargetProperties::GetInlineStrategy() const {
3670 const uint32_t idx = ePropertyInlineStrategy;
3671 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3672 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton1f746072012-08-29 21:13:06 +00003673}
3674
Kate Stoneb9c1b512016-09-06 20:57:50 +00003675const char *TargetProperties::GetArg0() const {
3676 const uint32_t idx = ePropertyArg0;
3677 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, nullptr);
Greg Clayton45392552012-10-17 22:57:12 +00003678}
3679
Kate Stoneb9c1b512016-09-06 20:57:50 +00003680void TargetProperties::SetArg0(const char *arg) {
3681 const uint32_t idx = ePropertyArg0;
3682 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3683 m_launch_info.SetArg0(arg);
Greg Clayton45392552012-10-17 22:57:12 +00003684}
3685
Kate Stoneb9c1b512016-09-06 20:57:50 +00003686bool TargetProperties::GetRunArguments(Args &args) const {
3687 const uint32_t idx = ePropertyRunArgs;
3688 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +00003689}
3690
Kate Stoneb9c1b512016-09-06 20:57:50 +00003691void TargetProperties::SetRunArguments(const Args &args) {
3692 const uint32_t idx = ePropertyRunArgs;
3693 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3694 m_launch_info.GetArguments() = args;
Greg Clayton67cc0632012-08-22 17:17:09 +00003695}
3696
Kate Stoneb9c1b512016-09-06 20:57:50 +00003697size_t TargetProperties::GetEnvironmentAsArgs(Args &env) const {
3698 const uint32_t idx = ePropertyEnvVars;
3699 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
Greg Clayton67cc0632012-08-22 17:17:09 +00003700}
3701
Kate Stoneb9c1b512016-09-06 20:57:50 +00003702void TargetProperties::SetEnvironmentFromArgs(const Args &env) {
3703 const uint32_t idx = ePropertyEnvVars;
3704 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, env);
3705 m_launch_info.GetEnvironmentEntries() = env;
Ilia K8f37ca52015-02-13 14:31:06 +00003706}
3707
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708bool TargetProperties::GetSkipPrologue() const {
3709 const uint32_t idx = ePropertySkipPrologue;
3710 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3711 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003712}
3713
Kate Stoneb9c1b512016-09-06 20:57:50 +00003714PathMappingList &TargetProperties::GetSourcePathMap() const {
3715 const uint32_t idx = ePropertySourceMap;
3716 OptionValuePathMappings *option_value =
3717 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3718 false, idx);
3719 assert(option_value);
3720 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003721}
3722
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3724 const uint32_t idx = ePropertyExecutableSearchPaths;
3725 OptionValueFileSpecList *option_value =
3726 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3727 false, idx);
3728 assert(option_value);
3729 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003730}
3731
Kate Stoneb9c1b512016-09-06 20:57:50 +00003732FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3733 const uint32_t idx = ePropertyDebugFileSearchPaths;
3734 OptionValueFileSpecList *option_value =
3735 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3736 false, idx);
3737 assert(option_value);
3738 return option_value->GetCurrentValue();
Michael Sartaina7499c92013-07-01 19:45:50 +00003739}
3740
Kate Stoneb9c1b512016-09-06 20:57:50 +00003741FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3742 const uint32_t idx = ePropertyClangModuleSearchPaths;
3743 OptionValueFileSpecList *option_value =
3744 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3745 false, idx);
3746 assert(option_value);
3747 return option_value->GetCurrentValue();
Sean Callanan85054342015-04-03 15:39:47 +00003748}
3749
Kate Stoneb9c1b512016-09-06 20:57:50 +00003750bool TargetProperties::GetEnableAutoImportClangModules() const {
3751 const uint32_t idx = ePropertyAutoImportClangModules;
3752 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3753 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callananf0c5aeb2015-04-20 16:31:29 +00003754}
3755
Kate Stoneb9c1b512016-09-06 20:57:50 +00003756bool TargetProperties::GetEnableAutoApplyFixIts() const {
3757 const uint32_t idx = ePropertyAutoApplyFixIts;
3758 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3759 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghama1e541b2016-03-25 01:57:14 +00003760}
3761
Kate Stoneb9c1b512016-09-06 20:57:50 +00003762bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3763 const uint32_t idx = ePropertyNotifyAboutFixIts;
3764 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3765 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghame5ee6f02016-03-29 22:00:08 +00003766}
3767
Kate Stoneb9c1b512016-09-06 20:57:50 +00003768bool TargetProperties::GetEnableSyntheticValue() const {
3769 const uint32_t idx = ePropertyEnableSynthetic;
3770 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3771 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003772}
3773
Kate Stoneb9c1b512016-09-06 20:57:50 +00003774uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3775 const uint32_t idx = ePropertyMaxChildrenCount;
3776 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3777 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003778}
3779
Kate Stoneb9c1b512016-09-06 20:57:50 +00003780uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3781 const uint32_t idx = ePropertyMaxSummaryLength;
3782 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3783 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003784}
3785
Kate Stoneb9c1b512016-09-06 20:57:50 +00003786uint32_t TargetProperties::GetMaximumMemReadSize() const {
3787 const uint32_t idx = ePropertyMaxMemReadSize;
3788 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3789 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granatad325bf92013-06-04 22:54:16 +00003790}
3791
Kate Stoneb9c1b512016-09-06 20:57:50 +00003792FileSpec TargetProperties::GetStandardInputPath() const {
3793 const uint32_t idx = ePropertyInputPath;
3794 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003795}
3796
Kate Stoneb9c1b512016-09-06 20:57:50 +00003797void TargetProperties::SetStandardInputPath(const char *p) {
3798 const uint32_t idx = ePropertyInputPath;
3799 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Greg Clayton67cc0632012-08-22 17:17:09 +00003800}
3801
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802FileSpec TargetProperties::GetStandardOutputPath() const {
3803 const uint32_t idx = ePropertyOutputPath;
3804 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003805}
3806
Kate Stoneb9c1b512016-09-06 20:57:50 +00003807void TargetProperties::SetStandardOutputPath(const char *p) {
3808 const uint32_t idx = ePropertyOutputPath;
3809 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Greg Clayton67cc0632012-08-22 17:17:09 +00003810}
3811
Kate Stoneb9c1b512016-09-06 20:57:50 +00003812FileSpec TargetProperties::GetStandardErrorPath() const {
3813 const uint32_t idx = ePropertyErrorPath;
3814 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003815}
3816
Kate Stoneb9c1b512016-09-06 20:57:50 +00003817LanguageType TargetProperties::GetLanguage() const {
3818 OptionValueLanguage *value =
3819 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3820 nullptr, ePropertyLanguage);
3821 if (value)
3822 return value->GetCurrentValue();
3823 return LanguageType();
Dawn Perchik23b1dec2015-07-21 22:05:07 +00003824}
3825
Kate Stoneb9c1b512016-09-06 20:57:50 +00003826const char *TargetProperties::GetExpressionPrefixContentsAsCString() {
3827 const uint32_t idx = ePropertyExprPrefix;
3828 OptionValueFileSpec *file =
3829 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3830 idx);
3831 if (file) {
3832 const bool null_terminate = true;
3833 DataBufferSP data_sp(file->GetFileContents(null_terminate));
3834 if (data_sp)
3835 return (const char *)data_sp->GetBytes();
3836 }
3837 return nullptr;
Greg Clayton6920b522012-08-22 18:39:03 +00003838}
3839
Kate Stoneb9c1b512016-09-06 20:57:50 +00003840void TargetProperties::SetStandardErrorPath(const char *p) {
3841 const uint32_t idx = ePropertyErrorPath;
3842 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
Greg Clayton67cc0632012-08-22 17:17:09 +00003843}
3844
Kate Stoneb9c1b512016-09-06 20:57:50 +00003845bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3846 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3847 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3848 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003849}
3850
Kate Stoneb9c1b512016-09-06 20:57:50 +00003851bool TargetProperties::GetUseHexImmediates() const {
3852 const uint32_t idx = ePropertyUseHexImmediates;
3853 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3854 nullptr, idx, g_properties[idx].default_uint_value != 0);
Daniel Malead79ae052013-08-07 21:54:09 +00003855}
3856
Kate Stoneb9c1b512016-09-06 20:57:50 +00003857bool TargetProperties::GetUseFastStepping() const {
3858 const uint32_t idx = ePropertyUseFastStepping;
3859 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3860 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham17d023f2013-03-13 17:58:04 +00003861}
3862
Kate Stoneb9c1b512016-09-06 20:57:50 +00003863bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3864 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3865 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3866 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Claytonfb6621e2013-12-06 21:59:52 +00003867}
3868
Kate Stoneb9c1b512016-09-06 20:57:50 +00003869LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3870 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3871 return (LoadScriptFromSymFile)
3872 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3873 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granata2ea43cd2013-05-13 17:03:52 +00003874}
3875
Kate Stoneb9c1b512016-09-06 20:57:50 +00003876LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3877 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3878 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3879 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molenda878ae012016-02-19 00:05:17 +00003880}
3881
Kate Stoneb9c1b512016-09-06 20:57:50 +00003882Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3883 const uint32_t idx = ePropertyHexImmediateStyle;
3884 return (Disassembler::HexImmediateStyle)
3885 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3886 nullptr, idx, g_properties[idx].default_uint_value);
Daniel Malead79ae052013-08-07 21:54:09 +00003887}
3888
Kate Stoneb9c1b512016-09-06 20:57:50 +00003889MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3890 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3891 return (MemoryModuleLoadLevel)
3892 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3893 nullptr, idx, g_properties[idx].default_uint_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00003894}
3895
Kate Stoneb9c1b512016-09-06 20:57:50 +00003896bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3897 const uint32_t idx = ePropertyTrapHandlerNames;
3898 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003899}
Greg Claytonfd814c52013-08-13 01:42:25 +00003900
Kate Stoneb9c1b512016-09-06 20:57:50 +00003901void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3902 const uint32_t idx = ePropertyTrapHandlerNames;
3903 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003904}
Greg Clayton67cc0632012-08-22 17:17:09 +00003905
Kate Stoneb9c1b512016-09-06 20:57:50 +00003906bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3907 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3908 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Enrico Granata560558e2015-02-11 02:35:39 +00003909}
3910
Kate Stoneb9c1b512016-09-06 20:57:50 +00003911void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3912 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3913 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granata560558e2015-02-11 02:35:39 +00003914}
3915
Kate Stoneb9c1b512016-09-06 20:57:50 +00003916bool TargetProperties::GetNonStopModeEnabled() const {
3917 const uint32_t idx = ePropertyNonStopModeEnabled;
3918 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Ewan Crawford78baa192015-05-13 09:18:18 +00003919}
3920
Kate Stoneb9c1b512016-09-06 20:57:50 +00003921void TargetProperties::SetNonStopModeEnabled(bool b) {
3922 const uint32_t idx = ePropertyNonStopModeEnabled;
3923 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00003924}
3925
Kate Stoneb9c1b512016-09-06 20:57:50 +00003926const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3927 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3928 return m_launch_info;
Ilia K8f37ca52015-02-13 14:31:06 +00003929}
3930
Kate Stoneb9c1b512016-09-06 20:57:50 +00003931void TargetProperties::SetProcessLaunchInfo(
3932 const ProcessLaunchInfo &launch_info) {
3933 m_launch_info = launch_info;
3934 SetArg0(launch_info.GetArg0());
3935 SetRunArguments(launch_info.GetArguments());
3936 SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
3937 const FileAction *input_file_action =
3938 launch_info.GetFileActionForFD(STDIN_FILENO);
3939 if (input_file_action) {
3940 const char *input_path = input_file_action->GetPath();
3941 if (input_path)
3942 SetStandardInputPath(input_path);
3943 }
3944 const FileAction *output_file_action =
3945 launch_info.GetFileActionForFD(STDOUT_FILENO);
3946 if (output_file_action) {
3947 const char *output_path = output_file_action->GetPath();
3948 if (output_path)
3949 SetStandardOutputPath(output_path);
3950 }
3951 const FileAction *error_file_action =
3952 launch_info.GetFileActionForFD(STDERR_FILENO);
3953 if (error_file_action) {
3954 const char *error_path = error_file_action->GetPath();
3955 if (error_path)
3956 SetStandardErrorPath(error_path);
3957 }
3958 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3959 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3960 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
Ilia K8f37ca52015-02-13 14:31:06 +00003961}
3962
Kate Stoneb9c1b512016-09-06 20:57:50 +00003963void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
3964 OptionValue *) {
3965 TargetProperties *this_ =
3966 reinterpret_cast<TargetProperties *>(target_property_ptr);
3967 this_->m_launch_info.SetArg0(this_->GetArg0());
Ilia K8f37ca52015-02-13 14:31:06 +00003968}
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
3971 OptionValue *) {
3972 TargetProperties *this_ =
3973 reinterpret_cast<TargetProperties *>(target_property_ptr);
3974 Args args;
3975 if (this_->GetRunArguments(args))
3976 this_->m_launch_info.GetArguments() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00003977}
3978
Kate Stoneb9c1b512016-09-06 20:57:50 +00003979void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
3980 OptionValue *) {
3981 TargetProperties *this_ =
3982 reinterpret_cast<TargetProperties *>(target_property_ptr);
3983 Args args;
3984 if (this_->GetEnvironmentAsArgs(args))
3985 this_->m_launch_info.GetEnvironmentEntries() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00003986}
3987
Kate Stoneb9c1b512016-09-06 20:57:50 +00003988void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
3989 OptionValue *) {
3990 TargetProperties *this_ =
3991 reinterpret_cast<TargetProperties *>(target_property_ptr);
3992 this_->m_launch_info.AppendOpenFileAction(
3993 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
Ilia K8f37ca52015-02-13 14:31:06 +00003994}
3995
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
3997 OptionValue *) {
3998 TargetProperties *this_ =
3999 reinterpret_cast<TargetProperties *>(target_property_ptr);
4000 this_->m_launch_info.AppendOpenFileAction(
4001 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004002}
4003
Kate Stoneb9c1b512016-09-06 20:57:50 +00004004void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4005 OptionValue *) {
4006 TargetProperties *this_ =
4007 reinterpret_cast<TargetProperties *>(target_property_ptr);
4008 this_->m_launch_info.AppendOpenFileAction(
4009 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004010}
4011
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012void TargetProperties::DetachOnErrorValueChangedCallback(
4013 void *target_property_ptr, OptionValue *) {
4014 TargetProperties *this_ =
4015 reinterpret_cast<TargetProperties *>(target_property_ptr);
4016 if (this_->GetDetachOnError())
4017 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4018 else
4019 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
Ilia K8f37ca52015-02-13 14:31:06 +00004020}
4021
Kate Stoneb9c1b512016-09-06 20:57:50 +00004022void TargetProperties::DisableASLRValueChangedCallback(
4023 void *target_property_ptr, OptionValue *) {
4024 TargetProperties *this_ =
4025 reinterpret_cast<TargetProperties *>(target_property_ptr);
4026 if (this_->GetDisableASLR())
4027 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4028 else
4029 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
Ilia K8f37ca52015-02-13 14:31:06 +00004030}
4031
Kate Stoneb9c1b512016-09-06 20:57:50 +00004032void TargetProperties::DisableSTDIOValueChangedCallback(
4033 void *target_property_ptr, OptionValue *) {
4034 TargetProperties *this_ =
4035 reinterpret_cast<TargetProperties *>(target_property_ptr);
4036 if (this_->GetDisableSTDIO())
4037 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4038 else
4039 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
Ilia K8f37ca52015-02-13 14:31:06 +00004040}
Ilia Keb2c19a2015-03-10 21:59:55 +00004041
4042//----------------------------------------------------------------------
4043// Target::TargetEventData
4044//----------------------------------------------------------------------
4045
Kate Stoneb9c1b512016-09-06 20:57:50 +00004046Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4047 : EventData(), m_target_sp(target_sp), m_module_list() {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4050 const ModuleList &module_list)
4051 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004052
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004053Target::TargetEventData::~TargetEventData() = default;
Ilia Keb2c19a2015-03-10 21:59:55 +00004054
Kate Stoneb9c1b512016-09-06 20:57:50 +00004055const ConstString &Target::TargetEventData::GetFlavorString() {
4056 static ConstString g_flavor("Target::TargetEventData");
4057 return g_flavor;
Ilia Keb2c19a2015-03-10 21:59:55 +00004058}
4059
Kate Stoneb9c1b512016-09-06 20:57:50 +00004060void Target::TargetEventData::Dump(Stream *s) const {
4061 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4062 if (i != 0)
4063 *s << ", ";
4064 m_module_list.GetModuleAtIndex(i)->GetDescription(
4065 s, lldb::eDescriptionLevelBrief);
4066 }
Ilia Keb2c19a2015-03-10 21:59:55 +00004067}
4068
4069const Target::TargetEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004070Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4071 if (event_ptr) {
4072 const EventData *event_data = event_ptr->GetData();
4073 if (event_data &&
4074 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4075 return static_cast<const TargetEventData *>(event_ptr->GetData());
4076 }
4077 return nullptr;
Ilia Keb2c19a2015-03-10 21:59:55 +00004078}
4079
Kate Stoneb9c1b512016-09-06 20:57:50 +00004080TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4081 TargetSP target_sp;
4082 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4083 if (event_data)
4084 target_sp = event_data->m_target_sp;
4085 return target_sp;
Ilia Keb2c19a2015-03-10 21:59:55 +00004086}
4087
4088ModuleList
Kate Stoneb9c1b512016-09-06 20:57:50 +00004089Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4090 ModuleList module_list;
4091 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4092 if (event_data)
4093 module_list = event_data->m_module_list;
4094 return module_list;
Ilia Keb2c19a2015-03-10 21:59:55 +00004095}