xref: /llvm-project/lldb/source/Commands/CommandObjectMemory.cpp (revision fdbe7c7faa547b16bf6da0fedbb7234b6ee3adef)
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 
9 #include "CommandObjectMemory.h"
10 #include "CommandObjectMemoryTag.h"
11 #include "lldb/Core/DumpDataExtractor.h"
12 #include "lldb/Core/Section.h"
13 #include "lldb/Core/ValueObjectMemory.h"
14 #include "lldb/Expression/ExpressionVariable.h"
15 #include "lldb/Host/OptionParser.h"
16 #include "lldb/Interpreter/CommandOptionArgumentTable.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/OptionArgParser.h"
19 #include "lldb/Interpreter/OptionGroupFormat.h"
20 #include "lldb/Interpreter/OptionGroupMemoryTag.h"
21 #include "lldb/Interpreter/OptionGroupOutputFile.h"
22 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
23 #include "lldb/Interpreter/OptionValueLanguage.h"
24 #include "lldb/Interpreter/OptionValueString.h"
25 #include "lldb/Interpreter/Options.h"
26 #include "lldb/Symbol/SymbolFile.h"
27 #include "lldb/Symbol/TypeList.h"
28 #include "lldb/Target/ABI.h"
29 #include "lldb/Target/Language.h"
30 #include "lldb/Target/MemoryHistory.h"
31 #include "lldb/Target/MemoryRegionInfo.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/StackFrame.h"
34 #include "lldb/Target/Target.h"
35 #include "lldb/Target/Thread.h"
36 #include "lldb/Utility/Args.h"
37 #include "lldb/Utility/DataBufferHeap.h"
38 #include "lldb/Utility/StreamString.h"
39 #include "llvm/Support/MathExtras.h"
40 #include <cinttypes>
41 #include <memory>
42 #include <optional>
43 
44 using namespace lldb;
45 using namespace lldb_private;
46 
47 #define LLDB_OPTIONS_memory_read
48 #include "CommandOptions.inc"
49 
50 class OptionGroupReadMemory : public OptionGroup {
51 public:
52   OptionGroupReadMemory()
53       : m_num_per_line(1, 1), m_offset(0, 0),
54         m_language_for_type(eLanguageTypeUnknown) {}
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 {
64     Status error;
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)
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':
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 
111   Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) {
112     Status error;
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 
135     case eFormatInstruction:
136       if (count_option_set)
137         byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
138       m_num_per_line = 1;
139       break;
140 
141     case eFormatAddressInfo:
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:
176     case eFormatBytesWithASCII:
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:
195     case eFormatCharPrintable:
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 
213     case eFormatComplexInteger:
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 
246     case eFormatVectorOfChar:
247     case eFormatVectorOfSInt8:
248     case eFormatVectorOfUInt8:
249     case eFormatVectorOfSInt16:
250     case eFormatVectorOfUInt16:
251     case eFormatVectorOfSInt32:
252     case eFormatVectorOfUInt32:
253     case eFormatVectorOfSInt64:
254     case eFormatVectorOfUInt64:
255     case eFormatVectorOfFloat16:
256     case eFormatVectorOfFloat32:
257     case eFormatVectorOfFloat64:
258     case eFormatVectorOfUInt128:
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 {
271     return m_num_per_line.OptionWasSet() || m_output_as_binary ||
272            m_view_as_type.OptionWasSet() || m_offset.OptionWasSet() ||
273            m_language_for_type.OptionWasSet();
274   }
275 
276   OptionValueUInt64 m_num_per_line;
277   bool m_output_as_binary = false;
278   OptionValueString m_view_as_type;
279   bool m_force = false;
280   OptionValueUInt64 m_offset;
281   OptionValueLanguage m_language_for_type;
282 };
283 
284 // Read memory from the inferior process
285 class CommandObjectMemoryRead : public CommandObjectParsed {
286 public:
287   CommandObjectMemoryRead(CommandInterpreter &interpreter)
288       : CommandObjectParsed(
289             interpreter, "memory read",
290             "Read from the memory of the current target process.", nullptr,
291             eCommandRequiresTarget | eCommandProcessMustBePaused),
292         m_format_options(eFormatBytesWithASCII, 1, 8),
293         m_memory_tag_options(/*note_binary=*/true),
294         m_prev_format_options(eFormatBytesWithASCII, 1, 8) {
295     CommandArgumentEntry arg1;
296     CommandArgumentEntry arg2;
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.
309     end_addr_arg.arg_type = eArgTypeAddressOrExpression;
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
321     m_option_group.Append(&m_format_options,
322                           OptionGroupFormat::OPTION_GROUP_FORMAT |
323                               OptionGroupFormat::OPTION_GROUP_COUNT,
324                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
325     m_option_group.Append(&m_format_options,
326                           OptionGroupFormat::OPTION_GROUP_GDB_FMT,
327                           LLDB_OPT_SET_1 | LLDB_OPT_SET_3);
328     // Add the "--size" option to group 1 and 2
329     m_option_group.Append(&m_format_options,
330                           OptionGroupFormat::OPTION_GROUP_SIZE,
331                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
332     m_option_group.Append(&m_memory_options);
333     m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL,
334                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
335     m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
336     m_option_group.Append(&m_memory_tag_options, LLDB_OPT_SET_ALL,
337                           LLDB_OPT_SET_ALL);
338     m_option_group.Finalize();
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 
350 protected:
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;
368     Status error;
369 
370     const char *view_as_type_cstr =
371         m_memory_options.m_view_as_type.GetCurrentValue();
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());
457       StackFrame *frame = m_exe_ctx.GetFramePtr();
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 =
468             m_memory_options.m_language_for_type.GetCurrentValue();
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 =
479                   target->GetPersistentExpressionStateForLanguage(lang)) {
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) {
489           result.AppendErrorWithFormat(
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) {
527         result.AppendErrorWithFormat(
528             "unable to get the byte size of the type '%s'\n",
529             view_as_type_cstr);
530         return false;
531       }
532       m_format_options.GetByteSizeValue() = *size;
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 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;
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()) {
559         m_format_options = m_prev_format_options;
560         m_memory_options = m_prev_memory_options;
561         m_outfile_options = m_prev_outfile_options;
562         m_varobj_options = m_prev_varobj_options;
563         m_memory_tag_options = m_prev_memory_tag_options;
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()
576             : m_format_options.GetByteSizeValue().GetCurrentValue();
577 
578     const size_t num_per_line =
579         m_memory_options.m_num_per_line.GetCurrentValue();
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(),
589                                         LLDB_INVALID_ADDRESS, &error);
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) {
598       lldb::addr_t end_addr = OptionArgParser::ToAddress(
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) {
606         result.AppendErrorWithFormat(
607             "end address (0x%" PRIx64
608             ") must be greater than the start address (0x%" PRIx64 ").\n",
609             end_addr, addr);
610         return false;
611       } else if (m_format_options.GetCountValue().OptionWasSet()) {
612         result.AppendErrorWithFormat(
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) {
626       result.AppendErrorWithFormat(
627           "Normally, \'memory read\' will not read over %" PRIu32
628           " bytes of data.\n",
629           max_unforced_size);
630       result.AppendErrorWithFormat(
631           "Please use --force to override this restriction just once.\n");
632       result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
633                                    "will often need a larger limit.\n");
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
642       if (!m_format_options.GetFormatValue().OptionWasSet())
643         m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
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());
654     } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
655                eFormatCString) {
656       data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0');
657       if (data_sp->GetBytes() == nullptr) {
658         result.AppendErrorWithFormat(
659             "can't allocate 0x%" PRIx32
660             " bytes for the memory read buffer, specify a smaller size to read",
661             (uint32_t)total_byte_size);
662         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 {
673           result.AppendErrorWithFormat(
674               "failed to read memory from 0x%" PRIx64 ".\n", addr);
675         }
676         return false;
677       }
678 
679       if (bytes_read < total_byte_size)
680         result.AppendWarningWithFormat(
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
687       if (m_format_options.GetByteSizeValue().OptionWasSet() &&
688           !m_format_options.HasGDBFormat())
689         item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
690       else
691         item_byte_size = target->GetMaximumSizeOfStringSummary();
692       if (!m_format_options.GetCountValue().OptionWasSet())
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) {
698         result.AppendErrorWithFormat(
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);
712         Status error;
713         size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
714                                                     item_byte_size + 1, error);
715         if (error.Fail()) {
716           result.AppendErrorWithFormat(
717               "failed to read memory from 0x%" PRIx64 ".\n", addr);
718           return false;
719         }
720 
721         if (item_byte_size == read) {
722           result.AppendWarningWithFormat(
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;
747     m_prev_format_options = m_format_options;
748     m_prev_memory_options = m_memory_options;
749     m_prev_outfile_options = m_outfile_options;
750     m_prev_varobj_options = m_varobj_options;
751     m_prev_memory_tag_options = m_memory_tag_options;
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 =
757         m_outfile_options.GetFile().GetCurrentValue();
758 
759     std::string path = outfile_spec.GetPath();
760     if (outfile_spec) {
761 
762       File::OpenOptions open_options =
763           File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate;
764       const bool append = m_outfile_options.GetAppend().GetCurrentValue();
765       open_options |=
766           append ? File::eOpenOptionAppend : File::eOpenOptionTruncate;
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()));
773         if (m_memory_options.m_output_as_binary) {
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 
804     ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
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) {
814           Format format = m_format_options.GetFormat();
815           if (format != eFormatDefault)
816             valobj_sp->SetFormat(format);
817 
818           DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
819               eLanguageRuntimeDescriptionDisplayVerbosityFull, format));
820 
821           valobj_sp->Dump(*output_stream_p, options);
822         } else {
823           result.AppendErrorWithFormat(
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 
832     result.SetStatus(eReturnStatusSuccessFinishResult);
833     DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
834                        target->GetArchitecture().GetAddressByteSize(),
835                        target->GetArchitecture().GetDataByteSize());
836 
837     Format format = m_format_options.GetFormat();
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
852         result.AppendErrorWithFormat(
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,
863         exe_scope, m_memory_tag_options.GetShowTags().GetCurrentValue());
864     m_next_addr = addr + bytes_dumped;
865     output_stream_p->EOL();
866     return true;
867   }
868 
869   OptionGroupOptions m_option_group;
870   OptionGroupFormat m_format_options;
871   OptionGroupReadMemory m_memory_options;
872   OptionGroupOutputFile m_outfile_options;
873   OptionGroupValueObjectDisplay m_varobj_options;
874   OptionGroupMemoryTag m_memory_tag_options;
875   lldb::addr_t m_next_addr = LLDB_INVALID_ADDRESS;
876   lldb::addr_t m_prev_byte_size = 0;
877   OptionGroupFormat m_prev_format_options;
878   OptionGroupReadMemory m_prev_memory_options;
879   OptionGroupOutputFile m_prev_outfile_options;
880   OptionGroupValueObjectDisplay m_prev_varobj_options;
881   OptionGroupMemoryTag m_prev_memory_tag_options;
882   CompilerType m_prev_compiler_type;
883 };
884 
885 #define LLDB_OPTIONS_memory_find
886 #include "CommandOptions.inc"
887 
888 // Find the specified data in memory
889 class CommandObjectMemoryFind : public CommandObjectParsed {
890 public:
891   class OptionGroupFindMemory : public OptionGroup {
892   public:
893     OptionGroupFindMemory() : m_count(1), m_offset(0) {}
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 {
903       Status error;
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 
937     OptionValueString m_expr;
938     OptionValueString m_string;
939     OptionValueUInt64 m_count;
940     OptionValueUInt64 m_offset;
941   };
942 
943   CommandObjectMemoryFind(CommandInterpreter &interpreter)
944       : CommandObjectParsed(
945             interpreter, "memory find",
946             "Find a value in the memory of the current target process.",
947             nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
948     CommandArgumentEntry arg1;
949     CommandArgumentEntry arg2;
950     CommandArgumentData addr_arg;
951     CommandArgumentData value_arg;
952 
953     // Define the first (and only) variant of this arg.
954     addr_arg.arg_type = eArgTypeAddressOrExpression;
955     addr_arg.arg_repetition = eArgRepeatPlain;
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.
962     value_arg.arg_type = eArgTypeAddressOrExpression;
963     value_arg.arg_repetition = eArgRepeatPlain;
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 
973     m_option_group.Append(&m_memory_options);
974     m_option_group.Append(&m_memory_tag_options, LLDB_OPT_SET_ALL,
975                           LLDB_OPT_SET_ALL);
976     m_option_group.Finalize();
977   }
978 
979   ~CommandObjectMemoryFind() override = default;
980 
981   Options *GetOptions() override { return &m_option_group; }
982 
983 protected:
984   class ProcessMemoryIterator {
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;
998       Status error;
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;
1010     lldb::addr_t m_base_addr;
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;
1026     lldb::addr_t low_addr = OptionArgParser::ToAddress(
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     }
1032     lldb::addr_t high_addr = OptionArgParser::ToAddress(
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 
1049     if (m_memory_options.m_string.OptionWasSet()) {
1050       std::optional<llvm::StringRef> str =
1051           m_memory_options.m_string.GetStringValue();
1052       if (!str) {
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.GetStringValue().value_or(""), frame,
1063                result_sp)) &&
1064           result_sp) {
1065         uint64_t value = result_sp->GetValueAsUnsigned(0);
1066         std::optional<uint64_t> size =
1067             result_sp->GetCompilerType().GetByteSize(nullptr);
1068         if (!size)
1069           return false;
1070         switch (*size) {
1071         case 1: {
1072           uint8_t byte = (uint8_t)value;
1073           buffer.CopyData(&byte, 1);
1074         } break;
1075         case 2: {
1076           uint16_t word = (uint16_t)value;
1077           buffer.CopyData(&word, 2);
1078         } break;
1079         case 4: {
1080           uint32_t lword = (uint32_t)value;
1081           buffer.CopyData(&lword, 4);
1082         } break;
1083         case 8: {
1084           buffer.CopyData(&value, 8);
1085         } break;
1086         case 3:
1087         case 5:
1088         case 6:
1089         case 7:
1090           result.AppendError("unknown type. pass a string instead");
1091           return false;
1092         default:
1093           result.AppendError(
1094               "result size larger than 8 bytes. pass a string instead");
1095           return false;
1096         }
1097       } else {
1098         result.AppendError(
1099             "expression evaluation failed. pass a string instead");
1100         return false;
1101       }
1102     } else {
1103       result.AppendError(
1104           "please pass either a block of text, or an expression to evaluate.");
1105       return false;
1106     }
1107 
1108     size_t count = m_memory_options.m_count.GetCurrentValue();
1109     found_location = low_addr;
1110     bool ever_found = false;
1111     while (count) {
1112       found_location = FastSearch(found_location, high_addr, buffer.GetBytes(),
1113                                   buffer.GetByteSize());
1114       if (found_location == LLDB_INVALID_ADDRESS) {
1115         if (!ever_found) {
1116           result.AppendMessage("data not found within the range.\n");
1117           result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
1118         } else
1119           result.AppendMessage("no more matches within the range.\n");
1120         break;
1121       }
1122       result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n",
1123                                      found_location);
1124 
1125       DataBufferHeap dumpbuffer(32, 0);
1126       process->ReadMemory(
1127           found_location + m_memory_options.m_offset.GetCurrentValue(),
1128           dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error);
1129       if (!error.Fail()) {
1130         DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(),
1131                            process->GetByteOrder(),
1132                            process->GetAddressByteSize());
1133         DumpDataExtractor(
1134             data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1135             dumpbuffer.GetByteSize(), 16,
1136             found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0,
1137             m_exe_ctx.GetBestExecutionContextScope(),
1138             m_memory_tag_options.GetShowTags().GetCurrentValue());
1139         result.GetOutputStream().EOL();
1140       }
1141 
1142       --count;
1143       found_location++;
1144       ever_found = true;
1145     }
1146 
1147     result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
1148     return true;
1149   }
1150 
1151   lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer,
1152                           size_t buffer_size) {
1153     const size_t region_size = high - low;
1154 
1155     if (region_size < buffer_size)
1156       return LLDB_INVALID_ADDRESS;
1157 
1158     std::vector<size_t> bad_char_heuristic(256, buffer_size);
1159     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1160     ProcessMemoryIterator iterator(process_sp, low);
1161 
1162     for (size_t idx = 0; idx < buffer_size - 1; idx++) {
1163       decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx];
1164       bad_char_heuristic[bcu_idx] = buffer_size - idx - 1;
1165     }
1166     for (size_t s = 0; s <= (region_size - buffer_size);) {
1167       int64_t j = buffer_size - 1;
1168       while (j >= 0 && buffer[j] == iterator[s + j])
1169         j--;
1170       if (j < 0)
1171         return low + s;
1172       else
1173         s += bad_char_heuristic[iterator[s + buffer_size - 1]];
1174     }
1175 
1176     return LLDB_INVALID_ADDRESS;
1177   }
1178 
1179   OptionGroupOptions m_option_group;
1180   OptionGroupFindMemory m_memory_options;
1181   OptionGroupMemoryTag m_memory_tag_options;
1182 };
1183 
1184 #define LLDB_OPTIONS_memory_write
1185 #include "CommandOptions.inc"
1186 
1187 // Write memory to the inferior process
1188 class CommandObjectMemoryWrite : public CommandObjectParsed {
1189 public:
1190   class OptionGroupWriteMemory : public OptionGroup {
1191   public:
1192     OptionGroupWriteMemory() = default;
1193 
1194     ~OptionGroupWriteMemory() override = default;
1195 
1196     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1197       return llvm::ArrayRef(g_memory_write_options);
1198     }
1199 
1200     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1201                           ExecutionContext *execution_context) override {
1202       Status error;
1203       const int short_option = g_memory_write_options[option_idx].short_option;
1204 
1205       switch (short_option) {
1206       case 'i':
1207         m_infile.SetFile(option_value, FileSpec::Style::native);
1208         FileSystem::Instance().Resolve(m_infile);
1209         if (!FileSystem::Instance().Exists(m_infile)) {
1210           m_infile.Clear();
1211           error.SetErrorStringWithFormat("input file does not exist: '%s'",
1212                                          option_value.str().c_str());
1213         }
1214         break;
1215 
1216       case 'o': {
1217         if (option_value.getAsInteger(0, m_infile_offset)) {
1218           m_infile_offset = 0;
1219           error.SetErrorStringWithFormat("invalid offset string '%s'",
1220                                          option_value.str().c_str());
1221         }
1222       } break;
1223 
1224       default:
1225         llvm_unreachable("Unimplemented option");
1226       }
1227       return error;
1228     }
1229 
1230     void OptionParsingStarting(ExecutionContext *execution_context) override {
1231       m_infile.Clear();
1232       m_infile_offset = 0;
1233     }
1234 
1235     FileSpec m_infile;
1236     off_t m_infile_offset;
1237   };
1238 
1239   CommandObjectMemoryWrite(CommandInterpreter &interpreter)
1240       : CommandObjectParsed(
1241             interpreter, "memory write",
1242             "Write to the memory of the current target process.", nullptr,
1243             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1244         m_format_options(
1245             eFormatBytes, 1, UINT64_MAX,
1246             {std::make_tuple(
1247                  eArgTypeFormat,
1248                  "The format to use for each of the value to be written."),
1249              std::make_tuple(eArgTypeByteSize,
1250                              "The size in bytes to write from input file or "
1251                              "each value.")}) {
1252     CommandArgumentEntry arg1;
1253     CommandArgumentEntry arg2;
1254     CommandArgumentData addr_arg;
1255     CommandArgumentData value_arg;
1256 
1257     // Define the first (and only) variant of this arg.
1258     addr_arg.arg_type = eArgTypeAddress;
1259     addr_arg.arg_repetition = eArgRepeatPlain;
1260 
1261     // There is only one variant this argument could be; put it into the
1262     // argument entry.
1263     arg1.push_back(addr_arg);
1264 
1265     // Define the first (and only) variant of this arg.
1266     value_arg.arg_type = eArgTypeValue;
1267     value_arg.arg_repetition = eArgRepeatPlus;
1268     value_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1269 
1270     // There is only one variant this argument could be; put it into the
1271     // argument entry.
1272     arg2.push_back(value_arg);
1273 
1274     // Push the data for the first argument into the m_arguments vector.
1275     m_arguments.push_back(arg1);
1276     m_arguments.push_back(arg2);
1277 
1278     m_option_group.Append(&m_format_options,
1279                           OptionGroupFormat::OPTION_GROUP_FORMAT,
1280                           LLDB_OPT_SET_1);
1281     m_option_group.Append(&m_format_options,
1282                           OptionGroupFormat::OPTION_GROUP_SIZE,
1283                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
1284     m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2);
1285     m_option_group.Finalize();
1286   }
1287 
1288   ~CommandObjectMemoryWrite() override = default;
1289 
1290   Options *GetOptions() override { return &m_option_group; }
1291 
1292 protected:
1293   bool DoExecute(Args &command, CommandReturnObject &result) override {
1294     // No need to check "process" for validity as eCommandRequiresProcess
1295     // ensures it is valid
1296     Process *process = m_exe_ctx.GetProcessPtr();
1297 
1298     const size_t argc = command.GetArgumentCount();
1299 
1300     if (m_memory_options.m_infile) {
1301       if (argc < 1) {
1302         result.AppendErrorWithFormat(
1303             "%s takes a destination address when writing file contents.\n",
1304             m_cmd_name.c_str());
1305         return false;
1306       }
1307       if (argc > 1) {
1308         result.AppendErrorWithFormat(
1309             "%s takes only a destination address when writing file contents.\n",
1310             m_cmd_name.c_str());
1311         return false;
1312       }
1313     } else if (argc < 2) {
1314       result.AppendErrorWithFormat(
1315           "%s takes a destination address and at least one value.\n",
1316           m_cmd_name.c_str());
1317       return false;
1318     }
1319 
1320     StreamString buffer(
1321         Stream::eBinary,
1322         process->GetTarget().GetArchitecture().GetAddressByteSize(),
1323         process->GetTarget().GetArchitecture().GetByteOrder());
1324 
1325     OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1326     size_t item_byte_size = byte_size_value.GetCurrentValue();
1327 
1328     Status error;
1329     lldb::addr_t addr = OptionArgParser::ToAddress(
1330         &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1331 
1332     if (addr == LLDB_INVALID_ADDRESS) {
1333       result.AppendError("invalid address expression\n");
1334       result.AppendError(error.AsCString());
1335       return false;
1336     }
1337 
1338     if (m_memory_options.m_infile) {
1339       size_t length = SIZE_MAX;
1340       if (item_byte_size > 1)
1341         length = item_byte_size;
1342       auto data_sp = FileSystem::Instance().CreateDataBuffer(
1343           m_memory_options.m_infile.GetPath(), length,
1344           m_memory_options.m_infile_offset);
1345       if (data_sp) {
1346         length = data_sp->GetByteSize();
1347         if (length > 0) {
1348           Status error;
1349           size_t bytes_written =
1350               process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1351 
1352           if (bytes_written == length) {
1353             // All bytes written
1354             result.GetOutputStream().Printf(
1355                 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1356                 (uint64_t)bytes_written, addr);
1357             result.SetStatus(eReturnStatusSuccessFinishResult);
1358           } else if (bytes_written > 0) {
1359             // Some byte written
1360             result.GetOutputStream().Printf(
1361                 "%" PRIu64 " bytes of %" PRIu64
1362                 " requested were written to 0x%" PRIx64 "\n",
1363                 (uint64_t)bytes_written, (uint64_t)length, addr);
1364             result.SetStatus(eReturnStatusSuccessFinishResult);
1365           } else {
1366             result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1367                                          " failed: %s.\n",
1368                                          addr, error.AsCString());
1369           }
1370         }
1371       } else {
1372         result.AppendErrorWithFormat("Unable to read contents of file.\n");
1373       }
1374       return result.Succeeded();
1375     } else if (item_byte_size == 0) {
1376       if (m_format_options.GetFormat() == eFormatPointer)
1377         item_byte_size = buffer.GetAddressByteSize();
1378       else
1379         item_byte_size = 1;
1380     }
1381 
1382     command.Shift(); // shift off the address argument
1383     uint64_t uval64;
1384     int64_t sval64;
1385     bool success = false;
1386     for (auto &entry : command) {
1387       switch (m_format_options.GetFormat()) {
1388       case kNumFormats:
1389       case eFormatFloat: // TODO: add support for floats soon
1390       case eFormatCharPrintable:
1391       case eFormatBytesWithASCII:
1392       case eFormatComplex:
1393       case eFormatEnum:
1394       case eFormatUnicode8:
1395       case eFormatUnicode16:
1396       case eFormatUnicode32:
1397       case eFormatVectorOfChar:
1398       case eFormatVectorOfSInt8:
1399       case eFormatVectorOfUInt8:
1400       case eFormatVectorOfSInt16:
1401       case eFormatVectorOfUInt16:
1402       case eFormatVectorOfSInt32:
1403       case eFormatVectorOfUInt32:
1404       case eFormatVectorOfSInt64:
1405       case eFormatVectorOfUInt64:
1406       case eFormatVectorOfFloat16:
1407       case eFormatVectorOfFloat32:
1408       case eFormatVectorOfFloat64:
1409       case eFormatVectorOfUInt128:
1410       case eFormatOSType:
1411       case eFormatComplexInteger:
1412       case eFormatAddressInfo:
1413       case eFormatHexFloat:
1414       case eFormatInstruction:
1415       case eFormatVoid:
1416         result.AppendError("unsupported format for writing memory");
1417         return false;
1418 
1419       case eFormatDefault:
1420       case eFormatBytes:
1421       case eFormatHex:
1422       case eFormatHexUppercase:
1423       case eFormatPointer: {
1424         // Decode hex bytes
1425         // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1426         // have to special case that:
1427         bool success = false;
1428         if (entry.ref().startswith("0x"))
1429           success = !entry.ref().getAsInteger(0, uval64);
1430         if (!success)
1431           success = !entry.ref().getAsInteger(16, uval64);
1432         if (!success) {
1433           result.AppendErrorWithFormat(
1434               "'%s' is not a valid hex string value.\n", entry.c_str());
1435           return false;
1436         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1437           result.AppendErrorWithFormat("Value 0x%" PRIx64
1438                                        " is too large to fit in a %" PRIu64
1439                                        " byte unsigned integer value.\n",
1440                                        uval64, (uint64_t)item_byte_size);
1441           return false;
1442         }
1443         buffer.PutMaxHex64(uval64, item_byte_size);
1444         break;
1445       }
1446       case eFormatBoolean:
1447         uval64 = OptionArgParser::ToBoolean(entry.ref(), false, &success);
1448         if (!success) {
1449           result.AppendErrorWithFormat(
1450               "'%s' is not a valid boolean string value.\n", entry.c_str());
1451           return false;
1452         }
1453         buffer.PutMaxHex64(uval64, item_byte_size);
1454         break;
1455 
1456       case eFormatBinary:
1457         if (entry.ref().getAsInteger(2, uval64)) {
1458           result.AppendErrorWithFormat(
1459               "'%s' is not a valid binary string value.\n", entry.c_str());
1460           return false;
1461         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1462           result.AppendErrorWithFormat("Value 0x%" PRIx64
1463                                        " is too large to fit in a %" PRIu64
1464                                        " byte unsigned integer value.\n",
1465                                        uval64, (uint64_t)item_byte_size);
1466           return false;
1467         }
1468         buffer.PutMaxHex64(uval64, item_byte_size);
1469         break;
1470 
1471       case eFormatCharArray:
1472       case eFormatChar:
1473       case eFormatCString: {
1474         if (entry.ref().empty())
1475           break;
1476 
1477         size_t len = entry.ref().size();
1478         // Include the NULL for C strings...
1479         if (m_format_options.GetFormat() == eFormatCString)
1480           ++len;
1481         Status error;
1482         if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1483           addr += len;
1484         } else {
1485           result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1486                                        " failed: %s.\n",
1487                                        addr, error.AsCString());
1488           return false;
1489         }
1490         break;
1491       }
1492       case eFormatDecimal:
1493         if (entry.ref().getAsInteger(0, sval64)) {
1494           result.AppendErrorWithFormat(
1495               "'%s' is not a valid signed decimal value.\n", entry.c_str());
1496           return false;
1497         } else if (!llvm::isIntN(item_byte_size * 8, sval64)) {
1498           result.AppendErrorWithFormat(
1499               "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1500               " byte signed integer value.\n",
1501               sval64, (uint64_t)item_byte_size);
1502           return false;
1503         }
1504         buffer.PutMaxHex64(sval64, item_byte_size);
1505         break;
1506 
1507       case eFormatUnsigned:
1508 
1509         if (entry.ref().getAsInteger(0, uval64)) {
1510           result.AppendErrorWithFormat(
1511               "'%s' is not a valid unsigned decimal string value.\n",
1512               entry.c_str());
1513           return false;
1514         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1515           result.AppendErrorWithFormat("Value %" PRIu64
1516                                        " is too large to fit in a %" PRIu64
1517                                        " byte unsigned integer value.\n",
1518                                        uval64, (uint64_t)item_byte_size);
1519           return false;
1520         }
1521         buffer.PutMaxHex64(uval64, item_byte_size);
1522         break;
1523 
1524       case eFormatOctal:
1525         if (entry.ref().getAsInteger(8, uval64)) {
1526           result.AppendErrorWithFormat(
1527               "'%s' is not a valid octal string value.\n", entry.c_str());
1528           return false;
1529         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1530           result.AppendErrorWithFormat("Value %" PRIo64
1531                                        " is too large to fit in a %" PRIu64
1532                                        " byte unsigned integer value.\n",
1533                                        uval64, (uint64_t)item_byte_size);
1534           return false;
1535         }
1536         buffer.PutMaxHex64(uval64, item_byte_size);
1537         break;
1538       }
1539     }
1540 
1541     if (!buffer.GetString().empty()) {
1542       Status error;
1543       if (process->WriteMemory(addr, buffer.GetString().data(),
1544                                buffer.GetString().size(),
1545                                error) == buffer.GetString().size())
1546         return true;
1547       else {
1548         result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1549                                      " failed: %s.\n",
1550                                      addr, error.AsCString());
1551         return false;
1552       }
1553     }
1554     return true;
1555   }
1556 
1557   OptionGroupOptions m_option_group;
1558   OptionGroupFormat m_format_options;
1559   OptionGroupWriteMemory m_memory_options;
1560 };
1561 
1562 // Get malloc/free history of a memory address.
1563 class CommandObjectMemoryHistory : public CommandObjectParsed {
1564 public:
1565   CommandObjectMemoryHistory(CommandInterpreter &interpreter)
1566       : CommandObjectParsed(interpreter, "memory history",
1567                             "Print recorded stack traces for "
1568                             "allocation/deallocation events "
1569                             "associated with an address.",
1570                             nullptr,
1571                             eCommandRequiresTarget | eCommandRequiresProcess |
1572                                 eCommandProcessMustBePaused |
1573                                 eCommandProcessMustBeLaunched) {
1574     CommandArgumentEntry arg1;
1575     CommandArgumentData addr_arg;
1576 
1577     // Define the first (and only) variant of this arg.
1578     addr_arg.arg_type = eArgTypeAddress;
1579     addr_arg.arg_repetition = eArgRepeatPlain;
1580 
1581     // There is only one variant this argument could be; put it into the
1582     // argument entry.
1583     arg1.push_back(addr_arg);
1584 
1585     // Push the data for the first argument into the m_arguments vector.
1586     m_arguments.push_back(arg1);
1587   }
1588 
1589   ~CommandObjectMemoryHistory() override = default;
1590 
1591   std::optional<std::string> GetRepeatCommand(Args &current_command_args,
1592                                               uint32_t index) override {
1593     return m_cmd_name;
1594   }
1595 
1596 protected:
1597   bool DoExecute(Args &command, CommandReturnObject &result) override {
1598     const size_t argc = command.GetArgumentCount();
1599 
1600     if (argc == 0 || argc > 1) {
1601       result.AppendErrorWithFormat("%s takes an address expression",
1602                                    m_cmd_name.c_str());
1603       return false;
1604     }
1605 
1606     Status error;
1607     lldb::addr_t addr = OptionArgParser::ToAddress(
1608         &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1609 
1610     if (addr == LLDB_INVALID_ADDRESS) {
1611       result.AppendError("invalid address expression");
1612       result.AppendError(error.AsCString());
1613       return false;
1614     }
1615 
1616     Stream *output_stream = &result.GetOutputStream();
1617 
1618     const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1619     const MemoryHistorySP &memory_history =
1620         MemoryHistory::FindPlugin(process_sp);
1621 
1622     if (!memory_history) {
1623       result.AppendError("no available memory history provider");
1624       return false;
1625     }
1626 
1627     HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1628 
1629     const bool stop_format = false;
1630     for (auto thread : thread_list) {
1631       thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
1632     }
1633 
1634     result.SetStatus(eReturnStatusSuccessFinishResult);
1635 
1636     return true;
1637   }
1638 };
1639 
1640 // CommandObjectMemoryRegion
1641 #pragma mark CommandObjectMemoryRegion
1642 
1643 #define LLDB_OPTIONS_memory_region
1644 #include "CommandOptions.inc"
1645 
1646 class CommandObjectMemoryRegion : public CommandObjectParsed {
1647 public:
1648   class OptionGroupMemoryRegion : public OptionGroup {
1649   public:
1650     OptionGroupMemoryRegion() : m_all(false, false) {}
1651 
1652     ~OptionGroupMemoryRegion() override = default;
1653 
1654     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1655       return llvm::ArrayRef(g_memory_region_options);
1656     }
1657 
1658     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1659                           ExecutionContext *execution_context) override {
1660       Status status;
1661       const int short_option = g_memory_region_options[option_idx].short_option;
1662 
1663       switch (short_option) {
1664       case 'a':
1665         m_all.SetCurrentValue(true);
1666         m_all.SetOptionWasSet();
1667         break;
1668       default:
1669         llvm_unreachable("Unimplemented option");
1670       }
1671 
1672       return status;
1673     }
1674 
1675     void OptionParsingStarting(ExecutionContext *execution_context) override {
1676       m_all.Clear();
1677     }
1678 
1679     OptionValueBoolean m_all;
1680   };
1681 
1682   CommandObjectMemoryRegion(CommandInterpreter &interpreter)
1683       : CommandObjectParsed(interpreter, "memory region",
1684                             "Get information on the memory region containing "
1685                             "an address in the current target process.",
1686                             "memory region <address-expression> (or --all)",
1687                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1688                                 eCommandProcessMustBeLaunched) {
1689     // Address in option set 1.
1690     m_arguments.push_back(CommandArgumentEntry{CommandArgumentData(
1691         eArgTypeAddressOrExpression, eArgRepeatPlain, LLDB_OPT_SET_1)});
1692     // "--all" will go in option set 2.
1693     m_option_group.Append(&m_memory_region_options);
1694     m_option_group.Finalize();
1695   }
1696 
1697   ~CommandObjectMemoryRegion() override = default;
1698 
1699   Options *GetOptions() override { return &m_option_group; }
1700 
1701 protected:
1702   void DumpRegion(CommandReturnObject &result, Target &target,
1703                   const MemoryRegionInfo &range_info, lldb::addr_t load_addr) {
1704     lldb_private::Address addr;
1705     ConstString section_name;
1706     if (target.ResolveLoadAddress(load_addr, addr)) {
1707       SectionSP section_sp(addr.GetSection());
1708       if (section_sp) {
1709         // Got the top most section, not the deepest section
1710         while (section_sp->GetParent())
1711           section_sp = section_sp->GetParent();
1712         section_name = section_sp->GetName();
1713       }
1714     }
1715 
1716     ConstString name = range_info.GetName();
1717     result.AppendMessageWithFormatv(
1718         "[{0:x16}-{1:x16}) {2:r}{3:w}{4:x}{5}{6}{7}{8}",
1719         range_info.GetRange().GetRangeBase(),
1720         range_info.GetRange().GetRangeEnd(), range_info.GetReadable(),
1721         range_info.GetWritable(), range_info.GetExecutable(), name ? " " : "",
1722         name, section_name ? " " : "", section_name);
1723     MemoryRegionInfo::OptionalBool memory_tagged = range_info.GetMemoryTagged();
1724     if (memory_tagged == MemoryRegionInfo::OptionalBool::eYes)
1725       result.AppendMessage("memory tagging: enabled");
1726 
1727     const std::optional<std::vector<addr_t>> &dirty_page_list =
1728         range_info.GetDirtyPageList();
1729     if (dirty_page_list) {
1730       const size_t page_count = dirty_page_list->size();
1731       result.AppendMessageWithFormat(
1732           "Modified memory (dirty) page list provided, %zu entries.\n",
1733           page_count);
1734       if (page_count > 0) {
1735         bool print_comma = false;
1736         result.AppendMessageWithFormat("Dirty pages: ");
1737         for (size_t i = 0; i < page_count; i++) {
1738           if (print_comma)
1739             result.AppendMessageWithFormat(", ");
1740           else
1741             print_comma = true;
1742           result.AppendMessageWithFormat("0x%" PRIx64, (*dirty_page_list)[i]);
1743         }
1744         result.AppendMessageWithFormat(".\n");
1745       }
1746     }
1747   }
1748 
1749   bool DoExecute(Args &command, CommandReturnObject &result) override {
1750     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1751     if (!process_sp) {
1752       m_prev_end_addr = LLDB_INVALID_ADDRESS;
1753       result.AppendError("invalid process");
1754       return false;
1755     }
1756 
1757     Status error;
1758     lldb::addr_t load_addr = m_prev_end_addr;
1759     m_prev_end_addr = LLDB_INVALID_ADDRESS;
1760 
1761     const size_t argc = command.GetArgumentCount();
1762     const lldb::ABISP &abi = process_sp->GetABI();
1763 
1764     if (argc == 1) {
1765       if (m_memory_region_options.m_all) {
1766         result.AppendError(
1767             "The \"--all\" option cannot be used when an address "
1768             "argument is given");
1769         return false;
1770       }
1771 
1772       auto load_addr_str = command[0].ref();
1773       load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1774                                              LLDB_INVALID_ADDRESS, &error);
1775       if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1776         result.AppendErrorWithFormat("invalid address argument \"%s\": %s\n",
1777                                      command[0].c_str(), error.AsCString());
1778         return false;
1779       }
1780     } else if (argc > 1 ||
1781                // When we're repeating the command, the previous end address is
1782                // used for load_addr. If that was 0xF...F then we must have
1783                // reached the end of memory.
1784                (argc == 0 && !m_memory_region_options.m_all &&
1785                 load_addr == LLDB_INVALID_ADDRESS) ||
1786                // If the target has non-address bits (tags, limited virtual
1787                // address size, etc.), the end of mappable memory will be lower
1788                // than that. So if we find any non-address bit set, we must be
1789                // at the end of the mappable range.
1790                (abi && (abi->FixAnyAddress(load_addr) != load_addr))) {
1791       result.AppendErrorWithFormat(
1792           "'%s' takes one argument or \"--all\" option:\nUsage: %s\n",
1793           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1794       return false;
1795     }
1796 
1797     // Is is important that we track the address used to request the region as
1798     // this will give the correct section name in the case that regions overlap.
1799     // On Windows we get mutliple regions that start at the same place but are
1800     // different sizes and refer to different sections.
1801     std::vector<std::pair<lldb_private::MemoryRegionInfo, lldb::addr_t>>
1802         region_list;
1803     if (m_memory_region_options.m_all) {
1804       // We don't use GetMemoryRegions here because it doesn't include unmapped
1805       // areas like repeating the command would. So instead, emulate doing that.
1806       lldb::addr_t addr = 0;
1807       while (error.Success() && addr != LLDB_INVALID_ADDRESS &&
1808              // When there are non-address bits the last range will not extend
1809              // to LLDB_INVALID_ADDRESS but to the max virtual address.
1810              // This prevents us looping forever if that is the case.
1811              (!abi || (abi->FixAnyAddress(addr) == addr))) {
1812         lldb_private::MemoryRegionInfo region_info;
1813         error = process_sp->GetMemoryRegionInfo(addr, region_info);
1814 
1815         if (error.Success()) {
1816           region_list.push_back({region_info, addr});
1817           addr = region_info.GetRange().GetRangeEnd();
1818         }
1819       }
1820     } else {
1821       lldb_private::MemoryRegionInfo region_info;
1822       error = process_sp->GetMemoryRegionInfo(load_addr, region_info);
1823       if (error.Success())
1824         region_list.push_back({region_info, load_addr});
1825     }
1826 
1827     if (error.Success()) {
1828       for (std::pair<MemoryRegionInfo, addr_t> &range : region_list) {
1829         DumpRegion(result, process_sp->GetTarget(), range.first, range.second);
1830         m_prev_end_addr = range.first.GetRange().GetRangeEnd();
1831       }
1832 
1833       result.SetStatus(eReturnStatusSuccessFinishResult);
1834       return true;
1835     }
1836 
1837     result.AppendErrorWithFormat("%s\n", error.AsCString());
1838     return false;
1839   }
1840 
1841   std::optional<std::string> GetRepeatCommand(Args &current_command_args,
1842                                               uint32_t index) override {
1843     // If we repeat this command, repeat it without any arguments so we can
1844     // show the next memory range
1845     return m_cmd_name;
1846   }
1847 
1848   lldb::addr_t m_prev_end_addr = LLDB_INVALID_ADDRESS;
1849 
1850   OptionGroupOptions m_option_group;
1851   OptionGroupMemoryRegion m_memory_region_options;
1852 };
1853 
1854 // CommandObjectMemory
1855 
1856 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter)
1857     : CommandObjectMultiword(
1858           interpreter, "memory",
1859           "Commands for operating on memory in the current target process.",
1860           "memory <subcommand> [<subcommand-options>]") {
1861   LoadSubCommand("find",
1862                  CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1863   LoadSubCommand("read",
1864                  CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1865   LoadSubCommand("write",
1866                  CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1867   LoadSubCommand("history",
1868                  CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1869   LoadSubCommand("region",
1870                  CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
1871   LoadSubCommand("tag",
1872                  CommandObjectSP(new CommandObjectMemoryTag(interpreter)));
1873 }
1874 
1875 CommandObjectMemory::~CommandObjectMemory() = default;
1876