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