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