forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgdb_arrow.py
2451 lines (1919 loc) · 68.3 KB
/
gdb_arrow.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from collections import namedtuple
from collections.abc import Sequence
import datetime
import decimal
import enum
from functools import lru_cache, partial
import itertools
import math
import operator
import struct
import sys
import warnings
import gdb
from gdb.types import get_basic_type
assert sys.version_info[0] >= 3, "Arrow GDB extension needs Python 3+"
# gdb API docs at https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html#Python-API
_type_ids = [
'NA', 'BOOL', 'UINT8', 'INT8', 'UINT16', 'INT16', 'UINT32', 'INT32',
'UINT64', 'INT64', 'HALF_FLOAT', 'FLOAT', 'DOUBLE', 'STRING', 'BINARY',
'FIXED_SIZE_BINARY', 'DATE32', 'DATE64', 'TIMESTAMP', 'TIME32', 'TIME64',
'INTERVAL_MONTHS', 'INTERVAL_DAY_TIME', 'DECIMAL128', 'DECIMAL256',
'LIST', 'STRUCT', 'SPARSE_UNION', 'DENSE_UNION', 'DICTIONARY', 'MAP',
'EXTENSION', 'FIXED_SIZE_LIST', 'DURATION', 'LARGE_STRING',
'LARGE_BINARY', 'LARGE_LIST', 'INTERVAL_MONTH_DAY_NANO']
# Mirror the C++ Type::type enum
Type = enum.IntEnum('Type', _type_ids, start=0)
# Mirror the C++ TimeUnit::type enum
TimeUnit = enum.IntEnum('TimeUnit', ['SECOND', 'MILLI', 'MICRO', 'NANO'],
start=0)
type_id_to_struct_code = {
Type.INT8: 'b',
Type.INT16: 'h',
Type.INT32: 'i',
Type.INT64: 'q',
Type.UINT8: 'B',
Type.UINT16: 'H',
Type.UINT32: 'I',
Type.UINT64: 'Q',
Type.HALF_FLOAT: 'e',
Type.FLOAT: 'f',
Type.DOUBLE: 'd',
Type.DATE32: 'i',
Type.DATE64: 'q',
Type.TIME32: 'i',
Type.TIME64: 'q',
Type.INTERVAL_DAY_TIME: 'ii',
Type.INTERVAL_MONTHS: 'i',
Type.INTERVAL_MONTH_DAY_NANO: 'iiq',
Type.DURATION: 'q',
Type.TIMESTAMP: 'q',
}
TimeUnitTraits = namedtuple('TimeUnitTraits', ('multiplier',
'fractional_digits'))
time_unit_traits = {
TimeUnit.SECOND: TimeUnitTraits(1, 0),
TimeUnit.MILLI: TimeUnitTraits(1_000, 3),
TimeUnit.MICRO: TimeUnitTraits(1_000_000, 6),
TimeUnit.NANO: TimeUnitTraits(1_000_000_000, 9),
}
def identity(v):
return v
def has_null_bitmap(type_id):
return type_id not in (Type.NA, Type.SPARSE_UNION, Type.DENSE_UNION)
@lru_cache()
def byte_order():
"""
Get the target program (not the GDB host's) endianness.
"""
s = gdb.execute("show endian", to_string=True).strip()
if 'big' in s:
return 'big'
elif 'little' in s:
return 'little'
warnings.warn('Could not determine target endianness '
f'from GDB\'s response:\n"""{s}"""')
# Fall back to host endianness
return sys.byteorder
def for_evaluation(val, ty=None):
"""
Return a parsable form of gdb.Value `val`, optionally with gdb.Type `ty`.
"""
if ty is None:
ty = get_basic_type(val.type)
typename = str(ty) # `ty.name` is sometimes None...
if '::' in typename and not typename.startswith('::'):
# ARROW-15652: expressions evaluated by GDB are evaluated in the
# scope of the C++ namespace of the currently selected frame.
# When inside a Parquet frame, `arrow::<some type>` would be looked
# up as `parquet::arrow::<some type>` and fail.
# Therefore, force the lookup to happen in the global namespace scope.
typename = f"::{typename}"
if ty.code == gdb.TYPE_CODE_PTR:
# It's already a pointer, can represent it directly
return f"(({typename}) ({val}))"
if val.address is None:
raise ValueError(f"Cannot further evaluate rvalue: {val}")
return f"(* ({typename}*) ({val.address}))"
def is_char_star(ty):
# Note that "const char*" can have TYPE_CODE_INT as target type...
ty = get_basic_type(ty)
return (ty.code == gdb.TYPE_CODE_PTR and
get_basic_type(ty.target()).code
in (gdb.TYPE_CODE_CHAR, gdb.TYPE_CODE_INT))
def deref(val):
"""
Dereference a raw or smart pointer.
"""
ty = get_basic_type(val.type)
if ty.code == gdb.TYPE_CODE_PTR:
return val.dereference()
if ty.name.startswith('std::'):
if "shared" in ty.name:
return SharedPtr(val).value
if "unique" in ty.name:
return UniquePtr(val).value
raise TypeError(f"Cannot dereference value of type '{ty.name}'")
_string_literal_mapping = {
ord('\\'): r'\\',
ord('\n'): r'\n',
ord('\r'): r'\r',
ord('\t'): r'\t',
ord('"'): r'\"',
}
for c in range(0, 32):
if c not in _string_literal_mapping:
_string_literal_mapping[c] = f"\\x{c:02x}"
def string_literal(s):
"""
Format a Python string or gdb.Value for display as a literal.
"""
max_len = 50
if isinstance(s, gdb.Value):
s = s.string()
if len(s) > max_len:
s = s[:max_len]
return '"' + s.translate(_string_literal_mapping) + '" [continued]'
else:
return '"' + s.translate(_string_literal_mapping) + '"'
def bytes_literal(val, size=None):
"""
Format a gdb.Value for display as a literal containing possibly
unprintable characters.
"""
return val.lazy_string(length=size).value()
def utf8_literal(val, size=None):
"""
Format a gdb.Value for display as a utf-8 literal.
"""
if size is None:
s = val.string(encoding='utf8', errors='backslashreplace')
elif size != 0:
s = val.string(encoding='utf8', errors='backslashreplace', length=size)
else:
s = ""
return string_literal(s)
def half_float_value(val):
"""
Return a Python float of the given half-float (represented as a uint64_t
gdb.Value).
"""
buf = gdb.selected_inferior().read_memory(val.address, 2)
return struct.unpack("e", buf)[0]
def load_atomic(val):
"""
Load a std::atomic<T>'s value.
"""
valty = val.type.template_argument(0)
# XXX This assumes std::atomic<T> has the same layout as a raw T.
return val.address.reinterpret_cast(valty.pointer()).dereference()
def load_null_count(val):
"""
Load a null count from a gdb.Value of an integer (either atomic or not).
"""
if get_basic_type(val.type).code != gdb.TYPE_CODE_INT:
val = load_atomic(val)
return val
def format_null_count(val):
"""
Format a null count value.
"""
if not isinstance(val, int):
null_count = int(load_null_count(val))
return (f"null count {null_count}" if null_count != -1
else "unknown null count")
def short_time_unit(val):
return ['s', 'ms', 'us', 'ns'][int(val)]
def format_month_interval(val):
"""
Format a MonthInterval value.
"""
return f"{int(val)}M"
def format_days_milliseconds(days, milliseconds):
return f"{days}d{milliseconds}ms"
def format_months_days_nanos(months, days, nanos):
return f"{months}M{days}d{nanos}ns"
_date_base = datetime.date(1970, 1, 1).toordinal()
def format_date32(val):
"""
Format a date32 value.
"""
val = int(val)
try:
decoded = datetime.date.fromordinal(val + _date_base)
except ValueError: # "ordinal must be >= 1"
return f"{val}d [year <= 0]"
else:
return f"{val}d [{decoded}]"
def format_date64(val):
"""
Format a date64 value.
"""
val = int(val)
days, remainder = divmod(val, 86400 * 1000)
if remainder:
return f"{val}ms [non-multiple of 86400000]"
try:
decoded = datetime.date.fromordinal(days + _date_base)
except ValueError: # "ordinal must be >= 1"
return f"{val}ms [year <= 0]"
else:
return f"{val}ms [{decoded}]"
def format_timestamp(val, unit):
"""
Format a timestamp value.
"""
val = int(val)
unit = int(unit)
short_unit = short_time_unit(unit)
traits = time_unit_traits[unit]
seconds, subseconds = divmod(val, traits.multiplier)
try:
dt = datetime.datetime.utcfromtimestamp(seconds)
except (ValueError, OSError, OverflowError):
# value out of range for datetime.datetime
pretty = "too large to represent"
else:
pretty = dt.isoformat().replace('T', ' ')
if traits.fractional_digits > 0:
pretty += f".{subseconds:0{traits.fractional_digits}d}"
return f"{val}{short_unit} [{pretty}]"
def cast_to_concrete(val, ty):
return (val.reference_value().reinterpret_cast(ty.reference())
.referenced_value())
def scalar_class_from_type(name):
"""
Given a DataTypeClass class name (such as "BooleanType"), return the
corresponding Scalar class name.
"""
assert name.endswith("Type")
return name[:-4] + "Scalar"
def array_class_from_type(name):
"""
Given a DataTypeClass class name (such as "BooleanType"), return the
corresponding Array class name.
"""
assert name.endswith("Type")
return name[:-4] + "Array"
class CString:
"""
A `const char*` or similar value.
"""
def __init__(self, val):
self.val = val
def __bool__(self):
return int(data) != 0 and int(data[0]) != 0
@property
def data(self):
return self.val
def bytes_literal(self):
return self.val.lazy_string().value()
def string_literal(self):
# XXX use lazy_string() as well?
return string_literal(self.val)
def string(self):
return self.val.string()
def __format__(self, fmt):
return str(self.bytes_literal())
# NOTE: gdb.parse_and_eval() is *slow* and calling it multiple times
# may add noticeable latencies. For standard C++ classes, we therefore
# try to fetch their properties from libstdc++ internals (which hopefully
# are stable), before falling back on calling the public API methods.
class SharedPtr:
"""
A `std::shared_ptr<T>` value.
"""
def __init__(self, val):
self.val = val
try:
# libstdc++ internals
self._ptr = val['_M_ptr']
except gdb.error:
# fallback for other C++ standard libraries
self._ptr = gdb.parse_and_eval(f"{for_evaluation(val)}.get()")
def get(self):
"""
Return the underlying pointer (a T*).
"""
return self._ptr
@property
def value(self):
"""
The underlying value (a T).
"""
return self._ptr.dereference()
class UniquePtr:
"""
A `std::unique_ptr<T>` value.
"""
def __init__(self, val):
self.val = val
ty = self.val.type.template_argument(0)
# XXX This assumes that the embedded T* pointer lies at the start
# of std::unique_ptr<T>.
self._ptr = self.val.address.reinterpret_cast(ty.pointer().pointer())
def get(self):
"""
Return the underlying pointer (a T*).
"""
return self._ptr
@property
def value(self):
"""
The underlying value (a T).
"""
return self._ptr.dereference()
class Variant:
"""
A `std::variant<...>`.
"""
def __init__(self, val):
self.val = val
try:
# libstdc++ internals
self.index = val['_M_index']
except gdb.error:
# fallback for other C++ standard libraries
self.index = gdb.parse_and_eval(f"{for_evaluation(val)}.index()")
try:
self.value_type = self.val.type.template_argument(self.index)
except RuntimeError:
# Index out of bounds
self.value_type = None
@property
def value(self):
if self.value_type is None:
return None
ptr = self.val.address
if ptr is not None:
return ptr.reinterpret_cast(self.value_type.pointer()
).dereference()
return None
class StdString:
"""
A `std::string` (or possibly `std::string_view`) value.
"""
def __init__(self, val):
self.val = val
try:
# libstdc++ internals
self._data = val['_M_dataplus']['_M_p']
self._size = val['_M_string_length']
except gdb.error:
# fallback for other C++ standard libraries
self._data = gdb.parse_and_eval(f"{for_evaluation(val)}.c_str()")
self._size = gdb.parse_and_eval(f"{for_evaluation(val)}.size()")
def __bool__(self):
return self._size != 0
@property
def data(self):
return self._data
@property
def size(self):
return self._size
def bytes_literal(self):
return self._data.lazy_string(length=self._size).value()
def string_literal(self):
# XXX use lazy_string() as well?
return string_literal(self._data)
def string(self):
return self._data.string()
def __format__(self, fmt):
return str(self.bytes_literal())
class StdVector(Sequence):
"""
A `std::vector<T>` value.
"""
def __init__(self, val):
self.val = val
try:
# libstdc++ internals
impl = self.val['_M_impl']
self._data = impl['_M_start']
self._size = int(impl['_M_finish'] - self._data)
except gdb.error:
# fallback for other C++ standard libraries
self._data = int(gdb.parse_and_eval(
f"{for_evaluation(self.val)}.data()"))
self._size = int(gdb.parse_and_eval(
f"{for_evaluation(self.val)}.size()"))
def _check_index(self, index):
if index < 0 or index >= self._size:
raise IndexError(
f"Index {index} out of bounds (should be in [0, {self._size - 1}])")
def __len__(self):
return self._size
def __getitem__(self, index):
self._check_index(index)
return self._data[index]
def eval_at(self, index, eval_format):
"""
Run `eval_format` with the value at `index`.
For example, if `eval_format` is "{}.get()", this will evaluate
"{self[index]}.get()".
"""
self._check_index(index)
return gdb.parse_and_eval(
eval_format.format(for_evaluation(self._data[index])))
def iter_eval(self, eval_format):
data_eval = for_evaluation(self._data)
for i in range(self._size):
yield gdb.parse_and_eval(
eval_format.format(f"{data_eval}[{i}]"))
@property
def size(self):
return self._size
class StdPtrVector(StdVector):
def __getitem__(self, index):
return deref(super().__getitem__(index))
class FieldVector(StdVector):
def __getitem__(self, index):
"""
Dereference the Field object at this index.
"""
return Field(deref(super().__getitem__(index)))
def __str__(self):
l = [str(self[i]) for i in range(len(self))]
return "{" + ", ".join(l) + "}"
class Field:
"""
A arrow::Field value.
"""
def __init__(self, val):
self.val = val
@property
def name(self):
return StdString(self.val['name_'])
@property
def type(self):
return deref(self.val['type_'])
@property
def nullable(self):
return bool(self.val['nullable_'])
def __str__(self):
return str(self.val)
class FieldPtr(Field):
"""
A std::shared_ptr<arrow::Field> value.
"""
def __init__(self, val):
super().__init__(deref(val))
class Buffer:
"""
A arrow::Buffer value.
"""
def __init__(self, val):
self.val = val
self.size = int(val['size_'])
@property
def data(self):
return self.val['data_']
def bytes_literal(self):
if self.size > 0:
return self.val['data_'].lazy_string(length=self.size).value()
else:
return '""'
def bytes_view(self, offset=0, length=None):
"""
Return a view over the bytes of this buffer.
"""
if self.size > 0:
if length is None:
length = self.size
mem = gdb.selected_inferior().read_memory(
self.val['data_'] + offset, self.size)
else:
mem = memoryview(b"")
# Read individual bytes as unsigned integers rather than
# Python bytes objects
return mem.cast('B')
view = bytes_view
class BufferPtr:
"""
A arrow::Buffer* value (possibly null).
"""
def __init__(self, val):
self.val = val
ptr = int(self.val)
self.buf = Buffer(val.dereference()) if ptr != 0 else None
@property
def data(self):
if self.buf is None:
return None
return self.buf.data
@property
def size(self):
if self.buf is None:
return None
return self.buf.size
def bytes_literal(self):
if self.buf is None:
return None
return self.buf.bytes_literal()
class TypedBuffer(Buffer):
"""
A buffer containing values of a given a struct format code.
"""
_boolean_format = object()
def __init__(self, val, mem_format):
super().__init__(val)
self.mem_format = mem_format
if not self.is_boolean:
self.byte_width = struct.calcsize('=' + self.mem_format)
@classmethod
def from_type_id(cls, val, type_id):
assert isinstance(type_id, int)
if type_id == Type.BOOL:
mem_format = cls._boolean_format
else:
mem_format = type_id_to_struct_code[type_id]
return cls(val, mem_format)
def view(self, offset=0, length=None):
"""
Return a view over the primitive values in this buffer.
The optional `offset` and `length` are expressed in primitive values,
not bytes.
"""
if self.is_boolean:
return Bitmap.from_buffer(self, offset, length)
byte_offset = offset * self.byte_width
if length is not None:
mem = self.bytes_view(byte_offset, length * self.byte_width)
else:
mem = self.bytes_view(byte_offset)
return TypedView(mem, self.mem_format)
@property
def is_boolean(self):
return self.mem_format is self._boolean_format
class TypedView(Sequence):
"""
View a bytes-compatible object as a sequence of objects described
by a struct format code.
"""
def __init__(self, mem, mem_format):
assert isinstance(mem, memoryview)
self.mem = mem
self.mem_format = mem_format
self.byte_width = struct.calcsize('=' + mem_format)
self.length = mem.nbytes // self.byte_width
def _check_index(self, index):
if not 0 <= index < self.length:
raise IndexError("Wrong index for bitmap")
def __len__(self):
return self.length
def __getitem__(self, index):
self._check_index(index)
w = self.byte_width
# Cannot use memoryview.cast() because the 'e' format for half-floats
# is poorly supported.
mem = self.mem[index * w:(index + 1) * w]
return struct.unpack('=' + self.mem_format, mem)
class Bitmap(Sequence):
"""
View a bytes-compatible object as a sequence of bools.
"""
_masks = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80]
def __init__(self, view, offset, length):
self.view = view
self.offset = offset
self.length = length
def _check_index(self, index):
if not 0 <= index < self.length:
raise IndexError("Wrong index for bitmap")
def __len__(self):
return self.length
def __getitem__(self, index):
self._check_index(index)
index += self.offset
byte_index, bit_index = divmod(index, 8)
byte = self.view[byte_index]
return byte & self._masks[bit_index] != 0
@classmethod
def from_buffer(cls, buf, offset, length):
assert isinstance(buf, Buffer)
byte_offset, bit_offset = divmod(offset, 8)
byte_length = math.ceil(length + offset / 8) - byte_offset
return cls(buf.bytes_view(byte_offset, byte_length),
bit_offset, length)
class MappedView(Sequence):
def __init__(self, func, view):
self.view = view
self.func = func
def __len__(self):
return len(self.view)
def __getitem__(self, index):
return self.func(self.view[index])
class StarMappedView(Sequence):
def __init__(self, func, view):
self.view = view
self.func = func
def __len__(self):
return len(self.view)
def __getitem__(self, index):
return self.func(*self.view[index])
class NullBitmap(Bitmap):
def __getitem__(self, index):
self._check_index(index)
if self.view is None:
return True
return super().__getitem__(index)
@classmethod
def from_buffer(cls, buf, offset, length):
"""
Create a null bitmap from a Buffer (or None if missing,
in which case all values are True).
"""
if buf is None:
return cls(buf, offset, length)
return super().from_buffer(buf, offset, length)
KeyValue = namedtuple('KeyValue', ('key', 'value'))
class Metadata(Sequence):
"""
A arrow::KeyValueMetadata value.
"""
def __init__(self, val):
self.val = val
self.keys = StdVector(self.val['keys_'])
self.values = StdVector(self.val['values_'])
def __len__(self):
return len(self.keys)
def __getitem__(self, i):
return KeyValue(StdString(self.keys[i]), StdString(self.values[i]))
class MetadataPtr(Sequence):
"""
A shared_ptr<arrow::KeyValueMetadata> value, possibly null.
"""
def __init__(self, val):
self.ptr = SharedPtr(val).get()
self.is_null = int(self.ptr) == 0
self.md = None if self.is_null else Metadata(self.ptr.dereference())
def __len__(self):
return 0 if self.is_null else len(self.md)
def __getitem__(self, i):
if self.is_null:
raise IndexError
return self.md[i]
DecimalTraits = namedtuple('DecimalTraits', ('bit_width', 'struct_format_le'))
decimal_traits = {
128: DecimalTraits(128, 'Qq'),
256: DecimalTraits(256, 'QQQq'),
}
class BaseDecimal:
"""
Base class for arrow::BasicDecimal{128,256...} values.
"""
def __init__(self, address):
self.address = address
@classmethod
def from_value(cls, val):
"""
Create a decimal from a gdb.Value representing the corresponding
arrow::BasicDecimal{128,256...}.
"""
return cls(val['array_'].address)
@classmethod
def from_address(cls, address):
"""
Create a decimal from a gdb.Value representing the address of the
raw decimal storage.
"""
return cls(address)
@property
def words(self):
"""
The decimal words, from least to most significant.
"""
mem = gdb.selected_inferior().read_memory(self.address,
self.traits.bit_width // 8)
fmt = self.traits.struct_format_le
if byte_order() == 'big':
fmt = fmt[::-1]
words = struct.unpack(f"={fmt}", mem)
if byte_order() == 'big':
words = words[::-1]
return words
def __int__(self):
"""
The underlying bigint value.
"""
v = 0
words = self.words
bits_per_word = self.traits.bit_width // len(words)
for w in reversed(words):
v = (v << bits_per_word) + w
return v
def format(self, precision, scale):
"""
Format as a decimal number with the given precision and scale.
"""
v = int(self)
with decimal.localcontext() as ctx:
ctx.prec = precision
ctx.capitals = False
return str(decimal.Decimal(v).scaleb(-scale))
class Decimal128(BaseDecimal):
traits = decimal_traits[128]
class Decimal256(BaseDecimal):
traits = decimal_traits[256]
decimal_bits_to_class = {
128: Decimal128,
256: Decimal256,
}
decimal_type_to_class = {
f"Decimal{bits}Type": cls
for (bits, cls) in decimal_bits_to_class.items()
}
class ExtensionType:
"""
A arrow::ExtensionType.
"""
def __init__(self, val):
self.val = val
@property
def storage_type(self):
return deref(self.val['storage_type_'])
def to_string(self):
"""
The result of calling ToString(show_metadata=True).
"""
# XXX `show_metadata` is an optional argument, but gdb doesn't allow
# omitting it.
return StdString(gdb.parse_and_eval(
f"{for_evaluation(self.val)}.ToString(true)"))
class Schema:
"""
A arrow::Schema.
"""
def __init__(self, val):
self.val = val
impl = deref(self.val['impl_'])
self.fields = FieldVector(impl['fields_'])
self.metadata = MetadataPtr(impl['metadata_'])
class RecordBatch:
"""
A arrow::RecordBatch.
"""
def __init__(self, val):
# XXX this relies on RecordBatch always being a SimpleRecordBatch
# under the hood. What if users create their own RecordBatch
# implementation?
self.val = cast_to_concrete(val,
gdb.lookup_type("arrow::SimpleRecordBatch"))
self.schema = Schema(deref(self.val['schema_']))
self.columns = StdPtrVector(self.val['columns_'])
@property
def num_rows(self):
return self.val['num_rows_']
class Table:
"""