1 //===-- CommandObjectMemory.cpp ---------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "clang/AST/Decl.h"
14 #include "CommandObjectMemory.h"
15 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Core/DumpDataExtractor.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/Section.h"
20 #include "lldb/Core/ValueObjectMemory.h"
21 #include "lldb/DataFormatters/ValueObjectPrinter.h"
22 #include "lldb/Host/OptionParser.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/CommandReturnObject.h"
25 #include "lldb/Interpreter/OptionArgParser.h"
26 #include "lldb/Interpreter/OptionGroupFormat.h"
27 #include "lldb/Interpreter/OptionGroupOutputFile.h"
28 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
29 #include "lldb/Interpreter/OptionValueString.h"
30 #include "lldb/Interpreter/Options.h"
31 #include "lldb/Symbol/ClangASTContext.h"
32 #include "lldb/Symbol/SymbolFile.h"
33 #include "lldb/Symbol/TypeList.h"
34 #include "lldb/Target/MemoryHistory.h"
35 #include "lldb/Target/MemoryRegionInfo.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/StackFrame.h"
38 #include "lldb/Target/Thread.h"
39 #include "lldb/Utility/Args.h"
40 #include "lldb/Utility/DataBufferHeap.h"
41 #include "lldb/Utility/DataBufferLLVM.h"
42 #include "lldb/Utility/StreamString.h"
44 #include "lldb/lldb-private.h"
47 using namespace lldb_private;
49 static constexpr OptionDefinition g_read_memory_options[] = {
51 {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNumberPerLine, "The number of items per line to display." },
52 {LLDB_OPT_SET_2, false, "binary", 'b', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If true, memory will be saved as binary. If false, the memory is saved save as an ASCII dump that "
53 "uses the format, size, count and number per line settings." },
54 {LLDB_OPT_SET_3, true , "type", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "The name of a type to view memory as." },
55 {LLDB_OPT_SET_3, false, "offset", 'E', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many elements of the specified type to skip before starting to display data." },
58 LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Necessary if reading over target.max-memory-read-size bytes." },
62 class OptionGroupReadMemory : public OptionGroup {
64 OptionGroupReadMemory()
65 : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(),
68 ~OptionGroupReadMemory() override = default;
70 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
71 return llvm::makeArrayRef(g_read_memory_options);
74 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
75 ExecutionContext *execution_context) override {
77 const int short_option = g_read_memory_options[option_idx].short_option;
79 switch (short_option) {
81 error = m_num_per_line.SetValueFromString(option_value);
82 if (m_num_per_line.GetCurrentValue() == 0)
83 error.SetErrorStringWithFormat(
84 "invalid value for --num-per-line option '%s'",
85 option_value.str().c_str());
89 m_output_as_binary = true;
93 error = m_view_as_type.SetValueFromString(option_value);
101 error = m_offset.SetValueFromString(option_value);
105 error.SetErrorStringWithFormat("unrecognized short option '%c'",
112 void OptionParsingStarting(ExecutionContext *execution_context) override {
113 m_num_per_line.Clear();
114 m_output_as_binary = false;
115 m_view_as_type.Clear();
120 Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) {
122 OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue();
123 OptionValueUInt64 &count_value = format_options.GetCountValue();
124 const bool byte_size_option_set = byte_size_value.OptionWasSet();
125 const bool num_per_line_option_set = m_num_per_line.OptionWasSet();
126 const bool count_option_set = format_options.GetCountValue().OptionWasSet();
128 switch (format_options.GetFormat()) {
133 if (!byte_size_option_set)
135 if (!num_per_line_option_set)
137 if (!count_option_set)
138 format_options.GetCountValue() = 8;
144 case eFormatInstruction:
145 if (count_option_set)
146 byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
150 case eFormatAddressInfo:
151 if (!byte_size_option_set)
152 byte_size_value = target->GetArchitecture().GetAddressByteSize();
154 if (!count_option_set)
155 format_options.GetCountValue() = 8;
159 byte_size_value = target->GetArchitecture().GetAddressByteSize();
160 if (!num_per_line_option_set)
162 if (!count_option_set)
163 format_options.GetCountValue() = 8;
171 case eFormatUnicode16:
172 case eFormatUnicode32:
173 case eFormatUnsigned:
174 case eFormatHexFloat:
175 if (!byte_size_option_set)
177 if (!num_per_line_option_set)
179 if (!count_option_set)
180 format_options.GetCountValue() = 8;
184 case eFormatBytesWithASCII:
185 if (byte_size_option_set) {
186 if (byte_size_value > 1)
187 error.SetErrorStringWithFormat(
188 "display format (bytes/bytes with ASCII) conflicts with the "
189 "specified byte size %" PRIu64 "\n"
190 "\tconsider using a different display format or don't specify "
192 byte_size_value.GetCurrentValue());
195 if (!num_per_line_option_set)
197 if (!count_option_set)
198 format_options.GetCountValue() = 32;
201 case eFormatCharArray:
203 case eFormatCharPrintable:
204 if (!byte_size_option_set)
206 if (!num_per_line_option_set)
208 if (!count_option_set)
209 format_options.GetCountValue() = 64;
213 if (!byte_size_option_set)
215 if (!num_per_line_option_set)
217 if (!count_option_set)
218 format_options.GetCountValue() = 8;
221 case eFormatComplexInteger:
222 if (!byte_size_option_set)
224 if (!num_per_line_option_set)
226 if (!count_option_set)
227 format_options.GetCountValue() = 8;
231 if (!byte_size_option_set)
233 if (!num_per_line_option_set) {
234 switch (byte_size_value) {
250 if (!count_option_set)
254 case eFormatVectorOfChar:
255 case eFormatVectorOfSInt8:
256 case eFormatVectorOfUInt8:
257 case eFormatVectorOfSInt16:
258 case eFormatVectorOfUInt16:
259 case eFormatVectorOfSInt32:
260 case eFormatVectorOfUInt32:
261 case eFormatVectorOfSInt64:
262 case eFormatVectorOfUInt64:
263 case eFormatVectorOfFloat16:
264 case eFormatVectorOfFloat32:
265 case eFormatVectorOfFloat64:
266 case eFormatVectorOfUInt128:
267 if (!byte_size_option_set)
268 byte_size_value = 128;
269 if (!num_per_line_option_set)
271 if (!count_option_set)
278 bool AnyOptionWasSet() const {
279 return m_num_per_line.OptionWasSet() || m_output_as_binary ||
280 m_view_as_type.OptionWasSet() || m_offset.OptionWasSet();
283 OptionValueUInt64 m_num_per_line;
284 bool m_output_as_binary;
285 OptionValueString m_view_as_type;
287 OptionValueUInt64 m_offset;
290 //----------------------------------------------------------------------
291 // Read memory from the inferior process
292 //----------------------------------------------------------------------
293 class CommandObjectMemoryRead : public CommandObjectParsed {
295 CommandObjectMemoryRead(CommandInterpreter &interpreter)
296 : CommandObjectParsed(
297 interpreter, "memory read",
298 "Read from the memory of the current target process.", nullptr,
299 eCommandRequiresTarget | eCommandProcessMustBePaused),
300 m_option_group(), m_format_options(eFormatBytesWithASCII, 1, 8),
301 m_memory_options(), m_outfile_options(), m_varobj_options(),
302 m_next_addr(LLDB_INVALID_ADDRESS), m_prev_byte_size(0),
303 m_prev_format_options(eFormatBytesWithASCII, 1, 8),
304 m_prev_memory_options(), m_prev_outfile_options(),
305 m_prev_varobj_options() {
306 CommandArgumentEntry arg1;
307 CommandArgumentEntry arg2;
308 CommandArgumentData start_addr_arg;
309 CommandArgumentData end_addr_arg;
311 // Define the first (and only) variant of this arg.
312 start_addr_arg.arg_type = eArgTypeAddressOrExpression;
313 start_addr_arg.arg_repetition = eArgRepeatPlain;
315 // There is only one variant this argument could be; put it into the
317 arg1.push_back(start_addr_arg);
319 // Define the first (and only) variant of this arg.
320 end_addr_arg.arg_type = eArgTypeAddressOrExpression;
321 end_addr_arg.arg_repetition = eArgRepeatOptional;
323 // There is only one variant this argument could be; put it into the
325 arg2.push_back(end_addr_arg);
327 // Push the data for the first argument into the m_arguments vector.
328 m_arguments.push_back(arg1);
329 m_arguments.push_back(arg2);
331 // Add the "--format" and "--count" options to group 1 and 3
332 m_option_group.Append(&m_format_options,
333 OptionGroupFormat::OPTION_GROUP_FORMAT |
334 OptionGroupFormat::OPTION_GROUP_COUNT,
335 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
336 m_option_group.Append(&m_format_options,
337 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
338 LLDB_OPT_SET_1 | LLDB_OPT_SET_3);
339 // Add the "--size" option to group 1 and 2
340 m_option_group.Append(&m_format_options,
341 OptionGroupFormat::OPTION_GROUP_SIZE,
342 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
343 m_option_group.Append(&m_memory_options);
344 m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL,
345 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
346 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
347 m_option_group.Finalize();
350 ~CommandObjectMemoryRead() override = default;
352 Options *GetOptions() override { return &m_option_group; }
354 const char *GetRepeatCommand(Args ¤t_command_args,
355 uint32_t index) override {
356 return m_cmd_name.c_str();
360 bool DoExecute(Args &command, CommandReturnObject &result) override {
361 // No need to check "target" for validity as eCommandRequiresTarget ensures
363 Target *target = m_exe_ctx.GetTargetPtr();
365 const size_t argc = command.GetArgumentCount();
367 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
368 result.AppendErrorWithFormat("%s takes a start address expression with "
369 "an optional end address expression.\n",
371 result.AppendRawWarning("Expressions should be quoted if they contain "
372 "spaces or other special characters.\n");
373 result.SetStatus(eReturnStatusFailed);
377 CompilerType clang_ast_type;
380 const char *view_as_type_cstr =
381 m_memory_options.m_view_as_type.GetCurrentValue();
382 if (view_as_type_cstr && view_as_type_cstr[0]) {
383 // We are viewing memory as a type
385 const bool exact_match = false;
387 uint32_t reference_count = 0;
388 uint32_t pointer_count = 0;
391 #define ALL_KEYWORDS \
393 KEYWORD("volatile") \
394 KEYWORD("restrict") \
399 #define KEYWORD(s) s,
400 static const char *g_keywords[] = {ALL_KEYWORDS};
403 #define KEYWORD(s) (sizeof(s) - 1),
404 static const int g_keyword_lengths[] = {ALL_KEYWORDS};
409 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
410 std::string type_str(view_as_type_cstr);
412 // Remove all instances of g_keywords that are followed by spaces
413 for (size_t i = 0; i < g_num_keywords; ++i) {
414 const char *keyword = g_keywords[i];
415 int keyword_len = g_keyword_lengths[i];
418 while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
419 if (type_str[idx + keyword_len] == ' ' ||
420 type_str[idx + keyword_len] == '\t') {
421 type_str.erase(idx, keyword_len + 1);
428 bool done = type_str.empty();
430 idx = type_str.find_first_not_of(" \t");
431 if (idx > 0 && idx != std::string::npos)
432 type_str.erase(0, idx);
434 // Strip trailing spaces
435 if (type_str.empty())
438 switch (type_str[type_str.size() - 1]) {
444 type_str.erase(type_str.size() - 1);
448 if (reference_count == 0) {
450 type_str.erase(type_str.size() - 1);
452 result.AppendErrorWithFormat("invalid type string: '%s'\n",
454 result.SetStatus(eReturnStatusFailed);
466 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
467 ConstString lookup_type_name(type_str.c_str());
468 StackFrame *frame = m_exe_ctx.GetFramePtr();
469 ModuleSP search_first;
471 search_first = frame->GetSymbolContext(eSymbolContextModule).module_sp;
473 target->GetImages().FindTypes(search_first.get(), lookup_type_name,
474 exact_match, 1, searched_symbol_files,
477 if (type_list.GetSize() == 0 && lookup_type_name.GetCString() &&
478 *lookup_type_name.GetCString() == '$') {
479 if (ClangPersistentVariables *persistent_vars =
480 llvm::dyn_cast_or_null<ClangPersistentVariables>(
481 target->GetPersistentExpressionStateForLanguage(
482 lldb::eLanguageTypeC))) {
483 clang::TypeDecl *tdecl = llvm::dyn_cast_or_null<clang::TypeDecl>(
484 persistent_vars->GetPersistentDecl(
485 ConstString(lookup_type_name)));
488 clang_ast_type.SetCompilerType(
489 ClangASTContext::GetASTContext(&tdecl->getASTContext()),
490 reinterpret_cast<lldb::opaque_compiler_type_t>(
491 const_cast<clang::Type *>(tdecl->getTypeForDecl())));
496 if (!clang_ast_type.IsValid()) {
497 if (type_list.GetSize() == 0) {
498 result.AppendErrorWithFormat("unable to find any types that match "
499 "the raw type '%s' for full type '%s'\n",
500 lookup_type_name.GetCString(),
502 result.SetStatus(eReturnStatusFailed);
505 TypeSP type_sp(type_list.GetTypeAtIndex(0));
506 clang_ast_type = type_sp->GetFullCompilerType();
510 while (pointer_count > 0) {
511 CompilerType pointer_type = clang_ast_type.GetPointerType();
512 if (pointer_type.IsValid())
513 clang_ast_type = pointer_type;
515 result.AppendError("unable make a pointer type\n");
516 result.SetStatus(eReturnStatusFailed);
522 llvm::Optional<uint64_t> size = clang_ast_type.GetByteSize(nullptr);
524 result.AppendErrorWithFormat(
525 "unable to get the byte size of the type '%s'\n",
527 result.SetStatus(eReturnStatusFailed);
530 m_format_options.GetByteSizeValue() = *size;
532 if (!m_format_options.GetCountValue().OptionWasSet())
533 m_format_options.GetCountValue() = 1;
535 error = m_memory_options.FinalizeSettings(target, m_format_options);
538 // Look for invalid combinations of settings
540 result.AppendError(error.AsCString());
541 result.SetStatus(eReturnStatusFailed);
546 size_t total_byte_size = 0;
548 // Use the last address and byte size and all options as they were if no
549 // options have been set
551 total_byte_size = m_prev_byte_size;
552 clang_ast_type = m_prev_clang_ast_type;
553 if (!m_format_options.AnyOptionWasSet() &&
554 !m_memory_options.AnyOptionWasSet() &&
555 !m_outfile_options.AnyOptionWasSet() &&
556 !m_varobj_options.AnyOptionWasSet()) {
557 m_format_options = m_prev_format_options;
558 m_memory_options = m_prev_memory_options;
559 m_outfile_options = m_prev_outfile_options;
560 m_varobj_options = m_prev_varobj_options;
564 size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
566 // TODO For non-8-bit byte addressable architectures this needs to be
567 // revisited to fully support all lldb's range of formatting options.
568 // Furthermore code memory reads (for those architectures) will not be
569 // correctly formatted even w/o formatting options.
570 size_t item_byte_size =
571 target->GetArchitecture().GetDataByteSize() > 1
572 ? target->GetArchitecture().GetDataByteSize()
573 : m_format_options.GetByteSizeValue().GetCurrentValue();
575 const size_t num_per_line =
576 m_memory_options.m_num_per_line.GetCurrentValue();
578 if (total_byte_size == 0) {
579 total_byte_size = item_count * item_byte_size;
580 if (total_byte_size == 0)
581 total_byte_size = 32;
585 addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref,
586 LLDB_INVALID_ADDRESS, &error);
588 if (addr == LLDB_INVALID_ADDRESS) {
589 result.AppendError("invalid start address expression.");
590 result.AppendError(error.AsCString());
591 result.SetStatus(eReturnStatusFailed);
596 lldb::addr_t end_addr = OptionArgParser::ToAddress(
597 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, nullptr);
598 if (end_addr == LLDB_INVALID_ADDRESS) {
599 result.AppendError("invalid end address expression.");
600 result.AppendError(error.AsCString());
601 result.SetStatus(eReturnStatusFailed);
603 } else if (end_addr <= addr) {
604 result.AppendErrorWithFormat(
605 "end address (0x%" PRIx64
606 ") must be greater that the start address (0x%" PRIx64 ").\n",
608 result.SetStatus(eReturnStatusFailed);
610 } else if (m_format_options.GetCountValue().OptionWasSet()) {
611 result.AppendErrorWithFormat(
612 "specify either the end address (0x%" PRIx64
613 ") or the count (--count %" PRIu64 "), not both.\n",
614 end_addr, (uint64_t)item_count);
615 result.SetStatus(eReturnStatusFailed);
619 total_byte_size = end_addr - addr;
620 item_count = total_byte_size / item_byte_size;
623 uint32_t max_unforced_size = target->GetMaximumMemReadSize();
625 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
626 result.AppendErrorWithFormat(
627 "Normally, \'memory read\' will not read over %" PRIu32
630 result.AppendErrorWithFormat(
631 "Please use --force to override this restriction just once.\n");
632 result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
633 "will often need a larger limit.\n");
637 DataBufferSP data_sp;
638 size_t bytes_read = 0;
639 if (clang_ast_type.GetOpaqueQualType()) {
640 // Make sure we don't display our type as ASCII bytes like the default
642 if (!m_format_options.GetFormatValue().OptionWasSet())
643 m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
645 llvm::Optional<uint64_t> size = clang_ast_type.GetByteSize(nullptr);
647 result.AppendError("can't get size of type");
650 bytes_read = *size * m_format_options.GetCountValue().GetCurrentValue();
653 addr = addr + (*size * m_memory_options.m_offset.GetCurrentValue());
654 } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
656 data_sp.reset(new DataBufferHeap(total_byte_size, '\0'));
657 if (data_sp->GetBytes() == nullptr) {
658 result.AppendErrorWithFormat(
659 "can't allocate 0x%" PRIx32
660 " bytes for the memory read buffer, specify a smaller size to read",
661 (uint32_t)total_byte_size);
662 result.SetStatus(eReturnStatusFailed);
666 Address address(addr, nullptr);
667 bytes_read = target->ReadMemory(address, false, data_sp->GetBytes(),
668 data_sp->GetByteSize(), error);
669 if (bytes_read == 0) {
670 const char *error_cstr = error.AsCString();
671 if (error_cstr && error_cstr[0]) {
672 result.AppendError(error_cstr);
674 result.AppendErrorWithFormat(
675 "failed to read memory from 0x%" PRIx64 ".\n", addr);
677 result.SetStatus(eReturnStatusFailed);
681 if (bytes_read < total_byte_size)
682 result.AppendWarningWithFormat(
683 "Not all bytes (%" PRIu64 "/%" PRIu64
684 ") were able to be read from 0x%" PRIx64 ".\n",
685 (uint64_t)bytes_read, (uint64_t)total_byte_size, addr);
687 // we treat c-strings as a special case because they do not have a fixed
689 if (m_format_options.GetByteSizeValue().OptionWasSet() &&
690 !m_format_options.HasGDBFormat())
691 item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
693 item_byte_size = target->GetMaximumSizeOfStringSummary();
694 if (!m_format_options.GetCountValue().OptionWasSet())
696 data_sp.reset(new DataBufferHeap((item_byte_size + 1) * item_count,
697 '\0')); // account for NULLs as necessary
698 if (data_sp->GetBytes() == nullptr) {
699 result.AppendErrorWithFormat(
700 "can't allocate 0x%" PRIx64
701 " bytes for the memory read buffer, specify a smaller size to read",
702 (uint64_t)((item_byte_size + 1) * item_count));
703 result.SetStatus(eReturnStatusFailed);
706 uint8_t *data_ptr = data_sp->GetBytes();
707 auto data_addr = addr;
708 auto count = item_count;
710 bool break_on_no_NULL = false;
711 while (item_count < count) {
713 buffer.resize(item_byte_size + 1, 0);
715 size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
716 item_byte_size + 1, error);
718 result.AppendErrorWithFormat(
719 "failed to read memory from 0x%" PRIx64 ".\n", addr);
720 result.SetStatus(eReturnStatusFailed);
724 if (item_byte_size == read) {
725 result.AppendWarningWithFormat(
726 "unable to find a NULL terminated string at 0x%" PRIx64
727 ".Consider increasing the maximum read length.\n",
730 break_on_no_NULL = true;
732 ++read; // account for final NULL byte
734 memcpy(data_ptr, &buffer[0], read);
738 item_count++; // if we break early we know we only read item_count
741 if (break_on_no_NULL)
744 data_sp.reset(new DataBufferHeap(data_sp->GetBytes(), bytes_read + 1));
747 m_next_addr = addr + bytes_read;
748 m_prev_byte_size = bytes_read;
749 m_prev_format_options = m_format_options;
750 m_prev_memory_options = m_memory_options;
751 m_prev_outfile_options = m_outfile_options;
752 m_prev_varobj_options = m_varobj_options;
753 m_prev_clang_ast_type = clang_ast_type;
755 StreamFile outfile_stream;
756 Stream *output_stream = nullptr;
757 const FileSpec &outfile_spec =
758 m_outfile_options.GetFile().GetCurrentValue();
760 std::string path = outfile_spec.GetPath();
763 uint32_t open_options =
764 File::eOpenOptionWrite | File::eOpenOptionCanCreate;
765 const bool append = m_outfile_options.GetAppend().GetCurrentValue();
767 open_options |= File::eOpenOptionAppend;
769 Status error = FileSystem::Instance().Open(outfile_stream.GetFile(),
770 outfile_spec, open_options);
771 if (error.Success()) {
772 if (m_memory_options.m_output_as_binary) {
773 const size_t bytes_written =
774 outfile_stream.Write(data_sp->GetBytes(), bytes_read);
775 if (bytes_written > 0) {
776 result.GetOutputStream().Printf(
777 "%zi bytes %s to '%s'\n", bytes_written,
778 append ? "appended" : "written", path.c_str());
781 result.AppendErrorWithFormat("Failed to write %" PRIu64
783 (uint64_t)bytes_read, path.c_str());
784 result.SetStatus(eReturnStatusFailed);
788 // We are going to write ASCII to the file just point the
789 // output_stream to our outfile_stream...
790 output_stream = &outfile_stream;
793 result.AppendErrorWithFormat("Failed to open file '%s' for %s.\n",
794 path.c_str(), append ? "append" : "write");
795 result.SetStatus(eReturnStatusFailed);
799 output_stream = &result.GetOutputStream();
802 ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
803 if (clang_ast_type.GetOpaqueQualType()) {
804 for (uint32_t i = 0; i < item_count; ++i) {
805 addr_t item_addr = addr + (i * item_byte_size);
806 Address address(item_addr);
807 StreamString name_strm;
808 name_strm.Printf("0x%" PRIx64, item_addr);
809 ValueObjectSP valobj_sp(ValueObjectMemory::Create(
810 exe_scope, name_strm.GetString(), address, clang_ast_type));
812 Format format = m_format_options.GetFormat();
813 if (format != eFormatDefault)
814 valobj_sp->SetFormat(format);
816 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
817 eLanguageRuntimeDescriptionDisplayVerbosityFull, format));
819 valobj_sp->Dump(*output_stream, options);
821 result.AppendErrorWithFormat(
822 "failed to create a value object for: (%s) %s\n",
823 view_as_type_cstr, name_strm.GetData());
824 result.SetStatus(eReturnStatusFailed);
831 result.SetStatus(eReturnStatusSuccessFinishResult);
832 DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
833 target->GetArchitecture().GetAddressByteSize(),
834 target->GetArchitecture().GetDataByteSize());
836 Format format = m_format_options.GetFormat();
837 if (((format == eFormatChar) || (format == eFormatCharPrintable)) &&
838 (item_byte_size != 1)) {
839 // if a count was not passed, or it is 1
840 if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) {
841 // this turns requests such as
842 // memory read -fc -s10 -c1 *charPtrPtr
843 // which make no sense (what is a char of size 10?) into a request for
844 // fetching 10 chars of size 1 from the same memory location
845 format = eFormatCharArray;
846 item_count = item_byte_size;
849 // here we passed a count, and it was not 1 so we have a byte_size and
850 // a count we could well multiply those, but instead let's just fail
851 result.AppendErrorWithFormat(
852 "reading memory as characters of size %" PRIu64 " is not supported",
853 (uint64_t)item_byte_size);
854 result.SetStatus(eReturnStatusFailed);
859 assert(output_stream);
860 size_t bytes_dumped = DumpDataExtractor(
861 data, output_stream, 0, format, item_byte_size, item_count,
862 num_per_line / target->GetArchitecture().GetDataByteSize(), addr, 0, 0,
864 m_next_addr = addr + bytes_dumped;
865 output_stream->EOL();
869 OptionGroupOptions m_option_group;
870 OptionGroupFormat m_format_options;
871 OptionGroupReadMemory m_memory_options;
872 OptionGroupOutputFile m_outfile_options;
873 OptionGroupValueObjectDisplay m_varobj_options;
874 lldb::addr_t m_next_addr;
875 lldb::addr_t m_prev_byte_size;
876 OptionGroupFormat m_prev_format_options;
877 OptionGroupReadMemory m_prev_memory_options;
878 OptionGroupOutputFile m_prev_outfile_options;
879 OptionGroupValueObjectDisplay m_prev_varobj_options;
880 CompilerType m_prev_clang_ast_type;
883 static constexpr OptionDefinition g_memory_find_option_table[] = {
885 {LLDB_OPT_SET_1, true, "expression", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeExpression, "Evaluate an expression to obtain a byte pattern."},
886 {LLDB_OPT_SET_2, true, "string", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Use text to find a byte pattern."},
887 {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many times to perform the search."},
888 {LLDB_OPT_SET_ALL, false, "dump-offset", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "When dumping memory for a match, an offset from the match location to start dumping from."},
892 //----------------------------------------------------------------------
893 // Find the specified data in memory
894 //----------------------------------------------------------------------
895 class CommandObjectMemoryFind : public CommandObjectParsed {
897 class OptionGroupFindMemory : public OptionGroup {
899 OptionGroupFindMemory() : OptionGroup(), m_count(1), m_offset(0) {}
901 ~OptionGroupFindMemory() override = default;
903 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
904 return llvm::makeArrayRef(g_memory_find_option_table);
907 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
908 ExecutionContext *execution_context) override {
910 const int short_option =
911 g_memory_find_option_table[option_idx].short_option;
913 switch (short_option) {
915 m_expr.SetValueFromString(option_value);
919 m_string.SetValueFromString(option_value);
923 if (m_count.SetValueFromString(option_value).Fail())
924 error.SetErrorString("unrecognized value for count");
928 if (m_offset.SetValueFromString(option_value).Fail())
929 error.SetErrorString("unrecognized value for dump-offset");
933 error.SetErrorStringWithFormat("unrecognized short option '%c'",
940 void OptionParsingStarting(ExecutionContext *execution_context) override {
946 OptionValueString m_expr;
947 OptionValueString m_string;
948 OptionValueUInt64 m_count;
949 OptionValueUInt64 m_offset;
952 CommandObjectMemoryFind(CommandInterpreter &interpreter)
953 : CommandObjectParsed(
954 interpreter, "memory find",
955 "Find a value in the memory of the current target process.",
956 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched),
957 m_option_group(), m_memory_options() {
958 CommandArgumentEntry arg1;
959 CommandArgumentEntry arg2;
960 CommandArgumentData addr_arg;
961 CommandArgumentData value_arg;
963 // Define the first (and only) variant of this arg.
964 addr_arg.arg_type = eArgTypeAddressOrExpression;
965 addr_arg.arg_repetition = eArgRepeatPlain;
967 // There is only one variant this argument could be; put it into the
969 arg1.push_back(addr_arg);
971 // Define the first (and only) variant of this arg.
972 value_arg.arg_type = eArgTypeAddressOrExpression;
973 value_arg.arg_repetition = eArgRepeatPlain;
975 // There is only one variant this argument could be; put it into the
977 arg2.push_back(value_arg);
979 // Push the data for the first argument into the m_arguments vector.
980 m_arguments.push_back(arg1);
981 m_arguments.push_back(arg2);
983 m_option_group.Append(&m_memory_options);
984 m_option_group.Finalize();
987 ~CommandObjectMemoryFind() override = default;
989 Options *GetOptions() override { return &m_option_group; }
992 class ProcessMemoryIterator {
994 ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base)
995 : m_process_sp(process_sp), m_base_addr(base), m_is_valid(true) {
996 lldbassert(process_sp.get() != nullptr);
999 bool IsValid() { return m_is_valid; }
1001 uint8_t operator[](lldb::addr_t offset) {
1008 m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) {
1017 ProcessSP m_process_sp;
1018 lldb::addr_t m_base_addr;
1021 bool DoExecute(Args &command, CommandReturnObject &result) override {
1022 // No need to check "process" for validity as eCommandRequiresProcess
1023 // ensures it is valid
1024 Process *process = m_exe_ctx.GetProcessPtr();
1026 const size_t argc = command.GetArgumentCount();
1029 result.AppendError("two addresses needed for memory find");
1034 lldb::addr_t low_addr = OptionArgParser::ToAddress(
1035 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
1036 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1037 result.AppendError("invalid low address");
1040 lldb::addr_t high_addr = OptionArgParser::ToAddress(
1041 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, &error);
1042 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1043 result.AppendError("invalid high address");
1047 if (high_addr <= low_addr) {
1049 "starting address must be smaller than ending address");
1053 lldb::addr_t found_location = LLDB_INVALID_ADDRESS;
1055 DataBufferHeap buffer;
1057 if (m_memory_options.m_string.OptionWasSet())
1058 buffer.CopyData(m_memory_options.m_string.GetStringValue());
1059 else if (m_memory_options.m_expr.OptionWasSet()) {
1060 StackFrame *frame = m_exe_ctx.GetFramePtr();
1061 ValueObjectSP result_sp;
1062 if ((eExpressionCompleted ==
1063 process->GetTarget().EvaluateExpression(
1064 m_memory_options.m_expr.GetStringValue(), frame, result_sp)) &&
1066 uint64_t value = result_sp->GetValueAsUnsigned(0);
1067 llvm::Optional<uint64_t> size =
1068 result_sp->GetCompilerType().GetByteSize(nullptr);
1073 uint8_t byte = (uint8_t)value;
1074 buffer.CopyData(&byte, 1);
1077 uint16_t word = (uint16_t)value;
1078 buffer.CopyData(&word, 2);
1081 uint32_t lword = (uint32_t)value;
1082 buffer.CopyData(&lword, 4);
1085 buffer.CopyData(&value, 8);
1091 result.AppendError("unknown type. pass a string instead");
1095 "result size larger than 8 bytes. pass a string instead");
1100 "expression evaluation failed. pass a string instead");
1105 "please pass either a block of text, or an expression to evaluate.");
1109 size_t count = m_memory_options.m_count.GetCurrentValue();
1110 found_location = low_addr;
1111 bool ever_found = false;
1113 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(),
1114 buffer.GetByteSize());
1115 if (found_location == LLDB_INVALID_ADDRESS) {
1117 result.AppendMessage("data not found within the range.\n");
1118 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
1120 result.AppendMessage("no more matches within the range.\n");
1123 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n",
1126 DataBufferHeap dumpbuffer(32, 0);
1127 process->ReadMemory(
1128 found_location + m_memory_options.m_offset.GetCurrentValue(),
1129 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error);
1130 if (!error.Fail()) {
1131 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(),
1132 process->GetByteOrder(),
1133 process->GetAddressByteSize());
1135 data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1136 dumpbuffer.GetByteSize(), 16,
1137 found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0);
1138 result.GetOutputStream().EOL();
1146 result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
1150 lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer,
1151 size_t buffer_size) {
1152 const size_t region_size = high - low;
1154 if (region_size < buffer_size)
1155 return LLDB_INVALID_ADDRESS;
1157 std::vector<size_t> bad_char_heuristic(256, buffer_size);
1158 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1159 ProcessMemoryIterator iterator(process_sp, low);
1161 for (size_t idx = 0; idx < buffer_size - 1; idx++) {
1162 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx];
1163 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1;
1165 for (size_t s = 0; s <= (region_size - buffer_size);) {
1166 int64_t j = buffer_size - 1;
1167 while (j >= 0 && buffer[j] == iterator[s + j])
1172 s += bad_char_heuristic[iterator[s + buffer_size - 1]];
1175 return LLDB_INVALID_ADDRESS;
1178 OptionGroupOptions m_option_group;
1179 OptionGroupFindMemory m_memory_options;
1182 static constexpr OptionDefinition g_memory_write_option_table[] = {
1184 {LLDB_OPT_SET_1, true, "infile", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFilename, "Write memory using the contents of a file."},
1185 {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "Start writing bytes from an offset within the input file."},
1189 //----------------------------------------------------------------------
1190 // Write memory to the inferior process
1191 //----------------------------------------------------------------------
1192 class CommandObjectMemoryWrite : public CommandObjectParsed {
1194 class OptionGroupWriteMemory : public OptionGroup {
1196 OptionGroupWriteMemory() : OptionGroup() {}
1198 ~OptionGroupWriteMemory() override = default;
1200 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1201 return llvm::makeArrayRef(g_memory_write_option_table);
1204 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1205 ExecutionContext *execution_context) override {
1207 const int short_option =
1208 g_memory_write_option_table[option_idx].short_option;
1210 switch (short_option) {
1212 m_infile.SetFile(option_value, FileSpec::Style::native);
1213 FileSystem::Instance().Resolve(m_infile);
1214 if (!FileSystem::Instance().Exists(m_infile)) {
1216 error.SetErrorStringWithFormat("input file does not exist: '%s'",
1217 option_value.str().c_str());
1222 if (option_value.getAsInteger(0, m_infile_offset)) {
1223 m_infile_offset = 0;
1224 error.SetErrorStringWithFormat("invalid offset string '%s'",
1225 option_value.str().c_str());
1230 error.SetErrorStringWithFormat("unrecognized short option '%c'",
1237 void OptionParsingStarting(ExecutionContext *execution_context) override {
1239 m_infile_offset = 0;
1243 off_t m_infile_offset;
1246 CommandObjectMemoryWrite(CommandInterpreter &interpreter)
1247 : CommandObjectParsed(
1248 interpreter, "memory write",
1249 "Write to the memory of the current target process.", nullptr,
1250 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1251 m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX),
1252 m_memory_options() {
1253 CommandArgumentEntry arg1;
1254 CommandArgumentEntry arg2;
1255 CommandArgumentData addr_arg;
1256 CommandArgumentData value_arg;
1258 // Define the first (and only) variant of this arg.
1259 addr_arg.arg_type = eArgTypeAddress;
1260 addr_arg.arg_repetition = eArgRepeatPlain;
1262 // There is only one variant this argument could be; put it into the
1264 arg1.push_back(addr_arg);
1266 // Define the first (and only) variant of this arg.
1267 value_arg.arg_type = eArgTypeValue;
1268 value_arg.arg_repetition = eArgRepeatPlus;
1270 // There is only one variant this argument could be; put it into the
1272 arg2.push_back(value_arg);
1274 // Push the data for the first argument into the m_arguments vector.
1275 m_arguments.push_back(arg1);
1276 m_arguments.push_back(arg2);
1278 m_option_group.Append(&m_format_options,
1279 OptionGroupFormat::OPTION_GROUP_FORMAT,
1281 m_option_group.Append(&m_format_options,
1282 OptionGroupFormat::OPTION_GROUP_SIZE,
1283 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
1284 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2);
1285 m_option_group.Finalize();
1288 ~CommandObjectMemoryWrite() override = default;
1290 Options *GetOptions() override { return &m_option_group; }
1292 bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) {
1293 if (total_byte_size > 8)
1296 if (total_byte_size == 8)
1299 const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1;
1300 return uval64 <= max;
1303 bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) {
1304 if (total_byte_size > 8)
1307 if (total_byte_size == 8)
1310 const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1;
1311 const int64_t min = ~(max);
1312 return min <= sval64 && sval64 <= max;
1316 bool DoExecute(Args &command, CommandReturnObject &result) override {
1317 // No need to check "process" for validity as eCommandRequiresProcess
1318 // ensures it is valid
1319 Process *process = m_exe_ctx.GetProcessPtr();
1321 const size_t argc = command.GetArgumentCount();
1323 if (m_memory_options.m_infile) {
1325 result.AppendErrorWithFormat(
1326 "%s takes a destination address when writing file contents.\n",
1327 m_cmd_name.c_str());
1328 result.SetStatus(eReturnStatusFailed);
1331 } else if (argc < 2) {
1332 result.AppendErrorWithFormat(
1333 "%s takes a destination address and at least one value.\n",
1334 m_cmd_name.c_str());
1335 result.SetStatus(eReturnStatusFailed);
1339 StreamString buffer(
1341 process->GetTarget().GetArchitecture().GetAddressByteSize(),
1342 process->GetTarget().GetArchitecture().GetByteOrder());
1344 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1345 size_t item_byte_size = byte_size_value.GetCurrentValue();
1348 lldb::addr_t addr = OptionArgParser::ToAddress(
1349 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
1351 if (addr == LLDB_INVALID_ADDRESS) {
1352 result.AppendError("invalid address expression\n");
1353 result.AppendError(error.AsCString());
1354 result.SetStatus(eReturnStatusFailed);
1358 if (m_memory_options.m_infile) {
1359 size_t length = SIZE_MAX;
1360 if (item_byte_size > 1)
1361 length = item_byte_size;
1362 auto data_sp = FileSystem::Instance().CreateDataBuffer(
1363 m_memory_options.m_infile.GetPath(), length,
1364 m_memory_options.m_infile_offset);
1366 length = data_sp->GetByteSize();
1369 size_t bytes_written =
1370 process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1372 if (bytes_written == length) {
1373 // All bytes written
1374 result.GetOutputStream().Printf(
1375 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1376 (uint64_t)bytes_written, addr);
1377 result.SetStatus(eReturnStatusSuccessFinishResult);
1378 } else if (bytes_written > 0) {
1379 // Some byte written
1380 result.GetOutputStream().Printf(
1381 "%" PRIu64 " bytes of %" PRIu64
1382 " requested were written to 0x%" PRIx64 "\n",
1383 (uint64_t)bytes_written, (uint64_t)length, addr);
1384 result.SetStatus(eReturnStatusSuccessFinishResult);
1386 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1388 addr, error.AsCString());
1389 result.SetStatus(eReturnStatusFailed);
1393 result.AppendErrorWithFormat("Unable to read contents of file.\n");
1394 result.SetStatus(eReturnStatusFailed);
1396 return result.Succeeded();
1397 } else if (item_byte_size == 0) {
1398 if (m_format_options.GetFormat() == eFormatPointer)
1399 item_byte_size = buffer.GetAddressByteSize();
1404 command.Shift(); // shift off the address argument
1407 bool success = false;
1408 for (auto &entry : command) {
1409 switch (m_format_options.GetFormat()) {
1411 case eFormatFloat: // TODO: add support for floats soon
1412 case eFormatCharPrintable:
1413 case eFormatBytesWithASCII:
1414 case eFormatComplex:
1416 case eFormatUnicode16:
1417 case eFormatUnicode32:
1418 case eFormatVectorOfChar:
1419 case eFormatVectorOfSInt8:
1420 case eFormatVectorOfUInt8:
1421 case eFormatVectorOfSInt16:
1422 case eFormatVectorOfUInt16:
1423 case eFormatVectorOfSInt32:
1424 case eFormatVectorOfUInt32:
1425 case eFormatVectorOfSInt64:
1426 case eFormatVectorOfUInt64:
1427 case eFormatVectorOfFloat16:
1428 case eFormatVectorOfFloat32:
1429 case eFormatVectorOfFloat64:
1430 case eFormatVectorOfUInt128:
1432 case eFormatComplexInteger:
1433 case eFormatAddressInfo:
1434 case eFormatHexFloat:
1435 case eFormatInstruction:
1437 result.AppendError("unsupported format for writing memory");
1438 result.SetStatus(eReturnStatusFailed);
1441 case eFormatDefault:
1444 case eFormatHexUppercase:
1445 case eFormatPointer:
1448 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1449 // have to special case that:
1450 bool success = false;
1451 if (entry.ref.startswith("0x"))
1452 success = !entry.ref.getAsInteger(0, uval64);
1454 success = !entry.ref.getAsInteger(16, uval64);
1456 result.AppendErrorWithFormat(
1457 "'%s' is not a valid hex string value.\n", entry.c_str());
1458 result.SetStatus(eReturnStatusFailed);
1460 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1461 result.AppendErrorWithFormat("Value 0x%" PRIx64
1462 " is too large to fit in a %" PRIu64
1463 " byte unsigned integer value.\n",
1464 uval64, (uint64_t)item_byte_size);
1465 result.SetStatus(eReturnStatusFailed);
1468 buffer.PutMaxHex64(uval64, item_byte_size);
1471 case eFormatBoolean:
1472 uval64 = OptionArgParser::ToBoolean(entry.ref, false, &success);
1474 result.AppendErrorWithFormat(
1475 "'%s' is not a valid boolean string value.\n", entry.c_str());
1476 result.SetStatus(eReturnStatusFailed);
1479 buffer.PutMaxHex64(uval64, item_byte_size);
1483 if (entry.ref.getAsInteger(2, uval64)) {
1484 result.AppendErrorWithFormat(
1485 "'%s' is not a valid binary string value.\n", entry.c_str());
1486 result.SetStatus(eReturnStatusFailed);
1488 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1489 result.AppendErrorWithFormat("Value 0x%" PRIx64
1490 " is too large to fit in a %" PRIu64
1491 " byte unsigned integer value.\n",
1492 uval64, (uint64_t)item_byte_size);
1493 result.SetStatus(eReturnStatusFailed);
1496 buffer.PutMaxHex64(uval64, item_byte_size);
1499 case eFormatCharArray:
1501 case eFormatCString: {
1502 if (entry.ref.empty())
1505 size_t len = entry.ref.size();
1506 // Include the NULL for C strings...
1507 if (m_format_options.GetFormat() == eFormatCString)
1510 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1513 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1515 addr, error.AsCString());
1516 result.SetStatus(eReturnStatusFailed);
1521 case eFormatDecimal:
1522 if (entry.ref.getAsInteger(0, sval64)) {
1523 result.AppendErrorWithFormat(
1524 "'%s' is not a valid signed decimal value.\n", entry.c_str());
1525 result.SetStatus(eReturnStatusFailed);
1527 } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) {
1528 result.AppendErrorWithFormat(
1529 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1530 " byte signed integer value.\n",
1531 sval64, (uint64_t)item_byte_size);
1532 result.SetStatus(eReturnStatusFailed);
1535 buffer.PutMaxHex64(sval64, item_byte_size);
1538 case eFormatUnsigned:
1540 if (!entry.ref.getAsInteger(0, uval64)) {
1541 result.AppendErrorWithFormat(
1542 "'%s' is not a valid unsigned decimal string value.\n",
1544 result.SetStatus(eReturnStatusFailed);
1546 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1547 result.AppendErrorWithFormat("Value %" PRIu64
1548 " is too large to fit in a %" PRIu64
1549 " byte unsigned integer value.\n",
1550 uval64, (uint64_t)item_byte_size);
1551 result.SetStatus(eReturnStatusFailed);
1554 buffer.PutMaxHex64(uval64, item_byte_size);
1558 if (entry.ref.getAsInteger(8, uval64)) {
1559 result.AppendErrorWithFormat(
1560 "'%s' is not a valid octal string value.\n", entry.c_str());
1561 result.SetStatus(eReturnStatusFailed);
1563 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1564 result.AppendErrorWithFormat("Value %" PRIo64
1565 " is too large to fit in a %" PRIu64
1566 " byte unsigned integer value.\n",
1567 uval64, (uint64_t)item_byte_size);
1568 result.SetStatus(eReturnStatusFailed);
1571 buffer.PutMaxHex64(uval64, item_byte_size);
1576 if (!buffer.GetString().empty()) {
1578 if (process->WriteMemory(addr, buffer.GetString().data(),
1579 buffer.GetString().size(),
1580 error) == buffer.GetString().size())
1583 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1585 addr, error.AsCString());
1586 result.SetStatus(eReturnStatusFailed);
1593 OptionGroupOptions m_option_group;
1594 OptionGroupFormat m_format_options;
1595 OptionGroupWriteMemory m_memory_options;
1598 //----------------------------------------------------------------------
1599 // Get malloc/free history of a memory address.
1600 //----------------------------------------------------------------------
1601 class CommandObjectMemoryHistory : public CommandObjectParsed {
1603 CommandObjectMemoryHistory(CommandInterpreter &interpreter)
1604 : CommandObjectParsed(
1605 interpreter, "memory history", "Print recorded stack traces for "
1606 "allocation/deallocation events "
1607 "associated with an address.",
1609 eCommandRequiresTarget | eCommandRequiresProcess |
1610 eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) {
1611 CommandArgumentEntry arg1;
1612 CommandArgumentData addr_arg;
1614 // Define the first (and only) variant of this arg.
1615 addr_arg.arg_type = eArgTypeAddress;
1616 addr_arg.arg_repetition = eArgRepeatPlain;
1618 // There is only one variant this argument could be; put it into the
1620 arg1.push_back(addr_arg);
1622 // Push the data for the first argument into the m_arguments vector.
1623 m_arguments.push_back(arg1);
1626 ~CommandObjectMemoryHistory() override = default;
1628 const char *GetRepeatCommand(Args ¤t_command_args,
1629 uint32_t index) override {
1630 return m_cmd_name.c_str();
1634 bool DoExecute(Args &command, CommandReturnObject &result) override {
1635 const size_t argc = command.GetArgumentCount();
1637 if (argc == 0 || argc > 1) {
1638 result.AppendErrorWithFormat("%s takes an address expression",
1639 m_cmd_name.c_str());
1640 result.SetStatus(eReturnStatusFailed);
1645 lldb::addr_t addr = OptionArgParser::ToAddress(
1646 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
1648 if (addr == LLDB_INVALID_ADDRESS) {
1649 result.AppendError("invalid address expression");
1650 result.AppendError(error.AsCString());
1651 result.SetStatus(eReturnStatusFailed);
1655 Stream *output_stream = &result.GetOutputStream();
1657 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1658 const MemoryHistorySP &memory_history =
1659 MemoryHistory::FindPlugin(process_sp);
1661 if (!memory_history) {
1662 result.AppendError("no available memory history provider");
1663 result.SetStatus(eReturnStatusFailed);
1667 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1669 const bool stop_format = false;
1670 for (auto thread : thread_list) {
1671 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
1674 result.SetStatus(eReturnStatusSuccessFinishResult);
1680 //-------------------------------------------------------------------------
1681 // CommandObjectMemoryRegion
1682 //-------------------------------------------------------------------------
1683 #pragma mark CommandObjectMemoryRegion
1685 class CommandObjectMemoryRegion : public CommandObjectParsed {
1687 CommandObjectMemoryRegion(CommandInterpreter &interpreter)
1688 : CommandObjectParsed(interpreter, "memory region",
1689 "Get information on the memory region containing "
1690 "an address in the current target process.",
1691 "memory region ADDR",
1692 eCommandRequiresProcess | eCommandTryTargetAPILock |
1693 eCommandProcessMustBeLaunched),
1694 m_prev_end_addr(LLDB_INVALID_ADDRESS) {}
1696 ~CommandObjectMemoryRegion() override = default;
1699 bool DoExecute(Args &command, CommandReturnObject &result) override {
1700 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1703 lldb::addr_t load_addr = m_prev_end_addr;
1704 m_prev_end_addr = LLDB_INVALID_ADDRESS;
1706 const size_t argc = command.GetArgumentCount();
1707 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) {
1708 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n",
1709 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1710 result.SetStatus(eReturnStatusFailed);
1712 if (command.GetArgumentCount() == 1) {
1713 auto load_addr_str = command[0].ref;
1714 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1715 LLDB_INVALID_ADDRESS, &error);
1716 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1717 result.AppendErrorWithFormat(
1718 "invalid address argument \"%s\": %s\n", command[0].c_str(),
1720 result.SetStatus(eReturnStatusFailed);
1724 lldb_private::MemoryRegionInfo range_info;
1725 error = process_sp->GetMemoryRegionInfo(load_addr, range_info);
1726 if (error.Success()) {
1727 lldb_private::Address addr;
1728 ConstString name = range_info.GetName();
1729 ConstString section_name;
1730 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) {
1731 SectionSP section_sp(addr.GetSection());
1733 // Got the top most section, not the deepest section
1734 while (section_sp->GetParent())
1735 section_sp = section_sp->GetParent();
1736 section_name = section_sp->GetName();
1739 result.AppendMessageWithFormat(
1740 "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s%s%s\n",
1741 range_info.GetRange().GetRangeBase(),
1742 range_info.GetRange().GetRangeEnd(),
1743 range_info.GetReadable() ? 'r' : '-',
1744 range_info.GetWritable() ? 'w' : '-',
1745 range_info.GetExecutable() ? 'x' : '-',
1746 name ? " " : "", name.AsCString(""),
1747 section_name ? " " : "", section_name.AsCString(""));
1748 m_prev_end_addr = range_info.GetRange().GetRangeEnd();
1749 result.SetStatus(eReturnStatusSuccessFinishResult);
1751 result.SetStatus(eReturnStatusFailed);
1752 result.AppendErrorWithFormat("%s\n", error.AsCString());
1756 m_prev_end_addr = LLDB_INVALID_ADDRESS;
1757 result.AppendError("invalid process");
1758 result.SetStatus(eReturnStatusFailed);
1760 return result.Succeeded();
1763 const char *GetRepeatCommand(Args ¤t_command_args,
1764 uint32_t index) override {
1765 // If we repeat this command, repeat it without any arguments so we can
1766 // show the next memory range
1767 return m_cmd_name.c_str();
1770 lldb::addr_t m_prev_end_addr;
1773 //-------------------------------------------------------------------------
1774 // CommandObjectMemory
1775 //-------------------------------------------------------------------------
1777 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter)
1778 : CommandObjectMultiword(
1779 interpreter, "memory",
1780 "Commands for operating on memory in the current target process.",
1781 "memory <subcommand> [<subcommand-options>]") {
1782 LoadSubCommand("find",
1783 CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1784 LoadSubCommand("read",
1785 CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1786 LoadSubCommand("write",
1787 CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1788 LoadSubCommand("history",
1789 CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1790 LoadSubCommand("region",
1791 CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
1794 CommandObjectMemory::~CommandObjectMemory() = default;