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