-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathrealm_parser.py
More file actions
2277 lines (2003 loc) · 89.9 KB
/
Copy pathrealm_parser.py
File metadata and controls
2277 lines (2003 loc) · 89.9 KB
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
# ---------------------------------------------------------------------------
# Vendored into iLEAPP from crush-forensics (github.com/kalink0/crush-forensics)
# by Marco Neumann (kalink0), Apache-2.0, unchanged except:
# * the two crush framework imports below are replaced with minimal local
# shims so the module is self-contained (iLEAPP has no crush.core.vfs /
# crush.parsers.base); the RealmParser class is kept verbatim but iLEAPP
# calls the module-level parse_realm_file() helper appended at the end
# instead, which reads a plain file path and returns decoded tables.
# The upstream author's copyright and SPDX header above are preserved.
#
# This is vendored third-party code kept faithful to upstream, so it is not
# held to iLEAPP's own lint rules; the file-level disable below silences the
# warnings its upstream style and pylint's type inference raise (broad excepts
# and deliberately-unused signature args in the on-disk decoders, plus a few
# not-an-iterable / no-member / import-error false positives). Do not add a
# blanket disable like this to iLEAPP's own artifact code.
# pylint: disable=unused-argument,broad-exception-caught,not-an-iterable,no-member,import-error
# ---------------------------------------------------------------------------
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 - now Marco Neumann (kalink0)
"""Realm database parser — header + array structure decoding.
Column value decoding is dispatched deterministically from each column's
declared type/nullable/collection flags, read directly off its ColKey
(spec child[5], the colkeys array) — not inferred by trying multiple
candidate shapes and seeing which one "looks right". The on-disk formats
implemented here (Cluster/ClusterTree, ArrayIntNull, ArrayBool[Null],
ArrayString/ArrayBinary in all three sub-formats, ArrayTimestamp,
ArrayFixedBytes, ArrayDecimal128, ArrayKey, BasicArray<float/double>) are
taken from the Realm Core C++ source (github.com/realm/realm-core,
Apache-2.0): spec.hpp, keys.hpp, column_type.hpp, cluster.hpp/.cpp,
cluster_tree.cpp, array_integer.hpp, array_bool.hpp, array_string*.hpp,
array_blobs_*.hpp, array_timestamp.hpp/.cpp, array_fixed_bytes.hpp,
array_decimal128.hpp, array_key.hpp, array_basic*.hpp,
column_type_traits.hpp, bplustree.hpp/.cpp, collection_parent.hpp,
list.hpp, lnklst.hpp, array_typed_link.hpp, array_mixed.hpp/.cpp,
data_type.hpp, dictionary.hpp/.cpp. File-relative citations are in each
function's docstring.
List and Set columns (including LinkList — Realm's on-disk type code 13,
a pre-Collections marker that predates the modern ColumnType enum but
still appears in real colkeys) are decoded by walking each row's own
BPlusTree<T> (a differently-laid-out inner node than ClusterNodeInner —
see _walk_bplustree_leaves) and reusing the same per-type leaf decoders
as regular columns.
Mixed and TypedLink are decoded too (_read_array_mixed,
_read_array_typed_link), including as a List/Set element type. A Mixed
value that itself holds a nested List/Set/Dictionary is also expanded,
not shown as a placeholder (array_mixed.hpp's m_refs slot, DataType
type_List=19/type_Set=20/type_Dictionary=21 — see _read_array_mixed,
_read_collection_at_ref, _read_dictionary_at_ref), recursing back into
this same dispatch with a depth cap (_MIXED_MAX_NEST_DEPTH) against a
corrupt/malicious reference chain. Only a data_type this dispatch
genuinely doesn't recognise (e.g. Geospatial, which turns out to have no
case in array_mixed.cpp's store() at all) falls through to a clearly
labelled "<mixed: unsupported type_N>" marker — never silently.
Dictionary<K,Mixed> columns (_read_dictionary_column) are decoded too: a
per-row 2-slot "dictionary top" array whose slot 0/1 are BPlusTree roots
for keys and values respectively, paired by identical index position
(dictionary.cpp); the key's declared type is read from the spec's
m_types array rather than the colkey (spec.hpp/.cpp
get_dictionary_key_type — see _extract_column_info) for a top-level
Dictionary column, or hardcoded to String for a Dictionary nested inside
a Mixed value (dictionary.cpp's ref-only constructor initializes
`m_key_type(type_String)` unconditionally — there is no Spec column to
consult in that case).
None of the above has a confirming real-world sample in this project's
test data (only hand-built synthetic fixtures matching the on-disk
format spec) — everything is dispatched from the declared type either
way, never guessed from shape, but "spec-derived" and "cross-checked
against a real Realm-produced file" are different claims. Where a
detail could not be pinned down by the C++ source itself, the exact gap
is documented at the point it was needed (e.g. _decode_bid's caveat
about its own BID-decode arithmetic, not about Realm's file layout).
"""
from __future__ import annotations
import decimal
import math
import re
import struct
import uuid as _uuid_mod
from datetime import datetime, timedelta, timezone
from typing import Any
# --- iLEAPP vendoring shims (replaces: from crush.core.vfs import VFS, VFSNode
# from crush.parsers.base import AbstractParser, ParseResult) ---
class VFS: # pragma: no cover - shim, real reads go through parse_realm_file()
pass
class VFSNode: # pragma: no cover
pass
class AbstractParser: # pragma: no cover
pass
class ParseResult: # pragma: no cover
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# --- end iLEAPP vendoring shims ---
_HEADER_SIZE = 24
_MNEMONIC = b"T-DB"
# width_ndx (bits [2:0] of array flags byte) → element width value
# Scheme 0: width is in bits. Scheme 1: width is in bytes.
_WIDTH_TABLE = [0, 1, 2, 4, 8, 16, 32, 64]
# Realm ColumnType codes stored in the low 6 bits of each ColKey (keys.hpp
# ColKey::get_type, column_type.hpp ColumnType::Type).
_REALM_COL_TYPES: dict[int, str] = {
0: "int",
1: "bool",
2: "string",
4: "data",
6: "mixed",
8: "date",
9: "float",
10: "double",
11: "decimal128",
12: "link",
13: "linklist",
14: "backlink",
15: "objectId",
16: "typedlink",
17: "uuid",
}
# Column types that are hidden (no user-visible name) and must be skipped.
# BackLink columns exist only as the reverse side of a Link and are not
# part of Table's public column set (mirrors Spec::get_public_column_count).
_HIDDEN_COL_TYPES: frozenset[int] = frozenset({14}) # BackLink
# ColumnAttr bits packed into ColKey bits [22:30) (column_type.hpp).
_COL_ATTR_NULLABLE = 0x10
_COL_ATTR_LIST = 0x20
_COL_ATTR_DICTIONARY = 0x40
_COL_ATTR_SET = 0x80
# ---------------------------------------------------------------------------
# Low-level helpers
# ---------------------------------------------------------------------------
def _read_at(vfs: VFS, node: VFSNode, offset: int, size: int) -> bytes:
if offset < 0:
return b""
try:
with vfs.open(node) as src:
try:
src.seek(offset)
return src.read(size)
except Exception:
data = src.read()
return data[offset : offset + size]
except Exception:
return b""
# ---------------------------------------------------------------------------
# File header (24 bytes)
# ---------------------------------------------------------------------------
def _parse_realm_header(data: bytes) -> dict[str, Any] | None:
if len(data) < _HEADER_SIZE:
return None
mnemonic = data[16:20]
if mnemonic != _MNEMONIC:
return None
top_ref0 = int.from_bytes(data[0:8], "little")
top_ref1 = int.from_bytes(data[8:16], "little")
fmt0 = data[20]
fmt1 = data[21]
reserved = data[22]
flags = data[23]
active = 1 if (flags & 0x01) else 0
return {
"Top reference 0": f"{top_ref0} (0x{top_ref0:x})",
"Top reference 1": f"{top_ref1} (0x{top_ref1:x})",
"Mnemonic": mnemonic.decode("ascii", errors="replace"),
"File format (top ref 0)": fmt0,
"File format (top ref 1)": fmt1,
"Reserved": reserved,
"Flags": f"0x{flags:02x}",
"Active top reference": active,
}
# ---------------------------------------------------------------------------
# Array header (8 bytes)
# ---------------------------------------------------------------------------
def _parse_array_header(data: bytes, offset: int = 0) -> dict[str, Any] | None:
"""Parse a Realm 8-byte array header at *offset* inside *data*.
Array header layout:
[0:4] checksum — always 0x41414141 ("AAAA")
[4] flags — 5 bit-groups (see below)
[5:8] size — big-endian uint24: number of elements in payload
Flags byte (MSB = bit 7):
bit 7 is_inner_bptree_node
bit 6 has_refs (1 = Reference Array; payload = file offsets)
bit 5 context_flag (purpose unclear)
bits [4:3] width_scheme (0=bits, 1=bytes, 2=size-only)
bits [2:0] width_ndx → _WIDTH_TABLE lookup
Payload size formulas (before 8-byte alignment):
scheme 0: ceil(width_bits * size / 8)
scheme 1: width_bytes * size
scheme 2: size
"""
if offset < 0 or len(data) < offset + 8:
return None
chunk = data[offset : offset + 8]
if chunk[0:4] != b"\x41\x41\x41\x41":
return None
flags = chunk[4]
size = int.from_bytes(chunk[5:8], "big")
is_inner = bool((flags >> 7) & 1)
has_refs = bool((flags >> 6) & 1)
context_flag = bool((flags >> 5) & 1)
width_scheme = (flags >> 3) & 3
width_ndx = flags & 7
width = _WIDTH_TABLE[width_ndx]
if width_scheme == 0:
payload_bytes = (width * size + 7) // 8 if width > 0 else 0
elif width_scheme == 1:
payload_bytes = width * size
else:
payload_bytes = size
payload_bytes_aligned = (payload_bytes + 7) & ~7
return {
"Checksum": "AAAA (0x41414141)",
"Flags (raw)": f"0x{flags:02x} (0b{flags:08b})",
"is_inner_bptree_node": is_inner,
"has_refs": has_refs,
"context_flag": context_flag,
"width_scheme": width_scheme,
"width_ndx": width_ndx,
"width": width,
"Element count (size)": size,
"Payload bytes (raw)": payload_bytes,
"Payload bytes (aligned)": payload_bytes_aligned,
"Total array bytes": 8 + payload_bytes_aligned,
}
def _elem_bytes(arr_hdr: dict[str, Any]) -> int:
"""Return element size in bytes for an already-decoded array header."""
scheme = arr_hdr["width_scheme"]
width = arr_hdr["width"]
if scheme == 0:
return width // 8 if width >= 8 else 0
if scheme == 1:
return int(width)
return 0 # scheme 2: variable / size-only
def _read_ref(data: bytes, payload_start: int, index: int, elem_bytes: int) -> int:
"""Read one little-endian integer from an array payload at *index*."""
off = payload_start + index * elem_bytes
if elem_bytes < 1 or off + elem_bytes > len(data):
return -1
return int.from_bytes(data[off : off + elem_bytes], "little")
# ---------------------------------------------------------------------------
# Schema extraction
# ---------------------------------------------------------------------------
def _read_uint_array(data: bytes, offset: int) -> list[int]:
"""Read all unsigned integer values from a Realm integer array at *offset*."""
hdr = _parse_array_header(data, offset)
if not hdr:
return []
count = hdr["Element count (size)"]
width = hdr["width"]
scheme = hdr["width_scheme"]
if count == 0 or width == 0:
return []
payload = data[offset + 8:]
vals: list[int] = []
if scheme == 0:
# bit-packed
for i in range(count):
bit_off = i * width
byte_off = bit_off // 8
eb = (width + 7) // 8
if byte_off + eb > len(payload):
break
v = int.from_bytes(payload[byte_off : byte_off + eb], "little")
mask = (1 << width) - 1
vals.append((v >> (bit_off % 8)) & mask)
elif scheme == 1:
eb = width
for i in range(count):
if (i + 1) * eb > len(payload):
break
vals.append(int.from_bytes(payload[i * eb : (i + 1) * eb], "little"))
return vals
def _extract_free_list(
data: bytes, root_offset: int, file_size: int
) -> list[dict[str, Any]]:
"""Extract the Realm free-space list from a root reference array.
Realm's Group node stores three parallel arrays at child indices 3/4/5:
child[3] — file positions of freed blocks
child[4] — byte sizes of freed blocks
child[5] — database version when each block was freed
Returns a list of dicts with keys:
offset, size, version, array_header (or None), strings (list[str]), bytes
"""
root_hdr = _parse_array_header(data, root_offset)
if root_hdr is None or not root_hdr["has_refs"]:
return []
ref_eb = _elem_bytes(root_hdr)
if ref_eb < 1 or root_hdr["Element count (size)"] < 6:
return []
payload_start = root_offset + 8
pos_off = _read_ref(data, payload_start, 3, ref_eb)
sz_off = _read_ref(data, payload_start, 4, ref_eb)
ver_off = _read_ref(data, payload_start, 5, ref_eb)
positions = _read_uint_array(data, pos_off)
sizes = _read_uint_array(data, sz_off)
versions = _read_uint_array(data, ver_off)
entries: list[dict[str, Any]] = []
for i, (pos, sz) in enumerate(zip(positions, sizes)):
if pos <= 0 or sz <= 0 or pos + sz > len(data):
continue
block = data[pos : pos + sz]
arr_hdr = _parse_array_header(data, pos)
strings: list[str] = []
if arr_hdr is None:
# Raw heap — extract null-separated printable strings (≥4 chars)
for chunk in block.split(b"\x00"):
try:
s = chunk.decode("utf-8")
if len(s) >= 4 and s.isprintable():
strings.append(s)
except Exception:
pass
entries.append({
"index": i,
"offset": pos,
"size": sz,
"version": versions[i] if i < len(versions) else None,
"array_header": arr_hdr,
"strings": strings,
"bytes": block,
})
return entries
def _extract_root_children(
data: bytes, root_offset: int, file_size: int
) -> list[dict[str, Any]]:
"""Return the child entries of a root Reference Array.
For each of the N references stored in the root array, returns a dict with
the child's file offset and its decoded array header (if readable).
"""
root_hdr = _parse_array_header(data, root_offset)
if root_hdr is None or not root_hdr["has_refs"]:
return []
ref_elem_bytes = _elem_bytes(root_hdr)
if ref_elem_bytes < 1:
return []
size = root_hdr["Element count (size)"]
payload_start = root_offset + 8
children: list[dict[str, Any]] = []
for i in range(size):
offset = _read_ref(data, payload_start, i, ref_elem_bytes)
child: dict[str, Any] = {"index": i, "offset": offset}
if 0 < offset < file_size:
child["array_header"] = _parse_array_header(data, offset)
else:
child["array_header"] = None
children.append(child)
return children
def _extract_schema(data: bytes, root_offset: int, file_size: int) -> list[str]:
"""Extract class/table names from the Realm schema group array.
B+ tree path followed:
root_offset → root Reference Array
entry[0] → schema group Data Array
each entry → null-terminated ASCII class name (padded to *width* bytes)
"""
root_hdr = _parse_array_header(data, root_offset)
if root_hdr is None or not root_hdr["has_refs"]:
return []
ref_elem_bytes = _elem_bytes(root_hdr)
if ref_elem_bytes < 1:
return []
payload_start = root_offset + 8
schema_offset = _read_ref(data, payload_start, 0, ref_elem_bytes)
if schema_offset <= 0 or schema_offset >= file_size:
return []
schema_hdr = _parse_array_header(data, schema_offset)
if schema_hdr is None:
return []
entry_bytes = _elem_bytes(schema_hdr)
count = schema_hdr["Element count (size)"]
if entry_bytes < 1 or count == 0:
return []
payload_start = schema_offset + 8
names: list[str] = []
for i in range(count):
entry_off = payload_start + i * entry_bytes
if entry_off + entry_bytes > len(data):
break
entry = data[entry_off : entry_off + entry_bytes]
null_pos = entry.find(b"\x00")
raw = entry[:null_pos] if null_pos >= 0 else entry
try:
name = raw.decode("ascii")
except Exception:
continue
if name:
names.append(name)
return names
# ---------------------------------------------------------------------------
# ClusterTree traversal
# ---------------------------------------------------------------------------
#
# Realm's Cluster leaf (cluster.hpp) stores: child[0] = key array (tagged
# integer -> compact sequential keys, row count = raw >> 1; or a ref to an
# explicit ArrayUnsigned of local key values), child[1..] = column data,
# one slot per column at index (colkey.index + 1) (s_first_col_index=1).
#
# Once a table outgrows one leaf, its ClusterTree root becomes a
# ClusterNodeInner (cluster_tree.cpp) with a *fixed* layout:
# child[0] = key-offsets ref, or 0 for "compact" (uniformly-sized) children
# child[1] = tagged sub_tree_depth
# child[2] = tagged sub_tree_size (total row count of this subtree)
# child[3..] = child node refs (each may itself be a leaf or inner node —
# determined by that child's own is_inner_bptree_node flag)
# Child key-space offsets: explicit (child[0] ref) values are absolute
# per-child offsets; compact form computes offset = child_index << shift,
# shift = sub_tree_depth * node_shift_factor. node_shift_factor is 8 for the
# default REALM_MAX_BPNODE_SIZE > 256 build (true for all mainstream Realm
# SDKs); the alternate value (2) is a debug-only build config and is not
# handled here.
_NODE_SHIFT_FACTOR = 8
def _walk_cluster_leaves(
data: bytes,
root_ref: int,
file_size: int,
_visited: set[int] | None = None,
_depth: int = 0,
_base_offset: int = 0,
) -> list[tuple[int, int]]:
"""Recursively resolve a ClusterTree root to its ordered leaf Clusters.
Returns a list of (leaf_ref, key_offset) pairs, in key order. key_offset
is the absolute base to add to each leaf row's local key value to
recover its real ObjKey (cluster.hpp Cluster::get_real_key).
"""
if _depth > 32 or root_ref <= 0 or root_ref >= file_size:
return []
if _visited is None:
_visited = set()
if root_ref in _visited:
return []
_visited.add(root_ref)
hdr = _parse_array_header(data, root_ref)
if hdr is None or not hdr["has_refs"]:
return []
if not hdr["is_inner_bptree_node"]:
return [(root_ref, _base_offset)]
eb = _elem_bytes(hdr)
if eb < 1:
return []
count = hdr["Element count (size)"]
keys_ref = _read_ref(data, root_ref + 8, 0, eb)
explicit_offsets: list[int] | None = _read_uint_array(data, keys_ref) if keys_ref > 0 else None
depth_raw = _read_ref(data, root_ref + 8, 1, eb)
sub_tree_depth = (depth_raw >> 1) if depth_raw >= 0 else 1
shift = max(sub_tree_depth, 0) * _NODE_SHIFT_FACTOR
leaves: list[tuple[int, int]] = []
for i in range(3, count):
child_ref = _read_ref(data, root_ref + 8, i, eb)
if child_ref <= 0 or child_ref >= file_size:
continue
child_idx = i - 3
if explicit_offsets is not None and child_idx < len(explicit_offsets):
child_rel_offset = explicit_offsets[child_idx]
else:
child_rel_offset = child_idx << shift
leaves.extend(
_walk_cluster_leaves(
data, child_ref, file_size, _visited, _depth + 1,
_base_offset + child_rel_offset,
)
)
return leaves
def _read_cluster_key_info(
data: bytes, cluster_ref: int, cluster_eb: int, file_size: int,
) -> tuple[int | None, list[int] | None]:
"""Decode a leaf Cluster's child[0] key slot.
Returns (row_count, local_key_values). child[0] is either a tagged
integer (RefOrTagged compact form — row count = raw >> 1, local keys are
implicitly 0..row_count-1) or a ref to a real ArrayUnsigned of explicit
local key values (cluster.hpp Cluster::init, node_size_from_header).
"""
raw = _read_ref(data, cluster_ref + 8, 0, cluster_eb)
if raw < 0:
return None, None
if raw & 1:
count = raw >> 1
return count, list(range(count))
if raw == 0 or raw >= file_size:
return None, None
hdr = _parse_array_header(data, raw)
if hdr is None or hdr["has_refs"]:
return None, None
count = hdr["Element count (size)"]
values = _read_scalar_leaf(data, raw, file_size)
if values is None:
return count, None
return count, [v if v is not None else 0 for v in values]
def _derive_row_count(
data: bytes,
col_data_ref: int,
num_cols: int,
cd_eb: int,
file_size: int,
) -> int | None:
"""Corruption-recovery fallback, used only when a leaf's key slot
(child[0], handled by _read_cluster_key_info) cannot be read at all —
e.g. a corrupt or partially-overwritten file; the primary, spec-driven
read has already failed by the time this runs.
This is not shape-guessing: in a well-formed Cluster leaf every scalar
column array holds exactly one entry per row, so all of them share the
same declared Element count — that equality is a real structural
invariant of cluster.hpp, not an assumption about what the data
"usually" looks like. Taking the most common count is a vote across
those redundant, independently-stored copies to recover the true count
even if corruption skewed a minority of them — the same logic as
reconstructing a value from redundant/parity copies. The caller flags
the affected table's row_count as estimated (row_count_estimated) so
this is never presented to the analyst as an authoritative figure.
"""
from collections import Counter
counts: list[int] = []
for c_idx in range(num_cols):
col_ref = _read_ref(data, col_data_ref + 8, c_idx, cd_eb)
if col_ref <= 0 or col_ref >= file_size:
continue
hdr = _parse_array_header(data, col_ref)
if hdr and not hdr["has_refs"]:
counts.append(hdr["Element count (size)"])
if not counts:
return None
return Counter(counts).most_common(1)[0][0]
# ---------------------------------------------------------------------------
# BPlusTree traversal — List / Set (and LinkList) columns
# ---------------------------------------------------------------------------
#
# Each row of a List/Set column owns an *independent* BPlusTree<T> holding
# its elements (list.hpp: Lst<T>::m_tree; collection_parent.hpp:
# CollectionParent::get_collection_ref — a plain ref per row, 0 = empty
# collection, read directly from the cluster's column-data array like any
# other flat ref array).
#
# BPlusTree<T>'s own inner-node layout (bplustree.cpp: BPlusTreeInner) is
# *not* the same as ClusterNodeInner:
# element[0] = tagged "elements per child" (compact form), or a
# ref to an m_offsets array of per-child start
# offsets (general form) — distinguished by the
# RefOrTagged tag bit, not by zero/nonzero
# element[1..N] = child node refs (get_bp_node_ref(ndx)=get(ndx+1))
# element[N+1] (last) = tagged total subtree size (get_tree_size=back()>>1)
# i.e. get_node_size() = Array::size() - 2 (2 bookkeeping slots, not 3).
def _walk_bplustree_leaves(
data: bytes,
root_ref: int,
file_size: int,
_visited: set[int] | None = None,
_depth: int = 0,
_base_offset: int = 0,
) -> list[tuple[int, int]]:
"""Recursively resolve a BPlusTree<T> root to its ordered leaf arrays.
Returns (leaf_ref, offset) pairs; leaf_ref points directly to a leaf
array in the *same* per-type format used for regular cluster columns
(e.g. ArrayKey for a List<Link>'s elements), so leaves are decoded by
reusing _decode_column_values with the collection's element type.
"""
if _depth > 32 or root_ref <= 0 or root_ref >= file_size:
return []
if _visited is None:
_visited = set()
if root_ref in _visited:
return []
_visited.add(root_ref)
hdr = _parse_array_header(data, root_ref)
if hdr is None:
return []
if not hdr["is_inner_bptree_node"]:
return [(root_ref, _base_offset)]
eb = _elem_bytes(hdr)
if eb < 1:
return []
count = hdr["Element count (size)"]
if count < 2:
return []
num_children = count - 2
elem0_raw = _read_ref(data, root_ref + 8, 0, eb)
is_compact = elem0_raw >= 0 and (elem0_raw & 1) != 0
elems_per_child = (elem0_raw >> 1) if is_compact else 0
explicit_offsets: list[int] | None = None
if not is_compact and elem0_raw > 0:
explicit_offsets = _read_uint_array(data, elem0_raw)
leaves: list[tuple[int, int]] = []
for i in range(num_children):
child_ref = _read_ref(data, root_ref + 8, i + 1, eb)
if child_ref <= 0 or child_ref >= file_size:
continue
if explicit_offsets is not None:
child_rel_offset = explicit_offsets[i - 1] if i > 0 and (i - 1) < len(explicit_offsets) else 0
else:
child_rel_offset = i * elems_per_child
leaves.extend(
_walk_bplustree_leaves(
data, child_ref, file_size, _visited, _depth + 1,
_base_offset + child_rel_offset,
)
)
return leaves
def _read_collection_column(
data: bytes,
col_ref: int,
file_size: int,
element_type: int,
nullable: bool,
) -> list[list[Any]] | None:
"""Decode a List/Set column: a flat ref array, one ref per row, each
pointing to that row's own BPlusTree<T> root (0 = empty collection).
Each row's elements are decoded by reusing _decode_column_values on
every leaf of that row's tree, with the collection's element type.
"""
hdr = _parse_array_header(data, col_ref)
if hdr is None or not hdr["has_refs"]:
return None
eb = _elem_bytes(hdr)
if eb < 1:
return None
count = hdr["Element count (size)"]
element_info = {
"type_code": element_type,
"nullable": nullable,
"is_list": False,
"is_dictionary": False,
"is_set": False,
}
results: list[list[Any]] = []
for i in range(count):
row_ref = _read_ref(data, col_ref + 8, i, eb)
if row_ref <= 0 or row_ref >= file_size:
results.append([])
continue
values: list[Any] = []
for leaf_ref, _off in _walk_bplustree_leaves(data, row_ref, file_size):
leaf_vals = _decode_column_values(data, leaf_ref, file_size, element_info)
if leaf_vals:
values.extend(leaf_vals)
results.append(values)
return results
def _read_dictionary_column(
data: bytes,
col_ref: int,
file_size: int,
key_type: int | None,
) -> list[dict[Any, Any]] | None:
"""Decode a Dictionary<K,Mixed> column: a flat ref array, one ref per
row (0 = empty/no dictionary), each pointing directly to that row's own
2-slot "dictionary top" array — no indirection (dictionary.cpp:
`if (ref) { m_dictionary_top->init_from_ref(ref); m_keys->init_from_parent();
m_values->init_from_parent(); }`).
Slot 0 of that array is a BPlusTree<K> root for the keys, slot 1 a
BPlusTree<Mixed> root for the values (dictionary.cpp constructor:
`m_keys->set_parent(m_dictionary_top.get(), 0);
m_values->set_parent(m_dictionary_top.get(), 1);` — values are always
Mixed-typed regardless of the declared key type). The two trees are
paired by identical index position, not an explicit key->value link
(dictionary.cpp: `REALM_ASSERT(m_keys->size() == m_values->size())`).
*key_type* is the DataType read from the spec's m_types array by the
caller (_extract_column_info) — dispatched through the same
_decode_column_values used for regular columns, since DataType and
ColumnType share the same integer values for scalar types. Returns
None (not a per-row failure) if the key type could not be determined,
since keys cannot be decoded at all without it. Per-instance decoding
(the 2-slot top array itself) is shared with Dictionaries nested
inside a Mixed value via _read_dictionary_at_ref.
"""
if key_type is None:
return None
hdr = _parse_array_header(data, col_ref)
if hdr is None or not hdr["has_refs"]:
return None
eb = _elem_bytes(hdr)
if eb < 1:
return None
count = hdr["Element count (size)"]
results: list[dict[Any, Any]] = []
for i in range(count):
top_ref = _read_ref(data, col_ref + 8, i, eb)
results.append(_read_dictionary_at_ref(data, top_ref, file_size, key_type))
return results
# ---------------------------------------------------------------------------
# Spec / column metadata
# ---------------------------------------------------------------------------
def _extract_column_names(
data: bytes,
table_ref: int,
table_eb: int,
file_size: int,
) -> list[str]:
"""Read public column names from the spec at child[0] of the table node.
Path: table_ref → child[0] (spec) → child[1] (names Data Array).
The names array holds one fixed-width null-terminated ASCII entry per
*public* column only (spec.hpp s_names_ndx=1; hidden BackLink columns
have no name slot — confirmed empirically: a table with N declared
columns has fewer name entries than colkey/type entries whenever it is
the target of a Link elsewhere in the schema).
Returns an empty list on any failure.
"""
spec_ref = _read_ref(data, table_ref + 8, 0, table_eb)
if spec_ref <= 0 or spec_ref >= file_size:
return []
spec_hdr = _parse_array_header(data, spec_ref)
if spec_hdr is None or not spec_hdr["has_refs"] or spec_hdr["Element count (size)"] < 2:
return []
spec_eb = _elem_bytes(spec_hdr)
if spec_eb < 1:
return []
names_ref = _read_ref(data, spec_ref + 8, 1, spec_eb)
if names_ref <= 0 or names_ref >= file_size:
return []
names_hdr = _parse_array_header(data, names_ref)
if names_hdr is None or names_hdr["has_refs"]:
return []
entry_bytes = _elem_bytes(names_hdr)
count = names_hdr["Element count (size)"]
if entry_bytes < 1 or count == 0:
return []
payload_start = names_ref + 8
names: list[str] = []
for i in range(count):
entry_off = payload_start + i * entry_bytes
if entry_off + entry_bytes > len(data):
break
entry = data[entry_off : entry_off + entry_bytes]
null_pos = entry.find(b"\x00")
raw = entry[:null_pos] if null_pos >= 0 else entry
try:
name = raw.decode("ascii").strip()
except Exception:
name = f"col_{i}"
names.append(name if name else f"col_{i}")
return names
def _extract_column_info(
data: bytes,
table_ref: int,
table_eb: int,
file_size: int,
) -> list[dict[str, Any]] | None:
"""Build the per-user-column decode plan directly from the colkeys array
(spec child[5]) — the single source of truth for column dispatch.
Each 64-bit ColKey packs index[0:16) | type[16:22) | attrs[22:30) |
tag[30:62) (keys.hpp ColKey::get_index/get_type/get_attrs). attrs bit
0x10=nullable, 0x20=list, 0x40=dictionary, 0x80=set (column_type.hpp
ColumnAttr). This replaces separately reading and cross-referencing the
spec's type-code array — the type is already embedded in the colkey.
For Dictionary columns, the *key* type isn't in the colkey at all —
it's packed into the upper 16 bits of the matching entry in the spec's
m_types array (spec child[0]), one entry per column in the same full
index space as colkeys (including hidden BackLink columns), set by
Spec::set_dictionary_key_type / read by Spec::get_dictionary_key_type
(spec.hpp/.cpp): `(type & 0xFFFF) + (int64_t(key_type) << 16)`.
DataType and ColumnType share the same integer values for the basic
scalar types (data_type.hpp: "Value assignments must be kept in sync
with column_type.h"), so the extracted key type can be dispatched with
the same type_code machinery used for regular columns.
Hidden BackLink columns (type 14) are skipped, matching the public
column order used by _extract_column_names. Returns None on failure.
"""
spec_ref = _read_ref(data, table_ref + 8, 0, table_eb)
if spec_ref <= 0 or spec_ref >= file_size:
return None
spec_hdr = _parse_array_header(data, spec_ref)
if spec_hdr is None or not spec_hdr["has_refs"] or spec_hdr["Element count (size)"] < 6:
return None
spec_eb = _elem_bytes(spec_hdr)
if spec_eb < 1:
return None
colkeys_ref = _read_ref(data, spec_ref + 8, 5, spec_eb)
if colkeys_ref <= 0 or colkeys_ref >= file_size:
return None
colkeys = _read_scalar_leaf(data, colkeys_ref, file_size)
if not colkeys:
return None
types_ref = _read_ref(data, spec_ref + 8, 0, spec_eb)
raw_types = _read_scalar_leaf(data, types_ref, file_size) if 0 < types_ref < file_size else None
infos: list[dict[str, Any]] = []
user_col_idx = 0
for spec_idx, colkey in enumerate(colkeys):
if colkey is None:
continue
colkey = int(colkey)
type_code = (colkey >> 16) & 0x3F
if type_code in _HIDDEN_COL_TYPES:
continue
attrs = (colkey >> 22) & 0xFF
is_dictionary = bool(attrs & _COL_ATTR_DICTIONARY)
dictionary_key_type = None
if is_dictionary and raw_types and spec_idx < len(raw_types):
raw_type_val = raw_types[spec_idx]
if raw_type_val is not None:
dictionary_key_type = (int(raw_type_val) >> 16) & 0xFFFF
infos.append({
"user_col_idx": user_col_idx,
"col_index": colkey & 0xFFFF,
"cluster_idx": (colkey & 0xFFFF) + 1,
"type_code": type_code,
"nullable": bool(attrs & _COL_ATTR_NULLABLE),
"is_list": bool(attrs & _COL_ATTR_LIST),
"is_dictionary": is_dictionary,
"is_set": bool(attrs & _COL_ATTR_SET),
"dictionary_key_type": dictionary_key_type,
})
user_col_idx += 1
return infos if infos else None
# TableKey::null_value (keys.hpp) — "no opposite table" sentinel.
_TABLE_KEY_NULL = 0x7FFFFFFF
def _read_table_own_key(
data: bytes, table_ref: int, table_eb: int, file_size: int,
) -> int | None:
"""Read a table's own TableKey (table.hpp top_position_for_key=3, a
tagged RefOrTagged value — Table::get_key_direct)."""
raw = _read_ref(data, table_ref + 8, 3, table_eb)
if raw < 0 or not (raw & 1):
return None
return raw >> 1
def _build_table_key_map(
data: bytes, root_offset: int, schema: list[str], file_size: int,
) -> dict[int, str]:
"""Map each table's own TableKey to its schema name, so Link/LinkList
columns can resolve which table they point to (table.hpp
top_position_for_key / top_position_for_opposite_table — see
_read_opposite_table_keys). TableKeys are stable identifiers assigned
at table-creation time, not necessarily the same as the physical
index into the Group's table-refs array, so this mapping is required
rather than assuming table_key == schema index.
"""
root_hdr = _parse_array_header(data, root_offset)
if root_hdr is None or not root_hdr["has_refs"]:
return {}
root_eb = _elem_bytes(root_hdr)
if root_eb < 1:
return {}
table_refs_off = _read_ref(data, root_offset + 8, 1, root_eb)
if table_refs_off <= 0 or table_refs_off >= file_size:
return {}
tr_hdr = _parse_array_header(data, table_refs_off)
if tr_hdr is None or not tr_hdr["has_refs"]:
return {}
tr_eb = _elem_bytes(tr_hdr)
num_tables = tr_hdr["Element count (size)"]
mapping: dict[int, str] = {}
for t_idx in range(num_tables):
table_ref = _read_ref(data, table_refs_off + 8, t_idx, tr_eb)
if table_ref <= 0 or table_ref >= file_size:
continue
t_hdr = _parse_array_header(data, table_ref)
if t_hdr is None or not t_hdr["has_refs"] or t_hdr["Element count (size)"] < 4:
continue
t_eb = _elem_bytes(t_hdr)
table_key = _read_table_own_key(data, table_ref, t_eb, file_size)
if table_key is not None:
mapping[table_key] = schema[t_idx] if t_idx < len(schema) else f"table[{t_idx}]"
return mapping
def _read_opposite_table_keys(
data: bytes, table_ref: int, table_eb: int, file_size: int,
) -> list[int | bool | None] | None:
"""Read table.hpp's m_opposite_table array (top_position_for_opposite_table
= 7): one raw TableKey per column, in the same full index space as the
colkeys/types/attrs arrays (including hidden BackLink columns) — used
to resolve a Link/LinkList column's target table
(Table::get_opposite_table_key)."""
ref = _read_ref(data, table_ref + 8, 7, table_eb)
if ref <= 0 or ref >= file_size:
return None
hdr = _parse_array_header(data, ref)
if hdr is None or hdr["has_refs"]:
return None
return _read_scalar_leaf(data, ref, file_size)
# ---------------------------------------------------------------------------
# Primitive value decoders — each implements exactly one real Realm Array
# class. No structural guessing: the caller already knows which one to call
# from the column's declared type (see _extract_column_info / _decode_column_values).
# ---------------------------------------------------------------------------
def _read_scalar_leaf(
data: bytes,
col_offset: int,
file_size: int,
) -> list[int | bool | None] | None:
"""Parse a flat, non-nullable Realm scalar array (ArrayInteger / boolean
bit-packed / any plain has_refs=False integer array — also reused as the
generic reader for colkeys, type codes, offsets, and key arrays).