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