forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 334
/
Copy pathSwiftFormatters.cpp
1965 lines (1675 loc) · 68.5 KB
/
SwiftFormatters.cpp
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
//===-- 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/ReflectionContextInterface.h"
#include "Plugins/LanguageRuntime/Swift/SwiftLanguageRuntime.h"
#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
#include "Plugins/TypeSystem/Swift/SwiftDemangle.h"
#include "Plugins/TypeSystem/Swift/TypeSystemSwiftTypeRef.h"
#include "lldb/DataFormatters/FormattersHelpers.h"
#include "lldb/DataFormatters/StringPrinter.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/Timer.h"
#include "lldb/ValueObject/ValueObject.h"
#include "lldb/lldb-enumerations.h"
#include "swift/ABI/Task.h"
#include "swift/AST/Types.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Demangling/ManglingMacros.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/raw_ostream.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.starts_with("immortal")) {
payload_sp = variant_sp->GetChildAtNamePath({g_immortal, g__value});
} else if (variantCase.starts_with("native")) {
payload_sp = variant_sp->GetChildAtNamePath({g_immortal, g__value});
} else if (variantCase.starts_with("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 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Immortal, Bridged ║ 1 │ 1 │ 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 & 0b0110'0000) == 0b0100'0000) { // x10xxxxx: 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 &summary_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;
}
StringPrinter::ReadStringAndDumpToStreamOptions read_options;
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;
};
/// Synthetic provider for `Swift.Task`.
///
/// As seen by lldb, a `Task` instance is an opaque pointer, with neither type
/// metadata nor an AST to describe it. To implement this synthetic provider, a
/// `Task`'s state is retrieved from a `ReflectionContext`, and that data is
/// used to manually construct `ValueObject` children.
class TaskSyntheticFrontEnd : public SyntheticChildrenFrontEnd {
public:
TaskSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp)
: SyntheticChildrenFrontEnd(*valobj_sp.get()) {
auto target_sp = m_backend.GetTargetSP();
auto ts_or_err =
target_sp->GetScratchTypeSystemForLanguage(eLanguageTypeSwift);
if (auto err = ts_or_err.takeError()) {
LLDB_LOG_ERROR(GetLog(LLDBLog::DataFormatters | LLDBLog::Types),
std::move(err),
"could not get Swift type system for Task synthetic "
"provider: {0}");
return;
}
m_ts = llvm::dyn_cast_or_null<TypeSystemSwiftTypeRef>(ts_or_err->get());
}
constexpr static StringLiteral TaskChildren[] = {
"address",
"id",
"kind",
"enqueuPriority",
"isChildTask",
"isFuture",
"isGroupChildTask",
"isAsyncLetTask",
"isCancelled",
"isStatusRecordLocked",
"isEscalated",
"isEnqueued",
"children",
"isRunning",
};
llvm::Expected<uint32_t> CalculateNumChildren() override {
auto count = ArrayRef(TaskChildren).size();
return m_task_info.hasIsRunning ? count : count - 1;
}
lldb::ValueObjectSP GetChildAtIndex(uint32_t idx) override {
auto target_sp = m_backend.GetTargetSP();
// TypeMangling for "Swift.Bool"
CompilerType bool_type =
m_ts->GetTypeFromMangledTypename(ConstString("$sSbD"));
// TypeMangling for "Swift.UInt32"
CompilerType uint32_type =
m_ts->GetTypeFromMangledTypename(ConstString("$ss6UInt32VD"));
// TypeMangling for "Swift.UInt64"
CompilerType uint64_type =
m_ts->GetTypeFromMangledTypename(ConstString("$ss6UInt64VD"));
// TypeMangling for "Swift.TaskPriority"
CompilerType priority_type =
m_ts->GetTypeFromMangledTypename(ConstString("$sScPD"));
#define RETURN_CHILD(FIELD, NAME, TYPE) \
if (!FIELD) { \
auto value = m_task_info.NAME; \
DataExtractor data{reinterpret_cast<const void *>(&value), sizeof(value), \
endian::InlHostByteOrder(), sizeof(void *)}; \
FIELD = ValueObject::CreateValueObjectFromData( \
#NAME, data, m_backend.GetExecutionContextRef(), TYPE); \
} \
return FIELD;
switch (idx) {
case 0:
if (!m_address_sp) {
// TypeMangling for "Swift.UnsafeRawPointer"
CompilerType raw_pointer_type =
m_ts->GetTypeFromMangledTypename(ConstString("$sSVD"));
addr_t value = m_task_ptr;
DataExtractor data{reinterpret_cast<const void *>(&value),
sizeof(value), endian::InlHostByteOrder(),
sizeof(void *)};
m_address_sp = ValueObject::CreateValueObjectFromData(
"address", data, m_backend.GetExecutionContextRef(),
raw_pointer_type);
}
return m_address_sp;
case 1:
RETURN_CHILD(m_id_sp, id, uint64_type);
case 2:
RETURN_CHILD(m_kind_sp, kind, uint32_type);
case 3:
RETURN_CHILD(m_enqueue_priority_sp, enqueuePriority, priority_type);
case 4:
RETURN_CHILD(m_is_child_task_sp, isChildTask, bool_type);
case 5:
RETURN_CHILD(m_is_future_sp, isFuture, bool_type);
case 6:
RETURN_CHILD(m_is_group_child_task_sp, isGroupChildTask, bool_type);
case 7:
RETURN_CHILD(m_is_async_let_task_sp, isAsyncLetTask, bool_type);
case 8:
RETURN_CHILD(m_is_cancelled_sp, isCancelled, bool_type);
case 9:
RETURN_CHILD(m_is_status_record_locked_sp, isStatusRecordLocked,
bool_type);
case 10:
RETURN_CHILD(m_is_escalated_sp, isEscalated, bool_type);
case 11:
RETURN_CHILD(m_is_enqueued_sp, isEnqueued, bool_type);
case 12: {
if (!m_child_tasks_sp) {
const auto &tasks = m_task_info.childTasks;
std::string mangled_typename =
mangledTypenameForTasksTuple(tasks.size());
CompilerType tasks_tuple_type =
m_ts->GetTypeFromMangledTypename(ConstString(mangled_typename));
DataExtractor data{tasks.data(), tasks.size() * sizeof(tasks[0]),
endian::InlHostByteOrder(), sizeof(void *)};
m_child_tasks_sp = ValueObject::CreateValueObjectFromData(
"children", data, m_backend.GetExecutionContextRef(),
tasks_tuple_type);
}
return m_child_tasks_sp;
}
case 13:
RETURN_CHILD(m_is_running_sp, isRunning, bool_type);
default:
return {};
}
#undef RETURN_CHILD
}
lldb::ChildCacheState Update() override {
if (auto *runtime = SwiftLanguageRuntime::Get(m_backend.GetProcessSP())) {
ThreadSafeReflectionContext reflection_ctx =
runtime->GetReflectionContext();
ValueObjectSP task_obj_sp = m_backend.GetChildMemberWithName("_task");
if (!task_obj_sp)
return ChildCacheState::eRefetch;
m_task_ptr = task_obj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
if (m_task_ptr != LLDB_INVALID_ADDRESS) {
llvm::Expected<ReflectionContextInterface::AsyncTaskInfo> task_info =
reflection_ctx->asyncTaskInfo(m_task_ptr);
if (auto err = task_info.takeError()) {
LLDB_LOG_ERROR(
GetLog(LLDBLog::DataFormatters | LLDBLog::Types), std::move(err),
"could not get info for async task {0:x}: {1}", m_task_ptr);
} else {
m_task_info = *task_info;
for (auto child :
{m_address_sp, m_id_sp, m_kind_sp, m_enqueue_priority_sp,
m_is_child_task_sp, m_is_future_sp, m_is_group_child_task_sp,
m_is_async_let_task_sp, m_is_cancelled_sp,
m_is_status_record_locked_sp, m_is_escalated_sp,
m_is_enqueued_sp, m_child_tasks_sp, m_is_running_sp})
child.reset();
}
}
}
return ChildCacheState::eRefetch;
}
bool MightHaveChildren() override { return true; }
size_t GetIndexOfChildWithName(ConstString name) override {
ArrayRef children = TaskChildren;
const auto *it = llvm::find(children, name);
if (it == children.end())
return UINT32_MAX;
return std::distance(children.begin(), it);
}
private:
std::string mangledTypenameForTasksTuple(size_t count) {
/*
Global > TypeMangling > Type > Tuple
TupleElement > Type > Structure
Module, text="Swift"
Identifier, text="UnsafeCurrentTask"
*/
using namespace ::swift::Demangle;
using Kind = Node::Kind;
NodeFactory factory;
auto [root, tuple] = swift_demangle::MakeNodeChain(
{Kind::TypeMangling, Kind::Type, Kind::Tuple}, factory);
// Make a TupleElement subtree N times, where N is the number of subtasks.
for (size_t i = 0; i < count; ++i) {
auto *structure = swift_demangle::MakeNodeChain(
tuple, {Kind::TupleElement, Kind::Type, Kind::Structure}, factory);
if (structure) {
structure->addChild(
factory.createNode(Kind::Module, ::swift::STDLIB_NAME), factory);
structure->addChild(
factory.createNode(Kind::Identifier, "UnsafeCurrentTask"), factory);
}
}
return mangleNode(root).result();
}
private:
TypeSystemSwiftTypeRef *m_ts = nullptr;
addr_t m_task_ptr = LLDB_INVALID_ADDRESS;
ReflectionContextInterface::AsyncTaskInfo m_task_info;
ValueObjectSP m_address_sp;
ValueObjectSP m_id_sp;
ValueObjectSP m_kind_sp;
ValueObjectSP m_enqueue_priority_sp;
ValueObjectSP m_is_child_task_sp;
ValueObjectSP m_is_future_sp;
ValueObjectSP m_is_group_child_task_sp;
ValueObjectSP m_is_async_let_task_sp;
ValueObjectSP m_is_cancelled_sp;
ValueObjectSP m_is_status_record_locked_sp;
ValueObjectSP m_is_escalated_sp;
ValueObjectSP m_is_enqueued_sp;
ValueObjectSP m_child_tasks_sp;
ValueObjectSP m_is_running_sp;
};
class UnsafeContinuationSyntheticFrontEnd : public SyntheticChildrenFrontEnd {
public:
UnsafeContinuationSyntheticFrontEnd(lldb::ValueObjectSP valobj_sp)
: SyntheticChildrenFrontEnd(*valobj_sp.get()) {
if (auto target_sp = m_backend.GetTargetSP()) {
if (auto ts_or_err =
target_sp->GetScratchTypeSystemForLanguage(eLanguageTypeSwift)) {
if (auto *ts = llvm::dyn_cast_or_null<TypeSystemSwiftTypeRef>(
ts_or_err->get()))
// TypeMangling for "Swift.UnsafeCurrentTask"
m_task_type = ts->GetTypeFromMangledTypename(ConstString("$sSctD"));
} else {
LLDB_LOG_ERROR(GetLog(LLDBLog::DataFormatters | LLDBLog::Types),
ts_or_err.takeError(),
"could not get Swift type system for UnsafeContinuation "
"synthetic provider: {0}");
}
}
}
llvm::Expected<uint32_t> CalculateNumChildren() override {
if (!m_task_sp)
return m_backend.GetNumChildren();
return 1;
}
bool MightHaveChildren() override { return true; }