blob: 236c7bf2c4300927dc3d095801b0677cfee42b61 [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"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/DataBufferHeap.h"
21#include "lldb/Core/DataExtractor.h"
Greg Clayton66111032010-06-23 01:19:29 +000022#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000024#include "lldb/Core/Section.h"
Greg Clayton84c39662011-04-27 22:04:39 +000025#include "lldb/Core/ValueObjectMemory.h"
Enrico Granata4d93b8c2013-09-30 19:11:51 +000026#include "lldb/DataFormatters/ValueObjectPrinter.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000027#include "lldb/Host/StringConvert.h"
Greg Clayton66111032010-06-23 01:19:29 +000028#include "lldb/Interpreter/Args.h"
Greg Clayton66111032010-06-23 01:19:29 +000029#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000030#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton84c39662011-04-27 22:04:39 +000031#include "lldb/Interpreter/OptionGroupFormat.h"
32#include "lldb/Interpreter/OptionGroupOutputFile.h"
Greg Clayton68ebae62011-04-28 20:55:26 +000033#include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
Greg Clayton67cc0632012-08-22 17:17:09 +000034#include "lldb/Interpreter/OptionValueString.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000035#include "lldb/Interpreter/Options.h"
Greg Claytond8d4a572015-08-11 21:38:15 +000036#include "lldb/Symbol/ClangASTContext.h"
Greg Claytonae088e52016-02-10 21:28:13 +000037#include "lldb/Symbol/SymbolFile.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000038#include "lldb/Symbol/TypeList.h"
Kuba Breckabeed8212014-09-04 01:03:18 +000039#include "lldb/Target/MemoryHistory.h"
Greg Clayton3385fa02016-06-09 16:34:06 +000040#include "lldb/Target/MemoryRegionInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/Process.h"
Jason Molendab57e4a12013-11-04 09:33:30 +000042#include "lldb/Target/StackFrame.h"
Kuba Breckabeed8212014-09-04 01:03:18 +000043#include "lldb/Target/Thread.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000044#include "lldb/Utility/StreamString.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045
Jason Molendaebeff4c2016-02-16 04:20:56 +000046#include "lldb/lldb-private.h"
Jason Molenda62e06812016-02-16 04:14:33 +000047
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048using namespace lldb;
49using namespace lldb_private;
50
Zachary Turner1f0f5b52016-09-22 20:22:55 +000051static OptionDefinition g_read_memory_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +000052 // clang-format off
Kate Stoneac9c3a62016-08-26 23:28:47 +000053 {LLDB_OPT_SET_1, false, "num-per-line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNumberPerLine, "The number of items per line to display." },
54 {LLDB_OPT_SET_2, false, "binary", 'b', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "If true, memory will be saved as binary. If false, the memory is saved save as an ASCII dump that "
55 "uses the format, size, count and number per line settings." },
56 {LLDB_OPT_SET_3, true , "type", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "The name of a type to view memory as." },
57 {LLDB_OPT_SET_3, false, "offset", 'E', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many elements of the specified type to skip before starting to display data." },
58 {LLDB_OPT_SET_1 |
59 LLDB_OPT_SET_2 |
60 LLDB_OPT_SET_3, false, "force", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Necessary if reading over target.max-memory-read-size bytes." },
Kate Stoneb9c1b512016-09-06 20:57:50 +000061 // clang-format on
Greg Clayton84c39662011-04-27 22:04:39 +000062};
63
Kate Stoneb9c1b512016-09-06 20:57:50 +000064class OptionGroupReadMemory : public OptionGroup {
Greg Clayton84c39662011-04-27 22:04:39 +000065public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000066 OptionGroupReadMemory()
67 : m_num_per_line(1, 1), m_output_as_binary(false), m_view_as_type(),
68 m_offset(0, 0) {}
Greg Clayton84c39662011-04-27 22:04:39 +000069
Kate Stoneb9c1b512016-09-06 20:57:50 +000070 ~OptionGroupReadMemory() override = default;
Eugene Zelenko26cac3a2016-02-20 00:58:29 +000071
Zachary Turner1f0f5b52016-09-22 20:22:55 +000072 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +000073 return llvm::makeArrayRef(g_read_memory_options);
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 }
Greg Clayton1deb7962011-10-25 06:44:01 +000075
Zachary Turner8cef4b02016-09-23 17:48:13 +000076 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 ExecutionContext *execution_context) override {
78 Error error;
Zachary Turner1f0f5b52016-09-22 20:22:55 +000079 const int short_option = g_read_memory_options[option_idx].short_option;
Kate Stoneb9c1b512016-09-06 20:57:50 +000080
81 switch (short_option) {
82 case 'l':
Zachary Turner8cef4b02016-09-23 17:48:13 +000083 error = m_num_per_line.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 if (m_num_per_line.GetCurrentValue() == 0)
85 error.SetErrorStringWithFormat(
Zachary Turner8cef4b02016-09-23 17:48:13 +000086 "invalid value for --num-per-line option '%s'",
87 option_value.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 break;
89
90 case 'b':
91 m_output_as_binary = true;
92 break;
93
94 case 't':
Zachary Turner8cef4b02016-09-23 17:48:13 +000095 error = m_view_as_type.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 break;
97
98 case 'r':
99 m_force = true;
100 break;
101
102 case 'E':
Zachary Turner8cef4b02016-09-23 17:48:13 +0000103 error = m_offset.SetValueFromString(option_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104 break;
105
106 default:
107 error.SetErrorStringWithFormat("unrecognized short option '%c'",
108 short_option);
109 break;
110 }
111 return error;
112 }
113
114 void OptionParsingStarting(ExecutionContext *execution_context) override {
115 m_num_per_line.Clear();
116 m_output_as_binary = false;
117 m_view_as_type.Clear();
118 m_force = false;
119 m_offset.Clear();
120 }
121
122 Error FinalizeSettings(Target *target, OptionGroupFormat &format_options) {
123 Error error;
124 OptionValueUInt64 &byte_size_value = format_options.GetByteSizeValue();
125 OptionValueUInt64 &count_value = format_options.GetCountValue();
126 const bool byte_size_option_set = byte_size_value.OptionWasSet();
127 const bool num_per_line_option_set = m_num_per_line.OptionWasSet();
128 const bool count_option_set = format_options.GetCountValue().OptionWasSet();
129
130 switch (format_options.GetFormat()) {
131 default:
132 break;
133
134 case eFormatBoolean:
135 if (!byte_size_option_set)
136 byte_size_value = 1;
137 if (!num_per_line_option_set)
138 m_num_per_line = 1;
139 if (!count_option_set)
140 format_options.GetCountValue() = 8;
141 break;
142
143 case eFormatCString:
144 break;
145
146 case eFormatInstruction:
147 if (count_option_set)
148 byte_size_value = target->GetArchitecture().GetMaximumOpcodeByteSize();
149 m_num_per_line = 1;
150 break;
151
152 case eFormatAddressInfo:
153 if (!byte_size_option_set)
154 byte_size_value = target->GetArchitecture().GetAddressByteSize();
155 m_num_per_line = 1;
156 if (!count_option_set)
157 format_options.GetCountValue() = 8;
158 break;
159
160 case eFormatPointer:
161 byte_size_value = target->GetArchitecture().GetAddressByteSize();
162 if (!num_per_line_option_set)
163 m_num_per_line = 4;
164 if (!count_option_set)
165 format_options.GetCountValue() = 8;
166 break;
167
168 case eFormatBinary:
169 case eFormatFloat:
170 case eFormatOctal:
171 case eFormatDecimal:
172 case eFormatEnum:
173 case eFormatUnicode16:
174 case eFormatUnicode32:
175 case eFormatUnsigned:
176 case eFormatHexFloat:
177 if (!byte_size_option_set)
178 byte_size_value = 4;
179 if (!num_per_line_option_set)
180 m_num_per_line = 1;
181 if (!count_option_set)
182 format_options.GetCountValue() = 8;
183 break;
184
185 case eFormatBytes:
186 case eFormatBytesWithASCII:
187 if (byte_size_option_set) {
188 if (byte_size_value > 1)
189 error.SetErrorStringWithFormat(
190 "display format (bytes/bytes with ASCII) conflicts with the "
191 "specified byte size %" PRIu64 "\n"
192 "\tconsider using a different display format or don't specify "
193 "the byte size.",
194 byte_size_value.GetCurrentValue());
195 } else
196 byte_size_value = 1;
197 if (!num_per_line_option_set)
198 m_num_per_line = 16;
199 if (!count_option_set)
200 format_options.GetCountValue() = 32;
201 break;
202
203 case eFormatCharArray:
204 case eFormatChar:
205 case eFormatCharPrintable:
206 if (!byte_size_option_set)
207 byte_size_value = 1;
208 if (!num_per_line_option_set)
209 m_num_per_line = 32;
210 if (!count_option_set)
211 format_options.GetCountValue() = 64;
212 break;
213
214 case eFormatComplex:
215 if (!byte_size_option_set)
216 byte_size_value = 8;
217 if (!num_per_line_option_set)
218 m_num_per_line = 1;
219 if (!count_option_set)
220 format_options.GetCountValue() = 8;
221 break;
222
223 case eFormatComplexInteger:
224 if (!byte_size_option_set)
225 byte_size_value = 8;
226 if (!num_per_line_option_set)
227 m_num_per_line = 1;
228 if (!count_option_set)
229 format_options.GetCountValue() = 8;
230 break;
231
232 case eFormatHex:
233 if (!byte_size_option_set)
234 byte_size_value = 4;
235 if (!num_per_line_option_set) {
236 switch (byte_size_value) {
237 case 1:
238 case 2:
239 m_num_per_line = 8;
240 break;
241 case 4:
242 m_num_per_line = 4;
243 break;
244 case 8:
245 m_num_per_line = 2;
246 break;
247 default:
248 m_num_per_line = 1;
249 break;
Greg Clayton84c39662011-04-27 22:04:39 +0000250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 }
252 if (!count_option_set)
253 count_value = 8;
254 break;
255
256 case eFormatVectorOfChar:
257 case eFormatVectorOfSInt8:
258 case eFormatVectorOfUInt8:
259 case eFormatVectorOfSInt16:
260 case eFormatVectorOfUInt16:
261 case eFormatVectorOfSInt32:
262 case eFormatVectorOfUInt32:
263 case eFormatVectorOfSInt64:
264 case eFormatVectorOfUInt64:
265 case eFormatVectorOfFloat16:
266 case eFormatVectorOfFloat32:
267 case eFormatVectorOfFloat64:
268 case eFormatVectorOfUInt128:
269 if (!byte_size_option_set)
270 byte_size_value = 128;
271 if (!num_per_line_option_set)
272 m_num_per_line = 1;
273 if (!count_option_set)
274 count_value = 4;
275 break;
Greg Clayton84c39662011-04-27 22:04:39 +0000276 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 return error;
278 }
Greg Clayton5009f9d2011-10-27 17:55:14 +0000279
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280 bool AnyOptionWasSet() const {
281 return m_num_per_line.OptionWasSet() || m_output_as_binary ||
282 m_view_as_type.OptionWasSet() || m_offset.OptionWasSet();
283 }
Greg Clayton5009f9d2011-10-27 17:55:14 +0000284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 OptionValueUInt64 m_num_per_line;
286 bool m_output_as_binary;
287 OptionValueString m_view_as_type;
288 bool m_force;
289 OptionValueUInt64 m_offset;
Greg Clayton84c39662011-04-27 22:04:39 +0000290};
291
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292//----------------------------------------------------------------------
293// Read memory from the inferior process
294//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295class CommandObjectMemoryRead : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000296public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 CommandObjectMemoryRead(CommandInterpreter &interpreter)
298 : CommandObjectParsed(
299 interpreter, "memory read",
300 "Read from the memory of the current target process.", nullptr,
301 eCommandRequiresTarget | eCommandProcessMustBePaused),
302 m_option_group(), m_format_options(eFormatBytesWithASCII, 1, 8),
303 m_memory_options(), m_outfile_options(), m_varobj_options(),
304 m_next_addr(LLDB_INVALID_ADDRESS), m_prev_byte_size(0),
305 m_prev_format_options(eFormatBytesWithASCII, 1, 8),
306 m_prev_memory_options(), m_prev_outfile_options(),
307 m_prev_varobj_options() {
308 CommandArgumentEntry arg1;
309 CommandArgumentEntry arg2;
310 CommandArgumentData start_addr_arg;
311 CommandArgumentData end_addr_arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 // Define the first (and only) variant of this arg.
314 start_addr_arg.arg_type = eArgTypeAddressOrExpression;
315 start_addr_arg.arg_repetition = eArgRepeatPlain;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 // There is only one variant this argument could be; put it into the
318 // argument entry.
319 arg1.push_back(start_addr_arg);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 // Define the first (and only) variant of this arg.
322 end_addr_arg.arg_type = eArgTypeAddressOrExpression;
323 end_addr_arg.arg_repetition = eArgRepeatOptional;
324
325 // There is only one variant this argument could be; put it into the
326 // argument entry.
327 arg2.push_back(end_addr_arg);
328
329 // Push the data for the first argument into the m_arguments vector.
330 m_arguments.push_back(arg1);
331 m_arguments.push_back(arg2);
332
333 // Add the "--format" and "--count" options to group 1 and 3
334 m_option_group.Append(&m_format_options,
335 OptionGroupFormat::OPTION_GROUP_FORMAT |
336 OptionGroupFormat::OPTION_GROUP_COUNT,
337 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
338 m_option_group.Append(&m_format_options,
339 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
340 LLDB_OPT_SET_1 | LLDB_OPT_SET_3);
341 // Add the "--size" option to group 1 and 2
342 m_option_group.Append(&m_format_options,
343 OptionGroupFormat::OPTION_GROUP_SIZE,
344 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
345 m_option_group.Append(&m_memory_options);
346 m_option_group.Append(&m_outfile_options, LLDB_OPT_SET_ALL,
347 LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3);
348 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
349 m_option_group.Finalize();
350 }
351
352 ~CommandObjectMemoryRead() override = default;
353
354 Options *GetOptions() override { return &m_option_group; }
355
356 const char *GetRepeatCommand(Args &current_command_args,
357 uint32_t index) override {
358 return m_cmd_name.c_str();
359 }
Greg Clayton82f4cf42011-10-26 04:32:38 +0000360
Jim Ingham5a988412012-06-08 21:56:10 +0000361protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 bool DoExecute(Args &command, CommandReturnObject &result) override {
363 // No need to check "target" for validity as eCommandRequiresTarget ensures
364 // it is valid
365 Target *target = m_exe_ctx.GetTargetPtr();
Greg Claytonf9fc6092013-01-09 19:44:40 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 const size_t argc = command.GetArgumentCount();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 if ((argc == 0 && m_next_addr == LLDB_INVALID_ADDRESS) || argc > 2) {
370 result.AppendErrorWithFormat("%s takes a start address expression with "
371 "an optional end address expression.\n",
372 m_cmd_name.c_str());
373 result.AppendRawWarning("Expressions should be quoted if they contain "
374 "spaces or other special characters.\n");
375 result.SetStatus(eReturnStatusFailed);
376 return false;
377 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 CompilerType clang_ast_type;
380 Error error;
Greg Clayton68ebae62011-04-28 20:55:26 +0000381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 const char *view_as_type_cstr =
383 m_memory_options.m_view_as_type.GetCurrentValue();
384 if (view_as_type_cstr && view_as_type_cstr[0]) {
385 // We are viewing memory as a type
386
387 SymbolContext sc;
388 const bool exact_match = false;
389 TypeList type_list;
390 uint32_t reference_count = 0;
391 uint32_t pointer_count = 0;
392 size_t idx;
393
394#define ALL_KEYWORDS \
395 KEYWORD("const") \
396 KEYWORD("volatile") \
397 KEYWORD("restrict") \
398 KEYWORD("struct") \
399 KEYWORD("class") \
400 KEYWORD("union")
401
Sean Callanan17cf1132012-07-10 21:24:26 +0000402#define KEYWORD(s) s,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 static const char *g_keywords[] = {ALL_KEYWORDS};
Sean Callanan17cf1132012-07-10 21:24:26 +0000404#undef KEYWORD
405
406#define KEYWORD(s) (sizeof(s) - 1),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 static const int g_keyword_lengths[] = {ALL_KEYWORDS};
Sean Callanan17cf1132012-07-10 21:24:26 +0000408#undef KEYWORD
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409
Sean Callanan17cf1132012-07-10 21:24:26 +0000410#undef ALL_KEYWORDS
Greg Clayton84c39662011-04-27 22:04:39 +0000411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 static size_t g_num_keywords = sizeof(g_keywords) / sizeof(const char *);
413 std::string type_str(view_as_type_cstr);
Greg Clayton84c39662011-04-27 22:04:39 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 // Remove all instances of g_keywords that are followed by spaces
416 for (size_t i = 0; i < g_num_keywords; ++i) {
417 const char *keyword = g_keywords[i];
418 int keyword_len = g_keyword_lengths[i];
Saleem Abdulrasoolba507b02015-10-18 19:34:38 +0000419
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 idx = 0;
421 while ((idx = type_str.find(keyword, idx)) != std::string::npos) {
422 if (type_str[idx + keyword_len] == ' ' ||
423 type_str[idx + keyword_len] == '\t') {
424 type_str.erase(idx, keyword_len + 1);
425 idx = 0;
426 } else {
427 idx += keyword_len;
428 }
Greg Clayton84c39662011-04-27 22:04:39 +0000429 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 }
431 bool done = type_str.empty();
432 //
433 idx = type_str.find_first_not_of(" \t");
434 if (idx > 0 && idx != std::string::npos)
435 type_str.erase(0, idx);
436 while (!done) {
437 // Strip trailing spaces
438 if (type_str.empty())
439 done = true;
440 else {
441 switch (type_str[type_str.size() - 1]) {
442 case '*':
443 ++pointer_count;
444 LLVM_FALLTHROUGH;
445 case ' ':
446 case '\t':
447 type_str.erase(type_str.size() - 1);
448 break;
Greg Clayton68ebae62011-04-28 20:55:26 +0000449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 case '&':
451 if (reference_count == 0) {
452 reference_count = 1;
453 type_str.erase(type_str.size() - 1);
454 } else {
455 result.AppendErrorWithFormat("invalid type string: '%s'\n",
456 view_as_type_cstr);
457 result.SetStatus(eReturnStatusFailed);
458 return false;
Greg Clayton82f4cf42011-10-26 04:32:38 +0000459 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 break;
461
462 default:
463 done = true;
464 break;
465 }
Greg Clayton82f4cf42011-10-26 04:32:38 +0000466 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 }
Greg Clayton82f4cf42011-10-26 04:32:38 +0000468
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files;
470 ConstString lookup_type_name(type_str.c_str());
471 StackFrame *frame = m_exe_ctx.GetFramePtr();
472 if (frame) {
473 sc = frame->GetSymbolContext(eSymbolContextModule);
474 if (sc.module_sp) {
475 sc.module_sp->FindTypes(sc, lookup_type_name, exact_match, 1,
476 searched_symbol_files, type_list);
Greg Clayton82f4cf42011-10-26 04:32:38 +0000477 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 }
479 if (type_list.GetSize() == 0) {
480 target->GetImages().FindTypes(sc, lookup_type_name, exact_match, 1,
481 searched_symbol_files, type_list);
482 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 if (type_list.GetSize() == 0 && lookup_type_name.GetCString() &&
485 *lookup_type_name.GetCString() == '$') {
486 if (ClangPersistentVariables *persistent_vars =
487 llvm::dyn_cast_or_null<ClangPersistentVariables>(
488 target->GetPersistentExpressionStateForLanguage(
489 lldb::eLanguageTypeC))) {
490 clang::TypeDecl *tdecl = llvm::dyn_cast_or_null<clang::TypeDecl>(
491 persistent_vars->GetPersistentDecl(
492 ConstString(lookup_type_name)));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 if (tdecl) {
495 clang_ast_type.SetCompilerType(
496 ClangASTContext::GetASTContext(&tdecl->getASTContext()),
497 reinterpret_cast<lldb::opaque_compiler_type_t>(
498 const_cast<clang::Type *>(tdecl->getTypeForDecl())));
499 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000500 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (!clang_ast_type.IsValid()) {
504 if (type_list.GetSize() == 0) {
505 result.AppendErrorWithFormat("unable to find any types that match "
506 "the raw type '%s' for full type '%s'\n",
507 lookup_type_name.GetCString(),
508 view_as_type_cstr);
509 result.SetStatus(eReturnStatusFailed);
510 return false;
511 } else {
512 TypeSP type_sp(type_list.GetTypeAtIndex(0));
513 clang_ast_type = type_sp->GetFullCompilerType();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 }
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 while (pointer_count > 0) {
518 CompilerType pointer_type = clang_ast_type.GetPointerType();
519 if (pointer_type.IsValid())
520 clang_ast_type = pointer_type;
521 else {
522 result.AppendError("unable make a pointer type\n");
523 result.SetStatus(eReturnStatusFailed);
524 return false;
Sean Callanan1276c332012-04-28 01:27:38 +0000525 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 --pointer_count;
527 }
Greg Clayton2e1f7452012-12-15 02:08:17 +0000528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 m_format_options.GetByteSizeValue() = clang_ast_type.GetByteSize(nullptr);
Greg Clayton46a44262013-07-24 18:17:35 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 if (m_format_options.GetByteSizeValue() == 0) {
532 result.AppendErrorWithFormat(
533 "unable to get the byte size of the type '%s'\n",
534 view_as_type_cstr);
535 result.SetStatus(eReturnStatusFailed);
536 return false;
537 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 if (!m_format_options.GetCountValue().OptionWasSet())
540 m_format_options.GetCountValue() = 1;
541 } else {
542 error = m_memory_options.FinalizeSettings(target, m_format_options);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543 }
544
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 // Look for invalid combinations of settings
546 if (error.Fail()) {
547 result.AppendError(error.AsCString());
548 result.SetStatus(eReturnStatusFailed);
549 return false;
550 }
551
552 lldb::addr_t addr;
553 size_t total_byte_size = 0;
554 if (argc == 0) {
555 // Use the last address and byte size and all options as they were
556 // if no options have been set
557 addr = m_next_addr;
558 total_byte_size = m_prev_byte_size;
559 clang_ast_type = m_prev_clang_ast_type;
560 if (!m_format_options.AnyOptionWasSet() &&
561 !m_memory_options.AnyOptionWasSet() &&
562 !m_outfile_options.AnyOptionWasSet() &&
563 !m_varobj_options.AnyOptionWasSet()) {
564 m_format_options = m_prev_format_options;
565 m_memory_options = m_prev_memory_options;
566 m_outfile_options = m_prev_outfile_options;
567 m_varobj_options = m_prev_varobj_options;
568 }
569 }
570
571 size_t item_count = m_format_options.GetCountValue().GetCurrentValue();
572
573 // TODO For non-8-bit byte addressable architectures this needs to be
574 // revisited to fully support all lldb's range of formatting options.
575 // Furthermore code memory reads (for those architectures) will not
576 // be correctly formatted even w/o formatting options.
577 size_t item_byte_size =
578 target->GetArchitecture().GetDataByteSize() > 1
579 ? target->GetArchitecture().GetDataByteSize()
580 : m_format_options.GetByteSizeValue().GetCurrentValue();
581
582 const size_t num_per_line =
583 m_memory_options.m_num_per_line.GetCurrentValue();
584
585 if (total_byte_size == 0) {
586 total_byte_size = item_count * item_byte_size;
587 if (total_byte_size == 0)
588 total_byte_size = 32;
589 }
590
591 if (argc > 0)
Zachary Turner14f6b2c2016-12-09 01:08:29 +0000592 addr = Args::StringToAddress(&m_exe_ctx, command[0].ref,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 LLDB_INVALID_ADDRESS, &error);
594
595 if (addr == LLDB_INVALID_ADDRESS) {
596 result.AppendError("invalid start address expression.");
597 result.AppendError(error.AsCString());
598 result.SetStatus(eReturnStatusFailed);
599 return false;
600 }
601
602 if (argc == 2) {
Zachary Turner14f6b2c2016-12-09 01:08:29 +0000603 lldb::addr_t end_addr = Args::StringToAddress(
604 &m_exe_ctx, command[1].ref, LLDB_INVALID_ADDRESS, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 if (end_addr == LLDB_INVALID_ADDRESS) {
606 result.AppendError("invalid end address expression.");
607 result.AppendError(error.AsCString());
608 result.SetStatus(eReturnStatusFailed);
609 return false;
610 } else if (end_addr <= addr) {
611 result.AppendErrorWithFormat(
612 "end address (0x%" PRIx64
613 ") must be greater that the start address (0x%" PRIx64 ").\n",
614 end_addr, addr);
615 result.SetStatus(eReturnStatusFailed);
616 return false;
617 } else if (m_format_options.GetCountValue().OptionWasSet()) {
618 result.AppendErrorWithFormat(
619 "specify either the end address (0x%" PRIx64
620 ") or the count (--count %" PRIu64 "), not both.\n",
621 end_addr, (uint64_t)item_count);
622 result.SetStatus(eReturnStatusFailed);
623 return false;
624 }
625
626 total_byte_size = end_addr - addr;
627 item_count = total_byte_size / item_byte_size;
628 }
629
630 uint32_t max_unforced_size = target->GetMaximumMemReadSize();
631
632 if (total_byte_size > max_unforced_size && !m_memory_options.m_force) {
633 result.AppendErrorWithFormat(
634 "Normally, \'memory read\' will not read over %" PRIu32
635 " bytes of data.\n",
636 max_unforced_size);
637 result.AppendErrorWithFormat(
638 "Please use --force to override this restriction just once.\n");
639 result.AppendErrorWithFormat("or set target.max-memory-read-size if you "
640 "will often need a larger limit.\n");
641 return false;
642 }
643
644 DataBufferSP data_sp;
645 size_t bytes_read = 0;
646 if (clang_ast_type.GetOpaqueQualType()) {
647 // Make sure we don't display our type as ASCII bytes like the default
648 // memory read
649 if (!m_format_options.GetFormatValue().OptionWasSet())
650 m_format_options.GetFormatValue().SetCurrentValue(eFormatDefault);
651
652 bytes_read = clang_ast_type.GetByteSize(nullptr) *
653 m_format_options.GetCountValue().GetCurrentValue();
654
655 if (argc > 0)
656 addr = addr + (clang_ast_type.GetByteSize(nullptr) *
657 m_memory_options.m_offset.GetCurrentValue());
658 } else if (m_format_options.GetFormatValue().GetCurrentValue() !=
659 eFormatCString) {
660 data_sp.reset(new DataBufferHeap(total_byte_size, '\0'));
661 if (data_sp->GetBytes() == nullptr) {
662 result.AppendErrorWithFormat(
663 "can't allocate 0x%" PRIx32
664 " bytes for the memory read buffer, specify a smaller size to read",
665 (uint32_t)total_byte_size);
666 result.SetStatus(eReturnStatusFailed);
667 return false;
668 }
669
670 Address address(addr, nullptr);
671 bytes_read = target->ReadMemory(address, false, data_sp->GetBytes(),
672 data_sp->GetByteSize(), error);
673 if (bytes_read == 0) {
674 const char *error_cstr = error.AsCString();
675 if (error_cstr && error_cstr[0]) {
676 result.AppendError(error_cstr);
677 } else {
678 result.AppendErrorWithFormat(
679 "failed to read memory from 0x%" PRIx64 ".\n", addr);
680 }
681 result.SetStatus(eReturnStatusFailed);
682 return false;
683 }
684
685 if (bytes_read < total_byte_size)
686 result.AppendWarningWithFormat(
687 "Not all bytes (%" PRIu64 "/%" PRIu64
688 ") were able to be read from 0x%" PRIx64 ".\n",
689 (uint64_t)bytes_read, (uint64_t)total_byte_size, addr);
690 } else {
691 // we treat c-strings as a special case because they do not have a fixed
692 // size
693 if (m_format_options.GetByteSizeValue().OptionWasSet() &&
694 !m_format_options.HasGDBFormat())
695 item_byte_size = m_format_options.GetByteSizeValue().GetCurrentValue();
696 else
697 item_byte_size = target->GetMaximumSizeOfStringSummary();
698 if (!m_format_options.GetCountValue().OptionWasSet())
699 item_count = 1;
700 data_sp.reset(new DataBufferHeap((item_byte_size + 1) * item_count,
701 '\0')); // account for NULLs as necessary
702 if (data_sp->GetBytes() == nullptr) {
703 result.AppendErrorWithFormat(
704 "can't allocate 0x%" PRIx64
705 " bytes for the memory read buffer, specify a smaller size to read",
706 (uint64_t)((item_byte_size + 1) * item_count));
707 result.SetStatus(eReturnStatusFailed);
708 return false;
709 }
710 uint8_t *data_ptr = data_sp->GetBytes();
711 auto data_addr = addr;
712 auto count = item_count;
713 item_count = 0;
714 bool break_on_no_NULL = false;
715 while (item_count < count) {
716 std::string buffer;
717 buffer.resize(item_byte_size + 1, 0);
718 Error error;
719 size_t read = target->ReadCStringFromMemory(data_addr, &buffer[0],
720 item_byte_size + 1, error);
721 if (error.Fail()) {
722 result.AppendErrorWithFormat(
723 "failed to read memory from 0x%" PRIx64 ".\n", addr);
724 result.SetStatus(eReturnStatusFailed);
725 return false;
726 }
727
728 if (item_byte_size == read) {
729 result.AppendWarningWithFormat(
730 "unable to find a NULL terminated string at 0x%" PRIx64
731 ".Consider increasing the maximum read length.\n",
732 data_addr);
733 --read;
734 break_on_no_NULL = true;
735 } else
736 ++read; // account for final NULL byte
737
738 memcpy(data_ptr, &buffer[0], read);
739 data_ptr += read;
740 data_addr += read;
741 bytes_read += read;
742 item_count++; // if we break early we know we only read item_count
743 // strings
744
745 if (break_on_no_NULL)
746 break;
747 }
748 data_sp.reset(new DataBufferHeap(data_sp->GetBytes(), bytes_read + 1));
749 }
750
751 m_next_addr = addr + bytes_read;
752 m_prev_byte_size = bytes_read;
753 m_prev_format_options = m_format_options;
754 m_prev_memory_options = m_memory_options;
755 m_prev_outfile_options = m_outfile_options;
756 m_prev_varobj_options = m_varobj_options;
757 m_prev_clang_ast_type = clang_ast_type;
758
759 StreamFile outfile_stream;
760 Stream *output_stream = nullptr;
761 const FileSpec &outfile_spec =
762 m_outfile_options.GetFile().GetCurrentValue();
763 if (outfile_spec) {
764 char path[PATH_MAX];
765 outfile_spec.GetPath(path, sizeof(path));
766
767 uint32_t open_options =
768 File::eOpenOptionWrite | File::eOpenOptionCanCreate;
769 const bool append = m_outfile_options.GetAppend().GetCurrentValue();
770 if (append)
771 open_options |= File::eOpenOptionAppend;
772
773 if (outfile_stream.GetFile().Open(path, open_options).Success()) {
774 if (m_memory_options.m_output_as_binary) {
775 const size_t bytes_written =
776 outfile_stream.Write(data_sp->GetBytes(), bytes_read);
777 if (bytes_written > 0) {
778 result.GetOutputStream().Printf(
779 "%zi bytes %s to '%s'\n", bytes_written,
780 append ? "appended" : "written", path);
781 return true;
782 } else {
783 result.AppendErrorWithFormat("Failed to write %" PRIu64
784 " bytes to '%s'.\n",
785 (uint64_t)bytes_read, path);
786 result.SetStatus(eReturnStatusFailed);
787 return false;
788 }
789 } else {
790 // We are going to write ASCII to the file just point the
791 // output_stream to our outfile_stream...
792 output_stream = &outfile_stream;
793 }
794 } else {
795 result.AppendErrorWithFormat("Failed to open file '%s' for %s.\n", path,
796 append ? "append" : "write");
797 result.SetStatus(eReturnStatusFailed);
798 return false;
799 }
800 } else {
801 output_stream = &result.GetOutputStream();
802 }
803
804 ExecutionContextScope *exe_scope = m_exe_ctx.GetBestExecutionContextScope();
805 if (clang_ast_type.GetOpaqueQualType()) {
806 for (uint32_t i = 0; i < item_count; ++i) {
807 addr_t item_addr = addr + (i * item_byte_size);
808 Address address(item_addr);
809 StreamString name_strm;
810 name_strm.Printf("0x%" PRIx64, item_addr);
811 ValueObjectSP valobj_sp(ValueObjectMemory::Create(
Zachary Turner22a26282016-11-12 18:17:36 +0000812 exe_scope, name_strm.GetString(), address, clang_ast_type));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 if (valobj_sp) {
814 Format format = m_format_options.GetFormat();
815 if (format != eFormatDefault)
816 valobj_sp->SetFormat(format);
817
818 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
819 eLanguageRuntimeDescriptionDisplayVerbosityFull, format));
820
821 valobj_sp->Dump(*output_stream, options);
822 } else {
823 result.AppendErrorWithFormat(
824 "failed to create a value object for: (%s) %s\n",
Zachary Turnerc1564272016-11-16 21:15:24 +0000825 view_as_type_cstr, name_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 result.SetStatus(eReturnStatusFailed);
827 return false;
828 }
829 }
830 return true;
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?)
846 // into a request for fetching 10 chars of size 1 from the same memory
847 // location
848 format = eFormatCharArray;
849 item_count = item_byte_size;
850 item_byte_size = 1;
851 } else {
852 // here we passed a count, and it was not 1
853 // so we have a byte_size and a count
854 // we could well multiply those, but instead let's just fail
855 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);
864 size_t bytes_dumped =
865 data.Dump(output_stream, 0, format, item_byte_size, item_count,
866 num_per_line / target->GetArchitecture().GetDataByteSize(),
867 addr, 0, 0, exe_scope);
868 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887OptionDefinition g_memory_find_option_table[] = {
888 // clang-format off
Kate Stoneac9c3a62016-08-26 23:28:47 +0000889 {LLDB_OPT_SET_1, true, "expression", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeExpression, "Evaluate an expression to obtain a byte pattern."},
890 {LLDB_OPT_SET_2, true, "string", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeName, "Use text to find a byte pattern."},
891 {LLDB_OPT_SET_ALL, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many times to perform the search."},
892 {LLDB_OPT_SET_ALL, false, "dump-offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "When dumping memory for a match, an offset from the match location to start dumping from."},
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 Turner8cef4b02016-09-23 17:48:13 +0000911 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 ExecutionContext *execution_context) override {
913 Error error;
914 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;
1010 Error error;
1011 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
1037 Error error;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001038 lldb::addr_t low_addr = Args::StringToAddress(&m_exe_ctx, command[0].ref,
1039 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 }
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001044 lldb::addr_t high_addr = Args::StringToAddress(
1045 &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());
1134 data.Dump(&result.GetOutputStream(), 0, lldb::eFormatBytesWithASCII, 1,
1135 dumpbuffer.GetByteSize(), 16,
1136 found_location + m_memory_options.m_offset.GetCurrentValue(),
1137 0, 0);
1138 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
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182OptionDefinition g_memory_write_option_table[] = {
1183 // clang-format off
Kate Stoneac9c3a62016-08-26 23:28:47 +00001184 {LLDB_OPT_SET_1, true, "infile", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Write memory using the contents of a file."},
1185 {LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, 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 Turner8cef4b02016-09-23 17:48:13 +00001204 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_value,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 ExecutionContext *execution_context) override {
1206 Error error;
1207 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':
Zachary Turner8cef4b02016-09-23 17:48:13 +00001212 m_infile.SetFile(option_value, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 if (!m_infile.Exists()) {
1214 m_infile.Clear();
1215 error.SetErrorStringWithFormat("input file does not exist: '%s'",
Zachary Turner8cef4b02016-09-23 17:48:13 +00001216 option_value.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 }
1218 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 case 'o': {
Zachary Turner8cef4b02016-09-23 17:48:13 +00001221 if (option_value.getAsInteger(0, m_infile_offset)) {
1222 m_infile_offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 error.SetErrorStringWithFormat("invalid offset string '%s'",
Zachary Turner8cef4b02016-09-23 17:48:13 +00001224 option_value.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225 }
1226 } break;
1227
1228 default:
1229 error.SetErrorStringWithFormat("unrecognized short option '%c'",
1230 short_option);
1231 break;
1232 }
1233 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001234 }
1235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 void OptionParsingStarting(ExecutionContext *execution_context) override {
1237 m_infile.Clear();
1238 m_infile_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001239 }
1240
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 FileSpec m_infile;
1242 off_t m_infile_offset;
1243 };
1244
1245 CommandObjectMemoryWrite(CommandInterpreter &interpreter)
1246 : CommandObjectParsed(
1247 interpreter, "memory write",
1248 "Write to the memory of the current target process.", nullptr,
1249 eCommandRequiresProcess | eCommandProcessMustBeLaunched),
1250 m_option_group(), m_format_options(eFormatBytes, 1, UINT64_MAX),
1251 m_memory_options() {
1252 CommandArgumentEntry arg1;
1253 CommandArgumentEntry arg2;
1254 CommandArgumentData addr_arg;
1255 CommandArgumentData value_arg;
1256
1257 // Define the first (and only) variant of this arg.
1258 addr_arg.arg_type = eArgTypeAddress;
1259 addr_arg.arg_repetition = eArgRepeatPlain;
1260
1261 // There is only one variant this argument could be; put it into the
1262 // argument entry.
1263 arg1.push_back(addr_arg);
1264
1265 // Define the first (and only) variant of this arg.
1266 value_arg.arg_type = eArgTypeValue;
1267 value_arg.arg_repetition = eArgRepeatPlus;
1268
1269 // There is only one variant this argument could be; put it into the
1270 // argument entry.
1271 arg2.push_back(value_arg);
1272
1273 // Push the data for the first argument into the m_arguments vector.
1274 m_arguments.push_back(arg1);
1275 m_arguments.push_back(arg2);
1276
1277 m_option_group.Append(&m_format_options,
1278 OptionGroupFormat::OPTION_GROUP_FORMAT,
1279 LLDB_OPT_SET_1);
1280 m_option_group.Append(&m_format_options,
1281 OptionGroupFormat::OPTION_GROUP_SIZE,
1282 LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
1283 m_option_group.Append(&m_memory_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_2);
1284 m_option_group.Finalize();
1285 }
1286
1287 ~CommandObjectMemoryWrite() override = default;
1288
1289 Options *GetOptions() override { return &m_option_group; }
1290
1291 bool UIntValueIsValidForSize(uint64_t uval64, size_t total_byte_size) {
1292 if (total_byte_size > 8)
1293 return false;
1294
1295 if (total_byte_size == 8)
1296 return true;
1297
1298 const uint64_t max = ((uint64_t)1 << (uint64_t)(total_byte_size * 8)) - 1;
1299 return uval64 <= max;
1300 }
1301
1302 bool SIntValueIsValidForSize(int64_t sval64, size_t total_byte_size) {
1303 if (total_byte_size > 8)
1304 return false;
1305
1306 if (total_byte_size == 8)
1307 return true;
1308
1309 const int64_t max = ((int64_t)1 << (uint64_t)(total_byte_size * 8 - 1)) - 1;
1310 const int64_t min = ~(max);
1311 return min <= sval64 && sval64 <= max;
1312 }
1313
Jim Ingham5a988412012-06-08 21:56:10 +00001314protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 bool DoExecute(Args &command, CommandReturnObject &result) override {
1316 // No need to check "process" for validity as eCommandRequiresProcess
1317 // ensures it is valid
1318 Process *process = m_exe_ctx.GetProcessPtr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 const size_t argc = command.GetArgumentCount();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 if (m_memory_options.m_infile) {
1323 if (argc < 1) {
1324 result.AppendErrorWithFormat(
1325 "%s takes a destination address when writing file contents.\n",
1326 m_cmd_name.c_str());
1327 result.SetStatus(eReturnStatusFailed);
1328 return false;
1329 }
1330 } else if (argc < 2) {
1331 result.AppendErrorWithFormat(
1332 "%s takes a destination address and at least one value.\n",
1333 m_cmd_name.c_str());
1334 result.SetStatus(eReturnStatusFailed);
1335 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336 }
1337
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 StreamString buffer(
1339 Stream::eBinary,
1340 process->GetTarget().GetArchitecture().GetAddressByteSize(),
1341 process->GetTarget().GetArchitecture().GetByteOrder());
1342
1343 OptionValueUInt64 &byte_size_value = m_format_options.GetByteSizeValue();
1344 size_t item_byte_size = byte_size_value.GetCurrentValue();
1345
1346 Error error;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001347 lldb::addr_t addr = Args::StringToAddress(&m_exe_ctx, command[0].ref,
1348 LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349
1350 if (addr == LLDB_INVALID_ADDRESS) {
1351 result.AppendError("invalid address expression\n");
1352 result.AppendError(error.AsCString());
1353 result.SetStatus(eReturnStatusFailed);
1354 return false;
1355 }
1356
1357 if (m_memory_options.m_infile) {
1358 size_t length = SIZE_MAX;
1359 if (item_byte_size > 1)
1360 length = item_byte_size;
1361 lldb::DataBufferSP data_sp(m_memory_options.m_infile.ReadFileContents(
1362 m_memory_options.m_infile_offset, length));
1363 if (data_sp) {
1364 length = data_sp->GetByteSize();
1365 if (length > 0) {
1366 Error error;
1367 size_t bytes_written =
1368 process->WriteMemory(addr, data_sp->GetBytes(), length, error);
1369
1370 if (bytes_written == length) {
1371 // All bytes written
1372 result.GetOutputStream().Printf(
1373 "%" PRIu64 " bytes were written to 0x%" PRIx64 "\n",
1374 (uint64_t)bytes_written, addr);
1375 result.SetStatus(eReturnStatusSuccessFinishResult);
1376 } else if (bytes_written > 0) {
1377 // Some byte written
1378 result.GetOutputStream().Printf(
1379 "%" PRIu64 " bytes of %" PRIu64
1380 " requested were written to 0x%" PRIx64 "\n",
1381 (uint64_t)bytes_written, (uint64_t)length, addr);
1382 result.SetStatus(eReturnStatusSuccessFinishResult);
1383 } else {
1384 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1385 " failed: %s.\n",
1386 addr, error.AsCString());
1387 result.SetStatus(eReturnStatusFailed);
1388 }
1389 }
1390 } else {
1391 result.AppendErrorWithFormat("Unable to read contents of file.\n");
1392 result.SetStatus(eReturnStatusFailed);
1393 }
1394 return result.Succeeded();
1395 } else if (item_byte_size == 0) {
1396 if (m_format_options.GetFormat() == eFormatPointer)
1397 item_byte_size = buffer.GetAddressByteSize();
1398 else
1399 item_byte_size = 1;
1400 }
1401
1402 command.Shift(); // shift off the address argument
1403 uint64_t uval64;
1404 int64_t sval64;
1405 bool success = false;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001406 for (auto &entry : command) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407 switch (m_format_options.GetFormat()) {
1408 case kNumFormats:
1409 case eFormatFloat: // TODO: add support for floats soon
1410 case eFormatCharPrintable:
1411 case eFormatBytesWithASCII:
1412 case eFormatComplex:
1413 case eFormatEnum:
1414 case eFormatUnicode16:
1415 case eFormatUnicode32:
1416 case eFormatVectorOfChar:
1417 case eFormatVectorOfSInt8:
1418 case eFormatVectorOfUInt8:
1419 case eFormatVectorOfSInt16:
1420 case eFormatVectorOfUInt16:
1421 case eFormatVectorOfSInt32:
1422 case eFormatVectorOfUInt32:
1423 case eFormatVectorOfSInt64:
1424 case eFormatVectorOfUInt64:
1425 case eFormatVectorOfFloat16:
1426 case eFormatVectorOfFloat32:
1427 case eFormatVectorOfFloat64:
1428 case eFormatVectorOfUInt128:
1429 case eFormatOSType:
1430 case eFormatComplexInteger:
1431 case eFormatAddressInfo:
1432 case eFormatHexFloat:
1433 case eFormatInstruction:
1434 case eFormatVoid:
1435 result.AppendError("unsupported format for writing memory");
1436 result.SetStatus(eReturnStatusFailed);
1437 return false;
1438
1439 case eFormatDefault:
1440 case eFormatBytes:
1441 case eFormatHex:
1442 case eFormatHexUppercase:
1443 case eFormatPointer:
1444 // Decode hex bytes
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001445 if (entry.ref.getAsInteger(16, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001447 "'%s' is not a valid hex string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 result.SetStatus(eReturnStatusFailed);
1449 return false;
1450 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1451 result.AppendErrorWithFormat("Value 0x%" PRIx64
1452 " is too large to fit in a %" PRIu64
1453 " byte unsigned integer value.\n",
1454 uval64, (uint64_t)item_byte_size);
1455 result.SetStatus(eReturnStatusFailed);
1456 return false;
1457 }
1458 buffer.PutMaxHex64(uval64, item_byte_size);
1459 break;
1460
1461 case eFormatBoolean:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001462 uval64 = Args::StringToBoolean(entry.ref, false, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 if (!success) {
1464 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001465 "'%s' is not a valid boolean string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 result.SetStatus(eReturnStatusFailed);
1467 return false;
1468 }
1469 buffer.PutMaxHex64(uval64, item_byte_size);
1470 break;
1471
1472 case eFormatBinary:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001473 if (entry.ref.getAsInteger(2, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001475 "'%s' is not a valid binary string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 result.SetStatus(eReturnStatusFailed);
1477 return false;
1478 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1479 result.AppendErrorWithFormat("Value 0x%" PRIx64
1480 " is too large to fit in a %" PRIu64
1481 " byte unsigned integer value.\n",
1482 uval64, (uint64_t)item_byte_size);
1483 result.SetStatus(eReturnStatusFailed);
1484 return false;
1485 }
1486 buffer.PutMaxHex64(uval64, item_byte_size);
1487 break;
1488
1489 case eFormatCharArray:
1490 case eFormatChar:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001491 case eFormatCString: {
1492 if (entry.ref.empty())
1493 break;
1494
1495 size_t len = entry.ref.size();
1496 // Include the NULL for C strings...
1497 if (m_format_options.GetFormat() == eFormatCString)
1498 ++len;
1499 Error error;
1500 if (process->WriteMemory(addr, entry.c_str(), len, error) == len) {
1501 addr += len;
1502 } else {
1503 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1504 " failed: %s.\n",
1505 addr, error.AsCString());
1506 result.SetStatus(eReturnStatusFailed);
1507 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001508 }
1509 break;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001510 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 case eFormatDecimal:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001512 if (entry.ref.getAsInteger(0, sval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001514 "'%s' is not a valid signed decimal value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 result.SetStatus(eReturnStatusFailed);
1516 return false;
1517 } else if (!SIntValueIsValidForSize(sval64, item_byte_size)) {
1518 result.AppendErrorWithFormat(
1519 "Value %" PRIi64 " is too large or small to fit in a %" PRIu64
1520 " byte signed integer value.\n",
1521 sval64, (uint64_t)item_byte_size);
1522 result.SetStatus(eReturnStatusFailed);
1523 return false;
1524 }
1525 buffer.PutMaxHex64(sval64, item_byte_size);
1526 break;
1527
1528 case eFormatUnsigned:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001529
1530 if (!entry.ref.getAsInteger(0, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 result.AppendErrorWithFormat(
1532 "'%s' is not a valid unsigned decimal string value.\n",
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001533 entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534 result.SetStatus(eReturnStatusFailed);
1535 return false;
1536 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1537 result.AppendErrorWithFormat("Value %" PRIu64
1538 " is too large to fit in a %" PRIu64
1539 " byte unsigned integer value.\n",
1540 uval64, (uint64_t)item_byte_size);
1541 result.SetStatus(eReturnStatusFailed);
1542 return false;
1543 }
1544 buffer.PutMaxHex64(uval64, item_byte_size);
1545 break;
1546
1547 case eFormatOctal:
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001548 if (entry.ref.getAsInteger(8, uval64)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001549 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001550 "'%s' is not a valid octal string value.\n", entry.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551 result.SetStatus(eReturnStatusFailed);
1552 return false;
1553 } else if (!UIntValueIsValidForSize(uval64, item_byte_size)) {
1554 result.AppendErrorWithFormat("Value %" PRIo64
1555 " is too large to fit in a %" PRIu64
1556 " byte unsigned integer value.\n",
1557 uval64, (uint64_t)item_byte_size);
1558 result.SetStatus(eReturnStatusFailed);
1559 return false;
1560 }
1561 buffer.PutMaxHex64(uval64, item_byte_size);
1562 break;
1563 }
1564 }
1565
1566 if (!buffer.GetString().empty()) {
1567 Error error;
Zachary Turnerc1564272016-11-16 21:15:24 +00001568 if (process->WriteMemory(addr, buffer.GetString().data(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569 buffer.GetString().size(),
1570 error) == buffer.GetString().size())
1571 return true;
1572 else {
1573 result.AppendErrorWithFormat("Memory write to 0x%" PRIx64
1574 " failed: %s.\n",
1575 addr, error.AsCString());
1576 result.SetStatus(eReturnStatusFailed);
1577 return false;
1578 }
1579 }
1580 return true;
1581 }
1582
1583 OptionGroupOptions m_option_group;
1584 OptionGroupFormat m_format_options;
1585 OptionGroupWriteMemory m_memory_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001586};
1587
Kuba Breckabeed8212014-09-04 01:03:18 +00001588//----------------------------------------------------------------------
1589// Get malloc/free history of a memory address.
1590//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001591class CommandObjectMemoryHistory : public CommandObjectParsed {
Kuba Breckabeed8212014-09-04 01:03:18 +00001592public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 CommandObjectMemoryHistory(CommandInterpreter &interpreter)
1594 : CommandObjectParsed(
1595 interpreter, "memory history", "Print recorded stack traces for "
1596 "allocation/deallocation events "
1597 "associated with an address.",
1598 nullptr,
1599 eCommandRequiresTarget | eCommandRequiresProcess |
1600 eCommandProcessMustBePaused | eCommandProcessMustBeLaunched) {
1601 CommandArgumentEntry arg1;
1602 CommandArgumentData addr_arg;
Eugene Zelenko26cac3a2016-02-20 00:58:29 +00001603
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 // Define the first (and only) variant of this arg.
1605 addr_arg.arg_type = eArgTypeAddress;
1606 addr_arg.arg_repetition = eArgRepeatPlain;
Eugene Zelenko26cac3a2016-02-20 00:58:29 +00001607
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 // There is only one variant this argument could be; put it into the
1609 // argument entry.
1610 arg1.push_back(addr_arg);
1611
1612 // Push the data for the first argument into the m_arguments vector.
1613 m_arguments.push_back(arg1);
1614 }
1615
1616 ~CommandObjectMemoryHistory() override = default;
1617
1618 const char *GetRepeatCommand(Args &current_command_args,
1619 uint32_t index) override {
1620 return m_cmd_name.c_str();
1621 }
1622
Kuba Breckabeed8212014-09-04 01:03:18 +00001623protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624 bool DoExecute(Args &command, CommandReturnObject &result) override {
1625 const size_t argc = command.GetArgumentCount();
1626
1627 if (argc == 0 || argc > 1) {
1628 result.AppendErrorWithFormat("%s takes an address expression",
1629 m_cmd_name.c_str());
1630 result.SetStatus(eReturnStatusFailed);
1631 return false;
Kuba Breckabeed8212014-09-04 01:03:18 +00001632 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001633
1634 Error error;
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001635 lldb::addr_t addr = Args::StringToAddress(&m_exe_ctx, command[0].ref,
1636 LLDB_INVALID_ADDRESS, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001637
1638 if (addr == LLDB_INVALID_ADDRESS) {
1639 result.AppendError("invalid address expression");
1640 result.AppendError(error.AsCString());
1641 result.SetStatus(eReturnStatusFailed);
1642 return false;
1643 }
1644
1645 Stream *output_stream = &result.GetOutputStream();
1646
1647 const ProcessSP &process_sp = m_exe_ctx.GetProcessSP();
1648 const MemoryHistorySP &memory_history =
1649 MemoryHistory::FindPlugin(process_sp);
1650
1651 if (!memory_history) {
1652 result.AppendError("no available memory history provider");
1653 result.SetStatus(eReturnStatusFailed);
1654 return false;
1655 }
1656
1657 HistoryThreads thread_list = memory_history->GetHistoryThreads(addr);
1658
Jim Ingham6a9767c2016-11-08 20:36:40 +00001659 const bool stop_format = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660 for (auto thread : thread_list) {
Jim Ingham6a9767c2016-11-08 20:36:40 +00001661 thread->GetStatus(*output_stream, 0, UINT32_MAX, 0, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 }
1663
1664 result.SetStatus(eReturnStatusSuccessFinishResult);
1665
1666 return true;
1667 }
Kuba Breckabeed8212014-09-04 01:03:18 +00001668};
1669
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001670//-------------------------------------------------------------------------
Greg Clayton3385fa02016-06-09 16:34:06 +00001671// CommandObjectMemoryRegion
1672//-------------------------------------------------------------------------
1673#pragma mark CommandObjectMemoryRegion
1674
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675class CommandObjectMemoryRegion : public CommandObjectParsed {
Greg Clayton3385fa02016-06-09 16:34:06 +00001676public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677 CommandObjectMemoryRegion(CommandInterpreter &interpreter)
1678 : CommandObjectParsed(interpreter, "memory region",
1679 "Get information on the memory region containing "
1680 "an address in the current target process.",
1681 "memory region ADDR",
1682 eCommandRequiresProcess | eCommandTryTargetAPILock |
1683 eCommandProcessMustBeLaunched),
1684 m_prev_end_addr(LLDB_INVALID_ADDRESS) {}
Greg Clayton3385fa02016-06-09 16:34:06 +00001685
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686 ~CommandObjectMemoryRegion() override = default;
Greg Clayton3385fa02016-06-09 16:34:06 +00001687
1688protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689 bool DoExecute(Args &command, CommandReturnObject &result) override {
1690 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1691 if (process_sp) {
1692 Error error;
1693 lldb::addr_t load_addr = m_prev_end_addr;
1694 m_prev_end_addr = LLDB_INVALID_ADDRESS;
Greg Clayton3385fa02016-06-09 16:34:06 +00001695
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 const size_t argc = command.GetArgumentCount();
1697 if (argc > 1 || (argc == 0 && load_addr == LLDB_INVALID_ADDRESS)) {
1698 result.AppendErrorWithFormat("'%s' takes one argument:\nUsage: %s\n",
1699 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1700 result.SetStatus(eReturnStatusFailed);
1701 } else {
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001702 auto load_addr_str = command[0].ref;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 if (command.GetArgumentCount() == 1) {
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001704 load_addr = Args::StringToAddress(&m_exe_ctx, load_addr_str,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001705 LLDB_INVALID_ADDRESS, &error);
1706 if (error.Fail() || load_addr == LLDB_INVALID_ADDRESS) {
1707 result.AppendErrorWithFormat(
Zachary Turner14f6b2c2016-12-09 01:08:29 +00001708 "invalid address argument \"%s\": %s\n", command[0].c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709 error.AsCString());
Greg Clayton3385fa02016-06-09 16:34:06 +00001710 result.SetStatus(eReturnStatusFailed);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 }
Greg Clayton3385fa02016-06-09 16:34:06 +00001712 }
Greg Clayton3385fa02016-06-09 16:34:06 +00001713
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 lldb_private::MemoryRegionInfo range_info;
1715 error = process_sp->GetMemoryRegionInfo(load_addr, range_info);
1716 if (error.Success()) {
1717 lldb_private::Address addr;
1718 ConstString section_name;
1719 if (process_sp->GetTarget().ResolveLoadAddress(load_addr, addr)) {
1720 SectionSP section_sp(addr.GetSection());
1721 if (section_sp) {
1722 // Got the top most section, not the deepest section
1723 while (section_sp->GetParent())
1724 section_sp = section_sp->GetParent();
1725 section_name = section_sp->GetName();
1726 }
1727 }
1728 result.AppendMessageWithFormat(
1729 "[0x%16.16" PRIx64 "-0x%16.16" PRIx64 ") %c%c%c%s%s\n",
1730 range_info.GetRange().GetRangeBase(),
1731 range_info.GetRange().GetRangeEnd(),
1732 range_info.GetReadable() ? 'r' : '-',
1733 range_info.GetWritable() ? 'w' : '-',
1734 range_info.GetExecutable() ? 'x' : '-', section_name ? " " : "",
1735 section_name ? section_name.AsCString() : "");
1736 m_prev_end_addr = range_info.GetRange().GetRangeEnd();
1737 result.SetStatus(eReturnStatusSuccessFinishResult);
1738 } else {
1739 result.SetStatus(eReturnStatusFailed);
1740 result.AppendErrorWithFormat("%s\n", error.AsCString());
1741 }
1742 }
1743 } else {
1744 m_prev_end_addr = LLDB_INVALID_ADDRESS;
1745 result.AppendError("invalid process");
1746 result.SetStatus(eReturnStatusFailed);
Greg Clayton3385fa02016-06-09 16:34:06 +00001747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 return result.Succeeded();
1749 }
Greg Clayton3385fa02016-06-09 16:34:06 +00001750
Kate Stoneb9c1b512016-09-06 20:57:50 +00001751 const char *GetRepeatCommand(Args &current_command_args,
1752 uint32_t index) override {
1753 // If we repeat this command, repeat it without any arguments so we can
1754 // show the next memory range
1755 return m_cmd_name.c_str();
1756 }
1757
1758 lldb::addr_t m_prev_end_addr;
Greg Clayton3385fa02016-06-09 16:34:06 +00001759};
1760
1761//-------------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762// CommandObjectMemory
1763//-------------------------------------------------------------------------
1764
Kate Stone7428a182016-07-14 22:03:10 +00001765CommandObjectMemory::CommandObjectMemory(CommandInterpreter &interpreter)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 : CommandObjectMultiword(
1767 interpreter, "memory",
1768 "Commands for operating on memory in the current target process.",
1769 "memory <subcommand> [<subcommand-options>]") {
1770 LoadSubCommand("find",
1771 CommandObjectSP(new CommandObjectMemoryFind(interpreter)));
1772 LoadSubCommand("read",
1773 CommandObjectSP(new CommandObjectMemoryRead(interpreter)));
1774 LoadSubCommand("write",
1775 CommandObjectSP(new CommandObjectMemoryWrite(interpreter)));
1776 LoadSubCommand("history",
1777 CommandObjectSP(new CommandObjectMemoryHistory(interpreter)));
1778 LoadSubCommand("region",
1779 CommandObjectSP(new CommandObjectMemoryRegion(interpreter)));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780}
1781
Eugene Zelenko26cac3a2016-02-20 00:58:29 +00001782CommandObjectMemory::~CommandObjectMemory() = default;