blob: 5c46a024be60fecfbee7e95b5b528c21737823bd [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Target.cpp ----------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010// C Includes
11// C++ Includes
Greg Clayton04df8ee2016-02-26 19:38:18 +000012#include <mutex>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// Other libraries and framework includes
14// Project includes
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
16#include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
17#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
Jim Ingham01f16662016-09-14 19:07:35 +000018#include "lldb/Breakpoint/BreakpointIDList.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Breakpoint/BreakpointResolver.h"
20#include "lldb/Breakpoint/BreakpointResolverAddress.h"
21#include "lldb/Breakpoint/BreakpointResolverFileLine.h"
Jim Ingham969795f2011-09-21 01:17:13 +000022#include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Breakpoint/BreakpointResolverName.h"
Johnny Chen01a67862011-10-14 00:42:25 +000024#include "lldb/Breakpoint/Watchpoint.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000025#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Core/Event.h"
Greg Clayton1f746072012-08-29 21:13:06 +000027#include "lldb/Core/Module.h"
28#include "lldb/Core/ModuleSpec.h"
29#include "lldb/Core/Section.h"
Greg Clayton9585fbf2013-03-19 00:20:55 +000030#include "lldb/Core/SourceManager.h"
Greg Claytonb09c5382013-12-13 17:20:18 +000031#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000032#include "lldb/Core/StreamFile.h"
Greg Clayton8b2fe6d2010-12-14 02:59:59 +000033#include "lldb/Core/Timer.h"
34#include "lldb/Core/ValueObject.h"
Sean Callanan66810412015-10-19 23:11:07 +000035#include "lldb/Expression/REPL.h"
Jim Ingham151c0322015-09-15 21:13:50 +000036#include "lldb/Expression/UserExpression.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Host/Host.h"
Jim Ingham9575d842011-03-11 03:53:59 +000038#include "lldb/Interpreter/CommandInterpreter.h"
39#include "lldb/Interpreter/CommandReturnObject.h"
Johnny Chenb90827e2012-06-04 23:19:54 +000040#include "lldb/Interpreter/OptionGroupWatchpoint.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000041#include "lldb/Interpreter/OptionValues.h"
42#include "lldb/Interpreter/Property.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000043#include "lldb/Symbol/ClangASTContext.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000044#include "lldb/Symbol/Function.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000045#include "lldb/Symbol/ObjectFile.h"
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +000046#include "lldb/Symbol/Symbol.h"
Jim Ingham151c0322015-09-15 21:13:50 +000047#include "lldb/Target/Language.h"
Zachary Turnera78bd7f2015-03-03 23:11:11 +000048#include "lldb/Target/LanguageRuntime.h"
49#include "lldb/Target/ObjCLanguageRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Target/Process.h"
Greg Claytond5944cd2013-12-06 01:12:00 +000051#include "lldb/Target/SectionLoadList.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000052#include "lldb/Target/StackFrame.h"
Jason Molendaeef51062013-11-05 03:57:19 +000053#include "lldb/Target/SystemRuntime.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000054#include "lldb/Target/Target.h"
Jim Ingham9575d842011-03-11 03:53:59 +000055#include "lldb/Target/Thread.h"
56#include "lldb/Target/ThreadSpec.h"
Zachary Turner5713a052017-03-22 18:40:07 +000057#include "lldb/Utility/FileSpec.h"
Sean Callanan9a6940c2015-10-21 00:36:34 +000058#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000059#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000060#include "lldb/Utility/StreamString.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061
62using namespace lldb;
63using namespace lldb_private;
64
Pavel Labath43d35412016-12-06 11:24:51 +000065constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
66
Kate Stoneb9c1b512016-09-06 20:57:50 +000067ConstString &Target::GetStaticBroadcasterClass() {
68 static ConstString class_name("lldb.target");
69 return class_name;
Jim Ingham4bddaeb2012-02-16 06:50:00 +000070}
71
Kate Stoneb9c1b512016-09-06 20:57:50 +000072Target::Target(Debugger &debugger, const ArchSpec &target_arch,
73 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000074 : TargetProperties(this),
Kate Stoneb9c1b512016-09-06 20:57:50 +000075 Broadcaster(debugger.GetBroadcasterManager(),
76 Target::GetStaticBroadcasterClass().AsCString()),
77 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
78 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
79 m_breakpoint_list(false), m_internal_breakpoint_list(true),
80 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
81 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
82 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
83 m_valid(true), m_suppress_stop_hooks(false),
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +000084 m_is_dummy_target(is_dummy_target)
Jim Ingham893c9322014-11-22 01:42:44 +000085
Chris Lattner30fdc8d2010-06-08 16:52:24 +000086{
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
88 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
89 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
90 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
91 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 CheckInWithManager();
Greg Claytoncfd1ace2010-10-31 03:01:06 +000094
Kate Stoneb9c1b512016-09-06 20:57:50 +000095 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
96 if (log)
97 log->Printf("%p Target::Target()", static_cast<void *>(this));
98 if (m_arch.IsValid()) {
99 LogIfAnyCategoriesSet(
100 LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)",
101 m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
102 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000103}
104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105Target::~Target() {
106 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
107 if (log)
108 log->Printf("%p Target::~Target()", static_cast<void *>(this));
109 DeleteCurrentProcess();
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000110}
111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112void Target::PrimeFromDummyTarget(Target *target) {
113 if (!target)
114 return;
Jim Ingham893c9322014-11-22 01:42:44 +0000115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 m_stop_hooks = target->m_stop_hooks;
117
118 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
119 if (breakpoint_sp->IsInternal())
120 continue;
121
122 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
123 AddBreakpoint(new_bp, false);
124 }
Jim Ingham893c9322014-11-22 01:42:44 +0000125}
126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
128 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
129 if (description_level != lldb::eDescriptionLevelBrief) {
130 s->Indent();
131 s->PutCString("Target\n");
132 s->IndentMore();
133 m_images.Dump(s);
134 m_breakpoint_list.Dump(s);
135 m_internal_breakpoint_list.Dump(s);
136 s->IndentLess();
137 } else {
138 Module *exe_module = GetExecutableModulePointer();
139 if (exe_module)
140 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
Caroline Ticeceb6b132010-10-26 03:11:13 +0000141 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 s->PutCString("No executable module.");
143 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000144}
145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146void Target::CleanupProcess() {
147 // Do any cleanup of the target we need to do between process instances.
148 // NB It is better to do this before destroying the process in case the
149 // clean up needs some help from the process.
150 m_breakpoint_list.ClearAllBreakpointSites();
151 m_internal_breakpoint_list.ClearAllBreakpointSites();
152 // Disable watchpoints just on the debugger side.
153 std::unique_lock<std::recursive_mutex> lock;
154 this->GetWatchpointList().GetListMutex(lock);
155 DisableAllWatchpoints(false);
156 ClearAllWatchpointHitCounts();
157 ClearAllWatchpointHistoricValues();
Greg Clayton90ba8112012-12-05 00:16:59 +0000158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160void Target::DeleteCurrentProcess() {
161 if (m_process_sp) {
Greg Claytond5944cd2013-12-06 01:12:00 +0000162 m_section_load_history.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 if (m_process_sp->IsAlive())
164 m_process_sp->Destroy(false);
165
166 m_process_sp->Finalize();
167
168 CleanupProcess();
169
170 m_process_sp.reset();
171 }
Greg Clayton3418c852011-08-10 02:10:13 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
Zachary Turner31659452016-11-17 21:15:14 +0000175 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176 const FileSpec *crash_file) {
177 DeleteCurrentProcess();
178 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
179 listener_sp, crash_file);
180 return m_process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000181}
182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
184
Zachary Turner97206d52017-05-12 04:51:55 +0000185lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 const char *repl_options, bool can_create) {
187 if (language == eLanguageTypeUnknown) {
188 std::set<LanguageType> repl_languages;
189
190 Language::GetLanguagesSupportingREPLs(repl_languages);
191
192 if (repl_languages.size() == 1) {
193 language = *repl_languages.begin();
194 } else if (repl_languages.size() == 0) {
195 err.SetErrorStringWithFormat(
196 "LLDB isn't configured with REPL support for any languages.");
197 return REPLSP();
198 } else {
199 err.SetErrorStringWithFormat(
200 "Multiple possible REPL languages. Please specify a language.");
201 return REPLSP();
202 }
203 }
204
205 REPLMap::iterator pos = m_repl_map.find(language);
206
207 if (pos != m_repl_map.end()) {
208 return pos->second;
209 }
210
211 if (!can_create) {
212 err.SetErrorStringWithFormat(
213 "Couldn't find an existing REPL for %s, and can't create a new one",
214 Language::GetNameForLanguageType(language));
215 return lldb::REPLSP();
216 }
217
218 Debugger *const debugger = nullptr;
219 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
220
221 if (ret) {
222 m_repl_map[language] = ret;
223 return m_repl_map[language];
224 }
225
226 if (err.Success()) {
227 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
228 Language::GetNameForLanguageType(language));
229 }
230
231 return lldb::REPLSP();
232}
233
234void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
235 lldbassert(!m_repl_map.count(language));
236
237 m_repl_map[language] = repl_sp;
238}
239
240void Target::Destroy() {
241 std::lock_guard<std::recursive_mutex> guard(m_mutex);
242 m_valid = false;
243 DeleteCurrentProcess();
244 m_platform_sp.reset();
245 m_arch.Clear();
246 ClearModules(true);
247 m_section_load_history.Clear();
248 const bool notify = false;
249 m_breakpoint_list.RemoveAll(notify);
250 m_internal_breakpoint_list.RemoveAll(notify);
251 m_last_created_breakpoint.reset();
252 m_last_created_watchpoint.reset();
253 m_search_filter_sp.reset();
254 m_image_search_paths.Clear(notify);
255 m_stop_hooks.clear();
256 m_stop_hook_next_id = 0;
257 m_suppress_stop_hooks = false;
258}
259
260BreakpointList &Target::GetBreakpointList(bool internal) {
261 if (internal)
262 return m_internal_breakpoint_list;
263 else
264 return m_breakpoint_list;
265}
266
267const BreakpointList &Target::GetBreakpointList(bool internal) const {
268 if (internal)
269 return m_internal_breakpoint_list;
270 else
271 return m_breakpoint_list;
272}
273
274BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
275 BreakpointSP bp_sp;
276
277 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
278 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
279 else
280 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
281
282 return bp_sp;
283}
284
285BreakpointSP Target::CreateSourceRegexBreakpoint(
286 const FileSpecList *containingModules,
287 const FileSpecList *source_file_spec_list,
288 const std::unordered_set<std::string> &function_names,
289 RegularExpression &source_regex, bool internal, bool hardware,
290 LazyBool move_to_nearest_code) {
291 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
292 containingModules, source_file_spec_list));
293 if (move_to_nearest_code == eLazyBoolCalculate)
294 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
295 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
296 nullptr, source_regex, function_names,
297 !static_cast<bool>(move_to_nearest_code)));
298
299 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
300}
301
302BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
303 const FileSpec &file, uint32_t line_no,
304 lldb::addr_t offset,
305 LazyBool check_inlines,
306 LazyBool skip_prologue, bool internal,
307 bool hardware,
308 LazyBool move_to_nearest_code) {
309 FileSpec remapped_file;
310 ConstString remapped_path;
311 if (GetSourcePathMap().ReverseRemapPath(ConstString(file.GetPath().c_str()),
312 remapped_path))
313 remapped_file.SetFile(remapped_path.AsCString(), true);
314 else
315 remapped_file = file;
316
317 if (check_inlines == eLazyBoolCalculate) {
318 const InlineStrategy inline_strategy = GetInlineStrategy();
319 switch (inline_strategy) {
320 case eInlineBreakpointsNever:
321 check_inlines = eLazyBoolNo;
322 break;
323
324 case eInlineBreakpointsHeaders:
325 if (remapped_file.IsSourceImplementationFile())
326 check_inlines = eLazyBoolNo;
327 else
328 check_inlines = eLazyBoolYes;
329 break;
330
331 case eInlineBreakpointsAlways:
332 check_inlines = eLazyBoolYes;
333 break;
334 }
335 }
336 SearchFilterSP filter_sp;
337 if (check_inlines == eLazyBoolNo) {
338 // Not checking for inlines, we are looking only for matching compile units
339 FileSpecList compile_unit_list;
340 compile_unit_list.Append(remapped_file);
341 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
342 &compile_unit_list);
343 } else {
344 filter_sp = GetSearchFilterForModuleList(containingModules);
345 }
346 if (skip_prologue == eLazyBoolCalculate)
347 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
348 if (move_to_nearest_code == eLazyBoolCalculate)
349 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
350
351 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
352 nullptr, remapped_file, line_no, offset, check_inlines, skip_prologue,
353 !static_cast<bool>(move_to_nearest_code)));
354 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
355}
356
357BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
358 bool hardware) {
359 Address so_addr;
360
361 // Check for any reason we want to move this breakpoint to other address.
362 addr = GetBreakableLoadAddress(addr);
363
364 // Attempt to resolve our load address if possible, though it is ok if
365 // it doesn't resolve to section/offset.
366
367 // Try and resolve as a load address if possible
368 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
369 if (!so_addr.IsValid()) {
370 // The address didn't resolve, so just set this as an absolute address
371 so_addr.SetOffset(addr);
372 }
373 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
374 return bp_sp;
375}
376
377BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
378 bool hardware) {
379 SearchFilterSP filter_sp(
380 new SearchFilterForUnconstrainedSearches(shared_from_this()));
381 BreakpointResolverSP resolver_sp(
382 new BreakpointResolverAddress(nullptr, addr));
383 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
384}
385
386lldb::BreakpointSP
387Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
388 const FileSpec *file_spec,
389 bool request_hardware) {
390 SearchFilterSP filter_sp(
391 new SearchFilterForUnconstrainedSearches(shared_from_this()));
392 BreakpointResolverSP resolver_sp(
393 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
394 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
395 false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396}
397
398BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399Target::CreateBreakpoint(const FileSpecList *containingModules,
400 const FileSpecList *containingSourceFiles,
401 const char *func_name, uint32_t func_name_type_mask,
402 LanguageType language, lldb::addr_t offset,
403 LazyBool skip_prologue, bool internal, bool hardware) {
404 BreakpointSP bp_sp;
405 if (func_name) {
406 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
407 containingModules, containingSourceFiles));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408
Greg Clayton03da4cc2013-04-19 21:31:16 +0000409 if (skip_prologue == eLazyBoolCalculate)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
411 if (language == lldb::eLanguageTypeUnknown)
412 language = GetLanguage();
413
414 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
415 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
416 offset, skip_prologue));
417 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
418 }
419 return bp_sp;
420}
421
422lldb::BreakpointSP
423Target::CreateBreakpoint(const FileSpecList *containingModules,
424 const FileSpecList *containingSourceFiles,
425 const std::vector<std::string> &func_names,
426 uint32_t func_name_type_mask, LanguageType language,
427 lldb::addr_t offset, LazyBool skip_prologue,
428 bool internal, bool hardware) {
429 BreakpointSP bp_sp;
430 size_t num_names = func_names.size();
431 if (num_names > 0) {
432 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
433 containingModules, containingSourceFiles));
434
435 if (skip_prologue == eLazyBoolCalculate)
436 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
437 if (language == lldb::eLanguageTypeUnknown)
438 language = GetLanguage();
439
440 BreakpointResolverSP resolver_sp(
441 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
442 language, offset, skip_prologue));
443 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
444 }
445 return bp_sp;
446}
447
448BreakpointSP Target::CreateBreakpoint(
449 const FileSpecList *containingModules,
450 const FileSpecList *containingSourceFiles, const char *func_names[],
451 size_t num_names, uint32_t func_name_type_mask, LanguageType language,
452 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
453 BreakpointSP bp_sp;
454 if (num_names > 0) {
455 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
456 containingModules, containingSourceFiles));
457
458 if (skip_prologue == eLazyBoolCalculate) {
459 if (offset == 0)
Greg Clayton03da4cc2013-04-19 21:31:16 +0000460 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461 else
462 skip_prologue = eLazyBoolNo;
Greg Clayton1b72fcb2010-08-24 00:45:41 +0000463 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 if (language == lldb::eLanguageTypeUnknown)
465 language = GetLanguage();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
468 nullptr, func_names, num_names, func_name_type_mask, language, offset,
469 skip_prologue));
470 resolver_sp->SetOffset(offset);
471 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
472 }
473 return bp_sp;
Jim Ingham133e0fb2012-03-03 02:05:11 +0000474}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000475
476SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477Target::GetSearchFilterForModule(const FileSpec *containingModule) {
478 SearchFilterSP filter_sp;
479 if (containingModule != nullptr) {
480 // TODO: We should look into sharing module based search filters
481 // across many breakpoints like we do for the simple target based one
482 filter_sp.reset(
483 new SearchFilterByModule(shared_from_this(), *containingModule));
484 } else {
485 if (!m_search_filter_sp)
486 m_search_filter_sp.reset(
487 new SearchFilterForUnconstrainedSearches(shared_from_this()));
488 filter_sp = m_search_filter_sp;
489 }
490 return filter_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000491}
492
Jim Ingham969795f2011-09-21 01:17:13 +0000493SearchFilterSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
495 SearchFilterSP filter_sp;
496 if (containingModules && containingModules->GetSize() != 0) {
497 // TODO: We should look into sharing module based search filters
498 // across many breakpoints like we do for the simple target based one
499 filter_sp.reset(
500 new SearchFilterByModuleList(shared_from_this(), *containingModules));
501 } else {
502 if (!m_search_filter_sp)
503 m_search_filter_sp.reset(
504 new SearchFilterForUnconstrainedSearches(shared_from_this()));
505 filter_sp = m_search_filter_sp;
506 }
507 return filter_sp;
Jim Ingham969795f2011-09-21 01:17:13 +0000508}
509
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
511 const FileSpecList *containingModules,
512 const FileSpecList *containingSourceFiles) {
513 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
514 return GetSearchFilterForModuleList(containingModules);
515
516 SearchFilterSP filter_sp;
517 if (containingModules == nullptr) {
518 // We could make a special "CU List only SearchFilter". Better yet was if
519 // these could be composable,
520 // but that will take a little reworking.
521
522 filter_sp.reset(new SearchFilterByModuleListAndCU(
523 shared_from_this(), FileSpecList(), *containingSourceFiles));
524 } else {
525 filter_sp.reset(new SearchFilterByModuleListAndCU(
526 shared_from_this(), *containingModules, *containingSourceFiles));
527 }
528 return filter_sp;
Jim Ingham87df91b2011-09-23 00:54:11 +0000529}
530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531BreakpointSP Target::CreateFuncRegexBreakpoint(
532 const FileSpecList *containingModules,
533 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
534 lldb::LanguageType requested_language, LazyBool skip_prologue,
535 bool internal, bool hardware) {
536 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
537 containingModules, containingSourceFiles));
538 bool skip = (skip_prologue == eLazyBoolCalculate)
539 ? GetSkipPrologue()
540 : static_cast<bool>(skip_prologue);
541 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
542 nullptr, func_regex, requested_language, 0, skip));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000545}
546
Jim Ingham219ba192012-03-05 04:47:34 +0000547lldb::BreakpointSP
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
549 bool catch_bp, bool throw_bp, bool internal,
Zachary Turner97206d52017-05-12 04:51:55 +0000550 Args *additional_args, Status *error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
552 *this, language, catch_bp, throw_bp, internal);
553 if (exc_bkpt_sp && additional_args) {
554 Breakpoint::BreakpointPreconditionSP precondition_sp =
555 exc_bkpt_sp->GetPrecondition();
556 if (precondition_sp && additional_args) {
557 if (error)
558 *error = precondition_sp->ConfigurePrecondition(*additional_args);
559 else
560 precondition_sp->ConfigurePrecondition(*additional_args);
Jim Inghama72b31c2015-04-22 19:42:18 +0000561 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 }
563 return exc_bkpt_sp;
Jim Ingham219ba192012-03-05 04:47:34 +0000564}
Jim Inghama72b31c2015-04-22 19:42:18 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
567 BreakpointResolverSP &resolver_sp,
568 bool internal, bool request_hardware,
569 bool resolve_indirect_symbols) {
570 BreakpointSP bp_sp;
571 if (filter_sp && resolver_sp) {
572 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, request_hardware,
573 resolve_indirect_symbols));
574 resolver_sp->SetBreakpoint(bp_sp.get());
575 AddBreakpoint(bp_sp, internal);
576 }
577 return bp_sp;
Jim Ingham33df7cd2014-12-06 01:28:03 +0000578}
579
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
581 if (!bp_sp)
582 return;
583 if (internal)
584 m_internal_breakpoint_list.Add(bp_sp, false);
585 else
586 m_breakpoint_list.Add(bp_sp, true);
Jim Ingham33df7cd2014-12-06 01:28:03 +0000587
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
589 if (log) {
590 StreamString s;
591 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
592 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
593 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
594 }
Jim Ingham33df7cd2014-12-06 01:28:03 +0000595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 bp_sp->ResolveBreakpoint();
Jim Ingham33df7cd2014-12-06 01:28:03 +0000597
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 if (!internal) {
599 m_last_created_breakpoint = bp_sp;
600 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601}
602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603bool Target::ProcessIsValid() {
604 return (m_process_sp && m_process_sp->IsAlive());
Johnny Chen86364b42011-09-20 23:28:55 +0000605}
606
Zachary Turner97206d52017-05-12 04:51:55 +0000607static bool CheckIfWatchpointsExhausted(Target *target, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 uint32_t num_supported_hardware_watchpoints;
Zachary Turner97206d52017-05-12 04:51:55 +0000609 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610 num_supported_hardware_watchpoints);
611 if (num_supported_hardware_watchpoints == 0) {
612 error.SetErrorStringWithFormat(
613 "Target supports (%u) hardware watchpoint slots.\n",
614 num_supported_hardware_watchpoints);
615 return false;
616 }
617 return true;
Johnny Chenb90827e2012-06-04 23:19:54 +0000618}
619
Johnny Chen01a67862011-10-14 00:42:25 +0000620// See also Watchpoint::SetWatchpointType(uint32_t type) and
Johnny Chenab9ee762011-09-14 00:26:03 +0000621// the OptionGroupWatchpoint::WatchType enum type.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
623 const CompilerType *type, uint32_t kind,
Zachary Turner97206d52017-05-12 04:51:55 +0000624 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
626 if (log)
627 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
628 " type = %u)\n",
629 __FUNCTION__, addr, (uint64_t)size, kind);
Johnny Chen0c406372011-09-14 20:23:45 +0000630
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631 WatchpointSP wp_sp;
632 if (!ProcessIsValid()) {
633 error.SetErrorString("process is not alive");
Johnny Chen01a67862011-10-14 00:42:25 +0000634 return wp_sp;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 }
Johnny Chen887062a2011-09-12 23:38:44 +0000636
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
638 if (size == 0)
639 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
642 return wp_sp;
643 }
644
645 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
646 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
647 }
648
649 if (!CheckIfWatchpointsExhausted(this, error))
650 return wp_sp;
651
652 // Currently we only support one watchpoint per address, with total number
653 // of watchpoints limited by the hardware which the inferior is running on.
654
655 // Grab the list mutex while doing operations.
656 const bool notify = false; // Don't notify about all the state changes we do
657 // on creating the watchpoint.
658 std::unique_lock<std::recursive_mutex> lock;
659 this->GetWatchpointList().GetListMutex(lock);
660 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
661 if (matched_sp) {
662 size_t old_size = matched_sp->GetByteSize();
663 uint32_t old_type =
664 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
665 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
666 // Return the existing watchpoint if both size and type match.
667 if (size == old_size && kind == old_type) {
668 wp_sp = matched_sp;
669 wp_sp->SetEnabled(false, notify);
670 } else {
671 // Nil the matched watchpoint; we will be creating a new one.
672 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
673 m_watchpoint_list.Remove(matched_sp->GetID(), true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 }
676
677 if (!wp_sp) {
678 wp_sp.reset(new Watchpoint(*this, addr, size, type));
679 wp_sp->SetWatchpointType(kind, notify);
680 m_watchpoint_list.Add(wp_sp, true);
681 }
682
683 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
684 if (log)
685 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
686 __FUNCTION__, error.Success() ? "succeeded" : "failed",
687 wp_sp->GetID());
688
689 if (error.Fail()) {
690 // Enabling the watchpoint on the device side failed.
691 // Remove the said watchpoint from the list maintained by the target
692 // instance.
693 m_watchpoint_list.Remove(wp_sp->GetID(), true);
694 // See if we could provide more helpful error message.
695 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
696 error.SetErrorStringWithFormat(
697 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
698
699 wp_sp.reset();
700 } else
701 m_last_created_watchpoint = wp_sp;
702 return wp_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000703}
704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705void Target::RemoveAllBreakpoints(bool internal_also) {
706 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
707 if (log)
708 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
709 internal_also ? "yes" : "no");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 m_breakpoint_list.RemoveAll(true);
712 if (internal_also)
713 m_internal_breakpoint_list.RemoveAll(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 m_last_created_breakpoint.reset();
716}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718void Target::DisableAllBreakpoints(bool internal_also) {
719 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
720 if (log)
721 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
722 internal_also ? "yes" : "no");
723
724 m_breakpoint_list.SetEnabledAll(false);
725 if (internal_also)
726 m_internal_breakpoint_list.SetEnabledAll(false);
727}
728
729void Target::EnableAllBreakpoints(bool internal_also) {
730 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
731 if (log)
732 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
733 internal_also ? "yes" : "no");
734
735 m_breakpoint_list.SetEnabledAll(true);
736 if (internal_also)
737 m_internal_breakpoint_list.SetEnabledAll(true);
738}
739
740bool Target::RemoveBreakpointByID(break_id_t break_id) {
741 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
742 if (log)
743 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
744 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
745
746 if (DisableBreakpointByID(break_id)) {
747 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
748 m_internal_breakpoint_list.Remove(break_id, false);
749 else {
750 if (m_last_created_breakpoint) {
751 if (m_last_created_breakpoint->GetID() == break_id)
752 m_last_created_breakpoint.reset();
753 }
754 m_breakpoint_list.Remove(break_id, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 return true;
757 }
758 return false;
759}
760
761bool Target::DisableBreakpointByID(break_id_t break_id) {
762 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
763 if (log)
764 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
765 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
766
767 BreakpointSP bp_sp;
768
769 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
770 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
771 else
772 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
773 if (bp_sp) {
774 bp_sp->SetEnabled(false);
775 return true;
776 }
777 return false;
778}
779
780bool Target::EnableBreakpointByID(break_id_t break_id) {
781 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
782 if (log)
783 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
784 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
785
786 BreakpointSP bp_sp;
787
788 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
789 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
790 else
791 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
792
793 if (bp_sp) {
794 bp_sp->SetEnabled(true);
795 return true;
796 }
797 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798}
799
Zachary Turner97206d52017-05-12 04:51:55 +0000800Status Target::SerializeBreakpointsToFile(const FileSpec &file,
801 const BreakpointIDList &bp_ids,
802 bool append) {
803 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +0000804
805 if (!file) {
806 error.SetErrorString("Invalid FileSpec.");
807 return error;
808 }
809
810 std::string path(file.GetPath());
Jim Ingham2d3628e2016-09-22 23:42:42 +0000811 StructuredData::ObjectSP input_data_sp;
812
813 StructuredData::ArraySP break_store_sp;
814 StructuredData::Array *break_store_ptr = nullptr;
815
816 if (append) {
817 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
818 if (error.Success()) {
819 break_store_ptr = input_data_sp->GetAsArray();
820 if (!break_store_ptr) {
821 error.SetErrorStringWithFormat(
822 "Tried to append to invalid input file %s", path.c_str());
823 return error;
824 }
825 }
826 }
827
828 if (!break_store_ptr) {
829 break_store_sp.reset(new StructuredData::Array());
830 break_store_ptr = break_store_sp.get();
831 }
832
Jim Ingham01f16662016-09-14 19:07:35 +0000833 StreamFile out_file(path.c_str(),
834 File::OpenOptions::eOpenOptionTruncate |
835 File::OpenOptions::eOpenOptionWrite |
836 File::OpenOptions::eOpenOptionCanCreate |
837 File::OpenOptions::eOpenOptionCloseOnExec,
838 lldb::eFilePermissionsFileDefault);
839 if (!out_file.GetFile().IsValid()) {
840 error.SetErrorStringWithFormat("Unable to open output file: %s.",
841 path.c_str());
842 return error;
843 }
844
845 std::unique_lock<std::recursive_mutex> lock;
846 GetBreakpointList().GetListMutex(lock);
847
Jim Ingham01f16662016-09-14 19:07:35 +0000848 if (bp_ids.GetSize() == 0) {
849 const BreakpointList &breakpoints = GetBreakpointList();
850
851 size_t num_breakpoints = breakpoints.GetSize();
852 for (size_t i = 0; i < num_breakpoints; i++) {
853 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
854 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
855 // If a breakpoint can't serialize it, just ignore it for now:
856 if (bkpt_save_sp)
Jim Ingham2d3628e2016-09-22 23:42:42 +0000857 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +0000858 }
859 } else {
860
861 std::unordered_set<lldb::break_id_t> processed_bkpts;
862 const size_t count = bp_ids.GetSize();
863 for (size_t i = 0; i < count; ++i) {
864 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
865 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
866
867 if (bp_id != LLDB_INVALID_BREAK_ID) {
868 // Only do each breakpoint once:
869 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
870 insert_result = processed_bkpts.insert(bp_id);
871 if (!insert_result.second)
872 continue;
873
874 Breakpoint *bp = GetBreakpointByID(bp_id).get();
875 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
876 // If the user explicitly asked to serialize a breakpoint, and we
877 // can't, then
878 // raise an error:
879 if (!bkpt_save_sp) {
880 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
881 bp_id);
882 return error;
883 }
Jim Ingham2d3628e2016-09-22 23:42:42 +0000884 break_store_ptr->AddItem(bkpt_save_sp);
Jim Ingham01f16662016-09-14 19:07:35 +0000885 }
886 }
887 }
888
Jim Ingham2d3628e2016-09-22 23:42:42 +0000889 break_store_ptr->Dump(out_file, false);
Jim Ingham01f16662016-09-14 19:07:35 +0000890 out_file.PutChar('\n');
891 return error;
892}
893
Zachary Turner97206d52017-05-12 04:51:55 +0000894Status Target::CreateBreakpointsFromFile(const FileSpec &file,
895 BreakpointIDList &new_bps) {
Jim Ingham3acdf382016-09-22 22:20:28 +0000896 std::vector<std::string> no_names;
897 return CreateBreakpointsFromFile(file, no_names, new_bps);
898}
899
Zachary Turner97206d52017-05-12 04:51:55 +0000900Status Target::CreateBreakpointsFromFile(const FileSpec &file,
901 std::vector<std::string> &names,
902 BreakpointIDList &new_bps) {
Jim Ingham01f16662016-09-14 19:07:35 +0000903 std::unique_lock<std::recursive_mutex> lock;
904 GetBreakpointList().GetListMutex(lock);
905
Zachary Turner97206d52017-05-12 04:51:55 +0000906 Status error;
Jim Ingham01f16662016-09-14 19:07:35 +0000907 StructuredData::ObjectSP input_data_sp =
908 StructuredData::ParseJSONFromFile(file, error);
909 if (!error.Success()) {
910 return error;
911 } else if (!input_data_sp || !input_data_sp->IsValid()) {
912 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
913 file.GetPath().c_str());
914 return error;
915 }
916
917 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
918 if (!bkpt_array) {
919 error.SetErrorStringWithFormat(
920 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
921 return error;
922 }
923
924 size_t num_bkpts = bkpt_array->GetSize();
Jim Ingham3acdf382016-09-22 22:20:28 +0000925 size_t num_names = names.size();
926
Jim Ingham01f16662016-09-14 19:07:35 +0000927 for (size_t i = 0; i < num_bkpts; i++) {
928 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
929 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
930 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
931 if (!bkpt_dict) {
932 error.SetErrorStringWithFormat(
933 "Invalid breakpoint data for element %zu from input file: %s.", i,
934 file.GetPath().c_str());
935 return error;
936 }
937 StructuredData::ObjectSP bkpt_data_sp =
938 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
Jim Ingham3acdf382016-09-22 22:20:28 +0000939 if (num_names &&
940 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
941 continue;
942
Jim Ingham01f16662016-09-14 19:07:35 +0000943 BreakpointSP bkpt_sp =
944 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
945 if (!error.Success()) {
946 error.SetErrorStringWithFormat(
947 "Error restoring breakpoint %zu from %s: %s.", i,
948 file.GetPath().c_str(), error.AsCString());
949 return error;
950 }
951 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
952 }
953 return error;
954}
955
Johnny Chenedf50372011-09-23 21:21:43 +0000956// The flag 'end_to_end', default to true, signifies that the operation is
957// performed end to end, for both the debugger and the debuggee.
958
Johnny Chen01a67862011-10-14 00:42:25 +0000959// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
960// to end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961bool Target::RemoveAllWatchpoints(bool end_to_end) {
962 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
963 if (log)
964 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +0000965
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 if (!end_to_end) {
967 m_watchpoint_list.RemoveAll(true);
968 return true;
969 }
Johnny Chenedf50372011-09-23 21:21:43 +0000970
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +0000972
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 if (!ProcessIsValid())
974 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000975
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 size_t num_watchpoints = m_watchpoint_list.GetSize();
977 for (size_t i = 0; i < num_watchpoints; ++i) {
978 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
979 if (!wp_sp)
980 return false;
Johnny Chen86364b42011-09-20 23:28:55 +0000981
Zachary Turner97206d52017-05-12 04:51:55 +0000982 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 if (rc.Fail())
984 return false;
985 }
986 m_watchpoint_list.RemoveAll(true);
987 m_last_created_watchpoint.reset();
988 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +0000989}
990
Johnny Chen01a67862011-10-14 00:42:25 +0000991// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
992// end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993bool Target::DisableAllWatchpoints(bool end_to_end) {
994 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
995 if (log)
996 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +0000997
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 if (!end_to_end) {
999 m_watchpoint_list.SetEnabledAll(false);
1000 return true;
1001 }
Johnny Chenedf50372011-09-23 21:21:43 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 if (!ProcessIsValid())
1006 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001007
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 size_t num_watchpoints = m_watchpoint_list.GetSize();
1009 for (size_t i = 0; i < num_watchpoints; ++i) {
1010 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1011 if (!wp_sp)
1012 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001013
Zachary Turner97206d52017-05-12 04:51:55 +00001014 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 if (rc.Fail())
1016 return false;
1017 }
1018 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001019}
1020
Johnny Chen01a67862011-10-14 00:42:25 +00001021// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
1022// end operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023bool Target::EnableAllWatchpoints(bool end_to_end) {
1024 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1025 if (log)
1026 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen86364b42011-09-20 23:28:55 +00001027
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 if (!end_to_end) {
1029 m_watchpoint_list.SetEnabledAll(true);
1030 return true;
1031 }
Johnny Chenedf50372011-09-23 21:21:43 +00001032
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 // Otherwise, it's an end to end operation.
Johnny Chenedf50372011-09-23 21:21:43 +00001034
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 if (!ProcessIsValid())
1036 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001037
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 size_t num_watchpoints = m_watchpoint_list.GetSize();
1039 for (size_t i = 0; i < num_watchpoints; ++i) {
1040 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1041 if (!wp_sp)
1042 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001043
Zachary Turner97206d52017-05-12 04:51:55 +00001044 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 if (rc.Fail())
1046 return false;
1047 }
1048 return true; // Success!
Johnny Chen86364b42011-09-20 23:28:55 +00001049}
1050
Johnny Chena4d6bc92012-02-25 06:44:30 +00001051// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052bool Target::ClearAllWatchpointHitCounts() {
1053 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1054 if (log)
1055 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chena4d6bc92012-02-25 06:44:30 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 size_t num_watchpoints = m_watchpoint_list.GetSize();
1058 for (size_t i = 0; i < num_watchpoints; ++i) {
1059 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1060 if (!wp_sp)
1061 return false;
Johnny Chena4d6bc92012-02-25 06:44:30 +00001062
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 wp_sp->ResetHitCount();
1064 }
1065 return true; // Success!
Johnny Chena4d6bc92012-02-25 06:44:30 +00001066}
1067
Enrico Granata5e3fe042015-02-11 00:37:54 +00001068// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069bool Target::ClearAllWatchpointHistoricValues() {
1070 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1071 if (log)
1072 log->Printf("Target::%s\n", __FUNCTION__);
1073
1074 size_t num_watchpoints = m_watchpoint_list.GetSize();
1075 for (size_t i = 0; i < num_watchpoints; ++i) {
1076 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1077 if (!wp_sp)
1078 return false;
1079
1080 wp_sp->ResetHistoricValues();
1081 }
1082 return true; // Success!
Enrico Granata5e3fe042015-02-11 00:37:54 +00001083}
1084
Johnny Chen01a67862011-10-14 00:42:25 +00001085// Assumption: Caller holds the list mutex lock for m_watchpoint_list
Johnny Chen6cc60e82011-10-05 21:35:46 +00001086// during these operations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1088 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1089 if (log)
1090 log->Printf("Target::%s\n", __FUNCTION__);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001091
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 if (!ProcessIsValid())
1093 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001094
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 size_t num_watchpoints = m_watchpoint_list.GetSize();
1096 for (size_t i = 0; i < num_watchpoints; ++i) {
1097 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1098 if (!wp_sp)
1099 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 wp_sp->SetIgnoreCount(ignore_count);
1102 }
1103 return true; // Success!
Johnny Chen6cc60e82011-10-05 21:35:46 +00001104}
1105
Johnny Chen01a67862011-10-14 00:42:25 +00001106// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1108 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1109 if (log)
1110 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001111
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001113 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114
1115 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1116 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001117 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 if (rc.Success())
1119 return true;
1120
1121 // Else, fallthrough.
1122 }
1123 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001124}
1125
Johnny Chen01a67862011-10-14 00:42:25 +00001126// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1128 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1129 if (log)
1130 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001131
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if (!ProcessIsValid())
Johnny Chen86364b42011-09-20 23:28:55 +00001133 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134
1135 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1136 if (wp_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001137 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 if (rc.Success())
1139 return true;
1140
1141 // Else, fallthrough.
1142 }
1143 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001144}
1145
Johnny Chen01a67862011-10-14 00:42:25 +00001146// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1148 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1149 if (log)
1150 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen86364b42011-09-20 23:28:55 +00001151
Kate Stoneb9c1b512016-09-06 20:57:50 +00001152 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1153 if (watch_to_remove_sp == m_last_created_watchpoint)
1154 m_last_created_watchpoint.reset();
1155
1156 if (DisableWatchpointByID(watch_id)) {
1157 m_watchpoint_list.Remove(watch_id, true);
1158 return true;
1159 }
1160 return false;
Johnny Chen86364b42011-09-20 23:28:55 +00001161}
1162
Johnny Chen01a67862011-10-14 00:42:25 +00001163// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1165 uint32_t ignore_count) {
1166 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1167 if (log)
1168 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
Johnny Chen6cc60e82011-10-05 21:35:46 +00001169
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170 if (!ProcessIsValid())
Johnny Chen6cc60e82011-10-05 21:35:46 +00001171 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172
1173 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1174 if (wp_sp) {
1175 wp_sp->SetIgnoreCount(ignore_count);
1176 return true;
1177 }
1178 return false;
Johnny Chen6cc60e82011-10-05 21:35:46 +00001179}
1180
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181ModuleSP Target::GetExecutableModule() {
1182 // search for the first executable in the module list
1183 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1184 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1185 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1186 if (obj == nullptr)
1187 continue;
1188 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1189 return module_sp;
1190 }
1191 // as fall back return the first module loaded
1192 return m_images.GetModuleAtIndex(0);
Greg Claytonaa149cb2011-08-11 02:48:45 +00001193}
1194
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195Module *Target::GetExecutableModulePointer() {
1196 return GetExecutableModule().get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197}
1198
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1200 Target *target) {
Zachary Turner97206d52017-05-12 04:51:55 +00001201 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 StreamString feedback_stream;
1203 if (module_sp &&
1204 !module_sp->LoadScriptingResourceInTarget(target, error,
1205 &feedback_stream)) {
1206 if (error.AsCString())
1207 target->GetDebugger().GetErrorFile()->Printf(
1208 "unable to load scripting data for module %s - error reported was "
1209 "%s\n",
1210 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1211 error.AsCString());
1212 }
1213 if (feedback_stream.GetSize())
1214 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1215 feedback_stream.GetData());
Enrico Granata17598482012-11-08 02:22:02 +00001216}
1217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218void Target::ClearModules(bool delete_locations) {
1219 ModulesDidUnload(m_images, delete_locations);
1220 m_section_load_history.Clear();
1221 m_images.Clear();
1222 m_scratch_type_system_map.Clear();
1223 m_ast_importer_sp.reset();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001224}
1225
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226void Target::DidExec() {
1227 // When a process exec's we need to know about it so we can do some cleanup.
1228 m_breakpoint_list.RemoveInvalidLocations(m_arch);
1229 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
Greg Claytonb35db632013-11-09 00:03:31 +00001230}
1231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232void Target::SetExecutableModule(ModuleSP &executable_sp,
1233 bool get_dependent_files) {
1234 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1235 ClearModules(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001236
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 if (executable_sp) {
Pavel Labathf9d16472017-05-15 13:02:37 +00001238 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1239 Timer scoped_timer(func_cat,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 "Target::SetExecutableModule (executable = '%s')",
1241 executable_sp->GetFileSpec().GetPath().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001242
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 m_images.Append(executable_sp); // The first image is our executable file
Jason Molendae1b68ad2012-12-05 00:25:49 +00001244
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 // If we haven't set an architecture yet, reset our architecture based on
1246 // what we found in the executable module.
1247 if (!m_arch.IsValid()) {
1248 m_arch = executable_sp->GetArchitecture();
1249 if (log)
1250 log->Printf("Target::SetExecutableModule setting architecture to %s "
1251 "(%s) based on executable file",
1252 m_arch.GetArchitectureName(),
1253 m_arch.GetTriple().getTriple().c_str());
Jason Molendadad8af42015-11-10 04:11:37 +00001254 }
1255
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 FileSpecList dependent_files;
1257 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
Greg Clayton095eeaa2013-11-05 23:28:00 +00001258
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259 if (executable_objfile && get_dependent_files) {
1260 executable_objfile->GetDependentModules(dependent_files);
1261 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1262 FileSpec dependent_file_spec(
1263 dependent_files.GetFileSpecPointerAtIndex(i));
1264 FileSpec platform_dependent_file_spec;
Greg Clayton67cc0632012-08-22 17:17:09 +00001265 if (m_platform_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1267 platform_dependent_file_spec);
1268 else
1269 platform_dependent_file_spec = dependent_file_spec;
1270
1271 ModuleSpec module_spec(platform_dependent_file_spec, m_arch);
1272 ModuleSP image_module_sp(GetSharedModule(module_spec));
1273 if (image_module_sp) {
1274 ObjectFile *objfile = image_module_sp->GetObjectFile();
1275 if (objfile)
1276 objfile->GetDependentModules(dependent_files);
1277 }
1278 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001279 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 }
Jim Inghamc6674fd2011-10-28 23:14:11 +00001281}
1282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283bool Target::SetArchitecture(const ArchSpec &arch_spec) {
1284 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1285 bool missing_local_arch = !m_arch.IsValid();
1286 bool replace_local_arch = true;
1287 bool compatible_local_arch = false;
1288 ArchSpec other(arch_spec);
Greg Claytone72dfb32012-02-24 01:59:29 +00001289
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 if (!missing_local_arch) {
1291 if (m_arch.IsCompatibleMatch(arch_spec)) {
1292 other.MergeFrom(m_arch);
1293
1294 if (m_arch.IsCompatibleMatch(other)) {
1295 compatible_local_arch = true;
1296 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1297 env_changed;
1298
1299 m_arch.PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1300 os_changed, os_ver_changed, env_changed);
1301
1302 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1303 replace_local_arch = false;
1304 }
1305 }
1306 }
1307
1308 if (compatible_local_arch || missing_local_arch) {
1309 // If we haven't got a valid arch spec, or the architectures are compatible
1310 // update the architecture, unless the one we already have is more specified
1311 if (replace_local_arch)
1312 m_arch = other;
1313 if (log)
1314 log->Printf("Target::SetArchitecture set architecture to %s (%s)",
1315 m_arch.GetArchitectureName(),
1316 m_arch.GetTriple().getTriple().c_str());
1317 return true;
1318 }
1319
1320 // If we have an executable file, try to reset the executable to the desired
1321 // architecture
1322 if (log)
1323 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1324 arch_spec.GetArchitectureName(),
1325 arch_spec.GetTriple().getTriple().c_str());
1326 m_arch = other;
1327 ModuleSP executable_sp = GetExecutableModule();
1328
1329 ClearModules(true);
1330 // Need to do something about unsetting breakpoints.
1331
1332 if (executable_sp) {
1333 if (log)
1334 log->Printf("Target::SetArchitecture Trying to select executable file "
1335 "architecture %s (%s)",
1336 arch_spec.GetArchitectureName(),
1337 arch_spec.GetTriple().getTriple().c_str());
1338 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
Zachary Turner97206d52017-05-12 04:51:55 +00001339 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1340 &GetExecutableSearchPaths(),
1341 nullptr, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342
1343 if (!error.Fail() && executable_sp) {
1344 SetExecutableModule(executable_sp, true);
1345 return true;
1346 }
1347 }
1348 return false;
Greg Claytondb598232011-01-07 01:57:07 +00001349}
1350
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1352 if (arch_spec.IsValid()) {
1353 if (m_arch.IsCompatibleMatch(arch_spec)) {
1354 // The current target arch is compatible with "arch_spec", see if we
1355 // can improve our current architecture using bits from "arch_spec"
Greg Claytonc749eb82011-07-11 05:12:02 +00001356
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357 // Merge bits from arch_spec into "merged_arch" and set our architecture
1358 ArchSpec merged_arch(m_arch);
1359 merged_arch.MergeFrom(arch_spec);
1360 return SetArchitecture(merged_arch);
1361 } else {
1362 // The new architecture is different, we just need to replace it
1363 return SetArchitecture(arch_spec);
Greg Claytondda4f7b2010-06-30 23:03:03 +00001364 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 }
1366 return false;
1367}
Greg Claytonc749eb82011-07-11 05:12:02 +00001368
Kate Stoneb9c1b512016-09-06 20:57:50 +00001369void Target::WillClearList(const ModuleList &module_list) {}
1370
1371void Target::ModuleAdded(const ModuleList &module_list,
1372 const ModuleSP &module_sp) {
1373 // A module is being added to this target for the first time
1374 if (m_valid) {
1375 ModuleList my_module_list;
1376 my_module_list.Append(module_sp);
1377 LoadScriptingResourceForModule(module_sp, this);
1378 ModulesDidLoad(my_module_list);
1379 }
1380}
1381
1382void Target::ModuleRemoved(const ModuleList &module_list,
1383 const ModuleSP &module_sp) {
1384 // A module is being removed from this target.
1385 if (m_valid) {
1386 ModuleList my_module_list;
1387 my_module_list.Append(module_sp);
1388 ModulesDidUnload(my_module_list, false);
1389 }
1390}
1391
1392void Target::ModuleUpdated(const ModuleList &module_list,
1393 const ModuleSP &old_module_sp,
1394 const ModuleSP &new_module_sp) {
1395 // A module is replacing an already added module
1396 if (m_valid) {
1397 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1398 new_module_sp);
1399 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1400 old_module_sp, new_module_sp);
1401 }
1402}
1403
1404void Target::ModulesDidLoad(ModuleList &module_list) {
1405 if (m_valid && module_list.GetSize()) {
1406 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1407 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1408 if (m_process_sp) {
1409 m_process_sp->ModulesDidLoad(module_list);
1410 }
1411 BroadcastEvent(eBroadcastBitModulesLoaded,
1412 new TargetEventData(this->shared_from_this(), module_list));
1413 }
1414}
1415
1416void Target::SymbolsDidLoad(ModuleList &module_list) {
1417 if (m_valid && module_list.GetSize()) {
1418 if (m_process_sp) {
1419 LanguageRuntime *runtime =
1420 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1421 if (runtime) {
1422 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1423 objc_runtime->SymbolsDidLoad(module_list);
1424 }
1425 }
1426
1427 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1428 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1429 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1430 new TargetEventData(this->shared_from_this(), module_list));
1431 }
1432}
1433
1434void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1435 if (m_valid && module_list.GetSize()) {
1436 UnloadModuleSections(module_list);
1437 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1438 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1439 delete_locations);
1440 BroadcastEvent(eBroadcastBitModulesUnloaded,
1441 new TargetEventData(this->shared_from_this(), module_list));
1442 }
1443}
1444
1445bool Target::ModuleIsExcludedForUnconstrainedSearches(
1446 const FileSpec &module_file_spec) {
1447 if (GetBreakpointsConsultPlatformAvoidList()) {
1448 ModuleList matchingModules;
1449 ModuleSpec module_spec(module_file_spec);
1450 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1451
1452 // If there is more than one module for this file spec, only return true if
1453 // ALL the modules are on the
1454 // black list.
1455 if (num_modules > 0) {
1456 for (size_t i = 0; i < num_modules; i++) {
1457 if (!ModuleIsExcludedForUnconstrainedSearches(
1458 matchingModules.GetModuleAtIndex(i)))
1459 return false;
1460 }
1461 return true;
1462 }
1463 }
1464 return false;
1465}
1466
1467bool Target::ModuleIsExcludedForUnconstrainedSearches(
1468 const lldb::ModuleSP &module_sp) {
1469 if (GetBreakpointsConsultPlatformAvoidList()) {
1470 if (m_platform_sp)
1471 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1472 module_sp);
1473 }
1474 return false;
1475}
1476
1477size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001478 size_t dst_len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 SectionSP section_sp(addr.GetSection());
1480 if (section_sp) {
1481 // If the contents of this section are encrypted, the on-disk file is
1482 // unusable. Read only from live memory.
1483 if (section_sp->IsEncrypted()) {
1484 error.SetErrorString("section is encrypted");
1485 return 0;
1486 }
1487 ModuleSP module_sp(section_sp->GetModule());
1488 if (module_sp) {
1489 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1490 if (objfile) {
1491 size_t bytes_read = objfile->ReadSectionData(
1492 section_sp.get(), addr.GetOffset(), dst, dst_len);
Greg Claytondb598232011-01-07 01:57:07 +00001493 if (bytes_read > 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494 return bytes_read;
Greg Claytondda4f7b2010-06-30 23:03:03 +00001495 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001496 error.SetErrorStringWithFormat("error reading data from section %s",
1497 section_sp->GetName().GetCString());
1498 } else
1499 error.SetErrorString("address isn't from a object file");
1500 } else
1501 error.SetErrorString("address isn't in a module");
1502 } else
1503 error.SetErrorString("address doesn't contain a section that points to a "
1504 "section in a object file");
1505
1506 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001507}
1508
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001510 void *dst, size_t dst_len, Status &error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 lldb::addr_t *load_addr_ptr) {
1512 error.Clear();
1513
1514 // if we end up reading this from process memory, we will fill this
1515 // with the actual load address
1516 if (load_addr_ptr)
1517 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1518
1519 size_t bytes_read = 0;
1520
1521 addr_t load_addr = LLDB_INVALID_ADDRESS;
1522 addr_t file_addr = LLDB_INVALID_ADDRESS;
1523 Address resolved_addr;
1524 if (!addr.IsSectionOffset()) {
1525 SectionLoadList &section_load_list = GetSectionLoadList();
1526 if (section_load_list.IsEmpty()) {
1527 // No sections are loaded, so we must assume we are not running
1528 // yet and anything we are given is a file address.
1529 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1530 // offset is the file address
1531 m_images.ResolveFileAddress(file_addr, resolved_addr);
1532 } else {
1533 // We have at least one section loaded. This can be because
1534 // we have manually loaded some sections with "target modules load ..."
1535 // or because we have have a live process that has sections loaded
1536 // through the dynamic loader
1537 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1538 // offset is the load address
1539 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1540 }
1541 }
1542 if (!resolved_addr.IsValid())
1543 resolved_addr = addr;
1544
1545 if (prefer_file_cache) {
1546 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1547 if (bytes_read > 0)
1548 return bytes_read;
1549 }
1550
1551 if (ProcessIsValid()) {
1552 if (load_addr == LLDB_INVALID_ADDRESS)
1553 load_addr = resolved_addr.GetLoadAddress(this);
1554
1555 if (load_addr == LLDB_INVALID_ADDRESS) {
1556 ModuleSP addr_module_sp(resolved_addr.GetModule());
1557 if (addr_module_sp && addr_module_sp->GetFileSpec())
Zachary Turner827d5d72016-12-16 04:27:00 +00001558 error.SetErrorStringWithFormatv(
1559 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1560 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561 else
1562 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1563 resolved_addr.GetFileAddress());
1564 } else {
1565 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1566 if (bytes_read != dst_len) {
1567 if (error.Success()) {
1568 if (bytes_read == 0)
1569 error.SetErrorStringWithFormat(
1570 "read memory from 0x%" PRIx64 " failed", load_addr);
1571 else
1572 error.SetErrorStringWithFormat(
1573 "only %" PRIu64 " of %" PRIu64
1574 " bytes were read from memory at 0x%" PRIx64,
1575 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1576 }
1577 }
1578 if (bytes_read) {
1579 if (load_addr_ptr)
1580 *load_addr_ptr = load_addr;
1581 return bytes_read;
1582 }
1583 // If the address is not section offset we have an address that
1584 // doesn't resolve to any address in any currently loaded shared
1585 // libraries and we failed to read memory so there isn't anything
1586 // more we can do. If it is section offset, we might be able to
1587 // read cached memory from the object file.
1588 if (!resolved_addr.IsSectionOffset())
1589 return 0;
1590 }
1591 }
1592
1593 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1594 // If we didn't already try and read from the object file cache, then
1595 // try it after failing to read from the process.
1596 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1597 }
1598 return 0;
1599}
1600
1601size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00001602 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 char buf[256];
1604 out_str.clear();
1605 addr_t curr_addr = addr.GetLoadAddress(this);
1606 Address address(addr);
1607 while (1) {
1608 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1609 if (length == 0)
1610 break;
1611 out_str.append(buf, length);
1612 // If we got "length - 1" bytes, we didn't get the whole C string, we
1613 // need to read some more characters
1614 if (length == sizeof(buf) - 1)
1615 curr_addr += length;
1616 else
1617 break;
1618 address = Address(curr_addr);
1619 }
1620 return out_str.size();
1621}
1622
1623size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00001624 size_t dst_max_len, Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 size_t total_cstr_len = 0;
1626 if (dst && dst_max_len) {
1627 result_error.Clear();
1628 // NULL out everything just to be safe
1629 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00001630 Status error;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001631 addr_t curr_addr = addr.GetLoadAddress(this);
1632 Address address(addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001633
1634 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't
1635 // think this really needs to be tied to the memory cache subsystem's
1636 // cache line size, so leave this as a fixed constant.
1637 const size_t cache_line_size = 512;
1638
1639 size_t bytes_left = dst_max_len - 1;
1640 char *curr_dst = dst;
1641
1642 while (bytes_left > 0) {
1643 addr_t cache_line_bytes_left =
1644 cache_line_size - (curr_addr % cache_line_size);
1645 addr_t bytes_to_read =
1646 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1647 size_t bytes_read =
1648 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1649
1650 if (bytes_read == 0) {
1651 result_error = error;
1652 dst[total_cstr_len] = '\0';
1653 break;
1654 }
1655 const size_t len = strlen(curr_dst);
1656
1657 total_cstr_len += len;
1658
1659 if (len < bytes_to_read)
1660 break;
1661
1662 curr_dst += bytes_read;
1663 curr_addr += bytes_read;
1664 bytes_left -= bytes_read;
1665 address = Address(curr_addr);
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001666 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667 } else {
1668 if (dst == nullptr)
1669 result_error.SetErrorString("invalid arguments");
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001670 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671 result_error.Clear();
1672 }
1673 return total_cstr_len;
Enrico Granata6b4ddc62013-01-21 19:20:50 +00001674}
1675
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1677 bool prefer_file_cache,
1678 uint32_t byte_size, bool is_signed,
Zachary Turner97206d52017-05-12 04:51:55 +00001679 Scalar &scalar, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 uint64_t uval;
1681
1682 if (byte_size <= sizeof(uval)) {
1683 size_t bytes_read =
1684 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1685 if (bytes_read == byte_size) {
1686 DataExtractor data(&uval, sizeof(uval), m_arch.GetByteOrder(),
1687 m_arch.GetAddressByteSize());
1688 lldb::offset_t offset = 0;
1689 if (byte_size <= 4)
1690 scalar = data.GetMaxU32(&offset, byte_size);
1691 else
1692 scalar = data.GetMaxU64(&offset, byte_size);
1693
1694 if (is_signed)
1695 scalar.SignExtend(byte_size * 8);
1696 return bytes_read;
1697 }
1698 } else {
1699 error.SetErrorStringWithFormat(
1700 "byte size of %u is too large for integer scalar type", byte_size);
1701 }
1702 return 0;
1703}
1704
1705uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1706 bool prefer_file_cache,
1707 size_t integer_byte_size,
1708 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00001709 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 Scalar scalar;
1711 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1712 false, scalar, error))
1713 return scalar.ULongLong(fail_value);
1714 return fail_value;
1715}
1716
1717bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
Zachary Turner97206d52017-05-12 04:51:55 +00001718 Status &error, Address &pointer_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719 Scalar scalar;
1720 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1721 m_arch.GetAddressByteSize(), false, scalar,
1722 error)) {
1723 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1724 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1725 SectionLoadList &section_load_list = GetSectionLoadList();
1726 if (section_load_list.IsEmpty()) {
1727 // No sections are loaded, so we must assume we are not running
1728 // yet and anything we are given is a file address.
1729 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1730 } else {
1731 // We have at least one section loaded. This can be because
1732 // we have manually loaded some sections with "target modules load ..."
1733 // or because we have have a live process that has sections loaded
1734 // through the dynamic loader
1735 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1736 }
1737 // We weren't able to resolve the pointer value, so just return
1738 // an address with no section
1739 if (!pointer_addr.IsValid())
1740 pointer_addr.SetOffset(pointer_vm_addr);
1741 return true;
1742 }
1743 }
1744 return false;
1745}
1746
1747ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
Zachary Turner97206d52017-05-12 04:51:55 +00001748 Status *error_ptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 ModuleSP module_sp;
1750
Zachary Turner97206d52017-05-12 04:51:55 +00001751 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752
1753 // First see if we already have this module in our module list. If we do,
1754 // then we're done, we don't need
1755 // to consult the shared modules list. But only do this if we are passed a
1756 // UUID.
1757
1758 if (module_spec.GetUUID().IsValid())
1759 module_sp = m_images.FindFirstModule(module_spec);
1760
1761 if (!module_sp) {
1762 ModuleSP old_module_sp; // This will get filled in if we have a new version
1763 // of the library
1764 bool did_create_module = false;
1765
1766 // If there are image search path entries, try to use them first to acquire
1767 // a suitable image.
1768 if (m_image_search_paths.GetSize()) {
1769 ModuleSpec transformed_spec(module_spec);
1770 if (m_image_search_paths.RemapPath(
1771 module_spec.GetFileSpec().GetDirectory(),
1772 transformed_spec.GetFileSpec().GetDirectory())) {
1773 transformed_spec.GetFileSpec().GetFilename() =
1774 module_spec.GetFileSpec().GetFilename();
1775 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1776 &GetExecutableSearchPaths(),
1777 &old_module_sp, &did_create_module);
1778 }
1779 }
1780
1781 if (!module_sp) {
1782 // If we have a UUID, we can check our global shared module list in case
1783 // we already have it. If we don't have a valid UUID, then we can't since
1784 // the path in "module_spec" will be a platform path, and we will need to
1785 // let the platform find that file. For example, we could be asking for
1786 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1787 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1788 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1789 // cache.
1790 if (module_spec.GetUUID().IsValid()) {
1791 // We have a UUID, it is OK to check the global module list...
1792 error = ModuleList::GetSharedModule(module_spec, module_sp,
1793 &GetExecutableSearchPaths(),
1794 &old_module_sp, &did_create_module);
1795 }
1796
1797 if (!module_sp) {
1798 // The platform is responsible for finding and caching an appropriate
1799 // module in the shared module cache.
1800 if (m_platform_sp) {
1801 error = m_platform_sp->GetSharedModule(
1802 module_spec, m_process_sp.get(), module_sp,
1803 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
1804 } else {
1805 error.SetErrorString("no platform is currently set");
Greg Claytond16e1e52011-07-12 17:06:17 +00001806 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001808 }
Greg Claytond16e1e52011-07-12 17:06:17 +00001809
Kate Stoneb9c1b512016-09-06 20:57:50 +00001810 // We found a module that wasn't in our target list. Let's make sure that
1811 // there wasn't an equivalent
1812 // module in the list already, and if there was, let's remove it.
1813 if (module_sp) {
1814 ObjectFile *objfile = module_sp->GetObjectFile();
1815 if (objfile) {
1816 switch (objfile->GetType()) {
1817 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
1818 /// a program's execution state
1819 case ObjectFile::eTypeExecutable: /// A normal executable
1820 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
1821 /// executable
1822 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1823 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
1824 /// used during execution
1825 break;
1826 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
1827 /// debug information
1828 if (error_ptr)
1829 error_ptr->SetErrorString("debug info files aren't valid target "
1830 "modules, please specify an executable");
1831 return ModuleSP();
1832 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
1833 /// against but not used for
1834 /// execution
1835 if (error_ptr)
1836 error_ptr->SetErrorString("stub libraries aren't valid target "
1837 "modules, please specify an executable");
1838 return ModuleSP();
1839 default:
1840 if (error_ptr)
1841 error_ptr->SetErrorString(
1842 "unsupported file type, please specify an executable");
1843 return ModuleSP();
Greg Claytond16e1e52011-07-12 17:06:17 +00001844 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845 // GetSharedModule is not guaranteed to find the old shared module, for
1846 // instance
1847 // in the common case where you pass in the UUID, it is only going to
1848 // find the one
1849 // module matching the UUID. In fact, it has no good way to know what
1850 // the "old module"
1851 // relevant to this target is, since there might be many copies of a
1852 // module with this file spec
1853 // in various running debug sessions, but only one of them will belong
1854 // to this target.
1855 // So let's remove the UUID from the module list, and look in the
1856 // target's module list.
1857 // Only do this if there is SOMETHING else in the module spec...
1858 if (!old_module_sp) {
1859 if (module_spec.GetUUID().IsValid() &&
1860 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
1861 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
1862 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1863 module_spec_copy.GetUUID().Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864
Kate Stoneb9c1b512016-09-06 20:57:50 +00001865 ModuleList found_modules;
1866 size_t num_found =
1867 m_images.FindModules(module_spec_copy, found_modules);
1868 if (num_found == 1) {
1869 old_module_sp = found_modules.GetModuleAtIndex(0);
Jim Ingham4a94c912012-05-17 18:38:42 +00001870 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 }
Greg Claytonb69bb2e2012-04-27 00:58:27 +00001872 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873
Jim Ingham7fca8c02017-04-28 00:51:06 +00001874 // Preload symbols outside of any lock, so hopefully we can do this for
1875 // each library in parallel.
1876 if (GetPreloadSymbols())
1877 module_sp->PreloadSymbols();
1878
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 if (old_module_sp &&
1880 m_images.GetIndexForModule(old_module_sp.get()) !=
1881 LLDB_INVALID_INDEX32) {
1882 m_images.ReplaceModule(old_module_sp, module_sp);
1883 Module *old_module_ptr = old_module_sp.get();
1884 old_module_sp.reset();
1885 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
1886 } else
1887 m_images.Append(module_sp);
1888 } else
1889 module_sp.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001890 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001891 }
1892 if (error_ptr)
1893 *error_ptr = error;
1894 return module_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001895}
1896
Kate Stoneb9c1b512016-09-06 20:57:50 +00001897TargetSP Target::CalculateTarget() { return shared_from_this(); }
1898
1899ProcessSP Target::CalculateProcess() { return m_process_sp; }
1900
1901ThreadSP Target::CalculateThread() { return ThreadSP(); }
1902
1903StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
1904
1905void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
1906 exe_ctx.Clear();
1907 exe_ctx.SetTargetPtr(this);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001908}
1909
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910PathMappingList &Target::GetImageSearchPathList() {
1911 return m_image_search_paths;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001912}
1913
Kate Stoneb9c1b512016-09-06 20:57:50 +00001914void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
1915 void *baton) {
1916 Target *target = (Target *)baton;
1917 ModuleSP exe_module_sp(target->GetExecutableModule());
1918 if (exe_module_sp)
1919 target->SetExecutableModule(exe_module_sp, true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001920}
1921
Zachary Turner97206d52017-05-12 04:51:55 +00001922TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 lldb::LanguageType language,
1924 bool create_on_demand) {
1925 if (!m_valid)
1926 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001927
Kate Stoneb9c1b512016-09-06 20:57:50 +00001928 if (error) {
1929 error->Clear();
1930 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001931
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
1933 // assembly code
1934 || language == eLanguageTypeUnknown) {
1935 std::set<lldb::LanguageType> languages_for_types;
1936 std::set<lldb::LanguageType> languages_for_expressions;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001937
Kate Stoneb9c1b512016-09-06 20:57:50 +00001938 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
1939 languages_for_expressions);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 if (languages_for_expressions.count(eLanguageTypeC)) {
1942 language = eLanguageTypeC; // LLDB's default. Override by setting the
1943 // target language.
1944 } else {
1945 if (languages_for_expressions.empty()) {
Greg Clayton5beec212015-10-08 21:04:34 +00001946 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001947 } else {
1948 language = *languages_for_expressions.begin();
1949 }
Sean Callanana994b0b2015-10-02 18:40:30 +00001950 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951 }
Sean Callananb92bd752015-10-01 16:28:02 +00001952
Kate Stoneb9c1b512016-09-06 20:57:50 +00001953 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
1954 create_on_demand);
Sean Callananb92bd752015-10-01 16:28:02 +00001955}
1956
1957PersistentExpressionState *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
1959 TypeSystem *type_system =
1960 GetScratchTypeSystemForLanguage(nullptr, language, true);
1961
1962 if (type_system) {
1963 return type_system->GetPersistentExpressionState();
1964 } else {
1965 return nullptr;
1966 }
Jim Ingham151c0322015-09-15 21:13:50 +00001967}
1968
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969UserExpression *Target::GetUserExpressionForLanguage(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00001970 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 Expression::ResultType desired_type,
Zachary Turner97206d52017-05-12 04:51:55 +00001972 const EvaluateExpressionOptions &options, Status &error) {
1973 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974
1975 TypeSystem *type_system =
1976 GetScratchTypeSystemForLanguage(&type_system_error, language);
1977 UserExpression *user_expr = nullptr;
1978
1979 if (!type_system) {
1980 error.SetErrorStringWithFormat(
1981 "Could not find type system for language %s: %s",
1982 Language::GetNameForLanguageType(language),
1983 type_system_error.AsCString());
1984 return nullptr;
1985 }
1986
Zachary Turnerc5d7df92016-11-08 04:52:16 +00001987 user_expr = type_system->GetUserExpression(expr, prefix, language,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 desired_type, options);
1989 if (!user_expr)
1990 error.SetErrorStringWithFormat(
1991 "Could not create an expression for language %s",
1992 Language::GetNameForLanguageType(language));
1993
1994 return user_expr;
Jim Ingham151c0322015-09-15 21:13:50 +00001995}
1996
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997FunctionCaller *Target::GetFunctionCallerForLanguage(
1998 lldb::LanguageType language, const CompilerType &return_type,
1999 const Address &function_address, const ValueList &arg_value_list,
Zachary Turner97206d52017-05-12 04:51:55 +00002000 const char *name, Status &error) {
2001 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002 TypeSystem *type_system =
2003 GetScratchTypeSystemForLanguage(&type_system_error, language);
2004 FunctionCaller *persistent_fn = nullptr;
2005
2006 if (!type_system) {
2007 error.SetErrorStringWithFormat(
2008 "Could not find type system for language %s: %s",
2009 Language::GetNameForLanguageType(language),
2010 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002011 return persistent_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002012 }
2013
2014 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2015 arg_value_list, name);
2016 if (!persistent_fn)
2017 error.SetErrorStringWithFormat(
2018 "Could not create an expression for language %s",
2019 Language::GetNameForLanguageType(language));
2020
2021 return persistent_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002022}
2023
2024UtilityFunction *
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025Target::GetUtilityFunctionForLanguage(const char *text,
2026 lldb::LanguageType language,
Zachary Turner97206d52017-05-12 04:51:55 +00002027 const char *name, Status &error) {
2028 Status type_system_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002029 TypeSystem *type_system =
2030 GetScratchTypeSystemForLanguage(&type_system_error, language);
2031 UtilityFunction *utility_fn = nullptr;
2032
2033 if (!type_system) {
2034 error.SetErrorStringWithFormat(
2035 "Could not find type system for language %s: %s",
2036 Language::GetNameForLanguageType(language),
2037 type_system_error.AsCString());
Jim Ingham151c0322015-09-15 21:13:50 +00002038 return utility_fn;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002039 }
2040
2041 utility_fn = type_system->GetUtilityFunction(text, name);
2042 if (!utility_fn)
2043 error.SetErrorStringWithFormat(
2044 "Could not create an expression for language %s",
2045 Language::GetNameForLanguageType(language));
2046
2047 return utility_fn;
Jim Ingham151c0322015-09-15 21:13:50 +00002048}
2049
Kate Stoneb9c1b512016-09-06 20:57:50 +00002050ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2051 if (m_valid) {
2052 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2053 nullptr, eLanguageTypeC, create_on_demand))
2054 return llvm::dyn_cast<ClangASTContext>(type_system);
2055 }
2056 return nullptr;
2057}
2058
2059ClangASTImporterSP Target::GetClangASTImporter() {
2060 if (m_valid) {
2061 if (!m_ast_importer_sp) {
2062 m_ast_importer_sp.reset(new ClangASTImporter());
Sean Callanan4bf80d52011-11-15 22:27:19 +00002063 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002064 return m_ast_importer_sp;
2065 }
2066 return ClangASTImporterSP();
Sean Callananb92bd752015-10-01 16:28:02 +00002067}
2068
Kate Stoneb9c1b512016-09-06 20:57:50 +00002069void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2070
2071void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2072
2073FileSpecList Target::GetDefaultExecutableSearchPaths() {
2074 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2075 if (properties_sp)
2076 return properties_sp->GetExecutableSearchPaths();
2077 return FileSpecList();
Sean Callanan686b2312011-11-16 18:20:47 +00002078}
2079
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2081 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2082 if (properties_sp)
2083 return properties_sp->GetDebugFileSearchPaths();
2084 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002085}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002086
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2088 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2089 if (properties_sp)
2090 return properties_sp->GetClangModuleSearchPaths();
2091 return FileSpecList();
Greg Clayton99d0faf2010-11-18 23:32:35 +00002092}
Caroline Ticedaccaa92010-09-20 20:44:43 +00002093
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094ArchSpec Target::GetDefaultArchitecture() {
2095 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2096 if (properties_sp)
2097 return properties_sp->GetDefaultArchitecture();
2098 return ArchSpec();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002099}
2100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2102 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2103 if (properties_sp) {
2104 LogIfAnyCategoriesSet(
2105 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2106 "default architecture to %s (%s)",
2107 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2108 return properties_sp->SetDefaultArchitecture(arch);
2109 }
Michael Sartaina7499c92013-07-01 19:45:50 +00002110}
2111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2113 const SymbolContext *sc_ptr) {
2114 // The target can either exist in the "process" of ExecutionContext, or in
2115 // the "target_sp" member of SymbolContext. This accessor helper function
2116 // will get the target from one of these locations.
2117
2118 Target *target = nullptr;
2119 if (sc_ptr != nullptr)
2120 target = sc_ptr->target_sp.get();
2121 if (target == nullptr && exe_ctx_ptr)
2122 target = exe_ctx_ptr->GetTargetPtr();
2123 return target;
Sean Callanan85054342015-04-03 15:39:47 +00002124}
2125
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126ExpressionResults Target::EvaluateExpression(
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002127 llvm::StringRef expr, ExecutionContextScope *exe_scope,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 lldb::ValueObjectSP &result_valobj_sp,
2129 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2130 result_valobj_sp.reset();
Caroline Ticedaccaa92010-09-20 20:44:43 +00002131
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 ExpressionResults execution_results = eExpressionSetupError;
Caroline Ticedaccaa92010-09-20 20:44:43 +00002133
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002134 if (expr.empty())
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002135 return execution_results;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136
2137 // We shouldn't run stop hooks in expressions.
2138 // Be sure to reset this if you return anywhere within this function.
2139 bool old_suppress_value = m_suppress_stop_hooks;
2140 m_suppress_stop_hooks = true;
2141
2142 ExecutionContext exe_ctx;
2143
2144 if (exe_scope) {
2145 exe_scope->CalculateExecutionContext(exe_ctx);
2146 } else if (m_process_sp) {
2147 m_process_sp->CalculateExecutionContext(exe_ctx);
2148 } else {
2149 CalculateExecutionContext(exe_ctx);
2150 }
2151
2152 // Make sure we aren't just trying to see the value of a persistent
2153 // variable (something like "$0")
2154 lldb::ExpressionVariableSP persistent_var_sp;
2155 // Only check for persistent variables the expression starts with a '$'
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002156 if (expr[0] == '$')
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2158 ->GetPersistentExpressionState()
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002159 ->GetVariable(expr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160
2161 if (persistent_var_sp) {
2162 result_valobj_sp = persistent_var_sp->GetValueObject();
2163 execution_results = eExpressionCompleted;
2164 } else {
2165 const char *prefix = GetExpressionPrefixContentsAsCString();
Zachary Turner97206d52017-05-12 04:51:55 +00002166 Status error;
Zachary Turnerc5d7df92016-11-08 04:52:16 +00002167 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2168 result_valobj_sp, error,
2169 0, // Line Number
2170 fixed_expression);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002171 }
2172
2173 m_suppress_stop_hooks = old_suppress_value;
2174
2175 return execution_results;
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00002176}
2177
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002178lldb::ExpressionVariableSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179Target::GetPersistentVariable(const ConstString &name) {
2180 lldb::ExpressionVariableSP variable_sp;
2181 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002182 [name, &variable_sp](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 if (PersistentExpressionState *persistent_state =
2184 type_system->GetPersistentExpressionState()) {
2185 variable_sp = persistent_state->GetVariable(name);
Greg Clayton5beec212015-10-08 21:04:34 +00002186
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187 if (variable_sp)
2188 return false; // Stop iterating the ForEach
Sean Callanan8f1f9a12015-09-30 19:57:57 +00002189 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190 return true; // Keep iterating the ForEach
2191 });
2192 return variable_sp;
Zachary Turner32abc6e2015-03-03 19:23:09 +00002193}
2194
Kate Stoneb9c1b512016-09-06 20:57:50 +00002195lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2196 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2197
2198 m_scratch_type_system_map.ForEach(
Zachary Turner3bc714b2017-03-02 00:05:25 +00002199 [name, &address](TypeSystem *type_system) -> bool {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 if (PersistentExpressionState *persistent_state =
2201 type_system->GetPersistentExpressionState()) {
2202 address = persistent_state->LookupSymbol(name);
2203 if (address != LLDB_INVALID_ADDRESS)
2204 return false; // Stop iterating the ForEach
Sean Callananb92bd752015-10-01 16:28:02 +00002205 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206 return true; // Keep iterating the ForEach
2207 });
2208 return address;
Sean Callananb92bd752015-10-01 16:28:02 +00002209}
2210
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2212 AddressClass addr_class) const {
2213 addr_t code_addr = load_addr;
2214 switch (m_arch.GetMachine()) {
2215 case llvm::Triple::mips:
2216 case llvm::Triple::mipsel:
2217 case llvm::Triple::mips64:
2218 case llvm::Triple::mips64el:
2219 switch (addr_class) {
2220 case eAddressClassData:
2221 case eAddressClassDebug:
2222 return LLDB_INVALID_ADDRESS;
Jaydeep Patil44d07fc2015-09-22 06:36:56 +00002223
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224 case eAddressClassUnknown:
2225 case eAddressClassInvalid:
2226 case eAddressClassCode:
2227 case eAddressClassCodeAlternateISA:
2228 case eAddressClassRuntime:
2229 if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2230 code_addr |= 1ull;
2231 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002232 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002234
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 case llvm::Triple::arm:
2236 case llvm::Triple::thumb:
2237 switch (addr_class) {
2238 case eAddressClassData:
2239 case eAddressClassDebug:
2240 return LLDB_INVALID_ADDRESS;
2241
2242 case eAddressClassUnknown:
2243 case eAddressClassInvalid:
2244 case eAddressClassCode:
2245 case eAddressClassCodeAlternateISA:
2246 case eAddressClassRuntime:
2247 // Check if bit zero it no set?
2248 if ((code_addr & 1ull) == 0) {
2249 // Bit zero isn't set, check if the address is a multiple of 2?
2250 if (code_addr & 2ull) {
2251 // The address is a multiple of 2 so it must be thumb, set bit zero
2252 code_addr |= 1ull;
2253 } else if (addr_class == eAddressClassCodeAlternateISA) {
2254 // We checked the address and the address claims to be the alternate
2255 // ISA
2256 // which means thumb, so set bit zero.
2257 code_addr |= 1ull;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002259 }
2260 break;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002261 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262 break;
2263
2264 default:
2265 break;
2266 }
2267 return code_addr;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002268}
2269
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2271 AddressClass addr_class) const {
2272 addr_t opcode_addr = load_addr;
2273 switch (m_arch.GetMachine()) {
2274 case llvm::Triple::mips:
2275 case llvm::Triple::mipsel:
2276 case llvm::Triple::mips64:
2277 case llvm::Triple::mips64el:
2278 case llvm::Triple::arm:
2279 case llvm::Triple::thumb:
2280 switch (addr_class) {
2281 case eAddressClassData:
2282 case eAddressClassDebug:
2283 return LLDB_INVALID_ADDRESS;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002284
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 case eAddressClassInvalid:
2286 case eAddressClassUnknown:
2287 case eAddressClassCode:
2288 case eAddressClassCodeAlternateISA:
2289 case eAddressClassRuntime:
2290 opcode_addr &= ~(1ull);
2291 break;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002292 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293 break;
2294
2295 default:
2296 break;
2297 }
2298 return opcode_addr;
Bhushan D. Attarde7f3daed2015-08-26 06:04:54 +00002299}
2300
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2302 addr_t breakable_addr = addr;
2303 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Greg Clayton9585fbf2013-03-19 00:20:55 +00002304
Kate Stoneb9c1b512016-09-06 20:57:50 +00002305 switch (m_arch.GetMachine()) {
2306 default:
2307 break;
2308 case llvm::Triple::mips:
2309 case llvm::Triple::mipsel:
2310 case llvm::Triple::mips64:
2311 case llvm::Triple::mips64el: {
2312 addr_t function_start = 0;
2313 addr_t current_offset = 0;
2314 uint32_t loop_count = 0;
2315 Address resolved_addr;
2316 uint32_t arch_flags = m_arch.GetFlags();
2317 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2318 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2319 SectionLoadList &section_load_list = GetSectionLoadList();
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00002320
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 if (section_load_list.IsEmpty())
2322 // No sections are loaded, so we must assume we are not running yet
2323 // and need to operate only on file address.
2324 m_images.ResolveFileAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002325 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002326 section_load_list.ResolveLoadAddress(addr, resolved_addr);
Greg Clayton8012cad2014-11-17 19:39:20 +00002327
Kate Stoneb9c1b512016-09-06 20:57:50 +00002328 // Get the function boundaries to make sure we don't scan back before the
2329 // beginning of the current function.
2330 ModuleSP temp_addr_module_sp(resolved_addr.GetModule());
2331 if (temp_addr_module_sp) {
2332 SymbolContext sc;
2333 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2334 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr,
2335 resolve_scope, sc);
2336 Address sym_addr;
2337 if (sc.function)
2338 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2339 else if (sc.symbol)
2340 sym_addr = sc.symbol->GetAddress();
2341
2342 function_start = sym_addr.GetLoadAddress(this);
2343 if (function_start == LLDB_INVALID_ADDRESS)
2344 function_start = sym_addr.GetFileAddress();
2345
2346 if (function_start)
2347 current_offset = addr - function_start;
2348 }
2349
2350 // If breakpoint address is start of function then we dont have to do
2351 // anything.
2352 if (current_offset == 0)
2353 return breakable_addr;
Greg Claytond5944cd2013-12-06 01:12:00 +00002354 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002355 loop_count = current_offset / 2;
Greg Claytond5944cd2013-12-06 01:12:00 +00002356
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 if (loop_count > 3) {
2358 // Scan previous 6 bytes
2359 if (IsMips16 | IsMicromips)
2360 loop_count = 3;
2361 // For mips-only, instructions are always 4 bytes, so scan previous 4
2362 // bytes only.
2363 else
2364 loop_count = 2;
Greg Clayton6b32f1e2013-12-18 02:06:45 +00002365 }
2366
Kate Stoneb9c1b512016-09-06 20:57:50 +00002367 // Create Disassembler Instance
2368 lldb::DisassemblerSP disasm_sp(
2369 Disassembler::FindPlugin(m_arch, nullptr, nullptr));
Todd Fiala75f47c32014-10-11 21:42:09 +00002370
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 ExecutionContext exe_ctx;
2372 CalculateExecutionContext(exe_ctx);
2373 InstructionList instruction_list;
2374 InstructionSP prev_insn;
2375 bool prefer_file_cache = true; // Read from file
2376 uint32_t inst_to_choose = 0;
2377
2378 for (uint32_t i = 1; i <= loop_count; i++) {
2379 // Adjust the address to read from.
2380 resolved_addr.Slide(-2);
2381 AddressRange range(resolved_addr, i * 2);
2382 uint32_t insn_size = 0;
2383
2384 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2385
2386 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2387 if (num_insns) {
2388 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2389 insn_size = prev_insn->GetOpcode().GetByteSize();
2390 if (i == 1 && insn_size == 2) {
2391 // This looks like a valid 2-byte instruction (but it could be a part
2392 // of upper 4 byte instruction).
2393 instruction_list.Append(prev_insn);
2394 inst_to_choose = 1;
2395 } else if (i == 2) {
2396 // Here we may get one 4-byte instruction or two 2-byte instructions.
2397 if (num_insns == 2) {
2398 // Looks like there are two 2-byte instructions above our breakpoint
2399 // target address.
2400 // Now the upper 2-byte instruction is either a valid 2-byte
2401 // instruction or could be a part of it's upper 4-byte instruction.
2402 // In both cases we don't care because in this case lower 2-byte
2403 // instruction is definitely a valid instruction
2404 // and whatever i=1 iteration has found out is true.
2405 inst_to_choose = 1;
2406 break;
2407 } else if (insn_size == 4) {
2408 // This instruction claims its a valid 4-byte instruction. But it
2409 // could be a part of it's upper 4-byte instruction.
2410 // Lets try scanning upper 2 bytes to verify this.
2411 instruction_list.Append(prev_insn);
2412 inst_to_choose = 2;
2413 }
2414 } else if (i == 3) {
2415 if (insn_size == 4)
2416 // FIXME: We reached here that means instruction at [target - 4] has
2417 // already claimed to be a 4-byte instruction,
2418 // and now instruction at [target - 6] is also claiming that it's a
2419 // 4-byte instruction. This can not be true.
2420 // In this case we can not decide the valid previous instruction so
2421 // we let lldb set the breakpoint at the address given by user.
2422 inst_to_choose = 0;
2423 else
2424 // This is straight-forward
2425 inst_to_choose = 2;
2426 break;
Greg Claytonb09c5382013-12-13 17:20:18 +00002427 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428 } else {
2429 // Decode failed, bytes do not form a valid instruction. So whatever
2430 // previous iteration has found out is true.
2431 if (i > 1) {
2432 inst_to_choose = i - 1;
2433 break;
2434 }
2435 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002436 }
Todd Fiala015d8182014-07-22 23:41:36 +00002437
Kate Stoneb9c1b512016-09-06 20:57:50 +00002438 // Check if we are able to find any valid instruction.
2439 if (inst_to_choose) {
2440 if (inst_to_choose > instruction_list.GetSize())
2441 inst_to_choose--;
2442 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2443
2444 if (prev_insn->HasDelaySlot()) {
2445 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2446 // Adjust the breakable address
2447 breakable_addr = addr - shift_size;
Todd Fialaac33cc92014-10-09 01:02:08 +00002448 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002449 log->Printf("Target::%s Breakpoint at 0x%8.8" PRIx64
2450 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n",
2451 __FUNCTION__, addr, breakable_addr);
2452 }
Greg Claytonb09c5382013-12-13 17:20:18 +00002453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002454 break;
2455 }
2456 }
2457 return breakable_addr;
2458}
2459
2460SourceManager &Target::GetSourceManager() {
2461 if (!m_source_manager_ap)
2462 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2463 return *m_source_manager_ap;
2464}
2465
2466ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2467 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2468 // we can make it
2469 // per-target
2470
2471 {
2472 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2473
2474 if (!m_clang_modules_decl_vendor_ap) {
2475 m_clang_modules_decl_vendor_ap.reset(
2476 ClangModulesDeclVendor::Create(*this));
2477 }
2478 }
2479
2480 return m_clang_modules_decl_vendor_ap.get();
2481}
2482
2483Target::StopHookSP Target::CreateStopHook() {
2484 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2485 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2486 m_stop_hooks[new_uid] = stop_hook_sp;
2487 return stop_hook_sp;
2488}
2489
2490bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2491 size_t num_removed = m_stop_hooks.erase(user_id);
2492 return (num_removed != 0);
2493}
2494
2495void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2496
2497Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2498 StopHookSP found_hook;
2499
2500 StopHookCollection::iterator specified_hook_iter;
2501 specified_hook_iter = m_stop_hooks.find(user_id);
2502 if (specified_hook_iter != m_stop_hooks.end())
2503 found_hook = (*specified_hook_iter).second;
2504 return found_hook;
2505}
2506
2507bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2508 bool active_state) {
2509 StopHookCollection::iterator specified_hook_iter;
2510 specified_hook_iter = m_stop_hooks.find(user_id);
2511 if (specified_hook_iter == m_stop_hooks.end())
2512 return false;
2513
2514 (*specified_hook_iter).second->SetIsActive(active_state);
2515 return true;
2516}
2517
2518void Target::SetAllStopHooksActiveState(bool active_state) {
2519 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2520 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2521 (*pos).second->SetIsActive(active_state);
2522 }
2523}
2524
2525void Target::RunStopHooks() {
2526 if (m_suppress_stop_hooks)
2527 return;
2528
2529 if (!m_process_sp)
2530 return;
2531
2532 // <rdar://problem/12027563> make sure we check that we are not stopped
2533 // because of us running a user expression
2534 // since in that case we do not want to run the stop-hooks
2535 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2536 return;
2537
2538 if (m_stop_hooks.empty())
2539 return;
2540
2541 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2542
2543 // If there aren't any active stop hooks, don't bother either:
2544 bool any_active_hooks = false;
2545 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2546 if ((*pos).second->IsActive()) {
2547 any_active_hooks = true;
2548 break;
2549 }
2550 }
2551 if (!any_active_hooks)
2552 return;
2553
2554 CommandReturnObject result;
2555
2556 std::vector<ExecutionContext> exc_ctx_with_reasons;
2557 std::vector<SymbolContext> sym_ctx_with_reasons;
2558
2559 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2560 size_t num_threads = cur_threadlist.GetSize();
2561 for (size_t i = 0; i < num_threads; i++) {
2562 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2563 if (cur_thread_sp->ThreadStoppedForAReason()) {
2564 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2565 exc_ctx_with_reasons.push_back(ExecutionContext(
2566 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2567 sym_ctx_with_reasons.push_back(
2568 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2569 }
2570 }
2571
2572 // If no threads stopped for a reason, don't run the stop-hooks.
2573 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2574 if (num_exe_ctx == 0)
2575 return;
2576
2577 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2578 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2579
2580 bool keep_going = true;
2581 bool hooks_ran = false;
2582 bool print_hook_header = (m_stop_hooks.size() != 1);
2583 bool print_thread_header = (num_exe_ctx != 1);
2584
2585 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2586 // result.Clear();
2587 StopHookSP cur_hook_sp = (*pos).second;
2588 if (!cur_hook_sp->IsActive())
2589 continue;
2590
2591 bool any_thread_matched = false;
2592 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2593 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2594 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2595 sym_ctx_with_reasons[i])) &&
2596 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2597 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2598 exc_ctx_with_reasons[i].GetThreadRef()))) {
2599 if (!hooks_ran) {
2600 hooks_ran = true;
2601 }
2602 if (print_hook_header && !any_thread_matched) {
2603 const char *cmd =
2604 (cur_hook_sp->GetCommands().GetSize() == 1
2605 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2606 : nullptr);
2607 if (cmd)
2608 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2609 cur_hook_sp->GetID(), cmd);
2610 else
2611 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2612 cur_hook_sp->GetID());
2613 any_thread_matched = true;
2614 }
2615
2616 if (print_thread_header)
2617 result.AppendMessageWithFormat(
2618 "-- Thread %d\n",
2619 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2620
2621 CommandInterpreterRunOptions options;
2622 options.SetStopOnContinue(true);
2623 options.SetStopOnError(true);
2624 options.SetEchoCommands(false);
2625 options.SetPrintResults(true);
2626 options.SetAddToHistory(false);
2627
2628 GetDebugger().GetCommandInterpreter().HandleCommands(
2629 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2630 result);
2631
2632 // If the command started the target going again, we should bag out of
2633 // running the stop hooks.
2634 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2635 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2636 result.AppendMessageWithFormat("Aborting stop hooks, hook %" PRIu64
2637 " set the program running.",
2638 cur_hook_sp->GetID());
2639 keep_going = false;
2640 }
2641 }
2642 }
2643 }
2644
2645 result.GetImmediateOutputStream()->Flush();
2646 result.GetImmediateErrorStream()->Flush();
2647}
2648
2649const TargetPropertiesSP &Target::GetGlobalProperties() {
2650 // NOTE: intentional leak so we don't crash if global destructor chain gets
2651 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +00002652 static TargetPropertiesSP *g_settings_sp_ptr =
2653 new TargetPropertiesSP(new TargetProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 return *g_settings_sp_ptr;
2655}
2656
Zachary Turner97206d52017-05-12 04:51:55 +00002657Status Target::Install(ProcessLaunchInfo *launch_info) {
2658 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002659 PlatformSP platform_sp(GetPlatform());
2660 if (platform_sp) {
2661 if (platform_sp->IsRemote()) {
2662 if (platform_sp->IsConnected()) {
2663 // Install all files that have an install path, and always install the
2664 // main executable when connected to a remote platform
2665 const ModuleList &modules = GetImages();
2666 const size_t num_images = modules.GetSize();
2667 for (size_t idx = 0; idx < num_images; ++idx) {
2668 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2669 if (module_sp) {
2670 const bool is_main_executable = module_sp == GetExecutableModule();
2671 FileSpec local_file(module_sp->GetFileSpec());
2672 if (local_file) {
2673 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2674 if (!remote_file) {
2675 if (is_main_executable) // TODO: add setting for always
2676 // installing main executable???
2677 {
2678 // Always install the main executable
2679 remote_file = platform_sp->GetRemoteWorkingDirectory();
2680 remote_file.AppendPathComponent(
2681 module_sp->GetFileSpec().GetFilename().GetCString());
2682 }
2683 }
2684 if (remote_file) {
2685 error = platform_sp->Install(local_file, remote_file);
2686 if (error.Success()) {
2687 module_sp->SetPlatformFileSpec(remote_file);
2688 if (is_main_executable) {
2689 platform_sp->SetFilePermissions(remote_file, 0700);
2690 if (launch_info)
2691 launch_info->SetExecutableFile(remote_file, false);
2692 }
2693 } else
2694 break;
2695 }
2696 }
2697 }
2698 }
2699 }
2700 }
2701 }
2702 return error;
2703}
2704
2705bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2706 uint32_t stop_id) {
2707 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2708}
2709
2710bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2711 Address &resolved_addr) {
2712 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2713}
2714
2715bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2716 addr_t new_section_load_addr,
2717 bool warn_multiple) {
2718 const addr_t old_section_load_addr =
2719 m_section_load_history.GetSectionLoadAddress(
2720 SectionLoadHistory::eStopIDNow, section_sp);
2721 if (old_section_load_addr != new_section_load_addr) {
2722 uint32_t stop_id = 0;
2723 ProcessSP process_sp(GetProcessSP());
2724 if (process_sp)
2725 stop_id = process_sp->GetStopID();
Greg Claytonb09c5382013-12-13 17:20:18 +00002726 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002727 stop_id = m_section_load_history.GetLastStopID();
2728 if (m_section_load_history.SetSectionLoadAddress(
2729 stop_id, section_sp, new_section_load_addr, warn_multiple))
2730 return true; // Return true if the section load address was changed...
2731 }
2732 return false; // Return false to indicate nothing changed
2733}
Todd Fialaac33cc92014-10-09 01:02:08 +00002734
Kate Stoneb9c1b512016-09-06 20:57:50 +00002735size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2736 size_t section_unload_count = 0;
2737 size_t num_modules = module_list.GetSize();
2738 for (size_t i = 0; i < num_modules; ++i) {
2739 section_unload_count +=
2740 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2741 }
2742 return section_unload_count;
2743}
Todd Fiala015d8182014-07-22 23:41:36 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2746 uint32_t stop_id = 0;
2747 ProcessSP process_sp(GetProcessSP());
2748 if (process_sp)
2749 stop_id = process_sp->GetStopID();
2750 else
2751 stop_id = m_section_load_history.GetLastStopID();
2752 SectionList *sections = module_sp->GetSectionList();
2753 size_t section_unload_count = 0;
2754 if (sections) {
2755 const uint32_t num_sections = sections->GetNumSections(0);
2756 for (uint32_t i = 0; i < num_sections; ++i) {
2757 section_unload_count += m_section_load_history.SetSectionUnloaded(
2758 stop_id, sections->GetSectionAtIndex(i));
Greg Claytonb09c5382013-12-13 17:20:18 +00002759 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 }
2761 return section_unload_count;
2762}
2763
2764bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2765 uint32_t stop_id = 0;
2766 ProcessSP process_sp(GetProcessSP());
2767 if (process_sp)
2768 stop_id = process_sp->GetStopID();
2769 else
2770 stop_id = m_section_load_history.GetLastStopID();
2771 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2772}
2773
2774bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2775 addr_t load_addr) {
2776 uint32_t stop_id = 0;
2777 ProcessSP process_sp(GetProcessSP());
2778 if (process_sp)
2779 stop_id = process_sp->GetStopID();
2780 else
2781 stop_id = m_section_load_history.GetLastStopID();
2782 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2783 load_addr);
2784}
2785
2786void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2787
Zachary Turner97206d52017-05-12 04:51:55 +00002788Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2789 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2791
2792 if (log)
2793 log->Printf("Target::%s() called for %s", __FUNCTION__,
2794 launch_info.GetExecutableFile().GetPath().c_str());
2795
2796 StateType state = eStateInvalid;
2797
2798 // Scope to temporarily get the process state in case someone has manually
2799 // remotely connected already to a process and we can skip the platform
2800 // launching.
2801 {
2802 ProcessSP process_sp(GetProcessSP());
2803
2804 if (process_sp) {
2805 state = process_sp->GetState();
2806 if (log)
2807 log->Printf(
2808 "Target::%s the process exists, and its current state is %s",
2809 __FUNCTION__, StateAsCString(state));
2810 } else {
2811 if (log)
2812 log->Printf("Target::%s the process instance doesn't currently exist.",
2813 __FUNCTION__);
2814 }
2815 }
2816
2817 launch_info.GetFlags().Set(eLaunchFlagDebug);
2818
2819 // Get the value of synchronous execution here. If you wait till after you
2820 // have started to
2821 // run, then you could have hit a breakpoint, whose command might switch the
2822 // value, and
2823 // then you'll pick up that incorrect value.
2824 Debugger &debugger = GetDebugger();
2825 const bool synchronous_execution =
2826 debugger.GetCommandInterpreter().GetSynchronous();
2827
2828 PlatformSP platform_sp(GetPlatform());
2829
2830 // Finalize the file actions, and if none were given, default to opening
2831 // up a pseudo terminal
2832 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2833 if (log)
2834 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2835 "default_to_use_pty=%s",
2836 __FUNCTION__, platform_sp ? "true" : "false",
2837 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2838 : "n/a",
2839 default_to_use_pty ? "true" : "false");
2840
2841 launch_info.FinalizeFileActions(this, default_to_use_pty);
2842
2843 if (state == eStateConnected) {
2844 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2845 error.SetErrorString(
2846 "can't launch in tty when launching through a remote connection");
2847 return error;
2848 }
2849 }
2850
2851 if (!launch_info.GetArchitecture().IsValid())
2852 launch_info.GetArchitecture() = GetArchitecture();
2853
2854 // If we're not already connected to the process, and if we have a platform
2855 // that can launch a process for debugging, go ahead and do that here.
2856 if (state != eStateConnected && platform_sp &&
2857 platform_sp->CanDebugProcess()) {
2858 if (log)
2859 log->Printf("Target::%s asking the platform to debug the process",
2860 __FUNCTION__);
2861
2862 // Get a weak pointer to the previous process if we have one
2863 ProcessWP process_wp;
2864 if (m_process_sp)
2865 process_wp = m_process_sp;
2866 m_process_sp =
2867 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2868
2869 // Cleanup the old process since someone might still have a strong
2870 // reference to this process and we would like to allow it to cleanup
2871 // as much as it can without the object being destroyed. We try to
2872 // lock the shared pointer and if that works, then someone else still
2873 // has a strong reference to the process.
2874
2875 ProcessSP old_process_sp(process_wp.lock());
2876 if (old_process_sp)
2877 old_process_sp->Finalize();
2878 } else {
2879 if (log)
2880 log->Printf("Target::%s the platform doesn't know how to debug a "
2881 "process, getting a process plugin to do this for us.",
2882 __FUNCTION__);
2883
2884 if (state == eStateConnected) {
2885 assert(m_process_sp);
2886 } else {
2887 // Use a Process plugin to construct the process.
2888 const char *plugin_name = launch_info.GetProcessPluginName();
2889 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
2890 nullptr);
Greg Claytonb09c5382013-12-13 17:20:18 +00002891 }
2892
Kate Stoneb9c1b512016-09-06 20:57:50 +00002893 // Since we didn't have a platform launch the process, launch it here.
2894 if (m_process_sp)
2895 error = m_process_sp->Launch(launch_info);
2896 }
2897
2898 if (!m_process_sp) {
Greg Claytonb09c5382013-12-13 17:20:18 +00002899 if (error.Success())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002900 error.SetErrorString("failed to launch or debug process");
Greg Claytonb09c5382013-12-13 17:20:18 +00002901 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002902 }
2903
2904 if (error.Success()) {
2905 if (synchronous_execution ||
2906 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2907 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2908 if (!hijack_listener_sp) {
2909 hijack_listener_sp =
2910 Listener::MakeListener("lldb.Target.Launch.hijack");
2911 launch_info.SetHijackListener(hijack_listener_sp);
2912 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2913 }
2914
2915 StateType state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002916 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002917
2918 if (state == eStateStopped) {
2919 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2920 if (synchronous_execution) {
2921 error = m_process_sp->PrivateResume();
2922 if (error.Success()) {
2923 state = m_process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002924 llvm::None, nullptr, true, hijack_listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 const bool must_be_alive =
2926 false; // eStateExited is ok, so this must be false
2927 if (!StateIsStoppedState(state, must_be_alive)) {
2928 error.SetErrorStringWithFormat("process isn't stopped: %s",
2929 StateAsCString(state));
2930 }
2931 }
2932 } else {
2933 m_process_sp->RestoreProcessEvents();
2934 error = m_process_sp->PrivateResume();
2935 }
2936 if (!error.Success()) {
Zachary Turner97206d52017-05-12 04:51:55 +00002937 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002938 error2.SetErrorStringWithFormat(
2939 "process resume at entry point failed: %s", error.AsCString());
2940 error = error2;
2941 }
2942 }
2943 } else if (state == eStateExited) {
2944 bool with_shell = !!launch_info.GetShell();
2945 const int exit_status = m_process_sp->GetExitStatus();
2946 const char *exit_desc = m_process_sp->GetExitDescription();
2947#define LAUNCH_SHELL_MESSAGE \
2948 "\n'r' and 'run' are aliases that default to launching through a " \
2949 "shell.\nTry launching without going through a shell by using 'process " \
2950 "launch'."
2951 if (exit_desc && exit_desc[0]) {
2952 if (with_shell)
2953 error.SetErrorStringWithFormat(
2954 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2955 exit_status, exit_desc);
2956 else
2957 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2958 exit_status, exit_desc);
2959 } else {
2960 if (with_shell)
2961 error.SetErrorStringWithFormat(
2962 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2963 exit_status);
2964 else
2965 error.SetErrorStringWithFormat("process exited with status %i",
2966 exit_status);
2967 }
2968 } else {
2969 error.SetErrorStringWithFormat(
2970 "initial process state wasn't stopped: %s", StateAsCString(state));
2971 }
2972 }
2973 m_process_sp->RestoreProcessEvents();
2974 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00002975 Status error2;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976 error2.SetErrorStringWithFormat("process launch failed: %s",
2977 error.AsCString());
2978 error = error2;
2979 }
2980 return error;
Greg Claytonb09c5382013-12-13 17:20:18 +00002981}
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002982
Zachary Turner97206d52017-05-12 04:51:55 +00002983Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002984 auto state = eStateInvalid;
2985 auto process_sp = GetProcessSP();
2986 if (process_sp) {
2987 state = process_sp->GetState();
2988 if (process_sp->IsAlive() && state != eStateConnected) {
2989 if (state == eStateAttaching)
Zachary Turner97206d52017-05-12 04:51:55 +00002990 return Status("process attach is in progress");
2991 return Status("a process is already being debugged");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002992 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002993 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002994
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995 const ModuleSP old_exec_module_sp = GetExecutableModule();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00002996
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997 // If no process info was specified, then use the target executable
2998 // name as the process to attach to by default
2999 if (!attach_info.ProcessInfoSpecified()) {
3000 if (old_exec_module_sp)
3001 attach_info.GetExecutableFile().GetFilename() =
3002 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003003
Kate Stoneb9c1b512016-09-06 20:57:50 +00003004 if (!attach_info.ProcessInfoSpecified()) {
Zachary Turner97206d52017-05-12 04:51:55 +00003005 return Status("no process specified, create a target with a file, or "
3006 "specify the --pid or --name");
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003007 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003009
Kate Stoneb9c1b512016-09-06 20:57:50 +00003010 const auto platform_sp =
3011 GetDebugger().GetPlatformList().GetSelectedPlatform();
3012 ListenerSP hijack_listener_sp;
3013 const bool async = attach_info.GetAsync();
3014 if (!async) {
3015 hijack_listener_sp =
3016 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3017 attach_info.SetHijackListener(hijack_listener_sp);
3018 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003019
Zachary Turner97206d52017-05-12 04:51:55 +00003020 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003021 if (state != eStateConnected && platform_sp != nullptr &&
3022 platform_sp->CanDebugProcess()) {
3023 SetPlatform(platform_sp);
3024 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3025 } else {
3026 if (state != eStateConnected) {
3027 const char *plugin_name = attach_info.GetProcessPluginName();
3028 process_sp =
3029 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3030 plugin_name, nullptr);
3031 if (process_sp == nullptr) {
3032 error.SetErrorStringWithFormat(
3033 "failed to create process using plugin %s",
3034 (plugin_name) ? plugin_name : "null");
3035 return error;
3036 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003037 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 if (hijack_listener_sp)
3039 process_sp->HijackProcessEvents(hijack_listener_sp);
3040 error = process_sp->Attach(attach_info);
3041 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003042
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043 if (error.Success() && process_sp) {
3044 if (async) {
3045 process_sp->RestoreProcessEvents();
3046 } else {
3047 state = process_sp->WaitForProcessToStop(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003048 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 process_sp->RestoreProcessEvents();
3050
3051 if (state != eStateStopped) {
3052 const char *exit_desc = process_sp->GetExitDescription();
3053 if (exit_desc)
3054 error.SetErrorStringWithFormat("%s", exit_desc);
Greg Claytone75e5d82015-10-20 00:14:20 +00003055 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 error.SetErrorString(
3057 "process did not stop (no such process or permission problem?)");
3058 process_sp->Destroy(false);
3059 }
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003060 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061 }
3062 return error;
Oleksiy Vyalov37386142015-02-10 22:49:57 +00003063}
3064
Jim Ingham9575d842011-03-11 03:53:59 +00003065//--------------------------------------------------------------
Greg Claytonfbb76342013-11-20 21:07:01 +00003066// Target::StopHook
Jim Ingham9575d842011-03-11 03:53:59 +00003067//--------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3069 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3070 m_thread_spec_ap(), m_active(true) {}
3071
3072Target::StopHook::StopHook(const StopHook &rhs)
3073 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3074 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3075 m_thread_spec_ap(), m_active(rhs.m_active) {
3076 if (rhs.m_thread_spec_ap)
3077 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
Jim Ingham9575d842011-03-11 03:53:59 +00003078}
3079
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003080Target::StopHook::~StopHook() = default;
Jim Ingham9575d842011-03-11 03:53:59 +00003081
Kate Stoneb9c1b512016-09-06 20:57:50 +00003082void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3083 m_specifier_sp.reset(specifier);
Zachary Turner32abc6e2015-03-03 19:23:09 +00003084}
3085
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3087 m_thread_spec_ap.reset(specifier);
Jim Ingham9575d842011-03-11 03:53:59 +00003088}
Jim Ingham9575d842011-03-11 03:53:59 +00003089
Kate Stoneb9c1b512016-09-06 20:57:50 +00003090void Target::StopHook::GetDescription(Stream *s,
3091 lldb::DescriptionLevel level) const {
3092 int indent_level = s->GetIndentLevel();
Jim Ingham9575d842011-03-11 03:53:59 +00003093
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 s->SetIndentLevel(indent_level + 2);
3095
3096 s->Printf("Hook: %" PRIu64 "\n", GetID());
3097 if (m_active)
3098 s->Indent("State: enabled\n");
3099 else
3100 s->Indent("State: disabled\n");
3101
3102 if (m_specifier_sp) {
3103 s->Indent();
3104 s->PutCString("Specifier:\n");
3105 s->SetIndentLevel(indent_level + 4);
3106 m_specifier_sp->GetDescription(s, level);
Jim Ingham9575d842011-03-11 03:53:59 +00003107 s->SetIndentLevel(indent_level + 2);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003108 }
Jim Ingham9575d842011-03-11 03:53:59 +00003109
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110 if (m_thread_spec_ap) {
3111 StreamString tmp;
3112 s->Indent("Thread:\n");
3113 m_thread_spec_ap->GetDescription(&tmp, level);
3114 s->SetIndentLevel(indent_level + 4);
Zachary Turnerc1564272016-11-16 21:15:24 +00003115 s->Indent(tmp.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003116 s->PutCString("\n");
3117 s->SetIndentLevel(indent_level + 2);
3118 }
Jim Ingham9575d842011-03-11 03:53:59 +00003119
Kate Stoneb9c1b512016-09-06 20:57:50 +00003120 s->Indent("Commands: \n");
3121 s->SetIndentLevel(indent_level + 4);
3122 uint32_t num_commands = m_commands.GetSize();
3123 for (uint32_t i = 0; i < num_commands; i++) {
3124 s->Indent(m_commands.GetStringAtIndex(i));
3125 s->PutCString("\n");
3126 }
3127 s->SetIndentLevel(indent_level);
Jim Ingham9575d842011-03-11 03:53:59 +00003128}
3129
Greg Clayton67cc0632012-08-22 17:17:09 +00003130//--------------------------------------------------------------
3131// class TargetProperties
3132//--------------------------------------------------------------
3133
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3135 {eNoDynamicValues, "no-dynamic-values",
3136 "Don't calculate the dynamic type of values"},
3137 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3138 "even if you have to run the target."},
3139 {eDynamicDontRunTarget, "no-run-target",
3140 "Calculate the dynamic type of values, but don't run the target."},
3141 {0, nullptr, nullptr}};
Caroline Ticedaccaa92010-09-20 20:44:43 +00003142
Kate Stoneb9c1b512016-09-06 20:57:50 +00003143static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3144 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3145 "locations (fastest). This setting "
3146 "should only be used if you know that "
3147 "no inlining occurs in your programs."},
3148 {eInlineBreakpointsHeaders, "headers",
3149 "Only check for inline breakpoint locations when setting breakpoints in "
3150 "header files, but not when setting breakpoint in implementation source "
3151 "files (default)."},
3152 {eInlineBreakpointsAlways, "always",
3153 "Always look for inline breakpoint locations when setting file and line "
3154 "breakpoints (slower but most accurate)."},
3155 {0, nullptr, nullptr}};
Greg Clayton1f746072012-08-29 21:13:06 +00003156
Kate Stoneb9c1b512016-09-06 20:57:50 +00003157typedef enum x86DisassemblyFlavor {
3158 eX86DisFlavorDefault,
3159 eX86DisFlavorIntel,
3160 eX86DisFlavorATT
Jim Ingham0f063ba2013-03-02 00:26:47 +00003161} x86DisassemblyFlavor;
3162
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3164 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3165 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3166 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3167 {0, nullptr, nullptr}};
3168
3169static OptionEnumValueElement g_hex_immediate_style_values[] = {
3170 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3171 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3172 {0, nullptr, nullptr}};
3173
3174static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3175 {eLoadScriptFromSymFileTrue, "true",
3176 "Load debug scripts inside symbol files"},
3177 {eLoadScriptFromSymFileFalse, "false",
3178 "Do not load debug scripts inside symbol files."},
3179 {eLoadScriptFromSymFileWarn, "warn",
3180 "Warn about debug scripts inside symbol files but do not load them."},
3181 {0, nullptr, nullptr}};
3182
3183static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3184 {eLoadCWDlldbinitTrue, "true",
3185 "Load .lldbinit files from current directory"},
3186 {eLoadCWDlldbinitFalse, "false",
3187 "Do not load .lldbinit files from current directory"},
3188 {eLoadCWDlldbinitWarn, "warn",
3189 "Warn about loading .lldbinit files from current directory"},
3190 {0, nullptr, nullptr}};
3191
3192static OptionEnumValueElement g_memory_module_load_level_values[] = {
3193 {eMemoryModuleLoadLevelMinimal, "minimal",
3194 "Load minimal information when loading modules from memory. Currently "
3195 "this setting loads sections only."},
3196 {eMemoryModuleLoadLevelPartial, "partial",
3197 "Load partial information when loading modules from memory. Currently "
3198 "this setting loads sections and function bounds."},
3199 {eMemoryModuleLoadLevelComplete, "complete",
3200 "Load complete information when loading modules from memory. Currently "
3201 "this setting loads sections and all symbols."},
3202 {0, nullptr, nullptr}};
3203
3204static PropertyDefinition g_properties[] = {
3205 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3206 "Default architecture to choose, when there's a choice."},
3207 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3208 nullptr, "Move breakpoints to nearest code."},
3209 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3210 nullptr, nullptr,
3211 "The language to use when interpreting expressions entered in commands."},
3212 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3213 "Path to a file containing expressions to be prepended to all "
3214 "expressions."},
3215 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3216 eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3217 "Should printed values be shown as their dynamic value."},
3218 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3219 nullptr, "Should synthetic values be used by default whenever available."},
3220 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3221 "Skip function prologues when setting breakpoints by name."},
3222 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3223 "Source path remappings are used to track the change of location between "
3224 "a source file when built, and "
3225 "where it exists on the current system. It consists of an array of "
3226 "duples, the first element of each duple is "
3227 "some part (starting at the root) of the path to the file when it was "
3228 "built, "
3229 "and the second is where the remainder of the original build hierarchy is "
3230 "rooted on the local system. "
3231 "Each element of the array is checked in order and the first one that "
3232 "results in a match wins."},
3233 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3234 nullptr, "Executable search paths to use when locating executable files "
3235 "whose paths don't match the local file system."},
3236 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3237 nullptr, nullptr,
3238 "List of directories to be searched when locating debug symbol files."},
3239 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3240 nullptr, nullptr,
3241 "List of directories to be searched when locating modules for Clang."},
3242 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3243 nullptr, nullptr,
3244 "Automatically load Clang modules referred to by the program."},
3245 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3246 nullptr, "Automatically apply fix-it hints to expressions."},
3247 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3248 nullptr, "Print the fixed expression text."},
Sean Callanan5deb06e2016-09-26 20:18:51 +00003249 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3250 nullptr, "Save intermediate object files generated by the LLVM JIT"},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003251 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3252 nullptr, "Maximum number of children to expand in any level of depth."},
3253 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3254 nullptr, nullptr,
3255 "Maximum number of characters to show when using %s in summary strings."},
3256 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3257 nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3258 "--force must be specified."},
3259 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3260 true, nullptr, nullptr, "Consult the platform module avoid list when "
3261 "setting non-module specific breakpoints."},
3262 {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3263 "The first argument passed to the program in the argument array which can "
3264 "be different from the executable itself."},
3265 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3266 "A list containing all the arguments to be passed to the executable when "
3267 "it is run. Note that this does NOT include the argv[0] which is in "
3268 "target.arg0."},
3269 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3270 nullptr, nullptr, "A list of all the environment variables to be passed "
3271 "to the executable's environment, and their values."},
3272 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3273 "Inherit the environment from the process that is running LLDB."},
3274 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3275 "The file/path to be used by the executable program for reading its "
3276 "standard input."},
3277 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3278 "The file/path to be used by the executable program for writing its "
3279 "standard output."},
3280 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3281 "The file/path to be used by the executable program for writing its "
3282 "standard error."},
3283 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3284 nullptr, "debugserver will detach (rather than killing) a process if it "
3285 "loses connection with lldb."},
Jim Ingham7fca8c02017-04-28 00:51:06 +00003286 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3287 "Enable loading of symbol tables before they are needed."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3289 "Disable Address Space Layout Randomization (ASLR)"},
3290 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3291 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3292 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3293 eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3294 "The strategy to use when settings breakpoints by file and line. "
3295 "Breakpoint locations can end up being inlined by the compiler, so that a "
3296 "compile unit 'a.c' might contain an inlined function from another source "
3297 "file. "
3298 "Usually this is limited to breakpoint locations from inlined functions "
3299 "from header or other include files, or more accurately "
3300 "non-implementation source files. "
3301 "Sometimes code might #include implementation files and cause inlined "
3302 "breakpoint locations in inlined implementation files. "
3303 "Always checking for inlined breakpoint locations can be expensive "
3304 "(memory and time), so if you have a project with many headers "
3305 "and find that setting breakpoints is slow, then you can change this "
3306 "setting to headers. "
3307 "This setting allows you to control exactly which strategy is used when "
3308 "setting "
3309 "file and line breakpoints."},
3310 // FIXME: This is the wrong way to do per-architecture settings, but we
3311 // don't have a general per architecture settings system in place yet.
3312 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3313 eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3314 "The default disassembly flavor to use for x86 or x86-64 targets."},
3315 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3316 nullptr, "Show immediates in disassembly as hexadecimal."},
3317 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3318 Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3319 "Which style to use for printing hexadecimal disassembly values."},
3320 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3321 nullptr, "Use a fast stepping algorithm based on running from branch to "
3322 "branch rather than instruction single-stepping."},
3323 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3324 eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3325 "Allow LLDB to load scripting resources embedded in symbol files when "
3326 "available."},
3327 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3328 nullptr, g_load_current_working_dir_lldbinit_values,
3329 "Allow LLDB to .lldbinit files from the current directory automatically."},
3330 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3331 eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3332 "Loading modules from memory can be slow as reading the symbol tables and "
3333 "other data can take a long time depending on your connection to the "
3334 "debug target. "
3335 "This setting helps users control how much information gets loaded when "
3336 "loading modules from memory."
3337 "'complete' is the default value for this setting which will load all "
3338 "sections and symbols by reading them from memory (slowest, most "
3339 "accurate). "
3340 "'partial' will load sections and attempt to find function bounds without "
3341 "downloading the symbol table (faster, still accurate, missing symbol "
3342 "names). "
3343 "'minimal' is the fastest setting and will load section data with no "
3344 "symbols, but should rarely be used as stack frames in these memory "
3345 "regions will be inaccurate and not provide any context (fastest). "},
3346 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3347 nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3348 "the host system supports executable specific crash log "
3349 "strings and this setting is set to true."},
3350 {"trap-handler-names", OptionValue::eTypeArray, true,
3351 OptionValue::eTypeString, nullptr, nullptr,
3352 "A list of trap handler function names, e.g. a common Unix user process "
3353 "one is _sigtramp."},
3354 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3355 nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3356 "support the operation of a language's runtime "
3357 "support."},
3358 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3359 "Disable lock-step debugging, instead control threads independently."},
3360 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3361
3362enum {
3363 ePropertyDefaultArch,
3364 ePropertyMoveToNearestCode,
3365 ePropertyLanguage,
3366 ePropertyExprPrefix,
3367 ePropertyPreferDynamic,
3368 ePropertyEnableSynthetic,
3369 ePropertySkipPrologue,
3370 ePropertySourceMap,
3371 ePropertyExecutableSearchPaths,
3372 ePropertyDebugFileSearchPaths,
3373 ePropertyClangModuleSearchPaths,
3374 ePropertyAutoImportClangModules,
3375 ePropertyAutoApplyFixIts,
3376 ePropertyNotifyAboutFixIts,
Sean Callanan5deb06e2016-09-26 20:18:51 +00003377 ePropertySaveObjects,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378 ePropertyMaxChildrenCount,
3379 ePropertyMaxSummaryLength,
3380 ePropertyMaxMemReadSize,
3381 ePropertyBreakpointUseAvoidList,
3382 ePropertyArg0,
3383 ePropertyRunArgs,
3384 ePropertyEnvVars,
3385 ePropertyInheritEnv,
3386 ePropertyInputPath,
3387 ePropertyOutputPath,
3388 ePropertyErrorPath,
3389 ePropertyDetachOnError,
Jim Ingham7fca8c02017-04-28 00:51:06 +00003390 ePropertyPreloadSymbols,
Kate Stoneb9c1b512016-09-06 20:57:50 +00003391 ePropertyDisableASLR,
3392 ePropertyDisableSTDIO,
3393 ePropertyInlineStrategy,
3394 ePropertyDisassemblyFlavor,
3395 ePropertyUseHexImmediates,
3396 ePropertyHexImmediateStyle,
3397 ePropertyUseFastStepping,
3398 ePropertyLoadScriptFromSymbolFile,
3399 ePropertyLoadCWDlldbinitFile,
3400 ePropertyMemoryModuleLoadLevel,
3401 ePropertyDisplayExpressionsInCrashlogs,
3402 ePropertyTrapHandlerNames,
3403 ePropertyDisplayRuntimeSupportValues,
3404 ePropertyNonStopModeEnabled,
3405 ePropertyExperimental
Jim Ingham0f063ba2013-03-02 00:26:47 +00003406};
3407
Kate Stoneb9c1b512016-09-06 20:57:50 +00003408class TargetOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +00003409public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003410 TargetOptionValueProperties(const ConstString &name)
3411 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
Caroline Ticedaccaa92010-09-20 20:44:43 +00003412
Kate Stoneb9c1b512016-09-06 20:57:50 +00003413 // This constructor is used when creating TargetOptionValueProperties when it
3414 // is part of a new lldb_private::Target instance. It will copy all current
3415 // global property values as needed
3416 TargetOptionValueProperties(Target *target,
3417 const TargetPropertiesSP &target_properties_sp)
3418 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3419 m_target(target), m_got_host_env(false) {}
Greg Clayton67cc0632012-08-22 17:17:09 +00003420
Kate Stoneb9c1b512016-09-06 20:57:50 +00003421 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3422 bool will_modify,
3423 uint32_t idx) const override {
3424 // When getting the value for a key from the target options, we will always
3425 // try and grab the setting from the current target if there is one. Else we
3426 // just
3427 // use the one from this instance.
3428 if (idx == ePropertyEnvVars)
3429 GetHostEnvironmentIfNeeded();
3430
3431 if (exe_ctx) {
3432 Target *target = exe_ctx->GetTargetPtr();
3433 if (target) {
3434 TargetOptionValueProperties *target_properties =
3435 static_cast<TargetOptionValueProperties *>(
3436 target->GetValueProperties().get());
3437 if (this != target_properties)
3438 return target_properties->ProtectedGetPropertyAtIndex(idx);
3439 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003440 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003441 return ProtectedGetPropertyAtIndex(idx);
3442 }
3443
3444 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3445
Greg Clayton67cc0632012-08-22 17:17:09 +00003446protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003447 void GetHostEnvironmentIfNeeded() const {
3448 if (!m_got_host_env) {
3449 if (m_target) {
3450 m_got_host_env = true;
3451 const uint32_t idx = ePropertyInheritEnv;
3452 if (GetPropertyAtIndexAsBoolean(
3453 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3454 PlatformSP platform_sp(m_target->GetPlatform());
3455 if (platform_sp) {
3456 StringList env;
3457 if (platform_sp->GetEnvironment(env)) {
3458 OptionValueDictionary *env_dict =
3459 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3460 ePropertyEnvVars);
3461 if (env_dict) {
3462 const bool can_replace = false;
3463 const size_t envc = env.GetSize();
3464 for (size_t idx = 0; idx < envc; idx++) {
3465 const char *env_entry = env.GetStringAtIndex(idx);
3466 if (env_entry) {
3467 const char *equal_pos = ::strchr(env_entry, '=');
3468 ConstString key;
3469 // It is ok to have environment variables with no values
3470 const char *value = nullptr;
3471 if (equal_pos) {
3472 key.SetCStringWithLength(env_entry,
3473 equal_pos - env_entry);
3474 if (equal_pos[1])
3475 value = equal_pos + 1;
3476 } else {
3477 key.SetCString(env_entry);
Greg Clayton67cc0632012-08-22 17:17:09 +00003478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003479 // Don't allow existing keys to be replaced with ones we get
3480 // from the platform environment
3481 env_dict->SetValueForKey(
3482 key, OptionValueSP(new OptionValueString(value)),
3483 can_replace);
3484 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003487 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003488 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003489 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003490 }
Greg Clayton67cc0632012-08-22 17:17:09 +00003491 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003492 }
3493 Target *m_target;
3494 mutable bool m_got_host_env;
Greg Clayton67cc0632012-08-22 17:17:09 +00003495};
3496
Greg Claytonfbb76342013-11-20 21:07:01 +00003497//----------------------------------------------------------------------
3498// TargetProperties
3499//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003500static PropertyDefinition g_experimental_properties[]{
3501 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3502 nullptr,
3503 "If true, inject local variables explicitly into the expression text. "
3504 "This will fix symbol resolution when there are name collisions between "
3505 "ivars and local variables. "
3506 "But it can make expressions run much more slowly."},
3507 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
Jim Inghambed67792016-07-07 18:25:48 +00003508
Kate Stoneb9c1b512016-09-06 20:57:50 +00003509enum { ePropertyInjectLocalVars = 0 };
Jim Inghambed67792016-07-07 18:25:48 +00003510
Kate Stoneb9c1b512016-09-06 20:57:50 +00003511class TargetExperimentalOptionValueProperties : public OptionValueProperties {
Jim Inghambed67792016-07-07 18:25:48 +00003512public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00003513 TargetExperimentalOptionValueProperties()
3514 : OptionValueProperties(
3515 ConstString(Properties::GetExperimentalSettingsName())) {}
Jim Inghambed67792016-07-07 18:25:48 +00003516};
3517
Kate Stoneb9c1b512016-09-06 20:57:50 +00003518TargetExperimentalProperties::TargetExperimentalProperties()
3519 : Properties(OptionValuePropertiesSP(
3520 new TargetExperimentalOptionValueProperties())) {
3521 m_collection_sp->Initialize(g_experimental_properties);
Jim Inghambed67792016-07-07 18:25:48 +00003522}
3523
3524//----------------------------------------------------------------------
3525// TargetProperties
3526//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003527TargetProperties::TargetProperties(Target *target)
3528 : Properties(), m_launch_info() {
3529 if (target) {
3530 m_collection_sp.reset(
3531 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
Ilia K8f37ca52015-02-13 14:31:06 +00003532
Kate Stoneb9c1b512016-09-06 20:57:50 +00003533 // Set callbacks to update launch_info whenever "settins set" updated any of
3534 // these properties
3535 m_collection_sp->SetValueChangedCallback(
3536 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3537 m_collection_sp->SetValueChangedCallback(
3538 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3539 m_collection_sp->SetValueChangedCallback(
3540 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3541 m_collection_sp->SetValueChangedCallback(
3542 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3543 this);
3544 m_collection_sp->SetValueChangedCallback(
3545 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3546 this);
3547 m_collection_sp->SetValueChangedCallback(
3548 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3549 this);
3550 m_collection_sp->SetValueChangedCallback(
3551 ePropertyDetachOnError,
3552 TargetProperties::DetachOnErrorValueChangedCallback, this);
3553 m_collection_sp->SetValueChangedCallback(
3554 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3555 this);
3556 m_collection_sp->SetValueChangedCallback(
3557 ePropertyDisableSTDIO,
3558 TargetProperties::DisableSTDIOValueChangedCallback, this);
Jim Inghambed67792016-07-07 18:25:48 +00003559
Kate Stoneb9c1b512016-09-06 20:57:50 +00003560 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3561 m_collection_sp->AppendProperty(
3562 ConstString(Properties::GetExperimentalSettingsName()),
3563 ConstString("Experimental settings - setting these won't produce "
3564 "errors if the setting is not present."),
3565 true, m_experimental_properties_up->GetValueProperties());
Jim Inghambed67792016-07-07 18:25:48 +00003566
Kate Stoneb9c1b512016-09-06 20:57:50 +00003567 // Update m_launch_info once it was created
3568 Arg0ValueChangedCallback(this, nullptr);
3569 RunArgsValueChangedCallback(this, nullptr);
3570 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3571 // Target::GetPlatform()
3572 InputPathValueChangedCallback(this, nullptr);
3573 OutputPathValueChangedCallback(this, nullptr);
3574 ErrorPathValueChangedCallback(this, nullptr);
3575 DetachOnErrorValueChangedCallback(this, nullptr);
3576 DisableASLRValueChangedCallback(this, nullptr);
3577 DisableSTDIOValueChangedCallback(this, nullptr);
3578 } else {
3579 m_collection_sp.reset(
3580 new TargetOptionValueProperties(ConstString("target")));
3581 m_collection_sp->Initialize(g_properties);
3582 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3583 m_collection_sp->AppendProperty(
3584 ConstString(Properties::GetExperimentalSettingsName()),
3585 ConstString("Experimental settings - setting these won't produce "
3586 "errors if the setting is not present."),
3587 true, m_experimental_properties_up->GetValueProperties());
3588 m_collection_sp->AppendProperty(
3589 ConstString("process"), ConstString("Settings specific to processes."),
3590 true, Process::GetGlobalProperties()->GetValueProperties());
3591 }
Caroline Ticedaccaa92010-09-20 20:44:43 +00003592}
3593
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003594TargetProperties::~TargetProperties() = default;
3595
Kate Stoneb9c1b512016-09-06 20:57:50 +00003596bool TargetProperties::GetInjectLocalVariables(
3597 ExecutionContext *exe_ctx) const {
3598 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3599 exe_ctx, false, ePropertyExperimental);
3600 OptionValueProperties *exp_values =
3601 exp_property->GetValue()->GetAsProperties();
3602 if (exp_values)
3603 return exp_values->GetPropertyAtIndexAsBoolean(
3604 exe_ctx, ePropertyInjectLocalVars, true);
3605 else
3606 return true;
Jim Inghambed67792016-07-07 18:25:48 +00003607}
3608
Kate Stoneb9c1b512016-09-06 20:57:50 +00003609void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3610 bool b) {
3611 const Property *exp_property =
3612 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3613 OptionValueProperties *exp_values =
3614 exp_property->GetValue()->GetAsProperties();
3615 if (exp_values)
3616 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3617 true);
Jim Inghambed67792016-07-07 18:25:48 +00003618}
3619
Kate Stoneb9c1b512016-09-06 20:57:50 +00003620ArchSpec TargetProperties::GetDefaultArchitecture() const {
3621 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3622 nullptr, ePropertyDefaultArch);
3623 if (value)
3624 return value->GetCurrentValue();
3625 return ArchSpec();
Greg Clayton67cc0632012-08-22 17:17:09 +00003626}
3627
Kate Stoneb9c1b512016-09-06 20:57:50 +00003628void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3629 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3630 nullptr, ePropertyDefaultArch);
3631 if (value)
3632 return value->SetCurrentValue(arch, true);
Greg Clayton67cc0632012-08-22 17:17:09 +00003633}
3634
Kate Stoneb9c1b512016-09-06 20:57:50 +00003635bool TargetProperties::GetMoveToNearestCode() const {
3636 const uint32_t idx = ePropertyMoveToNearestCode;
3637 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3638 nullptr, idx, g_properties[idx].default_uint_value != 0);
Ilia K055ad9b2015-05-18 13:41:01 +00003639}
3640
Kate Stoneb9c1b512016-09-06 20:57:50 +00003641lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3642 const uint32_t idx = ePropertyPreferDynamic;
3643 return (lldb::DynamicValueType)
3644 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3645 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003646}
3647
Kate Stoneb9c1b512016-09-06 20:57:50 +00003648bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3649 const uint32_t idx = ePropertyPreferDynamic;
3650 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
Greg Clayton15484402015-05-15 18:40:24 +00003651}
3652
Jim Ingham7fca8c02017-04-28 00:51:06 +00003653bool TargetProperties::GetPreloadSymbols() const {
3654 const uint32_t idx = ePropertyPreloadSymbols;
3655 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3656 nullptr, idx, g_properties[idx].default_uint_value != 0);
3657}
3658
3659void TargetProperties::SetPreloadSymbols(bool b) {
3660 const uint32_t idx = ePropertyPreloadSymbols;
3661 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3662}
3663
Kate Stoneb9c1b512016-09-06 20:57:50 +00003664bool TargetProperties::GetDisableASLR() const {
3665 const uint32_t idx = ePropertyDisableASLR;
3666 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3667 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003668}
3669
Kate Stoneb9c1b512016-09-06 20:57:50 +00003670void TargetProperties::SetDisableASLR(bool b) {
3671 const uint32_t idx = ePropertyDisableASLR;
3672 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003673}
3674
Kate Stoneb9c1b512016-09-06 20:57:50 +00003675bool TargetProperties::GetDetachOnError() const {
3676 const uint32_t idx = ePropertyDetachOnError;
3677 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3678 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham106d0282014-06-25 02:32:56 +00003679}
3680
Kate Stoneb9c1b512016-09-06 20:57:50 +00003681void TargetProperties::SetDetachOnError(bool b) {
3682 const uint32_t idx = ePropertyDetachOnError;
3683 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Jim Ingham106d0282014-06-25 02:32:56 +00003684}
3685
Kate Stoneb9c1b512016-09-06 20:57:50 +00003686bool TargetProperties::GetDisableSTDIO() const {
3687 const uint32_t idx = ePropertyDisableSTDIO;
3688 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3689 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003690}
3691
Kate Stoneb9c1b512016-09-06 20:57:50 +00003692void TargetProperties::SetDisableSTDIO(bool b) {
3693 const uint32_t idx = ePropertyDisableSTDIO;
3694 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Greg Clayton67cc0632012-08-22 17:17:09 +00003695}
3696
Kate Stoneb9c1b512016-09-06 20:57:50 +00003697const char *TargetProperties::GetDisassemblyFlavor() const {
3698 const uint32_t idx = ePropertyDisassemblyFlavor;
3699 const char *return_value;
3700
3701 x86DisassemblyFlavor flavor_value =
3702 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3703 nullptr, idx, g_properties[idx].default_uint_value);
3704 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3705 return return_value;
Jim Ingham0f063ba2013-03-02 00:26:47 +00003706}
3707
Kate Stoneb9c1b512016-09-06 20:57:50 +00003708InlineStrategy TargetProperties::GetInlineStrategy() const {
3709 const uint32_t idx = ePropertyInlineStrategy;
3710 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3711 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton1f746072012-08-29 21:13:06 +00003712}
3713
Zachary Turner31d97a52016-11-17 18:08:12 +00003714llvm::StringRef TargetProperties::GetArg0() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 const uint32_t idx = ePropertyArg0;
Zachary Turner31d97a52016-11-17 18:08:12 +00003716 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
Greg Clayton45392552012-10-17 22:57:12 +00003717}
3718
Zachary Turner31d97a52016-11-17 18:08:12 +00003719void TargetProperties::SetArg0(llvm::StringRef arg) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003720 const uint32_t idx = ePropertyArg0;
Zachary Turner514d8cd2016-09-23 18:06:53 +00003721 m_collection_sp->SetPropertyAtIndexAsString(
Zachary Turner31d97a52016-11-17 18:08:12 +00003722 nullptr, idx, arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003723 m_launch_info.SetArg0(arg);
Greg Clayton45392552012-10-17 22:57:12 +00003724}
3725
Kate Stoneb9c1b512016-09-06 20:57:50 +00003726bool TargetProperties::GetRunArguments(Args &args) const {
3727 const uint32_t idx = ePropertyRunArgs;
3728 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +00003729}
3730
Kate Stoneb9c1b512016-09-06 20:57:50 +00003731void TargetProperties::SetRunArguments(const Args &args) {
3732 const uint32_t idx = ePropertyRunArgs;
3733 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3734 m_launch_info.GetArguments() = args;
Greg Clayton67cc0632012-08-22 17:17:09 +00003735}
3736
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737size_t TargetProperties::GetEnvironmentAsArgs(Args &env) const {
3738 const uint32_t idx = ePropertyEnvVars;
3739 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
Greg Clayton67cc0632012-08-22 17:17:09 +00003740}
3741
Kate Stoneb9c1b512016-09-06 20:57:50 +00003742void TargetProperties::SetEnvironmentFromArgs(const Args &env) {
3743 const uint32_t idx = ePropertyEnvVars;
3744 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, env);
3745 m_launch_info.GetEnvironmentEntries() = env;
Ilia K8f37ca52015-02-13 14:31:06 +00003746}
3747
Kate Stoneb9c1b512016-09-06 20:57:50 +00003748bool TargetProperties::GetSkipPrologue() const {
3749 const uint32_t idx = ePropertySkipPrologue;
3750 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3751 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003752}
3753
Kate Stoneb9c1b512016-09-06 20:57:50 +00003754PathMappingList &TargetProperties::GetSourcePathMap() const {
3755 const uint32_t idx = ePropertySourceMap;
3756 OptionValuePathMappings *option_value =
3757 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3758 false, idx);
3759 assert(option_value);
3760 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003761}
3762
Kate Stoneb9c1b512016-09-06 20:57:50 +00003763FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3764 const uint32_t idx = ePropertyExecutableSearchPaths;
3765 OptionValueFileSpecList *option_value =
3766 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3767 false, idx);
3768 assert(option_value);
3769 return option_value->GetCurrentValue();
Greg Clayton67cc0632012-08-22 17:17:09 +00003770}
3771
Kate Stoneb9c1b512016-09-06 20:57:50 +00003772FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3773 const uint32_t idx = ePropertyDebugFileSearchPaths;
3774 OptionValueFileSpecList *option_value =
3775 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3776 false, idx);
3777 assert(option_value);
3778 return option_value->GetCurrentValue();
Michael Sartaina7499c92013-07-01 19:45:50 +00003779}
3780
Kate Stoneb9c1b512016-09-06 20:57:50 +00003781FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3782 const uint32_t idx = ePropertyClangModuleSearchPaths;
3783 OptionValueFileSpecList *option_value =
3784 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3785 false, idx);
3786 assert(option_value);
3787 return option_value->GetCurrentValue();
Sean Callanan85054342015-04-03 15:39:47 +00003788}
3789
Kate Stoneb9c1b512016-09-06 20:57:50 +00003790bool TargetProperties::GetEnableAutoImportClangModules() const {
3791 const uint32_t idx = ePropertyAutoImportClangModules;
3792 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3793 nullptr, idx, g_properties[idx].default_uint_value != 0);
Sean Callananf0c5aeb2015-04-20 16:31:29 +00003794}
3795
Kate Stoneb9c1b512016-09-06 20:57:50 +00003796bool TargetProperties::GetEnableAutoApplyFixIts() const {
3797 const uint32_t idx = ePropertyAutoApplyFixIts;
3798 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3799 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghama1e541b2016-03-25 01:57:14 +00003800}
3801
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3803 const uint32_t idx = ePropertyNotifyAboutFixIts;
3804 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3805 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghame5ee6f02016-03-29 22:00:08 +00003806}
3807
Sean Callanan5deb06e2016-09-26 20:18:51 +00003808bool TargetProperties::GetEnableSaveObjects() const {
3809 const uint32_t idx = ePropertySaveObjects;
3810 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3811 nullptr, idx, g_properties[idx].default_uint_value != 0);
3812}
3813
Kate Stoneb9c1b512016-09-06 20:57:50 +00003814bool TargetProperties::GetEnableSyntheticValue() const {
3815 const uint32_t idx = ePropertyEnableSynthetic;
3816 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3817 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003818}
3819
Kate Stoneb9c1b512016-09-06 20:57:50 +00003820uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3821 const uint32_t idx = ePropertyMaxChildrenCount;
3822 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3823 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003824}
3825
Kate Stoneb9c1b512016-09-06 20:57:50 +00003826uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3827 const uint32_t idx = ePropertyMaxSummaryLength;
3828 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3829 nullptr, idx, g_properties[idx].default_uint_value);
Greg Clayton67cc0632012-08-22 17:17:09 +00003830}
3831
Kate Stoneb9c1b512016-09-06 20:57:50 +00003832uint32_t TargetProperties::GetMaximumMemReadSize() const {
3833 const uint32_t idx = ePropertyMaxMemReadSize;
3834 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3835 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granatad325bf92013-06-04 22:54:16 +00003836}
3837
Kate Stoneb9c1b512016-09-06 20:57:50 +00003838FileSpec TargetProperties::GetStandardInputPath() const {
3839 const uint32_t idx = ePropertyInputPath;
3840 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003841}
3842
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003843void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003844 const uint32_t idx = ePropertyInputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003845 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003846}
3847
Kate Stoneb9c1b512016-09-06 20:57:50 +00003848FileSpec TargetProperties::GetStandardOutputPath() const {
3849 const uint32_t idx = ePropertyOutputPath;
3850 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003851}
3852
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003853void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003854 const uint32_t idx = ePropertyOutputPath;
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003855 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
Greg Clayton67cc0632012-08-22 17:17:09 +00003856}
3857
Kate Stoneb9c1b512016-09-06 20:57:50 +00003858FileSpec TargetProperties::GetStandardErrorPath() const {
3859 const uint32_t idx = ePropertyErrorPath;
3860 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Clayton67cc0632012-08-22 17:17:09 +00003861}
3862
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003863void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3864 const uint32_t idx = ePropertyErrorPath;
3865 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3866}
3867
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868LanguageType TargetProperties::GetLanguage() const {
3869 OptionValueLanguage *value =
3870 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3871 nullptr, ePropertyLanguage);
3872 if (value)
3873 return value->GetCurrentValue();
3874 return LanguageType();
Dawn Perchik23b1dec2015-07-21 22:05:07 +00003875}
3876
Kate Stoneb9c1b512016-09-06 20:57:50 +00003877const char *TargetProperties::GetExpressionPrefixContentsAsCString() {
3878 const uint32_t idx = ePropertyExprPrefix;
3879 OptionValueFileSpec *file =
3880 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3881 idx);
3882 if (file) {
3883 const bool null_terminate = true;
3884 DataBufferSP data_sp(file->GetFileContents(null_terminate));
3885 if (data_sp)
3886 return (const char *)data_sp->GetBytes();
3887 }
3888 return nullptr;
Greg Clayton6920b522012-08-22 18:39:03 +00003889}
3890
Kate Stoneb9c1b512016-09-06 20:57:50 +00003891bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3892 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3893 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3894 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +00003895}
3896
Kate Stoneb9c1b512016-09-06 20:57:50 +00003897bool TargetProperties::GetUseHexImmediates() const {
3898 const uint32_t idx = ePropertyUseHexImmediates;
3899 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3900 nullptr, idx, g_properties[idx].default_uint_value != 0);
Daniel Malead79ae052013-08-07 21:54:09 +00003901}
3902
Kate Stoneb9c1b512016-09-06 20:57:50 +00003903bool TargetProperties::GetUseFastStepping() const {
3904 const uint32_t idx = ePropertyUseFastStepping;
3905 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3906 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham17d023f2013-03-13 17:58:04 +00003907}
3908
Kate Stoneb9c1b512016-09-06 20:57:50 +00003909bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3910 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3911 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3912 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Claytonfb6621e2013-12-06 21:59:52 +00003913}
3914
Kate Stoneb9c1b512016-09-06 20:57:50 +00003915LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3916 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3917 return (LoadScriptFromSymFile)
3918 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3919 nullptr, idx, g_properties[idx].default_uint_value);
Enrico Granata2ea43cd2013-05-13 17:03:52 +00003920}
3921
Kate Stoneb9c1b512016-09-06 20:57:50 +00003922LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3923 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3924 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3925 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molenda878ae012016-02-19 00:05:17 +00003926}
3927
Kate Stoneb9c1b512016-09-06 20:57:50 +00003928Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3929 const uint32_t idx = ePropertyHexImmediateStyle;
3930 return (Disassembler::HexImmediateStyle)
3931 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3932 nullptr, idx, g_properties[idx].default_uint_value);
Daniel Malead79ae052013-08-07 21:54:09 +00003933}
3934
Kate Stoneb9c1b512016-09-06 20:57:50 +00003935MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3936 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3937 return (MemoryModuleLoadLevel)
3938 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3939 nullptr, idx, g_properties[idx].default_uint_value);
Greg Claytonfd814c52013-08-13 01:42:25 +00003940}
3941
Kate Stoneb9c1b512016-09-06 20:57:50 +00003942bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3943 const uint32_t idx = ePropertyTrapHandlerNames;
3944 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003945}
Greg Claytonfd814c52013-08-13 01:42:25 +00003946
Kate Stoneb9c1b512016-09-06 20:57:50 +00003947void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3948 const uint32_t idx = ePropertyTrapHandlerNames;
3949 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Jason Molendaa4bea722014-02-14 05:06:49 +00003950}
Greg Clayton67cc0632012-08-22 17:17:09 +00003951
Kate Stoneb9c1b512016-09-06 20:57:50 +00003952bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3953 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3954 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Enrico Granata560558e2015-02-11 02:35:39 +00003955}
3956
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3958 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3959 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Enrico Granata560558e2015-02-11 02:35:39 +00003960}
3961
Kate Stoneb9c1b512016-09-06 20:57:50 +00003962bool TargetProperties::GetNonStopModeEnabled() const {
3963 const uint32_t idx = ePropertyNonStopModeEnabled;
3964 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
Ewan Crawford78baa192015-05-13 09:18:18 +00003965}
3966
Kate Stoneb9c1b512016-09-06 20:57:50 +00003967void TargetProperties::SetNonStopModeEnabled(bool b) {
3968 const uint32_t idx = ePropertyNonStopModeEnabled;
3969 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
Ewan Crawfordaa7eda72015-06-24 15:14:26 +00003970}
3971
Kate Stoneb9c1b512016-09-06 20:57:50 +00003972const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3973 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3974 return m_launch_info;
Ilia K8f37ca52015-02-13 14:31:06 +00003975}
3976
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977void TargetProperties::SetProcessLaunchInfo(
3978 const ProcessLaunchInfo &launch_info) {
3979 m_launch_info = launch_info;
3980 SetArg0(launch_info.GetArg0());
3981 SetRunArguments(launch_info.GetArguments());
3982 SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
3983 const FileAction *input_file_action =
3984 launch_info.GetFileActionForFD(STDIN_FILENO);
3985 if (input_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003986 SetStandardInputPath(input_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003987 }
3988 const FileAction *output_file_action =
3989 launch_info.GetFileActionForFD(STDOUT_FILENO);
3990 if (output_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003991 SetStandardOutputPath(output_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003992 }
3993 const FileAction *error_file_action =
3994 launch_info.GetFileActionForFD(STDERR_FILENO);
3995 if (error_file_action) {
Zachary Turner27a5c2b2016-09-23 22:11:51 +00003996 SetStandardErrorPath(error_file_action->GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003997 }
3998 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3999 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4000 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
Ilia K8f37ca52015-02-13 14:31:06 +00004001}
4002
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4004 OptionValue *) {
4005 TargetProperties *this_ =
4006 reinterpret_cast<TargetProperties *>(target_property_ptr);
4007 this_->m_launch_info.SetArg0(this_->GetArg0());
Ilia K8f37ca52015-02-13 14:31:06 +00004008}
4009
Kate Stoneb9c1b512016-09-06 20:57:50 +00004010void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4011 OptionValue *) {
4012 TargetProperties *this_ =
4013 reinterpret_cast<TargetProperties *>(target_property_ptr);
4014 Args args;
4015 if (this_->GetRunArguments(args))
4016 this_->m_launch_info.GetArguments() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00004017}
4018
Kate Stoneb9c1b512016-09-06 20:57:50 +00004019void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4020 OptionValue *) {
4021 TargetProperties *this_ =
4022 reinterpret_cast<TargetProperties *>(target_property_ptr);
4023 Args args;
4024 if (this_->GetEnvironmentAsArgs(args))
4025 this_->m_launch_info.GetEnvironmentEntries() = args;
Ilia K8f37ca52015-02-13 14:31:06 +00004026}
4027
Kate Stoneb9c1b512016-09-06 20:57:50 +00004028void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4029 OptionValue *) {
4030 TargetProperties *this_ =
4031 reinterpret_cast<TargetProperties *>(target_property_ptr);
4032 this_->m_launch_info.AppendOpenFileAction(
4033 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
Ilia K8f37ca52015-02-13 14:31:06 +00004034}
4035
Kate Stoneb9c1b512016-09-06 20:57:50 +00004036void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4037 OptionValue *) {
4038 TargetProperties *this_ =
4039 reinterpret_cast<TargetProperties *>(target_property_ptr);
4040 this_->m_launch_info.AppendOpenFileAction(
4041 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004042}
4043
Kate Stoneb9c1b512016-09-06 20:57:50 +00004044void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4045 OptionValue *) {
4046 TargetProperties *this_ =
4047 reinterpret_cast<TargetProperties *>(target_property_ptr);
4048 this_->m_launch_info.AppendOpenFileAction(
4049 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
Ilia K8f37ca52015-02-13 14:31:06 +00004050}
4051
Kate Stoneb9c1b512016-09-06 20:57:50 +00004052void TargetProperties::DetachOnErrorValueChangedCallback(
4053 void *target_property_ptr, OptionValue *) {
4054 TargetProperties *this_ =
4055 reinterpret_cast<TargetProperties *>(target_property_ptr);
4056 if (this_->GetDetachOnError())
4057 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4058 else
4059 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
Ilia K8f37ca52015-02-13 14:31:06 +00004060}
4061
Kate Stoneb9c1b512016-09-06 20:57:50 +00004062void TargetProperties::DisableASLRValueChangedCallback(
4063 void *target_property_ptr, OptionValue *) {
4064 TargetProperties *this_ =
4065 reinterpret_cast<TargetProperties *>(target_property_ptr);
4066 if (this_->GetDisableASLR())
4067 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4068 else
4069 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
Ilia K8f37ca52015-02-13 14:31:06 +00004070}
4071
Kate Stoneb9c1b512016-09-06 20:57:50 +00004072void TargetProperties::DisableSTDIOValueChangedCallback(
4073 void *target_property_ptr, OptionValue *) {
4074 TargetProperties *this_ =
4075 reinterpret_cast<TargetProperties *>(target_property_ptr);
4076 if (this_->GetDisableSTDIO())
4077 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4078 else
4079 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
Ilia K8f37ca52015-02-13 14:31:06 +00004080}
Ilia Keb2c19a2015-03-10 21:59:55 +00004081
4082//----------------------------------------------------------------------
4083// Target::TargetEventData
4084//----------------------------------------------------------------------
4085
Kate Stoneb9c1b512016-09-06 20:57:50 +00004086Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4087 : EventData(), m_target_sp(target_sp), m_module_list() {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004088
Kate Stoneb9c1b512016-09-06 20:57:50 +00004089Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4090 const ModuleList &module_list)
4091 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
Ilia Keb2c19a2015-03-10 21:59:55 +00004092
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004093Target::TargetEventData::~TargetEventData() = default;
Ilia Keb2c19a2015-03-10 21:59:55 +00004094
Kate Stoneb9c1b512016-09-06 20:57:50 +00004095const ConstString &Target::TargetEventData::GetFlavorString() {
4096 static ConstString g_flavor("Target::TargetEventData");
4097 return g_flavor;
Ilia Keb2c19a2015-03-10 21:59:55 +00004098}
4099
Kate Stoneb9c1b512016-09-06 20:57:50 +00004100void Target::TargetEventData::Dump(Stream *s) const {
4101 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4102 if (i != 0)
4103 *s << ", ";
4104 m_module_list.GetModuleAtIndex(i)->GetDescription(
4105 s, lldb::eDescriptionLevelBrief);
4106 }
Ilia Keb2c19a2015-03-10 21:59:55 +00004107}
4108
4109const Target::TargetEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004110Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4111 if (event_ptr) {
4112 const EventData *event_data = event_ptr->GetData();
4113 if (event_data &&
4114 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4115 return static_cast<const TargetEventData *>(event_ptr->GetData());
4116 }
4117 return nullptr;
Ilia Keb2c19a2015-03-10 21:59:55 +00004118}
4119
Kate Stoneb9c1b512016-09-06 20:57:50 +00004120TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4121 TargetSP target_sp;
4122 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4123 if (event_data)
4124 target_sp = event_data->m_target_sp;
4125 return target_sp;
Ilia Keb2c19a2015-03-10 21:59:55 +00004126}
4127
4128ModuleList
Kate Stoneb9c1b512016-09-06 20:57:50 +00004129Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4130 ModuleList module_list;
4131 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4132 if (event_data)
4133 module_list = event_data->m_module_list;
4134 return module_list;
Ilia Keb2c19a2015-03-10 21:59:55 +00004135}