1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
|
//===-- SwiftFormatters.cpp -------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SwiftFormatters.h"
#include "Plugins/Language/Swift/SwiftStringIndex.h"
#include "Plugins/LanguageRuntime/Swift/SwiftLanguageRuntime.h"
#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/DataFormatters/FormattersHelpers.h"
#include "lldb/DataFormatters/StringPrinter.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/Timer.h"
#include "lldb/lldb-enumerations.h"
#include "swift/AST/Types.h"
#include "swift/Demangling/ManglingMacros.h"
#include "llvm/ADT/StringRef.h"
#include <optional>
// FIXME: we should not need this
#include "Plugins/Language/CPlusPlus/CxxStringTypes.h"
#include "Plugins/Language/ObjC/Cocoa.h"
#include "Plugins/Language/ObjC/NSString.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;
using namespace lldb_private::formatters::swift;
using namespace llvm;
bool lldb_private::formatters::swift::Character_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
static ConstString g__str("_str");
ValueObjectSP str_sp = valobj.GetChildMemberWithName(g__str, true);
if (!str_sp)
return false;
return String_SummaryProvider(*str_sp, stream, options);
}
bool lldb_private::formatters::swift::UnicodeScalar_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
static ConstString g_value("_value");
ValueObjectSP value_sp(valobj.GetChildMemberWithName(g_value, true));
if (!value_sp)
return false;
return Char32SummaryProvider(*value_sp.get(), stream, options);
}
bool lldb_private::formatters::swift::StringGuts_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return StringGuts_SummaryProvider(
valobj, stream, options,
StringPrinter::ReadStringAndDumpToStreamOptions());
}
bool lldb_private::formatters::swift::SwiftSharedString_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return SwiftSharedString_SummaryProvider_2(
valobj, stream, options,
StringPrinter::ReadStringAndDumpToStreamOptions());
}
struct StringSlice {
uint64_t start, end;
};
template <typename AddrT>
static void applySlice(AddrT &address, uint64_t &length,
std::optional<StringSlice> slice) {
if (!slice)
return;
// No slicing is performed when the slice starts beyond the string's bounds.
if (slice->start > length)
return;
// The slicing logic does handle the corner case where slice->start == length.
auto offset = slice->start;
auto slice_length = slice->end - slice->start;
// Adjust from the start.
address += offset;
length -= offset;
// Reduce to the slice length, unless it's larger than the remaining length.
length = std::min(slice_length, length);
}
static bool readStringFromAddress(
uint64_t startAddress, uint64_t length, ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options,
StringPrinter::ReadStringAndDumpToStreamOptions read_options) {
if (length == 0) {
stream.Printf("\"\"");
return true;
}
read_options.SetLocation(startAddress);
read_options.SetTargetSP(valobj.GetTargetSP());
read_options.SetStream(&stream);
read_options.SetSourceSize(length);
read_options.SetHasSourceSize(true);
read_options.SetNeedsZeroTermination(false);
read_options.SetIgnoreMaxLength(summary_options.GetCapping() ==
lldb::eTypeSummaryUncapped);
read_options.SetBinaryZeroIsTerminator(false);
read_options.SetEscapeStyle(StringPrinter::EscapeStyle::Swift);
return StringPrinter::ReadStringAndDumpToStream<
StringPrinter::StringElementType::UTF8>(read_options);
};
static bool makeStringGutsSummary(
ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options,
StringPrinter::ReadStringAndDumpToStreamOptions read_options,
std::optional<StringSlice> slice = std::nullopt) {
LLDB_SCOPED_TIMER();
static ConstString g__object("_object");
static ConstString g__storage("_storage");
static ConstString g__value("_value");
auto error = [&](std::string message) {
stream << "<cannot decode string: " << message << ">";
return true;
};
ProcessSP process(valobj.GetProcessSP());
if (!process)
return error("no live process");
auto ptrSize = process->GetAddressByteSize();
auto object_sp = valobj.GetChildMemberWithName(g__object, true);
if (!object_sp)
return error("unexpected layout");
// We retrieve String contents by first extracting the
// platform-independent 128-bit raw value representation from
// _StringObject, then interpreting that.
Status status;
uint64_t raw0;
uint64_t raw1;
if (ptrSize == 8) {
// On 64-bit platforms, we simply need to get the raw integer
// values of the two stored properties.
static ConstString g__countAndFlagsBits("_countAndFlagsBits");
auto countAndFlagsBits = object_sp->GetChildAtNamePath(
{g__countAndFlagsBits, g__value});
if (!countAndFlagsBits)
return error("unexpected layout");
raw0 = countAndFlagsBits->GetValueAsUnsigned(0);
auto object = object_sp->GetChildMemberWithName(g__object, true);
if (!object)
return error("unexpected layout (object)");
raw1 = object->GetValueAsUnsigned(0);
} else if (ptrSize == 4) {
// On 32-bit platforms, we emulate what `_StringObject.rawBits`
// does. It involves inspecting the variant and rearranging bits
// to match the 64-bit representation.
static ConstString g__count("_count");
static ConstString g__variant("_variant");
static ConstString g__discriminator("_discriminator");
static ConstString g__flags("_flags");
static ConstString g_immortal("immortal");
auto count_sp = object_sp->GetChildAtNamePath({g__count, g__value});
if (!count_sp)
return error("unexpected layout (count)");
uint64_t count = count_sp->GetValueAsUnsigned(0);
auto discriminator_sp =
object_sp->GetChildAtNamePath({g__discriminator, g__value});
if (!discriminator_sp)
return error("unexpected layout (discriminator)");
uint64_t discriminator = discriminator_sp->GetValueAsUnsigned(0) & 0xff;
auto flags_sp = object_sp->GetChildAtNamePath({g__flags, g__value});
if (!flags_sp)
return error("unexpected layout (flags)");
uint64_t flags = flags_sp->GetValueAsUnsigned(0) & 0xffff;
auto variant_sp = object_sp->GetChildMemberWithName(g__variant, true);
if (!variant_sp)
return error("unexpected layout (variant)");
llvm::StringRef variantCase = variant_sp->GetValueAsCString();
ValueObjectSP payload_sp;
if (variantCase.startswith("immortal")) {
payload_sp = variant_sp->GetChildAtNamePath({g_immortal, g__value});
} else if (variantCase.startswith("native")) {
payload_sp = variant_sp->GetChildAtNamePath({g_immortal, g__value});
} else if (variantCase.startswith("bridged")) {
static ConstString g_bridged("bridged");
auto anyobject_sp = variant_sp->GetChildMemberWithName(g_bridged, true);
if (!anyobject_sp)
return error("unexpected layout (bridged)");
payload_sp = anyobject_sp->GetChildAtIndex(0, true); // "instance"
} else {
return error("unknown variant");
}
if (!payload_sp)
return error("no payload");
uint64_t pointerBits = payload_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
if (pointerBits == LLDB_INVALID_ADDRESS)
return error("invalid payload");
if ((discriminator & 0xB0) == 0xA0) {
raw0 = count | (pointerBits << 32);
raw1 = flags | (discriminator << 56);
} else {
raw0 = count | (flags << 48);
raw1 = pointerBits | (discriminator << 56);
}
} else {
return error("unsupported pointer size");
}
// Copied from StringObject.swift
//
// TODO: Hyperlink to final set of documentation diagrams instead
//
/*
On 64-bit platforms, the discriminator is the most significant 4 bits of the
bridge object.
┌─────────────────────╥─────┬─────┬─────┬─────┐
│ Form ║ b63 │ b62 │ b61 │ b60 │
╞═════════════════════╬═════╪═════╪═════╪═════╡
│ Immortal, Small ║ 1 │ASCII│ 1 │ 0 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Immortal, Large ║ 1 │ 0 │ 0 │ 0 │
╞═════════════════════╬═════╪═════╪═════╪═════╡
│ Native ║ 0 │ 0 │ 0 │ 0 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Shared ║ x │ 0 │ 0 │ 0 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Shared, Bridged ║ 0 │ 1 │ 0 │ 0 │
╞═════════════════════╬═════╪═════╪═════╪═════╡
│ Foreign ║ x │ 0 │ 0 │ 1 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Foreign, Bridged ║ 0 │ 1 │ 0 │ 1 │
└─────────────────────╨─────┴─────┴─────┴─────┘
b63: isImmortal: Should the Swift runtime skip ARC
- Small strings are just values, always immortal
- Large strings can sometimes be immortal, e.g. literals
b62: (large) isBridged / (small) isASCII
- For large strings, this means lazily-bridged NSString: perform ObjC ARC
- Small strings repurpose this as a dedicated bit to remember ASCII-ness
b61: isSmall: Dedicated bit to denote small strings
b60: isForeign: aka isSlow, cannot provide access to contiguous UTF-8
All non-small forms share the same structure for the other half of the bits
(i.e. non-object bits) as a word containing code unit count and various
performance flags. The top 16 bits are for performance flags, which are not
semantically relevant but communicate that some operations can be done more
efficiently on this particular string, and the lower 48 are the code unit
count (aka endIndex).
┌─────────┬───────┬──────────────────┬─────────────────┬────────┬───────┐
│ b63 │ b62 │ b61 │ b60 │ b59:48 │ b47:0 │
├─────────┼───────┼──────────────────┼─────────────────┼────────┼───────┤
│ isASCII │ isNFC │ isNativelyStored │ isTailAllocated │ TBD │ count │
└─────────┴───────┴──────────────────┴─────────────────┴────────┴───────┘
isASCII: set when all code units are known to be ASCII, enabling:
- Trivial Unicode scalars, they're just the code units
- Trivial UTF-16 transcoding (just bit-extend)
- Also, isASCII always implies isNFC
isNFC: set when the contents are in normal form C
- Enables trivial lexicographical comparisons: just memcmp
- `isASCII` always implies `isNFC`, but not vice versa
isNativelyStored: set for native stored strings
- `largeAddressBits` holds an instance of `_StringStorage`.
- I.e. the start of the code units is at the stored address + `nativeBias`
isTailAllocated: start of the code units is at the stored address + `nativeBias`
- `isNativelyStored` always implies `isTailAllocated`, but not vice versa
(e.g. literals)
TBD: Reserved for future usage
- Setting a TBD bit to 1 must be semantically equivalent to 0
- I.e. it can only be used to "cache" fast-path information in the future
count: stores the number of code units, corresponds to `endIndex`.
*/
uint8_t discriminator = raw1 >> 56;
if ((discriminator & 0b1011'0000) == 0b1010'0000) { // 1x10xxxx: Small string
uint64_t count = (raw1 >> 56) & 0b1111;
uint64_t maxCount = (ptrSize == 8 ? 15 : 10);
if (count > maxCount)
return error("count > maxCount");
uint64_t rawBuffer[2] = {raw0, raw1};
auto *buffer = (uint8_t *)&rawBuffer;
applySlice(buffer, count, slice);
StringPrinter::ReadBufferAndDumpToStreamOptions options(read_options);
options.SetData(lldb_private::DataExtractor(
buffer, count, process->GetByteOrder(), ptrSize));
options.SetStream(&stream);
options.SetSourceSize(count);
options.SetBinaryZeroIsTerminator(false);
options.SetEscapeStyle(StringPrinter::EscapeStyle::Swift);
return StringPrinter::ReadBufferAndDumpToStream<
StringPrinter::StringElementType::UTF8>(options);
}
uint64_t count = raw0 & 0x0000FFFFFFFFFFFF;
uint16_t flags = raw0 >> 48;
lldb::addr_t objectAddress = (raw1 & 0x0FFFFFFFFFFFFFFF);
// Catch a zero-initialized string.
if (!objectAddress) {
stream << "<uninitialized>";
return true;
}
if ((flags & 0x1000) != 0) { // Tail-allocated / biased address
// Tail-allocation is only for natively stored or literals.
if ((discriminator & 0b0111'0000) != 0)
return error("unexpected discriminator");
uint64_t bias = (ptrSize == 8 ? 32 : 20);
auto address = objectAddress + bias;
applySlice(address, count, slice);
return readStringFromAddress(
address, count, valobj, stream, summary_options, read_options);
}
if ((discriminator & 0b1111'0000) == 0) { // Shared string
// FIXME: Verify that there is a __SharedStringStorage instance at `address`.
// Shared strings must not be tail-allocated or natively stored.
if ((flags & 0x3000) != 0)
return false;
uint64_t startOffset = (ptrSize == 8 ? 24 : 12);
auto address = objectAddress + startOffset;
lldb::addr_t start = process->ReadPointerFromMemory(address, status);
if (status.Fail())
return error(status.AsCString());
applySlice(address, count, slice);
return readStringFromAddress(
start, count, valobj, stream, summary_options, read_options);
}
// Native/shared strings should already have been handled.
if ((discriminator & 0b0111'0000) == 0)
return error("unexpected discriminator");
if ((discriminator & 0b1110'0000) == 0b0100'0000) { // 010xxxxx: Bridged
TypeSystemClangSP clang_ts_sp =
ScratchTypeSystemClang::GetForTarget(process->GetTarget());
if (!clang_ts_sp)
return error("no Clang type system");
CompilerType id_type = clang_ts_sp->GetBasicType(lldb::eBasicTypeObjCID);
// We may have an NSString pointer inline, so try formatting it directly.
lldb_private::DataExtractor DE(&objectAddress, ptrSize,
process->GetByteOrder(), ptrSize);
auto nsstring = ValueObject::CreateValueObjectFromData(
"nsstring", DE, valobj.GetExecutionContextRef(), id_type);
if (!nsstring || nsstring->GetError().Fail())
return error("could not create NSString value object");
return NSStringSummaryProvider(*nsstring.get(), stream, summary_options);
}
if ((discriminator & 0b1111'1000) == 0b0001'1000) { // 0001xxxx: Foreign
// Not currently generated: Foreign non-bridged strings are not currently
// used in Swift.
return error("unexpected discriminator");
}
// Invalid discriminator.
return error("invalid discriminator");
}
bool lldb_private::formatters::swift::StringGuts_SummaryProvider(
ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options,
StringPrinter::ReadStringAndDumpToStreamOptions read_options) {
return makeStringGutsSummary(valobj, stream, summary_options, read_options);
}
bool lldb_private::formatters::swift::String_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return String_SummaryProvider(
valobj, stream, options,
StringPrinter::ReadStringAndDumpToStreamOptions());
}
bool lldb_private::formatters::swift::String_SummaryProvider(
ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options,
StringPrinter::ReadStringAndDumpToStreamOptions read_options) {
static ConstString g_guts("_guts");
ValueObjectSP guts_sp = valobj.GetChildMemberWithName(g_guts, true);
if (guts_sp)
return StringGuts_SummaryProvider(*guts_sp, stream, summary_options,
read_options);
return false;
}
bool lldb_private::formatters::swift::Substring_SummaryProvider(
ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options) {
static ConstString g__slice("_slice");
static ConstString g__base("_base");
static ConstString g__startIndex("_startIndex");
static ConstString g__endIndex("_endIndex");
static ConstString g__rawBits("_rawBits");
auto slice_sp = valobj.GetChildMemberWithName(g__slice, true);
if (!slice_sp)
return false;
auto base_sp = slice_sp->GetChildMemberWithName(g__base, true);
if (!base_sp)
return false;
auto get_index =
[&slice_sp](ConstString index_name) -> std::optional<StringIndex> {
auto raw_bits_sp = slice_sp->GetChildAtNamePath({index_name, g__rawBits});
if (!raw_bits_sp)
return std::nullopt;
bool success = false;
StringIndex index =
raw_bits_sp->GetSyntheticValue()->GetValueAsUnsigned(0, &success);
if (!success)
return std::nullopt;
return index;
};
std::optional<StringIndex> start_index = get_index(g__startIndex);
std::optional<StringIndex> end_index = get_index(g__endIndex);
if (!start_index || !end_index)
return false;
if (!start_index->matchesEncoding(*end_index))
return false;
static ConstString g_guts("_guts");
auto guts_sp = base_sp->GetChildMemberWithName(g_guts, true);
if (!guts_sp)
return false;
StringPrinter::ReadStringAndDumpToStreamOptions read_options;
StringSlice slice{start_index->encodedOffset(), end_index->encodedOffset()};
return makeStringGutsSummary(*guts_sp, stream, summary_options, read_options,
slice);
}
bool lldb_private::formatters::swift::StringIndex_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
static ConstString g__rawBits("_rawBits");
auto raw_bits_sp = valobj.GetChildMemberWithName(g__rawBits, true);
if (!raw_bits_sp)
return false;
bool success = false;
StringIndex index =
raw_bits_sp->GetSyntheticValue()->GetValueAsUnsigned(0, &success);
if (!success)
return false;
stream.Printf("%llu[%s]", index.encodedOffset(), index.encodingName());
if (index.transcodedOffset() != 0)
stream.Printf("+%u", index.transcodedOffset());
return true;
}
bool lldb_private::formatters::swift::StaticString_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return StaticString_SummaryProvider(
valobj, stream, options,
StringPrinter::ReadStringAndDumpToStreamOptions());
}
bool lldb_private::formatters::swift::StaticString_SummaryProvider(
ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options,
StringPrinter::ReadStringAndDumpToStreamOptions read_options) {
LLDB_SCOPED_TIMER();
static ConstString g__startPtrOrData("_startPtrOrData");
static ConstString g__byteSize("_utf8CodeUnitCount");
static ConstString g__flags("_flags");
ValueObjectSP flags_sp(valobj.GetChildMemberWithName(g__flags, true));
if (!flags_sp)
return false;
ProcessSP process_sp(valobj.GetProcessSP());
if (!process_sp)
return false;
// 0 == pointer representation
InferiorSizedWord flags(flags_sp->GetValueAsUnsigned(0), *process_sp);
if (0 != (flags & 0x1).GetValue())
return false;
ValueObjectSP startptr_sp(
valobj.GetChildMemberWithName(g__startPtrOrData, true));
ValueObjectSP bytesize_sp(valobj.GetChildMemberWithName(g__byteSize, true));
if (!startptr_sp || !bytesize_sp)
return false;
lldb::addr_t start_ptr =
startptr_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
uint64_t size = bytesize_sp->GetValueAsUnsigned(0);
if (start_ptr == LLDB_INVALID_ADDRESS || start_ptr == 0)
return false;
if (size == 0) {
stream.Printf("\"\"");
return true;
}
read_options.SetTargetSP(valobj.GetTargetSP());
read_options.SetLocation(start_ptr);
read_options.SetSourceSize(size);
read_options.SetHasSourceSize(true);
read_options.SetBinaryZeroIsTerminator(false);
read_options.SetNeedsZeroTermination(false);
read_options.SetStream(&stream);
read_options.SetIgnoreMaxLength(summary_options.GetCapping() ==
lldb::eTypeSummaryUncapped);
read_options.SetEscapeStyle(StringPrinter::EscapeStyle::Swift);
return StringPrinter::ReadStringAndDumpToStream<
StringPrinter::StringElementType::UTF8>(read_options);
}
bool lldb_private::formatters::swift::SwiftSharedString_SummaryProvider_2(
ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &summary_options,
StringPrinter::ReadStringAndDumpToStreamOptions read_options) {
LLDB_SCOPED_TIMER();
ProcessSP process(valobj.GetProcessSP());
if (!process)
return false;
Status error;
auto ptr_size = process->GetAddressByteSize();
lldb::addr_t raw1 = valobj.GetPointerValue();
lldb::addr_t address = (raw1 & 0x00FFFFFFFFFFFFFF);
uint64_t startOffset = (ptr_size == 8 ? 24 : 12);
lldb::addr_t start =
process->ReadPointerFromMemory(address + startOffset, error);
if (error.Fail())
return false;
lldb::addr_t raw0 =
process->ReadPointerFromMemory(address + startOffset + ptr_size, error);
if (error.Fail())
return false;
uint64_t count = raw0 & 0x0000FFFFFFFFFFFF;
return readStringFromAddress(start, count, valobj, stream, summary_options,
read_options);
}
bool lldb_private::formatters::swift::SwiftStringStorage_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
LLDB_SCOPED_TIMER();
ProcessSP process(valobj.GetProcessSP());
if (!process)
return false;
auto ptrSize = process->GetAddressByteSize();
uint64_t bias = (ptrSize == 8 ? 32 : 20);
uint64_t raw0_offset = (ptrSize == 8 ? 24 : 12);
lldb::addr_t raw1 = valobj.GetPointerValue();
lldb::addr_t address = (raw1 & 0x00FFFFFFFFFFFFFF) + bias;
Status error;
lldb::addr_t raw0 = process->ReadPointerFromMemory(raw1 + raw0_offset, error);
if (error.Fail())
return false;
uint64_t count = raw0 & 0x0000FFFFFFFFFFFF;
return readStringFromAddress(
address, count, valobj, stream, options,
StringPrinter::ReadStringAndDumpToStreamOptions());
}
bool lldb_private::formatters::swift::Bool_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
static ConstString g_value("_value");
ValueObjectSP value_child(valobj.GetChildMemberWithName(g_value, true));
if (!value_child)
return false;
// Swift Bools are stored in a byte, but only the LSB of the byte is
// significant. The swift::irgen::FixedTypeInfo structure represents
// this information by providing a mask of the "extra bits" for the type.
// But at present CompilerType has no way to represent that information.
// So for now we hard code it.
uint64_t value = value_child->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
const uint64_t mask = 1 << 0;
value &= mask;
switch (value) {
case 0:
stream.Printf("false");
return true;
case 1:
stream.Printf("true");
return true;
case LLDB_INVALID_ADDRESS:
return false;
default:
stream.Printf("<invalid> (0x%" PRIx8 ")", (uint8_t)value);
return true;
}
}
bool lldb_private::formatters::swift::DarwinBoolean_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
static ConstString g__value("_value");
ValueObjectSP value_child(valobj.GetChildMemberWithName(g__value, true));
if (!value_child)
return false;
auto value = value_child->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
switch (value) {
case 0:
stream.Printf("false");
return true;
default:
stream.Printf("true");
return true;
}
}
static bool RangeFamily_SummaryProvider(ValueObject &valobj, Stream &stream,
const TypeSummaryOptions &options,
bool isHalfOpen) {
LLDB_SCOPED_TIMER();
static ConstString g_lowerBound("lowerBound");
static ConstString g_upperBound("upperBound");
ValueObjectSP lowerBound_sp(
valobj.GetChildMemberWithName(g_lowerBound, true));
ValueObjectSP upperBound_sp(
valobj.GetChildMemberWithName(g_upperBound, true));
if (!lowerBound_sp || !upperBound_sp)
return false;
lowerBound_sp = lowerBound_sp->GetQualifiedRepresentationIfAvailable(
lldb::eDynamicDontRunTarget, true);
upperBound_sp = upperBound_sp->GetQualifiedRepresentationIfAvailable(
lldb::eDynamicDontRunTarget, true);
auto start_summary = lowerBound_sp->GetValueAsCString();
auto end_summary = upperBound_sp->GetValueAsCString();
// the Range should not have a summary unless both start and end indices have
// one - or it will look awkward
if (!start_summary || !start_summary[0] || !end_summary || !end_summary[0])
return false;
stream.Printf("%s%s%s", start_summary, isHalfOpen ? "..<" : "...",
end_summary);
return true;
}
bool lldb_private::formatters::swift::Range_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return RangeFamily_SummaryProvider(valobj, stream, options, true);
}
bool lldb_private::formatters::swift::CountableRange_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return RangeFamily_SummaryProvider(valobj, stream, options, true);
}
bool lldb_private::formatters::swift::ClosedRange_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return RangeFamily_SummaryProvider(valobj, stream, options, false);
}
bool lldb_private::formatters::swift::CountableClosedRange_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
return RangeFamily_SummaryProvider(valobj, stream, options, false);
}
bool lldb_private::formatters::swift::BuiltinObjC_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
stream.Printf("0x%" PRIx64 " ", valobj.GetValueAsUnsigned(0));
llvm::Expected<std::string> desc = valobj.GetObjectDescription();
if (desc)
stream << toString(desc.takeError());
else
stream << *desc;
return true;
}
namespace lldb_private {
namespace formatters {
namespace swift {
class EnumSyntheticFrontEnd : public SyntheticChildrenFrontEnd {
public:
EnumSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp);
llvm::Expected<uint32_t> CalculateNumChildren() override;
lldb::ValueObjectSP GetChildAtIndex(uint32_t idx) override;
lldb::ChildCacheState Update() override;
bool MightHaveChildren() override;
size_t GetIndexOfChildWithName(ConstString name) override;
private:
ExecutionContextRef m_exe_ctx_ref;
ConstString m_element_name;
size_t m_child_index;
};
}
}
}
lldb_private::formatters::swift::EnumSyntheticFrontEnd::EnumSyntheticFrontEnd(
lldb::ValueObjectSP valobj_sp)
: SyntheticChildrenFrontEnd(*valobj_sp.get()), m_exe_ctx_ref(),
m_element_name(nullptr), m_child_index(UINT32_MAX) {
if (valobj_sp)
Update();
}
llvm::Expected<uint32_t>
lldb_private::formatters::swift::EnumSyntheticFrontEnd::CalculateNumChildren() {
return m_child_index != UINT32_MAX ? 1 : 0;
}
lldb::ValueObjectSP
lldb_private::formatters::swift::EnumSyntheticFrontEnd::GetChildAtIndex(
uint32_t idx) {
if (idx)
return ValueObjectSP();
if (m_child_index == UINT32_MAX)
return ValueObjectSP();
return m_backend.GetChildAtIndex(m_child_index, true);
}
lldb::ChildCacheState
lldb_private::formatters::swift::EnumSyntheticFrontEnd::Update() {
m_element_name.Clear();
m_child_index = UINT32_MAX;
m_exe_ctx_ref = m_backend.GetExecutionContextRef();
m_element_name.SetCString(m_backend.GetValueAsCString());
m_child_index = m_backend.GetIndexOfChildWithName(m_element_name);
return ChildCacheState::eRefetch;
}
bool lldb_private::formatters::swift::EnumSyntheticFrontEnd::
MightHaveChildren() {
return m_child_index != UINT32_MAX;
}
size_t
lldb_private::formatters::swift::EnumSyntheticFrontEnd::GetIndexOfChildWithName(
ConstString name) {
if (name == m_element_name)
return 0;
return UINT32_MAX;
}
SyntheticChildrenFrontEnd *
lldb_private::formatters::swift::EnumSyntheticFrontEndCreator(
CXXSyntheticChildren *, lldb::ValueObjectSP valobj_sp) {
if (!valobj_sp)
return NULL;
return (new EnumSyntheticFrontEnd(valobj_sp));
}
bool lldb_private::formatters::swift::ObjC_Selector_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
LLDB_SCOPED_TIMER();
static ConstString g_ptr("ptr");
static ConstString g__rawValue("_rawValue");
ValueObjectSP ptr_sp(valobj.GetChildAtNamePath({g_ptr, g__rawValue}));
if (!ptr_sp)
return false;
auto ptr_value = ptr_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
if (0 == ptr_value || LLDB_INVALID_ADDRESS == ptr_value)
return false;
StringPrinter::ReadStringAndDumpToStreamOptions read_options;
read_options.SetLocation(ptr_value);
read_options.SetTargetSP(valobj.GetTargetSP());
read_options.SetStream(&stream);
read_options.SetQuote('"');
read_options.SetNeedsZeroTermination(true);
read_options.SetEscapeStyle(StringPrinter::EscapeStyle::Swift);
return StringPrinter::ReadStringAndDumpToStream<
StringPrinter::StringElementType::ASCII>(read_options);
}
template <int Key> struct TypePreservingNSNumber;
template <> struct TypePreservingNSNumber<0> {
typedef int64_t SixtyFourValueType;
typedef int32_t ThirtyTwoValueType;
static constexpr const char *FormatString = "Int(%" PRId64 ")";
};
template <> struct TypePreservingNSNumber<1> {
typedef int64_t ValueType;
static constexpr const char *FormatString = "Int64(%" PRId64 ")";
};
template <> struct TypePreservingNSNumber<2> {
typedef int32_t ValueType;
static constexpr const char *FormatString = "Int32(%" PRId32 ")";
};
template <> struct TypePreservingNSNumber<3> {
typedef int16_t ValueType;
static constexpr const char *FormatString = "Int16(%" PRId16 ")";
};
template <> struct TypePreservingNSNumber<4> {
typedef int8_t ValueType;
static constexpr const char *FormatString = "Int8(%" PRId8 ")";
};
template <> struct TypePreservingNSNumber<5> {
typedef uint64_t SixtyFourValueType;
typedef uint32_t ThirtyTwoValueType;
static constexpr const char *FormatString = "UInt(%" PRIu64 ")";
};
template <> struct TypePreservingNSNumber<6> {
typedef uint64_t ValueType;
static constexpr const char *FormatString = "UInt64(%" PRIu64 ")";
};
template <> struct TypePreservingNSNumber<7> {
typedef uint32_t ValueType;
static constexpr const char *FormatString = "UInt32(%" PRIu32 ")";
};
template <> struct TypePreservingNSNumber<8> {
typedef uint16_t ValueType;
static constexpr const char *FormatString = "UInt16(%" PRIu16 ")";
};
template <> struct TypePreservingNSNumber<9> {
typedef uint8_t ValueType;
static constexpr const char *FormatString = "UInt8(%" PRIu8 ")";
};
template <> struct TypePreservingNSNumber<10> {
typedef float ValueType;
static constexpr const char *FormatString = "Float(%f)";
};
template <> struct TypePreservingNSNumber<11> {
typedef double ValueType;
static constexpr const char *FormatString = "Double(%f)";
};
template <> struct TypePreservingNSNumber<12> {
typedef double SixtyFourValueType;
typedef float ThirtyTwoValueType;
static constexpr const char *FormatString = "CGFloat(%f)";
};
template <> struct TypePreservingNSNumber<13> {
typedef bool ValueType;
static constexpr const char *FormatString = "Bool(%d)";
};
template <int Key,
typename Value = typename TypePreservingNSNumber<Key>::ValueType>
bool PrintTypePreservingNSNumber(DataBufferSP buffer_sp, Stream &stream) {
Value value;
memcpy(&value, buffer_sp->GetBytes(), sizeof(value));
stream.Printf(TypePreservingNSNumber<Key>::FormatString, value);
return true;
}
template <>
bool PrintTypePreservingNSNumber<13, void>(DataBufferSP buffer_sp,
Stream &stream) {
typename TypePreservingNSNumber<13>::ValueType value;
memcpy(&value, buffer_sp->GetBytes(), sizeof(value));
stream.PutCString(value ? "true" : "false");
return true;
}
template <int Key, typename SixtyFour =
typename TypePreservingNSNumber<Key>::SixtyFourValueType,
typename ThirtyTwo =
typename TypePreservingNSNumber<Key>::ThirtyTwoValueType>
bool PrintTypePreservingNSNumber(DataBufferSP buffer_sp, ProcessSP process_sp,
Stream &stream) {
switch (process_sp->GetAddressByteSize()) {
case 4: {
ThirtyTwo value;
memcpy(&value, buffer_sp->GetBytes(), sizeof(value));
stream.Printf(TypePreservingNSNumber<Key>::FormatString, (SixtyFour)value);
return true;
}
case 8: {
SixtyFour value;
memcpy(&value, buffer_sp->GetBytes(), sizeof(value));
stream.Printf(TypePreservingNSNumber<Key>::FormatString, value);
return true;
}
}
llvm_unreachable("unknown address byte size");
}
bool lldb_private::formatters::swift::TypePreservingNSNumber_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
LLDB_SCOPED_TIMER();
lldb::addr_t ptr_value(valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS));
if (ptr_value == LLDB_INVALID_ADDRESS)
return false;
ProcessSP process_sp(valobj.GetProcessSP());
if (!process_sp)
return false;
uint32_t ptr_size = process_sp->GetAddressByteSize();
const uint32_t size_of_tag = 1;
const uint32_t size_of_payload = 8;
lldb::addr_t addr_of_payload = ptr_value + ptr_size;
lldb::addr_t addr_of_tag = addr_of_payload + size_of_payload;
Status read_error;
uint64_t tag = process_sp->ReadUnsignedIntegerFromMemory(
addr_of_tag, size_of_tag, 0, read_error);
if (read_error.Fail())
return false;
WritableDataBufferSP buffer_sp(new DataBufferHeap(size_of_payload, 0));
process_sp->ReadMemoryFromInferior(addr_of_payload, buffer_sp->GetBytes(),
size_of_payload, read_error);
if (read_error.Fail())
return false;
#define PROCESS_DEPENDENT_TAG(Key) \
case Key: \
return PrintTypePreservingNSNumber<Key>(buffer_sp, process_sp, stream);
#define PROCESS_INDEPENDENT_TAG(Key) \
case Key: \
return PrintTypePreservingNSNumber<Key>(buffer_sp, stream);
switch (tag) {
PROCESS_DEPENDENT_TAG(0);
PROCESS_INDEPENDENT_TAG(1);
PROCESS_INDEPENDENT_TAG(2);
PROCESS_INDEPENDENT_TAG(3);
PROCESS_INDEPENDENT_TAG(4);
PROCESS_DEPENDENT_TAG(5);
PROCESS_INDEPENDENT_TAG(6);
PROCESS_INDEPENDENT_TAG(7);
PROCESS_INDEPENDENT_TAG(8);
PROCESS_INDEPENDENT_TAG(9);
PROCESS_INDEPENDENT_TAG(10);
PROCESS_INDEPENDENT_TAG(11);
PROCESS_DEPENDENT_TAG(12);
PROCESS_INDEPENDENT_TAG(13);
default:
break;
}
#undef PROCESS_DEPENDENT_TAG
#undef PROCESS_INDEPENDENT_TAG
return false;
}
namespace {
/// Enumerate the kinds of SIMD elements.
enum class SIMDElementKind {
Int32,
UInt32,
Float32,
Float64
};
/// A helper for formatting a kind of SIMD element.
class SIMDElementFormatter {
SIMDElementKind m_kind;
public:
SIMDElementFormatter(SIMDElementKind kind) : m_kind(kind) {}
/// Create a string representation of a SIMD element given a pointer to it.
std::string Format(const uint8_t *data) const {
std::string S;
llvm::raw_string_ostream OS(S);
switch (m_kind) {
case SIMDElementKind::Int32: {
auto *p = reinterpret_cast<const int32_t *>(data);
OS << *p;
break;
}
case SIMDElementKind::UInt32: {
auto *p = reinterpret_cast<const uint32_t *>(data);
OS << *p;
break;
}
case SIMDElementKind::Float32: {
auto *p = reinterpret_cast<const float *>(data);
OS << *p;
break;
}
case SIMDElementKind::Float64: {
auto *p = reinterpret_cast<const double *>(data);
OS << *p;
break;
}
}
return S;
}
/// Get the size in bytes of this kind of SIMD element.
unsigned getElementSize() const {
return (m_kind == SIMDElementKind::Float64) ? 8 : 4;
}
};
/// Read a vector from a buffer target.
std::optional<std::vector<std::string>>
ReadVector(const SIMDElementFormatter &formatter, const uint8_t *buffer,
unsigned len, unsigned offset, unsigned num_elements) {
unsigned elt_size = formatter.getElementSize();
if ((offset + num_elements * elt_size) > len)
return std::nullopt;
std::vector<std::string> elements;
for (unsigned I = 0; I < num_elements; ++I)
elements.emplace_back(formatter.Format(buffer + offset + (I * elt_size)));
return elements;
}
/// Read a SIMD vector from the target.
std::optional<std::vector<std::string>>
ReadVector(Process &process, ValueObject &valobj,
const SIMDElementFormatter &formatter, unsigned num_elements) {
Status error;
static ConstString g_storage("_storage");
static ConstString g_value("_value");
ValueObjectSP value_sp = valobj.GetChildAtNamePath({g_storage, g_value});
if (!value_sp)
return std::nullopt;
// The layout of the vector is the same as what you'd expect for a C-style
// array. It's a contiguous bag of bytes with no padding.
lldb_private::DataExtractor data;
uint64_t len = value_sp->GetData(data, error);
if (error.Fail())
return std::nullopt;
const uint8_t *buffer = data.GetDataStart();
return ReadVector(formatter, buffer, len, 0, num_elements);
}
/// Print a vector of elements as a row, if possible.
bool PrintRow(Stream &stream, std::optional<std::vector<std::string>> vec) {
if (!vec)
return false;
std::string joined = llvm::join(*vec, ", ");
stream.Printf("(%s)", joined.c_str());
return true;
}
void PrintMatrix(Stream &stream,
const std::vector<std::vector<std::string>> &matrix,
int num_columns, int num_rows) {
// Print each row.
stream.Printf("\n[ ");
for (int J = 0; J < num_rows; ++J) {
// Join the J-th row's elements with commas.
std::vector<std::string> row;
for (int I = 0; I < num_columns; ++I)
row.emplace_back(std::move(matrix[I][J]));
std::string joined = llvm::join(row, ", ");
// Add spacing and punctuation to 1) make it possible to copy the matrix
// into a Python repl and 2) to avoid writing '[[' in FileCheck tests.
if (J > 0)
stream.Printf(" ");
stream.Printf("[%s]", joined.c_str());
if (J != (num_rows - 1))
stream.Printf(",\n");
else
stream.Printf(" ]\n");
}
}
} // end anonymous namespace
bool lldb_private::formatters::swift::SIMDVector_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
LLDB_SCOPED_TIMER();
// SIMD vector contains an inner member `_storage` which is an opaque
// container. Given SIMD is always in the form SIMDX<Type> where X is a
// positive integer, we can calculate the number of elements and the
// dynamic archetype (and hence its size). Everything follows naturally
// as the elements are laid out in a contigous buffer without padding.
CompilerType simd_type = valobj.GetCompilerType().GetCanonicalType();
auto ts = simd_type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>();
if (!ts)
return false;
ExecutionContext exe_ctx = valobj.GetExecutionContextRef().Lock(true);
std::optional<uint64_t> opt_type_size =
simd_type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
if (!opt_type_size)
return false;
uint64_t type_size = *opt_type_size;
lldbassert(simd_type.GetNumTemplateArguments() == 1 && "broken SIMD type");
if (simd_type.GetNumTemplateArguments() != 1)
return false;
auto arg_type = ts->GetGenericArgumentType(simd_type.GetOpaqueQualType(), 0);
lldbassert(arg_type && "Unexpected invalid SIMD generic argument type");
if (!arg_type)
return false;
std::optional<uint64_t> opt_arg_size =
arg_type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
if (!opt_arg_size)
return false;
uint64_t arg_size = *opt_arg_size;
DataExtractor storage_buf;
Status error;
uint64_t len = valobj.GetData(storage_buf, error);
lldbassert(len == type_size && "extracted less bytes than requested");
if (len < type_size)
return false;
// We deduce the number of elements looking at the size of the swift
// type and the size of the generic argument, as we know the type is
// laid out contiguosly in memory. SIMD3, though, has an element of
// padding. Given this is the only type in the standard library with
// padding, we special-case it.
ConstString full_type_name = simd_type.GetTypeName();
llvm::StringRef type_name = full_type_name.GetStringRef();
uint64_t num_elements = type_size / arg_size;
auto generic_pos = type_name.find("<");
if (generic_pos != llvm::StringRef::npos)
type_name = type_name.slice(0, generic_pos);
if (type_name == "Swift.SIMD3")
num_elements = 3;
std::vector<std::string> elem_vector;
for (uint64_t i = 0; i < num_elements; ++i) {
DataExtractor elem_extractor(storage_buf, i * arg_size, arg_size);
auto simd_elem = ValueObject::CreateValueObjectFromData(
"simd_elem", elem_extractor, valobj.GetExecutionContextRef(), arg_type);
if (!simd_elem || simd_elem->GetError().Fail())
return false;
auto synthetic = simd_elem->GetSyntheticValue();
if (!synthetic)
return false;
const char *value_string = synthetic->GetValueAsCString();
elem_vector.push_back(value_string);
}
return PrintRow(stream, elem_vector);
}
bool lldb_private::formatters::swift::LegacySIMD_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
LLDB_SCOPED_TIMER();
Status error;
ProcessSP process_sp(valobj.GetProcessSP());
if (!process_sp)
return false;
Process &process = *process_sp.get();
// Get the type name without the "simd.simd_" prefix.
ConstString full_type_name = valobj.GetTypeName();
llvm::StringRef type_name = full_type_name.GetStringRef();
if (type_name.startswith("simd."))
type_name = type_name.drop_front(5);
if (type_name.startswith("simd_"))
type_name = type_name.drop_front(5);
// Get the type of object this is.
bool is_quaternion = type_name.startswith("quat");
bool is_matrix = type_name[type_name.size() - 2] == 'x';
bool is_vector = !is_matrix && !is_quaternion;
// Get the kind of SIMD element inside of this object.
std::optional<SIMDElementKind> kind = std::nullopt;
if (type_name.startswith("int"))
kind = SIMDElementKind::Int32;
else if (type_name.startswith("uint"))
kind = SIMDElementKind::UInt32;
else if ((is_quaternion && type_name.endswith("f")) ||
type_name.startswith("float"))
kind = SIMDElementKind::Float32;
else if ((is_quaternion && type_name.endswith("d")) ||
type_name.startswith("double"))
kind = SIMDElementKind::Float64;
if (!kind)
return false;
SIMDElementFormatter formatter(*kind);
if (is_vector) {
unsigned num_elements = llvm::hexDigitValue(type_name.back());
return PrintRow(stream,
ReadVector(process, valobj, formatter, num_elements));
} else if (is_quaternion) {
static ConstString g_vector("vector");
ValueObjectSP vec_sp = valobj.GetChildAtNamePath({g_vector});
if (!vec_sp)
return false;
return PrintRow(stream, ReadVector(process, *vec_sp.get(), formatter, 4));
} else if (is_matrix) {
static ConstString g_columns("columns");
ValueObjectSP columns_sp = valobj.GetChildAtNamePath({g_columns});
if (!columns_sp)
return false;
unsigned num_columns = llvm::hexDigitValue(type_name[type_name.size() - 3]);
unsigned num_rows = llvm::hexDigitValue(type_name[type_name.size() - 1]);
// SIMD matrices are stored column-major. Collect each column vector as a
// precursor for row-by-row pretty-printing.
std::vector<std::vector<std::string>> columns;
for (unsigned I = 0; I < num_columns; ++I) {
std::string col_num_str = llvm::utostr(I);
ConstString col_num_const_str(col_num_str.c_str());
ValueObjectSP column_sp =
columns_sp->GetChildAtNamePath({col_num_const_str});
if (!column_sp)
return false;
auto vec = ReadVector(process, *column_sp.get(), formatter, num_rows);
if (!vec)
return false;
columns.emplace_back(std::move(*vec));
}
PrintMatrix(stream, columns, num_columns, num_rows);
return true;
}
return false;
}
bool lldb_private::formatters::swift::GLKit_SummaryProvider(
ValueObject &valobj, Stream &stream, const TypeSummaryOptions &options) {
LLDB_SCOPED_TIMER();
// Get the type name without the "GLKit." prefix.
ConstString full_type_name = valobj.GetTypeName();
llvm::StringRef type_name = full_type_name.GetStringRef();
if (type_name.startswith("GLKit."))
type_name = type_name.drop_front(6);
// Get the type of object this is.
bool is_quaternion = type_name == "GLKQuaternion";
bool is_matrix = type_name.startswith("GLKMatrix");
bool is_vector = type_name.startswith("GLKVector");
if (!(is_quaternion || is_matrix || is_vector))
return false;
SIMDElementFormatter formatter(SIMDElementKind::Float32);
unsigned num_elements =
is_quaternion ? 4 : llvm::hexDigitValue(type_name.back());
DataExtractor data;
Status error;
uint64_t len = valobj.GetData(data, error);
const uint8_t *buffer = data.GetDataStart();
if (!is_matrix) {
return PrintRow(stream,
ReadVector(formatter, buffer, len, 0, num_elements));
}
// GLKit matrices are stored column-major. Collect each column vector as a
// precursor for row-by-row pretty-printing.
std::vector<std::vector<std::string>> columns;
for (unsigned I = 0; I < num_elements; ++I) {
auto vec =
ReadVector(formatter, buffer, len, I * 4 * num_elements, num_elements);
if (!vec)
return false;
columns.emplace_back(std::move(*vec));
}
PrintMatrix(stream, columns, num_elements, num_elements);
return true;
}
|