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