-
Notifications
You must be signed in to change notification settings - Fork 455
/
lldb_bson.py
1449 lines (1209 loc) · 50.8 KB
/
lldb_bson.py
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
"""
This Python module is intended for use with the LLDB debugger.
To import using this module in an LLDB session, execute the following command
in LLDB::
command script import <path-to-lldb_bson.py>
This may be useful to add as a "startup/init" command for an LLDB executor such
as VSCode.
From this point, all ``bson_t`` variables will show their full contents
recursively.
- Bonus: If using CodeLLDB, it is possible to add watch expressions to elements
within a (nested) BSON document.
To add a Python watch expression, prefix the watch string with ``/py``, and
the remainder of the string will be evaluated in the LLDB Python interpreter
rather than the LLDB evaluator. For example:
/py 'hello, ' + 'world'
will evaluate to a string "Hello, world".
To reference a bson_t object, use the ``$variable_name`` syntax. Then, use the
``@`` operator with the special global ``bson`` object to walk through the
document as if it were a regular Python object::
/py $my_bson_t @ bson.topElement.path["string key"].array[3].name
Only the leading ``bson`` is required in the path, since it provides the
"magic" necessary to perform document traversal. For example, with the
given document ``userdata``::
{
users: [
{username: "joe", age: 41},
{username: "alex", age: 33},
{username: "jane', age: 29}
]
}
the "age" of "alex" can be watched with the following watch expression:
/py $userdata @bson.users[1].age
"""
from __future__ import annotations
import enum
import functools
import hashlib
import json
import shlex
import struct
import traceback
from datetime import datetime
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Dict,
Generator,
Generic,
Iterable,
NamedTuple,
Sequence,
Tuple,
Type,
TypeVar,
Union,
cast,
)
import lldb # pyright: ignore
from lldb import ( # pyright: ignore
SBAddress,
SBDebugger,
SBError,
SBFrame,
SBProcess,
SBSyntheticValueProvider,
SBType,
SBValue,
)
if TYPE_CHECKING:
from typing_extensions import override
else:
def override(f: T) -> T:
return f
def print_errors(fn: FuncT) -> FuncT:
"""Exceptions from the decorated function will be printed, then re-raised"""
@functools.wraps(fn)
def _wrap(*args: Any, **kwargs: Any) -> Any:
try:
return fn(*args, **kwargs)
except:
e = traceback.format_exc()
print(e)
raise
return cast("FuncT", _wrap)
@print_errors
def __lldb_init_module(debugger: SBDebugger, internal_dict: InternalDict):
# Inject the global magic document traverser:
internal_dict["bson"] = _BSONWalker()
# Register types:
for cls in _SyntheticMeta.synthetics:
# The (regex of) the type that is handled by this class:
ty = shlex.quote(cls.__typename__)
if cls.__enable_synthetic__:
# Register a synthetic child provider, generating the trees that can be expanded
cmd = f"type synthetic add -l lldb_bson.{cls.__name__} -x '^{ty}$'"
debugger.HandleCommand(cmd)
if cls.__summary_str__ is not None:
# Generate a simple summary string for this object
quoted = cls.__summary_str__.replace("'", "\\'")
cmd = f"type summary add --summary-string '{quoted}' -x '^{ty}$'"
debugger.HandleCommand(cmd)
if hasattr(cls, "__summary__"):
# More complex: Call a Python function that will create the summary
cmd = f"type summary add -F lldb_bson.{cls.__name__}.__summary__ -x '^{ty}$'"
debugger.HandleCommand(cmd)
# Render __bson_byte__ as "bytes with ASCII." __bson_byte__ is a
# debug-only type generated on-the-fly in LLDB
debugger.HandleCommand("type format add -f Y __bson_byte__")
# Arrays of bytes as a sequence of hex values:
debugger.HandleCommand(r"type summary add -s '${var[]%x}' -x '__bson_byte__\[[0-9]+\]'")
print("lldb_bson is ready")
_ = __lldb_init_module # Silence "unused function" warnings
FuncT = TypeVar("FuncT", bound=Callable[..., Any])
"Type of functions"
T = TypeVar("T")
"Unbounded invariant type parameter"
InternalDict = Dict[str, Any]
"Type of internal dictionaries, provided by LLDB"
ValueFactory = Callable[[], SBValue]
ChildItem = Union[
Tuple[str, "str | int"], ValueFactory, Tuple[str, "str | int", "lldb.ValueFormatType|None", "SBType|None"]
]
class _SyntheticMeta(type):
"""
Metaclass that handles subclassing of SyntheticDisplayBase. Does basic checks
and collects definitions into a list of display types
"""
synthetics: list[Type[SyntheticDisplayBase[Any]]] = []
"The display type classes that have been defined"
@override
def __new__(
cls: Type[_SyntheticMeta], name: str, bases: tuple[type, ...], namespace: dict[str, Any]
) -> Type[SyntheticDisplayBase[Any]]:
new_class: Type[SyntheticDisplayBase[Any]] = type.__new__(cast(type, cls), name, bases, namespace)
if namespace.get("__abstract__"):
return new_class
# Check for the required __typename__ and __parse__
if not hasattr(new_class, "__typename__"):
raise TypeError(f'Type "{new_class}" is missing a "__typename__" attribute')
if not hasattr(new_class, "__parse__"):
raise TypeError(f'Type "{new_class}" has no "__parse__" method')
# Remember this new class:
cls.synthetics.append(new_class)
return new_class
class SyntheticDisplayBase(Generic[T], SBSyntheticValueProvider, metaclass=_SyntheticMeta):
__abstract__: ClassVar[bool] = True
"If true, disables metaclass checks"
__summary_str__: ClassVar[str | None] = None
"Set to an LLDB '--summary-string' formatting string for rendering the inline value summary"
__enable_synthetic__: ClassVar[bool] = True
"If False, do not generate synthetic children (used for primitive values)"
if TYPE_CHECKING:
__typename__: ClassVar[str]
"""
The (regular expression) name of the type that is handled by this class.
This is a required class attribute.
"""
@classmethod
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
"""
If provided, supplies the Python function that will dynamically
generate a summary string from the SBValue.
"""
...
@classmethod
def __parse__(cls, value: SBValue) -> T:
"""
Required method: Parse the data that lives at the given SBValue into
a representation that will be useful for later display.
"""
...
@classmethod
@print_errors
def __get_sbtype__(cls, frame: SBFrame, addr: int) -> SBType:
"""
Obtain the SBType for this class. Can be overriden in subclasses, and
the type may consider the value that lives at the address.
"""
return generate_or_get_type(f"struct {cls.__typename__} {{}}", frame)
@print_errors
def __init__(self, val: SBValue, idict: InternalDict | None = None) -> None:
self.__sbvalue = val
"The SBValue given for this object"
self.__children: list[ChildItem] = []
"The synthetic children associated with the value"
self.__value: T | None = None
"The decoded value, or ``None`` if it has not yet been decoded"
@property
def sbvalue(self) -> SBValue:
"""Obtain the SBValue associated with this display object"""
return self.__sbvalue
@property
def value(self) -> T:
"""Obtain the decoded BSON value"""
if self.__value is None:
self.__value = self.__parse__(self.sbvalue)
return self.__value
@property
def address(self) -> int:
"""Obtain the memory address of the associated object"""
return self.sbvalue.load_addr
@print_errors
@override
def update(self) -> bool | None:
"""Update the parsed value and the child objects"""
self.__value = None # Clear the value so it will be re-read
self.__children = list(self.get_children())
def get_children(self) -> Iterable[ChildItem]:
"""
Subclasses must provide this method such that it returns an iterable
object of ``ChildItem`` types. These will be used to generate the
synthetic children that are displayed by LLDB.
"""
raise NotImplementedError
@override
def num_children(self) -> int:
"""Called by LLDB to know how many children exist"""
n = len(self.__children)
return n
@override
def has_children(self) -> bool:
"""Optimization opportunity for LLDB if it knows it doesn't need to ask"""
return self.__enable_synthetic__ and self.num_children() != 0
@print_errors
@override
def get_child_at_index(self, pos: int) -> SBValue:
"""
Obtain the synthetic child of this value at index 'pos'.
"""
# LLDB sometimes calls us with a child that we don't have?
if pos >= len(self.__children):
print(f"NOTE: lldb called get_child_at_index({pos}), but we only have {len(self.__children)} children")
return SBValue()
# Get the child:
nth = self.__children[pos]
# If not a tuple:
if not isinstance(nth, tuple):
# The type is a ValueFactory, which will return a new SBValue
val = nth()
assert val.error.success, f"{val.error=}, {nth=}, {pos=}"
return val
# Otherwise, they yielded a tuple:
if len(nth) == 4:
# A four-tuple of key, value, an LLDB value format, and an LLDB value type
key, val, fmt, ty = nth
sbval = self.create_value(key, val, format=fmt, cast_to=ty)
else:
# Just a key and a value
key, val = nth
sbval = self.create_value(key, val)
assert sbval.error.success, (sbval.error, key, val)
return sbval
def create_value(
self,
name: str,
value: str | int | float,
cast_to: SBType | None = None,
format: lldb.ValueFormatType | None = None,
) -> SBValue:
"""Cast a Python primitive into an LLDB SBValue."""
# Encode the value in a JSON string, which will coincidentally be a valid
# C expression that LLDB can parse:
encoded = json.dumps(value)
val = self.__sbvalue.CreateValueFromExpression(name, encoded)
if cast_to:
val = val.Cast(cast_to)
if format is not None:
val.format = format
return val
class PrimitiveDisplay(Generic[T], SyntheticDisplayBase[T]):
"""
Displays a primitive type. We can't use LLDB's basic types directly, since
we must force a little-endian encoding.
Set the __struct_format__ class variable to a Python struct format string.
"""
__abstract__ = True
__enable_synthetic__: ClassVar[bool] = False
__struct_format__: ClassVar[str]
"The struct format string that will be used to extract the value from memory"
@classmethod
@override
@print_errors
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
return json.dumps(cls.__parse__(value))
@classmethod
@override
def __parse__(cls, value: SBValue) -> T:
unpack = struct.Struct(cls.__struct_format__)
buf = memcache.get_cached(value.load_addr)[: unpack.size]
val: T = unpack.unpack(buf)[0]
return val
class DoubleDisplay(PrimitiveDisplay[float]):
"""Displays BSON doubles"""
__typename__ = "__bson_double__"
__struct_format__: ClassVar[str] = "<d"
class UTF8Display(SyntheticDisplayBase[bytes]):
"""Display type for BSON UTF-8 values"""
__typename__ = "__bson_utf8__"
__summary_str__ = "${var[1]}" # Display the second child (which is the actual string)
@classmethod
@override
def __parse__(cls, value: SBValue) -> bytes:
buf = memcache.get_cached(value.load_addr)
size = read_i32le(buf)
return bytes(buf[4:][:size])
@override
def get_children(self) -> Iterable[ChildItem]:
strlen = len(self.value)
yield "size (bytes)", strlen
# Create a char[] type to represent the string content:
array_t = self.sbvalue.target.GetBasicType(lldb.eBasicTypeChar).GetArrayType(strlen)
yield lambda: self.sbvalue.synthetic_child_from_address("[content]", self.address + 4, array_t)
try:
# Attempt a UTF-8 decode. We don't actually show this, we just want to
# check if there are encoding errors, which we will display in the output
self.value.decode("utf-8")
except UnicodeDecodeError as e:
yield "decode error", str(e)
class DocumentInfo(NamedTuple):
"""A decoded document"""
elements: Sequence[DocumentElement | DocumentError]
"Existing elements or errors found while parsing the data"
class DocumentElement(NamedTuple):
"""Represents an element within a document"""
type: BSONType
key: str
value_offset: int
"Offset from the beginning of the document data where the element's value appears"
value_size: int
"The size of the element's value (in bytes)"
class DocumentError(NamedTuple):
"""Represents an error while decoding a document"""
message: str
error_offset: int
class DocumentDisplay(SyntheticDisplayBase["DocumentInfo | DocumentError"]):
"""
Main display of BSON document elements. This parses a document/array, and
generates the child elements that can be further expanded and inspected.
This type does not refer to the _MemCache, since this object is usually
the top-level object and is the one responsible for filling the cache.
"""
__typename__ = "__bson_document_[0-9]+__"
__qualifier__: ClassVar[str] = "document"
"The 'qualifier' of this type. Overriden by ArrayDisplay."
@classmethod
@override
@print_errors
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
prefix = cls.__qualifier__
doc = cls.__parse__(value)
if isinstance(doc, DocumentError):
return f"Error parsing {prefix} at byte {doc.error_offset}: {doc.message}"
if len(doc.elements) == 0:
return f"{prefix} (empty)"
if len(doc.elements) == 1:
return f"{prefix} (1 element)"
return f"{prefix} ({len(doc.elements)} elements)"
@classmethod
@override
def __get_sbtype__(cls, frame: SBFrame, addr: int) -> SBType:
"""Generate a unique type for the length of the document, allowing for byte-wise inspection"""
# Read the size prefix:
err = SBError()
header = frame.thread.process.ReadMemory(addr, 4, err)
assert err.success, f"{err=}, {frame=}, {addr=}"
size = read_i32le(header)
# Generate the type:
typename = f"__bson_{cls.__qualifier__}_{size}__"
doc_t = generate_or_get_type(
f"""
enum __bson_byte__ : unsigned char {{}};
struct {typename} {{ __bson_byte__ bytes[{size}]; }}
""",
frame,
)
return doc_t
@classmethod
@override
def __parse__(cls, value: SBValue) -> DocumentInfo | DocumentError:
try:
# Read from memory and refresh the segment in the memory cache. All
# child element displays will re-use the same memory segment that
# will be pulled here:
buf = memcache.read(value)[1]
except LookupError as e:
return DocumentError(f"Failed to read memory: {e}", value.load_addr)
return cls.parse_bytes(buf)
@classmethod
def parse_bytes(cls, buf: bytes) -> DocumentInfo | DocumentError:
"""Parse a document from the given data buffer"""
elems = list(cls._parse_elems(buf))
return DocumentInfo(elems)
@classmethod
def _parse_elems(cls, buf: bytes) -> Iterable[DocumentElement | DocumentError]:
"""Iteratively yield elements, or an error if parsing fails"""
cur_offset = 4
array_idx = 0
while buf:
elem = yield from cls._parse_one(buf[cur_offset:], cur_offset)
if isinstance(elem, DocumentError):
# An error ocurred, so we can't reliably continue parsing
yield elem
return
if elem.type == BSONType.EOD:
# This is the end.
break
# Yield this one, and then advance to the next element:
yield elem
elem_size = 1 + len(elem.key) + 1 + elem.value_size
if cls.__qualifier__ == "array":
# Validate that array keys are increasing integers:
expect_key = str(array_idx)
if elem.key != expect_key:
yield DocumentError(
f"Array element must have incrementing integer keys "
f'(Expected "{expect_key}", got "{elem.key}")',
cur_offset,
)
array_idx += 1
cur_offset += elem_size
# Check that we actually consumed the whole buffer:
remain = len(buf) - cur_offset
if remain > 1:
yield DocumentError(f"Extra {len(buf)} bytes in document data", cur_offset)
@classmethod
def _parse_one(
cls, buf: bytes, elem_offset: int
) -> Generator[DocumentError, None, DocumentElement | DocumentError]:
try:
# Read the tag type
type_tag = BSONType(buf[0])
except ValueError:
# The tag byte is not a valid tag value
return DocumentError(f"Invalid element type tag 0x{buf[0]:x}", elem_offset)
except IndexError:
# 'buf' was empty
return DocumentError(f"Unexpected end-of-data", elem_offset)
# Stop if this is the end:
if type_tag == BSONType.EOD:
return DocumentElement(type_tag, "", 0, 0)
# Find the null terminator on the key:
try:
key_nulpos = buf.index(0, 1)
except ValueError:
return DocumentError(f"Unexpected end-of-data while parsing the element key", elem_offset)
key_bytes = buf[1:key_nulpos]
try:
key = key_bytes.decode("utf-8")
except UnicodeDecodeError as e:
yield DocumentError(f"Element key {key_bytes} is not valid UTF-8 ({e})", elem_offset)
key = key_bytes.decode("utf-8", errors="replace")
# The offset of the value within the element:
inner_offset = key_nulpos + 1
# The buffer that starts at the value:
value_bytes = buf[inner_offset:]
# Get the fixed size of the element:
fixed_size = {
BSONType.Double: 8,
BSONType.Bool: 1,
BSONType.Undefined: 0,
BSONType.Null: 0,
BSONType.MinKey: 0,
BSONType.MaxKey: 0,
BSONType.Datetime: 8,
BSONType.ObjectID: 12,
BSONType.Int32: 4,
BSONType.Timestamp: 8,
BSONType.Int64: 8,
BSONType.Decimal128: 16,
}
value_size = fixed_size.get(BSONType(type_tag))
if value_size is not None:
pass # This element has a fixed size
elif type_tag in (BSONType.Code, BSONType.Symbol, BSONType.UTF8):
# Size is 4 + a length prefix
value_size = read_i32le(value_bytes) + 4
elif type_tag in (BSONType.Array, BSONType.Document, BSONType.CodeWithScope):
# Size is given by the length prefix
value_size = read_i32le(value_bytes)
elif type_tag == BSONType.DBPointer:
# Size is a length prefix, plus four, plus 12 bytes for the OID
value_size = read_i32le(value_bytes) + 4 + 12
elif type_tag == BSONType.Regex:
# Size is dynamic and given as two C strings:
nul1 = value_bytes.index(0)
nul2 = value_bytes.index(0, nul1 + 1)
value_size = nul2 + 1
elif type_tag == BSONType.Binary:
# Size is a length prefix, plus four, plus one for the subtype
value_size = read_i32le(value_bytes) + 4 + 1
else:
assert False, f"Unhandled value tag? {type_tag=} {buf=} {key=}"
# The absolute offset of the element within the parent document:
value_offset = elem_offset + inner_offset
return DocumentElement(type_tag, key, value_offset, value_size)
@override
def get_children(self) -> Iterable[ChildItem]:
doc = self.value
if isinstance(doc, DocumentError):
# The entire document failed to parse. Just generate one error:
yield "[error]", f"Parsing error at byte {doc.error_offset}: {doc.message}"
return
for elem in doc.elements:
if isinstance(elem, DocumentError):
# There was an error at this location.
yield "[error]", f"Data error at offset {elem.error_offset}: {elem.message}"
else:
# Create a ValueFactory for each element:
yield functools.partial(self.create_child, self.sbvalue, elem)
@classmethod
def create_child(cls, parent: SBValue, elem: DocumentElement) -> SBValue:
"""Generate the child elements for LLDB to walk through"""
if cls.__qualifier__ == "array":
# Don't quote the integer keys
name = f"[{elem.key}]"
else:
name = f"['{elem.key}']"
value_addr = parent.load_addr + elem.value_offset
frame = parent.frame
# Create a new SBType to represent the element value. For each type tag, we
# want a function that maps an SBFrame and an address to a new SBType:
by_type: dict[BSONType, Callable[[SBFrame, int], SBType]] = {
BSONType.Double: DoubleDisplay.__get_sbtype__,
BSONType.UTF8: UTF8Display.__get_sbtype__,
BSONType.Document: DocumentDisplay.__get_sbtype__,
BSONType.Binary: BinaryDisplay.__get_sbtype__,
BSONType.Array: ArrayDisplay.__get_sbtype__,
# For bool, we can just use LLDB's basic type:
BSONType.Bool: lambda _fr, _addr: parent.target.GetBasicType(lldb.eBasicTypeBool),
BSONType.Code: CodeDisplay.__get_sbtype__,
BSONType.CodeWithScope: CodeWithScopeDisplay.__get_sbtype__,
BSONType.Int32: Int32Display.__get_sbtype__,
BSONType.Int64: Int64Display.__get_sbtype__,
BSONType.ObjectID: ObjectIDDisplay.__get_sbtype__,
BSONType.DBPointer: DBPointerDisplay.__get_sbtype__,
BSONType.Regex: RegexDisplay.__get_sbtype__,
BSONType.Symbol: SymbolDisplay.__get_sbtype__,
BSONType.Datetime: DatetimeDisplay.__get_sbtype__,
BSONType.Timestamp: TimestampDisplay.__get_sbtype__,
BSONType.Decimal128: Decimal128Display.__get_sbtype__,
BSONType.Null: NullDisplay.__get_sbtype__,
BSONType.Undefined: UndefinedDisplay.__get_sbtype__,
BSONType.MaxKey: MaxKeyDisplay.__get_sbtype__,
BSONType.MinKey: MinKeyDisplay.__get_sbtype__,
}
get_type = by_type.get(elem.type)
assert get_type is not None, f"Unhandled type tag? {elem=}"
# Create the SBType:
type = get_type(frame, value_addr)
# Create a synthetic child of that type at the address of the element's value:
val = parent.synthetic_child_from_address(name, value_addr, type)
assert val.error.success, f"{elem=}, {val.error=}"
return val
class ArrayDisplay(DocumentDisplay):
"""Display for arrays. Most logic is implemented in the DocumentDisplay base."""
__typename__ = "__bson_array_[0-9]+__"
__qualifier__: ClassVar[str] = "array"
class BinaryInfo(NamedTuple):
subtype: int
data: bytes
class BinaryDisplay(SyntheticDisplayBase[BinaryInfo]):
"""Display for a BSON binary value"""
__typename__ = "__bson_binary__"
@classmethod
@override
def __parse__(cls, value: SBValue) -> BinaryInfo:
buf = memcache.get_cached(value.load_addr)
# Size prefix:
data_size = read_i32le(buf)
# Type tag:
type = buf[4]
# The remainder of the data:
data = buf[5:][:data_size]
return BinaryInfo(type, data)
@override
def get_children(self) -> Iterable[ChildItem]:
yield "size", len(self.value.data)
byte_t = generate_or_get_type("enum __bson_byte__ : char {}", self.sbvalue.frame)
yield "subtype", self.value.subtype, lldb.eFormatHex, byte_t
array_t = byte_t.GetArrayType(len(self.value.data))
yield lambda: self.sbvalue.synthetic_child_from_address("data", self.address + 5, array_t)
class UndefinedDisplay(SyntheticDisplayBase[None]):
"""
Display type for 'undefined' values. Also derived from for other unit types.
"""
__typename__ = "__bson_undefined__"
__summary_str__ = "undefined"
__enable_synthetic__: ClassVar[bool] = False
@classmethod
@override
def __parse__(cls, value: SBValue) -> None:
return None
class ObjectIDDisplay(SyntheticDisplayBase[bytes]):
"""Display type for ObjectIDs"""
__typename__ = "__bson_objectid__"
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
val = cls.__parse__(value)
return f'ObjectID("{val.hex()}")'
@classmethod
@override
def __get_sbtype__(cls, frame: SBFrame, addr: int) -> SBType:
return generate_or_get_type(
r"""
enum __bson_byte__ : char {};
struct __bson_objectid__ { __bson_byte__ bytes[12]; }
""",
frame,
)
@classmethod
@override
def __parse__(cls, value: SBValue) -> bytes:
buf = memcache.get_cached(value.load_addr)
return buf[:12]
@override
def get_children(self) -> Iterable[ChildItem]:
yield "spelling", self.value.hex()
class DatetimeDisplay(SyntheticDisplayBase[int]):
"""Display for BSON Datetime objects"""
__typename__ = "__bson_datetime__"
__summary_str__: ClassVar[str] = "datetime: ${var[0]}"
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
dt = datetime.fromtimestamp(cls.__parse__(value) / 1000)
s = f"{dt:%a %b %m %Y %H:%M:%S +%fμs}"
return f'Date("{s}")'
@classmethod
@override
def __parse__(cls, val: SBValue) -> int:
buf = memcache.get_cached(val.load_addr)
buf = buf[:8]
value: int = struct.unpack("<Q", buf)[0]
return value
@override
def get_children(self) -> Iterable[ChildItem]:
# We can create a rich display using Python's datetime parsing:
dt = datetime.fromtimestamp(self.value / 1000)
# Adjusted to the local time zone:
adjusted = dt.astimezone()
yield from {
"[isoformat]": dt.isoformat(),
"[date]": f"{dt:%B %d, %Y}",
"[time]": dt.strftime("%H:%M:%S +%fμs"),
"[local]": adjusted.strftime("%c"),
"Year": dt.year,
"Month": dt.month,
"Day": dt.day,
"Hour": dt.hour,
"Minute": dt.minute,
"Second": dt.second,
"+μs": dt.microsecond,
}.items()
class NullDisplay(UndefinedDisplay):
"""Display for the BSON 'null' type"""
__typename__ = "__bson_null__"
__summary_str__ = "null"
class RegexDisplay(SyntheticDisplayBase[Tuple[bytes, bytes]]):
"""Display type for BSON regular expressions"""
__typename__ = "__bson_regex_[0-9]+_[0-9]+__"
__enable_synthetic__: ClassVar[bool] = False
@classmethod
@override
def __get_sbtype__(cls, frame: SBFrame, addr: int) -> SBType:
regex, opts = cls.parse_at(addr)
regex_len = len(regex) + 1
opts_len = len(opts) + 1
# Synthesize a struct with two char[] matching the strings:
return generate_or_get_type(
rf"""
struct __bson_regex_{regex_len}_{opts_len}__ {{
char regex[{regex_len}];
char options[{opts_len}];
}}
""",
frame,
)
@classmethod
@override
def __parse__(cls, value: SBValue) -> tuple[bytes, bytes]:
return cls.parse_at(value.load_addr)
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
# Create a JS-style regex literal:
pair = cls.__parse__(value)
regex, options = cls.decode_pair(pair)
regex = regex.replace("/", "\\/").replace("\n", "\\n")
return f"/{regex}/{options}"
@classmethod
def parse_at(cls, addr: int) -> tuple[bytes, bytes]:
buf = memcache.get_cached(addr)
# A regex is encoded with two C-strings. Find the nulls:
nulpos_1 = buf.index(0)
nulpos_2 = buf.index(0, nulpos_1 + 1)
# Split them up:
regex = buf[:nulpos_1]
options = buf[nulpos_1 + 1 : nulpos_2]
# Decode and return:
return regex, options
@classmethod
def decode_pair(cls, value: tuple[bytes, bytes]) -> tuple[str, str]:
regex, options = value
regex = regex.decode("utf-8", errors="replace")
options = options.decode("utf-8", errors="replace")
return regex, options
class DBPointerDisplay(SyntheticDisplayBase[Tuple[bytes, int]]):
"""Display type for DBPointers"""
__typename__ = "__bson_dbpointer__"
__summary_str__: ClassVar[str | None] = "DBPointer(${var[0]}, ${var[1]})"
@classmethod
@override
def __parse__(cls, value: SBValue) -> tuple[bytes, int]:
buf = memcache.get_cached(value.load_addr)
# Grab the string and the OID position
strlen = read_i32le(buf)
size = strlen + 4 + 12
return buf[:size], strlen + 4
@override
def get_children(self) -> Iterable[ChildItem]:
utf8_t = UTF8Display.__get_sbtype__(self.sbvalue.frame, self.address)
oid_offset = self.value[1]
oid_t = ObjectIDDisplay.__get_sbtype__(self.sbvalue.frame, self.address + oid_offset)
yield lambda: self.sbvalue.synthetic_child_from_address("collection", self.sbvalue.load_addr, utf8_t)
yield lambda: self.sbvalue.synthetic_child_from_address("object", self.sbvalue.load_addr + oid_offset, oid_t)
class CodeDisplay(UTF8Display):
"""Display type for BSON code"""
__typename__ = "__bson_code__"
__summary_str__ = "Code(${var[1]})"
class SymbolDisplay(UTF8Display):
"""Display type for BSON symbols"""
__typename__ = "__bson_symbol__"
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
spell = cls.__parse__(value)
dec = spell.decode("utf-8", errors="replace").rstrip("\x00")
return f"Symbol({dec})"
class CodeWithScopeDisplay(SyntheticDisplayBase[int]):
"""Display type for BSON 'Code w/ Scope'"""
__typename__ = "__code_with_scope__"
__summary_str__: ClassVar[str | None] = "Code(${var[0][1]}, ${var[1]})"
@classmethod
@override
def __parse__(cls, value: SBValue) -> int:
buf = memcache.get_cached(value.load_addr)
# Find the end position of the string:
strlen = read_i32le(buf[4:])
str_end = 4 + strlen + 4
return str_end
@override
def get_children(self) -> Iterable[ChildItem]:
code_t = CodeDisplay.__get_sbtype__(self.sbvalue.frame, self.address)
scope_doc_offset = self.value
doc_t = DocumentDisplay.__get_sbtype__(self.sbvalue.frame, self.address + scope_doc_offset)
yield lambda: checked(self.sbvalue.synthetic_child_from_address("code", self.address + 4, code_t))
yield lambda: checked(
self.sbvalue.synthetic_child_from_address("scope", self.address + scope_doc_offset, doc_t)
)
class Int32Display(PrimitiveDisplay[int]):
"""Display for 32-bit BSON integers"""
__typename__ = "__bson_int32__"
__struct_format__: ClassVar[str] = "<i"
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
return f"NumberInt({cls.__parse__(value)})"
class Int64Display(PrimitiveDisplay[int]):
"""Display for 64-bit BSON integers"""
__typename__ = "__bson_int64__"
__struct_format__: ClassVar[str] = "<q"
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
return f"NumberLong({cls.__parse__(value)})"
class TimestampDisplay(SyntheticDisplayBase[Tuple[int, int]]):
"""Display type for BSON timestamps"""
__typename__ = "__bson_timestamp__"
__summary_str__ = "Timestamp(${var[0]}, ${var[1]})"
@classmethod
@override
def __parse__(cls, value: SBValue) -> tuple[int, int]:
buf = memcache.get_cached(value.load_addr)[:8]
# Just two 32bit integers:
timestamp, increment = struct.unpack("<ii", buf)
return timestamp, increment
@override
def get_children(self) -> Iterable[ChildItem]:
yield "timestamp", self.value[0]
yield "increment", self.value[1]
class Decimal128Value(NamedTuple):
"""Represents a parsed Decimal128 value"""
sign: int
combination: int
exponent: int
significand: int
spelling: str
class Decimal128Display(SyntheticDisplayBase[Decimal128Value]):
"""The display type for BSON's Decimal128 type"""
__typename__ = "__bson_decimal128__"
@classmethod
@override
def __get_sbtype__(cls, frame: SBFrame, addr: int) -> SBType:
"""Generate a type for byte-wise introspection"""
return generate_or_get_type(
r"""
struct __bson_decimal128__ {
unsigned char bytes[16];
}
""",
frame,
)
@classmethod
@override
def __summary__(cls, value: SBValue, idict: InternalDict) -> str:
val = cls.__parse__(value)
return f'NumberDecimal("{val.spelling}")'
@classmethod
@override
def __parse__(cls, value: SBValue) -> Decimal128Value:
dat = bytes(value.data.uint8)
# The value is little-endian encoded, so we manually read it in that encoding
d1 = read_i32le(dat)
d2 = read_i32le(dat[4:])
d3 = read_i32le(dat[8:])
d4 = read_i32le(dat[12:])
# Combin the parts:
low_word = (d2 << 32) | d1