-
Notifications
You must be signed in to change notification settings - Fork 165
/
btrfs_tree.py
3020 lines (2572 loc) · 80.1 KB
/
btrfs_tree.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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# SPDX-License-Identifier: LGPL-2.1-or-later
"""Helpers for introspecting btrfs btree structures"""
from contextlib import suppress
import enum
import functools
import operator
import struct
import sys
import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
import uuid
if TYPE_CHECKING:
from _typeshed import SupportsWrite
from typing import Final, Self # novermin
from drgn import IntegerLike, Object, cast
from drgn.helpers.common.format import escape_ascii_string
from drgn.helpers.linux.mm import page_size, page_to_virt
from drgn.helpers.linux.radixtree import radix_tree_lookup
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)
_NOT_FOUND = object()
class cached_property(Generic[_T_co]):
def __init__(self, func: Callable[[Any], _T_co]) -> None:
self.func = func
self.__doc__ = func.__doc__
self.__module__ = func.__module__
def __set_name__(self, owner: Type[Any], name: str) -> None:
self.attrname = name
def __get__(self, instance: object, owner: Optional[Type[Any]] = None) -> _T_co:
cache = instance.__dict__
val = cache.get(self.attrname, _NOT_FOUND)
if val is _NOT_FOUND:
val = self.func(instance)
cache[self.attrname] = val
return val
_crc32c_table = [0] * 256
for i in range(256):
fwd = i
for j in range(8, 0, -1):
if fwd & 1:
fwd = (fwd >> 1) ^ 0x82F63B78
else:
fwd >>= 1
_crc32c_table[i] = fwd & 0xFFFFFFFF
def _crc32c(b: bytes, crc: int = 0) -> int:
for c in b:
crc = (crc >> 8) ^ _crc32c_table[(crc ^ c) & 0xFF]
return crc
def btrfs_name_hash(name: bytes) -> int:
return _crc32c(name, 0xFFFFFFFE)
def _hash_extent_data_ref(root_objectid: int, owner: int, offset: int) -> int:
high_crc = _crc32c(root_objectid.to_bytes(8, "little"), 0xFFFFFFFF)
low_crc = _crc32c(owner.to_bytes(8, "little"), 0xFFFFFFFF)
low_crc = _crc32c(offset.to_bytes(8, "little"), low_crc)
return (high_crc << 31) ^ low_crc
class _BtrfsEnum(enum.IntEnum):
def __str__(self) -> str:
return self._name_
class _BtrfsFlag(enum.IntFlag):
def __str__(self) -> str:
if not self:
return "0x0(none)"
# btrfs-progs as of v6.8.1 ignores unknown flags when printing them,
# but _name_ includes the numeric value of unknown flags.
return f"{hex(self)}({self._name_})"
EnumT = TypeVar("EnumT", bound=enum.Enum)
def _try_cast_enum(enum_type: Type[EnumT], value: int) -> Union[EnumT, int]:
try:
return enum_type(value)
except ValueError:
return value
class BtrfsType(_BtrfsEnum):
# Generated with
# sed -rn 's/^#\s*define\s+BTRFS_(([0-9A-Za-z_]+)_KEY|(UUID_KEY_SUBVOL|UUID_KEY_RECEIVED_SUBVOL))\s+([0-9]+).*/ \2\3 = \4/p' include/uapi/linux/btrfs_tree.h |
# grep -v -e BALANCE_ITEM -e DEV_STATS
#
# UUID_KEY_{,RECEIVED_}SUBVOL broke with the usual naming scheme.
# BALANCE_ITEM and DEV_STATS are obsolete names for TEMPORARY_ITEM and
# PERSISTENT_ITEM, respectively.
INODE_ITEM = 1
INODE_REF = 12
INODE_EXTREF = 13
XATTR_ITEM = 24
VERITY_DESC_ITEM = 36
VERITY_MERKLE_ITEM = 37
ORPHAN_ITEM = 48
DIR_LOG_ITEM = 60
DIR_LOG_INDEX = 72
DIR_ITEM = 84
DIR_INDEX = 96
EXTENT_DATA = 108
EXTENT_CSUM = 128
ROOT_ITEM = 132
ROOT_BACKREF = 144
ROOT_REF = 156
EXTENT_ITEM = 168
METADATA_ITEM = 169
EXTENT_OWNER_REF = 172
TREE_BLOCK_REF = 176
EXTENT_DATA_REF = 178
SHARED_BLOCK_REF = 182
SHARED_DATA_REF = 184
BLOCK_GROUP_ITEM = 192
FREE_SPACE_INFO = 198
FREE_SPACE_EXTENT = 199
FREE_SPACE_BITMAP = 200
DEV_EXTENT = 204
DEV_ITEM = 216
CHUNK_ITEM = 228
RAID_STRIPE = 230
QGROUP_STATUS = 240
QGROUP_INFO = 242
QGROUP_LIMIT = 244
QGROUP_RELATION = 246
TEMPORARY_ITEM = 248
PERSISTENT_ITEM = 249
DEV_REPLACE = 250
UUID_KEY_SUBVOL = 251
UUID_KEY_RECEIVED_SUBVOL = 252
STRING_ITEM = 253
class BtrfsObjectid(_BtrfsEnum):
# Generated with
# sed -rn 's/^#\s*define\s+BTRFS_([0-9A-Za-z_]+)_OBJECTID\s+(-?[0-9]+).*/ \1 = \2/p' include/uapi/linux/btrfs_tree.h |
# grep -v -e DEV_STATS -e FIRST_FREE -e LAST_FREE -e FIRST_CHUNK_TREE -e DEV_ITEMS -e BTREE_INODE -e EMPTY_SUBVOL_DIR |
# sed -r 's/-[0-9]+/& \& 0xffffffffffffffff/'
#
# DEV_STATS (0) only applies if the type is PERSISTENT_ITEM.
# FIRST_FREE (256) and LAST_FREE (-256) define the range of normal
# objectids and aren't meaningful on their own.
# FIRST_CHUNK_TREE (256) only applies if the type is CHUNK_ITEM.
# DEV_ITEMS (1) only applies if the type is DEV_ITEM.
# BTREE_INODE (1) and EMPTY_SUBVOL_DIR (2) are only used as special inode
# numbers in memory.
ROOT_TREE = 1
EXTENT_TREE = 2
CHUNK_TREE = 3
DEV_TREE = 4
FS_TREE = 5
ROOT_TREE_DIR = 6
CSUM_TREE = 7
QUOTA_TREE = 8
UUID_TREE = 9
FREE_SPACE_TREE = 10
BLOCK_GROUP_TREE = 11
RAID_STRIPE_TREE = 12
BALANCE = -4 & 0xFFFFFFFFFFFFFFFF
ORPHAN = -5 & 0xFFFFFFFFFFFFFFFF
TREE_LOG = -6 & 0xFFFFFFFFFFFFFFFF
TREE_LOG_FIXUP = -7 & 0xFFFFFFFFFFFFFFFF
TREE_RELOC = -8 & 0xFFFFFFFFFFFFFFFF
DATA_RELOC_TREE = -9 & 0xFFFFFFFFFFFFFFFF
EXTENT_CSUM = -10 & 0xFFFFFFFFFFFFFFFF
FREE_SPACE = -11 & 0xFFFFFFFFFFFFFFFF
FREE_INO = -12 & 0xFFFFFFFFFFFFFFFF
_non_standard_objectid_types = frozenset(
{
BtrfsType.PERSISTENT_ITEM,
BtrfsType.DEV_EXTENT,
BtrfsType.QGROUP_RELATION,
BtrfsType.UUID_KEY_SUBVOL,
BtrfsType.UUID_KEY_RECEIVED_SUBVOL,
BtrfsType.DEV_ITEM,
}
)
_BTRFS_QGROUP_LEVEL_SHIFT = 48
def _qgroup_id_str(id: int) -> str:
level = id >> _BTRFS_QGROUP_LEVEL_SHIFT
subvolid = id & ((1 << _BTRFS_QGROUP_LEVEL_SHIFT) - 1)
return f"{level}/{subvolid}"
def _objectid_to_str(objectid: int, type: int) -> str:
# Based on print_objectid() in btrfs-progs.
if type == BtrfsType.PERSISTENT_ITEM:
if objectid == 0:
return "DEV_STATS"
elif type == BtrfsType.DEV_EXTENT:
return str(objectid)
elif type == BtrfsType.QGROUP_RELATION:
return _qgroup_id_str(objectid)
elif type in (BtrfsType.UUID_KEY_SUBVOL, BtrfsType.UUID_KEY_RECEIVED_SUBVOL):
return f"0x{objectid:016x}"
elif objectid == 1 and type == BtrfsType.DEV_ITEM:
return "DEV_ITEMS"
elif objectid == 256 and type == BtrfsType.CHUNK_ITEM:
return "FIRST_CHUNK_TREE"
elif objectid == 0xFFFFFFFFFFFFFFFF:
return "-1"
else:
try:
return str(BtrfsObjectid(objectid))
except ValueError:
pass
return str(int(objectid))
_btrfs_disk_key_fmt = "<QBQ"
_btrfs_disk_key_struct = struct.Struct(_btrfs_disk_key_fmt)
_btrfs_item_struct = struct.Struct(_btrfs_disk_key_fmt + "II")
_btrfs_key_ptr_struct = struct.Struct(_btrfs_disk_key_fmt + "QQ")
class BtrfsHeaderFlag(_BtrfsFlag):
WRITTEN = 1 << 0
RELOC = 1 << 1
_btrfs_header_struct = struct.Struct("<32s16sQQ16sQQIB")
class BtrfsHeader(NamedTuple):
csum: bytes
fsid: uuid.UUID
bytenr: int
flags: int
chunk_tree_uuid: uuid.UUID
generation: int
owner: int
nritems: int
level: int
@staticmethod
def from_bytes(b: bytes) -> "BtrfsHeader":
(
csum,
fsid,
bytenr,
flags,
chunk_tree_uuid,
generation,
owner,
nritems,
level,
) = _btrfs_header_struct.unpack_from(b)
return BtrfsHeader(
csum=csum,
fsid=uuid.UUID(bytes=fsid),
bytenr=bytenr,
flags=BtrfsHeaderFlag(flags),
chunk_tree_uuid=uuid.UUID(bytes=chunk_tree_uuid),
generation=generation,
owner=owner,
nritems=nritems,
level=level,
)
class BtrfsKey(
NamedTuple(
"BtrfsKey",
[
("objectid", Union[BtrfsObjectid, int]),
("type", Union[BtrfsType, int]),
("offset", int),
],
)
):
def __new__(cls, objectid: int, type: int, offset: int) -> "Self":
with suppress(ValueError):
type = BtrfsType(type)
if type not in _non_standard_objectid_types:
with suppress(ValueError):
objectid = BtrfsObjectid(objectid)
return super().__new__(cls, objectid, type, offset)
@classmethod
def _make(cls, iterable: Iterable[Any]) -> "Self":
return cls.__new__(cls, *iterable)
@staticmethod
def from_bytes(b: bytes) -> "BtrfsKey":
return BtrfsKey._make(_btrfs_disk_key_struct.unpack_from(b))
def __str__(self) -> str:
# Based on btrfs_print_key() in btrfs-progs.
type = (
self.type._name_
if isinstance(self.type, BtrfsType)
else f"UNKNOWN.{self.type}"
)
if self.type in (
BtrfsType.QGROUP_INFO,
BtrfsType.QGROUP_LIMIT,
BtrfsType.QGROUP_RELATION,
):
offset = _qgroup_id_str(self.offset)
elif self.type in (
BtrfsType.UUID_KEY_SUBVOL,
BtrfsType.UUID_KEY_RECEIVED_SUBVOL,
):
offset = f"0x{self.offset:016x}"
elif (
self.type == BtrfsType.ROOT_ITEM
and self.objectid == BtrfsObjectid.TREE_RELOC
):
offset = _objectid_to_str(self.offset, self.type)
elif self.offset == 0xFFFFFFFFFFFFFFFF:
# btrfs-progs as of v6.8.1 skips this for ROOT_ITEM.
offset = "-1"
else:
offset = str(self.offset)
return f"({_objectid_to_str(self.objectid, self.type)} {type} {offset})"
BTRFS_MIN_KEY = BtrfsKey(0, 0, 0)
BTRFS_MAX_KEY = BtrfsKey(2**64 - 1, 2**8 - 1, 2**64 - 1)
class BtrfsKeyPtr(NamedTuple):
key: BtrfsKey
blockptr: int
generation: int
@staticmethod
def from_bytes(b: bytes) -> "BtrfsKeyPtr":
t = _btrfs_key_ptr_struct.unpack_from(b)
return BtrfsKeyPtr(BtrfsKey._make(t[:3]), *t[3:])
# class _BtrfsItemHandler(NamedTuple, Generic[_T]) and replacing Any with _T
# would be more accurate, but that fails at runtime on Python 3.6; see
# python/typing#449. This is good enough since it's checked more strictly
# through _register_item_handler().
class _BtrfsItemHandler(NamedTuple):
parse: Callable[[BtrfsKey, bytes], Any]
print: Callable[[BtrfsKey, bytes, Any, str, "Optional[SupportsWrite[str]]"], None]
_btrfs_item_handlers = {}
# We could define one big dictionary literal with type
# Dict[int, _BtrfsItemHandler], but then mypy won't enforce that the return
# type of parse() matches the parameter type of print().
def _register_item_handler(
type: BtrfsType,
parse: Callable[[BtrfsKey, bytes], _T],
print: Callable[[BtrfsKey, bytes, _T, str, "Optional[SupportsWrite[str]]"], None],
) -> None:
assert type not in _btrfs_item_handlers
_btrfs_item_handlers[int(type)] = _BtrfsItemHandler(parse, print)
def _parse_unknown_item(key: BtrfsKey, raw_data: bytes) -> None:
return None
def _print_unknown_item(
key: BtrfsKey,
raw_data: bytes,
data: None,
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
step = 30
for i in range(0, len(raw_data), step):
print(f"{indent}{'raw' if i == 0 else ' '} {raw_data[i:i + step].hex()}")
_unknown_item_type_handler = _BtrfsItemHandler(
parse=_parse_unknown_item,
print=_print_unknown_item,
)
def _parse_empty_item(key: BtrfsKey, raw_data: bytes) -> None:
if raw_data:
raise ValueError("expected empty item")
return None
def _parse_raw_item(key: BtrfsKey, raw_data: bytes) -> bytes:
return raw_data
def _parse_item_from_bytes(
from_bytes: Callable[[bytes], _T]
) -> Callable[[BtrfsKey, bytes], _T]:
@functools.wraps(from_bytes)
def wrapper(key: BtrfsKey, raw_data: bytes) -> _T:
return from_bytes(raw_data)
return wrapper
def _print_nothing(
key: BtrfsKey,
raw_data: bytes,
data: None,
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
return
def _print_empty_item(
s: str,
) -> Callable[[BtrfsKey, bytes, None, str, "Optional[SupportsWrite[str]]"], None]:
def print_empty_item(
key: BtrfsKey,
raw_data: bytes,
data: None,
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
print(f"{indent}{s}", file=file)
return print_empty_item
class BtrfsTimespec(NamedTuple):
sec: int
nsec: int
def __str__(self) -> str:
# btrfs-progs as of v6.8.1 doesn't zero-pad nsec. This is a bug.
return f"{self.sec}.{self.nsec:09} ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.sec))})"
class BtrfsInodeFlag(_BtrfsFlag):
NODATASUM = 1 << 0
NODATACOW = 1 << 1
READONLY = 1 << 2
NOCOMPRESS = 1 << 3
PREALLOC = 1 << 4
SYNC = 1 << 5
IMMUTABLE = 1 << 6
APPEND = 1 << 7
NODUMP = 1 << 8
NOATIME = 1 << 9
DIRSYNC = 1 << 10
COMPRESS = 1 << 11
_btrfs_inode_item_struct = struct.Struct("<5Q4I3Q32xQIQIQIQI")
class BtrfsInodeItem(
NamedTuple(
"BtrfsInodeItem",
[
("generation", int),
("transid", int),
("size", int),
("nbytes", int),
("block_group", int),
("nlink", int),
("uid", int),
("gid", int),
("mode", int),
("rdev", int),
("flags", BtrfsInodeFlag),
("sequence", int),
("atime", BtrfsTimespec),
("ctime", BtrfsTimespec),
("mtime", BtrfsTimespec),
("otime", BtrfsTimespec),
],
)
):
def __new__(
cls,
generation: int,
transid: int,
size: int,
nbytes: int,
block_group: int,
nlink: int,
uid: int,
gid: int,
mode: int,
rdev: int,
flags: int,
sequence: int,
atime: BtrfsTimespec,
ctime: BtrfsTimespec,
mtime: BtrfsTimespec,
otime: BtrfsTimespec,
) -> "Self":
return super().__new__(
cls,
generation=generation,
transid=transid,
size=size,
nbytes=nbytes,
block_group=block_group,
nlink=nlink,
uid=uid,
gid=gid,
mode=mode,
rdev=rdev,
flags=BtrfsInodeFlag(flags),
sequence=sequence,
atime=atime,
ctime=ctime,
mtime=mtime,
otime=otime,
)
@classmethod
def _make(cls, iterable: Iterable[Any]) -> "Self":
return cls.__new__(cls, *iterable)
@staticmethod
def from_bytes(b: bytes) -> "BtrfsInodeItem":
(
generation,
transid,
size,
nbytes,
block_group,
nlink,
uid,
gid,
mode,
rdev,
flags,
sequence,
atime_sec,
atime_nsec,
ctime_sec,
ctime_nsec,
mtime_sec,
mtime_nsec,
otime_sec,
otime_nsec,
) = _btrfs_inode_item_struct.unpack_from(b)
return BtrfsInodeItem(
generation=generation,
transid=transid,
size=size,
nbytes=nbytes,
block_group=block_group,
nlink=nlink,
uid=uid,
gid=gid,
mode=mode,
rdev=rdev,
flags=flags,
sequence=sequence,
atime=BtrfsTimespec(atime_sec, atime_nsec),
ctime=BtrfsTimespec(ctime_sec, ctime_nsec),
mtime=BtrfsTimespec(mtime_sec, mtime_nsec),
otime=BtrfsTimespec(otime_sec, otime_nsec),
)
def _print_inode_item(
key: BtrfsKey,
raw_data: bytes,
item: BtrfsInodeItem,
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
print(
f"""\
{indent}generation {item.generation} transid {item.transid} size {item.size} nbytes {item.nbytes}
{indent}block group {item.block_group} mode {item.mode:o} links {item.nlink} uid {item.uid} gid {item.gid} rdev {item.rdev}
{indent}sequence {item.sequence} flags {item.flags}
{indent}atime {item.atime}
{indent}ctime {item.ctime}
{indent}mtime {item.mtime}
{indent}otime {item.otime}
""",
end="",
file=file,
)
_register_item_handler(
BtrfsType.INODE_ITEM,
_parse_item_from_bytes(BtrfsInodeItem.from_bytes),
_print_inode_item,
)
_btrfs_inode_ref_struct = struct.Struct("<QH")
class BtrfsInodeRef(NamedTuple):
index: int # type: ignore[assignment] # Conflicts with tuple.index()
name: bytes
@staticmethod
def from_bytes(b: bytes) -> "BtrfsInodeRef":
index, name_len = _btrfs_inode_ref_struct.unpack_from(b)
name_offset = _btrfs_inode_ref_struct.size
return BtrfsInodeRef(
index=index,
name=b[name_offset : name_offset + name_len],
)
def _print_inode_ref(
key: BtrfsKey,
raw_data: bytes,
ref: BtrfsInodeRef,
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
print(
f"""\
{indent}index {ref.index} namelen {len(ref.name)} name: {escape_ascii_string(ref.name)}
""",
end="",
file=file,
)
_register_item_handler(
BtrfsType.INODE_REF,
_parse_item_from_bytes(BtrfsInodeRef.from_bytes),
_print_inode_ref,
)
_btrfs_inode_extref_struct = struct.Struct("<QQH")
class BtrfsInodeExtref(NamedTuple):
parent_objectid: int
index: int # type: ignore[assignment] # Conflicts with tuple.index()
name: bytes
# TODO: test
@staticmethod
def from_bytes(b: bytes) -> "BtrfsInodeExtref":
parent_objectid, index, name_len = _btrfs_inode_extref_struct.unpack_from(b)
name_offset = _btrfs_inode_extref_struct.size
return BtrfsInodeExtref(
parent_objectid=parent_objectid,
index=index,
name=b[name_offset : name_offset + name_len],
)
def _parse_inode_extref_array(
key: BtrfsKey, raw_data: bytes
) -> Sequence[BtrfsInodeExtref]:
view = memoryview(raw_data)
offset = 0
refs = []
while offset < len(raw_data):
extref = BtrfsInodeExtref.from_bytes(view[offset:])
refs.append(extref)
offset += _btrfs_inode_extref_struct.size + len(extref.name)
return refs
def _print_inode_extref_array(
key: BtrfsKey,
raw_data: bytes,
refs: Sequence[BtrfsInodeExtref],
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
for ref in refs:
print(
f"""\
{indent}index {ref.index} parent {ref.parent_objectid} namelen {len(ref.name)} name {escape_ascii_string(ref.name)}
""",
end="",
file=file,
)
_register_item_handler(
BtrfsType.INODE_EXTREF,
_parse_inode_extref_array,
_print_inode_extref_array,
)
class BtrfsFileType(_BtrfsEnum):
FILE = 1
DIR = 2
CHRDEV = 3
BLKDEV = 4
FIFO = 5
SOCK = 6
SYMLINK = 7
XATTR = 8
_btrfs_dir_item_struct = struct.Struct("<QBQQHHB")
class BtrfsDirItem(
NamedTuple(
"BtrfsDirItem",
[
("location", BtrfsKey),
("transid", int),
("type", Union[BtrfsFileType, int]),
("name", bytes),
("data", bytes),
],
)
):
def __new__(
cls, location: BtrfsKey, transid: int, type: int, name: bytes, data: bytes
) -> "Self":
return super().__new__(
cls,
location=location,
transid=transid,
type=_try_cast_enum(BtrfsFileType, type),
name=name,
data=data,
)
@classmethod
def _make(cls, iterable: Iterable[Any]) -> "Self":
return cls.__new__(cls, *iterable)
@staticmethod
def from_bytes(b: bytes) -> "BtrfsDirItem":
(
location_objectid,
location_type,
location_offset,
transid,
data_len,
name_len,
type,
) = _btrfs_dir_item_struct.unpack_from(b)
name_offset = _btrfs_dir_item_struct.size
data_offset = name_offset + name_len
return BtrfsDirItem(
location=BtrfsKey(location_objectid, location_type, location_offset),
transid=transid,
type=type,
name=b[name_offset:data_offset],
data=b[data_offset : data_offset + data_len],
)
def _parse_dir_item_array(key: BtrfsKey, raw_data: bytes) -> Sequence[BtrfsDirItem]:
view = memoryview(raw_data)
offset = 0
items = []
while offset < len(raw_data):
di = BtrfsDirItem.from_bytes(view[offset:])
items.append(di)
offset += _btrfs_dir_item_struct.size + len(di.name) + len(di.data)
return items
def _print_dir_item(
key: BtrfsKey,
raw_data: bytes,
item: BtrfsDirItem,
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
type = (
item.type._name_
if isinstance(item.type, BtrfsFileType)
else f"DIR_ITEM.{item.type}"
)
# btrfs-progs as of v6.8.1 doesn't escape any strings.
print(
f"""\
{indent}location key {item.location} type {type}
{indent}transid {item.transid} data_len {len(item.data)} name_len {len(item.name)}
{indent}name: {escape_ascii_string(item.name)}
""",
end="",
file=file,
)
if item.data:
print(f"{indent}data {escape_ascii_string(item.data)}", file=file)
def _print_dir_item_array(
key: BtrfsKey,
raw_data: bytes,
items: Sequence[BtrfsDirItem],
indent: str,
file: "Optional[SupportsWrite[str]]",
) -> None:
for item in items:
_print_dir_item(key, raw_data, item, indent, file)
_register_item_handler(
BtrfsType.XATTR_ITEM,
_parse_dir_item_array,
_print_dir_item_array,
)
_register_item_handler(
BtrfsType.DIR_ITEM,
_parse_dir_item_array,
_print_dir_item_array,
)
_register_item_handler(
BtrfsType.DIR_INDEX,
_parse_dir_item_array,
_print_dir_item_array,
)
# TODO: VERITY_DESC_ITEM handler
# TODO: VERITY_MERKLE_ITEM handler
_register_item_handler(
BtrfsType.ORPHAN_ITEM,
_parse_empty_item,
_print_empty_item("orphan item"),
)
# TODO: DIR_LOG_ITEM handler
# TODO: DIR_LOG_INDEX handler
class BtrfsCompressionType(_BtrfsEnum):
NONE = 0
ZLIB = 1
LZO = 2
ZSTD = 3
_compression_type_to_str_dict: Dict[int, str] = {
BtrfsCompressionType.NONE: "none",
BtrfsCompressionType.ZLIB: "zlib",
BtrfsCompressionType.LZO: "lzo",
BtrfsCompressionType.ZSTD: "zstd",
}
def _compress_type_to_str(compression: int) -> str:
try:
return _compression_type_to_str_dict[compression]
except KeyError:
return f"UNKNOWN.{int(compression)}"
class BtrfsFileExtentType(_BtrfsEnum):
INLINE = 0
REG = 1
PREALLOC = 2
_file_extent_type_to_str_dict: Dict[int, str] = {
BtrfsFileExtentType.INLINE: "inline",
BtrfsFileExtentType.REG: "regular",
BtrfsFileExtentType.PREALLOC: "prealloc",
}
def _file_extent_type_to_str(type: int) -> str:
return _file_extent_type_to_str_dict.get(type, "unknown")
class BtrfsFileExtentItem(
NamedTuple(
"BtrfsFileExtentItem",
[
("generation", int),
("ram_bytes", int),
("compression", Union[BtrfsCompressionType, int]),
("encryption", int),
("other_encoding", int),
("type", Union[BtrfsFileExtentType, int]),
("disk_bytenr", int),
("disk_num_bytes", int),
("offset", int),
("num_bytes", int),
],
)
):
def __new__(
cls,
generation: int,
ram_bytes: int,
compression: int,
encryption: int,
other_encoding: int,
type: int,
disk_bytenr: int,
disk_num_bytes: int,
offset: int,
num_bytes: int,
) -> "Self":
return super().__new__(
cls,
generation=generation,
ram_bytes=ram_bytes,
compression=_try_cast_enum(BtrfsCompressionType, compression),
encryption=encryption,
other_encoding=other_encoding,
type=_try_cast_enum(BtrfsFileExtentType, type),
disk_bytenr=disk_bytenr,
disk_num_bytes=disk_num_bytes,
offset=offset,
num_bytes=num_bytes,
)
@classmethod
def _make(cls, iterable: Iterable[Any]) -> "Self":
return cls.__new__(cls, *iterable)
class BtrfsInlineFileExtentItem(
NamedTuple(
"BtrfsInlineFileExtentItem",
[
("generation", int),
("ram_bytes", int),
("compression", Union[BtrfsCompressionType, int]),
("encryption", int),
("other_encoding", int),
("type", Union[BtrfsFileExtentType, int]),
("data", bytes),
],
)
):
def __new__(
cls,
generation: int,
ram_bytes: int,
compression: int,
encryption: int,
other_encoding: int,
type: int,
data: bytes,
) -> "Self":
return super().__new__(
cls,
generation=generation,
ram_bytes=ram_bytes,
compression=_try_cast_enum(BtrfsCompressionType, compression),
encryption=encryption,
other_encoding=other_encoding,
type=_try_cast_enum(BtrfsFileExtentType, type),
data=data,
)
@classmethod
def _make(cls, iterable: Iterable[Any]) -> "Self":
return cls.__new__(cls, *iterable)
_btrfs_file_extent_item_common_struct = struct.Struct("<QQBBHB")
_btrfs_file_extent_item_not_inline_struct = struct.Struct("<4Q")