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