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