LLDB mainline
CommandObjectMemory.cpp
Go to the documentation of this file.
1//===-- CommandObjectMemory.cpp -------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
12#include "lldb/Core/Section.h"
28#include "lldb/Target/ABI.h"
32#include "lldb/Target/Process.h"
34#include "lldb/Target/Target.h"
35#include "lldb/Target/Thread.h"
36#include "lldb/Utility/Args.h"
39#include "llvm/Support/MathExtras.h"
40#include <cinttypes>
41#include <memory>
42#include <optional>
43
44using namespace lldb;
45using namespace lldb_private;
46
47#define LLDB_OPTIONS_memory_read
48#include "CommandOptions.inc"
49
51public:
53 : m_num_per_line(1, 1), m_offset(0, 0),
55
56 ~OptionGroupReadMemory() override = default;
57
58 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
59 return llvm::ArrayRef(g_memory_read_options);
60 }
61
62 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
63 ExecutionContext *execution_context) override {
65 const int short_option = g_memory_read_options[option_idx].short_option;
66
67 switch (short_option) {
68 case 'l':
71 error.SetErrorStringWithFormat(
72 "invalid value for --num-per-line option '%s'",
73 option_value.str().c_str());
74 break;
75
76 case 'b':
77 m_output_as_binary = true;
78 break;
79
80 case 't':
82 break;
83
84 case 'r':
85 m_force = true;
86 break;
87
88 case 'x':
90 break;
91
92 case 'E':
93 error = m_offset.SetValueFromString(option_value);
94 break;
95
96 default:
97 llvm_unreachable("Unimplemented option");
98 }
99 return error;
100 }
101
102 void OptionParsingStarting(ExecutionContext *execution_context) override {
104 m_output_as_binary = false;
106 m_force = false;
107 m_offset.Clear();
109 }
110
113 OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue();
114 OptionValueUInt64 &count_value = format_options.GetCountValue();
115 const bool byte_size_option_set = byte_size_value.OptionWasSet();
116 const bool num_per_line_option_set = m_num_per_line.OptionWasSet();
117 const bool count_option_set = format_options.GetCountValue().OptionWasSet();
118
119 switch (format_options.GetFormat()) {
120 default:
121 break;
122
123 case eFormatBoolean:
124 if (!byte_size_option_set)
125 byte_size_value = 1;
126 if (!num_per_line_option_set)
127 m_num_per_line = 1;
128 if (!count_option_set)
129 format_options.GetCountValue() = 8;
130 break;
131
132 case eFormatCString:
133 break;
134
136 if (count_option_set)
137 byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
138 m_num_per_line = 1;
139 break;
140
142 if (!byte_size_option_set)
143 byte_size_value = target->GetArchitecture().GetAddressByteSize();
144 m_num_per_line = 1;
145 if (!count_option_set)
146 format_options.GetCountValue() = 8;
147 break;
148
149 case eFormatPointer:
150 byte_size_value = target->GetArchitecture().GetAddressByteSize();
151 if (!num_per_line_option_set)
152 m_num_per_line = 4;
153 if (!count_option_set)
154 format_options.GetCountValue() = 8;
155 break;
156
157 case eFormatBinary:
158 case eFormatFloat:
159 case eFormatOctal:
160 case eFormatDecimal:
161 case eFormatEnum:
162 case eFormatUnicode8:
163 case eFormatUnicode16:
164 case eFormatUnicode32:
165 case eFormatUnsigned:
166 case eFormatHexFloat:
167 if (!byte_size_option_set)
168 byte_size_value = 4;
169 if (!num_per_line_option_set)
170 m_num_per_line = 1;
171 if (!count_option_set)
172 format_options.GetCountValue() = 8;
173 break;
174
175 case eFormatBytes:
177 if (byte_size_option_set) {
178 if (byte_size_value > 1)
179 error.SetErrorStringWithFormat(
180 "display format (bytes/bytes with ASCII) conflicts with the "
181 "specified byte size %" PRIu64 "\n"
182 "\tconsider using a different display format or don't specify "
183 "the byte size.",
184 byte_size_value.GetCurrentValue());
185 } else
186 byte_size_value = 1;
187 if (!num_per_line_option_set)
188 m_num_per_line = 16;
189 if (!count_option_set)
190 format_options.GetCountValue() = 32;
191 break;
192
193 case eFormatCharArray:
194 case eFormatChar:
196 if (!byte_size_option_set)
197 byte_size_value = 1;
198 if (!num_per_line_option_set)
199 m_num_per_line = 32;
200 if (!count_option_set)
201 format_options.GetCountValue() = 64;
202 break;
203
204 case eFormatComplex:
205 if (!byte_size_option_set)
206 byte_size_value = 8;
207 if (!num_per_line_option_set)
208 m_num_per_line = 1;
209 if (!count_option_set)
210 format_options.GetCountValue() = 8;
211 break;
212
214 if (!byte_size_option_set)
215 byte_size_value = 8;
216 if (!num_per_line_option_set)
217 m_num_per_line = 1;
218 if (!count_option_set)
219 format_options.GetCountValue() = 8;
220 break;
221
222 case eFormatHex:
223 if (!byte_size_option_set)
224 byte_size_value = 4;
225 if (!num_per_line_option_set) {
226 switch (byte_size_value) {
227 case 1:
228 case 2:
229 m_num_per_line = 8;
230 break;
231 case 4:
232 m_num_per_line = 4;
233 break;
234 case 8:
235 m_num_per_line = 2;
236 break;
237 default:
238 m_num_per_line = 1;
239 break;
240 }
241 }
242 if (!count_option_set)
243 count_value = 8;
244 break;
245
259 if (!byte_size_option_set)
260 byte_size_value = 128;
261 if (!num_per_line_option_set)
262 m_num_per_line = 1;
263 if (!count_option_set)
264 count_value = 4;
265 break;
266 }
267 return error;
268 }
269
270 bool AnyOptionWasSet() const {
274 }
275
277 bool m_output_as_binary = false;
279 bool m_force = false;
282};
283
284// Read memory from the inferior process
286public:
289 interpreter, "memory read",
290 "Read from the memory of the current target process.", nullptr,
291 eCommandRequiresTarget | eCommandProcessMustBePaused),
293 m_memory_tag_options(/*note_binary=*/true),
297 CommandArgumentData start_addr_arg;
298 CommandArgumentData end_addr_arg;
299
300 // Define the first (and only) variant of this arg.
301 start_addr_arg.arg_type = eArgTypeAddressOrExpression;
302 start_addr_arg.arg_repetition = eArgRepeatPlain;
303
304 // There is only one variant this argument could be; put it into the
305 // argument entry.
306 arg1.push_back(start_addr_arg);
307
308 // Define the first (and only) variant of this arg.
310 end_addr_arg.arg_repetition = eArgRepeatOptional;
311
312 // There is only one variant this argument could be; put it into the
313 // argument entry.
314 arg2.push_back(end_addr_arg);
315
316 // Push the data for the first argument into the m_arguments vector.
317 m_arguments.push_back(arg1);
318 m_arguments.push_back(arg2);
319
320 // Add the "--format" and "--count" options to group 1 and 3
328 // Add the "--size" option to group 1 and 2
339 }
340
341 ~CommandObjectMemoryRead() override = default;
342
343 Options *GetOptions() override { return &m_option_group; }
344
345 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
346 uint32_t index) override {
347 return m_cmd_name;
348 }
349
350protected:
351 bool DoExecute(Args &command, CommandReturnObject &result) override {
352 // No need to check "target" for validity as eCommandRequiresTarget ensures
353 // it is valid
354 Target *target = m_exe_ctx.GetTargetPtr();
355
356 const size_t argc = command.GetArgumentCount();
357
358 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
359 result.AppendErrorWithFormat("%s takes a start address expression with "
360 "an optional end address expression.\n",
361 m_cmd_name.c_str());
362 result.AppendWarning("Expressions should be quoted if they contain "
363 "spaces or other special characters.");
364 return false;
365 }
366
367 CompilerType compiler_type;
369
370 const char *view_as_type_cstr =
372 if (view_as_type_cstr && view_as_type_cstr[0]) {
373 // We are viewing memory as a type
374
375 const bool exact_match = false;
376 TypeList type_list;
377 uint32_t reference_count = 0;
378 uint32_t pointer_count = 0;
379 size_t idx;
380
381#define ALL_KEYWORDS \
382 KEYWORD("const") \
383 KEYWORD("volatile") \
384 KEYWORD("restrict") \
385 KEYWORD("struct") \
386 KEYWORD("class") \
387 KEYWORD("union")
388
389#define KEYWORD(s) s,
390 static const char *g_keywords[] = {ALL_KEYWORDS};
391#undef KEYWORD
392
393#define KEYWORD(s) (sizeof(s) - 1),
394 static const int g_keyword_lengths[] = {ALL_KEYWORDS};
395#undef KEYWORD
396
397#undef ALL_KEYWORDS
398
399 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
400 std::string type_str(view_as_type_cstr);
401
402 // Remove all instances of g_keywords that are followed by spaces
403 for (size_t i = 0; i < g_num_keywords; ++i) {
404 const char *keyword = g_keywords[i];
405 int keyword_len = g_keyword_lengths[i];
406
407 idx = 0;
408 while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
409 if (type_str[idx + keyword_len] == ' ' ||
410 type_str[idx + keyword_len] == '\t') {
411 type_str.erase(idx, keyword_len + 1);
412 idx = 0;
413 } else {
414 idx += keyword_len;
415 }
416 }
417 }
418 bool done = type_str.empty();
419 //
420 idx = type_str.find_first_not_of(" \t");
421 if (idx > 0 && idx != std::string::npos)
422 type_str.erase(0, idx);
423 while (!done) {
424 // Strip trailing spaces
425 if (type_str.empty())
426 done = true;
427 else {
428 switch (type_str[type_str.size() - 1]) {
429 case '*':
430 ++pointer_count;
431 [[fallthrough]];
432 case ' ':
433 case '\t':
434 type_str.erase(type_str.size() - 1);
435 break;
436
437 case '&':
438 if (reference_count == 0) {
439 reference_count = 1;
440 type_str.erase(type_str.size() - 1);
441 } else {
442 result.AppendErrorWithFormat("invalid type string: '%s'\n",
443 view_as_type_cstr);
444 return false;
445 }
446 break;
447
448 default:
449 done = true;
450 break;
451 }
452 }
453 }
454
455 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
456 ConstString lookup_type_name(type_str.c_str());
458 ModuleSP search_first;
459 if (frame) {
460 search_first = frame->GetSymbolContext(eSymbolContextModule).module_sp;
461 }
462 target->GetImages().FindTypes(search_first.get(), lookup_type_name,
463 exact_match, 1, searched_symbol_files,
464 type_list);
465
466 if (type_list.GetSize() == 0 && lookup_type_name.GetCString()) {
467 LanguageType language_for_type =
469 std::set<LanguageType> languages_to_check;
470 if (language_for_type != eLanguageTypeUnknown) {
471 languages_to_check.insert(language_for_type);
472 } else {
473 languages_to_check = Language::GetSupportedLanguages();
474 }
475
476 std::set<CompilerType> user_defined_types;
477 for (auto lang : languages_to_check) {
478 if (auto *persistent_vars =
480 if (std::optional<CompilerType> type =
481 persistent_vars->GetCompilerTypeFromPersistentDecl(
482 lookup_type_name)) {
483 user_defined_types.emplace(*type);
484 }
485 }
486 }
487
488 if (user_defined_types.size() > 1) {
490 "Mutiple types found matching raw type '%s', please disambiguate "
491 "by specifying the language with -x",
492 lookup_type_name.GetCString());
493 return false;
494 }
495
496 if (user_defined_types.size() == 1) {
497 compiler_type = *user_defined_types.begin();
498 }
499 }
500
501 if (!compiler_type.IsValid()) {
502 if (type_list.GetSize() == 0) {
503 result.AppendErrorWithFormat("unable to find any types that match "
504 "the raw type '%s' for full type '%s'\n",
505 lookup_type_name.GetCString(),
506 view_as_type_cstr);
507 return false;
508 } else {
509 TypeSP type_sp(type_list.GetTypeAtIndex(0));
510 compiler_type = type_sp->GetFullCompilerType();
511 }
512 }
513
514 while (pointer_count > 0) {
515 CompilerType pointer_type = compiler_type.GetPointerType();
516 if (pointer_type.IsValid())
517 compiler_type = pointer_type;
518 else {
519 result.AppendError("unable make a pointer type\n");
520 return false;
521 }
522 --pointer_count;
523 }
524
525 std::optional<uint64_t> size = compiler_type.GetByteSize(nullptr);
526 if (!size) {
528 "unable to get the byte size of the type '%s'\n",
529 view_as_type_cstr);
530 return false;
531 }
533
536 } else {
538 }
539
540 // Look for invalid combinations of settings
541 if (error.Fail()) {
542 result.AppendError(error.AsCString());
543 return false;
544 }
545
546 lldb::addr_t addr;
547 size_t total_byte_size = 0;
548 if (argc == 0) {
549 // Use the last address and byte size and all options as they were if no
550 // options have been set
551 addr = m_next_addr;
552 total_byte_size = m_prev_byte_size;
553 compiler_type = m_prev_compiler_type;
564 }
565 }
566
567 size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
568
569 // TODO For non-8-bit byte addressable architectures this needs to be
570 // revisited to fully support all lldb's range of formatting options.
571 // Furthermore code memory reads (for those architectures) will not be
572 // correctly formatted even w/o formatting options.
573 size_t item_byte_size =
574 target->GetArchitecture().GetDataByteSize() > 1
575 ? target->GetArchitecture().GetDataByteSize()
577
578 const size_t num_per_line =
580
581 if (total_byte_size == 0) {
582 total_byte_size = item_count * item_byte_size;
583 if (total_byte_size == 0)
584 total_byte_size = 32;
585 }
586
587 if (argc > 0)
588 addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref(),
590
591 if (addr == LLDB_INVALID_ADDRESS) {
592 result.AppendError("invalid start address expression.");
593 result.AppendError(error.AsCString());
594 return false;
595 }
596
597 if (argc == 2) {
599 &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, nullptr);
600
601 if (end_addr == LLDB_INVALID_ADDRESS) {
602 result.AppendError("invalid end address expression.");
603 result.AppendError(error.AsCString());
604 return false;
605 } else if (end_addr <= addr) {
607 "end address (0x%" PRIx64
608 ") must be greater than the start address (0x%" PRIx64 ").\n",
609 end_addr, addr);
610 return false;
613 "specify either the end address (0x%" PRIx64
614 ") or the count (--count %" PRIu64 "), not both.\n",
615 end_addr, (uint64_t)item_count);
616 return false;
617 }
618
619 total_byte_size = end_addr - addr;
620 item_count = total_byte_size / item_byte_size;
621 }
622
623 uint32_t max_unforced_size = target->GetMaximumMemReadSize();
624
625 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
627 "Normally, \'memory read\' will not read over %" PRIu32
628 " bytes of data.\n",
629 max_unforced_size);
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");
634 return false;
635 }
636
637 WritableDataBufferSP data_sp;
638 size_t bytes_read = 0;
639 if (compiler_type.GetOpaqueQualType()) {
640 // Make sure we don't display our type as ASCII bytes like the default
641 // memory read
644
645 std::optional<uint64_t> size = compiler_type.GetByteSize(nullptr);
646 if (!size) {
647 result.AppendError("can't get size of type");
648 return false;
649 }
650 bytes_read = *size * m_format_options.GetCountValue().GetCurrentValue();
651
652 if (argc > 0)
653 addr = addr + (*size * m_memory_options.m_offset.GetCurrentValue());
656 data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0');
657 if (data_sp->GetBytes() == nullptr) {
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 return false;
663 }
664
665 Address address(addr, nullptr);
666 bytes_read = target->ReadMemory(address, data_sp->GetBytes(),
667 data_sp->GetByteSize(), error, true);
668 if (bytes_read == 0) {
669 const char *error_cstr = error.AsCString();
670 if (error_cstr && error_cstr[0]) {
671 result.AppendError(error_cstr);
672 } else {
674 "failed to read memory from 0x%" PRIx64 ".\n", addr);
675 }
676 return false;
677 }
678
679 if (bytes_read < total_byte_size)
681 "Not all bytes (%" PRIu64 "/%" PRIu64
682 ") were able to be read from 0x%" PRIx64 ".\n",
683 (uint64_t)bytes_read, (uint64_t)total_byte_size, addr);
684 } else {
685 // we treat c-strings as a special case because they do not have a fixed
686 // size
690 else
691 item_byte_size = target->GetMaximumSizeOfStringSummary();
693 item_count = 1;
694 data_sp = std::make_shared<DataBufferHeap>(
695 (item_byte_size + 1) * item_count,
696 '\0'); // account for NULLs as necessary
697 if (data_sp->GetBytes() == nullptr) {
699 "can't allocate 0x%" PRIx64
700 " bytes for the memory read buffer, specify a smaller size to read",
701 (uint64_t)((item_byte_size + 1) * item_count));
702 return false;
703 }
704 uint8_t *data_ptr = data_sp->GetBytes();
705 auto data_addr = addr;
706 auto count = item_count;
707 item_count = 0;
708 bool break_on_no_NULL = false;
709 while (item_count < count) {
710 std::string buffer;
711 buffer.resize(item_byte_size + 1, 0);
713 size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
714 item_byte_size + 1, error);
715 if (error.Fail()) {
717 "failed to read memory from 0x%" PRIx64 ".\n", addr);
718 return false;
719 }
720
721 if (item_byte_size == read) {
723 "unable to find a NULL terminated string at 0x%" PRIx64
724 ". Consider increasing the maximum read length.\n",
725 data_addr);
726 --read;
727 break_on_no_NULL = true;
728 } else
729 ++read; // account for final NULL byte
730
731 memcpy(data_ptr, &buffer[0], read);
732 data_ptr += read;
733 data_addr += read;
734 bytes_read += read;
735 item_count++; // if we break early we know we only read item_count
736 // strings
737
738 if (break_on_no_NULL)
739 break;
740 }
741 data_sp =
742 std::make_shared<DataBufferHeap>(data_sp->GetBytes(), bytes_read + 1);
743 }
744
745 m_next_addr = addr + bytes_read;
746 m_prev_byte_size = bytes_read;
752 m_prev_compiler_type = compiler_type;
753
754 std::unique_ptr<Stream> output_stream_storage;
755 Stream *output_stream_p = nullptr;
756 const FileSpec &outfile_spec =
758
759 std::string path = outfile_spec.GetPath();
760 if (outfile_spec) {
761
762 File::OpenOptions open_options =
764 const bool append = m_outfile_options.GetAppend().GetCurrentValue();
765 open_options |=
767
768 auto outfile = FileSystem::Instance().Open(outfile_spec, open_options);
769
770 if (outfile) {
771 auto outfile_stream_up =
772 std::make_unique<StreamFile>(std::move(outfile.get()));
774 const size_t bytes_written =
775 outfile_stream_up->Write(data_sp->GetBytes(), bytes_read);
776 if (bytes_written > 0) {
777 result.GetOutputStream().Printf(
778 "%zi bytes %s to '%s'\n", bytes_written,
779 append ? "appended" : "written", path.c_str());
780 return true;
781 } else {
782 result.AppendErrorWithFormat("Failed to write %" PRIu64
783 " bytes to '%s'.\n",
784 (uint64_t)bytes_read, path.c_str());
785 return false;
786 }
787 } else {
788 // We are going to write ASCII to the file just point the
789 // output_stream to our outfile_stream...
790 output_stream_storage = std::move(outfile_stream_up);
791 output_stream_p = output_stream_storage.get();
792 }
793 } else {
794 result.AppendErrorWithFormat("Failed to open file '%s' for %s:\n",
795 path.c_str(), append ? "append" : "write");
796
797 result.AppendError(llvm::toString(outfile.takeError()));
798 return false;
799 }
800 } else {
801 output_stream_p = &result.GetOutputStream();
802 }
803
805 if (compiler_type.GetOpaqueQualType()) {
806 for (uint32_t i = 0; i < item_count; ++i) {
807 addr_t item_addr = addr + (i * item_byte_size);
808 Address address(item_addr);
809 StreamString name_strm;
810 name_strm.Printf("0x%" PRIx64, item_addr);
811 ValueObjectSP valobj_sp(ValueObjectMemory::Create(
812 exe_scope, name_strm.GetString(), address, compiler_type));
813 if (valobj_sp) {
815 if (format != eFormatDefault)
816 valobj_sp->SetFormat(format);
817
820
821 valobj_sp->Dump(*output_stream_p, options);
822 } else {
824 "failed to create a value object for: (%s) %s\n",
825 view_as_type_cstr, name_strm.GetData());
826 return false;
827 }
828 }
829 return true;
830 }
831
833 DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
835 target->GetArchitecture().GetDataByteSize());
836
838 if (((format == eFormatChar) || (format == eFormatCharPrintable)) &&
839 (item_byte_size != 1)) {
840 // if a count was not passed, or it is 1
841 if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) {
842 // this turns requests such as
843 // memory read -fc -s10 -c1 *charPtrPtr
844 // which make no sense (what is a char of size 10?) into a request for
845 // fetching 10 chars of size 1 from the same memory location
846 format = eFormatCharArray;
847 item_count = item_byte_size;
848 item_byte_size = 1;
849 } else {
850 // here we passed a count, and it was not 1 so we have a byte_size and
851 // a count we could well multiply those, but instead let's just fail
853 "reading memory as characters of size %" PRIu64 " is not supported",
854 (uint64_t)item_byte_size);
855 return false;
856 }
857 }
858
859 assert(output_stream_p);
860 size_t bytes_dumped = DumpDataExtractor(
861 data, output_stream_p, 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_p->EOL();
866 return true;
867 }
868
883};
884
885#define LLDB_OPTIONS_memory_find
886#include "CommandOptions.inc"
887
888// Find the specified data in memory
890public:
892 public:
894
895 ~OptionGroupFindMemory() override = default;
896
897 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
898 return llvm::ArrayRef(g_memory_find_options);
899 }
900
901 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
902 ExecutionContext *execution_context) override {
904 const int short_option = g_memory_find_options[option_idx].short_option;
905
906 switch (short_option) {
907 case 'e':
908 m_expr.SetValueFromString(option_value);
909 break;
910
911 case 's':
912 m_string.SetValueFromString(option_value);
913 break;
914
915 case 'c':
916 if (m_count.SetValueFromString(option_value).Fail())
917 error.SetErrorString("unrecognized value for count");
918 break;
919
920 case 'o':
921 if (m_offset.SetValueFromString(option_value).Fail())
922 error.SetErrorString("unrecognized value for dump-offset");
923 break;
924
925 default:
926 llvm_unreachable("Unimplemented option");
927 }
928 return error;
929 }
930
931 void OptionParsingStarting(ExecutionContext *execution_context) override {
932 m_expr.Clear();
933 m_string.Clear();
934 m_count.Clear();
935 }
936
941 };
942
945 interpreter, "memory find",
946 "Find a value in the memory of the current target process.",
947 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
950 CommandArgumentData addr_arg;
951 CommandArgumentData value_arg;
952
953 // Define the first (and only) variant of this arg.
956
957 // There is only one variant this argument could be; put it into the
958 // argument entry.
959 arg1.push_back(addr_arg);
960
961 // Define the first (and only) variant of this arg.
964
965 // There is only one variant this argument could be; put it into the
966 // argument entry.
967 arg2.push_back(value_arg);
968
969 // Push the data for the first argument into the m_arguments vector.
970 m_arguments.push_back(arg1);
971 m_arguments.push_back(arg2);
972
977 }
978
979 ~CommandObjectMemoryFind() override = default;
980
981 Options *GetOptions() override { return &m_option_group; }
982
983protected:
985 public:
986 ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base)
987 : m_process_sp(process_sp), m_base_addr(base) {
988 lldbassert(process_sp.get() != nullptr);
989 }
990
991 bool IsValid() { return m_is_valid; }
992
993 uint8_t operator[](lldb::addr_t offset) {
994 if (!IsValid())
995 return 0;
996
997 uint8_t retval = 0;
999 if (0 ==
1000 m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) {
1001 m_is_valid = false;
1002 return 0;
1003 }
1004
1005 return retval;
1006 }
1007
1008 private:
1009 ProcessSP m_process_sp;
1011 bool m_is_valid = true;
1012 };
1013 bool DoExecute(Args &command, CommandReturnObject &result) override {
1014 // No need to check "process" for validity as eCommandRequiresProcess
1015 // ensures it is valid
1016 Process *process = m_exe_ctx.GetProcessPtr();
1017
1018 const size_t argc = command.GetArgumentCount();
1019
1020 if (argc != 2) {
1021 result.AppendError("two addresses needed for memory find");
1022 return false;
1023 }
1024
1025 Status error;
1027 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1028 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1029 result.AppendError("invalid low address");
1030 return false;
1031 }
1033 &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, &error);
1034 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1035 result.AppendError("invalid high address");
1036 return false;
1037 }
1038
1039 if (high_addr <= low_addr) {
1040 result.AppendError(
1041 "starting address must be smaller than ending address");
1042 return false;
1043 }
1044
1045 lldb::addr_t found_location = LLDB_INVALID_ADDRESS;
1046
1047 DataBufferHeap buffer;
1048
1050 llvm::StringRef str =
1051 m_memory_options.m_string.GetValueAs<llvm::StringRef>().value_or("");
1052 if (str.empty()) {
1053 result.AppendError("search string must have non-zero length.");
1054 return false;
1055 }
1056 buffer.CopyData(str);
1057 } else if (m_memory_options.m_expr.OptionWasSet()) {
1058 StackFrame *frame = m_exe_ctx.GetFramePtr();
1059 ValueObjectSP result_sp;
1060 if ((eExpressionCompleted ==
1061 process->GetTarget().EvaluateExpression(
1062 m_memory_options.m_expr.GetValueAs<llvm::StringRef>().value_or(
1063 ""),
1064 frame, result_sp)) &&
1065 result_sp) {
1066 uint64_t value = result_sp->GetValueAsUnsigned(0);
1067 std::optional<uint64_t> size =
1068 result_sp->GetCompilerType().GetByteSize(nullptr);
1069 if (!size)
1070 return false;
1071 switch (*size) {
1072 case 1: {
1073 uint8_t byte = (uint8_t)value;
1074 buffer.CopyData(&byte, 1);
1075 } break;
1076 case 2: {
1077 uint16_t word = (uint16_t)value;
1078 buffer.CopyData(&word, 2);
1079 } break;
1080 case 4: {
1081 uint32_t lword = (uint32_t)value;
1082 buffer.CopyData(&lword, 4);
1083 } break;
1084 case 8: {
1085 buffer.CopyData(&value, 8);
1086 } break;
1087 case 3:
1088 case 5:
1089 case 6:
1090 case 7:
1091 result.AppendError("unknown type. pass a string instead");
1092 return false;
1093 default:
1094 result.AppendError(
1095 "result size larger than 8 bytes. pass a string instead");
1096 return false;
1097 }
1098 } else {
1099 result.AppendError(
1100 "expression evaluation failed. pass a string instead");
1101 return false;
1102 }
1103 } else {
1104 result.AppendError(
1105 "please pass either a block of text, or an expression to evaluate.");
1106 return false;
1107 }
1108
1109 size_t count = m_memory_options.m_count.GetCurrentValue();
1110 found_location = low_addr;
1111 bool ever_found = false;
1112 while (count) {
1113 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(),
1114 buffer.GetByteSize());
1115 if (found_location == LLDB_INVALID_ADDRESS) {
1116 if (!ever_found) {
1117 result.AppendMessage("data not found within the range.\n");
1119 } else
1120 result.AppendMessage("no more matches within the range.\n");
1121 break;
1122 }
1123 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n",
1124 found_location);
1125
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,
1140 result.GetOutputStream().EOL();
1141 }
1142
1143 --count;
1144 found_location++;
1145 ever_found = true;
1146 }
1147
1149 return true;
1150 }
1151
1153 size_t buffer_size) {
1154 const size_t region_size = high - low;
1155
1156 if (region_size < buffer_size)
1157 return LLDB_INVALID_ADDRESS;
1158
1159 std::vector<size_t> bad_char_heuristic(256, buffer_size);
1160 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1161 ProcessMemoryIterator iterator(process_sp, low);
1162
1163 for (size_t idx = 0; idx < buffer_size - 1; idx++) {
1164 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx];
1165 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1;
1166 }
1167 for (size_t s = 0; s <= (region_size - buffer_size);) {
1168 int64_t j = buffer_size - 1;
1169 while (j >= 0 && buffer[j] == iterator[s + j])
1170 j--;
1171 if (j < 0)
1172 return low + s;
1173 else
1174 s += bad_char_heuristic[iterator[s + buffer_size - 1]];
1175 }
1176
1177 return LLDB_INVALID_ADDRESS;
1178 }
1179
1183};
1184
1185#define LLDB_OPTIONS_memory_write
1186#include "CommandOptions.inc"
1187
1188// Write memory to the inferior process
1190public:
1192 public:
1194
1195 ~OptionGroupWriteMemory() override = default;
1196
1197 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1198 return llvm::ArrayRef(g_memory_write_options);
1199 }
1200
1201 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1202 ExecutionContext *execution_context) override {
1203 Status error;
1204 const int short_option = g_memory_write_options[option_idx].short_option;
1205
1206 switch (short_option) {
1207 case 'i':
1208 m_infile.SetFile(option_value, FileSpec::Style::native);
1210 if (!FileSystem::Instance().Exists(m_infile)) {
1211 m_infile.Clear();
1212 error.SetErrorStringWithFormat("input file does not exist: '%s'",
1213 option_value.str().c_str());
1214 }
1215 break;
1216
1217 case 'o': {
1218 if (option_value.getAsInteger(0, m_infile_offset)) {
1219 m_infile_offset = 0;
1220 error.SetErrorStringWithFormat("invalid offset string '%s'",
1221 option_value.str().c_str());
1222 }
1223 } break;
1224
1225 default:
1226 llvm_unreachable("Unimplemented option");
1227 }
1228 return error;
1229 }
1230
1231 void OptionParsingStarting(ExecutionContext *execution_context) override {
1232 m_infile.Clear();
1233 m_infile_offset = 0;
1234 }
1235
1238 };
1239
1242 interpreter, "memory write",
1243 "Write to the memory of the current target process.", nullptr,
1244 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1247 {std::make_tuple(
1249 "The format to use for each of the value to be written."),
1250 std::make_tuple(eArgTypeByteSize,
1251 "The size in bytes to write from input file or "
1252 "each value.")}) {
1255 CommandArgumentData addr_arg;
1256 CommandArgumentData value_arg;
1257
1258 // Define the first (and only) variant of this arg.
1259 addr_arg.arg_type = eArgTypeAddress;
1260 addr_arg.arg_repetition = eArgRepeatPlain;
1261
1262 // There is only one variant this argument could be; put it into the
1263 // argument entry.
1264 arg1.push_back(addr_arg);
1265
1266 // Define the first (and only) variant of this arg.
1267 value_arg.arg_type = eArgTypeValue;
1268 value_arg.arg_repetition = eArgRepeatPlus;
1269 value_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1270
1271 // There is only one variant this argument could be; put it into the
1272 // argument entry.
1273 arg2.push_back(value_arg);
1274
1275 // Push the data for the first argument into the m_arguments vector.
1276 m_arguments.push_back(arg1);
1277 m_arguments.push_back(arg2);
1278
1287 }
1288
1289 ~CommandObjectMemoryWrite() override = default;
1290
1291 Options *GetOptions() override { return &m_option_group; }
1292
1293protected:
1294 bool DoExecute(Args &command, CommandReturnObject &result) override {
1295 // No need to check "process" for validity as eCommandRequiresProcess
1296 // ensures it is valid
1297 Process *process = m_exe_ctx.GetProcessPtr();
1298
1299 const size_t argc = command.GetArgumentCount();
1300
1302 if (argc < 1) {
1303 result.AppendErrorWithFormat(
1304 "%s takes a destination address when writing file contents.\n",
1305 m_cmd_name.c_str());
1306 return false;
1307 }
1308 if (argc > 1) {
1309 result.AppendErrorWithFormat(
1310 "%s takes only a destination address when writing file contents.\n",
1311 m_cmd_name.c_str());
1312 return false;
1313 }
1314 } else if (argc < 2) {
1315 result.AppendErrorWithFormat(
1316 "%s takes a destination address and at least one value.\n",
1317 m_cmd_name.c_str());
1318 return false;
1319 }
1320
1321 StreamString buffer(
1324 process->GetTarget().GetArchitecture().GetByteOrder());
1325
1327 size_t item_byte_size = byte_size_value.GetCurrentValue();
1328
1329 Status error;
1331 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1332
1333 if (addr == LLDB_INVALID_ADDRESS) {
1334 result.AppendError("invalid address expression\n");
1335 result.AppendError(error.AsCString());
1336 return false;
1337 }
1338
1340 size_t length = SIZE_MAX;
1341 if (item_byte_size > 1)
1342 length = item_byte_size;
1343 auto data_sp = FileSystem::Instance().CreateDataBuffer(
1346 if (data_sp) {
1347 length = data_sp->GetByteSize();
1348 if (length > 0) {
1349 Status error;
1350 size_t bytes_written =
1351 process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1352
1353 if (bytes_written == length) {
1354 // All bytes written
1355 result.GetOutputStream().Printf(
1356 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1357 (uint64_t)bytes_written, addr);
1359 } else if (bytes_written > 0) {
1360 // Some byte written
1361 result.GetOutputStream().Printf(
1362 "%" PRIu64 " bytes of %" PRIu64
1363 " requested were written to 0x%" PRIx64 "\n",
1364 (uint64_t)bytes_written, (uint64_t)length, addr);
1366 } else {
1367 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1368 " failed: %s.\n",
1369 addr, error.AsCString());
1370 }
1371 }
1372 } else {
1373 result.AppendErrorWithFormat("Unable to read contents of file.\n");
1374 }
1375 return result.Succeeded();
1376 } else if (item_byte_size == 0) {
1378 item_byte_size = buffer.GetAddressByteSize();
1379 else
1380 item_byte_size = 1;
1381 }
1382
1383 command.Shift(); // shift off the address argument
1384 uint64_t uval64;
1385 int64_t sval64;
1386 bool success = false;
1387 for (auto &entry : command) {
1388 switch (m_format_options.GetFormat()) {
1389 case kNumFormats:
1390 case eFormatFloat: // TODO: add support for floats soon
1393 case eFormatComplex:
1394 case eFormatEnum:
1395 case eFormatUnicode8:
1396 case eFormatUnicode16:
1397 case eFormatUnicode32:
1411 case eFormatOSType:
1413 case eFormatAddressInfo:
1414 case eFormatHexFloat:
1415 case eFormatInstruction:
1416 case eFormatVoid:
1417 result.AppendError("unsupported format for writing memory");
1418 return false;
1419
1420 case eFormatDefault:
1421 case eFormatBytes:
1422 case eFormatHex:
1424 case eFormatPointer: {
1425 // Decode hex bytes
1426 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1427 // have to special case that:
1428 bool success = false;
1429 if (entry.ref().startswith("0x"))
1430 success = !entry.ref().getAsInteger(0, uval64);
1431 if (!success)
1432 success = !entry.ref().getAsInteger(16, uval64);
1433 if (!success) {
1434 result.AppendErrorWithFormat(
1435 "'%s' is not a valid hex string value.\n", entry.c_str());
1436 return false;
1437 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1438 result.AppendErrorWithFormat("Value 0x%" PRIx64
1439 " is too large to fit in a %" PRIu64
1440 " byte unsigned integer value.\n",
1441 uval64, (uint64_t)item_byte_size);
1442 return false;
1443 }
1444 buffer.PutMaxHex64(uval64, item_byte_size);
1445 break;
1446 }
1447 case eFormatBoolean:
1448 uval64 = OptionArgParser::ToBoolean(entry.ref(), false, &success);
1449 if (!success) {
1450 result.AppendErrorWithFormat(
1451 "'%s' is not a valid boolean string value.\n", entry.c_str());
1452 return false;
1453 }
1454 buffer.PutMaxHex64(uval64, item_byte_size);
1455 break;
1456
1457 case eFormatBinary:
1458 if (entry.ref().getAsInteger(2, uval64)) {
1459 result.AppendErrorWithFormat(
1460 "'%s' is not a valid binary string value.\n", entry.c_str());
1461 return false;
1462 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1463 result.AppendErrorWithFormat("Value 0x%" PRIx64
1464 " is too large to fit in a %" PRIu64
1465 " byte unsigned integer value.\n",
1466 uval64, (uint64_t)item_byte_size);
1467 return false;
1468 }
1469 buffer.PutMaxHex64(uval64, item_byte_size);
1470 break;
1471
1472 case eFormatCharArray:
1473 case eFormatChar:
1474 case eFormatCString: {
1475 if (entry.ref().empty())
1476 break;
1477
1478 size_t len = entry.ref().size();
1479 // Include the NULL for C strings...
1481 ++len;
1482 Status error;
1483 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1484 addr += len;
1485 } else {
1486 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1487 " failed: %s.\n",
1488 addr, error.AsCString());
1489 return false;
1490 }
1491 break;
1492 }
1493 case eFormatDecimal:
1494 if (entry.ref().getAsInteger(0, sval64)) {
1495 result.AppendErrorWithFormat(
1496 "'%s' is not a valid signed decimal value.\n", entry.c_str());
1497 return false;
1498 } else if (!llvm::isIntN(item_byte_size * 8, sval64)) {
1499 result.AppendErrorWithFormat(
1500 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1501 " byte signed integer value.\n",
1502 sval64, (uint64_t)item_byte_size);
1503 return false;
1504 }
1505 buffer.PutMaxHex64(sval64, item_byte_size);
1506 break;
1507
1508 case eFormatUnsigned:
1509
1510 if (entry.ref().getAsInteger(0, uval64)) {
1511 result.AppendErrorWithFormat(
1512 "'%s' is not a valid unsigned decimal string value.\n",
1513 entry.c_str());
1514 return false;
1515 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1516 result.AppendErrorWithFormat("Value %" PRIu64
1517 " is too large to fit in a %" PRIu64
1518 " byte unsigned integer value.\n",
1519 uval64, (uint64_t)item_byte_size);
1520 return false;
1521 }
1522 buffer.PutMaxHex64(uval64, item_byte_size);
1523 break;
1524
1525 case eFormatOctal:
1526 if (entry.ref().getAsInteger(8, uval64)) {
1527 result.AppendErrorWithFormat(
1528 "'%s' is not a valid octal string value.\n", entry.c_str());
1529 return false;
1530 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1531 result.AppendErrorWithFormat("Value %" PRIo64
1532 " is too large to fit in a %" PRIu64
1533 " byte unsigned integer value.\n",
1534 uval64, (uint64_t)item_byte_size);
1535 return false;
1536 }
1537 buffer.PutMaxHex64(uval64, item_byte_size);
1538 break;
1539 }
1540 }
1541
1542 if (!buffer.GetString().empty()) {
1543 Status error;
1544 if (process->WriteMemory(addr, buffer.GetString().data(),
1545 buffer.GetString().size(),
1546 error) == buffer.GetString().size())
1547 return true;
1548 else {
1549 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1550 " failed: %s.\n",
1551 addr, error.AsCString());
1552 return false;
1553 }
1554 }
1555 return true;
1556 }
1557
1561};
1562
1563// Get malloc/free history of a memory address.
1565public:
1567 : CommandObjectParsed(interpreter, "memory history",
1568 "Print recorded stack traces for "
1569 "allocation/deallocation events "
1570 "associated with an address.",
1571 nullptr,
1572 eCommandRequiresTarget | eCommandRequiresProcess |
1573 eCommandProcessMustBePaused |
1574 eCommandProcessMustBeLaunched) {
1576 CommandArgumentData addr_arg;
1577
1578 // Define the first (and only) variant of this arg.
1579 addr_arg.arg_type = eArgTypeAddress;
1581
1582 // There is only one variant this argument could be; put it into the
1583 // argument entry.
1584 arg1.push_back(addr_arg);
1585
1586 // Push the data for the first argument into the m_arguments vector.
1587 m_arguments.push_back(arg1);
1588 }
1589
1590 ~CommandObjectMemoryHistory() override = default;
1591
1592 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
1593 uint32_t index) override {
1594 return m_cmd_name;
1595 }
1596
1597protected:
1598 bool DoExecute(Args &command, CommandReturnObject &result) override {
1599 const size_t argc = command.GetArgumentCount();
1600
1601 if (argc == 0 || argc > 1) {
1602 result.AppendErrorWithFormat("%s takes an address expression",
1603 m_cmd_name.c_str());
1604 return false;
1605 }
1606
1607 Status error;
1609 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1610
1611 if (addr == LLDB_INVALID_ADDRESS) {
1612 result.AppendError("invalid address expression");
1613 result.AppendError(error.AsCString());
1614 return false;
1615 }
1616
1617 Stream *output_stream = &result.GetOutputStream();
1618
1619 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1620 const MemoryHistorySP &memory_history =
1621 MemoryHistory::FindPlugin(process_sp);
1622
1623 if (!memory_history) {
1624 result.AppendError("no available memory history provider");
1625 return false;
1626 }
1627
1628 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1629
1630 const bool stop_format = false;
1631 for (auto thread : thread_list) {
1632 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
1633 }
1634
1636
1637 return true;
1638 }
1639};
1640
1641// CommandObjectMemoryRegion
1642#pragma mark CommandObjectMemoryRegion
1643
1644#define LLDB_OPTIONS_memory_region
1645#include "CommandOptions.inc"
1646
1648public:
1650 public:
1651 OptionGroupMemoryRegion() : m_all(false, false) {}
1652
1653 ~OptionGroupMemoryRegion() override = default;
1654
1655 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1656 return llvm::ArrayRef(g_memory_region_options);
1657 }
1658
1659 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1660 ExecutionContext *execution_context) override {
1661 Status status;
1662 const int short_option = g_memory_region_options[option_idx].short_option;
1663
1664 switch (short_option) {
1665 case 'a':
1666 m_all.SetCurrentValue(true);
1668 break;
1669 default:
1670 llvm_unreachable("Unimplemented option");
1671 }
1672
1673 return status;
1674 }
1675
1676 void OptionParsingStarting(ExecutionContext *execution_context) override {
1677 m_all.Clear();
1678 }
1679
1681 };
1682
1684 : CommandObjectParsed(interpreter, "memory region",
1685 "Get information on the memory region containing "
1686 "an address in the current target process.",
1687 "memory region <address-expression> (or --all)",
1688 eCommandRequiresProcess | eCommandTryTargetAPILock |
1689 eCommandProcessMustBeLaunched) {
1690 // Address in option set 1.
1693 // "--all" will go in option set 2.
1696 }
1697
1698 ~CommandObjectMemoryRegion() override = default;
1699
1700 Options *GetOptions() override { return &m_option_group; }
1701
1702protected:
1704 const MemoryRegionInfo &range_info, lldb::addr_t load_addr) {
1706 ConstString section_name;
1707 if (target.ResolveLoadAddress(load_addr, addr)) {
1708 SectionSP section_sp(addr.GetSection());
1709 if (section_sp) {
1710 // Got the top most section, not the deepest section
1711 while (section_sp->GetParent())
1712 section_sp = section_sp->GetParent();
1713 section_name = section_sp->GetName();
1714 }
1715 }
1716
1717 ConstString name = range_info.GetName();
1719 "[{0:x16}-{1:x16}) {2:r}{3:w}{4:x}{5}{6}{7}{8}",
1720 range_info.GetRange().GetRangeBase(),
1721 range_info.GetRange().GetRangeEnd(), range_info.GetReadable(),
1722 range_info.GetWritable(), range_info.GetExecutable(), name ? " " : "",
1723 name, section_name ? " " : "", section_name);
1724 MemoryRegionInfo::OptionalBool memory_tagged = range_info.GetMemoryTagged();
1725 if (memory_tagged == MemoryRegionInfo::OptionalBool::eYes)
1726 result.AppendMessage("memory tagging: enabled");
1727
1728 const std::optional<std::vector<addr_t>> &dirty_page_list =
1729 range_info.GetDirtyPageList();
1730 if (dirty_page_list) {
1731 const size_t page_count = dirty_page_list->size();
1733 "Modified memory (dirty) page list provided, %zu entries.\n",
1734 page_count);
1735 if (page_count > 0) {
1736 bool print_comma = false;
1737 result.AppendMessageWithFormat("Dirty pages: ");
1738 for (size_t i = 0; i < page_count; i++) {
1739 if (print_comma)
1740 result.AppendMessageWithFormat(", ");
1741 else
1742 print_comma = true;
1743 result.AppendMessageWithFormat("0x%" PRIx64, (*dirty_page_list)[i]);
1744 }
1745 result.AppendMessageWithFormat(".\n");
1746 }
1747 }
1748 }
1749
1750 bool DoExecute(Args &command, CommandReturnObject &result) override {
1751 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1752 if (!process_sp) {
1754 result.AppendError("invalid process");
1755 return false;
1756 }
1757
1758 Status error;
1759 lldb::addr_t load_addr = m_prev_end_addr;
1761
1762 const size_t argc = command.GetArgumentCount();
1763 const lldb::ABISP &abi = process_sp->GetABI();
1764
1765 if (argc == 1) {
1767 result.AppendError(
1768 "The \"--all\" option cannot be used when an address "
1769 "argument is given");
1770 return false;
1771 }
1772
1773 auto load_addr_str = command[0].ref();
1774 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1776 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1777 result.AppendErrorWithFormat("invalid address argument \"%s\": %s\n",
1778 command[0].c_str(), error.AsCString());
1779 return false;
1780 }
1781 } else if (argc > 1 ||
1782 // When we're repeating the command, the previous end address is
1783 // used for load_addr. If that was 0xF...F then we must have
1784 // reached the end of memory.
1785 (argc == 0 && !m_memory_region_options.m_all &&
1786 load_addr == LLDB_INVALID_ADDRESS) ||
1787 // If the target has non-address bits (tags, limited virtual
1788 // address size, etc.), the end of mappable memory will be lower
1789 // than that. So if we find any non-address bit set, we must be
1790 // at the end of the mappable range.
1791 (abi && (abi->FixAnyAddress(load_addr) != load_addr))) {
1792 result.AppendErrorWithFormat(
1793 "'%s' takes one argument or \"--all\" option:\nUsage: %s\n",
1794 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1795 return false;
1796 }
1797
1798 // Is is important that we track the address used to request the region as
1799 // this will give the correct section name in the case that regions overlap.
1800 // On Windows we get mutliple regions that start at the same place but are
1801 // different sizes and refer to different sections.
1802 std::vector<std::pair<lldb_private::MemoryRegionInfo, lldb::addr_t>>
1803 region_list;
1805 // We don't use GetMemoryRegions here because it doesn't include unmapped
1806 // areas like repeating the command would. So instead, emulate doing that.
1807 lldb::addr_t addr = 0;
1808 while (error.Success() && addr != LLDB_INVALID_ADDRESS &&
1809 // When there are non-address bits the last range will not extend
1810 // to LLDB_INVALID_ADDRESS but to the max virtual address.
1811 // This prevents us looping forever if that is the case.
1812 (!abi || (abi->FixAnyAddress(addr) == addr))) {
1814 error = process_sp->GetMemoryRegionInfo(addr, region_info);
1815
1816 if (error.Success()) {
1817 region_list.push_back({region_info, addr});
1818 addr = region_info.GetRange().GetRangeEnd();
1819 }
1820 }
1821 } else {
1823 error = process_sp->GetMemoryRegionInfo(load_addr, region_info);
1824 if (error.Success())
1825 region_list.push_back({region_info, load_addr});
1826 }
1827
1828 if (error.Success()) {
1829 for (std::pair<MemoryRegionInfo, addr_t> &range : region_list) {
1830 DumpRegion(result, process_sp->GetTarget(), range.first, range.second);
1831 m_prev_end_addr = range.first.GetRange().GetRangeEnd();
1832 }
1833
1835 return true;
1836 }
1837
1838 result.AppendErrorWithFormat("%s\n", error.AsCString());
1839 return false;
1840 }
1841
1842 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
1843 uint32_t index) override {
1844 // If we repeat this command, repeat it without any arguments so we can
1845 // show the next memory range
1846 return m_cmd_name;
1847 }
1848
1850
1853};
1854
1855// CommandObjectMemory
1856
1859 interpreter, "memory",
1860 "Commands for operating on memory in the current target process.",
1861 "memory <subcommand> [<subcommand-options>]") {
1862 LoadSubCommand("find",
1863 CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1864 LoadSubCommand("read",
1865 CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1866 LoadSubCommand("write",
1867 CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1868 LoadSubCommand("history",
1869 CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1870 LoadSubCommand("region",
1871 CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
1872 LoadSubCommand("tag",
1873 CommandObjectSP(new CommandObjectMemoryTag(interpreter)));
1874}
1875
#define ALL_KEYWORDS
static llvm::raw_ostream & error(Stream &strm)
#define lldbassert(x)
Definition: LLDBAssert.h:13
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base)
OptionGroupMemoryTag m_memory_tag_options
lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer, size_t buffer_size)
OptionGroupOptions m_option_group
Options * GetOptions() override
OptionGroupFindMemory m_memory_options
~CommandObjectMemoryFind() override=default
CommandObjectMemoryFind(CommandInterpreter &interpreter)
bool DoExecute(Args &command, CommandReturnObject &result) override
std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
~CommandObjectMemoryHistory() override=default
bool DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMemoryHistory(CommandInterpreter &interpreter)
Options * GetOptions() override
~CommandObjectMemoryRead() override=default
OptionGroupOptions m_option_group
OptionGroupMemoryTag m_memory_tag_options
OptionGroupOutputFile m_prev_outfile_options
OptionGroupValueObjectDisplay m_prev_varobj_options
OptionGroupValueObjectDisplay m_varobj_options
CommandObjectMemoryRead(CommandInterpreter &interpreter)
OptionGroupOutputFile m_outfile_options
OptionGroupReadMemory m_memory_options
OptionGroupFormat m_format_options
std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
bool DoExecute(Args &command, CommandReturnObject &result) override
OptionGroupMemoryTag m_prev_memory_tag_options
OptionGroupFormat m_prev_format_options
OptionGroupReadMemory m_prev_memory_options
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
bool DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMemoryRegion(CommandInterpreter &interpreter)
void DumpRegion(CommandReturnObject &result, Target &target, const MemoryRegionInfo &range_info, lldb::addr_t load_addr)
OptionGroupMemoryRegion m_memory_region_options
std::optional< std::string > GetRepeatCommand(Args &current_command_args, uint32_t index) override
Get the command that appropriate for a "repeat" of the current command.
~CommandObjectMemoryRegion() override=default
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
bool DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMemoryWrite(CommandInterpreter &interpreter)
OptionGroupWriteMemory m_memory_options
Options * GetOptions() override
~CommandObjectMemoryWrite() override=default
Status FinalizeSettings(Target *target, OptionGroupFormat &format_options)
OptionValueUInt64 m_num_per_line
OptionValueString m_view_as_type
void OptionParsingStarting(ExecutionContext *execution_context) override
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
~OptionGroupReadMemory() override=default
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
OptionValueLanguage m_language_for_type
A section + offset based address class.
Definition: Address.h:59
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition: Address.h:429
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:691
uint32_t GetDataByteSize() const
Architecture data byte width accessor.
Definition: ArchSpec.cpp:675
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition: ArchSpec.cpp:738
uint32_t GetMaximumOpcodeByteSize() const
Definition: ArchSpec.cpp:934
A command line argument class.
Definition: Args.h:33
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition: Args.cpp:285
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:116
CommandObjectMemory(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
std::vector< CommandArgumentData > CommandArgumentEntry
ExecutionContext m_exe_ctx
std::vector< CommandArgumentEntry > m_arguments
void AppendMessage(llvm::StringRef in_string)
void void AppendError(llvm::StringRef in_string)
void AppendWarningWithFormat(const char *format,...) __attribute__((format(printf
void SetStatus(lldb::ReturnStatus status)
void void AppendMessageWithFormatv(const char *format, Args &&... args)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void AppendMessageWithFormat(const char *format,...) __attribute__((format(printf
void void AppendWarning(llvm::StringRef in_string)
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
std::optional< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
Definition: CompilerType.h:234
A uniqued constant string class.
Definition: ConstString.h:39
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:218
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
void CopyData(const void *src, lldb::offset_t src_len)
Makes a copy of the src_len bytes in src.
An data extractor class.
Definition: DataExtractor.h:48
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
A file utility class.
Definition: FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:173
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:366
void Clear()
Clears the object state.
Definition: FileSpec.cpp:258
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
int Open(const char *path, int flags, int mode)
Wraps ::open in a platform-independent way.
static FileSystem & Instance()
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
@ eOpenOptionWriteOnly
Definition: File.h:52
@ eOpenOptionAppend
Definition: File.h:54
@ eOpenOptionCanCreate
Definition: File.h:56
@ eOpenOptionTruncate
Definition: File.h:57
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition: Language.cpp:380
static lldb::MemoryHistorySP FindPlugin(const lldb::ProcessSP process)
OptionalBool GetWritable() const
OptionalBool GetMemoryTagged() const
const std::optional< std::vector< lldb::addr_t > > & GetDirtyPageList() const
Get a vector of target VM pages that are dirty – that have been modified – within this memory region.
OptionalBool GetReadable() const
OptionalBool GetExecutable() const
void FindTypes(Module *search_first, ConstString name, bool name_is_fully_qualified, size_t max_matches, llvm::DenseSet< SymbolFile * > &searched_symbol_files, TypeList &types) const
Find types by name.
Definition: ModuleList.cpp:561
static const uint32_t OPTION_GROUP_GDB_FMT
OptionValueUInt64 & GetByteSizeValue()
static const uint32_t OPTION_GROUP_FORMAT
static const uint32_t OPTION_GROUP_COUNT
static const uint32_t OPTION_GROUP_SIZE
OptionValueFormat & GetFormatValue()
OptionValueUInt64 & GetCountValue()
void Append(OptionGroup *group)
Append options from a OptionGroup class.
Definition: Options.cpp:755
const OptionValueFileSpec & GetFile()
const OptionValueBoolean & GetAppend()
DumpValueObjectOptions GetAsDumpOptions(LanguageRuntimeDescriptionDisplayVerbosity lang_descr_verbosity=eLanguageRuntimeDescriptionDisplayVerbosityFull, lldb::Format format=lldb::eFormatDefault, lldb::TypeSummaryImplSP summary_sp=lldb::TypeSummaryImplSP())
void SetCurrentValue(lldb::Format value)
lldb::Format GetCurrentValue() const
lldb::LanguageType GetCurrentValue() const
Status SetValueFromString(llvm::StringRef value, VarSetOperationType op=eVarSetOperationAssign) override
Status SetValueFromString(llvm::StringRef value, VarSetOperationType op=eVarSetOperationAssign) override
const char * GetCurrentValue() const
Status SetValueFromString(llvm::StringRef value, VarSetOperationType op=eVarSetOperationAssign) override
std::optional< T > GetValueAs() const
Definition: OptionValue.h:269
A command line option parsing protocol class.
Definition: Options.h:58
A plug-in interface definition class for debugging a process.
Definition: Process.h:333
virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition: Process.cpp:1929
lldb::ByteOrder GetByteOrder() const
Definition: Process.cpp:3388
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3392
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition: Process.cpp:2128
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1222
This base class provides an interface to stack frames.
Definition: StackFrame.h:41
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
Definition: StackFrame.cpp:300
An error handling class.
Definition: Status.h:44
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
const char * GetData() const
Definition: StreamString.h:43
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
uint32_t GetAddressByteSize() const
Get the address size in bytes.
Definition: Stream.cpp:179
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:128
@ eBinary
Get and put data as binary instead of as the default string mode.
Definition: Stream.h:32
size_t PutMaxHex64(uint64_t uvalue, size_t byte_size, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition: Stream.cpp:288
lldb::ModuleSP module_sp
The Module for a given query.
uint32_t GetMaximumSizeOfStringSummary() const
Definition: Target.cpp:4504
uint32_t GetMaximumMemReadSize() const
Definition: Target.cpp:4510
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2406
size_t ReadMemory(const Address &addr, void *dst, size_t dst_len, Status &error, bool force_live_memory=false, lldb::addr_t *load_addr_ptr=nullptr)
Definition: Target.cpp:1782
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition: Target.cpp:1903
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow)
Definition: Target.cpp:3009
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:954
const ArchSpec & GetArchitecture() const
Definition: Target.h:996
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Definition: Target.cpp:2553
uint32_t GetSize() const
Definition: TypeList.cpp:60
lldb::TypeSP GetTypeAtIndex(uint32_t idx)
Definition: TypeList.cpp:66
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, llvm::StringRef name, const Address &address, lldb::TypeSP &type_sp)
#define LLDB_OPT_SET_1
Definition: lldb-defines.h:102
#define UINT64_MAX
Definition: lldb-defines.h:23
#define LLDB_OPT_SET_2
Definition: lldb-defines.h:103
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:101
#define LLDB_OPT_SET_3
Definition: lldb-defines.h:104
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:74
#define UINT32_MAX
Definition: lldb-defines.h:19
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
std::vector< lldb::ThreadSP > HistoryThreads
Definition: MemoryHistory.h:21
lldb::offset_t DumpDataExtractor(const DataExtractor &DE, Stream *s, lldb::offset_t offset, lldb::Format item_format, size_t item_byte_size, size_t item_count, size_t num_per_line, uint64_t base_addr, uint32_t item_bit_size, uint32_t item_bit_offset, ExecutionContextScope *exe_scope=nullptr, bool show_memory_tags=false)
Dumps item_count objects into the stream s.
Definition: SBAddress.h:15
Format
Display format definitions.
@ eFormatCString
NULL terminated C strings.
@ eFormatCharArray
Print characters with no single quotes, used for character arrays that can contain non printable char...
@ eFormatInstruction
Disassemble an opcode.
@ eFormatVectorOfChar
@ eFormatVectorOfUInt64
@ eFormatVoid
Do not print this.
@ eFormatVectorOfFloat16
@ eFormatVectorOfSInt64
@ eFormatComplex
Floating point complex type.
@ eFormatHexFloat
ISO C99 hex float string.
@ eFormatBytesWithASCII
@ eFormatOSType
OS character codes encoded into an integer 'PICT' 'text' etc...
@ eFormatUnicode16
@ eFormatAddressInfo
Describe what an address points to (func + offset.
@ eFormatVectorOfUInt128
@ eFormatVectorOfUInt8
@ eFormatVectorOfFloat32
@ eFormatVectorOfSInt32
@ eFormatUnicode32
@ eFormatVectorOfSInt8
@ eFormatVectorOfUInt16
@ eFormatHexUppercase
@ eFormatVectorOfFloat64
@ eFormatCharPrintable
Only printable characters, '.' if not printable.
@ eFormatComplexInteger
Integer complex type.
@ eFormatVectorOfSInt16
@ eFormatVectorOfUInt32
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eExpressionCompleted
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeByteSize
@ eArgTypeAddressOrExpression
uint64_t addr_t
Definition: lldb-types.h:79
Used to build individual command argument lists.
Definition: CommandObject.h:93
static lldb::addr_t ToAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
Try to parse an address.
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)
BaseType GetRangeBase() const
Definition: RangeMap.h:45
BaseType GetRangeEnd() const
Definition: RangeMap.h:78