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