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"
27#include "lldb/Target/ABI.h"
31#include "lldb/Target/Process.h"
33#include "lldb/Target/Target.h"
34#include "lldb/Target/Thread.h"
35#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:
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':
69 error = m_num_per_line.SetValueFromString(option_value);
70 if (m_num_per_line.GetCurrentValue() == 0)
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':
81 error = m_view_as_type.SetValueFromString(option_value);
82 break;
83
84 case 'r':
85 m_force = true;
86 break;
87
88 case 'x':
89 error = m_language_for_type.SetValueFromString(option_value);
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 {
103 m_num_per_line.Clear();
104 m_output_as_binary = false;
105 m_view_as_type.Clear();
106 m_force = false;
107 m_offset.Clear();
108 m_language_for_type.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 eFormatFloat128:
160 case eFormatOctal:
161 case eFormatDecimal:
162 case eFormatEnum:
163 case eFormatUnicode8:
164 case eFormatUnicode16:
165 case eFormatUnicode32:
166 case eFormatUnsigned:
167 case eFormatHexFloat:
168 if (!byte_size_option_set)
169 byte_size_value = 4;
170 if (!num_per_line_option_set)
171 m_num_per_line = 1;
172 if (!count_option_set)
173 format_options.GetCountValue() = 8;
174 break;
175
176 case eFormatBytes:
178 if (byte_size_option_set) {
179 if (byte_size_value > 1)
181 "display format (bytes/bytes with ASCII) conflicts with the "
182 "specified byte size %" PRIu64 "\n"
183 "\tconsider using a different display format or don't specify "
184 "the byte size.",
185 byte_size_value.GetCurrentValue());
186 } else
187 byte_size_value = 1;
188 if (!num_per_line_option_set)
189 m_num_per_line = 16;
190 if (!count_option_set)
191 format_options.GetCountValue() = 32;
192 break;
193
194 case eFormatCharArray:
195 case eFormatChar:
197 if (!byte_size_option_set)
198 byte_size_value = 1;
199 if (!num_per_line_option_set)
200 m_num_per_line = 32;
201 if (!count_option_set)
202 format_options.GetCountValue() = 64;
203 break;
204
205 case eFormatComplex:
206 if (!byte_size_option_set)
207 byte_size_value = 8;
208 if (!num_per_line_option_set)
209 m_num_per_line = 1;
210 if (!count_option_set)
211 format_options.GetCountValue() = 8;
212 break;
213
215 if (!byte_size_option_set)
216 byte_size_value = 8;
217 if (!num_per_line_option_set)
218 m_num_per_line = 1;
219 if (!count_option_set)
220 format_options.GetCountValue() = 8;
221 break;
222
223 case eFormatHex:
224 if (!byte_size_option_set)
225 byte_size_value = 4;
226 if (!num_per_line_option_set) {
227 switch (byte_size_value) {
228 case 1:
229 case 2:
230 m_num_per_line = 8;
231 break;
232 case 4:
233 m_num_per_line = 4;
234 break;
235 case 8:
236 m_num_per_line = 2;
237 break;
238 default:
239 m_num_per_line = 1;
240 break;
241 }
242 }
243 if (!count_option_set)
244 count_value = 8;
245 break;
246
260 if (!byte_size_option_set)
261 byte_size_value = 128;
262 if (!num_per_line_option_set)
263 m_num_per_line = 1;
264 if (!count_option_set)
265 count_value = 4;
266 break;
267 }
268 return error;
269 }
270
271 bool AnyOptionWasSet() const {
272 return m_num_per_line.OptionWasSet() || m_output_as_binary ||
273 m_view_as_type.OptionWasSet() || m_offset.OptionWasSet() ||
274 m_language_for_type.OptionWasSet();
275 }
276
278 bool m_output_as_binary = false;
280 bool m_force = false;
283};
284
285// Read memory from the inferior process
287public:
290 interpreter, "memory read",
291 "Read from the memory of the current target process.", nullptr,
292 eCommandRequiresTarget | eCommandProcessMustBePaused),
294 m_memory_tag_options(/*note_binary=*/true),
298 CommandArgumentData start_addr_arg;
299 CommandArgumentData end_addr_arg;
300
301 // Define the first (and only) variant of this arg.
302 start_addr_arg.arg_type = eArgTypeAddressOrExpression;
303 start_addr_arg.arg_repetition = eArgRepeatPlain;
304
305 // There is only one variant this argument could be; put it into the
306 // argument entry.
307 arg1.push_back(start_addr_arg);
308
309 // Define the first (and only) variant of this arg.
311 end_addr_arg.arg_repetition = eArgRepeatOptional;
312
313 // There is only one variant this argument could be; put it into the
314 // argument entry.
315 arg2.push_back(end_addr_arg);
316
317 // Push the data for the first argument into the m_arguments vector.
318 m_arguments.push_back(arg1);
319 m_arguments.push_back(arg2);
320
321 // Add the "--format" and "--count" options to group 1 and 3
329 // Add the "--size" option to group 1 and 2
339 m_option_group.Finalize();
340 }
341
342 ~CommandObjectMemoryRead() override = default;
343
344 Options *GetOptions() override { return &m_option_group; }
345
346 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
347 uint32_t index) override {
348 return m_cmd_name;
349 }
350
351protected:
352 void DoExecute(Args &command, CommandReturnObject &result) override {
353 // No need to check "target" for validity as eCommandRequiresTarget ensures
354 // it is valid
355 Target *target = m_exe_ctx.GetTargetPtr();
356
357 const size_t argc = command.GetArgumentCount();
358
359 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
360 result.AppendErrorWithFormat("%s takes a start address expression with "
361 "an optional end address expression.\n",
362 m_cmd_name.c_str());
363 result.AppendWarning("expressions should be quoted if they contain "
364 "spaces or other special characters");
365 return;
366 }
367
368 ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
369
370 CompilerType compiler_type;
372
373 const char *view_as_type_cstr =
374 m_memory_options.m_view_as_type.GetCurrentValue();
375 if (view_as_type_cstr && view_as_type_cstr[0]) {
376 // We are viewing memory as a type
377
378 uint32_t reference_count = 0;
379 uint32_t pointer_count = 0;
380 size_t idx;
381
382#define ALL_KEYWORDS \
383 KEYWORD("const") \
384 KEYWORD("volatile") \
385 KEYWORD("restrict") \
386 KEYWORD("struct") \
387 KEYWORD("class") \
388 KEYWORD("union")
389
390#define KEYWORD(s) s,
391 static const char *g_keywords[] = {ALL_KEYWORDS};
392#undef KEYWORD
393
394#define KEYWORD(s) (sizeof(s) - 1),
395 static const int g_keyword_lengths[] = {ALL_KEYWORDS};
396#undef KEYWORD
397
398#undef ALL_KEYWORDS
399
400 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
401 std::string type_str(view_as_type_cstr);
402
403 // Remove all instances of g_keywords that are followed by spaces
404 for (size_t i = 0; i < g_num_keywords; ++i) {
405 const char *keyword = g_keywords[i];
406 int keyword_len = g_keyword_lengths[i];
407
408 idx = 0;
409 while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
410 if (type_str[idx + keyword_len] == ' ' ||
411 type_str[idx + keyword_len] == '\t') {
412 type_str.erase(idx, keyword_len + 1);
413 idx = 0;
414 } else {
415 idx += keyword_len;
416 }
417 }
418 }
419 bool done = type_str.empty();
420 //
421 idx = type_str.find_first_not_of(" \t");
422 if (idx > 0 && idx != std::string::npos)
423 type_str.erase(0, idx);
424 while (!done) {
425 // Strip trailing spaces
426 if (type_str.empty())
427 done = true;
428 else {
429 switch (type_str[type_str.size() - 1]) {
430 case '*':
431 ++pointer_count;
432 [[fallthrough]];
433 case ' ':
434 case '\t':
435 type_str.erase(type_str.size() - 1);
436 break;
437
438 case '&':
439 if (reference_count == 0) {
440 reference_count = 1;
441 type_str.erase(type_str.size() - 1);
442 } else {
443 result.AppendErrorWithFormat("invalid type string: '%s'\n",
444 view_as_type_cstr);
445 return;
446 }
447 break;
448
449 default:
450 done = true;
451 break;
452 }
453 }
454 }
455
456 ConstString lookup_type_name(type_str.c_str());
457 StackFrame *frame = m_exe_ctx.GetFramePtr();
458 ModuleSP search_first;
459 if (frame)
460 search_first = frame->GetSymbolContext(eSymbolContextModule).module_sp;
461 TypeQuery query(lookup_type_name.GetStringRef(),
462 TypeQueryOptions::e_find_one);
463 TypeResults results;
464 target->GetImages().FindTypes(search_first.get(), query, results);
465 TypeSP type_sp = results.GetFirstType();
466
467 if (!type_sp && lookup_type_name.GetCString()) {
468 LanguageType language_for_type =
469 m_memory_options.m_language_for_type.GetCurrentValue();
470 std::set<LanguageType> languages_to_check;
471 if (language_for_type != eLanguageTypeUnknown) {
472 languages_to_check.insert(language_for_type);
473 } else {
474 languages_to_check = Language::GetSupportedLanguages();
475 }
476
477 std::set<CompilerType> user_defined_types;
478 for (auto lang : languages_to_check) {
479 if (auto *persistent_vars =
481 if (std::optional<CompilerType> type =
482 persistent_vars->GetCompilerTypeFromPersistentDecl(
483 lookup_type_name)) {
484 user_defined_types.emplace(*type);
485 }
486 }
487 }
488
489 if (user_defined_types.size() > 1) {
491 "Mutiple types found matching raw type '%s', please disambiguate "
492 "by specifying the language with -x",
493 lookup_type_name.GetCString());
494 return;
495 }
496
497 if (user_defined_types.size() == 1) {
498 compiler_type = *user_defined_types.begin();
499 }
500 }
501
502 if (!compiler_type.IsValid()) {
503 if (type_sp) {
504 compiler_type = type_sp->GetFullCompilerType();
505 } else {
506 result.AppendErrorWithFormat("unable to find any types that match "
507 "the raw type '%s' for full type '%s'\n",
508 lookup_type_name.GetCString(),
509 view_as_type_cstr);
510 return;
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;
521 }
522 --pointer_count;
523 }
524
525 auto size_or_err = compiler_type.GetByteSize(exe_scope);
526 if (!size_or_err) {
528 "unable to get the byte size of the type '%s'\n%s",
529 view_as_type_cstr, llvm::toString(size_or_err.takeError()).c_str());
530 return;
531 }
532 m_format_options.GetByteSizeValue() = *size_or_err;
533
534 if (!m_format_options.GetCountValue().OptionWasSet())
535 m_format_options.GetCountValue() = 1;
536 } else {
537 error = m_memory_options.FinalizeSettings(target, m_format_options);
538 }
539
540 // Look for invalid combinations of settings
541 if (error.Fail()) {
542 result.AppendError(error.AsCString());
543 return;
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;
554 if (!m_format_options.AnyOptionWasSet() &&
555 !m_memory_options.AnyOptionWasSet() &&
556 !m_outfile_options.AnyOptionWasSet() &&
557 !m_varobj_options.AnyOptionWasSet() &&
558 !m_memory_tag_options.AnyOptionWasSet()) {
564 }
565 }
566
567 size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
568 size_t item_byte_size =
569 m_format_options.GetByteSizeValue().GetCurrentValue();
570 const size_t num_per_line =
571 m_memory_options.m_num_per_line.GetCurrentValue();
572
573 if (total_byte_size == 0) {
574 total_byte_size = item_count * item_byte_size;
575 if (total_byte_size == 0)
576 total_byte_size = 32;
577 }
578
579 if (argc > 0)
580 addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref(),
582
583 if (addr == LLDB_INVALID_ADDRESS) {
584 result.AppendError("invalid start address expression.");
585 result.AppendError(error.AsCString());
586 return;
587 }
588
589 if (argc == 2) {
591 &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, nullptr);
592
593 if (end_addr == LLDB_INVALID_ADDRESS) {
594 result.AppendError("invalid end address expression.");
595 result.AppendError(error.AsCString());
596 return;
597 } else if (end_addr <= addr) {
599 "end address (0x%" PRIx64
600 ") must be greater than the start address (0x%" PRIx64 ").\n",
601 end_addr, addr);
602 return;
603 } else if (m_format_options.GetCountValue().OptionWasSet()) {
605 "specify either the end address (0x%" PRIx64
606 ") or the count (--count %" PRIu64 "), not both.\n",
607 end_addr, (uint64_t)item_count);
608 return;
609 }
610
611 total_byte_size = end_addr - addr;
612 item_count = total_byte_size / item_byte_size;
613 }
614
615 uint32_t max_unforced_size = target->GetMaximumMemReadSize();
616
617 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
619 "Normally, \'memory read\' will not read over %" PRIu32
620 " bytes of data.\n",
621 max_unforced_size);
623 "Please use --force to override this restriction just once.\n");
624 result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
625 "will often need a larger limit.\n");
626 return;
627 }
628
629 WritableDataBufferSP data_sp;
630 size_t bytes_read = 0;
631 if (compiler_type.GetOpaqueQualType()) {
632 // Make sure we don't display our type as ASCII bytes like the default
633 // memory read
634 if (!m_format_options.GetFormatValue().OptionWasSet())
635 m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
636
637 auto size_or_err = compiler_type.GetByteSize(exe_scope);
638 if (!size_or_err) {
639 result.AppendError(llvm::toString(size_or_err.takeError()));
640 return;
641 }
642 auto size = *size_or_err;
643 bytes_read = size * m_format_options.GetCountValue().GetCurrentValue();
644
645 if (argc > 0)
646 addr = addr + (size * m_memory_options.m_offset.GetCurrentValue());
647 } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
649 data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0');
650 if (data_sp->GetBytes() == nullptr) {
652 "can't allocate 0x%" PRIx32
653 " bytes for the memory read buffer, specify a smaller size to read",
654 (uint32_t)total_byte_size);
655 return;
656 }
657
658 Address address(addr);
659 bytes_read = target->ReadMemory(address, data_sp->GetBytes(),
660 data_sp->GetByteSize(), error, true);
661 if (bytes_read == 0) {
662 const char *error_cstr = error.AsCString();
663 if (error_cstr && error_cstr[0]) {
664 result.AppendError(error_cstr);
665 } else {
667 "failed to read memory from 0x%" PRIx64 ".\n", addr);
668 }
669 return;
670 }
671
672 if (bytes_read < total_byte_size)
673 result.AppendWarningWithFormatv("not all bytes ({0} / {1}) "
674 "were able to be read from {2:x}",
675 bytes_read, total_byte_size, addr);
676 } else {
677 // we treat c-strings as a special case because they do not have a fixed
678 // size
679 if (m_format_options.GetByteSizeValue().OptionWasSet() &&
680 !m_format_options.HasGDBFormat())
681 item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
682 else
683 item_byte_size = target->GetMaximumSizeOfStringSummary();
684 if (!m_format_options.GetCountValue().OptionWasSet())
685 item_count = 1;
686 data_sp = std::make_shared<DataBufferHeap>(
687 (item_byte_size + 1) * item_count,
688 '\0'); // account for NULLs as necessary
689 if (data_sp->GetBytes() == nullptr) {
691 "can't allocate 0x%" PRIx64
692 " bytes for the memory read buffer, specify a smaller size to read",
693 (uint64_t)((item_byte_size + 1) * item_count));
694 return;
695 }
696 uint8_t *data_ptr = data_sp->GetBytes();
697 auto data_addr = addr;
698 auto count = item_count;
699 item_count = 0;
700 bool break_on_no_NULL = false;
701 while (item_count < count) {
702 std::string buffer;
703 buffer.resize(item_byte_size + 1, 0);
705 size_t read = target->ReadCStringFromMemory(
706 Address(data_addr), &buffer[0], item_byte_size + 1, error);
707 if (error.Fail()) {
709 "failed to read memory from 0x%" PRIx64 ".\n", addr);
710 return;
711 }
712
713 if (item_byte_size == read) {
715 "unable to find a NULL terminated string at {0:x}"
716 ". Consider increasing the maximum read length",
717 data_addr);
718 --read;
719 break_on_no_NULL = true;
720 } else
721 ++read; // account for final NULL byte
722
723 memcpy(data_ptr, &buffer[0], read);
724 data_ptr += read;
725 data_addr += read;
726 bytes_read += read;
727 item_count++; // if we break early we know we only read item_count
728 // strings
729
730 if (break_on_no_NULL)
731 break;
732 }
733 data_sp =
734 std::make_shared<DataBufferHeap>(data_sp->GetBytes(), bytes_read + 1);
735 }
736
737 m_next_addr = addr + bytes_read;
738 m_prev_byte_size = bytes_read;
744 m_prev_compiler_type = compiler_type;
745
746 std::unique_ptr<Stream> output_stream_storage;
747 Stream *output_stream_p = nullptr;
748 const FileSpec &outfile_spec =
749 m_outfile_options.GetFile().GetCurrentValue();
750
751 std::string path = outfile_spec.GetPath();
752 if (outfile_spec) {
753
754 File::OpenOptions open_options =
756 const bool append = m_outfile_options.GetAppend().GetCurrentValue();
757 open_options |=
759
760 auto outfile = FileSystem::Instance().Open(outfile_spec, open_options);
761
762 if (outfile) {
763 auto outfile_stream_up =
764 std::make_unique<StreamFile>(std::move(outfile.get()));
765 if (m_memory_options.m_output_as_binary) {
766 const size_t bytes_written =
767 outfile_stream_up->Write(data_sp->GetBytes(), bytes_read);
768 if (bytes_written > 0) {
769 result.GetOutputStream().Printf(
770 "%zi bytes %s to '%s'\n", bytes_written,
771 append ? "appended" : "written", path.c_str());
772 return;
773 } else {
774 result.AppendErrorWithFormat("Failed to write %" PRIu64
775 " bytes to '%s'.\n",
776 (uint64_t)bytes_read, path.c_str());
777 return;
778 }
779 } else {
780 // We are going to write ASCII to the file just point the
781 // output_stream to our outfile_stream...
782 output_stream_storage = std::move(outfile_stream_up);
783 output_stream_p = output_stream_storage.get();
784 }
785 } else {
786 result.AppendErrorWithFormat("Failed to open file '%s' for %s:\n",
787 path.c_str(), append ? "append" : "write");
788
789 result.AppendError(llvm::toString(outfile.takeError()));
790 return;
791 }
792 } else {
793 output_stream_p = &result.GetOutputStream();
794 }
795
796 if (compiler_type.GetOpaqueQualType()) {
797 for (uint32_t i = 0; i < item_count; ++i) {
798 addr_t item_addr = addr + (i * item_byte_size);
799 Address address(item_addr);
800 StreamString name_strm;
801 name_strm.Printf("0x%" PRIx64, item_addr);
803 exe_scope, name_strm.GetString(), address, compiler_type));
804 if (valobj_sp) {
805 Format format = m_format_options.GetFormat();
806 if (format != eFormatDefault)
807 valobj_sp->SetFormat(format);
808
809 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
811
812 if (llvm::Error error = valobj_sp->Dump(*output_stream_p, options)) {
813 result.AppendError(toString(std::move(error)));
814 return;
815 }
816 } else {
818 "failed to create a value object for: (%s) %s\n",
819 view_as_type_cstr, name_strm.GetData());
820 return;
821 }
822 }
823 return;
824 }
825
827 DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
829
830 Format format = m_format_options.GetFormat();
831 if (((format == eFormatChar) || (format == eFormatCharPrintable)) &&
832 (item_byte_size != 1)) {
833 // if a count was not passed, or it is 1
834 if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) {
835 // this turns requests such as
836 // memory read -fc -s10 -c1 *charPtrPtr
837 // which make no sense (what is a char of size 10?) into a request for
838 // fetching 10 chars of size 1 from the same memory location
839 format = eFormatCharArray;
840 item_count = item_byte_size;
841 item_byte_size = 1;
842 } else {
843 // here we passed a count, and it was not 1 so we have a byte_size and
844 // a count we could well multiply those, but instead let's just fail
846 "reading memory as characters of size %" PRIu64 " is not supported",
847 (uint64_t)item_byte_size);
848 return;
849 }
850 }
851
852 assert(output_stream_p);
853 size_t bytes_dumped =
854 DumpDataExtractor(data, output_stream_p, 0, format, item_byte_size,
855 item_count, num_per_line, addr, 0, 0, exe_scope,
856 m_memory_tag_options.GetShowTags().GetCurrentValue());
857 m_next_addr = addr + bytes_dumped;
858 output_stream_p->EOL();
859 }
860
875};
876
877#define LLDB_OPTIONS_memory_find
878#include "CommandOptions.inc"
879
880static llvm::Error CopyExpressionResult(ValueObject &result,
881 DataBufferHeap &buffer,
882 ExecutionContextScope *scope) {
883 uint64_t value = result.GetValueAsUnsigned(0);
884 auto size_or_err = result.GetCompilerType().GetByteSize(scope);
885 if (!size_or_err)
886 return size_or_err.takeError();
887
888 switch (*size_or_err) {
889 case 1: {
890 uint8_t byte = (uint8_t)value;
891 buffer.CopyData(&byte, 1);
892 } break;
893 case 2: {
894 uint16_t word = (uint16_t)value;
895 buffer.CopyData(&word, 2);
896 } break;
897 case 4: {
898 uint32_t lword = (uint32_t)value;
899 buffer.CopyData(&lword, 4);
900 } break;
901 case 8: {
902 buffer.CopyData(&value, 8);
903 } break;
904 default:
905 return llvm::createStringError(
906 "Only expressions resulting in 1, 2, 4, or 8-byte-sized values are "
907 "supported. For other pattern sizes the --string (-s) option may be "
908 "used.");
909 }
910
911 return llvm::Error::success();
912}
913
914static llvm::Expected<ValueObjectSP>
915EvaluateExpression(llvm::StringRef expression, StackFrame &frame,
916 Process &process) {
917 ValueObjectSP result_sp;
918 auto status =
919 process.GetTarget().EvaluateExpression(expression, &frame, result_sp);
920 if (!result_sp)
921 return llvm::createStringError(
922 "No result returned from expression. Exit status: %d", status);
923
924 if (status != eExpressionCompleted)
925 return result_sp->GetError().ToError();
926
927 result_sp = result_sp->GetQualifiedRepresentationIfAvailable(
928 result_sp->GetDynamicValueType(), /*synthValue=*/true);
929 if (!result_sp)
930 return llvm::createStringError("failed to get dynamic result type");
931
932 return result_sp;
933}
934
935// Find the specified data in memory
937public:
939 public:
941
942 ~OptionGroupFindMemory() override = default;
943
944 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
945 return llvm::ArrayRef(g_memory_find_options);
946 }
947
948 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
949 ExecutionContext *execution_context) override {
951 const int short_option = g_memory_find_options[option_idx].short_option;
952
953 switch (short_option) {
954 case 'e':
955 m_expr.SetValueFromString(option_value);
956 break;
957
958 case 's':
959 m_string.SetValueFromString(option_value);
960 break;
961
962 case 'c':
963 if (m_count.SetValueFromString(option_value).Fail())
964 error = Status::FromErrorString("unrecognized value for count");
965 break;
966
967 case 'o':
968 if (m_offset.SetValueFromString(option_value).Fail())
969 error = Status::FromErrorString("unrecognized value for dump-offset");
970 break;
971
972 default:
973 llvm_unreachable("Unimplemented option");
974 }
975 return error;
976 }
977
978 void OptionParsingStarting(ExecutionContext *execution_context) override {
979 m_expr.Clear();
980 m_string.Clear();
981 m_count.Clear();
982 }
983
988 };
989
992 interpreter, "memory find",
993 "Find a value in the memory of the current target process.",
994 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
997 CommandArgumentData addr_arg;
998 CommandArgumentData value_arg;
999
1000 // Define the first (and only) variant of this arg.
1003
1004 // There is only one variant this argument could be; put it into the
1005 // argument entry.
1006 arg1.push_back(addr_arg);
1007
1008 // Define the first (and only) variant of this arg.
1010 value_arg.arg_repetition = eArgRepeatPlain;
1011
1012 // There is only one variant this argument could be; put it into the
1013 // argument entry.
1014 arg2.push_back(value_arg);
1015
1016 // Push the data for the first argument into the m_arguments vector.
1017 m_arguments.push_back(arg1);
1018 m_arguments.push_back(arg2);
1019
1023 m_option_group.Finalize();
1024 }
1025
1026 ~CommandObjectMemoryFind() override = default;
1027
1028 Options *GetOptions() override { return &m_option_group; }
1029
1030protected:
1031 void DoExecute(Args &command, CommandReturnObject &result) override {
1032 // No need to check "process" for validity as eCommandRequiresProcess
1033 // ensures it is valid
1034 Process *process = m_exe_ctx.GetProcessPtr();
1035
1036 const size_t argc = command.GetArgumentCount();
1037
1038 if (argc != 2) {
1039 result.AppendError("two addresses needed for memory find");
1040 return;
1041 }
1042
1043 Status error;
1045 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1046 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1047 result.AppendError("invalid low address");
1048 return;
1049 }
1051 &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, &error);
1052 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1053 result.AppendError("invalid high address");
1054 return;
1055 }
1056
1057 if (high_addr <= low_addr) {
1058 result.AppendError(
1059 "starting address must be smaller than ending address");
1060 return;
1061 }
1062
1063 lldb::addr_t found_location = LLDB_INVALID_ADDRESS;
1064
1065 DataBufferHeap buffer;
1066
1067 if (m_memory_options.m_string.OptionWasSet()) {
1068 llvm::StringRef str =
1069 m_memory_options.m_string.GetValueAs<llvm::StringRef>().value_or("");
1070 if (str.empty()) {
1071 result.AppendError("search string must have non-zero length.");
1072 return;
1073 }
1074 buffer.CopyData(str);
1075 } else if (m_memory_options.m_expr.OptionWasSet()) {
1076 auto result_or_err = EvaluateExpression(
1077 m_memory_options.m_expr.GetValueAs<llvm::StringRef>().value_or(""),
1078 m_exe_ctx.GetFrameRef(), *process);
1079 if (!result_or_err) {
1080 result.AppendError("Expression evaluation failed: ");
1081 result.AppendError(llvm::toString(result_or_err.takeError()));
1082 return;
1083 }
1084
1085 ValueObjectSP result_sp = *result_or_err;
1086
1087 if (auto err = CopyExpressionResult(*result_sp, buffer,
1088 m_exe_ctx.GetFramePtr())) {
1089 result.AppendError(llvm::toString(std::move(err)));
1090 return;
1091 }
1092 } else {
1093 result.AppendError(
1094 "please pass either a block of text, or an expression to evaluate.");
1095 return;
1096 }
1097
1098 size_t count = m_memory_options.m_count.GetCurrentValue();
1099 found_location = low_addr;
1100 bool ever_found = false;
1101 while (count) {
1102 found_location = process->FindInMemory(
1103 found_location, high_addr, buffer.GetBytes(), buffer.GetByteSize());
1104 if (found_location == LLDB_INVALID_ADDRESS) {
1105 if (!ever_found) {
1106 result.AppendMessage("data not found within the range.\n");
1108 } else
1109 result.AppendMessage("no more matches within the range.\n");
1110 break;
1111 }
1112 result.AppendMessageWithFormatv("data found at location: {0:x}",
1113 found_location);
1114
1115 DataBufferHeap dumpbuffer(32, 0);
1116 process->ReadMemory(
1117 found_location + m_memory_options.m_offset.GetCurrentValue(),
1118 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error);
1119 if (!error.Fail()) {
1120 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(),
1121 process->GetByteOrder(),
1122 process->GetAddressByteSize());
1124 data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1125 dumpbuffer.GetByteSize(), 16,
1126 found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0,
1127 m_exe_ctx.GetBestExecutionContextScope(),
1128 m_memory_tag_options.GetShowTags().GetCurrentValue());
1129 result.GetOutputStream().EOL();
1130 }
1131
1132 --count;
1133 found_location++;
1134 ever_found = true;
1135 }
1136
1138 }
1139
1143};
1144
1145#define LLDB_OPTIONS_memory_write
1146#include "CommandOptions.inc"
1147
1148// Write memory to the inferior process
1150public:
1152 public:
1154
1155 ~OptionGroupWriteMemory() override = default;
1156
1157 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1158 return llvm::ArrayRef(g_memory_write_options);
1159 }
1160
1161 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1162 ExecutionContext *execution_context) override {
1163 Status error;
1164 const int short_option = g_memory_write_options[option_idx].short_option;
1165
1166 switch (short_option) {
1167 case 'i':
1168 m_infile.SetFile(option_value, FileSpec::Style::native);
1170 if (!FileSystem::Instance().Exists(m_infile)) {
1171 m_infile.Clear();
1173 "input file does not exist: '%s'", option_value.str().c_str());
1174 }
1175 break;
1176
1177 case 'o': {
1178 if (option_value.getAsInteger(0, m_infile_offset)) {
1179 m_infile_offset = 0;
1181 "invalid offset string '%s'", option_value.str().c_str());
1182 }
1183 } break;
1184
1185 default:
1186 llvm_unreachable("Unimplemented option");
1187 }
1188 return error;
1189 }
1190
1191 void OptionParsingStarting(ExecutionContext *execution_context) override {
1192 m_infile.Clear();
1193 m_infile_offset = 0;
1194 }
1195
1198 };
1199
1202 interpreter, "memory write",
1203 "Write to the memory of the current target process.", nullptr,
1204 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1207 {std::make_tuple(
1209 "The format to use for each of the value to be written."),
1210 std::make_tuple(eArgTypeByteSize,
1211 "The size in bytes to write from input file or "
1212 "each value.")}) {
1215 CommandArgumentData addr_arg;
1216 CommandArgumentData value_arg;
1217
1218 // Define the first (and only) variant of this arg.
1219 addr_arg.arg_type = eArgTypeAddress;
1220 addr_arg.arg_repetition = eArgRepeatPlain;
1221
1222 // There is only one variant this argument could be; put it into the
1223 // argument entry.
1224 arg1.push_back(addr_arg);
1225
1226 // Define the first (and only) variant of this arg.
1227 value_arg.arg_type = eArgTypeValue;
1228 value_arg.arg_repetition = eArgRepeatPlus;
1229 value_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1230
1231 // There is only one variant this argument could be; put it into the
1232 // argument entry.
1233 arg2.push_back(value_arg);
1234
1235 // Push the data for the first argument into the m_arguments vector.
1236 m_arguments.push_back(arg1);
1237 m_arguments.push_back(arg2);
1238
1247 }
1248
1249 ~CommandObjectMemoryWrite() override = default;
1250
1251 Options *GetOptions() override { return &m_option_group; }
1252
1253protected:
1254 void DoExecute(Args &command, CommandReturnObject &result) override {
1255 // No need to check "process" for validity as eCommandRequiresProcess
1256 // ensures it is valid
1257 Process *process = m_exe_ctx.GetProcessPtr();
1258
1259 const size_t argc = command.GetArgumentCount();
1260
1261 if (m_memory_options.m_infile) {
1262 if (argc < 1) {
1263 result.AppendErrorWithFormat(
1264 "%s takes a destination address when writing file contents.\n",
1265 m_cmd_name.c_str());
1266 return;
1267 }
1268 if (argc > 1) {
1269 result.AppendErrorWithFormat(
1270 "%s takes only a destination address when writing file contents.\n",
1271 m_cmd_name.c_str());
1272 return;
1273 }
1274 } else if (argc < 2) {
1275 result.AppendErrorWithFormat(
1276 "%s takes a destination address and at least one value.\n",
1277 m_cmd_name.c_str());
1278 return;
1279 }
1280
1281 StreamString buffer(Stream::eBinary, process->GetByteOrder());
1282
1283 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1284 size_t item_byte_size = byte_size_value.GetCurrentValue();
1285
1286 Status error;
1288 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1289
1290 if (addr == LLDB_INVALID_ADDRESS) {
1291 result.AppendError("invalid address expression\n");
1292 result.AppendError(error.AsCString());
1293 return;
1294 }
1295
1296 if (m_memory_options.m_infile) {
1297 size_t length = SIZE_MAX;
1298 if (item_byte_size > 1)
1299 length = item_byte_size;
1300 auto data_sp = FileSystem::Instance().CreateDataBuffer(
1301 m_memory_options.m_infile.GetPath(), length,
1302 m_memory_options.m_infile_offset);
1303 if (data_sp) {
1304 length = data_sp->GetByteSize();
1305 if (length > 0) {
1306 Status error;
1307 size_t bytes_written =
1308 process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1309
1310 if (bytes_written == length) {
1311 // All bytes written
1312 result.GetOutputStream().Printf(
1313 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1314 (uint64_t)bytes_written, addr);
1316 } else if (bytes_written > 0) {
1317 // Some byte written
1318 result.GetOutputStream().Printf(
1319 "%" PRIu64 " bytes of %" PRIu64
1320 " requested were written to 0x%" PRIx64 "\n",
1321 (uint64_t)bytes_written, (uint64_t)length, addr);
1323 } else {
1324 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1325 " failed: %s.\n",
1326 addr, error.AsCString());
1327 }
1328 }
1329 } else {
1330 result.AppendErrorWithFormat("Unable to read contents of file.\n");
1331 }
1332 return;
1333 } else if (item_byte_size == 0) {
1334 if (m_format_options.GetFormat() == eFormatPointer)
1335 item_byte_size = process->GetAddressByteSize();
1336 else
1337 item_byte_size = 1;
1338 }
1339
1340 command.Shift(); // shift off the address argument
1341 uint64_t uval64;
1342 int64_t sval64;
1343 bool success = false;
1344 for (auto &entry : command) {
1345 switch (m_format_options.GetFormat()) {
1346 case kNumFormats:
1347 case eFormatFloat: // TODO: add support for floats soon
1348 case eFormatFloat128:
1351 case eFormatComplex:
1352 case eFormatEnum:
1353 case eFormatUnicode8:
1354 case eFormatUnicode16:
1355 case eFormatUnicode32:
1369 case eFormatOSType:
1371 case eFormatAddressInfo:
1372 case eFormatHexFloat:
1373 case eFormatInstruction:
1374 case eFormatVoid:
1375 result.AppendError("unsupported format for writing memory");
1376 return;
1377
1378 case eFormatDefault:
1379 case eFormatBytes:
1380 case eFormatHex:
1382 case eFormatPointer: {
1383 // Decode hex bytes
1384 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1385 // have to special case that:
1386 bool success = false;
1387 if (entry.ref().starts_with("0x"))
1388 success = !entry.ref().getAsInteger(0, uval64);
1389 if (!success)
1390 success = !entry.ref().getAsInteger(16, uval64);
1391 if (!success) {
1392 result.AppendErrorWithFormat(
1393 "'%s' is not a valid hex string value.\n", entry.c_str());
1394 return;
1395 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1396 result.AppendErrorWithFormat("Value 0x%" PRIx64
1397 " is too large to fit in a %" PRIu64
1398 " byte unsigned integer value.\n",
1399 uval64, (uint64_t)item_byte_size);
1400 return;
1401 }
1402 buffer.PutMaxHex64(uval64, item_byte_size);
1403 break;
1404 }
1405 case eFormatBoolean:
1406 uval64 = OptionArgParser::ToBoolean(entry.ref(), false, &success);
1407 if (!success) {
1408 result.AppendErrorWithFormat(
1409 "'%s' is not a valid boolean string value.\n", entry.c_str());
1410 return;
1411 }
1412 buffer.PutMaxHex64(uval64, item_byte_size);
1413 break;
1414
1415 case eFormatBinary:
1416 if (entry.ref().getAsInteger(2, uval64)) {
1417 result.AppendErrorWithFormat(
1418 "'%s' is not a valid binary string value.\n", entry.c_str());
1419 return;
1420 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1421 result.AppendErrorWithFormat("Value 0x%" PRIx64
1422 " is too large to fit in a %" PRIu64
1423 " byte unsigned integer value.\n",
1424 uval64, (uint64_t)item_byte_size);
1425 return;
1426 }
1427 buffer.PutMaxHex64(uval64, item_byte_size);
1428 break;
1429
1430 case eFormatCharArray:
1431 case eFormatChar:
1432 case eFormatCString: {
1433 if (entry.ref().empty())
1434 break;
1435
1436 size_t len = entry.ref().size();
1437 // Include the NULL for C strings...
1438 if (m_format_options.GetFormat() == eFormatCString)
1439 ++len;
1440 Status error;
1441 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1442 addr += len;
1443 } else {
1444 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1445 " failed: %s.\n",
1446 addr, error.AsCString());
1447 return;
1448 }
1449 break;
1450 }
1451 case eFormatDecimal:
1452 if (entry.ref().getAsInteger(0, sval64)) {
1453 result.AppendErrorWithFormat(
1454 "'%s' is not a valid signed decimal value.\n", entry.c_str());
1455 return;
1456 } else if (!llvm::isIntN(item_byte_size * 8, sval64)) {
1457 result.AppendErrorWithFormat(
1458 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1459 " byte signed integer value.\n",
1460 sval64, (uint64_t)item_byte_size);
1461 return;
1462 }
1463 buffer.PutMaxHex64(sval64, item_byte_size);
1464 break;
1465
1466 case eFormatUnsigned:
1467
1468 if (entry.ref().getAsInteger(0, uval64)) {
1469 result.AppendErrorWithFormat(
1470 "'%s' is not a valid unsigned decimal string value.\n",
1471 entry.c_str());
1472 return;
1473 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1474 result.AppendErrorWithFormat("Value %" PRIu64
1475 " is too large to fit in a %" PRIu64
1476 " byte unsigned integer value.\n",
1477 uval64, (uint64_t)item_byte_size);
1478 return;
1479 }
1480 buffer.PutMaxHex64(uval64, item_byte_size);
1481 break;
1482
1483 case eFormatOctal:
1484 if (entry.ref().getAsInteger(8, uval64)) {
1485 result.AppendErrorWithFormat(
1486 "'%s' is not a valid octal string value.\n", entry.c_str());
1487 return;
1488 } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1489 result.AppendErrorWithFormat("Value %" PRIo64
1490 " is too large to fit in a %" PRIu64
1491 " byte unsigned integer value.\n",
1492 uval64, (uint64_t)item_byte_size);
1493 return;
1494 }
1495 buffer.PutMaxHex64(uval64, item_byte_size);
1496 break;
1497 }
1498 }
1499
1500 if (!buffer.GetString().empty()) {
1501 Status error;
1502 const char *buffer_data = buffer.GetString().data();
1503 const size_t buffer_size = buffer.GetString().size();
1504 const size_t write_size =
1505 process->WriteMemory(addr, buffer_data, buffer_size, error);
1506
1507 if (write_size != buffer_size) {
1508 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1509 " failed: %s.\n",
1510 addr, error.AsCString());
1511 return;
1512 }
1513 }
1514 }
1515
1519};
1520
1521// Get malloc/free history of a memory address.
1523public:
1525 : CommandObjectParsed(interpreter, "memory history",
1526 "Print recorded stack traces for "
1527 "allocation/deallocation events "
1528 "associated with an address.",
1529 nullptr,
1530 eCommandRequiresTarget | eCommandRequiresProcess |
1531 eCommandProcessMustBePaused |
1532 eCommandProcessMustBeLaunched) {
1534 CommandArgumentData addr_arg;
1535
1536 // Define the first (and only) variant of this arg.
1537 addr_arg.arg_type = eArgTypeAddress;
1539
1540 // There is only one variant this argument could be; put it into the
1541 // argument entry.
1542 arg1.push_back(addr_arg);
1543
1544 // Push the data for the first argument into the m_arguments vector.
1545 m_arguments.push_back(arg1);
1546 }
1547
1548 ~CommandObjectMemoryHistory() override = default;
1549
1550 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
1551 uint32_t index) override {
1552 return m_cmd_name;
1553 }
1554
1555protected:
1556 void DoExecute(Args &command, CommandReturnObject &result) override {
1557 const size_t argc = command.GetArgumentCount();
1558
1559 if (argc == 0 || argc > 1) {
1560 result.AppendErrorWithFormat("%s takes an address expression",
1561 m_cmd_name.c_str());
1562 return;
1563 }
1564
1565 Status error;
1567 &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1568
1569 if (addr == LLDB_INVALID_ADDRESS) {
1570 result.AppendError("invalid address expression");
1571 result.AppendError(error.AsCString());
1572 return;
1573 }
1574
1575 Stream *output_stream = &result.GetOutputStream();
1576
1577 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1578 const MemoryHistorySP &memory_history =
1579 MemoryHistory::FindPlugin(process_sp);
1580
1581 if (!memory_history) {
1582 result.AppendError("no available memory history provider");
1583 return;
1584 }
1585
1586 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1587
1588 const bool stop_format = false;
1589 for (auto thread : thread_list) {
1590 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format,
1591 /*should_filter*/ false);
1592 }
1593
1595 }
1596};
1597
1598// CommandObjectMemoryRegion
1599#pragma mark CommandObjectMemoryRegion
1600
1601#define LLDB_OPTIONS_memory_region
1602#include "CommandOptions.inc"
1603
1605public:
1607 public:
1608 OptionGroupMemoryRegion() : m_all(false, false) {}
1609
1610 ~OptionGroupMemoryRegion() override = default;
1611
1612 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1613 return llvm::ArrayRef(g_memory_region_options);
1614 }
1615
1616 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1617 ExecutionContext *execution_context) override {
1618 Status status;
1619 const int short_option = g_memory_region_options[option_idx].short_option;
1620
1621 switch (short_option) {
1622 case 'a':
1623 m_all.SetCurrentValue(true);
1624 m_all.SetOptionWasSet();
1625 break;
1626 default:
1627 llvm_unreachable("Unimplemented option");
1628 }
1629
1630 return status;
1631 }
1632
1633 void OptionParsingStarting(ExecutionContext *execution_context) override {
1634 m_all.Clear();
1635 }
1636
1638 };
1639
1642 interpreter, "memory region",
1643 "Get information on the memory region containing "
1644 "an address in the current target process.\n"
1645 "If this command is given an <address-expression> once "
1646 "and then repeated without options, it will try to print "
1647 "the memory region that follows the previously printed "
1648 "region. The command can be repeated until the end of "
1649 "the address range is reached.",
1650 "memory region <address-expression> (or --all)",
1651 eCommandRequiresProcess | eCommandTryTargetAPILock |
1652 eCommandProcessMustBeLaunched) {
1653 // Address in option set 1.
1656 // "--all" will go in option set 2.
1658 m_option_group.Finalize();
1659 }
1660
1661 ~CommandObjectMemoryRegion() override = default;
1662
1663 Options *GetOptions() override { return &m_option_group; }
1664
1665protected:
1667 const MemoryRegionInfo &range_info, lldb::addr_t load_addr) {
1669 ConstString section_name;
1670 if (target.ResolveLoadAddress(load_addr, addr)) {
1671 SectionSP section_sp(addr.GetSection());
1672 if (section_sp) {
1673 // Got the top most section, not the deepest section
1674 while (section_sp->GetParent())
1675 section_sp = section_sp->GetParent();
1676 section_name = section_sp->GetName();
1677 }
1678 }
1679
1680 ConstString name = range_info.GetName();
1682 "[{0:x16}-{1:x16}) {2:r}{3:w}{4:x}{5}{6}{7}{8}",
1683 range_info.GetRange().GetRangeBase(),
1684 range_info.GetRange().GetRangeEnd(), range_info.GetReadable(),
1685 range_info.GetWritable(), range_info.GetExecutable(), name ? " " : "",
1686 name, section_name ? " " : "", section_name);
1687 LazyBool memory_tagged = range_info.GetMemoryTagged();
1688 if (memory_tagged == eLazyBoolYes)
1689 result.AppendMessage("memory tagging: enabled");
1690 LazyBool is_shadow_stack = range_info.IsShadowStack();
1691 if (is_shadow_stack == eLazyBoolYes)
1692 result.AppendMessage("shadow stack: yes");
1693
1694 const std::optional<std::vector<addr_t>> &dirty_page_list =
1695 range_info.GetDirtyPageList();
1696 if (dirty_page_list) {
1697 const size_t page_count = dirty_page_list->size();
1699 "Modified memory (dirty) page list provided, {0} entries.",
1700 page_count);
1701 if (page_count > 0) {
1702 bool print_comma = false;
1703 Stream &strm = result.GetOutputStream();
1704 strm << "Dirty pages: ";
1705 for (size_t i = 0; i < page_count; i++) {
1706 if (print_comma)
1707 strm << ", ";
1708 else
1709 print_comma = true;
1710 strm << llvm::formatv("{0:x}", (*dirty_page_list)[i]);
1711 }
1712 strm << ".\n";
1713 }
1714 }
1715 }
1716
1717 void DoExecute(Args &command, CommandReturnObject &result) override {
1718 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1719 if (!process_sp) {
1721 result.AppendError("invalid process");
1722 return;
1723 }
1724
1725 Status error;
1726 lldb::addr_t load_addr = m_prev_end_addr;
1728
1729 const size_t argc = command.GetArgumentCount();
1730 const lldb::ABISP &abi = process_sp->GetABI();
1731
1732 if (argc == 0) {
1733 if (!m_memory_region_options.m_all) {
1734 if ( // When we're repeating the command, the previous end
1735 // address is used for load_addr. If that was 0xF...F then
1736 // we must have reached the end of memory.
1737 (load_addr == LLDB_INVALID_ADDRESS) ||
1738 // If the target has non-address bits (tags, limited virtual
1739 // address size, etc.), the end of mappable memory will be
1740 // lower than that. So if we find any non-address bit set,
1741 // we must be at the end of the mappable range.
1742 (abi && (abi->FixAnyAddress(load_addr) != load_addr))) {
1743 result.AppendErrorWithFormat(
1744 "No next region address set: one address expression argument or "
1745 "\"--all\" option required:\nUsage: %s\n",
1746 m_cmd_syntax.c_str());
1747 return;
1748 }
1749 }
1750 } else if (argc == 1) {
1751 if (m_memory_region_options.m_all) {
1752 result.AppendError(
1753 "The \"--all\" option cannot be used when an address "
1754 "argument is given");
1755 return;
1756 }
1757
1758 auto load_addr_str = command[0].ref();
1759 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1761 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1762 result.AppendErrorWithFormat("invalid address argument \"%s\": %s\n",
1763 command[0].c_str(), error.AsCString());
1764 return;
1765 }
1766 } else {
1767 // argc > 1
1768 result.AppendErrorWithFormat(
1769 "'%s' takes one argument or \"--all\" option:\nUsage: %s\n",
1770 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1771 return;
1772 }
1773
1774 // It is important that we track the address used to request the region as
1775 // this will give the correct section name in the case that regions overlap.
1776 // On Windows we get multiple regions that start at the same place but are
1777 // different sizes and refer to different sections.
1778 std::vector<std::pair<lldb_private::MemoryRegionInfo, lldb::addr_t>>
1779 region_list;
1780 if (m_memory_region_options.m_all) {
1781 // We don't use GetMemoryRegions here because it doesn't include unmapped
1782 // areas like repeating the command would. So instead, emulate doing that.
1783 lldb::addr_t addr = 0;
1784 while (error.Success() && addr != LLDB_INVALID_ADDRESS &&
1785 // When there are non-address bits the last range will not extend
1786 // to LLDB_INVALID_ADDRESS but to the max virtual address.
1787 // This prevents us looping forever if that is the case.
1788 (!abi || (abi->FixAnyAddress(addr) == addr))) {
1790 error = process_sp->GetMemoryRegionInfo(addr, region_info);
1791
1792 if (error.Success()) {
1793 region_list.push_back({region_info, addr});
1794 addr = region_info.GetRange().GetRangeEnd();
1795 }
1796 }
1797 } else {
1799 error = process_sp->GetMemoryRegionInfo(load_addr, region_info);
1800 if (error.Success())
1801 region_list.push_back({region_info, load_addr});
1802 }
1803
1804 if (error.Success()) {
1805 for (std::pair<MemoryRegionInfo, addr_t> &range : region_list) {
1806 DumpRegion(result, process_sp->GetTarget(), range.first, range.second);
1807 m_prev_end_addr = range.first.GetRange().GetRangeEnd();
1808 }
1809
1811 return;
1812 }
1813
1814 result.AppendErrorWithFormat("%s\n", error.AsCString());
1815 }
1816
1817 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
1818 uint32_t index) override {
1819 // If we repeat this command, repeat it without any arguments so we can
1820 // show the next memory range
1821 return m_cmd_name;
1822 }
1823
1825
1828};
1829
1830// CommandObjectMemory
1831
1834 interpreter, "memory",
1835 "Commands for operating on memory in the current target process.",
1836 "memory <subcommand> [<subcommand-options>]") {
1837 LoadSubCommand("find",
1838 CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1839 LoadSubCommand("read",
1840 CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1841 LoadSubCommand("write",
1842 CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1843 LoadSubCommand("history",
1845 LoadSubCommand("region",
1846 CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
1847 LoadSubCommand("tag",
1848 CommandObjectSP(new CommandObjectMemoryTag(interpreter)));
1849}
1850
static llvm::Error CopyExpressionResult(ValueObject &result, DataBufferHeap &buffer, ExecutionContextScope *scope)
#define ALL_KEYWORDS
static llvm::Expected< ValueObjectSP > EvaluateExpression(llvm::StringRef expression, StackFrame &frame, Process &process)
static llvm::raw_ostream & error(Stream &strm)
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
OptionGroupMemoryTag m_memory_tag_options
Options * GetOptions() override
OptionGroupFindMemory m_memory_options
~CommandObjectMemoryFind() override=default
CommandObjectMemoryFind(CommandInterpreter &interpreter)
void 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.
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectMemoryHistory() override=default
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
void DoExecute(Args &command, CommandReturnObject &result) override
OptionGroupValueObjectDisplay m_varobj_options
CommandObjectMemoryRead(CommandInterpreter &interpreter)
OptionGroupOutputFile m_outfile_options
OptionGroupReadMemory m_memory_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.
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
void 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
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMemoryWrite(CommandInterpreter &interpreter)
OptionGroupWriteMemory m_memory_options
~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:62
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:432
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:681
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:730
uint32_t GetMaximumOpcodeByteSize() const
Definition ArchSpec.cpp:929
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:295
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
CommandObjectMemory(CommandInterpreter &interpreter)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
std::vector< CommandArgumentData > CommandArgumentEntry
std::vector< CommandArgumentEntry > m_arguments
void AppendMessage(llvm::StringRef in_string)
void AppendError(llvm::StringRef in_string)
void AppendWarningWithFormatv(const char *format, Args &&...args)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
void void AppendMessageWithFormatv(const char *format, Args &&...args)
void AppendWarning(llvm::StringRef in_string)
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
Get the number of bytes in the data buffer.
void CopyData(const void *src, lldb::offset_t src_len)
Makes a copy of the src_len bytes in src.
An data extractor class.
"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.
A file utility class.
Definition FileSpec.h:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
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
@ eOpenOptionCanCreate
Definition File.h:56
@ eOpenOptionTruncate
Definition File.h:57
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition Language.cpp:458
static lldb::MemoryHistorySP FindPlugin(const lldb::ProcessSP process)
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.
void FindTypes(Module *search_first, const TypeQuery &query, lldb_private::TypeResults &results) const
Find types using a type-matching object that contains all search parameters.
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
OptionValueUInt64 & GetCountValue()
void Append(OptionGroup *group)
Append options from a OptionGroup class.
Definition Options.cpp:760
A command line option parsing protocol class.
Definition Options.h:58
A plug-in interface definition class for debugging a process.
Definition Process.h:355
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:1911
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3770
lldb::addr_t FindInMemory(lldb::addr_t low, lldb::addr_t high, const uint8_t *buf, size_t size)
Find a pattern within a memory region.
Definition Process.cpp:3509
uint32_t GetAddressByteSize() const
Definition Process.cpp:3774
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2419
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1251
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
@ eBinary
Get and put data as binary instead of as the default string mode.
Definition Stream.h:32
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:153
size_t PutMaxHex64(uint64_t uvalue, size_t byte_size, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:321
lldb::ModuleSP module_sp
The Module for a given query.
uint32_t GetMaximumSizeOfStringSummary() const
Definition Target.cpp:5007
uint32_t GetMaximumMemReadSize() const
Definition Target.cpp:5013
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2672
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3319
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition Target.cpp:2116
virtual 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, bool *did_read_live_memory=nullptr)
Definition Target.cpp:1990
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1157
const ArchSpec & GetArchitecture() const
Definition Target.h:1199
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:2836
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
lldb::TypeSP GetFirstType() const
Definition Type.h:385
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, llvm::StringRef name, const Address &address, lldb::TypeSP &type_sp)
virtual uint64_t GetValueAsUnsigned(uint64_t fail_value, bool *success=nullptr)
CompilerType GetCompilerType()
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
#define LLDB_OPT_SET_1
#define UINT64_MAX
#define LLDB_OPT_SET_2
#define LLDB_OPT_SET_ALL
#define LLDB_OPT_SET_3
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
A class that represents a running process on the host machine.
std::vector< lldb::ThreadSP > HistoryThreads
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.
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
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...
@ eFormatAddressInfo
Describe what an address points to (func + offset with file/line, symbol + offset,...
@ eFormatVectorOfUInt128
@ eFormatVectorOfUInt8
@ eFormatVectorOfFloat32
@ eFormatVectorOfSInt32
@ eFormatVectorOfSInt8
@ eFormatVectorOfUInt16
@ eFormatHexUppercase
@ eFormatVectorOfFloat64
@ eFormatCharPrintable
Only printable characters, '.' if not printable.
@ eFormatComplexInteger
Integer complex type.
@ eFormatVectorOfSInt16
@ eFormatFloat128
Disambiguate between 128-bit long double (which uses eFormatFloat) and __float128 (which uses eFormat...
@ eFormatVectorOfUInt32
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::MemoryHistory > MemoryHistorySP
@ eExpressionCompleted
std::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::Process > ProcessSP
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeAddressOrExpression
std::shared_ptr< lldb_private::Section > SectionSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Module > ModuleSP
Used to build individual command argument lists.
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 lldb::addr_t ToRawAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
As for ToAddress but do not remove non-address bits from the result.
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