blob: 95001e08d29b8c94aac921d5a65c5fc4346d6125 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandObjectMemory.cpp ---------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010// C Includes
Virgile Bellobdae3782013-08-28 12:14:27 +000011#include <inttypes.h>
12
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C++ Includes
14// Other libraries and framework includes
Zachary Turnera78bd7f2015-03-03 23:11:11 +000015#include "clang/AST/Decl.h"
Jason Molenda62e06812016-02-16 04:14:33 +000016
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017// Project includes
Eugene Zelenko26cac3a2016-02-20 00:58:29 +000018#include "CommandObjectMemory.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000019#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
Greg Clayton66111032010-06-23 01:19:29 +000020#include "lldb/Core/Debugger.h"
Zachary Turner29cb8682017-03-03 20:57:05 +000021#include "lldb/Core/DumpDataExtractor.h"
Greg Clayton1f746072012-08-29 21:13:06 +000022#include "lldb/Core/Module.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000023#include "lldb/Core/Section.h"
Greg Clayton84c39662011-04-27 22:04:39 +000024#include "lldb/Core/ValueObjectMemory.h"
Enrico Granata4d93b8c2013-09-30 19:11:51 +000025#include "lldb/DataFormatters/ValueObjectPrinter.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000026#include "lldb/Host/OptionParser.h"
Greg Clayton66111032010-06-23 01:19:29 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000028#include "lldb/Interpreter/CommandReturnObject.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000029#include "lldb/Interpreter/OptionArgParser.h"
Greg Clayton84c39662011-04-27 22:04:39 +000030#include "lldb/Interpreter/OptionGroupFormat.h"
31#include "lldb/Interpreter/OptionGroupOutputFile.h"
Greg Clayton68ebae62011-04-28 20:55:26 +000032#include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000033#include "lldb/Interpreter/OptionValueString.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000034#include "lldb/Interpreter/Options.h"
Greg Claytond8d4a572015-08-11 21:38:15 +000035#include "lldb/Symbol/ClangASTContext.h"
Greg Claytonae088e52016-02-10 21:28:13 +000036#include "lldb/Symbol/SymbolFile.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000037#include "lldb/Symbol/TypeList.h"
Kuba Breckabeed8212014-09-04 01:03:18 +000038#include "lldb/Target/MemoryHistory.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000039#include "lldb/Target/MemoryRegionInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000041#include "lldb/Target/StackFrame.h"
Kuba Breckabeed8212014-09-04 01:03:18 +000042#include "lldb/Target/Thread.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000043#include "lldb/Utility/Args.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000044#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner7f6a7a32017-03-06 23:42:14 +000045#include "lldb/Utility/DataBufferLLVM.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000046#include "lldb/Utility/StreamString.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047
Jason Molendaebeff4c2016-02-16 04:20:56 +000048#include "lldb/lldb-private.h"
Jason Molenda62e06812016-02-16 04:14:33 +000049
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050using namespace lldb;
51using namespace lldb_private;
52
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000053static constexpr OptionDefinition g_read_memory_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000055 {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNumberPerLine, "The number of items per line to display." },
56 {LLDB_OPT_SET_2, false, "binary", 'b', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "If true, memory will be saved as binary. If false, the memory is saved save as an ASCII dump that "
Kate Stoneac9c3a62016-08-26 23:28:47 +000057 "uses the format, size, count and number per line settings." },
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000058 {LLDB_OPT_SET_3, true , "type", 't', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone, "The name of a type to view memory as." },
59 {LLDB_OPT_SET_3, false, "offset", 'E', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many elements of the specified type to skip before starting to display data." },
Kate Stoneac9c3a62016-08-26 23:28:47 +000060 {LLDB_OPT_SET_1 |
61 LLDB_OPT_SET_2 |
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +000062 LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Necessary if reading over target.max-memory-read-size bytes." },
Kate Stoneb9c1b512016-09-06 20:57:50 +000063 // clang-format on
Greg Clayton84c39662011-04-27 22:04:39 +000064};
65
Kate Stoneb9c1b512016-09-06 20:57:50 +000066class OptionGroupReadMemory : public OptionGroup {
Greg Clayton84c39662011-04-27 22:04:39 +000067public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 OptionGroupReadMemory()
69 : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(),
70 m_offset(0, 0) {}
Greg Clayton84c39662011-04-27 22:04:39 +000071
Kate Stoneb9c1b512016-09-06 20:57:50 +000072 ~OptionGroupReadMemory() override = default;
Eugene Zelenko26cac3a2016-02-20 00:58:29 +000073
Zachary Turner1f0f5b52016-09-22 20:22:55 +000074 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +000075 return llvm::makeArrayRef(g_read_memory_options);
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 }
Greg Clayton1deb7962011-10-25 06:44:01 +000077
Zachary Turner97206d52017-05-12 04:51:55 +000078 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
79 ExecutionContext *execution_context) override {
80 Status error;
Zachary Turner1f0f5b52016-09-22 20:22:55 +000081 const int short_option = g_read_memory_options[option_idx].short_option;
Kate Stoneb9c1b512016-09-06 20:57:50 +000082
83 switch (short_option) {
84 case 'l':
Zachary Turner8cef4b02016-09-23 17:48:13 +000085 error = m_num_per_line.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 if (m_num_per_line.GetCurrentValue() == 0)
87 error.SetErrorStringWithFormat(
Zachary Turner8cef4b02016-09-23 17:48:13 +000088 "invalid value for --num-per-line option '%s'",
89 option_value.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 break;
91
92 case 'b':
93 m_output_as_binary = true;
94 break;
95
96 case 't':
Zachary Turner8cef4b02016-09-23 17:48:13 +000097 error = m_view_as_type.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 break;
99
100 case 'r':
101 m_force = true;
102 break;
103
104 case 'E':
Zachary Turner8cef4b02016-09-23 17:48:13 +0000105 error = m_offset.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 break;
107
108 default:
109 error.SetErrorStringWithFormat("unrecognized short option '%c'",
110 short_option);
111 break;
112 }
113 return error;
114 }
115
116 void OptionParsingStarting(ExecutionContext *execution_context) override {
117 m_num_per_line.Clear();
118 m_output_as_binary = false;
119 m_view_as_type.Clear();
120 m_force = false;
121 m_offset.Clear();
122 }
123
Zachary Turner97206d52017-05-12 04:51:55 +0000124 Status FinalizeSettings(Target *target, OptionGroupFormat &format_options) {
125 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue();
127 OptionValueUInt64 &count_value = format_options.GetCountValue();
128 const bool byte_size_option_set = byte_size_value.OptionWasSet();
129 const bool num_per_line_option_set = m_num_per_line.OptionWasSet();
130 const bool count_option_set = format_options.GetCountValue().OptionWasSet();
131
132 switch (format_options.GetFormat()) {
133 default:
134 break;
135
136 case eFormatBoolean:
137 if (!byte_size_option_set)
138 byte_size_value = 1;
139 if (!num_per_line_option_set)
140 m_num_per_line = 1;
141 if (!count_option_set)
142 format_options.GetCountValue() = 8;
143 break;
144
145 case eFormatCString:
146 break;
147
148 case eFormatInstruction:
149 if (count_option_set)
150 byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
151 m_num_per_line = 1;
152 break;
153
154 case eFormatAddressInfo:
155 if (!byte_size_option_set)
156 byte_size_value = target->GetArchitecture().GetAddressByteSize();
157 m_num_per_line = 1;
158 if (!count_option_set)
159 format_options.GetCountValue() = 8;
160 break;
161
162 case eFormatPointer:
163 byte_size_value = target->GetArchitecture().GetAddressByteSize();
164 if (!num_per_line_option_set)
165 m_num_per_line = 4;
166 if (!count_option_set)
167 format_options.GetCountValue() = 8;
168 break;
169
170 case eFormatBinary:
171 case eFormatFloat:
172 case eFormatOctal:
173 case eFormatDecimal:
174 case eFormatEnum:
175 case eFormatUnicode16:
176 case eFormatUnicode32:
177 case eFormatUnsigned:
178 case eFormatHexFloat:
179 if (!byte_size_option_set)
180 byte_size_value = 4;
181 if (!num_per_line_option_set)
182 m_num_per_line = 1;
183 if (!count_option_set)
184 format_options.GetCountValue() = 8;
185 break;
186
187 case eFormatBytes:
188 case eFormatBytesWithASCII:
189 if (byte_size_option_set) {
190 if (byte_size_value > 1)
191 error.SetErrorStringWithFormat(
192 "display format (bytes/bytes with ASCII) conflicts with the "
193 "specified byte size %" PRIu64 "\n"
194 "\tconsider using a different display format or don't specify "
195 "the byte size.",
196 byte_size_value.GetCurrentValue());
197 } else
198 byte_size_value = 1;
199 if (!num_per_line_option_set)
200 m_num_per_line = 16;
201 if (!count_option_set)
202 format_options.GetCountValue() = 32;
203 break;
204
205 case eFormatCharArray:
206 case eFormatChar:
207 case eFormatCharPrintable:
208 if (!byte_size_option_set)
209 byte_size_value = 1;
210 if (!num_per_line_option_set)
211 m_num_per_line = 32;
212 if (!count_option_set)
213 format_options.GetCountValue() = 64;
214 break;
215
216 case eFormatComplex:
217 if (!byte_size_option_set)
218 byte_size_value = 8;
219 if (!num_per_line_option_set)
220 m_num_per_line = 1;
221 if (!count_option_set)
222 format_options.GetCountValue() = 8;
223 break;
224
225 case eFormatComplexInteger:
226 if (!byte_size_option_set)
227 byte_size_value = 8;
228 if (!num_per_line_option_set)
229 m_num_per_line = 1;
230 if (!count_option_set)
231 format_options.GetCountValue() = 8;
232 break;
233
234 case eFormatHex:
235 if (!byte_size_option_set)
236 byte_size_value = 4;
237 if (!num_per_line_option_set) {
238 switch (byte_size_value) {
239 case 1:
240 case 2:
241 m_num_per_line = 8;
242 break;
243 case 4:
244 m_num_per_line = 4;
245 break;
246 case 8:
247 m_num_per_line = 2;
248 break;
249 default:
250 m_num_per_line = 1;
251 break;
Greg Clayton84c39662011-04-27 22:04:39 +0000252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 }
254 if (!count_option_set)
255 count_value = 8;
256 break;
257
258 case eFormatVectorOfChar:
259 case eFormatVectorOfSInt8:
260 case eFormatVectorOfUInt8:
261 case eFormatVectorOfSInt16:
262 case eFormatVectorOfUInt16:
263 case eFormatVectorOfSInt32:
264 case eFormatVectorOfUInt32:
265 case eFormatVectorOfSInt64:
266 case eFormatVectorOfUInt64:
267 case eFormatVectorOfFloat16:
268 case eFormatVectorOfFloat32:
269 case eFormatVectorOfFloat64:
270 case eFormatVectorOfUInt128:
271 if (!byte_size_option_set)
272 byte_size_value = 128;
273 if (!num_per_line_option_set)
274 m_num_per_line = 1;
275 if (!count_option_set)
276 count_value = 4;
277 break;
Greg Clayton84c39662011-04-27 22:04:39 +0000278 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279 return error;
280 }
Greg Clayton5009f9d2011-10-27 17:55:14 +0000281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 bool AnyOptionWasSet() const {
283 return m_num_per_line.OptionWasSet() || m_output_as_binary ||
284 m_view_as_type.OptionWasSet() || m_offset.OptionWasSet();
285 }
Greg Clayton5009f9d2011-10-27 17:55:14 +0000286
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287 OptionValueUInt64 m_num_per_line;
288 bool m_output_as_binary;
289 OptionValueString m_view_as_type;
290 bool m_force;
291 OptionValueUInt64 m_offset;
Greg Clayton84c39662011-04-27 22:04:39 +0000292};
293
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294//----------------------------------------------------------------------
295// Read memory from the inferior process
296//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297class CommandObjectMemoryRead : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 CommandObjectMemoryRead(CommandInterpreter &interpreter)
300 : CommandObjectParsed(
301 interpreter, "memory read",
302 "Read from the memory of the current target process.", nullptr,
303 eCommandRequiresTarget | eCommandProcessMustBePaused),
304 m_option_group(), m_format_options(eFormatBytesWithASCII, 1, 8),
305 m_memory_options(), m_outfile_options(), m_varobj_options(),
306 m_next_addr(LLDB_INVALID_ADDRESS), m_prev_byte_size(0),
307 m_prev_format_options(eFormatBytesWithASCII, 1, 8),
308 m_prev_memory_options(), m_prev_outfile_options(),
309 m_prev_varobj_options() {
310 CommandArgumentEntry arg1;
311 CommandArgumentEntry arg2;
312 CommandArgumentData start_addr_arg;
313 CommandArgumentData end_addr_arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315 // Define the first (and only) variant of this arg.
316 start_addr_arg.arg_type = eArgTypeAddressOrExpression;
317 start_addr_arg.arg_repetition = eArgRepeatPlain;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 // There is only one variant this argument could be; put it into the
320 // argument entry.
321 arg1.push_back(start_addr_arg);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 // Define the first (and only) variant of this arg.
324 end_addr_arg.arg_type = eArgTypeAddressOrExpression;
325 end_addr_arg.arg_repetition = eArgRepeatOptional;
326
327 // There is only one variant this argument could be; put it into the
328 // argument entry.
329 arg2.push_back(end_addr_arg);
330
331 // Push the data for the first argument into the m_arguments vector.
332 m_arguments.push_back(arg1);
333 m_arguments.push_back(arg2);
334
335 // Add the "--format" and "--count" options to group 1 and 3
336 m_option_group.Append(&m_format_options,
337 OptionGroupFormat::OPTION_GROUP_FORMAT |
338 OptionGroupFormat::OPTION_GROUP_COUNT,
339 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
340 m_option_group.Append(&m_format_options,
341 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
342 LLDB_OPT_SET_1 | LLDB_OPT_SET_3);
343 // Add the "--size" option to group 1 and 2
344 m_option_group.Append(&m_format_options,
345 OptionGroupFormat::OPTION_GROUP_SIZE,
346 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
347 m_option_group.Append(&m_memory_options);
348 m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL,
349 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
350 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
351 m_option_group.Finalize();
352 }
353
354 ~CommandObjectMemoryRead() override = default;
355
356 Options *GetOptions() override { return &m_option_group; }
357
358 const char *GetRepeatCommand(Args &current_command_args,
359 uint32_t index) override {
360 return m_cmd_name.c_str();
361 }
Greg Clayton82f4cf42011-10-26 04:32:38 +0000362
Jim Ingham5a988412012-06-08 21:56:10 +0000363protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 bool DoExecute(Args &command, CommandReturnObject &result) override {
365 // No need to check "target" for validity as eCommandRequiresTarget ensures
366 // it is valid
367 Target *target = m_exe_ctx.GetTargetPtr();
Greg Claytonf9fc6092013-01-09 19:44:40 +0000368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 const size_t argc = command.GetArgumentCount();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
372 result.AppendErrorWithFormat("%s takes a start address expression with "
373 "an optional end address expression.\n",
374 m_cmd_name.c_str());
375 result.AppendRawWarning("Expressions should be quoted if they contain "
376 "spaces or other special characters.\n");
377 result.SetStatus(eReturnStatusFailed);
378 return false;
379 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 CompilerType clang_ast_type;
Zachary Turner97206d52017-05-12 04:51:55 +0000382 Status error;
Greg Clayton68ebae62011-04-28 20:55:26 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 const char *view_as_type_cstr =
385 m_memory_options.m_view_as_type.GetCurrentValue();
386 if (view_as_type_cstr && view_as_type_cstr[0]) {
387 // We are viewing memory as a type
388
389 SymbolContext sc;
390 const bool exact_match = false;
391 TypeList type_list;
392 uint32_t reference_count = 0;
393 uint32_t pointer_count = 0;
394 size_t idx;
395
396#define ALL_KEYWORDS \
397 KEYWORD("const") \
398 KEYWORD("volatile") \
399 KEYWORD("restrict") \
400 KEYWORD("struct") \
401 KEYWORD("class") \
402 KEYWORD("union")
403
Sean Callanan17cf1132012-07-10 21:24:26 +0000404#define KEYWORD(s) s,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 static const char *g_keywords[] = {ALL_KEYWORDS};
Sean Callanan17cf1132012-07-10 21:24:26 +0000406#undef KEYWORD
407
408#define KEYWORD(s) (sizeof(s) - 1),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 static const int g_keyword_lengths[] = {ALL_KEYWORDS};
Sean Callanan17cf1132012-07-10 21:24:26 +0000410#undef KEYWORD
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411
Sean Callanan17cf1132012-07-10 21:24:26 +0000412#undef ALL_KEYWORDS
Greg Clayton84c39662011-04-27 22:04:39 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
415 std::string type_str(view_as_type_cstr);
Greg Clayton84c39662011-04-27 22:04:39 +0000416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 // Remove all instances of g_keywords that are followed by spaces
418 for (size_t i = 0; i < g_num_keywords; ++i) {
419 const char *keyword = g_keywords[i];
420 int keyword_len = g_keyword_lengths[i];
Saleem Abdulrasoolba507b02015-10-18 19:34:38 +0000421
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 idx = 0;
423 while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
424 if (type_str[idx + keyword_len] == ' ' ||
425 type_str[idx + keyword_len] == '\t') {
426 type_str.erase(idx, keyword_len + 1);
427 idx = 0;
428 } else {
429 idx += keyword_len;
430 }
Greg Clayton84c39662011-04-27 22:04:39 +0000431 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 }
433 bool done = type_str.empty();
434 //
435 idx = type_str.find_first_not_of(" \t");
436 if (idx > 0 && idx != std::string::npos)
437 type_str.erase(0, idx);
438 while (!done) {
439 // Strip trailing spaces
440 if (type_str.empty())
441 done = true;
442 else {
443 switch (type_str[type_str.size() - 1]) {
444 case '*':
445 ++pointer_count;
446 LLVM_FALLTHROUGH;
447 case ' ':
448 case '\t':
449 type_str.erase(type_str.size() - 1);
450 break;
Greg Clayton68ebae62011-04-28 20:55:26 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 case '&':
453 if (reference_count == 0) {
454 reference_count = 1;
455 type_str.erase(type_str.size() - 1);
456 } else {
457 result.AppendErrorWithFormat("invalid type string: '%s'\n",
458 view_as_type_cstr);
459 result.SetStatus(eReturnStatusFailed);
460 return false;
Greg Clayton82f4cf42011-10-26 04:32:38 +0000461 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 break;
463
464 default:
465 done = true;
466 break;
467 }
Greg Clayton82f4cf42011-10-26 04:32:38 +0000468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 }
Greg Clayton82f4cf42011-10-26 04:32:38 +0000470
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
472 ConstString lookup_type_name(type_str.c_str());
473 StackFrame *frame = m_exe_ctx.GetFramePtr();
474 if (frame) {
475 sc = frame->GetSymbolContext(eSymbolContextModule);
476 if (sc.module_sp) {
477 sc.module_sp->FindTypes(sc, lookup_type_name, exact_match, 1,
478 searched_symbol_files, type_list);
Greg Clayton82f4cf42011-10-26 04:32:38 +0000479 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 }
481 if (type_list.GetSize() == 0) {
482 target->GetImages().FindTypes(sc, lookup_type_name, exact_match, 1,
483 searched_symbol_files, type_list);
484 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 if (type_list.GetSize() == 0 && lookup_type_name.GetCString() &&
487 *lookup_type_name.GetCString() == '$') {
488 if (ClangPersistentVariables *persistent_vars =
489 llvm::dyn_cast_or_null<ClangPersistentVariables>(
490 target->GetPersistentExpressionStateForLanguage(
491 lldb::eLanguageTypeC))) {
492 clang::TypeDecl *tdecl = llvm::dyn_cast_or_null<clang::TypeDecl>(
493 persistent_vars->GetPersistentDecl(
494 ConstString(lookup_type_name)));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000495
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 if (tdecl) {
497 clang_ast_type.SetCompilerType(
498 ClangASTContext::GetASTContext(&tdecl->getASTContext()),
499 reinterpret_cast<lldb::opaque_compiler_type_t>(
500 const_cast<clang::Type *>(tdecl->getTypeForDecl())));
501 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000502 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 if (!clang_ast_type.IsValid()) {
506 if (type_list.GetSize() == 0) {
507 result.AppendErrorWithFormat("unable to find any types that match "
508 "the raw type '%s' for full type '%s'\n",
509 lookup_type_name.GetCString(),
510 view_as_type_cstr);
511 result.SetStatus(eReturnStatusFailed);
512 return false;
513 } else {
514 TypeSP type_sp(type_list.GetTypeAtIndex(0));
515 clang_ast_type = type_sp->GetFullCompilerType();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000516 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 }
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 while (pointer_count > 0) {
520 CompilerType pointer_type = clang_ast_type.GetPointerType();
521 if (pointer_type.IsValid())
522 clang_ast_type = pointer_type;
523 else {
524 result.AppendError("unable make a pointer type\n");
525 result.SetStatus(eReturnStatusFailed);
526 return false;
Sean Callanan1276c332012-04-28 01:27:38 +0000527 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 --pointer_count;
529 }
Greg Clayton2e1f7452012-12-15 02:08:17 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 m_format_options.GetByteSizeValue() = clang_ast_type.GetByteSize(nullptr);
Greg Clayton46a44262013-07-24 18:17:35 +0000532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 if (m_format_options.GetByteSizeValue() == 0) {
534 result.AppendErrorWithFormat(
535 "unable to get the byte size of the type '%s'\n",
536 view_as_type_cstr);
537 result.SetStatus(eReturnStatusFailed);
538 return false;
539 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000540
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 if (!m_format_options.GetCountValue().OptionWasSet())
542 m_format_options.GetCountValue() = 1;
543 } else {
544 error = m_memory_options.FinalizeSettings(target, m_format_options);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000545 }
546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 // Look for invalid combinations of settings
548 if (error.Fail()) {
549 result.AppendError(error.AsCString());
550 result.SetStatus(eReturnStatusFailed);
551 return false;
552 }
553
554 lldb::addr_t addr;
555 size_t total_byte_size = 0;
556 if (argc == 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000557 // Use the last address and byte size and all options as they were if no
558 // options have been set
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 addr = m_next_addr;
560 total_byte_size = m_prev_byte_size;
561 clang_ast_type = m_prev_clang_ast_type;
562 if (!m_format_options.AnyOptionWasSet() &&
563 !m_memory_options.AnyOptionWasSet() &&
564 !m_outfile_options.AnyOptionWasSet() &&
565 !m_varobj_options.AnyOptionWasSet()) {
566 m_format_options = m_prev_format_options;
567 m_memory_options = m_prev_memory_options;
568 m_outfile_options = m_prev_outfile_options;
569 m_varobj_options = m_prev_varobj_options;
570 }
571 }
572
573 size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
574
575 // TODO For non-8-bit byte addressable architectures this needs to be
576 // revisited to fully support all lldb's range of formatting options.
Adrian Prantl05097242018-04-30 16:49:04 +0000577 // Furthermore code memory reads (for those architectures) will not be
578 // correctly formatted even w/o formatting options.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 size_t item_byte_size =
580 target->GetArchitecture().GetDataByteSize() > 1
581 ? target->GetArchitecture().GetDataByteSize()
582 : m_format_options.GetByteSizeValue().GetCurrentValue();
583
584 const size_t num_per_line =
585 m_memory_options.m_num_per_line.GetCurrentValue();
586
587 if (total_byte_size == 0) {
588 total_byte_size = item_count * item_byte_size;
589 if (total_byte_size == 0)
590 total_byte_size = 32;
591 }
592
593 if (argc > 0)
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000594 addr = OptionArgParser::ToAddress(&m_exe_ctx, command[0].ref,
595 LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596
597 if (addr == LLDB_INVALID_ADDRESS) {
598 result.AppendError("invalid start address expression.");
599 result.AppendError(error.AsCString());
600 result.SetStatus(eReturnStatusFailed);
601 return false;
602 }
603
604 if (argc == 2) {
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000605 lldb::addr_t end_addr = OptionArgParser::ToAddress(
Zachary Turner14f6b2c2016-12-09 01:08:29 +0000606 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 if (end_addr == LLDB_INVALID_ADDRESS) {
608 result.AppendError("invalid end address expression.");
609 result.AppendError(error.AsCString());
610 result.SetStatus(eReturnStatusFailed);
611 return false;
612 } else if (end_addr <= addr) {
613 result.AppendErrorWithFormat(
614 "end address (0x%" PRIx64
615 ") must be greater that the start address (0x%" PRIx64 ").\n",
616 end_addr, addr);
617 result.SetStatus(eReturnStatusFailed);
618 return false;
619 } else if (m_format_options.GetCountValue().OptionWasSet()) {
620 result.AppendErrorWithFormat(
621 "specify either the end address (0x%" PRIx64
622 ") or the count (--count %" PRIu64 "), not both.\n",
623 end_addr, (uint64_t)item_count);
624 result.SetStatus(eReturnStatusFailed);
625 return false;
626 }
627
628 total_byte_size = end_addr - addr;
629 item_count = total_byte_size / item_byte_size;
630 }
631
632 uint32_t max_unforced_size = target->GetMaximumMemReadSize();
633
634 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
635 result.AppendErrorWithFormat(
636 "Normally, \'memory read\' will not read over %" PRIu32
637 " bytes of data.\n",
638 max_unforced_size);
639 result.AppendErrorWithFormat(
640 "Please use --force to override this restriction just once.\n");
641 result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
642 "will often need a larger limit.\n");
643 return false;
644 }
645
646 DataBufferSP data_sp;
647 size_t bytes_read = 0;
648 if (clang_ast_type.GetOpaqueQualType()) {
649 // Make sure we don't display our type as ASCII bytes like the default
650 // memory read
651 if (!m_format_options.GetFormatValue().OptionWasSet())
652 m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
653
654 bytes_read = clang_ast_type.GetByteSize(nullptr) *
655 m_format_options.GetCountValue().GetCurrentValue();
656
657 if (argc > 0)
658 addr = addr + (clang_ast_type.GetByteSize(nullptr) *
659 m_memory_options.m_offset.GetCurrentValue());
660 } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
661 eFormatCString) {
662 data_sp.reset(new DataBufferHeap(total_byte_size, '\0'));
663 if (data_sp->GetBytes() == nullptr) {
664 result.AppendErrorWithFormat(
665 "can't allocate 0x%" PRIx32
666 " bytes for the memory read buffer, specify a smaller size to read",
667 (uint32_t)total_byte_size);
668 result.SetStatus(eReturnStatusFailed);
669 return false;
670 }
671
672 Address address(addr, nullptr);
673 bytes_read = target->ReadMemory(address, false, data_sp->GetBytes(),
674 data_sp->GetByteSize(), error);
675 if (bytes_read == 0) {
676 const char *error_cstr = error.AsCString();
677 if (error_cstr && error_cstr[0]) {
678 result.AppendError(error_cstr);
679 } else {
680 result.AppendErrorWithFormat(
681 "failed to read memory from 0x%" PRIx64 ".\n", addr);
682 }
683 result.SetStatus(eReturnStatusFailed);
684 return false;
685 }
686
687 if (bytes_read < total_byte_size)
688 result.AppendWarningWithFormat(
689 "Not all bytes (%" PRIu64 "/%" PRIu64
690 ") were able to be read from 0x%" PRIx64 ".\n",
691 (uint64_t)bytes_read, (uint64_t)total_byte_size, addr);
692 } else {
693 // we treat c-strings as a special case because they do not have a fixed
694 // size
695 if (m_format_options.GetByteSizeValue().OptionWasSet() &&
696 !m_format_options.HasGDBFormat())
697 item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
698 else
699 item_byte_size = target->GetMaximumSizeOfStringSummary();
700 if (!m_format_options.GetCountValue().OptionWasSet())
701 item_count = 1;
702 data_sp.reset(new DataBufferHeap((item_byte_size + 1) * item_count,
703 '\0')); // account for NULLs as necessary
704 if (data_sp->GetBytes() == nullptr) {
705 result.AppendErrorWithFormat(
706 "can't allocate 0x%" PRIx64
707 " bytes for the memory read buffer, specify a smaller size to read",
708 (uint64_t)((item_byte_size + 1) * item_count));
709 result.SetStatus(eReturnStatusFailed);
710 return false;
711 }
712 uint8_t *data_ptr = data_sp->GetBytes();
713 auto data_addr = addr;
714 auto count = item_count;
715 item_count = 0;
716 bool break_on_no_NULL = false;
717 while (item_count < count) {
718 std::string buffer;
719 buffer.resize(item_byte_size + 1, 0);
Zachary Turner97206d52017-05-12 04:51:55 +0000720 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
722 item_byte_size + 1, error);
723 if (error.Fail()) {
724 result.AppendErrorWithFormat(
725 "failed to read memory from 0x%" PRIx64 ".\n", addr);
726 result.SetStatus(eReturnStatusFailed);
727 return false;
728 }
729
730 if (item_byte_size == read) {
731 result.AppendWarningWithFormat(
732 "unable to find a NULL terminated string at 0x%" PRIx64
733 ".Consider increasing the maximum read length.\n",
734 data_addr);
735 --read;
736 break_on_no_NULL = true;
737 } else
738 ++read; // account for final NULL byte
739
740 memcpy(data_ptr, &buffer[0], read);
741 data_ptr += read;
742 data_addr += read;
743 bytes_read += read;
744 item_count++; // if we break early we know we only read item_count
745 // strings
746
747 if (break_on_no_NULL)
748 break;
749 }
750 data_sp.reset(new DataBufferHeap(data_sp->GetBytes(), bytes_read + 1));
751 }
752
753 m_next_addr = addr + bytes_read;
754 m_prev_byte_size = bytes_read;
755 m_prev_format_options = m_format_options;
756 m_prev_memory_options = m_memory_options;
757 m_prev_outfile_options = m_outfile_options;
758 m_prev_varobj_options = m_varobj_options;
759 m_prev_clang_ast_type = clang_ast_type;
760
761 StreamFile outfile_stream;
762 Stream *output_stream = nullptr;
763 const FileSpec &outfile_spec =
764 m_outfile_options.GetFile().GetCurrentValue();
765 if (outfile_spec) {
766 char path[PATH_MAX];
767 outfile_spec.GetPath(path, sizeof(path));
768
769 uint32_t open_options =
770 File::eOpenOptionWrite | File::eOpenOptionCanCreate;
771 const bool append = m_outfile_options.GetAppend().GetCurrentValue();
772 if (append)
773 open_options |= File::eOpenOptionAppend;
774
775 if (outfile_stream.GetFile().Open(path, open_options).Success()) {
776 if (m_memory_options.m_output_as_binary) {
777 const size_t bytes_written =
778 outfile_stream.Write(data_sp->GetBytes(), bytes_read);
779 if (bytes_written > 0) {
780 result.GetOutputStream().Printf(
781 "%zi bytes %s to '%s'\n", bytes_written,
782 append ? "appended" : "written", path);
783 return true;
784 } else {
785 result.AppendErrorWithFormat("Failed to write %" PRIu64
786 " bytes to '%s'.\n",
787 (uint64_t)bytes_read, path);
788 result.SetStatus(eReturnStatusFailed);
789 return false;
790 }
791 } else {
792 // We are going to write ASCII to the file just point the
793 // output_stream to our outfile_stream...
794 output_stream = &outfile_stream;
795 }
796 } else {
797 result.AppendErrorWithFormat("Failed to open file '%s' for %s.\n", path,
798 append ? "append" : "write");
799 result.SetStatus(eReturnStatusFailed);
800 return false;
801 }
802 } else {
803 output_stream = &result.GetOutputStream();
804 }
805
806 ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
807 if (clang_ast_type.GetOpaqueQualType()) {
808 for (uint32_t i = 0; i < item_count; ++i) {
809 addr_t item_addr = addr + (i * item_byte_size);
810 Address address(item_addr);
811 StreamString name_strm;
812 name_strm.Printf("0x%" PRIx64, item_addr);
813 ValueObjectSP valobj_sp(ValueObjectMemory::Create(
Zachary Turner22a26282016-11-12 18:17:36 +0000814 exe_scope, name_strm.GetString(), address, clang_ast_type));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 if (valobj_sp) {
816 Format format = m_format_options.GetFormat();
817 if (format != eFormatDefault)
818 valobj_sp->SetFormat(format);
819
820 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
821 eLanguageRuntimeDescriptionDisplayVerbosityFull, format));
822
823 valobj_sp->Dump(*output_stream, options);
824 } else {
825 result.AppendErrorWithFormat(
826 "failed to create a value object for: (%s) %s\n",
Zachary Turnerc1564272016-11-16 21:15:24 +0000827 view_as_type_cstr, name_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 result.SetStatus(eReturnStatusFailed);
829 return false;
830 }
831 }
832 return true;
833 }
834
835 result.SetStatus(eReturnStatusSuccessFinishResult);
836 DataExtractor data(data_sp, target->GetArchitecture().GetByteOrder(),
837 target->GetArchitecture().GetAddressByteSize(),
838 target->GetArchitecture().GetDataByteSize());
839
840 Format format = m_format_options.GetFormat();
841 if (((format == eFormatChar) || (format == eFormatCharPrintable)) &&
842 (item_byte_size != 1)) {
843 // if a count was not passed, or it is 1
844 if (!m_format_options.GetCountValue().OptionWasSet() || item_count == 1) {
845 // this turns requests such as
846 // memory read -fc -s10 -c1 *charPtrPtr
Adrian Prantl05097242018-04-30 16:49:04 +0000847 // which make no sense (what is a char of size 10?) into a request for
848 // fetching 10 chars of size 1 from the same memory location
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 format = eFormatCharArray;
850 item_count = item_byte_size;
851 item_byte_size = 1;
852 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000853 // here we passed a count, and it was not 1 so we have a byte_size and
854 // a count we could well multiply those, but instead let's just fail
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 result.AppendErrorWithFormat(
856 "reading memory as characters of size %" PRIu64 " is not supported",
857 (uint64_t)item_byte_size);
858 result.SetStatus(eReturnStatusFailed);
859 return false;
860 }
861 }
862
863 assert(output_stream);
Zachary Turner29cb8682017-03-03 20:57:05 +0000864 size_t bytes_dumped = DumpDataExtractor(
865 data, output_stream, 0, format, item_byte_size, item_count,
866 num_per_line / target->GetArchitecture().GetDataByteSize(), addr, 0, 0,
867 exe_scope);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 m_next_addr = addr + bytes_dumped;
869 output_stream->EOL();
870 return true;
871 }
872
873 OptionGroupOptions m_option_group;
874 OptionGroupFormat m_format_options;
875 OptionGroupReadMemory m_memory_options;
876 OptionGroupOutputFile m_outfile_options;
877 OptionGroupValueObjectDisplay m_varobj_options;
878 lldb::addr_t m_next_addr;
879 lldb::addr_t m_prev_byte_size;
880 OptionGroupFormat m_prev_format_options;
881 OptionGroupReadMemory m_prev_memory_options;
882 OptionGroupOutputFile m_prev_outfile_options;
883 OptionGroupValueObjectDisplay m_prev_varobj_options;
884 CompilerType m_prev_clang_ast_type;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885};
886
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000887static constexpr OptionDefinition g_memory_find_option_table[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000889 {LLDB_OPT_SET_1, true, "expression", 'e', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeExpression, "Evaluate an expression to obtain a byte pattern."},
890 {LLDB_OPT_SET_2, true, "string", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeName, "Use text to find a byte pattern."},
891 {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCount, "How many times to perform the search."},
892 {LLDB_OPT_SET_ALL, false, "dump-offset", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "When dumping memory for a match, an offset from the match location to start dumping from."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 // clang-format on
Enrico Granata53468432013-11-13 02:18:44 +0000894};
895
Enrico Granata53468432013-11-13 02:18:44 +0000896//----------------------------------------------------------------------
897// Find the specified data in memory
898//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899class CommandObjectMemoryFind : public CommandObjectParsed {
Enrico Granata53468432013-11-13 02:18:44 +0000900public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 class OptionGroupFindMemory : public OptionGroup {
Enrico Granata53468432013-11-13 02:18:44 +0000902 public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 OptionGroupFindMemory() : OptionGroup(), m_count(1), m_offset(0) {}
Eugene Zelenko26cac3a2016-02-20 00:58:29 +0000904
905 ~OptionGroupFindMemory() override = default;
906
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000907 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000908 return llvm::makeArrayRef(g_memory_find_option_table);
Enrico Granata53468432013-11-13 02:18:44 +0000909 }
Enrico Granata8d81a842013-11-13 20:08:30 +0000910
Zachary Turner97206d52017-05-12 04:51:55 +0000911 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
912 ExecutionContext *execution_context) override {
913 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 const int short_option =
915 g_memory_find_option_table[option_idx].short_option;
916
917 switch (short_option) {
918 case 'e':
Zachary Turner8cef4b02016-09-23 17:48:13 +0000919 m_expr.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 break;
921
922 case 's':
Zachary Turner8cef4b02016-09-23 17:48:13 +0000923 m_string.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 break;
925
926 case 'c':
Zachary Turner8cef4b02016-09-23 17:48:13 +0000927 if (m_count.SetValueFromString(option_value).Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 error.SetErrorString("unrecognized value for count");
929 break;
930
931 case 'o':
Zachary Turner8cef4b02016-09-23 17:48:13 +0000932 if (m_offset.SetValueFromString(option_value).Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 error.SetErrorString("unrecognized value for dump-offset");
934 break;
935
936 default:
937 error.SetErrorStringWithFormat("unrecognized short option '%c'",
938 short_option);
939 break;
940 }
941 return error;
Enrico Granata53468432013-11-13 02:18:44 +0000942 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943
944 void OptionParsingStarting(ExecutionContext *execution_context) override {
945 m_expr.Clear();
946 m_string.Clear();
947 m_count.Clear();
Enrico Granata53468432013-11-13 02:18:44 +0000948 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949
950 OptionValueString m_expr;
951 OptionValueString m_string;
952 OptionValueUInt64 m_count;
953 OptionValueUInt64 m_offset;
Enrico Granata53468432013-11-13 02:18:44 +0000954 };
Kate Stone7428a182016-07-14 22:03:10 +0000955
956 CommandObjectMemoryFind(CommandInterpreter &interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 : CommandObjectParsed(
958 interpreter, "memory find",
959 "Find a value in the memory of the current target process.",
960 nullptr, eCommandRequiresProcess | eCommandProcessMustBeLaunched),
961 m_option_group(), m_memory_options() {
Enrico Granata53468432013-11-13 02:18:44 +0000962 CommandArgumentEntry arg1;
963 CommandArgumentEntry arg2;
964 CommandArgumentData addr_arg;
965 CommandArgumentData value_arg;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966
Enrico Granata53468432013-11-13 02:18:44 +0000967 // Define the first (and only) variant of this arg.
Enrico Granata760af882015-08-03 20:47:19 +0000968 addr_arg.arg_type = eArgTypeAddressOrExpression;
Enrico Granata53468432013-11-13 02:18:44 +0000969 addr_arg.arg_repetition = eArgRepeatPlain;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970
971 // There is only one variant this argument could be; put it into the
972 // argument entry.
973 arg1.push_back(addr_arg);
974
Enrico Granata53468432013-11-13 02:18:44 +0000975 // Define the first (and only) variant of this arg.
Enrico Granata760af882015-08-03 20:47:19 +0000976 value_arg.arg_type = eArgTypeAddressOrExpression;
977 value_arg.arg_repetition = eArgRepeatPlain;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978
979 // There is only one variant this argument could be; put it into the
980 // argument entry.
981 arg2.push_back(value_arg);
982
Enrico Granata53468432013-11-13 02:18:44 +0000983 // Push the data for the first argument into the m_arguments vector.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 m_arguments.push_back(arg1);
985 m_arguments.push_back(arg2);
986
987 m_option_group.Append(&m_memory_options);
Enrico Granata53468432013-11-13 02:18:44 +0000988 m_option_group.Finalize();
989 }
Eugene Zelenko26cac3a2016-02-20 00:58:29 +0000990
991 ~CommandObjectMemoryFind() override = default;
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 Options *GetOptions() override { return &m_option_group; }
994
Enrico Granata53468432013-11-13 02:18:44 +0000995protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 class ProcessMemoryIterator {
Enrico Granata7eef5fa2016-09-01 00:09:59 +0000997 public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 ProcessMemoryIterator(ProcessSP process_sp, lldb::addr_t base)
999 : m_process_sp(process_sp), m_base_addr(base), m_is_valid(true) {
1000 lldbassert(process_sp.get() != nullptr);
Enrico Granata53468432013-11-13 02:18:44 +00001001 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002
1003 bool IsValid() { return m_is_valid; }
1004
1005 uint8_t operator[](lldb::addr_t offset) {
1006 if (!IsValid())
1007 return 0;
1008
1009 uint8_t retval = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00001010 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (0 ==
1012 m_process_sp->ReadMemory(m_base_addr + offset, &retval, 1, error)) {
1013 m_is_valid = false;
1014 return 0;
1015 }
1016
1017 return retval;
1018 }
1019
1020 private:
1021 ProcessSP m_process_sp;
1022 lldb::addr_t m_base_addr;
1023 bool m_is_valid;
1024 };
1025 bool DoExecute(Args &command, CommandReturnObject &result) override {
1026 // No need to check "process" for validity as eCommandRequiresProcess
1027 // ensures it is valid
1028 Process *process = m_exe_ctx.GetProcessPtr();
1029
1030 const size_t argc = command.GetArgumentCount();
1031
1032 if (argc != 2) {
1033 result.AppendError("two addresses needed for memory find");
1034 return false;
1035 }
1036
Zachary Turner97206d52017-05-12 04:51:55 +00001037 Status error;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001038 lldb::addr_t low_addr = OptionArgParser::ToAddress(
1039 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 if (low_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1041 result.AppendError("invalid low address");
1042 return false;
1043 }
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001044 lldb::addr_t high_addr = OptionArgParser::ToAddress(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001045 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 if (high_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1047 result.AppendError("invalid high address");
1048 return false;
1049 }
1050
1051 if (high_addr <= low_addr) {
1052 result.AppendError(
1053 "starting address must be smaller than ending address");
1054 return false;
1055 }
1056
1057 lldb::addr_t found_location = LLDB_INVALID_ADDRESS;
1058
1059 DataBufferHeap buffer;
1060
1061 if (m_memory_options.m_string.OptionWasSet())
Zachary Turner31d97a52016-11-17 18:08:12 +00001062 buffer.CopyData(m_memory_options.m_string.GetStringValue());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 else if (m_memory_options.m_expr.OptionWasSet()) {
1064 StackFrame *frame = m_exe_ctx.GetFramePtr();
1065 ValueObjectSP result_sp;
1066 if ((eExpressionCompleted ==
1067 process->GetTarget().EvaluateExpression(
1068 m_memory_options.m_expr.GetStringValue(), frame, result_sp)) &&
1069 result_sp) {
1070 uint64_t value = result_sp->GetValueAsUnsigned(0);
1071 switch (result_sp->GetCompilerType().GetByteSize(nullptr)) {
1072 case 1: {
1073 uint8_t byte = (uint8_t)value;
1074 buffer.CopyData(&byte, 1);
1075 } break;
1076 case 2: {
1077 uint16_t word = (uint16_t)value;
1078 buffer.CopyData(&word, 2);
1079 } break;
1080 case 4: {
1081 uint32_t lword = (uint32_t)value;
1082 buffer.CopyData(&lword, 4);
1083 } break;
1084 case 8: {
1085 buffer.CopyData(&value, 8);
1086 } break;
1087 case 3:
1088 case 5:
1089 case 6:
1090 case 7:
1091 result.AppendError("unknown type. pass a string instead");
1092 return false;
1093 default:
1094 result.AppendError(
1095 "result size larger than 8 bytes. pass a string instead");
1096 return false;
1097 }
1098 } else {
1099 result.AppendError(
1100 "expression evaluation failed. pass a string instead");
1101 return false;
1102 }
1103 } else {
1104 result.AppendError(
1105 "please pass either a block of text, or an expression to evaluate.");
1106 return false;
1107 }
1108
1109 size_t count = m_memory_options.m_count.GetCurrentValue();
1110 found_location = low_addr;
1111 bool ever_found = false;
1112 while (count) {
1113 found_location = FastSearch(found_location, high_addr, buffer.GetBytes(),
1114 buffer.GetByteSize());
1115 if (found_location == LLDB_INVALID_ADDRESS) {
1116 if (!ever_found) {
1117 result.AppendMessage("data not found within the range.\n");
1118 result.SetStatus(lldb::eReturnStatusSuccessFinishNoResult);
1119 } else
1120 result.AppendMessage("no more matches within the range.\n");
1121 break;
1122 }
1123 result.AppendMessageWithFormat("data found at location: 0x%" PRIx64 "\n",
1124 found_location);
1125
1126 DataBufferHeap dumpbuffer(32, 0);
1127 process->ReadMemory(
1128 found_location + m_memory_options.m_offset.GetCurrentValue(),
1129 dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(), error);
1130 if (!error.Fail()) {
1131 DataExtractor data(dumpbuffer.GetBytes(), dumpbuffer.GetByteSize(),
1132 process->GetByteOrder(),
1133 process->GetAddressByteSize());
Zachary Turner29cb8682017-03-03 20:57:05 +00001134 DumpDataExtractor(
1135 data, &result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1136 dumpbuffer.GetByteSize(), 16,
1137 found_location + m_memory_options.m_offset.GetCurrentValue(), 0, 0);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 result.GetOutputStream().EOL();
1139 }
1140
1141 --count;
1142 found_location++;
1143 ever_found = true;
1144 }
1145
1146 result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
1147 return true;
1148 }
1149
1150 lldb::addr_t FastSearch(lldb::addr_t low, lldb::addr_t high, uint8_t *buffer,
1151 size_t buffer_size) {
1152 const size_t region_size = high - low;
1153
1154 if (region_size < buffer_size)
1155 return LLDB_INVALID_ADDRESS;
1156
1157 std::vector<size_t> bad_char_heuristic(256, buffer_size);
1158 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1159 ProcessMemoryIterator iterator(process_sp, low);
1160
1161 for (size_t idx = 0; idx < buffer_size - 1; idx++) {
1162 decltype(bad_char_heuristic)::size_type bcu_idx = buffer[idx];
1163 bad_char_heuristic[bcu_idx] = buffer_size - idx - 1;
1164 }
1165 for (size_t s = 0; s <= (region_size - buffer_size);) {
1166 int64_t j = buffer_size - 1;
1167 while (j >= 0 && buffer[j] == iterator[s + j])
1168 j--;
1169 if (j < 0)
1170 return low + s;
1171 else
1172 s += bad_char_heuristic[iterator[s + buffer_size - 1]];
1173 }
1174
1175 return LLDB_INVALID_ADDRESS;
1176 }
1177
1178 OptionGroupOptions m_option_group;
1179 OptionGroupFindMemory m_memory_options;
Enrico Granata53468432013-11-13 02:18:44 +00001180};
1181
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00001182static constexpr OptionDefinition g_memory_write_option_table[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00001184 {LLDB_OPT_SET_1, true, "infile", 'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeFilename, "Write memory using the contents of a file."},
1185 {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeOffset, "Start writing bytes from an offset within the input file."},
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 // clang-format on
Greg Clayton1deb7962011-10-25 06:44:01 +00001187};
1188
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189//----------------------------------------------------------------------
1190// Write memory to the inferior process
1191//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192class CommandObjectMemoryWrite : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001193public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 class OptionGroupWriteMemory : public OptionGroup {
1195 public:
1196 OptionGroupWriteMemory() : OptionGroup() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 ~OptionGroupWriteMemory() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001200 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +00001201 return llvm::makeArrayRef(g_memory_write_option_table);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001202 }
1203
Zachary Turner97206d52017-05-12 04:51:55 +00001204 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
1205 ExecutionContext *execution_context) override {
1206 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 const int short_option =
1208 g_memory_write_option_table[option_idx].short_option;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 switch (short_option) {
1211 case 'i':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001212 m_infile.SetFile(option_value, FileSpec::Style::native);
1213 FileSystem::Instance().Resolve(m_infile);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00001214 if (!FileSystem::Instance().Exists(m_infile)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 m_infile.Clear();
1216 error.SetErrorStringWithFormat("input file does not exist: '%s'",
Zachary Turner8cef4b02016-09-23 17:48:13 +00001217 option_value.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 }
1219 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001220
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 case 'o': {
Zachary Turner8cef4b02016-09-23 17:48:13 +00001222 if (option_value.getAsInteger(0, m_infile_offset)) {
1223 m_infile_offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 error.SetErrorStringWithFormat("invalid offset string '%s'",
Zachary Turner8cef4b02016-09-23 17:48:13 +00001225 option_value.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 }
1227 } break;
1228
1229 default:
1230 error.SetErrorStringWithFormat("unrecognized short option '%c'",
1231 short_option);
1232 break;
1233 }
1234 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235 }
1236
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 void OptionParsingStarting(ExecutionContext *execution_context) override {
1238 m_infile.Clear();
1239 m_infile_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001240 }
1241
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 FileSpec m_infile;
1243 off_t m_infile_offset;
1244 };
1245
1246 CommandObjectMemoryWrite(CommandInterpreter &interpreter)
1247 : CommandObjectParsed(
1248 interpreter, "memory write",
1249 "Write to the memory of the current target process.", nullptr,
1250 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1251 m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX),
1252 m_memory_options() {
1253 CommandArgumentEntry arg1;
1254 CommandArgumentEntry arg2;
1255 CommandArgumentData addr_arg;
1256 CommandArgumentData value_arg;
1257
1258 // Define the first (and only) variant of this arg.
1259 addr_arg.arg_type = eArgTypeAddress;
1260 addr_arg.arg_repetition = eArgRepeatPlain;
1261
1262 // There is only one variant this argument could be; put it into the
1263 // argument entry.
1264 arg1.push_back(addr_arg);
1265
1266 // Define the first (and only) variant of this arg.
1267 value_arg.arg_type = eArgTypeValue;
1268 value_arg.arg_repetition = eArgRepeatPlus;
1269
1270 // There is only one variant this argument could be; put it into the
1271 // argument entry.
1272 arg2.push_back(value_arg);
1273
1274 // Push the data for the first argument into the m_arguments vector.
1275 m_arguments.push_back(arg1);
1276 m_arguments.push_back(arg2);
1277
1278 m_option_group.Append(&m_format_options,
1279 OptionGroupFormat::OPTION_GROUP_FORMAT,
1280 LLDB_OPT_SET_1);
1281 m_option_group.Append(&m_format_options,
1282 OptionGroupFormat::OPTION_GROUP_SIZE,
1283 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
1284 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2);
1285 m_option_group.Finalize();
1286 }
1287
1288 ~CommandObjectMemoryWrite() override = default;
1289
1290 Options *GetOptions() override { return &m_option_group; }
1291
1292 bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) {
1293 if (total_byte_size > 8)
1294 return false;
1295
1296 if (total_byte_size == 8)
1297 return true;
1298
1299 const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1;
1300 return uval64 <= max;
1301 }
1302
1303 bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) {
1304 if (total_byte_size > 8)
1305 return false;
1306
1307 if (total_byte_size == 8)
1308 return true;
1309
1310 const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1;
1311 const int64_t min = ~(max);
1312 return min <= sval64 && sval64 <= max;
1313 }
1314
Jim Ingham5a988412012-06-08 21:56:10 +00001315protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 bool DoExecute(Args &command, CommandReturnObject &result) override {
1317 // No need to check "process" for validity as eCommandRequiresProcess
1318 // ensures it is valid
1319 Process *process = m_exe_ctx.GetProcessPtr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321 const size_t argc = command.GetArgumentCount();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322
Kate Stoneb9c1b512016-09-06 20:57:50 +00001323 if (m_memory_options.m_infile) {
1324 if (argc < 1) {
1325 result.AppendErrorWithFormat(
1326 "%s takes a destination address when writing file contents.\n",
1327 m_cmd_name.c_str());
1328 result.SetStatus(eReturnStatusFailed);
1329 return false;
1330 }
1331 } else if (argc < 2) {
1332 result.AppendErrorWithFormat(
1333 "%s takes a destination address and at least one value.\n",
1334 m_cmd_name.c_str());
1335 result.SetStatus(eReturnStatusFailed);
1336 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337 }
1338
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339 StreamString buffer(
1340 Stream::eBinary,
1341 process->GetTarget().GetArchitecture().GetAddressByteSize(),
1342 process->GetTarget().GetArchitecture().GetByteOrder());
1343
1344 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1345 size_t item_byte_size = byte_size_value.GetCurrentValue();
1346
Zachary Turner97206d52017-05-12 04:51:55 +00001347 Status error;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001348 lldb::addr_t addr = OptionArgParser::ToAddress(
1349 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350
1351 if (addr == LLDB_INVALID_ADDRESS) {
1352 result.AppendError("invalid address expression\n");
1353 result.AppendError(error.AsCString());
1354 result.SetStatus(eReturnStatusFailed);
1355 return false;
1356 }
1357
1358 if (m_memory_options.m_infile) {
1359 size_t length = SIZE_MAX;
1360 if (item_byte_size > 1)
1361 length = item_byte_size;
Zachary Turner7f6a7a32017-03-06 23:42:14 +00001362 auto data_sp = DataBufferLLVM::CreateSliceFromPath(
1363 m_memory_options.m_infile.GetPath(), length,
1364 m_memory_options.m_infile_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 if (data_sp) {
1366 length = data_sp->GetByteSize();
1367 if (length > 0) {
Zachary Turner97206d52017-05-12 04:51:55 +00001368 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001369 size_t bytes_written =
1370 process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1371
1372 if (bytes_written == length) {
1373 // All bytes written
1374 result.GetOutputStream().Printf(
1375 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1376 (uint64_t)bytes_written, addr);
1377 result.SetStatus(eReturnStatusSuccessFinishResult);
1378 } else if (bytes_written > 0) {
1379 // Some byte written
1380 result.GetOutputStream().Printf(
1381 "%" PRIu64 " bytes of %" PRIu64
1382 " requested were written to 0x%" PRIx64 "\n",
1383 (uint64_t)bytes_written, (uint64_t)length, addr);
1384 result.SetStatus(eReturnStatusSuccessFinishResult);
1385 } else {
1386 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1387 " failed: %s.\n",
1388 addr, error.AsCString());
1389 result.SetStatus(eReturnStatusFailed);
1390 }
1391 }
1392 } else {
1393 result.AppendErrorWithFormat("Unable to read contents of file.\n");
1394 result.SetStatus(eReturnStatusFailed);
1395 }
1396 return result.Succeeded();
1397 } else if (item_byte_size == 0) {
1398 if (m_format_options.GetFormat() == eFormatPointer)
1399 item_byte_size = buffer.GetAddressByteSize();
1400 else
1401 item_byte_size = 1;
1402 }
1403
1404 command.Shift(); // shift off the address argument
1405 uint64_t uval64;
1406 int64_t sval64;
1407 bool success = false;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001408 for (auto &entry : command) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 switch (m_format_options.GetFormat()) {
1410 case kNumFormats:
1411 case eFormatFloat: // TODO: add support for floats soon
1412 case eFormatCharPrintable:
1413 case eFormatBytesWithASCII:
1414 case eFormatComplex:
1415 case eFormatEnum:
1416 case eFormatUnicode16:
1417 case eFormatUnicode32:
1418 case eFormatVectorOfChar:
1419 case eFormatVectorOfSInt8:
1420 case eFormatVectorOfUInt8:
1421 case eFormatVectorOfSInt16:
1422 case eFormatVectorOfUInt16:
1423 case eFormatVectorOfSInt32:
1424 case eFormatVectorOfUInt32:
1425 case eFormatVectorOfSInt64:
1426 case eFormatVectorOfUInt64:
1427 case eFormatVectorOfFloat16:
1428 case eFormatVectorOfFloat32:
1429 case eFormatVectorOfFloat64:
1430 case eFormatVectorOfUInt128:
1431 case eFormatOSType:
1432 case eFormatComplexInteger:
1433 case eFormatAddressInfo:
1434 case eFormatHexFloat:
1435 case eFormatInstruction:
1436 case eFormatVoid:
1437 result.AppendError("unsupported format for writing memory");
1438 result.SetStatus(eReturnStatusFailed);
1439 return false;
1440
1441 case eFormatDefault:
1442 case eFormatBytes:
1443 case eFormatHex:
1444 case eFormatHexUppercase:
1445 case eFormatPointer:
Jim Inghambef72b72017-04-06 01:33:38 +00001446 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 // Decode hex bytes
Jim Inghambef72b72017-04-06 01:33:38 +00001448 // Be careful, getAsInteger with a radix of 16 rejects "0xab" so we
1449 // have to special case that:
1450 bool success = false;
1451 if (entry.ref.startswith("0x"))
1452 success = !entry.ref.getAsInteger(0, uval64);
1453 if (!success)
1454 success = !entry.ref.getAsInteger(16, uval64);
1455 if (!success) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001457 "'%s' is not a valid hex string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 result.SetStatus(eReturnStatusFailed);
1459 return false;
1460 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1461 result.AppendErrorWithFormat("Value 0x%" PRIx64
1462 " is too large to fit in a %" PRIu64
1463 " byte unsigned integer value.\n",
1464 uval64, (uint64_t)item_byte_size);
1465 result.SetStatus(eReturnStatusFailed);
1466 return false;
1467 }
1468 buffer.PutMaxHex64(uval64, item_byte_size);
1469 break;
Jim Inghambef72b72017-04-06 01:33:38 +00001470 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001471 case eFormatBoolean:
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001472 uval64 = OptionArgParser::ToBoolean(entry.ref, false, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473 if (!success) {
1474 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001475 "'%s' is not a valid boolean string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 result.SetStatus(eReturnStatusFailed);
1477 return false;
1478 }
1479 buffer.PutMaxHex64(uval64, item_byte_size);
1480 break;
1481
1482 case eFormatBinary:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001483 if (entry.ref.getAsInteger(2, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001485 "'%s' is not a valid binary string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 result.SetStatus(eReturnStatusFailed);
1487 return false;
1488 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1489 result.AppendErrorWithFormat("Value 0x%" PRIx64
1490 " is too large to fit in a %" PRIu64
1491 " byte unsigned integer value.\n",
1492 uval64, (uint64_t)item_byte_size);
1493 result.SetStatus(eReturnStatusFailed);
1494 return false;
1495 }
1496 buffer.PutMaxHex64(uval64, item_byte_size);
1497 break;
1498
1499 case eFormatCharArray:
1500 case eFormatChar:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001501 case eFormatCString: {
1502 if (entry.ref.empty())
1503 break;
1504
1505 size_t len = entry.ref.size();
1506 // Include the NULL for C strings...
1507 if (m_format_options.GetFormat() == eFormatCString)
1508 ++len;
Zachary Turner97206d52017-05-12 04:51:55 +00001509 Status error;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001510 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1511 addr += len;
1512 } else {
1513 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1514 " failed: %s.\n",
1515 addr, error.AsCString());
1516 result.SetStatus(eReturnStatusFailed);
1517 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 }
1519 break;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001520 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 case eFormatDecimal:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001522 if (entry.ref.getAsInteger(0, sval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001524 "'%s' is not a valid signed decimal value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525 result.SetStatus(eReturnStatusFailed);
1526 return false;
1527 } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) {
1528 result.AppendErrorWithFormat(
1529 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1530 " byte signed integer value.\n",
1531 sval64, (uint64_t)item_byte_size);
1532 result.SetStatus(eReturnStatusFailed);
1533 return false;
1534 }
1535 buffer.PutMaxHex64(sval64, item_byte_size);
1536 break;
1537
1538 case eFormatUnsigned:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001539
1540 if (!entry.ref.getAsInteger(0, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 result.AppendErrorWithFormat(
1542 "'%s' is not a valid unsigned decimal string value.\n",
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001543 entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544 result.SetStatus(eReturnStatusFailed);
1545 return false;
1546 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1547 result.AppendErrorWithFormat("Value %" PRIu64
1548 " is too large to fit in a %" PRIu64
1549 " byte unsigned integer value.\n",
1550 uval64, (uint64_t)item_byte_size);
1551 result.SetStatus(eReturnStatusFailed);
1552 return false;
1553 }
1554 buffer.PutMaxHex64(uval64, item_byte_size);
1555 break;
1556
1557 case eFormatOctal:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001558 if (entry.ref.getAsInteger(8, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001560 "'%s' is not a valid octal string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561 result.SetStatus(eReturnStatusFailed);
1562 return false;
1563 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1564 result.AppendErrorWithFormat("Value %" PRIo64
1565 " is too large to fit in a %" PRIu64
1566 " byte unsigned integer value.\n",
1567 uval64, (uint64_t)item_byte_size);
1568 result.SetStatus(eReturnStatusFailed);
1569 return false;
1570 }
1571 buffer.PutMaxHex64(uval64, item_byte_size);
1572 break;
1573 }
1574 }
1575
1576 if (!buffer.GetString().empty()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001577 Status error;
Zachary Turnerc1564272016-11-16 21:15:24 +00001578 if (process->WriteMemory(addr, buffer.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 buffer.GetString().size(),
1580 error) == buffer.GetString().size())
1581 return true;
1582 else {
1583 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1584 " failed: %s.\n",
1585 addr, error.AsCString());
1586 result.SetStatus(eReturnStatusFailed);
1587 return false;
1588 }
1589 }
1590 return true;
1591 }
1592
1593 OptionGroupOptions m_option_group;
1594 OptionGroupFormat m_format_options;
1595 OptionGroupWriteMemory m_memory_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001596};
1597
Kuba Breckabeed8212014-09-04 01:03:18 +00001598//----------------------------------------------------------------------
1599// Get malloc/free history of a memory address.
1600//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601class CommandObjectMemoryHistory : public CommandObjectParsed {
Kuba Breckabeed8212014-09-04 01:03:18 +00001602public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 CommandObjectMemoryHistory(CommandInterpreter &interpreter)
1604 : CommandObjectParsed(
1605 interpreter, "memory history", "Print recorded stack traces for "
1606 "allocation/deallocation events "
1607 "associated with an address.",
1608 nullptr,
1609 eCommandRequiresTarget | eCommandRequiresProcess |
1610 eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) {
1611 CommandArgumentEntry arg1;
1612 CommandArgumentData addr_arg;
Eugene Zelenko26cac3a2016-02-20 00:58:29 +00001613
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 // Define the first (and only) variant of this arg.
1615 addr_arg.arg_type = eArgTypeAddress;
1616 addr_arg.arg_repetition = eArgRepeatPlain;
Eugene Zelenko26cac3a2016-02-20 00:58:29 +00001617
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618 // There is only one variant this argument could be; put it into the
1619 // argument entry.
1620 arg1.push_back(addr_arg);
1621
1622 // Push the data for the first argument into the m_arguments vector.
1623 m_arguments.push_back(arg1);
1624 }
1625
1626 ~CommandObjectMemoryHistory() override = default;
1627
1628 const char *GetRepeatCommand(Args &current_command_args,
1629 uint32_t index) override {
1630 return m_cmd_name.c_str();
1631 }
1632
Kuba Breckabeed8212014-09-04 01:03:18 +00001633protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 bool DoExecute(Args &command, CommandReturnObject &result) override {
1635 const size_t argc = command.GetArgumentCount();
1636
1637 if (argc == 0 || argc > 1) {
1638 result.AppendErrorWithFormat("%s takes an address expression",
1639 m_cmd_name.c_str());
1640 result.SetStatus(eReturnStatusFailed);
1641 return false;
Kuba Breckabeed8212014-09-04 01:03:18 +00001642 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643
Zachary Turner97206d52017-05-12 04:51:55 +00001644 Status error;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001645 lldb::addr_t addr = OptionArgParser::ToAddress(
1646 &m_exe_ctx, command[0].ref, LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647
1648 if (addr == LLDB_INVALID_ADDRESS) {
1649 result.AppendError("invalid address expression");
1650 result.AppendError(error.AsCString());
1651 result.SetStatus(eReturnStatusFailed);
1652 return false;
1653 }
1654
1655 Stream *output_stream = &result.GetOutputStream();
1656
1657 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1658 const MemoryHistorySP &memory_history =
1659 MemoryHistory::FindPlugin(process_sp);
1660
1661 if (!memory_history) {
1662 result.AppendError("no available memory history provider");
1663 result.SetStatus(eReturnStatusFailed);
1664 return false;
1665 }
1666
1667 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1668
Jim Ingham6a9767c2016-11-08 20:36:40 +00001669 const bool stop_format = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001670 for (auto thread : thread_list) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001671 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 }
1673
1674 result.SetStatus(eReturnStatusSuccessFinishResult);
1675
1676 return true;
1677 }
Kuba Breckabeed8212014-09-04 01:03:18 +00001678};
1679
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680//-------------------------------------------------------------------------
Greg Clayton3385fa02016-06-09 16:34:06 +00001681// CommandObjectMemoryRegion
1682//-------------------------------------------------------------------------
1683#pragma mark CommandObjectMemoryRegion
1684
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685class CommandObjectMemoryRegion : public CommandObjectParsed {
Greg Clayton3385fa02016-06-09 16:34:06 +00001686public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 CommandObjectMemoryRegion(CommandInterpreter &interpreter)
1688 : CommandObjectParsed(interpreter, "memory region",
1689 "Get information on the memory region containing "
1690 "an address in the current target process.",
1691 "memory region ADDR",
1692 eCommandRequiresProcess | eCommandTryTargetAPILock |
1693 eCommandProcessMustBeLaunched),
1694 m_prev_end_addr(LLDB_INVALID_ADDRESS) {}
Greg Clayton3385fa02016-06-09 16:34:06 +00001695
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 ~CommandObjectMemoryRegion() override = default;
Greg Clayton3385fa02016-06-09 16:34:06 +00001697
1698protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 bool DoExecute(Args &command, CommandReturnObject &result) override {
1700 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1701 if (process_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001702 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 lldb::addr_t load_addr = m_prev_end_addr;
1704 m_prev_end_addr = LLDB_INVALID_ADDRESS;
Greg Clayton3385fa02016-06-09 16:34:06 +00001705
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706 const size_t argc = command.GetArgumentCount();
1707 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) {
1708 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n",
1709 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1710 result.SetStatus(eReturnStatusFailed);
1711 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712 if (command.GetArgumentCount() == 1) {
Jim Ingham7b579462018-04-11 19:27:03 +00001713 auto load_addr_str = command[0].ref;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001714 load_addr = OptionArgParser::ToAddress(&m_exe_ctx, load_addr_str,
1715 LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1717 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001718 "invalid address argument \"%s\": %s\n", command[0].c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719 error.AsCString());
Greg Clayton3385fa02016-06-09 16:34:06 +00001720 result.SetStatus(eReturnStatusFailed);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721 }
Greg Clayton3385fa02016-06-09 16:34:06 +00001722 }
Greg Clayton3385fa02016-06-09 16:34:06 +00001723
Kate Stoneb9c1b512016-09-06 20:57:50 +00001724 lldb_private::MemoryRegionInfo range_info;
1725 error = process_sp->GetMemoryRegionInfo(load_addr, range_info);
1726 if (error.Success()) {
1727 lldb_private::Address addr;
1728 ConstString section_name;
1729 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) {
1730 SectionSP section_sp(addr.GetSection());
1731 if (section_sp) {
1732 // Got the top most section, not the deepest section
1733 while (section_sp->GetParent())
1734 section_sp = section_sp->GetParent();
1735 section_name = section_sp->GetName();
1736 }
1737 }
1738 result.AppendMessageWithFormat(
1739 "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s\n",
1740 range_info.GetRange().GetRangeBase(),
1741 range_info.GetRange().GetRangeEnd(),
1742 range_info.GetReadable() ? 'r' : '-',
1743 range_info.GetWritable() ? 'w' : '-',
1744 range_info.GetExecutable() ? 'x' : '-', section_name ? " " : "",
1745 section_name ? section_name.AsCString() : "");
1746 m_prev_end_addr = range_info.GetRange().GetRangeEnd();
1747 result.SetStatus(eReturnStatusSuccessFinishResult);
1748 } else {
1749 result.SetStatus(eReturnStatusFailed);
1750 result.AppendErrorWithFormat("%s\n", error.AsCString());
1751 }
1752 }
1753 } else {
1754 m_prev_end_addr = LLDB_INVALID_ADDRESS;
1755 result.AppendError("invalid process");
1756 result.SetStatus(eReturnStatusFailed);
Greg Clayton3385fa02016-06-09 16:34:06 +00001757 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 return result.Succeeded();
1759 }
Greg Clayton3385fa02016-06-09 16:34:06 +00001760
Kate Stoneb9c1b512016-09-06 20:57:50 +00001761 const char *GetRepeatCommand(Args &current_command_args,
1762 uint32_t index) override {
1763 // If we repeat this command, repeat it without any arguments so we can
1764 // show the next memory range
1765 return m_cmd_name.c_str();
1766 }
1767
1768 lldb::addr_t m_prev_end_addr;
Greg Clayton3385fa02016-06-09 16:34:06 +00001769};
1770
1771//-------------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001772// CommandObjectMemory
1773//-------------------------------------------------------------------------
1774
Kate Stone7428a182016-07-14 22:03:10 +00001775CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001776 : CommandObjectMultiword(
1777 interpreter, "memory",
1778 "Commands for operating on memory in the current target process.",
1779 "memory <subcommand> [<subcommand-options>]") {
1780 LoadSubCommand("find",
1781 CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1782 LoadSubCommand("read",
1783 CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1784 LoadSubCommand("write",
1785 CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1786 LoadSubCommand("history",
1787 CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1788 LoadSubCommand("region",
1789 CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790}
1791
Eugene Zelenko26cac3a2016-02-20 00:58:29 +00001792CommandObjectMemory::~CommandObjectMemory() = default;