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/CommandReturnObject.h"
17 #include "lldb/Interpreter/OptionArgParser.h"
18 #include "lldb/Interpreter/OptionGroupFormat.h"
19 #include "lldb/Interpreter/OptionGroupMemoryTag.h"
20 #include "lldb/Interpreter/OptionGroupOutputFile.h"
21 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
22 #include "lldb/Interpreter/OptionValueLanguage.h"
23 #include "lldb/Interpreter/OptionValueString.h"
24 #include "lldb/Interpreter/Options.h"
25 #include "lldb/Symbol/SymbolFile.h"
26 #include "lldb/Symbol/TypeList.h"
27 #include "lldb/Target/ABI.h"
28 #include "lldb/Target/Language.h"
29 #include "lldb/Target/MemoryHistory.h"
30 #include "lldb/Target/MemoryRegionInfo.h"
31 #include "lldb/Target/Process.h"
32 #include "lldb/Target/StackFrame.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "lldb/Utility/Args.h"
36 #include "lldb/Utility/DataBufferHeap.h"
37 #include "lldb/Utility/StreamString.h"
38 #include "llvm/Support/MathExtras.h"
39 #include <cinttypes>
40 #include <memory>
41 
42 using namespace lldb;
43 using namespace lldb_private;
44 
45 #define LLDB_OPTIONS_memory_read
46 #include "CommandOptions.inc"
47 
48 class OptionGroupReadMemory : public OptionGroup {
49 public:
50   OptionGroupReadMemory()
51       : m_num_per_line(1, 1), m_offset(0, 0),
52         m_language_for_type(eLanguageTypeUnknown) {}
53 
54   ~OptionGroupReadMemory() override = default;
55 
56   llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
57     return llvm::makeArrayRef(g_memory_read_options);
58   }
59 
60   Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
61                         ExecutionContext *execution_context) override {
62     Status error;
63     const int short_option = g_memory_read_options[option_idx].short_option;
64 
65     switch (short_option) {
66     case 'l':
67       error = m_num_per_line.SetValueFromString(option_value);
68       if (m_num_per_line.GetCurrentValue() == 0)
69         error.SetErrorStringWithFormat(
70             "invalid value for --num-per-line option '%s'",
71             option_value.str().c_str());
72       break;
73 
74     case 'b':
75       m_output_as_binary = true;
76       break;
77 
78     case 't':
79       error = m_view_as_type.SetValueFromString(option_value);
80       break;
81 
82     case 'r':
83       m_force = true;
84       break;
85 
86     case 'x':
87       error = m_language_for_type.SetValueFromString(option_value);
88       break;
89 
90     case 'E':
91       error = m_offset.SetValueFromString(option_value);
92       break;
93 
94     default:
95       llvm_unreachable("Unimplemented option");
96     }
97     return error;
98   }
99 
100   void OptionParsingStarting(ExecutionContext *execution_context) override {
101     m_num_per_line.Clear();
102     m_output_as_binary = false;
103     m_view_as_type.Clear();
104     m_force = false;
105     m_offset.Clear();
106     m_language_for_type.Clear();
107   }
108 
109   Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) {
110     Status error;
111     OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue();
112     OptionValueUInt64 &count_value = format_options.GetCountValue();
113     const bool byte_size_option_set = byte_size_value.OptionWasSet();
114     const bool num_per_line_option_set = m_num_per_line.OptionWasSet();
115     const bool count_option_set = format_options.GetCountValue().OptionWasSet();
116 
117     switch (format_options.GetFormat()) {
118     default:
119       break;
120 
121     case eFormatBoolean:
122       if (!byte_size_option_set)
123         byte_size_value = 1;
124       if (!num_per_line_option_set)
125         m_num_per_line = 1;
126       if (!count_option_set)
127         format_options.GetCountValue() = 8;
128       break;
129 
130     case eFormatCString:
131       break;
132 
133     case eFormatInstruction:
134       if (count_option_set)
135         byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
136       m_num_per_line = 1;
137       break;
138 
139     case eFormatAddressInfo:
140       if (!byte_size_option_set)
141         byte_size_value = target->GetArchitecture().GetAddressByteSize();
142       m_num_per_line = 1;
143       if (!count_option_set)
144         format_options.GetCountValue() = 8;
145       break;
146 
147     case eFormatPointer:
148       byte_size_value = target->GetArchitecture().GetAddressByteSize();
149       if (!num_per_line_option_set)
150         m_num_per_line = 4;
151       if (!count_option_set)
152         format_options.GetCountValue() = 8;
153       break;
154 
155     case eFormatBinary:
156     case eFormatFloat:
157     case eFormatOctal:
158     case eFormatDecimal:
159     case eFormatEnum:
160     case eFormatUnicode8:
161     case eFormatUnicode16:
162     case eFormatUnicode32:
163     case eFormatUnsigned:
164     case eFormatHexFloat:
165       if (!byte_size_option_set)
166         byte_size_value = 4;
167       if (!num_per_line_option_set)
168         m_num_per_line = 1;
169       if (!count_option_set)
170         format_options.GetCountValue() = 8;
171       break;
172 
173     case eFormatBytes:
174     case eFormatBytesWithASCII:
175       if (byte_size_option_set) {
176         if (byte_size_value > 1)
177           error.SetErrorStringWithFormat(
178               "display format (bytes/bytes with ASCII) conflicts with the "
179               "specified byte size %" PRIu64 "\n"
180               "\tconsider using a different display format or don't specify "
181               "the byte size.",
182               byte_size_value.GetCurrentValue());
183       } else
184         byte_size_value = 1;
185       if (!num_per_line_option_set)
186         m_num_per_line = 16;
187       if (!count_option_set)
188         format_options.GetCountValue() = 32;
189       break;
190 
191     case eFormatCharArray:
192     case eFormatChar:
193     case eFormatCharPrintable:
194       if (!byte_size_option_set)
195         byte_size_value = 1;
196       if (!num_per_line_option_set)
197         m_num_per_line = 32;
198       if (!count_option_set)
199         format_options.GetCountValue() = 64;
200       break;
201 
202     case eFormatComplex:
203       if (!byte_size_option_set)
204         byte_size_value = 8;
205       if (!num_per_line_option_set)
206         m_num_per_line = 1;
207       if (!count_option_set)
208         format_options.GetCountValue() = 8;
209       break;
210 
211     case eFormatComplexInteger:
212       if (!byte_size_option_set)
213         byte_size_value = 8;
214       if (!num_per_line_option_set)
215         m_num_per_line = 1;
216       if (!count_option_set)
217         format_options.GetCountValue() = 8;
218       break;
219 
220     case eFormatHex:
221       if (!byte_size_option_set)
222         byte_size_value = 4;
223       if (!num_per_line_option_set) {
224         switch (byte_size_value) {
225         case 1:
226         case 2:
227           m_num_per_line = 8;
228           break;
229         case 4:
230           m_num_per_line = 4;
231           break;
232         case 8:
233           m_num_per_line = 2;
234           break;
235         default:
236           m_num_per_line = 1;
237           break;
238         }
239       }
240       if (!count_option_set)
241         count_value = 8;
242       break;
243 
244     case eFormatVectorOfChar:
245     case eFormatVectorOfSInt8:
246     case eFormatVectorOfUInt8:
247     case eFormatVectorOfSInt16:
248     case eFormatVectorOfUInt16:
249     case eFormatVectorOfSInt32:
250     case eFormatVectorOfUInt32:
251     case eFormatVectorOfSInt64:
252     case eFormatVectorOfUInt64:
253     case eFormatVectorOfFloat16:
254     case eFormatVectorOfFloat32:
255     case eFormatVectorOfFloat64:
256     case eFormatVectorOfUInt128:
257       if (!byte_size_option_set)
258         byte_size_value = 128;
259       if (!num_per_line_option_set)
260         m_num_per_line = 1;
261       if (!count_option_set)
262         count_value = 4;
263       break;
264     }
265     return error;
266   }
267 
268   bool AnyOptionWasSet() const {
269     return m_num_per_line.OptionWasSet() || m_output_as_binary ||
270            m_view_as_type.OptionWasSet() || m_offset.OptionWasSet() ||
271            m_language_for_type.OptionWasSet();
272   }
273 
274   OptionValueUInt64 m_num_per_line;
275   bool m_output_as_binary = false;
276   OptionValueString m_view_as_type;
277   bool m_force;
278   OptionValueUInt64 m_offset;
279   OptionValueLanguage m_language_for_type;
280 };
281 
282 // Read memory from the inferior process
283 class CommandObjectMemoryRead : public CommandObjectParsed {
284 public:
285   CommandObjectMemoryRead(CommandInterpreter &interpreter)
286       : CommandObjectParsed(
287             interpreter, "memory read",
288             "Read from the memory of the current target process.", nullptr,
289             eCommandRequiresTarget | eCommandProcessMustBePaused),
290         m_format_options(eFormatBytesWithASCII, 1, 8),
291 
292         m_prev_format_options(eFormatBytesWithASCII, 1, 8) {
293     CommandArgumentEntry arg1;
294     CommandArgumentEntry arg2;
295     CommandArgumentData start_addr_arg;
296     CommandArgumentData end_addr_arg;
297 
298     // Define the first (and only) variant of this arg.
299     start_addr_arg.arg_type = eArgTypeAddressOrExpression;
300     start_addr_arg.arg_repetition = eArgRepeatPlain;
301 
302     // There is only one variant this argument could be; put it into the
303     // argument entry.
304     arg1.push_back(start_addr_arg);
305 
306     // Define the first (and only) variant of this arg.
307     end_addr_arg.arg_type = eArgTypeAddressOrExpression;
308     end_addr_arg.arg_repetition = eArgRepeatOptional;
309 
310     // There is only one variant this argument could be; put it into the
311     // argument entry.
312     arg2.push_back(end_addr_arg);
313 
314     // Push the data for the first argument into the m_arguments vector.
315     m_arguments.push_back(arg1);
316     m_arguments.push_back(arg2);
317 
318     // Add the "--format" and "--count" options to group 1 and 3
319     m_option_group.Append(&m_format_options,
320                           OptionGroupFormat::OPTION_GROUP_FORMAT |
321                               OptionGroupFormat::OPTION_GROUP_COUNT,
322                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
323     m_option_group.Append(&m_format_options,
324                           OptionGroupFormat::OPTION_GROUP_GDB_FMT,
325                           LLDB_OPT_SET_1 | LLDB_OPT_SET_3);
326     // Add the "--size" option to group 1 and 2
327     m_option_group.Append(&m_format_options,
328                           OptionGroupFormat::OPTION_GROUP_SIZE,
329                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
330     m_option_group.Append(&m_memory_options);
331     m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL,
332                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
333     m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
334     m_option_group.Append(&m_memory_tag_options, LLDB_OPT_SET_ALL,
335                           LLDB_OPT_SET_ALL);
336     m_option_group.Finalize();
337   }
338 
339   ~CommandObjectMemoryRead() override = default;
340 
341   Options *GetOptions() override { return &m_option_group; }
342 
343   llvm::Optional<std::string> GetRepeatCommand(Args &current_command_args,
344                                                uint32_t index) override {
345     return m_cmd_name;
346   }
347 
348 protected:
349   bool DoExecute(Args &command, CommandReturnObject &result) override {
350     // No need to check "target" for validity as eCommandRequiresTarget ensures
351     // it is valid
352     Target *target = m_exe_ctx.GetTargetPtr();
353 
354     const size_t argc = command.GetArgumentCount();
355 
356     if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
357       result.AppendErrorWithFormat("%s takes a start address expression with "
358                                    "an optional end address expression.\n",
359                                    m_cmd_name.c_str());
360       result.AppendWarning("Expressions should be quoted if they contain "
361                            "spaces or other special characters.");
362       return false;
363     }
364 
365     CompilerType compiler_type;
366     Status error;
367 
368     const char *view_as_type_cstr =
369         m_memory_options.m_view_as_type.GetCurrentValue();
370     if (view_as_type_cstr && view_as_type_cstr[0]) {
371       // We are viewing memory as a type
372 
373       const bool exact_match = false;
374       TypeList type_list;
375       uint32_t reference_count = 0;
376       uint32_t pointer_count = 0;
377       size_t idx;
378 
379 #define ALL_KEYWORDS                                                           \
380   KEYWORD("const")                                                             \
381   KEYWORD("volatile")                                                          \
382   KEYWORD("restrict")                                                          \
383   KEYWORD("struct")                                                            \
384   KEYWORD("class")                                                             \
385   KEYWORD("union")
386 
387 #define KEYWORD(s) s,
388       static const char *g_keywords[] = {ALL_KEYWORDS};
389 #undef KEYWORD
390 
391 #define KEYWORD(s) (sizeof(s) - 1),
392       static const int g_keyword_lengths[] = {ALL_KEYWORDS};
393 #undef KEYWORD
394 
395 #undef ALL_KEYWORDS
396 
397       static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
398       std::string type_str(view_as_type_cstr);
399 
400       // Remove all instances of g_keywords that are followed by spaces
401       for (size_t i = 0; i < g_num_keywords; ++i) {
402         const char *keyword = g_keywords[i];
403         int keyword_len = g_keyword_lengths[i];
404 
405         idx = 0;
406         while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
407           if (type_str[idx + keyword_len] == ' ' ||
408               type_str[idx + keyword_len] == '\t') {
409             type_str.erase(idx, keyword_len + 1);
410             idx = 0;
411           } else {
412             idx += keyword_len;
413           }
414         }
415       }
416       bool done = type_str.empty();
417       //
418       idx = type_str.find_first_not_of(" \t");
419       if (idx > 0 && idx != std::string::npos)
420         type_str.erase(0, idx);
421       while (!done) {
422         // Strip trailing spaces
423         if (type_str.empty())
424           done = true;
425         else {
426           switch (type_str[type_str.size() - 1]) {
427           case '*':
428             ++pointer_count;
429             LLVM_FALLTHROUGH;
430           case ' ':
431           case '\t':
432             type_str.erase(type_str.size() - 1);
433             break;
434 
435           case '&':
436             if (reference_count == 0) {
437               reference_count = 1;
438               type_str.erase(type_str.size() - 1);
439             } else {
440               result.AppendErrorWithFormat("invalid type string: '%s'\n",
441                                            view_as_type_cstr);
442               return false;
443             }
444             break;
445 
446           default:
447             done = true;
448             break;
449           }
450         }
451       }
452 
453       llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
454       ConstString lookup_type_name(type_str.c_str());
455       StackFrame *frame = m_exe_ctx.GetFramePtr();
456       ModuleSP search_first;
457       if (frame) {
458         search_first = frame->GetSymbolContext(eSymbolContextModule).module_sp;
459       }
460       target->GetImages().FindTypes(search_first.get(), lookup_type_name,
461                                     exact_match, 1, searched_symbol_files,
462                                     type_list);
463 
464       if (type_list.GetSize() == 0 && lookup_type_name.GetCString()) {
465         LanguageType language_for_type =
466             m_memory_options.m_language_for_type.GetCurrentValue();
467         std::set<LanguageType> languages_to_check;
468         if (language_for_type != eLanguageTypeUnknown) {
469           languages_to_check.insert(language_for_type);
470         } else {
471           languages_to_check = Language::GetSupportedLanguages();
472         }
473 
474         std::set<CompilerType> user_defined_types;
475         for (auto lang : languages_to_check) {
476           if (auto *persistent_vars =
477                   target->GetPersistentExpressionStateForLanguage(lang)) {
478             if (llvm::Optional<CompilerType> type =
479                     persistent_vars->GetCompilerTypeFromPersistentDecl(
480                         lookup_type_name)) {
481               user_defined_types.emplace(*type);
482             }
483           }
484         }
485 
486         if (user_defined_types.size() > 1) {
487           result.AppendErrorWithFormat(
488               "Mutiple types found matching raw type '%s', please disambiguate "
489               "by specifying the language with -x",
490               lookup_type_name.GetCString());
491           return false;
492         }
493 
494         if (user_defined_types.size() == 1) {
495           compiler_type = *user_defined_types.begin();
496         }
497       }
498 
499       if (!compiler_type.IsValid()) {
500         if (type_list.GetSize() == 0) {
501           result.AppendErrorWithFormat("unable to find any types that match "
502                                        "the raw type '%s' for full type '%s'\n",
503                                        lookup_type_name.GetCString(),
504                                        view_as_type_cstr);
505           return false;
506         } else {
507           TypeSP type_sp(type_list.GetTypeAtIndex(0));
508           compiler_type = type_sp->GetFullCompilerType();
509         }
510       }
511 
512       while (pointer_count > 0) {
513         CompilerType pointer_type = compiler_type.GetPointerType();
514         if (pointer_type.IsValid())
515           compiler_type = pointer_type;
516         else {
517           result.AppendError("unable make a pointer type\n");
518           return false;
519         }
520         --pointer_count;
521       }
522 
523       llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr);
524       if (!size) {
525         result.AppendErrorWithFormat(
526             "unable to get the byte size of the type '%s'\n",
527             view_as_type_cstr);
528         return false;
529       }
530       m_format_options.GetByteSizeValue() = *size;
531 
532       if (!m_format_options.GetCountValue().OptionWasSet())
533         m_format_options.GetCountValue() = 1;
534     } else {
535       error = m_memory_options.FinalizeSettings(target, m_format_options);
536     }
537 
538     // Look for invalid combinations of settings
539     if (error.Fail()) {
540       result.AppendError(error.AsCString());
541       return false;
542     }
543 
544     lldb::addr_t addr;
545     size_t total_byte_size = 0;
546     if (argc == 0) {
547       // Use the last address and byte size and all options as they were if no
548       // options have been set
549       addr = m_next_addr;
550       total_byte_size = m_prev_byte_size;
551       compiler_type = m_prev_compiler_type;
552       if (!m_format_options.AnyOptionWasSet() &&
553           !m_memory_options.AnyOptionWasSet() &&
554           !m_outfile_options.AnyOptionWasSet() &&
555           !m_varobj_options.AnyOptionWasSet() &&
556           !m_memory_tag_options.AnyOptionWasSet()) {
557         m_format_options = m_prev_format_options;
558         m_memory_options = m_prev_memory_options;
559         m_outfile_options = m_prev_outfile_options;
560         m_varobj_options = m_prev_varobj_options;
561         m_memory_tag_options = m_prev_memory_tag_options;
562       }
563     }
564 
565     size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
566 
567     // TODO For non-8-bit byte addressable architectures this needs to be
568     // revisited to fully support all lldb's range of formatting options.
569     // Furthermore code memory reads (for those architectures) will not be
570     // correctly formatted even w/o formatting options.
571     size_t item_byte_size =
572         target->GetArchitecture().GetDataByteSize() > 1
573             ? target->GetArchitecture().GetDataByteSize()
574             : m_format_options.GetByteSizeValue().GetCurrentValue();
575 
576     const size_t num_per_line =
577         m_memory_options.m_num_per_line.GetCurrentValue();
578 
579     if (total_byte_size == 0) {
580       total_byte_size = item_count * item_byte_size;
581       if (total_byte_size == 0)
582         total_byte_size = 32;
583     }
584 
585     if (argc > 0)
586       addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref(),
587                                         LLDB_INVALID_ADDRESS, &error);
588 
589     if (addr == LLDB_INVALID_ADDRESS) {
590       result.AppendError("invalid start address expression.");
591       result.AppendError(error.AsCString());
592       return false;
593     }
594 
595     ABISP abi = m_exe_ctx.GetProcessPtr()->GetABI();
596     if (abi)
597       addr = abi->FixDataAddress(addr);
598 
599     if (argc == 2) {
600       lldb::addr_t end_addr = OptionArgParser::ToAddress(
601           &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, nullptr);
602       if (end_addr != LLDB_INVALID_ADDRESS && abi)
603         end_addr = abi->FixDataAddress(end_addr);
604 
605       if (end_addr == LLDB_INVALID_ADDRESS) {
606         result.AppendError("invalid end address expression.");
607         result.AppendError(error.AsCString());
608         return false;
609       } else if (end_addr <= addr) {
610         result.AppendErrorWithFormat(
611             "end address (0x%" PRIx64
612             ") must be greater than the start address (0x%" PRIx64 ").\n",
613             end_addr, addr);
614         return false;
615       } else if (m_format_options.GetCountValue().OptionWasSet()) {
616         result.AppendErrorWithFormat(
617             "specify either the end address (0x%" PRIx64
618             ") or the count (--count %" PRIu64 "), not both.\n",
619             end_addr, (uint64_t)item_count);
620         return false;
621       }
622 
623       total_byte_size = end_addr - addr;
624       item_count = total_byte_size / item_byte_size;
625     }
626 
627     uint32_t max_unforced_size = target->GetMaximumMemReadSize();
628 
629     if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
630       result.AppendErrorWithFormat(
631           "Normally, \'memory read\' will not read over %" PRIu32
632           " bytes of data.\n",
633           max_unforced_size);
634       result.AppendErrorWithFormat(
635           "Please use --force to override this restriction just once.\n");
636       result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
637                                    "will often need a larger limit.\n");
638       return false;
639     }
640 
641     WritableDataBufferSP data_sp;
642     size_t bytes_read = 0;
643     if (compiler_type.GetOpaqueQualType()) {
644       // Make sure we don't display our type as ASCII bytes like the default
645       // memory read
646       if (!m_format_options.GetFormatValue().OptionWasSet())
647         m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
648 
649       llvm::Optional<uint64_t> size = compiler_type.GetByteSize(nullptr);
650       if (!size) {
651         result.AppendError("can't get size of type");
652         return false;
653       }
654       bytes_read = *size * m_format_options.GetCountValue().GetCurrentValue();
655 
656       if (argc > 0)
657         addr = addr + (*size * m_memory_options.m_offset.GetCurrentValue());
658     } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
659                eFormatCString) {
660       data_sp = std::make_shared<DataBufferHeap>(total_byte_size, '\0');
661       if (data_sp->GetBytes() == nullptr) {
662         result.AppendErrorWithFormat(
663             "can't allocate 0x%" PRIx32
664             " bytes for the memory read buffer, specify a smaller size to read",
665             (uint32_t)total_byte_size);
666         return false;
667       }
668 
669       Address address(addr, nullptr);
670       bytes_read = target->ReadMemory(address, data_sp->GetBytes(),
671                                       data_sp->GetByteSize(), error, true);
672       if (bytes_read == 0) {
673         const char *error_cstr = error.AsCString();
674         if (error_cstr && error_cstr[0]) {
675           result.AppendError(error_cstr);
676         } else {
677           result.AppendErrorWithFormat(
678               "failed to read memory from 0x%" PRIx64 ".\n", addr);
679         }
680         return false;
681       }
682 
683       if (bytes_read < total_byte_size)
684         result.AppendWarningWithFormat(
685             "Not all bytes (%" PRIu64 "/%" PRIu64
686             ") were able to be read from 0x%" PRIx64 ".\n",
687             (uint64_t)bytes_read, (uint64_t)total_byte_size, addr);
688     } else {
689       // we treat c-strings as a special case because they do not have a fixed
690       // size
691       if (m_format_options.GetByteSizeValue().OptionWasSet() &&
692           !m_format_options.HasGDBFormat())
693         item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
694       else
695         item_byte_size = target->GetMaximumSizeOfStringSummary();
696       if (!m_format_options.GetCountValue().OptionWasSet())
697         item_count = 1;
698       data_sp = std::make_shared<DataBufferHeap>(
699           (item_byte_size + 1) * item_count,
700           '\0'); // account for NULLs as necessary
701       if (data_sp->GetBytes() == nullptr) {
702         result.AppendErrorWithFormat(
703             "can't allocate 0x%" PRIx64
704             " bytes for the memory read buffer, specify a smaller size to read",
705             (uint64_t)((item_byte_size + 1) * item_count));
706         return false;
707       }
708       uint8_t *data_ptr = data_sp->GetBytes();
709       auto data_addr = addr;
710       auto count = item_count;
711       item_count = 0;
712       bool break_on_no_NULL = false;
713       while (item_count < count) {
714         std::string buffer;
715         buffer.resize(item_byte_size + 1, 0);
716         Status error;
717         size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
718                                                     item_byte_size + 1, error);
719         if (error.Fail()) {
720           result.AppendErrorWithFormat(
721               "failed to read memory from 0x%" PRIx64 ".\n", addr);
722           return false;
723         }
724 
725         if (item_byte_size == read) {
726           result.AppendWarningWithFormat(
727               "unable to find a NULL terminated string at 0x%" PRIx64
728               ". Consider increasing the maximum read length.\n",
729               data_addr);
730           --read;
731           break_on_no_NULL = true;
732         } else
733           ++read; // account for final NULL byte
734 
735         memcpy(data_ptr, &buffer[0], read);
736         data_ptr += read;
737         data_addr += read;
738         bytes_read += read;
739         item_count++; // if we break early we know we only read item_count
740                       // strings
741 
742         if (break_on_no_NULL)
743           break;
744       }
745       data_sp =
746           std::make_shared<DataBufferHeap>(data_sp->GetBytes(), bytes_read + 1);
747     }
748 
749     m_next_addr = addr + bytes_read;
750     m_prev_byte_size = bytes_read;
751     m_prev_format_options = m_format_options;
752     m_prev_memory_options = m_memory_options;
753     m_prev_outfile_options = m_outfile_options;
754     m_prev_varobj_options = m_varobj_options;
755     m_prev_memory_tag_options = m_memory_tag_options;
756     m_prev_compiler_type = compiler_type;
757 
758     std::unique_ptr<Stream> output_stream_storage;
759     Stream *output_stream_p = nullptr;
760     const FileSpec &outfile_spec =
761         m_outfile_options.GetFile().GetCurrentValue();
762 
763     std::string path = outfile_spec.GetPath();
764     if (outfile_spec) {
765 
766       File::OpenOptions open_options =
767           File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate;
768       const bool append = m_outfile_options.GetAppend().GetCurrentValue();
769       open_options |=
770           append ? File::eOpenOptionAppend : File::eOpenOptionTruncate;
771 
772       auto outfile = FileSystem::Instance().Open(outfile_spec, open_options);
773 
774       if (outfile) {
775         auto outfile_stream_up =
776             std::make_unique<StreamFile>(std::move(outfile.get()));
777         if (m_memory_options.m_output_as_binary) {
778           const size_t bytes_written =
779               outfile_stream_up->Write(data_sp->GetBytes(), bytes_read);
780           if (bytes_written > 0) {
781             result.GetOutputStream().Printf(
782                 "%zi bytes %s to '%s'\n", bytes_written,
783                 append ? "appended" : "written", path.c_str());
784             return true;
785           } else {
786             result.AppendErrorWithFormat("Failed to write %" PRIu64
787                                          " bytes to '%s'.\n",
788                                          (uint64_t)bytes_read, path.c_str());
789             return false;
790           }
791         } else {
792           // We are going to write ASCII to the file just point the
793           // output_stream to our outfile_stream...
794           output_stream_storage = std::move(outfile_stream_up);
795           output_stream_p = output_stream_storage.get();
796         }
797       } else {
798         result.AppendErrorWithFormat("Failed to open file '%s' for %s:\n",
799                                      path.c_str(), append ? "append" : "write");
800 
801         result.AppendError(llvm::toString(outfile.takeError()));
802         return false;
803       }
804     } else {
805       output_stream_p = &result.GetOutputStream();
806     }
807 
808     ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
809     if (compiler_type.GetOpaqueQualType()) {
810       for (uint32_t i = 0; i < item_count; ++i) {
811         addr_t item_addr = addr + (i * item_byte_size);
812         Address address(item_addr);
813         StreamString name_strm;
814         name_strm.Printf("0x%" PRIx64, item_addr);
815         ValueObjectSP valobj_sp(ValueObjectMemory::Create(
816             exe_scope, name_strm.GetString(), address, compiler_type));
817         if (valobj_sp) {
818           Format format = m_format_options.GetFormat();
819           if (format != eFormatDefault)
820             valobj_sp->SetFormat(format);
821 
822           DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
823               eLanguageRuntimeDescriptionDisplayVerbosityFull, format));
824 
825           valobj_sp->Dump(*output_stream_p, options);
826         } else {
827           result.AppendErrorWithFormat(
828               "failed to create a value object for: (%s) %s\n",
829               view_as_type_cstr, name_strm.GetData());
830           return false;
831         }
832       }
833       return true;
834     }
835 
836     result.SetStatus(eReturnStatusSuccessFinishResult);
837     DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
838                        target->GetArchitecture().GetAddressByteSize(),
839                        target->GetArchitecture().GetDataByteSize());
840 
841     Format format = m_format_options.GetFormat();
842     if (((format == eFormatChar) || (format == eFormatCharPrintable)) &&
843         (item_byte_size != 1)) {
844       // if a count was not passed, or it is 1
845       if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) {
846         // this turns requests such as
847         // memory read -fc -s10 -c1 *charPtrPtr
848         // which make no sense (what is a char of size 10?) into a request for
849         // fetching 10 chars of size 1 from the same memory location
850         format = eFormatCharArray;
851         item_count = item_byte_size;
852         item_byte_size = 1;
853       } else {
854         // here we passed a count, and it was not 1 so we have a byte_size and
855         // a count we could well multiply those, but instead let's just fail
856         result.AppendErrorWithFormat(
857             "reading memory as characters of size %" PRIu64 " is not supported",
858             (uint64_t)item_byte_size);
859         return false;
860       }
861     }
862 
863     assert(output_stream_p);
864     size_t bytes_dumped = DumpDataExtractor(
865         data, output_stream_p, 0, format, item_byte_size, item_count,
866         num_per_line / target->GetArchitecture().GetDataByteSize(), addr, 0, 0,
867         exe_scope, m_memory_tag_options.GetShowTags().GetCurrentValue());
868     m_next_addr = addr + bytes_dumped;
869     output_stream_p->EOL();
870     return true;
871   }
872 
873   OptionGroupOptions m_option_group;
874   OptionGroupFormat m_format_options;
875   OptionGroupReadMemory m_memory_options;
876   OptionGroupOutputFile m_outfile_options;
877   OptionGroupValueObjectDisplay m_varobj_options;
878   OptionGroupMemoryTag m_memory_tag_options;
879   lldb::addr_t m_next_addr = LLDB_INVALID_ADDRESS;
880   lldb::addr_t m_prev_byte_size = 0;
881   OptionGroupFormat m_prev_format_options;
882   OptionGroupReadMemory m_prev_memory_options;
883   OptionGroupOutputFile m_prev_outfile_options;
884   OptionGroupValueObjectDisplay m_prev_varobj_options;
885   OptionGroupMemoryTag m_prev_memory_tag_options;
886   CompilerType m_prev_compiler_type;
887 };
888 
889 #define LLDB_OPTIONS_memory_find
890 #include "CommandOptions.inc"
891 
892 // Find the specified data in memory
893 class CommandObjectMemoryFind : public CommandObjectParsed {
894 public:
895   class OptionGroupFindMemory : public OptionGroup {
896   public:
897     OptionGroupFindMemory() : m_count(1), m_offset(0) {}
898 
899     ~OptionGroupFindMemory() override = default;
900 
901     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
902       return llvm::makeArrayRef(g_memory_find_options);
903     }
904 
905     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
906                           ExecutionContext *execution_context) override {
907       Status error;
908       const int short_option = g_memory_find_options[option_idx].short_option;
909 
910       switch (short_option) {
911       case 'e':
912         m_expr.SetValueFromString(option_value);
913         break;
914 
915       case 's':
916         m_string.SetValueFromString(option_value);
917         break;
918 
919       case 'c':
920         if (m_count.SetValueFromString(option_value).Fail())
921           error.SetErrorString("unrecognized value for count");
922         break;
923 
924       case 'o':
925         if (m_offset.SetValueFromString(option_value).Fail())
926           error.SetErrorString("unrecognized value for dump-offset");
927         break;
928 
929       default:
930         llvm_unreachable("Unimplemented option");
931       }
932       return error;
933     }
934 
935     void OptionParsingStarting(ExecutionContext *execution_context) override {
936       m_expr.Clear();
937       m_string.Clear();
938       m_count.Clear();
939     }
940 
941     OptionValueString m_expr;
942     OptionValueString m_string;
943     OptionValueUInt64 m_count;
944     OptionValueUInt64 m_offset;
945   };
946 
947   CommandObjectMemoryFind(CommandInterpreter &interpreter)
948       : CommandObjectParsed(
949             interpreter, "memory find",
950             "Find a value in the memory of the current target process.",
951             nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched) {
952     CommandArgumentEntry arg1;
953     CommandArgumentEntry arg2;
954     CommandArgumentData addr_arg;
955     CommandArgumentData value_arg;
956 
957     // Define the first (and only) variant of this arg.
958     addr_arg.arg_type = eArgTypeAddressOrExpression;
959     addr_arg.arg_repetition = eArgRepeatPlain;
960 
961     // There is only one variant this argument could be; put it into the
962     // argument entry.
963     arg1.push_back(addr_arg);
964 
965     // Define the first (and only) variant of this arg.
966     value_arg.arg_type = eArgTypeAddressOrExpression;
967     value_arg.arg_repetition = eArgRepeatPlain;
968 
969     // There is only one variant this argument could be; put it into the
970     // argument entry.
971     arg2.push_back(value_arg);
972 
973     // Push the data for the first argument into the m_arguments vector.
974     m_arguments.push_back(arg1);
975     m_arguments.push_back(arg2);
976 
977     m_option_group.Append(&m_memory_options);
978     m_option_group.Finalize();
979   }
980 
981   ~CommandObjectMemoryFind() override = default;
982 
983   Options *GetOptions() override { return &m_option_group; }
984 
985 protected:
986   class ProcessMemoryIterator {
987   public:
988     ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base)
989         : m_process_sp(process_sp), m_base_addr(base) {
990       lldbassert(process_sp.get() != nullptr);
991     }
992 
993     bool IsValid() { return m_is_valid; }
994 
995     uint8_t operator[](lldb::addr_t offset) {
996       if (!IsValid())
997         return 0;
998 
999       uint8_t retval = 0;
1000       Status error;
1001       if (0 ==
1002           m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) {
1003         m_is_valid = false;
1004         return 0;
1005       }
1006 
1007       return retval;
1008     }
1009 
1010   private:
1011     ProcessSP m_process_sp;
1012     lldb::addr_t m_base_addr;
1013     bool m_is_valid = true;
1014   };
1015   bool DoExecute(Args &command, CommandReturnObject &result) override {
1016     // No need to check "process" for validity as eCommandRequiresProcess
1017     // ensures it is valid
1018     Process *process = m_exe_ctx.GetProcessPtr();
1019 
1020     const size_t argc = command.GetArgumentCount();
1021 
1022     if (argc != 2) {
1023       result.AppendError("two addresses needed for memory find");
1024       return false;
1025     }
1026 
1027     Status error;
1028     lldb::addr_t low_addr = OptionArgParser::ToAddress(
1029         &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1030     if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1031       result.AppendError("invalid low address");
1032       return false;
1033     }
1034     lldb::addr_t high_addr = OptionArgParser::ToAddress(
1035         &m_exe_ctx, command[1].ref(), LLDB_INVALID_ADDRESS, &error);
1036     if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1037       result.AppendError("invalid high address");
1038       return false;
1039     }
1040 
1041     ABISP abi = m_exe_ctx.GetProcessPtr()->GetABI();
1042     if (abi) {
1043       low_addr = abi->FixDataAddress(low_addr);
1044       high_addr = abi->FixDataAddress(high_addr);
1045     }
1046 
1047     if (high_addr <= low_addr) {
1048       result.AppendError(
1049           "starting address must be smaller than ending address");
1050       return false;
1051     }
1052 
1053     lldb::addr_t found_location = LLDB_INVALID_ADDRESS;
1054 
1055     DataBufferHeap buffer;
1056 
1057     if (m_memory_options.m_string.OptionWasSet()) {
1058       llvm::StringRef str = m_memory_options.m_string.GetStringValue();
1059       if (str.empty()) {
1060         result.AppendError("search string must have non-zero length.");
1061         return false;
1062       }
1063       buffer.CopyData(str);
1064     } else if (m_memory_options.m_expr.OptionWasSet()) {
1065       StackFrame *frame = m_exe_ctx.GetFramePtr();
1066       ValueObjectSP result_sp;
1067       if ((eExpressionCompleted ==
1068            process->GetTarget().EvaluateExpression(
1069                m_memory_options.m_expr.GetStringValue(), frame, result_sp)) &&
1070           result_sp) {
1071         uint64_t value = result_sp->GetValueAsUnsigned(0);
1072         llvm::Optional<uint64_t> size =
1073             result_sp->GetCompilerType().GetByteSize(nullptr);
1074         if (!size)
1075           return false;
1076         switch (*size) {
1077         case 1: {
1078           uint8_t byte = (uint8_t)value;
1079           buffer.CopyData(&byte, 1);
1080         } break;
1081         case 2: {
1082           uint16_t word = (uint16_t)value;
1083           buffer.CopyData(&word, 2);
1084         } break;
1085         case 4: {
1086           uint32_t lword = (uint32_t)value;
1087           buffer.CopyData(&lword, 4);
1088         } break;
1089         case 8: {
1090           buffer.CopyData(&value, 8);
1091         } break;
1092         case 3:
1093         case 5:
1094         case 6:
1095         case 7:
1096           result.AppendError("unknown type. pass a string instead");
1097           return false;
1098         default:
1099           result.AppendError(
1100               "result size larger than 8 bytes. pass a string instead");
1101           return false;
1102         }
1103       } else {
1104         result.AppendError(
1105             "expression evaluation failed. pass a string instead");
1106         return false;
1107       }
1108     } else {
1109       result.AppendError(
1110           "please pass either a block of text, or an expression to evaluate.");
1111       return false;
1112     }
1113 
1114     size_t count = m_memory_options.m_count.GetCurrentValue();
1115     found_location = low_addr;
1116     bool ever_found = false;
1117     while (count) {
1118       found_location = FastSearch(found_location, high_addr, buffer.GetBytes(),
1119                                   buffer.GetByteSize());
1120       if (found_location == LLDB_INVALID_ADDRESS) {
1121         if (!ever_found) {
1122           result.AppendMessage("data not found within the range.\n");
1123           result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
1124         } else
1125           result.AppendMessage("no more matches within the range.\n");
1126         break;
1127       }
1128       result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n",
1129                                      found_location);
1130 
1131       DataBufferHeap dumpbuffer(32, 0);
1132       process->ReadMemory(
1133           found_location + m_memory_options.m_offset.GetCurrentValue(),
1134           dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error);
1135       if (!error.Fail()) {
1136         DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(),
1137                            process->GetByteOrder(),
1138                            process->GetAddressByteSize());
1139         DumpDataExtractor(
1140             data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1141             dumpbuffer.GetByteSize(), 16,
1142             found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0);
1143         result.GetOutputStream().EOL();
1144       }
1145 
1146       --count;
1147       found_location++;
1148       ever_found = true;
1149     }
1150 
1151     result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
1152     return true;
1153   }
1154 
1155   lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer,
1156                           size_t buffer_size) {
1157     const size_t region_size = high - low;
1158 
1159     if (region_size < buffer_size)
1160       return LLDB_INVALID_ADDRESS;
1161 
1162     std::vector<size_t> bad_char_heuristic(256, buffer_size);
1163     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1164     ProcessMemoryIterator iterator(process_sp, low);
1165 
1166     for (size_t idx = 0; idx < buffer_size - 1; idx++) {
1167       decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx];
1168       bad_char_heuristic[bcu_idx] = buffer_size - idx - 1;
1169     }
1170     for (size_t s = 0; s <= (region_size - buffer_size);) {
1171       int64_t j = buffer_size - 1;
1172       while (j >= 0 && buffer[j] == iterator[s + j])
1173         j--;
1174       if (j < 0)
1175         return low + s;
1176       else
1177         s += bad_char_heuristic[iterator[s + buffer_size - 1]];
1178     }
1179 
1180     return LLDB_INVALID_ADDRESS;
1181   }
1182 
1183   OptionGroupOptions m_option_group;
1184   OptionGroupFindMemory m_memory_options;
1185 };
1186 
1187 #define LLDB_OPTIONS_memory_write
1188 #include "CommandOptions.inc"
1189 
1190 // Write memory to the inferior process
1191 class CommandObjectMemoryWrite : public CommandObjectParsed {
1192 public:
1193   class OptionGroupWriteMemory : public OptionGroup {
1194   public:
1195     OptionGroupWriteMemory() = default;
1196 
1197     ~OptionGroupWriteMemory() override = default;
1198 
1199     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1200       return llvm::makeArrayRef(g_memory_write_options);
1201     }
1202 
1203     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1204                           ExecutionContext *execution_context) override {
1205       Status error;
1206       const int short_option = g_memory_write_options[option_idx].short_option;
1207 
1208       switch (short_option) {
1209       case 'i':
1210         m_infile.SetFile(option_value, FileSpec::Style::native);
1211         FileSystem::Instance().Resolve(m_infile);
1212         if (!FileSystem::Instance().Exists(m_infile)) {
1213           m_infile.Clear();
1214           error.SetErrorStringWithFormat("input file does not exist: '%s'",
1215                                          option_value.str().c_str());
1216         }
1217         break;
1218 
1219       case 'o': {
1220         if (option_value.getAsInteger(0, m_infile_offset)) {
1221           m_infile_offset = 0;
1222           error.SetErrorStringWithFormat("invalid offset string '%s'",
1223                                          option_value.str().c_str());
1224         }
1225       } break;
1226 
1227       default:
1228         llvm_unreachable("Unimplemented option");
1229       }
1230       return error;
1231     }
1232 
1233     void OptionParsingStarting(ExecutionContext *execution_context) override {
1234       m_infile.Clear();
1235       m_infile_offset = 0;
1236     }
1237 
1238     FileSpec m_infile;
1239     off_t m_infile_offset;
1240   };
1241 
1242   CommandObjectMemoryWrite(CommandInterpreter &interpreter)
1243       : CommandObjectParsed(
1244             interpreter, "memory write",
1245             "Write to the memory of the current target process.", nullptr,
1246             eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1247         m_format_options(
1248             eFormatBytes, 1, UINT64_MAX,
1249             {std::make_tuple(
1250                  eArgTypeFormat,
1251                  "The format to use for each of the value to be written."),
1252              std::make_tuple(eArgTypeByteSize,
1253                              "The size in bytes to write from input file or "
1254                              "each value.")}) {
1255     CommandArgumentEntry arg1;
1256     CommandArgumentEntry arg2;
1257     CommandArgumentData addr_arg;
1258     CommandArgumentData value_arg;
1259 
1260     // Define the first (and only) variant of this arg.
1261     addr_arg.arg_type = eArgTypeAddress;
1262     addr_arg.arg_repetition = eArgRepeatPlain;
1263 
1264     // There is only one variant this argument could be; put it into the
1265     // argument entry.
1266     arg1.push_back(addr_arg);
1267 
1268     // Define the first (and only) variant of this arg.
1269     value_arg.arg_type = eArgTypeValue;
1270     value_arg.arg_repetition = eArgRepeatPlus;
1271     value_arg.arg_opt_set_association = LLDB_OPT_SET_1;
1272 
1273     // There is only one variant this argument could be; put it into the
1274     // argument entry.
1275     arg2.push_back(value_arg);
1276 
1277     // Push the data for the first argument into the m_arguments vector.
1278     m_arguments.push_back(arg1);
1279     m_arguments.push_back(arg2);
1280 
1281     m_option_group.Append(&m_format_options,
1282                           OptionGroupFormat::OPTION_GROUP_FORMAT,
1283                           LLDB_OPT_SET_1);
1284     m_option_group.Append(&m_format_options,
1285                           OptionGroupFormat::OPTION_GROUP_SIZE,
1286                           LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
1287     m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2);
1288     m_option_group.Finalize();
1289   }
1290 
1291   ~CommandObjectMemoryWrite() override = default;
1292 
1293   Options *GetOptions() override { return &m_option_group; }
1294 
1295 protected:
1296   bool DoExecute(Args &command, CommandReturnObject &result) override {
1297     // No need to check "process" for validity as eCommandRequiresProcess
1298     // ensures it is valid
1299     Process *process = m_exe_ctx.GetProcessPtr();
1300 
1301     const size_t argc = command.GetArgumentCount();
1302 
1303     if (m_memory_options.m_infile) {
1304       if (argc < 1) {
1305         result.AppendErrorWithFormat(
1306             "%s takes a destination address when writing file contents.\n",
1307             m_cmd_name.c_str());
1308         return false;
1309       }
1310       if (argc > 1) {
1311         result.AppendErrorWithFormat(
1312             "%s takes only a destination address when writing file contents.\n",
1313             m_cmd_name.c_str());
1314         return false;
1315       }
1316     } else if (argc < 2) {
1317       result.AppendErrorWithFormat(
1318           "%s takes a destination address and at least one value.\n",
1319           m_cmd_name.c_str());
1320       return false;
1321     }
1322 
1323     StreamString buffer(
1324         Stream::eBinary,
1325         process->GetTarget().GetArchitecture().GetAddressByteSize(),
1326         process->GetTarget().GetArchitecture().GetByteOrder());
1327 
1328     OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1329     size_t item_byte_size = byte_size_value.GetCurrentValue();
1330 
1331     Status error;
1332     lldb::addr_t addr = OptionArgParser::ToAddress(
1333         &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1334 
1335     if (addr == LLDB_INVALID_ADDRESS) {
1336       result.AppendError("invalid address expression\n");
1337       result.AppendError(error.AsCString());
1338       return false;
1339     }
1340 
1341     if (m_memory_options.m_infile) {
1342       size_t length = SIZE_MAX;
1343       if (item_byte_size > 1)
1344         length = item_byte_size;
1345       auto data_sp = FileSystem::Instance().CreateDataBuffer(
1346           m_memory_options.m_infile.GetPath(), length,
1347           m_memory_options.m_infile_offset);
1348       if (data_sp) {
1349         length = data_sp->GetByteSize();
1350         if (length > 0) {
1351           Status error;
1352           size_t bytes_written =
1353               process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1354 
1355           if (bytes_written == length) {
1356             // All bytes written
1357             result.GetOutputStream().Printf(
1358                 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1359                 (uint64_t)bytes_written, addr);
1360             result.SetStatus(eReturnStatusSuccessFinishResult);
1361           } else if (bytes_written > 0) {
1362             // Some byte written
1363             result.GetOutputStream().Printf(
1364                 "%" PRIu64 " bytes of %" PRIu64
1365                 " requested were written to 0x%" PRIx64 "\n",
1366                 (uint64_t)bytes_written, (uint64_t)length, addr);
1367             result.SetStatus(eReturnStatusSuccessFinishResult);
1368           } else {
1369             result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1370                                          " failed: %s.\n",
1371                                          addr, error.AsCString());
1372           }
1373         }
1374       } else {
1375         result.AppendErrorWithFormat("Unable to read contents of file.\n");
1376       }
1377       return result.Succeeded();
1378     } else if (item_byte_size == 0) {
1379       if (m_format_options.GetFormat() == eFormatPointer)
1380         item_byte_size = buffer.GetAddressByteSize();
1381       else
1382         item_byte_size = 1;
1383     }
1384 
1385     command.Shift(); // shift off the address argument
1386     uint64_t uval64;
1387     int64_t sval64;
1388     bool success = false;
1389     for (auto &entry : command) {
1390       switch (m_format_options.GetFormat()) {
1391       case kNumFormats:
1392       case eFormatFloat: // TODO: add support for floats soon
1393       case eFormatCharPrintable:
1394       case eFormatBytesWithASCII:
1395       case eFormatComplex:
1396       case eFormatEnum:
1397       case eFormatUnicode8:
1398       case eFormatUnicode16:
1399       case eFormatUnicode32:
1400       case eFormatVectorOfChar:
1401       case eFormatVectorOfSInt8:
1402       case eFormatVectorOfUInt8:
1403       case eFormatVectorOfSInt16:
1404       case eFormatVectorOfUInt16:
1405       case eFormatVectorOfSInt32:
1406       case eFormatVectorOfUInt32:
1407       case eFormatVectorOfSInt64:
1408       case eFormatVectorOfUInt64:
1409       case eFormatVectorOfFloat16:
1410       case eFormatVectorOfFloat32:
1411       case eFormatVectorOfFloat64:
1412       case eFormatVectorOfUInt128:
1413       case eFormatOSType:
1414       case eFormatComplexInteger:
1415       case eFormatAddressInfo:
1416       case eFormatHexFloat:
1417       case eFormatInstruction:
1418       case eFormatVoid:
1419         result.AppendError("unsupported format for writing memory");
1420         return false;
1421 
1422       case eFormatDefault:
1423       case eFormatBytes:
1424       case eFormatHex:
1425       case eFormatHexUppercase:
1426       case eFormatPointer: {
1427         // Decode hex bytes
1428         // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1429         // have to special case that:
1430         bool success = false;
1431         if (entry.ref().startswith("0x"))
1432           success = !entry.ref().getAsInteger(0, uval64);
1433         if (!success)
1434           success = !entry.ref().getAsInteger(16, uval64);
1435         if (!success) {
1436           result.AppendErrorWithFormat(
1437               "'%s' is not a valid hex string value.\n", entry.c_str());
1438           return false;
1439         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1440           result.AppendErrorWithFormat("Value 0x%" PRIx64
1441                                        " is too large to fit in a %" PRIu64
1442                                        " byte unsigned integer value.\n",
1443                                        uval64, (uint64_t)item_byte_size);
1444           return false;
1445         }
1446         buffer.PutMaxHex64(uval64, item_byte_size);
1447         break;
1448       }
1449       case eFormatBoolean:
1450         uval64 = OptionArgParser::ToBoolean(entry.ref(), false, &success);
1451         if (!success) {
1452           result.AppendErrorWithFormat(
1453               "'%s' is not a valid boolean string value.\n", entry.c_str());
1454           return false;
1455         }
1456         buffer.PutMaxHex64(uval64, item_byte_size);
1457         break;
1458 
1459       case eFormatBinary:
1460         if (entry.ref().getAsInteger(2, uval64)) {
1461           result.AppendErrorWithFormat(
1462               "'%s' is not a valid binary string value.\n", entry.c_str());
1463           return false;
1464         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1465           result.AppendErrorWithFormat("Value 0x%" PRIx64
1466                                        " is too large to fit in a %" PRIu64
1467                                        " byte unsigned integer value.\n",
1468                                        uval64, (uint64_t)item_byte_size);
1469           return false;
1470         }
1471         buffer.PutMaxHex64(uval64, item_byte_size);
1472         break;
1473 
1474       case eFormatCharArray:
1475       case eFormatChar:
1476       case eFormatCString: {
1477         if (entry.ref().empty())
1478           break;
1479 
1480         size_t len = entry.ref().size();
1481         // Include the NULL for C strings...
1482         if (m_format_options.GetFormat() == eFormatCString)
1483           ++len;
1484         Status error;
1485         if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1486           addr += len;
1487         } else {
1488           result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1489                                        " failed: %s.\n",
1490                                        addr, error.AsCString());
1491           return false;
1492         }
1493         break;
1494       }
1495       case eFormatDecimal:
1496         if (entry.ref().getAsInteger(0, sval64)) {
1497           result.AppendErrorWithFormat(
1498               "'%s' is not a valid signed decimal value.\n", entry.c_str());
1499           return false;
1500         } else if (!llvm::isIntN(item_byte_size * 8, sval64)) {
1501           result.AppendErrorWithFormat(
1502               "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1503               " byte signed integer value.\n",
1504               sval64, (uint64_t)item_byte_size);
1505           return false;
1506         }
1507         buffer.PutMaxHex64(sval64, item_byte_size);
1508         break;
1509 
1510       case eFormatUnsigned:
1511 
1512         if (entry.ref().getAsInteger(0, uval64)) {
1513           result.AppendErrorWithFormat(
1514               "'%s' is not a valid unsigned decimal string value.\n",
1515               entry.c_str());
1516           return false;
1517         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1518           result.AppendErrorWithFormat("Value %" PRIu64
1519                                        " is too large to fit in a %" PRIu64
1520                                        " byte unsigned integer value.\n",
1521                                        uval64, (uint64_t)item_byte_size);
1522           return false;
1523         }
1524         buffer.PutMaxHex64(uval64, item_byte_size);
1525         break;
1526 
1527       case eFormatOctal:
1528         if (entry.ref().getAsInteger(8, uval64)) {
1529           result.AppendErrorWithFormat(
1530               "'%s' is not a valid octal string value.\n", entry.c_str());
1531           return false;
1532         } else if (!llvm::isUIntN(item_byte_size * 8, uval64)) {
1533           result.AppendErrorWithFormat("Value %" PRIo64
1534                                        " is too large to fit in a %" PRIu64
1535                                        " byte unsigned integer value.\n",
1536                                        uval64, (uint64_t)item_byte_size);
1537           return false;
1538         }
1539         buffer.PutMaxHex64(uval64, item_byte_size);
1540         break;
1541       }
1542     }
1543 
1544     if (!buffer.GetString().empty()) {
1545       Status error;
1546       if (process->WriteMemory(addr, buffer.GetString().data(),
1547                                buffer.GetString().size(),
1548                                error) == buffer.GetString().size())
1549         return true;
1550       else {
1551         result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1552                                      " failed: %s.\n",
1553                                      addr, error.AsCString());
1554         return false;
1555       }
1556     }
1557     return true;
1558   }
1559 
1560   OptionGroupOptions m_option_group;
1561   OptionGroupFormat m_format_options;
1562   OptionGroupWriteMemory m_memory_options;
1563 };
1564 
1565 // Get malloc/free history of a memory address.
1566 class CommandObjectMemoryHistory : public CommandObjectParsed {
1567 public:
1568   CommandObjectMemoryHistory(CommandInterpreter &interpreter)
1569       : CommandObjectParsed(interpreter, "memory history",
1570                             "Print recorded stack traces for "
1571                             "allocation/deallocation events "
1572                             "associated with an address.",
1573                             nullptr,
1574                             eCommandRequiresTarget | eCommandRequiresProcess |
1575                                 eCommandProcessMustBePaused |
1576                                 eCommandProcessMustBeLaunched) {
1577     CommandArgumentEntry arg1;
1578     CommandArgumentData addr_arg;
1579 
1580     // Define the first (and only) variant of this arg.
1581     addr_arg.arg_type = eArgTypeAddress;
1582     addr_arg.arg_repetition = eArgRepeatPlain;
1583 
1584     // There is only one variant this argument could be; put it into the
1585     // argument entry.
1586     arg1.push_back(addr_arg);
1587 
1588     // Push the data for the first argument into the m_arguments vector.
1589     m_arguments.push_back(arg1);
1590   }
1591 
1592   ~CommandObjectMemoryHistory() override = default;
1593 
1594   llvm::Optional<std::string> GetRepeatCommand(Args &current_command_args,
1595                                                uint32_t index) override {
1596     return m_cmd_name;
1597   }
1598 
1599 protected:
1600   bool DoExecute(Args &command, CommandReturnObject &result) override {
1601     const size_t argc = command.GetArgumentCount();
1602 
1603     if (argc == 0 || argc > 1) {
1604       result.AppendErrorWithFormat("%s takes an address expression",
1605                                    m_cmd_name.c_str());
1606       return false;
1607     }
1608 
1609     Status error;
1610     lldb::addr_t addr = OptionArgParser::ToAddress(
1611         &m_exe_ctx, command[0].ref(), LLDB_INVALID_ADDRESS, &error);
1612 
1613     if (addr == LLDB_INVALID_ADDRESS) {
1614       result.AppendError("invalid address expression");
1615       result.AppendError(error.AsCString());
1616       return false;
1617     }
1618 
1619     Stream *output_stream = &result.GetOutputStream();
1620 
1621     const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1622     const MemoryHistorySP &memory_history =
1623         MemoryHistory::FindPlugin(process_sp);
1624 
1625     if (!memory_history) {
1626       result.AppendError("no available memory history provider");
1627       return false;
1628     }
1629 
1630     HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1631 
1632     const bool stop_format = false;
1633     for (auto thread : thread_list) {
1634       thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
1635     }
1636 
1637     result.SetStatus(eReturnStatusSuccessFinishResult);
1638 
1639     return true;
1640   }
1641 };
1642 
1643 // CommandObjectMemoryRegion
1644 #pragma mark CommandObjectMemoryRegion
1645 
1646 class CommandObjectMemoryRegion : public CommandObjectParsed {
1647 public:
1648   CommandObjectMemoryRegion(CommandInterpreter &interpreter)
1649       : CommandObjectParsed(interpreter, "memory region",
1650                             "Get information on the memory region containing "
1651                             "an address in the current target process.",
1652                             "memory region ADDR",
1653                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1654                                 eCommandProcessMustBeLaunched) {}
1655 
1656   ~CommandObjectMemoryRegion() override = default;
1657 
1658 protected:
1659   bool DoExecute(Args &command, CommandReturnObject &result) override {
1660     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1661     if (!process_sp) {
1662       m_prev_end_addr = LLDB_INVALID_ADDRESS;
1663       result.AppendError("invalid process");
1664       return false;
1665     }
1666 
1667     Status error;
1668     lldb::addr_t load_addr = m_prev_end_addr;
1669     m_prev_end_addr = LLDB_INVALID_ADDRESS;
1670 
1671     const size_t argc = command.GetArgumentCount();
1672     const lldb::ABISP &abi = process_sp->GetABI();
1673 
1674     if (argc == 1) {
1675       auto load_addr_str = command[0].ref();
1676       // Non-address bits in this will be handled later by GetMemoryRegion
1677       load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1678                                              LLDB_INVALID_ADDRESS, &error);
1679       if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1680         result.AppendErrorWithFormat("invalid address argument \"%s\": %s\n",
1681                                      command[0].c_str(), error.AsCString());
1682         return false;
1683       }
1684     } else if (argc > 1 ||
1685                // When we're repeating the command, the previous end address is
1686                // used for load_addr. If that was 0xF...F then we must have
1687                // reached the end of memory.
1688                (argc == 0 && load_addr == LLDB_INVALID_ADDRESS) ||
1689                // If the target has non-address bits (tags, limited virtual
1690                // address size, etc.), the end of mappable memory will be lower
1691                // than that. So if we find any non-address bit set, we must be
1692                // at the end of the mappable range.
1693                (abi && (abi->FixAnyAddress(load_addr) != load_addr))) {
1694       result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n",
1695                                    m_cmd_name.c_str(), m_cmd_syntax.c_str());
1696       return false;
1697     }
1698 
1699     lldb_private::MemoryRegionInfo range_info;
1700     error = process_sp->GetMemoryRegionInfo(load_addr, range_info);
1701     if (error.Success()) {
1702       lldb_private::Address addr;
1703       ConstString name = range_info.GetName();
1704       ConstString section_name;
1705       if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) {
1706         SectionSP section_sp(addr.GetSection());
1707         if (section_sp) {
1708           // Got the top most section, not the deepest section
1709           while (section_sp->GetParent())
1710             section_sp = section_sp->GetParent();
1711           section_name = section_sp->GetName();
1712         }
1713       }
1714 
1715       result.AppendMessageWithFormatv(
1716           "[{0:x16}-{1:x16}) {2:r}{3:w}{4:x}{5}{6}{7}{8}",
1717           range_info.GetRange().GetRangeBase(),
1718           range_info.GetRange().GetRangeEnd(), range_info.GetReadable(),
1719           range_info.GetWritable(), range_info.GetExecutable(), name ? " " : "",
1720           name, section_name ? " " : "", section_name);
1721       MemoryRegionInfo::OptionalBool memory_tagged =
1722           range_info.GetMemoryTagged();
1723       if (memory_tagged == MemoryRegionInfo::OptionalBool::eYes)
1724         result.AppendMessage("memory tagging: enabled");
1725 
1726       const llvm::Optional<std::vector<addr_t>> &dirty_page_list =
1727           range_info.GetDirtyPageList();
1728       if (dirty_page_list.hasValue()) {
1729         const size_t page_count = dirty_page_list.getValue().size();
1730         result.AppendMessageWithFormat(
1731             "Modified memory (dirty) page list provided, %zu entries.\n",
1732             page_count);
1733         if (page_count > 0) {
1734           bool print_comma = false;
1735           result.AppendMessageWithFormat("Dirty pages: ");
1736           for (size_t i = 0; i < page_count; i++) {
1737             if (print_comma)
1738               result.AppendMessageWithFormat(", ");
1739             else
1740               print_comma = true;
1741             result.AppendMessageWithFormat("0x%" PRIx64,
1742                                            dirty_page_list.getValue()[i]);
1743           }
1744           result.AppendMessageWithFormat(".\n");
1745         }
1746       }
1747 
1748       m_prev_end_addr = range_info.GetRange().GetRangeEnd();
1749       result.SetStatus(eReturnStatusSuccessFinishResult);
1750       return true;
1751     }
1752 
1753     result.AppendErrorWithFormat("%s\n", error.AsCString());
1754     return false;
1755   }
1756 
1757   llvm::Optional<std::string> GetRepeatCommand(Args &current_command_args,
1758                                                uint32_t index) override {
1759     // If we repeat this command, repeat it without any arguments so we can
1760     // show the next memory range
1761     return m_cmd_name;
1762   }
1763 
1764   lldb::addr_t m_prev_end_addr = LLDB_INVALID_ADDRESS;
1765 };
1766 
1767 // CommandObjectMemory
1768 
1769 CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter)
1770     : CommandObjectMultiword(
1771           interpreter, "memory",
1772           "Commands for operating on memory in the current target process.",
1773           "memory <subcommand> [<subcommand-options>]") {
1774   LoadSubCommand("find",
1775                  CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1776   LoadSubCommand("read",
1777                  CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1778   LoadSubCommand("write",
1779                  CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1780   LoadSubCommand("history",
1781                  CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1782   LoadSubCommand("region",
1783                  CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
1784   LoadSubCommand("tag",
1785                  CommandObjectSP(new CommandObjectMemoryTag(interpreter)));
1786 }
1787 
1788 CommandObjectMemory::~CommandObjectMemory() = default;
1789