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