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