Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

APFS: the on-disk format, a UDIF unpacker, and a reader checked against the image

vcvkk385f998dcde6
diff --git a/tools/apfs/apfs.py b/tools/apfs/apfs.py
new file mode 100755
index 0000000..8332988
--- /dev/null
+++ b/tools/apfs/apfs.py
@@ -0,0 +1,1203 @@
+#!/usr/bin/env python3
+# Read an APFS container: the volumes in it, their directory trees, and the contents of
+# files -- including the ones stored compressed. Read only, and it never writes to the
+# image.
+#
+# The on-disk structures are described in bsd/miscfs/apfs/apfs_format.h (exported to
+# xnu/files/); the layout this file assumes is checked against that header by
+# tools/apfs/run-tests.sh, so the two cannot drift apart silently.
+#
+# usage: apfs.py info IMAGE
+# apfs.py ls IMAGE [PATH]
+# apfs.py tree IMAGE [PATH]
+# apfs.py cat IMAGE PATH
+# apfs.py stat IMAGE PATH
+# apfs.py census IMAGE (walk everything, count what is in there)
+# IMAGE is a raw APFS partition, or a .dmg -- the APFS partition inside it is used.
+# -v VOLUME picks a volume by name or index (default: the first one with a root directory).
+
+import os
+import struct
+import sys
+import zlib
+
+BLOCK0 = 0
+
+# ---------------------------------------------------------------- object header
+
+OBJ_HDR_SIZE = 32
+OBJECT_TYPE_MASK = 0x0000FFFF
+OBJ_STORAGETYPE_MASK = 0xC0000000
+OBJ_VIRTUAL = 0x00000000
+OBJ_EPHEMERAL = 0x80000000
+OBJ_PHYSICAL = 0x40000000
+OBJ_NOHEADER = 0x20000000
+
+OBJECT_TYPE_NX_SUPERBLOCK = 0x01
+OBJECT_TYPE_BTREE = 0x02
+OBJECT_TYPE_BTREE_NODE = 0x03
+OBJECT_TYPE_OMAP = 0x0B
+OBJECT_TYPE_CHECKPOINT_MAP = 0x0C
+OBJECT_TYPE_FS = 0x0D
+OBJECT_TYPE_FSTREE = 0x0E
+
+NX_MAGIC = b"NXSB"
+APFS_MAGIC = b"APSB"
+
+OID_NX_SUPERBLOCK = 1
+
+# ---------------------------------------------------------------- b-tree
+
+BTNODE_ROOT = 0x0001
+BTNODE_LEAF = 0x0002
+BTNODE_FIXED_KV_SIZE = 0x0004
+BTNODE_HASHED = 0x0008
+BTNODE_NOHEADER = 0x0010
+
+BTREE_PHYSICAL = 0x00000010
+
+BTREE_NODE_DATA_OFF = 56 # where btn_data starts, i.e. sizeof(btree_node_phys)
+BTREE_INFO_SIZE = 40 # sizeof(btree_info), kept at the end of a root node
+
+# ---------------------------------------------------------------- record kinds
+
+OBJ_ID_MASK = 0x0FFFFFFFFFFFFFFF
+OBJ_TYPE_SHIFT = 60
+
+TYPE_SNAP_METADATA = 1
+TYPE_EXTENT = 2
+TYPE_INODE = 3
+TYPE_XATTR = 4
+TYPE_SIBLING_LINK = 5
+TYPE_DSTREAM_ID = 6
+TYPE_CRYPTO_STATE = 7
+TYPE_FILE_EXTENT = 8
+TYPE_DIR_REC = 9
+TYPE_DIR_STATS = 10
+TYPE_SNAP_NAME = 11
+TYPE_SIBLING_MAP = 12
+TYPE_FILE_INFO = 13
+
+TYPE_NAMES = {
+ 1: "snap_metadata", 2: "extent", 3: "inode", 4: "xattr", 5: "sibling_link",
+ 6: "dstream_id", 7: "crypto_state", 8: "file_extent", 9: "dir_rec",
+ 10: "dir_stats", 11: "snap_name", 12: "sibling_map", 13: "file_info",
+}
+
+ROOT_DIR_INO_NUM = 2
+
+J_DREC_LEN_MASK = 0x000003FF
+J_DREC_HASH_SHIFT = 10
+DREC_TYPE_MASK = 0x000F
+
+J_FILE_EXTENT_LEN_MASK = 0x00FFFFFFFFFFFFFF
+
+XATTR_DATA_STREAM = 0x01
+XATTR_DATA_EMBEDDED = 0x02
+
+INO_EXT_TYPE_NAME = 4
+INO_EXT_TYPE_DSTREAM = 8
+INO_EXT_TYPE_SPARSE_BYTES = 13
+INO_EXT_TYPE_RDEV = 14
+
+INODE_IS_SPARSE = 0x00000200
+INODE_HAS_UNCOMPRESSED_SIZE = 0x00040000
+
+S_IFMT = 0o170000
+S_IFIFO, S_IFCHR, S_IFDIR, S_IFBLK = 0o010000, 0o020000, 0o040000, 0o060000
+S_IFREG, S_IFLNK, S_IFSOCK = 0o100000, 0o120000, 0o140000
+
+SYMLINK_EA_NAME = "com.apple.fs.symlink"
+DECMPFS_XATTR_NAME = "com.apple.decmpfs"
+RSRC_FORK_XATTR_NAME = "com.apple.ResourceFork"
+
+DECMPFS_MAGIC = 0x636D7066
+DECMPFS_BLOCK_SIZE = 65536
+
+INCOMPAT_CASE_INSENSITIVE = 0x01
+INCOMPAT_NORMALIZATION_INSENSITIVE = 0x08
+INCOMPAT_SEALED_VOLUME = 0x20
+
+
+class ApfsError(Exception):
+ pass
+
+
+# ---------------------------------------------------------------- checksum
+
+def _fletcher64_py(buf):
+ mod = 0xFFFFFFFF
+ words = struct.unpack("<%dI" % (len(buf) // 4), buf)
+ sum1 = sum2 = 0
+ for w in words:
+ sum1 += w
+ sum2 += sum1
+ sum1 %= mod
+ sum2 %= mod
+ c1 = mod - ((sum1 + sum2) % mod)
+ c2 = mod - ((sum1 + c1) % mod)
+ return (c2 << 32) | c1
+
+
+def _make_fletcher64():
+ """numpy if it is there -- this runs over every metadata block we touch."""
+ try:
+ import numpy as np
+ except ImportError:
+ return _fletcher64_py
+
+ def f(buf):
+ mod = 0xFFFFFFFF
+ w = np.frombuffer(buf, dtype="<u4").astype(np.uint64)
+ n = len(w)
+ # sum1 = sum(w), sum2 = sum((n-i) * w[i]) -- both exact in 64 bits for a block
+ sum1 = int(w.sum())
+ weights = np.arange(n, 0, -1, dtype=np.uint64)
+ sum2 = int((w * weights).sum())
+ sum1 %= mod
+ sum2 %= mod
+ c1 = mod - ((sum1 + sum2) % mod)
+ c2 = mod - ((sum1 + c1) % mod)
+ return (c2 << 32) | c1
+ return f
+
+
+fletcher64 = _make_fletcher64()
+
+
+def checksum_ok(block):
+ """An object block carries its Fletcher-64 in the first eight bytes."""
+ if len(block) % 4:
+ return False
+ return fletcher64(block[8:]) == int.from_bytes(block[:8], "little")
+
+
+# ---------------------------------------------------------------- the image
+
+class RawImage:
+ def __init__(self, path):
+ self.fd = os.open(path, os.O_RDONLY)
+ self.size = os.lseek(self.fd, 0, os.SEEK_END)
+ self.path = path
+
+ def read(self, off, length):
+ return os.pread(self.fd, length, off)
+
+ def close(self):
+ os.close(self.fd)
+
+
+class DmgImage:
+ """A .dmg, read through its APFS partition so offsets look like a raw partition."""
+
+ def __init__(self, path):
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from dmg import Dmg, read_gpt, APFS_PART_TYPE
+ self.dmg = Dmg(path)
+ parts = [p for p in read_gpt(self.dmg) if p.type_guid == APFS_PART_TYPE]
+ if not parts:
+ raise ApfsError("%s: no APFS partition in the image" % path)
+ self.base = parts[0].offset
+ self.size = parts[0].length
+ self.path = path
+
+ def read(self, off, length):
+ return self.dmg.read(self.base + off, length)
+
+ def close(self):
+ pass
+
+
+def open_image(path):
+ with open(path, "rb") as f:
+ f.seek(0, 2)
+ size = f.tell()
+ if size > 512:
+ f.seek(size - 512)
+ if f.read(4) == b"koly":
+ return DmgImage(path)
+ return RawImage(path)
+
+
+# ---------------------------------------------------------------- blocks
+
+class Blocks:
+ """Block-sized reads with a small cache, and the checksum check on every object."""
+
+ def __init__(self, image, block_size, cache_blocks=4096):
+ self.image = image
+ self.block_size = block_size
+ self.cache = {}
+ self.cache_limit = cache_blocks
+ self.reads = 0
+ self.cache_hits = 0
+ self.cksum_checked = 0
+ self.cksum_bad = 0
+
+ def raw(self, addr, count=1):
+ return self.image.read(addr * self.block_size, count * self.block_size)
+
+ def get(self, addr, verify=True):
+ b = self.cache.get(addr)
+ if b is not None:
+ self.cache_hits += 1
+ return b
+ b = self.raw(addr)
+ if len(b) != self.block_size:
+ raise ApfsError("short read at block %d" % addr)
+ if verify:
+ self.cksum_checked += 1
+ if not checksum_ok(b):
+ self.cksum_bad += 1
+ raise ApfsError("block %d: bad Fletcher-64 checksum" % addr)
+ if len(self.cache) >= self.cache_limit:
+ # cheap enough: drop a chunk of the cache rather than track an LRU order
+ for k in list(self.cache)[:self.cache_limit // 4]:
+ del self.cache[k]
+ self.cache[addr] = b
+ return b
+
+
+def obj_hdr(block):
+ oid, xid, otype, osub = struct.unpack_from("<QQII", block, 8)
+ return oid, xid, otype, osub
+
+
+# ---------------------------------------------------------------- b-tree
+
+class Node:
+ __slots__ = ("addr", "blk", "flags", "level", "nkeys", "toc_off", "toc_len",
+ "key_base", "val_end", "fixed", "key_size", "val_size")
+
+ def __init__(self, addr, blk, block_size, key_size=0, val_size=0):
+ self.addr = addr
+ self.blk = blk
+ (self.flags, self.level, self.nkeys) = struct.unpack_from("<HHI", blk, 32)
+ ts_off, ts_len = struct.unpack_from("<HH", blk, 40)
+ self.toc_off = BTREE_NODE_DATA_OFF + ts_off
+ self.toc_len = ts_len
+ # keys start right after the table of contents, values end at the end of the
+ # block -- except in a root node, where btree_info sits in the last bytes
+ self.key_base = self.toc_off + self.toc_len
+ self.val_end = len(blk) - (BTREE_INFO_SIZE if (self.flags & BTNODE_ROOT) else 0)
+ self.fixed = bool(self.flags & BTNODE_FIXED_KV_SIZE)
+ self.key_size = key_size
+ self.val_size = val_size
+
+ @property
+ def is_leaf(self):
+ return bool(self.flags & BTNODE_LEAF)
+
+ def entry(self, i):
+ """(key bytes, value bytes) of entry i."""
+ if self.fixed:
+ koff, voff = struct.unpack_from("<HH", self.blk, self.toc_off + 4 * i)
+ klen = self.key_size
+ vlen = self.val_size if self.is_leaf else 8
+ else:
+ koff, klen, voff, vlen = struct.unpack_from(
+ "<HHHH", self.blk, self.toc_off + 8 * i)
+ k = self.blk[self.key_base + koff:self.key_base + koff + klen]
+ if voff == 0xFFFF: # a ghost: a key with no value
+ return k, b""
+ v = self.blk[self.val_end - voff:self.val_end - voff + vlen]
+ return k, v
+
+ def key(self, i):
+ if self.fixed:
+ koff = struct.unpack_from("<H", self.blk, self.toc_off + 4 * i)[0]
+ klen = self.key_size
+ else:
+ koff, klen = struct.unpack_from("<HH", self.blk, self.toc_off + 8 * i)
+ return self.blk[self.key_base + koff:self.key_base + koff + klen]
+
+ def child_oid(self, i):
+ _k, v = self.entry(i)
+ return struct.unpack_from("<Q", v, 0)[0]
+
+
+class Btree:
+ """
+ One B-tree. A tree is either physical -- a node's identifier is its block address --
+ or virtual, and then identifiers are resolved through an object map.
+ """
+
+ def __init__(self, blocks, root_oid, resolve=None, name="btree"):
+ self.blocks = blocks
+ self.name = name
+ self.resolve = resolve
+ self.root_addr = self._addr(root_oid, physical_hint=True)
+ rb = blocks.get(self.root_addr)
+ (bt_flags, bt_node_size, bt_key_size, bt_val_size) = struct.unpack_from(
+ "<IIII", rb, len(rb) - BTREE_INFO_SIZE)
+ self.bt_flags = bt_flags
+ self.node_size = bt_node_size
+ self.key_size = bt_key_size
+ self.val_size = bt_val_size
+ (self.longest_key, self.longest_val, self.key_count, self.node_count) = \
+ struct.unpack_from("<IIQQ", rb, len(rb) - BTREE_INFO_SIZE + 16)
+ self.physical = bool(bt_flags & BTREE_PHYSICAL)
+ self.root = Node(self.root_addr, rb, blocks.block_size, bt_key_size, bt_val_size)
+ self.nodes_read = 0
+
+ def _addr(self, oid, physical_hint=False):
+ if physical_hint and self.resolve is None:
+ return oid
+ if self.resolve is None:
+ return oid
+ if getattr(self, "physical", None):
+ return oid
+ return self.resolve(oid)
+
+ def node(self, oid):
+ addr = oid if (self.physical or self.resolve is None) else self.resolve(oid)
+ blk = self.blocks.get(addr)
+ self.nodes_read += 1
+ return Node(addr, blk, self.blocks.block_size, self.key_size, self.val_size)
+
+ def child(self, node, i):
+ return self.node(node.child_oid(i))
+
+ def iter_from(self, less):
+ """
+ Every entry from the first key for which less(key) is false, in key order.
+ `less` says whether a key sorts before the point we want to start at; passing
+ a function that is always false walks the whole tree.
+ """
+ path = []
+ node = self.root
+ while not node.is_leaf:
+ i = 0
+ for j in range(node.nkeys):
+ if less(node.key(j)):
+ i = j
+ else:
+ break
+ path.append((node, i))
+ node = self.child(node, i)
+ i = 0
+ while i < node.nkeys and less(node.key(i)):
+ i += 1
+ while True:
+ while i < node.nkeys:
+ yield node.entry(i)
+ i += 1
+ # done with this leaf: step the path to the next one
+ while path and path[-1][1] + 1 >= path[-1][0].nkeys:
+ path.pop()
+ if not path:
+ return
+ pnode, pi = path[-1]
+ path[-1] = (pnode, pi + 1)
+ node = self.child(pnode, pi + 1)
+ while not node.is_leaf:
+ path.append((node, 0))
+ node = self.child(node, 0)
+ i = 0
+
+ def iter_all(self):
+ return self.iter_from(lambda k: False)
+
+
+# ---------------------------------------------------------------- object map
+
+class Omap:
+ """An object map: (object identifier, transaction) -> block address."""
+
+ def __init__(self, blocks, omap_addr):
+ blk = blocks.get(omap_addr)
+ oid, xid, otype, _sub = obj_hdr(blk)
+ if (otype & OBJECT_TYPE_MASK) != OBJECT_TYPE_OMAP:
+ raise ApfsError("block %d is not an object map (type 0x%x)" % (omap_addr, otype))
+ (self.flags, self.snap_count, self.tree_type, self.snapshot_tree_type) = \
+ struct.unpack_from("<IIII", blk, 32)
+ (self.tree_oid, self.snapshot_tree_oid) = struct.unpack_from("<QQ", blk, 48)
+ self.tree = Btree(blocks, self.tree_oid, name="omap")
+ self.cache = {}
+
+ def lookup(self, oid, xid=None):
+ """
+ Where an object lives: the newest version at or before xid (the newest of all, if
+ xid is None). The map is keyed by (identifier, transaction), so the versions of
+ one object are a run; we take the last one that is not newer than we asked for.
+ """
+ hit = self.cache.get(oid)
+ if hit is not None:
+ return hit
+ want_xid = (1 << 64) - 1 if xid is None else xid
+
+ def less(k):
+ o, _x = struct.unpack_from("<QQ", k, 0)
+ return o < oid
+
+ best = None
+ for k, v in self.tree.iter_from(less):
+ o, x = struct.unpack_from("<QQ", k, 0)
+ if o != oid:
+ break
+ if x <= want_xid:
+ best = v
+ if best is None:
+ raise ApfsError("object %d is not in the object map" % oid)
+ _flags, _size, paddr = struct.unpack_from("<IIq", best, 0)
+ self.cache[oid] = paddr
+ return paddr
+
+ def resolver(self):
+ return lambda oid: self.lookup(oid)
+
+
+# ---------------------------------------------------------------- container
+
+class Container:
+ def __init__(self, path):
+ self.image = open_image(path)
+ self.path = path
+ head = self.image.read(0, 4096)
+ if head[32:36] != NX_MAGIC:
+ raise ApfsError("%s: no NXSB magic at offset 32 -- not an APFS container" % path)
+ block_size = struct.unpack_from("<I", head, 36)[0]
+ if not (4096 <= block_size <= 65536) or (block_size & (block_size - 1)):
+ raise ApfsError("%s: block size %d makes no sense" % (path, block_size))
+ self.blocks = Blocks(self.image, block_size)
+ self.block_size = block_size
+ self.sb = self._newest_superblock()
+ self.nx = self._parse_nx(self.sb)
+ self.omap = Omap(self.blocks, self.nx["omap_oid"])
+
+ def _parse_nx(self, blk):
+ d = {}
+ (d["magic"], d["block_size"], d["block_count"]) = struct.unpack_from("<IIQ", blk, 32)
+ (d["features"], d["ro_compat"], d["incompat"]) = struct.unpack_from("<QQQ", blk, 48)
+ d["uuid"] = blk[72:88]
+ (d["next_oid"], d["next_xid"]) = struct.unpack_from("<QQ", blk, 88)
+ (d["xp_desc_blocks"], d["xp_data_blocks"]) = struct.unpack_from("<II", blk, 104)
+ (d["xp_desc_base"], d["xp_data_base"]) = struct.unpack_from("<qq", blk, 112)
+ (d["xp_desc_next"], d["xp_data_next"], d["xp_desc_index"], d["xp_desc_len"],
+ d["xp_data_index"], d["xp_data_len"]) = struct.unpack_from("<IIIIII", blk, 128)
+ (d["spaceman_oid"], d["omap_oid"], d["reaper_oid"]) = struct.unpack_from("<QQQ", blk, 152)
+ d["max_file_systems"] = struct.unpack_from("<I", blk, 180)[0]
+ d["fs_oid"] = list(struct.unpack_from("<100Q", blk, 184))
+ _, _, _, d["xid"] = obj_hdr(blk)
+ return d
+
+ def _newest_superblock(self):
+ """
+ Block zero's copy can be stale. The live container superblock is the one with the
+ largest transaction identifier in the checkpoint descriptor area, so read block
+ zero only to find that area, then search it.
+ """
+ b0 = self.blocks.get(BLOCK0, verify=False)
+ if not checksum_ok(b0):
+ raise ApfsError("the container superblock in block 0 fails its checksum")
+ base = struct.unpack_from("<q", b0, 112)[0]
+ count = struct.unpack_from("<I", b0, 104)[0]
+ best, best_xid = b0, obj_hdr(b0)[1]
+ self.checkpoints_seen = 0
+ for i in range(count):
+ blk = self.blocks.raw(base + i)
+ if len(blk) != self.block_size or not checksum_ok(blk):
+ continue
+ oid, xid, otype, _sub = obj_hdr(blk)
+ if (otype & OBJECT_TYPE_MASK) != OBJECT_TYPE_NX_SUPERBLOCK:
+ continue
+ if blk[32:36] != NX_MAGIC or oid != OID_NX_SUPERBLOCK:
+ continue
+ self.checkpoints_seen += 1
+ if xid > best_xid:
+ best, best_xid = blk, xid
+ self.xid = best_xid
+ return best
+
+ def volumes(self):
+ out = []
+ for i, oid in enumerate(self.nx["fs_oid"]):
+ if not oid:
+ continue
+ try:
+ addr = self.omap.lookup(oid, self.xid)
+ blk = self.blocks.get(addr)
+ except ApfsError:
+ continue
+ if blk[32:36] != APFS_MAGIC:
+ continue
+ out.append(Volume(self, i, oid, addr, blk))
+ return out
+
+ def close(self):
+ self.image.close()
+
+
+# ---------------------------------------------------------------- volume
+
+class Volume:
+ def __init__(self, container, index, oid, addr, blk):
+ self.c = container
+ self.index = index
+ self.oid = oid
+ self.addr = addr
+ b = blk
+ (self.magic, self.fs_index) = struct.unpack_from("<II", b, 32)
+ (self.features, self.ro_compat, self.incompat) = struct.unpack_from("<QQQ", b, 40)
+ self.unmount_time = struct.unpack_from("<Q", b, 64)[0]
+ (self.reserve_blocks, self.quota_blocks, self.alloc_count) = \
+ struct.unpack_from("<QQQ", b, 72)
+ # apfs_meta_crypto is 20 bytes, packed, right after apfs_fs_alloc_count
+ off = 96 + 20
+ (self.root_tree_type, self.extentref_tree_type, self.snap_meta_tree_type) = \
+ struct.unpack_from("<III", b, off)
+ off += 12
+ (self.omap_oid, self.root_tree_oid, self.extentref_tree_oid,
+ self.snap_meta_tree_oid) = struct.unpack_from("<QQQQ", b, off)
+ off += 32
+ (self.revert_to_xid, self.revert_to_sblock_oid) = struct.unpack_from("<QQ", b, off)
+ off += 16
+ self.next_obj_id = struct.unpack_from("<Q", b, off)[0]
+ off += 8
+ (self.num_files, self.num_directories, self.num_symlinks,
+ self.num_other, self.num_snapshots) = struct.unpack_from("<QQQQQ", b, off)
+ off += 40
+ (self.blocks_alloced, self.blocks_freed) = struct.unpack_from("<QQ", b, off)
+ off += 16
+ self.vol_uuid = b[off:off + 16]
+ off += 16
+ self.last_mod_time = struct.unpack_from("<Q", b, off)[0]
+ off += 8
+ self.fs_flags = struct.unpack_from("<Q", b, off)[0]
+ off += 8
+ off += 48 * 9 # apfs_formatted_by + apfs_modified_by[8]
+ self.volname = b[off:off + 256].split(b"\0", 1)[0].decode("utf-8", "replace")
+ off += 256
+ self.next_doc_id = struct.unpack_from("<I", b, off)[0]
+ off += 4
+ self.role = struct.unpack_from("<H", b, off)[0]
+ self.xid = obj_hdr(b)[1]
+ self._omap = None
+ self._tree = None
+
+ @property
+ def case_insensitive(self):
+ return bool(self.incompat & INCOMPAT_CASE_INSENSITIVE)
+
+ @property
+ def sealed(self):
+ return bool(self.incompat & INCOMPAT_SEALED_VOLUME)
+
+ @property
+ def omap(self):
+ if self._omap is None:
+ self._omap = Omap(self.c.blocks, self.omap_oid)
+ return self._omap
+
+ @property
+ def tree(self):
+ if self._tree is None:
+ self._tree = Btree(self.c.blocks, self.root_tree_oid,
+ resolve=self.omap.resolver(), name="fstree")
+ return self._tree
+
+ # -------- records
+
+ def records(self, obj_id, rec_type):
+ """
+ Every record of one kind belonging to one object, in key order.
+
+ A file-system tree sorts by object identifier first and record kind second, so the
+ records of one (object, kind) are a contiguous run. That is all the ordering this
+ needs to know -- how keys of the same kind sort among themselves (by name, by hash,
+ by offset) differs per kind and is left to the caller, which just reads the run.
+ """
+ want = (obj_id, rec_type)
+
+ def less(k):
+ v = struct.unpack_from("<Q", k, 0)[0]
+ return (v & OBJ_ID_MASK, v >> OBJ_TYPE_SHIFT) < want
+
+ for k, v in self.tree.iter_from(less):
+ x = struct.unpack_from("<Q", k, 0)[0]
+ if (x & OBJ_ID_MASK, x >> OBJ_TYPE_SHIFT) != want:
+ return
+ yield k, v
+
+ def inode(self, obj_id):
+ for _k, v in self.records(obj_id, TYPE_INODE):
+ return Inode(self, obj_id, v)
+ return None
+
+ def dir_entries(self, obj_id):
+ """(name, file_id, d_type) for each entry of a directory."""
+ out = []
+ for k, v in self.records(obj_id, TYPE_DIR_REC):
+ # iOS volumes use the hashed key: a 32-bit field holding the name length and
+ # a hash of the name, then the name itself
+ nlh = struct.unpack_from("<I", k, 8)[0]
+ name_len = nlh & J_DREC_LEN_MASK
+ name = k[12:12 + name_len].split(b"\0", 1)[0]
+ file_id, _date, flags = struct.unpack_from("<QQH", v, 0)
+ out.append((name.decode("utf-8", "surrogateescape"), file_id,
+ flags & DREC_TYPE_MASK))
+ return out
+
+ def xattrs(self, obj_id):
+ """{name: (flags, xdata bytes)} of one object's extended attributes."""
+ out = {}
+ for k, v in self.records(obj_id, TYPE_XATTR):
+ name_len = struct.unpack_from("<H", k, 8)[0]
+ name = k[10:10 + name_len].split(b"\0", 1)[0].decode("utf-8", "replace")
+ flags, xdata_len = struct.unpack_from("<HH", v, 0)
+ out[name] = (flags, v[4:4 + xdata_len])
+ return out
+
+ def extents(self, stream_id):
+ """(logical offset, length, physical block) for one data stream, in order."""
+ out = []
+ for k, v in self.records(stream_id, TYPE_FILE_EXTENT):
+ logical = struct.unpack_from("<Q", k, 8)[0]
+ len_and_flags, phys, _crypto = struct.unpack_from("<QQQ", v, 0)
+ out.append((logical, len_and_flags & J_FILE_EXTENT_LEN_MASK, phys))
+ out.sort()
+ return out
+
+ # -------- reading a data stream
+
+ def read_stream(self, stream_id, size):
+ """
+ The bytes of a data stream. Gaps between extents, and extents whose physical
+ block is zero, are holes and read as zeros -- that is how a sparse file is stored.
+ """
+ bs = self.c.block_size
+ out = bytearray(size)
+ for logical, length, phys in self.extents(stream_id):
+ if logical >= size:
+ continue
+ n = min(length, size - logical)
+ if phys == 0:
+ continue # a hole; the buffer is already zero
+ nblocks = (length + bs - 1) // bs
+ data = self.c.blocks.raw(phys, nblocks)
+ out[logical:logical + n] = data[:n]
+ return bytes(out)
+
+ def xattr_bytes(self, obj_id, name, xattrs=None):
+ """One attribute's value, whether it is stored inline or in its own stream."""
+ xs = self.xattrs(obj_id) if xattrs is None else xattrs
+ if name not in xs:
+ return None
+ flags, xdata = xs[name]
+ if flags & XATTR_DATA_EMBEDDED:
+ return xdata
+ if flags & XATTR_DATA_STREAM:
+ xattr_obj_id, size = struct.unpack_from("<QQ", xdata, 0)
+ return self.read_stream(xattr_obj_id, size)
+ return xdata
+
+ # -------- paths
+
+ def lookup(self, path):
+ """(object identifier, d_type) for a path, or None. Case folded if the volume is."""
+ oid = ROOT_DIR_INO_NUM
+ dtype = 4
+ for part in [p for p in path.split("/") if p and p != "."]:
+ ents = self.dir_entries(oid)
+ hit = None
+ for name, fid, t in ents:
+ if name == part:
+ hit = (fid, t)
+ break
+ if hit is None and self.case_insensitive:
+ lp = part.lower()
+ for name, fid, t in ents:
+ if name.lower() == lp:
+ hit = (fid, t)
+ break
+ if hit is None:
+ return None
+ oid, dtype = hit
+ return oid, dtype
+
+
+# ---------------------------------------------------------------- inode
+
+def parse_xfields(buf):
+ """The extended fields at the tail of an inode or directory entry: {type: bytes}."""
+ if len(buf) < 4:
+ return {}
+ num, used = struct.unpack_from("<HH", buf, 0)
+ out = {}
+ hdr = 4 + 4 * num
+ if hdr > len(buf):
+ return {}
+ off = hdr
+ for i in range(num):
+ xtype, _xflags, xsize = struct.unpack_from("<BBH", buf, 4 + 4 * i)
+ out[xtype] = buf[off:off + xsize]
+ off += (xsize + 7) & ~7 # each field is padded out to eight bytes
+ return out
+
+
+class Inode:
+ def __init__(self, vol, obj_id, v):
+ self.vol = vol
+ self.obj_id = obj_id
+ (self.parent_id, self.private_id) = struct.unpack_from("<QQ", v, 0)
+ (self.create_time, self.mod_time, self.change_time, self.access_time) = \
+ struct.unpack_from("<QQQQ", v, 16)
+ self.internal_flags = struct.unpack_from("<Q", v, 48)[0]
+ self.nchildren = struct.unpack_from("<i", v, 56)[0]
+ self.nlink = self.nchildren
+ (self.protection_class, self.write_gen, self.bsd_flags) = \
+ struct.unpack_from("<III", v, 60)
+ (self.owner, self.group) = struct.unpack_from("<II", v, 72)
+ (self.mode, _pad) = struct.unpack_from("<HH", v, 80)
+ self.uncompressed_size = struct.unpack_from("<Q", v, 84)[0]
+ self.xf = parse_xfields(v[92:])
+ self._xattrs = None
+ self._dstream = None
+ if INO_EXT_TYPE_DSTREAM in self.xf:
+ d = self.xf[INO_EXT_TYPE_DSTREAM]
+ (size, alloced, _crypto, written, read) = struct.unpack_from("<QQQQQ", d, 0)
+ self._dstream = (size, alloced)
+
+ @property
+ def xattrs(self):
+ if self._xattrs is None:
+ self._xattrs = self.vol.xattrs(self.obj_id)
+ return self._xattrs
+
+ @property
+ def ifmt(self):
+ return self.mode & S_IFMT
+
+ @property
+ def is_dir(self):
+ return self.ifmt == S_IFDIR
+
+ @property
+ def is_reg(self):
+ return self.ifmt == S_IFREG
+
+ @property
+ def is_link(self):
+ return self.ifmt == S_IFLNK
+
+ @property
+ def is_sparse(self):
+ return bool(self.internal_flags & INODE_IS_SPARSE)
+
+ @property
+ def rdev(self):
+ d = self.xf.get(INO_EXT_TYPE_RDEV)
+ return struct.unpack_from("<I", d, 0)[0] if d else 0
+
+ @property
+ def decmpfs(self):
+ """The com.apple.decmpfs attribute's value, or None if the file is not compressed."""
+ return self.vol.xattr_bytes(self.obj_id, DECMPFS_XATTR_NAME, self.xattrs)
+
+ @property
+ def size(self):
+ """The logical size: what stat would report."""
+ hdr = self.decmpfs
+ if hdr is not None and len(hdr) >= 16:
+ magic, _ctype, usize = struct.unpack_from("<IIQ", hdr, 0)
+ if magic == DECMPFS_MAGIC:
+ return usize
+ if self.is_link:
+ t = self.symlink_target_bytes()
+ return len(t) if t is not None else 0
+ if self._dstream:
+ return self._dstream[0]
+ return 0
+
+ def symlink_target_bytes(self):
+ t = self.vol.xattr_bytes(self.obj_id, SYMLINK_EA_NAME, self.xattrs)
+ if t is None:
+ return None
+ return t.split(b"\0", 1)[0]
+
+ def contents(self):
+ """The file's bytes, decompressing them if that is how they are stored."""
+ if self.is_link:
+ return self.symlink_target_bytes() or b""
+ hdr = self.decmpfs
+ if hdr is not None and len(hdr) >= 16 and \
+ struct.unpack_from("<I", hdr, 0)[0] == DECMPFS_MAGIC:
+ return self.decompress(hdr)
+ if self._dstream is None:
+ return b""
+ return self.vol.read_stream(self.private_id, self._dstream[0])
+
+ def decompress(self, hdr):
+ magic, ctype, usize = struct.unpack_from("<IIQ", hdr, 0)
+ attr = hdr[16:]
+ if ctype in (3, 9, 11): # the bytes are in the attribute itself
+ return decmpfs_attr(ctype, attr, usize)
+ if ctype in (4, 10, 12): # the bytes are in the resource fork
+ rsrc = self.vol.xattr_bytes(self.obj_id, RSRC_FORK_XATTR_NAME, self.xattrs)
+ if rsrc is None:
+ raise ApfsError("inode %d: compression type %d but no resource fork"
+ % (self.obj_id, ctype))
+ return decmpfs_rsrc(ctype, rsrc, usize)
+ raise ApfsError("inode %d: unknown decmpfs compression type %d"
+ % (self.obj_id, ctype))
+
+
+def _inflate(buf, out_len):
+ """
+ One zlib stream. A leading 0xff is decmpfs's way of saying "this piece did not
+ compress, the rest is the bytes as they are".
+ """
+ if buf[:1] == b"\xff":
+ return buf[1:1 + out_len]
+ return zlib.decompress(buf)
+
+
+def decmpfs_attr(ctype, attr, usize):
+ """
+ The contents sit in the com.apple.decmpfs attribute itself, right after the header.
+
+ Type 9 means they were stored as they are, with one marker byte in front. All 23947
+ type-9 files in the iOS 16.5 root file system have 0xcc there and exactly usize bytes
+ after it, which is how the marker's length was settled -- the attribute is taken as
+ bare only if it is already exactly usize bytes long.
+ """
+ if ctype == 9:
+ if len(attr) == usize:
+ return attr
+ return attr[1:1 + usize]
+ if ctype == 3:
+ return _inflate(attr, usize)[:usize]
+ if ctype == 11:
+ import lzfse
+ if attr[:1] == b"\xff":
+ return attr[1:1 + usize]
+ return lzfse.decompress(attr)[:usize]
+ raise ApfsError("compression type %d in the attribute is not supported" % ctype)
+
+
+def decmpfs_rsrc(ctype, rsrc, usize):
+ """
+ The contents are in the com.apple.ResourceFork attribute, cut into 64 KB pieces, each
+ compressed on its own.
+
+ The fork is a real HFS-Plus resource fork: sixteen big-endian bytes giving the offset
+ and the length of the resource data and of the resource map. At that data offset sits
+ a four-byte big-endian length, and the piece table starts right after it -- a
+ little-endian count, then an (offset, length) pair per piece, the offsets measured
+ from the start of the table. The table is not at a fixed place: the data offset is
+ 256 in every file here, so the table lands at 260, but it has to be read rather than
+ assumed.
+ """
+ if len(rsrc) < 16:
+ raise ApfsError("resource fork too short (%d bytes)" % len(rsrc))
+ data_off, _map_off, _data_len, _map_len = struct.unpack_from(">IIII", rsrc, 0)
+ base = data_off + 4
+ if base + 4 > len(rsrc):
+ raise ApfsError("resource fork: data offset %d is past the end of the fork "
+ "(%d bytes)" % (data_off, len(rsrc)))
+ nblocks = struct.unpack_from("<I", rsrc, base)[0]
+ want = (usize + DECMPFS_BLOCK_SIZE - 1) // DECMPFS_BLOCK_SIZE
+ if nblocks != want:
+ raise ApfsError("resource fork says %d pieces, %d bytes needs %d"
+ % (nblocks, usize, want))
+ out = bytearray()
+ for i in range(nblocks):
+ off, length = struct.unpack_from("<II", rsrc, base + 4 + 8 * i)
+ piece = rsrc[base + off:base + off + length]
+ n = min(DECMPFS_BLOCK_SIZE, usize - len(out))
+ if ctype == 4:
+ out += _inflate(piece, n)[:n]
+ elif ctype == 10:
+ out += piece[:n]
+ elif ctype == 12:
+ import lzfse
+ out += (piece[1:1 + n] if piece[:1] == b"\xff"
+ else lzfse.decompress(piece)[:n])
+ else:
+ raise ApfsError("compression type %d in the resource fork is not supported"
+ % ctype)
+ if len(out) != usize:
+ raise ApfsError("decompressed %d bytes, the header says %d" % (len(out), usize))
+ return bytes(out)
+
+
+# ---------------------------------------------------------------- walking
+
+DT_CHAR = {1: "p", 2: "c", 4: "d", 6: "b", 8: "-", 10: "l", 12: "s", 14: "w"}
+
+
+def walk(vol, oid, path="", depth=0, max_depth=None):
+ """Depth-first over a directory tree, yielding (path, name, file_id, d_type)."""
+ if max_depth is not None and depth > max_depth:
+ return
+ for name, fid, dt in sorted(vol.dir_entries(oid)):
+ p = path + "/" + name
+ yield p, name, fid, dt
+ if dt == 4:
+ yield from walk(vol, fid, p, depth + 1, max_depth)
+
+
+# ---------------------------------------------------------------- commands
+
+def pick_volume(c, want):
+ vols = c.volumes()
+ if not vols:
+ raise ApfsError("no volumes in this container")
+ if want is None:
+ for v in vols:
+ if v.inode(ROOT_DIR_INO_NUM) is not None:
+ return v
+ return vols[0]
+ for v in vols:
+ if v.volname == want or str(v.index) == str(want):
+ return v
+ raise ApfsError("no volume named %r (have: %s)"
+ % (want, ", ".join(v.volname for v in vols)))
+
+
+def cmd_info(path, want):
+ c = Container(path)
+ n = c.nx
+ print("%s: APFS container, block size %d, %d blocks (%.2f GB)"
+ % (path, c.block_size, n["block_count"], n["block_count"] * c.block_size / 1e9))
+ print(" uuid %s" % _uuid(n["uuid"]))
+ print(" newest checkpoint xid %d (%d container superblocks in the descriptor area)"
+ % (c.xid, c.checkpoints_seen))
+ print(" checkpoint desc base %d, %d blocks" % (n["xp_desc_base"], n["xp_desc_blocks"]))
+ print(" container omap block %d" % n["omap_oid"])
+ print(" features 0x%x ro-compat 0x%x incompatible 0x%x"
+ % (n["features"], n["ro_compat"], n["incompat"]))
+ vols = c.volumes()
+ print(" %d volumes:" % len(vols))
+ for v in vols:
+ print(" [%d] %-22s role 0x%04x xid %d" % (v.index, v.volname, v.role, v.xid))
+ print(" files %d dirs %d symlinks %d other %d snapshots %d"
+ % (v.num_files, v.num_directories, v.num_symlinks, v.num_other,
+ v.num_snapshots))
+ print(" incompatible 0x%x%s%s fs flags 0x%x"
+ % (v.incompat,
+ " case-insensitive" if v.case_insensitive else "",
+ " sealed" if v.sealed else "", v.fs_flags))
+ print(" omap block %d root tree oid %d used %d blocks (%.2f GB)"
+ % (v.omap_oid, v.root_tree_oid, v.alloc_count,
+ v.alloc_count * c.block_size / 1e9))
+ v = pick_volume(c, want)
+ t = v.tree
+ print(" volume %r file-system tree: %d records, %d nodes, flags 0x%x, "
+ "longest key %d, longest value %d"
+ % (v.volname, t.key_count, t.node_count, t.bt_flags, t.longest_key,
+ t.longest_val))
+ print(" blocks read %d, cache hits %d, checksums verified %d, bad %d"
+ % (c.blocks.cksum_checked, c.blocks.cache_hits, c.blocks.cksum_checked,
+ c.blocks.cksum_bad))
+ c.close()
+
+
+def _uuid(b):
+ h = b.hex()
+ return "%s-%s-%s-%s-%s" % (h[0:8], h[8:12], h[12:16], h[16:20], h[20:32])
+
+
+def cmd_ls(path, where, want):
+ c = Container(path)
+ v = pick_volume(c, want)
+ hit = v.lookup(where)
+ if hit is None:
+ raise ApfsError("%s: no such path on volume %r" % (where, v.volname))
+ oid, dt = hit
+ if dt != 4:
+ _print_one(v, where.rsplit("/", 1)[-1] or "/", oid)
+ c.close()
+ return
+ for name, fid, t in sorted(v.dir_entries(oid)):
+ _print_one(v, name, fid)
+ c.close()
+
+
+def _print_one(v, name, fid):
+ ino = v.inode(fid)
+ if ino is None:
+ print("? %20s %s (no inode record)" % ("", name))
+ return
+ kind = DT_CHAR.get({S_IFDIR: 4, S_IFREG: 8, S_IFLNK: 10, S_IFIFO: 1, S_IFCHR: 2,
+ S_IFBLK: 6, S_IFSOCK: 12}.get(ino.ifmt, 0), "?")
+ extra = ""
+ if ino.is_link:
+ extra = " -> " + (ino.symlink_target_bytes() or b"").decode("utf-8", "replace")
+ cmp_ = ""
+ h = ino.decmpfs
+ if h is not None and len(h) >= 16:
+ cmp_ = " [decmpfs %d]" % struct.unpack_from("<I", h, 4)[0]
+ if ino.is_sparse:
+ cmp_ += " [sparse]"
+ print("%s%s %4d:%-4d %12d %-8d %s%s%s"
+ % (kind, _modestr(ino.mode), ino.owner, ino.group, ino.size, fid, name,
+ extra, cmp_))
+
+
+def _modestr(mode):
+ s = ""
+ for who in (6, 3, 0):
+ s += "r" if mode & (0o4 << who) else "-"
+ s += "w" if mode & (0o2 << who) else "-"
+ s += "x" if mode & (0o1 << who) else "-"
+ return s
+
+
+def cmd_tree(path, where, want):
+ c = Container(path)
+ v = pick_volume(c, want)
+ hit = v.lookup(where)
+ if hit is None:
+ raise ApfsError("%s: no such path" % where)
+ n = 0
+ for p, _name, _fid, dt in walk(v, hit[0], where.rstrip("/")):
+ print(("%s/" % p) if dt == 4 else p)
+ n += 1
+ print("# %d entries" % n, file=sys.stderr)
+ c.close()
+
+
+def cmd_cat(path, where, want):
+ c = Container(path)
+ v = pick_volume(c, want)
+ hit = v.lookup(where)
+ if hit is None:
+ raise ApfsError("%s: no such path" % where)
+ ino = v.inode(hit[0])
+ sys.stdout.buffer.write(ino.contents())
+ c.close()
+
+
+def cmd_stat(path, where, want):
+ c = Container(path)
+ v = pick_volume(c, want)
+ hit = v.lookup(where)
+ if hit is None:
+ raise ApfsError("%s: no such path" % where)
+ ino = v.inode(hit[0])
+ print("path %s" % where)
+ print("inode %d parent %d private %d" % (ino.obj_id, ino.parent_id,
+ ino.private_id))
+ print("mode %06o (%s) uid %d gid %d" % (ino.mode, _modestr(ino.mode),
+ ino.owner, ino.group))
+ print("size %d" % ino.size)
+ print("nlink/nchildren %d" % ino.nchildren)
+ print("flags internal 0x%x bsd 0x%x%s" % (ino.internal_flags, ino.bsd_flags,
+ " sparse" if ino.is_sparse else ""))
+ if ino._dstream:
+ print("dstream size %d allocated %d" % ino._dstream)
+ h = ino.decmpfs
+ if h is not None and len(h) >= 16:
+ magic, ctype, usize = struct.unpack_from("<IIQ", h, 0)
+ print("decmpfs type %d uncompressed %d attribute %d bytes"
+ % (ctype, usize, len(h)))
+ xs = ino.xattrs
+ if xs:
+ print("xattrs %s" % ", ".join("%s(%d,flags 0x%x)" % (k, len(d), f)
+ for k, (f, d) in sorted(xs.items())))
+ ex = v.extents(ino.private_id)
+ if ex:
+ print("extents %d:" % len(ex))
+ for logical, length, phys in ex[:16]:
+ print(" logical %12d len %9d block %d%s"
+ % (logical, length, phys, " (hole)" if phys == 0 else ""))
+ if len(ex) > 16:
+ print(" ... %d more" % (len(ex) - 16))
+ if ino.is_link:
+ print("symlink -> %s" % (ino.symlink_target_bytes() or b"").decode(
+ "utf-8", "replace"))
+ c.close()
+
+
+def cmd_census(path, want):
+ """Walk the whole tree and count what is in it: the quickest honest sanity check."""
+ c = Container(path)
+ v = pick_volume(c, want)
+ counts = {}
+ cmp_types = {}
+ total = 0
+ dirs = files = links = other = 0
+ bytes_logical = 0
+ for p, _name, fid, dt in walk(v, ROOT_DIR_INO_NUM):
+ total += 1
+ counts[dt] = counts.get(dt, 0) + 1
+ if dt == 4:
+ dirs += 1
+ continue
+ ino = v.inode(fid)
+ if ino is None:
+ other += 1
+ continue
+ if ino.is_link:
+ links += 1
+ continue
+ if not ino.is_reg:
+ other += 1
+ continue
+ files += 1
+ h = ino.decmpfs
+ if h is not None and len(h) >= 16:
+ ct = struct.unpack_from("<I", h, 4)[0]
+ cmp_types[ct] = cmp_types.get(ct, 0) + 1
+ bytes_logical += ino.size
+ if total % 20000 == 0:
+ sys.stderr.write("\r %d entries..." % total)
+ sys.stderr.flush()
+ sys.stderr.write("\r")
+ print("volume %r: %d directory entries" % (v.volname, total))
+ print(" directories %d regular %d symlinks %d other %d" % (dirs, files, links, other))
+ print(" d_type counts: %s" % ", ".join("%s=%d" % (DT_CHAR.get(k, k), n)
+ for k, n in sorted(counts.items())))
+ print(" logical bytes in regular files: %d (%.2f GB)"
+ % (bytes_logical, bytes_logical / 1e9))
+ print(" decmpfs compression types in use: %s"
+ % (", ".join("type %d: %d files" % (k, n) for k, n in sorted(cmp_types.items()))
+ or "none"))
+ print(" superblock says: files %d, dirs %d, symlinks %d, other %d"
+ % (v.num_files, v.num_directories, v.num_symlinks, v.num_other))
+ print(" blocks: %d checksums verified, %d bad, %d cache hits"
+ % (c.blocks.cksum_checked, c.blocks.cksum_bad, c.blocks.cache_hits))
+ c.close()
+
+
+def main(argv):
+ want = None
+ args = []
+ i = 1
+ while i < len(argv):
+ if argv[i] == "-v" and i + 1 < len(argv):
+ want = argv[i + 1]
+ i += 2
+ continue
+ args.append(argv[i])
+ i += 1
+ if not args:
+ print(__doc__ or "", file=sys.stderr)
+ print("usage: apfs.py {info|ls|tree|cat|stat|census} IMAGE [PATH] [-v VOLUME]",
+ file=sys.stderr)
+ return 2
+ cmd = args[0]
+ try:
+ if cmd == "info":
+ cmd_info(args[1], want)
+ elif cmd == "ls":
+ cmd_ls(args[1], args[2] if len(args) > 2 else "/", want)
+ elif cmd == "tree":
+ cmd_tree(args[1], args[2] if len(args) > 2 else "/", want)
+ elif cmd == "cat":
+ cmd_cat(args[1], args[2], want)
+ elif cmd == "stat":
+ cmd_stat(args[1], args[2], want)
+ elif cmd == "census":
+ cmd_census(args[1], want)
+ else:
+ raise ApfsError("unknown command %r" % cmd)
+ except ApfsError as e:
+ print("apfs.py: %s" % e, file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/tools/apfs/dmg.py b/tools/apfs/dmg.py
new file mode 100755
index 0000000..bd0e58c
--- /dev/null
+++ b/tools/apfs/dmg.py
@@ -0,0 +1,437 @@
+#!/usr/bin/env python3
+# Read a UDIF disk image (.dmg): the block table in its XML property list, and the
+# compressed chunks it points at. Enough of the format to get at what is inside:
+# random reads anywhere in the decompressed image, and a whole-image extract.
+#
+# A UDIF file is laid out back to front: the compressed data comes first, then an XML
+# property list, then a 512-byte trailer ("koly") that says where the plist is. The
+# plist holds one "blkx" resource per partition -- each a "mish" block table whose
+# entries map a run of output sectors to a run of bytes in the file.
+#
+# usage: dmg.py info IMAGE
+# dmg.py extract IMAGE OUT [--part N | --apfs]
+# dmg.py cat IMAGE OFFSET LENGTH (hex dump, for poking at structures)
+
+import base64
+import bz2
+import lzma
+import plistlib
+import struct
+import sys
+import zlib
+
+SECTOR = 512
+
+# chunk types, as they appear in a block table entry
+CHUNK_ZERO = 0x00000000 # a run of zeros, no data in the file
+CHUNK_RAW = 0x00000001 # stored as is
+CHUNK_IGNORE = 0x00000002 # unallocated, reads as zeros
+CHUNK_COMMENT = 0x7FFFFFFE
+CHUNK_ADC = 0x80000004
+CHUNK_ZLIB = 0x80000005
+CHUNK_BZIP2 = 0x80000006
+CHUNK_LZFSE = 0x80000007
+CHUNK_LZMA = 0x80000008
+CHUNK_LAST = 0xFFFFFFFF
+
+CHUNK_NAMES = {
+ CHUNK_ZERO: "zero", CHUNK_RAW: "raw", CHUNK_IGNORE: "ignore",
+ CHUNK_COMMENT: "comment", CHUNK_ADC: "adc", CHUNK_ZLIB: "zlib",
+ CHUNK_BZIP2: "bzip2", CHUNK_LZFSE: "lzfse", CHUNK_LZMA: "lzma",
+ CHUNK_LAST: "last",
+}
+
+
+class Chunk:
+ __slots__ = ("type", "sector", "count", "in_off", "in_len")
+
+ def __init__(self, type_, sector, count, in_off, in_len):
+ self.type = type_
+ self.sector = sector # first output sector, absolute
+ self.count = count # output sectors
+ self.in_off = in_off # byte offset in the file
+ self.in_len = in_len # bytes in the file
+
+ @property
+ def out_off(self):
+ return self.sector * SECTOR
+
+ @property
+ def out_len(self):
+ return self.count * SECTOR
+
+ def __repr__(self):
+ return "<chunk %s out=%d+%d in=%d+%d>" % (
+ CHUNK_NAMES.get(self.type, hex(self.type)),
+ self.out_off, self.out_len, self.in_off, self.in_len)
+
+
+class Blkx:
+ """One block table: the chunks of one partition (or of the whole image)."""
+
+ def __init__(self, name, id_, blob):
+ self.name = name
+ self.id = id_
+ magic, ver, sector, count, data_off, _bufs, _descs = struct.unpack_from(
+ ">4sIQQQII", blob, 0)
+ if magic != b"mish":
+ raise ValueError("block table %r: bad magic %r" % (name, magic))
+ self.version = ver
+ self.sector = sector # where this partition starts in the image
+ self.count = count # its length in sectors
+ nchunks = struct.unpack_from(">I", blob, 0xC8)[0]
+ self.chunks = []
+ off = 0xCC
+ for _ in range(nchunks):
+ t, _comment, csec, ccnt, coff, clen = struct.unpack_from(">IIQQQQ", blob, off)
+ off += 40
+ if t in (CHUNK_LAST, CHUNK_COMMENT):
+ continue
+ # a chunk's sector number is relative to the table, its file offset to data_off
+ self.chunks.append(Chunk(t, sector + csec, ccnt, data_off + coff, clen))
+
+ @property
+ def out_off(self):
+ return self.sector * SECTOR
+
+ @property
+ def out_len(self):
+ return self.count * SECTOR
+
+
+def _adc_decompress(src, out_len):
+ """Apple Data Compression: a byte-oriented LZ with three kinds of opcode."""
+ out = bytearray()
+ i = 0
+ while i < len(src) and len(out) < out_len:
+ b = src[i]
+ if b & 0x80: # literal run, 1..128 bytes
+ n = (b & 0x7F) + 1
+ out += src[i + 1:i + 1 + n]
+ i += 1 + n
+ elif b & 0x40: # long match: 4..67 bytes, distance <= 65535
+ n = (b & 0x3F) + 4
+ dist = (src[i + 1] << 8) | src[i + 2]
+ i += 3
+ for _ in range(n):
+ out.append(out[-dist - 1])
+ else: # short match: 3..10 bytes, distance <= 1023
+ n = ((b & 0x3C) >> 2) + 3
+ dist = ((b & 0x03) << 8) | src[i + 1]
+ i += 2
+ for _ in range(n):
+ out.append(out[-dist - 1])
+ return bytes(out[:out_len])
+
+
+def _lzfse_decompress(src, out_len):
+ try:
+ import lzfse
+ except ImportError:
+ raise SystemExit("dmg.py: this image uses LZFSE chunks; install the python "
+ "'lzfse' module (pip install lzfse)")
+ return lzfse.decompress(src)[:out_len]
+
+
+class Dmg:
+ """A UDIF image, readable at any offset of its decompressed contents."""
+
+ def __init__(self, path):
+ self.path = path
+ self.f = open(path, "rb")
+ self.f.seek(0, 2)
+ self.file_size = self.f.tell()
+ self._read_trailer()
+ self._read_plist()
+ # one cached decompressed chunk: reads walk forward, so this is nearly always a hit
+ self._cache_key = None
+ self._cache_buf = None
+
+ def _read_trailer(self):
+ self.f.seek(self.file_size - 512)
+ k = self.f.read(512)
+ if k[:4] != b"koly":
+ raise ValueError("%s: no UDIF trailer (koly) at the end of the file" % self.path)
+ self.version = struct.unpack_from(">I", k, 4)[0]
+ self.flags = struct.unpack_from(">I", k, 0xC)[0]
+ self.data_fork_off, self.data_fork_len = struct.unpack_from(">QQ", k, 0x18)
+ self.rsrc_fork_off, self.rsrc_fork_len = struct.unpack_from(">QQ", k, 0x28)
+ self.xml_off, self.xml_len = struct.unpack_from(">QQ", k, 0xD8)
+ self.image_variant = struct.unpack_from(">I", k, 0x1E8)[0]
+ self.sector_count = struct.unpack_from(">Q", k, 0x1EC)[0]
+
+ def _read_plist(self):
+ if not self.xml_len:
+ raise ValueError("%s: no XML property list; a resource fork table is not "
+ "supported" % self.path)
+ self.f.seek(self.xml_off)
+ pl = plistlib.loads(self.f.read(self.xml_len))
+ self.tables = []
+ for ent in pl["resource-fork"]["blkx"]:
+ data = ent["Data"]
+ if isinstance(data, str):
+ data = base64.b64decode(data)
+ self.tables.append(Blkx(ent.get("Name", ""), ent.get("ID", ""), data))
+ self.tables.sort(key=lambda b: b.sector)
+ # one flat chunk list for the whole image, so a read need not care about partitions
+ self._chunks = []
+ for b in self.tables:
+ self._chunks.extend(b.chunks)
+ self._chunks.sort(key=lambda c: c.sector)
+ self._starts = [c.out_off for c in self._chunks]
+
+ @property
+ def size(self):
+ return self.sector_count * SECTOR
+
+ def _chunk_data(self, c):
+ """The decompressed bytes of one chunk."""
+ if self._cache_key == c.in_off and self._cache_buf is not None:
+ return self._cache_buf
+ if c.type in (CHUNK_ZERO, CHUNK_IGNORE):
+ buf = b"\0" * c.out_len
+ else:
+ self.f.seek(c.in_off)
+ raw = self.f.read(c.in_len)
+ if c.type == CHUNK_RAW:
+ buf = raw
+ elif c.type == CHUNK_ZLIB:
+ buf = zlib.decompress(raw)
+ elif c.type == CHUNK_BZIP2:
+ buf = bz2.decompress(raw)
+ elif c.type == CHUNK_LZMA:
+ buf = lzma.decompress(raw)
+ elif c.type == CHUNK_LZFSE:
+ buf = _lzfse_decompress(raw, c.out_len)
+ elif c.type == CHUNK_ADC:
+ buf = _adc_decompress(raw, c.out_len)
+ else:
+ raise ValueError("unknown chunk type 0x%08x at output offset %d"
+ % (c.type, c.out_off))
+ if len(buf) != c.out_len:
+ raise ValueError("chunk at output offset %d: %d bytes out of %s, "
+ "expected %d" % (c.out_off, len(buf),
+ CHUNK_NAMES.get(c.type, "?"), c.out_len))
+ self._cache_key, self._cache_buf = c.in_off, buf
+ return buf
+
+ def read(self, off, length):
+ """Read the decompressed image. Holes between chunks read as zeros."""
+ import bisect
+ out = bytearray()
+ end = off + length
+ while off < end:
+ i = bisect.bisect_right(self._starts, off) - 1
+ c = self._chunks[i] if i >= 0 else None
+ if c is None or off >= c.out_off + c.out_len:
+ # before the first chunk, or in a hole: zeros up to the next chunk
+ nxt = self._starts[i + 1] if i + 1 < len(self._starts) else end
+ n = min(end, nxt) - off
+ out += b"\0" * n
+ off += n
+ continue
+ buf = self._chunk_data(c)
+ inner = off - c.out_off
+ n = min(end - off, c.out_len - inner)
+ out += buf[inner:inner + n]
+ off += n
+ return bytes(out)
+
+ def extract(self, out_path, start=0, length=None, progress=None):
+ """Write a byte range of the decompressed image to a file."""
+ if length is None:
+ length = self.size - start
+ end = start + length
+ written = 0
+ with open(out_path, "wb") as g:
+ # walk the chunks that overlap the range, so nothing is decompressed twice
+ import bisect
+ i = max(0, bisect.bisect_right(self._starts, start) - 1)
+ pos = start
+ while pos < end:
+ c = self._chunks[i] if i < len(self._chunks) else None
+ if c is None or c.out_off >= end:
+ g.write(b"\0" * (end - pos))
+ written += end - pos
+ break
+ if pos < c.out_off: # hole before this chunk
+ n = c.out_off - pos
+ g.write(b"\0" * n)
+ written += n
+ pos = c.out_off
+ if pos >= c.out_off + c.out_len:
+ i += 1
+ continue
+ buf = self._chunk_data(c)
+ inner = pos - c.out_off
+ n = min(end - pos, c.out_len - inner)
+ g.write(buf[inner:inner + n])
+ written += n
+ pos += n
+ if progress and (i & 0x3FF) == 0:
+ progress(written, length)
+ i += 1
+ if progress:
+ progress(written, length)
+ return written
+
+
+# ---- GPT, just enough to find the partitions in an extracted whole-disk image ----
+
+APFS_PART_TYPE = "7C3457EF-0000-11AA-AA11-00306543ECAC"
+
+
+def _guid(b):
+ """A GPT type GUID: three little-endian fields then eight bytes as they lie."""
+ d1, d2, d3 = struct.unpack_from("<IHH", b, 0)
+ return "%08X-%04X-%04X-%s-%s" % (
+ d1, d2, d3, b[8:10].hex().upper(), b[10:16].hex().upper())
+
+
+class Partition:
+ def __init__(self, index, type_guid, part_guid, first, last, name):
+ self.index = index
+ self.type_guid = type_guid
+ self.guid = part_guid
+ self.first_lba = first
+ self.last_lba = last
+ self.name = name
+
+ @property
+ def offset(self):
+ return self.first_lba * SECTOR
+
+ @property
+ def length(self):
+ return (self.last_lba - self.first_lba + 1) * SECTOR
+
+
+def read_gpt(reader):
+ """Partitions of a GPT, from anything with a read(off, len). [] if there is no GPT."""
+ hdr = reader.read(SECTOR, SECTOR)
+ if hdr[:8] != b"EFI PART":
+ return []
+ part_lba, nparts, entsz = struct.unpack_from("<QII", hdr, 72)
+ tbl = reader.read(part_lba * SECTOR, nparts * entsz)
+ out = []
+ for i in range(nparts):
+ e = tbl[i * entsz:(i + 1) * entsz]
+ t = _guid(e[0:16])
+ if t == "00000000-0000-0000-0000-000000000000":
+ continue
+ first, last = struct.unpack_from("<QQ", e, 32)
+ name = e[56:128].decode("utf-16-le", "replace").rstrip("\0")
+ out.append(Partition(i, t, _guid(e[16:32]), first, last, name))
+ return out
+
+
+def _fmt(n):
+ return "%d (%.2f GB)" % (n, n / 1e9) if n >= 1 << 30 else "%d (%.1f MB)" % (n, n / 1e6)
+
+
+def cmd_info(path):
+ d = Dmg(path)
+ print("%s: %d bytes on disk" % (path, d.file_size))
+ print("UDIF version %d, flags 0x%x, image variant %d" % (d.version, d.flags, d.image_variant))
+ print("data fork off=%d len=%d" % (d.data_fork_off, d.data_fork_len))
+ print("xml plist off=%d len=%d" % (d.xml_off, d.xml_len))
+ print("image size %s in %d sectors" % (_fmt(d.size), d.sector_count))
+ print()
+ kinds = {}
+ for c in d._chunks:
+ k = kinds.setdefault(CHUNK_NAMES.get(c.type, hex(c.type)), [0, 0, 0])
+ k[0] += 1
+ k[1] += c.in_len
+ k[2] += c.out_len
+ print("%d block tables, %d chunks:" % (len(d.tables), len(d._chunks)))
+ for name, (n, cin, cout) in sorted(kinds.items()):
+ print(" %-8s %7d chunks %14d -> %14d bytes" % (name, n, cin, cout))
+ print()
+ print("block tables:")
+ for b in d.tables:
+ print(" id=%-4s out=%d+%d (%s) %d chunks %s"
+ % (b.id, b.out_off, b.out_len, _fmt(b.out_len), len(b.chunks), b.name))
+ print()
+ parts = read_gpt(d)
+ if not parts:
+ print("no GPT at sector 1 -- the image is a bare file system, not a whole disk")
+ return
+ print("GPT, %d partitions:" % len(parts))
+ for p in parts:
+ tag = " <- APFS" if p.type_guid == APFS_PART_TYPE else ""
+ print(" %d lba %d..%d off=%d len=%s %-24s %s%s"
+ % (p.index, p.first_lba, p.last_lba, p.offset, _fmt(p.length),
+ p.name, p.type_guid, tag))
+
+
+def cmd_extract(path, out, which):
+ d = Dmg(path)
+ start, length, what = 0, d.size, "the whole image"
+ if which is not None:
+ parts = read_gpt(d)
+ if not parts:
+ raise SystemExit("dmg.py: no GPT in this image, nothing to pick from")
+ if which == "apfs":
+ cand = [p for p in parts if p.type_guid == APFS_PART_TYPE]
+ if not cand:
+ raise SystemExit("dmg.py: no APFS partition in the GPT")
+ p = cand[0]
+ else:
+ sel = [p for p in parts if p.index == int(which)]
+ if not sel:
+ raise SystemExit("dmg.py: no partition %s" % which)
+ p = sel[0]
+ start, length = p.offset, p.length
+ what = "partition %d (%s)" % (p.index, p.name)
+
+ def prog(done, total):
+ pct = 100.0 * done / total if total else 100.0
+ sys.stderr.write("\r %s: %6.2f%% %d/%d bytes" % (what, pct, done, total))
+ sys.stderr.flush()
+
+ n = d.extract(out, start, length, prog)
+ sys.stderr.write("\n")
+ print("%s -> %s: %d bytes from offset %d" % (path, out, n, start))
+ head = d.read(start, 64)
+ print("first 32 bytes: %s" % head[:32].hex())
+ # an APFS container starts with an object header; its magic is 32 bytes in
+ if head[32:36] == b"NXSB":
+ print("magic at offset 32: NXSB -- an APFS container")
+
+
+def cmd_cat(path, off, length):
+ d = Dmg(path)
+ buf = d.read(off, length)
+ for i in range(0, len(buf), 16):
+ row = buf[i:i + 16]
+ txt = "".join(chr(c) if 32 <= c < 127 else "." for c in row)
+ print("%012x %-47s %s" % (off + i, row.hex(" "), txt))
+
+
+def main(argv):
+ if len(argv) < 3:
+ print(__doc__ or "", file=sys.stderr)
+ print("usage: dmg.py info IMAGE\n"
+ " dmg.py extract IMAGE OUT [--part N | --apfs]\n"
+ " dmg.py cat IMAGE OFFSET LENGTH", file=sys.stderr)
+ return 2
+ cmd = argv[1]
+ if cmd == "info":
+ cmd_info(argv[2])
+ elif cmd == "extract":
+ which = None
+ for a in argv[4:]:
+ if a == "--apfs":
+ which = "apfs"
+ elif a.startswith("--part"):
+ which = a.split("=", 1)[1] if "=" in a else argv[argv.index(a) + 1]
+ cmd_extract(argv[2], argv[3], which)
+ elif cmd == "cat":
+ cmd_cat(argv[2], int(argv[3], 0), int(argv[4], 0))
+ else:
+ raise SystemExit("dmg.py: unknown command %r" % cmd)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/tools/apfs/fmt_check.c b/tools/apfs/fmt_check.c
new file mode 100644
index 0000000..7705012
--- /dev/null
+++ b/tools/apfs/fmt_check.c
@@ -0,0 +1,223 @@
+/*
+ * Print the size of every structure in apfs_format.h and the offset of every field the
+ * reader depends on, so that the header and tools/apfs/apfs.py can be checked against
+ * each other instead of being trusted to agree. Built and run by run-tests.sh.
+ *
+ * Output is one line per item: "name<TAB>offset<TAB>size", and "name<TAB>sizeof" for a
+ * whole structure.
+ */
+
+#include <stdio.h>
+#include <stddef.h>
+
+#include "apfs_format.h"
+
+#define SIZE(t) printf("%s\tsizeof\t%zu\n", #t, sizeof(struct t))
+#define OFF(t, f) printf("%s.%s\t%zu\t%zu\n", #t, #f, offsetof(struct t, f), \
+ sizeof(((struct t *)0)->f))
+/* a flexible array member has no size of its own, so only its offset is printed */
+#define OFFA(t, f) printf("%s.%s\t%zu\t0\n", #t, #f, offsetof(struct t, f))
+
+int
+main(void)
+{
+ SIZE(apfs_prange);
+ OFF(apfs_prange, pr_start_paddr);
+ OFF(apfs_prange, pr_block_count);
+
+ SIZE(apfs_obj_phys);
+ OFF(apfs_obj_phys, o_cksum);
+ OFF(apfs_obj_phys, o_oid);
+ OFF(apfs_obj_phys, o_xid);
+ OFF(apfs_obj_phys, o_type);
+ OFF(apfs_obj_phys, o_subtype);
+
+ SIZE(apfs_nx_superblock);
+ OFF(apfs_nx_superblock, nx_magic);
+ OFF(apfs_nx_superblock, nx_block_size);
+ OFF(apfs_nx_superblock, nx_block_count);
+ OFF(apfs_nx_superblock, nx_features);
+ OFF(apfs_nx_superblock, nx_readonly_compatible_features);
+ OFF(apfs_nx_superblock, nx_incompatible_features);
+ OFF(apfs_nx_superblock, nx_uuid);
+ OFF(apfs_nx_superblock, nx_next_oid);
+ OFF(apfs_nx_superblock, nx_next_xid);
+ OFF(apfs_nx_superblock, nx_xp_desc_blocks);
+ OFF(apfs_nx_superblock, nx_xp_data_blocks);
+ OFF(apfs_nx_superblock, nx_xp_desc_base);
+ OFF(apfs_nx_superblock, nx_xp_data_base);
+ OFF(apfs_nx_superblock, nx_xp_desc_next);
+ OFF(apfs_nx_superblock, nx_xp_data_next);
+ OFF(apfs_nx_superblock, nx_xp_desc_index);
+ OFF(apfs_nx_superblock, nx_xp_desc_len);
+ OFF(apfs_nx_superblock, nx_xp_data_index);
+ OFF(apfs_nx_superblock, nx_xp_data_len);
+ OFF(apfs_nx_superblock, nx_spaceman_oid);
+ OFF(apfs_nx_superblock, nx_omap_oid);
+ OFF(apfs_nx_superblock, nx_reaper_oid);
+ OFF(apfs_nx_superblock, nx_max_file_systems);
+ OFF(apfs_nx_superblock, nx_fs_oid);
+
+ SIZE(apfs_checkpoint_mapping);
+ OFF(apfs_checkpoint_mapping, cpm_type);
+ OFF(apfs_checkpoint_mapping, cpm_oid);
+ OFF(apfs_checkpoint_mapping, cpm_paddr);
+ OFF(apfs_checkpoint_map_phys, cpm_flags);
+ OFF(apfs_checkpoint_map_phys, cpm_count);
+ OFFA(apfs_checkpoint_map_phys, cpm_map);
+
+ SIZE(apfs_omap_phys);
+ OFF(apfs_omap_phys, om_flags);
+ OFF(apfs_omap_phys, om_snap_count);
+ OFF(apfs_omap_phys, om_tree_type);
+ OFF(apfs_omap_phys, om_snapshot_tree_type);
+ OFF(apfs_omap_phys, om_tree_oid);
+ OFF(apfs_omap_phys, om_snapshot_tree_oid);
+
+ SIZE(apfs_omap_key);
+ OFF(apfs_omap_key, ok_oid);
+ OFF(apfs_omap_key, ok_xid);
+ SIZE(apfs_omap_val);
+ OFF(apfs_omap_val, ov_flags);
+ OFF(apfs_omap_val, ov_size);
+ OFF(apfs_omap_val, ov_paddr);
+
+ SIZE(apfs_wrapped_meta_crypto_state);
+ SIZE(apfs_modified_by);
+
+ SIZE(apfs_superblock);
+ OFF(apfs_superblock, apfs_magic);
+ OFF(apfs_superblock, apfs_fs_index);
+ OFF(apfs_superblock, apfs_features);
+ OFF(apfs_superblock, apfs_readonly_compatible_features);
+ OFF(apfs_superblock, apfs_incompatible_features);
+ OFF(apfs_superblock, apfs_unmount_time);
+ OFF(apfs_superblock, apfs_fs_reserve_block_count);
+ OFF(apfs_superblock, apfs_fs_quota_block_count);
+ OFF(apfs_superblock, apfs_fs_alloc_count);
+ OFF(apfs_superblock, apfs_meta_crypto);
+ OFF(apfs_superblock, apfs_root_tree_type);
+ OFF(apfs_superblock, apfs_extentref_tree_type);
+ OFF(apfs_superblock, apfs_snap_meta_tree_type);
+ OFF(apfs_superblock, apfs_omap_oid);
+ OFF(apfs_superblock, apfs_root_tree_oid);
+ OFF(apfs_superblock, apfs_extentref_tree_oid);
+ OFF(apfs_superblock, apfs_snap_meta_tree_oid);
+ OFF(apfs_superblock, apfs_revert_to_xid);
+ OFF(apfs_superblock, apfs_revert_to_sblock_oid);
+ OFF(apfs_superblock, apfs_next_obj_id);
+ OFF(apfs_superblock, apfs_num_files);
+ OFF(apfs_superblock, apfs_num_directories);
+ OFF(apfs_superblock, apfs_num_symlinks);
+ OFF(apfs_superblock, apfs_num_other_fsobjects);
+ OFF(apfs_superblock, apfs_num_snapshots);
+ OFF(apfs_superblock, apfs_total_blocks_alloced);
+ OFF(apfs_superblock, apfs_total_blocks_freed);
+ OFF(apfs_superblock, apfs_vol_uuid);
+ OFF(apfs_superblock, apfs_last_mod_time);
+ OFF(apfs_superblock, apfs_fs_flags);
+ OFF(apfs_superblock, apfs_formatted_by);
+ OFF(apfs_superblock, apfs_modified_by);
+ OFF(apfs_superblock, apfs_volname);
+ OFF(apfs_superblock, apfs_next_doc_id);
+ OFF(apfs_superblock, apfs_role);
+
+ SIZE(apfs_nloc);
+ OFF(apfs_nloc, off);
+ OFF(apfs_nloc, len);
+ SIZE(apfs_kvloc);
+ SIZE(apfs_kvoff);
+
+ SIZE(apfs_btree_node_phys);
+ OFF(apfs_btree_node_phys, btn_flags);
+ OFF(apfs_btree_node_phys, btn_level);
+ OFF(apfs_btree_node_phys, btn_nkeys);
+ OFF(apfs_btree_node_phys, btn_table_space);
+ OFF(apfs_btree_node_phys, btn_free_space);
+ OFF(apfs_btree_node_phys, btn_key_free_list);
+ OFF(apfs_btree_node_phys, btn_val_free_list);
+ OFFA(apfs_btree_node_phys, btn_data);
+
+ SIZE(apfs_btree_info_fixed);
+ SIZE(apfs_btree_info);
+ OFF(apfs_btree_info, bt_fixed);
+ OFF(apfs_btree_info, bt_longest_key);
+ OFF(apfs_btree_info, bt_longest_val);
+ OFF(apfs_btree_info, bt_key_count);
+ OFF(apfs_btree_info, bt_node_count);
+
+ SIZE(apfs_j_key);
+ SIZE(apfs_j_inode_val);
+ OFF(apfs_j_inode_val, parent_id);
+ OFF(apfs_j_inode_val, private_id);
+ OFF(apfs_j_inode_val, create_time);
+ OFF(apfs_j_inode_val, mod_time);
+ OFF(apfs_j_inode_val, change_time);
+ OFF(apfs_j_inode_val, access_time);
+ OFF(apfs_j_inode_val, internal_flags);
+ OFF(apfs_j_inode_val, nchildren);
+ OFF(apfs_j_inode_val, default_protection_class);
+ OFF(apfs_j_inode_val, write_generation_counter);
+ OFF(apfs_j_inode_val, bsd_flags);
+ OFF(apfs_j_inode_val, owner);
+ OFF(apfs_j_inode_val, group);
+ OFF(apfs_j_inode_val, mode);
+ OFF(apfs_j_inode_val, pad1);
+ OFF(apfs_j_inode_val, uncompressed_size);
+ OFFA(apfs_j_inode_val, xfields);
+
+ OFF(apfs_j_drec_key, name_len);
+ OFF(apfs_j_drec_key, name);
+ OFF(apfs_j_drec_hashed_key, name_len_and_hash);
+ OFF(apfs_j_drec_hashed_key, name);
+ OFF(apfs_j_drec_val, file_id);
+ OFF(apfs_j_drec_val, date_added);
+ OFF(apfs_j_drec_val, flags);
+ OFFA(apfs_j_drec_val, xfields);
+
+ OFF(apfs_j_xattr_key, name_len);
+ OFF(apfs_j_xattr_key, name);
+ OFF(apfs_j_xattr_val, flags);
+ OFF(apfs_j_xattr_val, xdata_len);
+ OFF(apfs_j_xattr_val, xdata);
+
+ SIZE(apfs_j_dstream);
+ OFF(apfs_j_dstream, size);
+ OFF(apfs_j_dstream, alloced_size);
+ OFF(apfs_j_dstream, default_crypto_id);
+ OFF(apfs_j_dstream, total_bytes_written);
+ OFF(apfs_j_dstream, total_bytes_read);
+ SIZE(apfs_j_xattr_dstream);
+ OFF(apfs_j_xattr_dstream, xattr_obj_id);
+ OFF(apfs_j_xattr_dstream, dstream);
+
+ OFF(apfs_j_file_extent_key, logical_addr);
+ OFF(apfs_j_file_extent_val, len_and_flags);
+ OFF(apfs_j_file_extent_val, phys_block_num);
+ OFF(apfs_j_file_extent_val, crypto_id);
+
+ OFF(apfs_j_phys_ext_val, len_and_kind);
+ OFF(apfs_j_phys_ext_val, owning_obj_id);
+ OFF(apfs_j_phys_ext_val, refcnt);
+
+ OFF(apfs_j_sibling_key, sibling_id);
+ OFF(apfs_j_sibling_val, parent_id);
+ OFF(apfs_j_sibling_val, name_len);
+ OFF(apfs_j_sibling_val, name);
+
+ SIZE(apfs_xf_blob);
+ OFF(apfs_xf_blob, xf_num_exts);
+ OFF(apfs_xf_blob, xf_used_data);
+ OFFA(apfs_xf_blob, xf_data);
+ SIZE(apfs_x_field);
+ OFF(apfs_x_field, x_type);
+ OFF(apfs_x_field, x_flags);
+ OFF(apfs_x_field, x_size);
+
+ OFF(apfs_decmpfs_disk_header, compression_magic);
+ OFF(apfs_decmpfs_disk_header, compression_type);
+ OFF(apfs_decmpfs_disk_header, uncompressed_size);
+ OFF(apfs_decmpfs_disk_header, attr_bytes);
+
+ return 0;
+}
diff --git a/tools/apfs/run-tests.sh b/tools/apfs/run-tests.sh
new file mode 100755
index 0000000..3c8140c
--- /dev/null
+++ b/tools/apfs/run-tests.sh
@@ -0,0 +1,72 @@
+#!/bin/bash
+# Everything about the APFS reader that can be checked on the computer.
+#
+# 1. the on-disk structures in apfs_format.h against the offsets apfs.py reads at
+# 2. the UDIF reader against the image's own trailer and partition table
+# 3. the APFS reader against 7-Zip's, over every entry in the volume (needs ios165/)
+# 4. file contents against the files 7-Zip extracted, byte for byte (needs ios165/)
+#
+# Steps 3 and 4 need the APFS partition unpacked out of ios165/rootfs.dmg; pass it as
+# $1, or set APFS_IMAGE. Without it only the first two steps run.
+#
+# usage: tools/apfs/run-tests.sh [APFS-PARTITION-OR-DMG]
+
+set -u
+HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
+ROOT=$(cd "$HERE/../.." && pwd)
+IMAGE=${1:-${APFS_IMAGE:-}}
+TMP=$(mktemp -d)
+trap 'rm -rf "$TMP"' EXIT
+fail=0
+
+# the header lives in the kernel tree; xnu/files/ has the exported copy
+HDR_DIR=""
+for d in "$ROOT/xnu-src/xnu-8796.121.2/bsd/miscfs/apfs" "$ROOT/xnu/files/bsd/miscfs/apfs"; do
+ [ -f "$d/apfs_format.h" ] && { HDR_DIR=$d; break; }
+done
+if [ -z "$HDR_DIR" ]; then
+ echo "run-tests.sh: apfs_format.h is in neither the kernel tree nor xnu/files" >&2
+ exit 1
+fi
+
+echo "== 1. apfs_format.h ($HDR_DIR) against the offsets apfs.py reads at"
+cc -std=c11 -Wall -Wextra -I"$HDR_DIR" -o "$TMP/fmt_check" "$HERE/fmt_check.c" || exit 1
+"$TMP/fmt_check" > "$TMP/fmt.txt" || exit 1
+python3 "$HERE/test_format.py" "$TMP/fmt.txt" || fail=1
+echo
+
+echo "== 1b. hole handling, on made-up extent lists (the image has no sparse file)"
+python3 "$HERE/test_sparse.py" || fail=1
+echo
+
+echo "== 2. the UDIF reader on ios165/rootfs.dmg"
+if [ -f "$ROOT/ios165/rootfs.dmg" ]; then
+ python3 "$HERE/dmg.py" info "$ROOT/ios165/rootfs.dmg" | tail -n 14 || fail=1
+else
+ echo " skipped: ios165/rootfs.dmg is not here (run ios165/fetch.sh with KEEP=1)"
+fi
+echo
+
+if [ -z "$IMAGE" ] || [ ! -f "$IMAGE" ]; then
+ echo "== 3, 4. skipped: no APFS image given"
+ echo " unpack one with: tools/apfs/dmg.py extract ios165/rootfs.dmg OUT.apfs --apfs"
+ exit $fail
+fi
+
+echo "== 3. every entry in the volume against 7-Zip's listing"
+if [ -f "$ROOT/ios165/rootfs.slt" ]; then
+ python3 "$HERE/verify.py" listing "$IMAGE" "$ROOT/ios165/rootfs.slt" || fail=1
+else
+ echo " skipped: ios165/rootfs.slt is not here"
+fi
+echo
+
+echo "== 4. file contents against what 7-Zip extracted"
+if [ -d "$ROOT/ios165/rootfs" ]; then
+ python3 "$HERE/verify.py" sample "$IMAGE" "$ROOT/ios165/rootfs" || fail=1
+ echo " (that is a sample of every kind; --all compares all of them)"
+else
+ echo " skipped: ios165/rootfs is not here"
+fi
+
+exit $fail
diff --git a/tools/apfs/test_format.py b/tools/apfs/test_format.py
new file mode 100755
index 0000000..a78f545
--- /dev/null
+++ b/tools/apfs/test_format.py
@@ -0,0 +1,220 @@
+#!/usr/bin/env python3
+# Check that apfs.py and apfs_format.h describe the same bytes.
+#
+# apfs.py reads the disk with struct.unpack_from and literal offsets. The table below is
+# those offsets, written out in one place; fmt_check.c prints what the C header says the
+# same offsets are. If the header and the reader ever drift apart, this fails.
+#
+# usage: test_format.py FMT_CHECK_OUTPUT
+
+import sys
+
+# (structure, field) -> (offset, size). Size 0 means a trailing variable-length field,
+# where only the offset is checked.
+EXPECTED = {
+ ("apfs_obj_phys", "o_cksum"): (0, 8),
+ ("apfs_obj_phys", "o_oid"): (8, 8),
+ ("apfs_obj_phys", "o_xid"): (16, 8),
+ ("apfs_obj_phys", "o_type"): (24, 4),
+ ("apfs_obj_phys", "o_subtype"): (28, 4),
+
+ ("apfs_nx_superblock", "nx_magic"): (32, 4),
+ ("apfs_nx_superblock", "nx_block_size"): (36, 4),
+ ("apfs_nx_superblock", "nx_block_count"): (40, 8),
+ ("apfs_nx_superblock", "nx_features"): (48, 8),
+ ("apfs_nx_superblock", "nx_readonly_compatible_features"): (56, 8),
+ ("apfs_nx_superblock", "nx_incompatible_features"): (64, 8),
+ ("apfs_nx_superblock", "nx_uuid"): (72, 16),
+ ("apfs_nx_superblock", "nx_next_oid"): (88, 8),
+ ("apfs_nx_superblock", "nx_next_xid"): (96, 8),
+ ("apfs_nx_superblock", "nx_xp_desc_blocks"): (104, 4),
+ ("apfs_nx_superblock", "nx_xp_data_blocks"): (108, 4),
+ ("apfs_nx_superblock", "nx_xp_desc_base"): (112, 8),
+ ("apfs_nx_superblock", "nx_xp_data_base"): (120, 8),
+ ("apfs_nx_superblock", "nx_xp_desc_next"): (128, 4),
+ ("apfs_nx_superblock", "nx_spaceman_oid"): (152, 8),
+ ("apfs_nx_superblock", "nx_omap_oid"): (160, 8),
+ ("apfs_nx_superblock", "nx_reaper_oid"): (168, 8),
+ ("apfs_nx_superblock", "nx_max_file_systems"): (180, 4),
+ ("apfs_nx_superblock", "nx_fs_oid"): (184, 800),
+
+ ("apfs_omap_phys", "om_flags"): (32, 4),
+ ("apfs_omap_phys", "om_tree_type"): (40, 4),
+ ("apfs_omap_phys", "om_tree_oid"): (48, 8),
+ ("apfs_omap_phys", "om_snapshot_tree_oid"): (56, 8),
+ ("apfs_omap_key", "ok_oid"): (0, 8),
+ ("apfs_omap_key", "ok_xid"): (8, 8),
+ ("apfs_omap_val", "ov_flags"): (0, 4),
+ ("apfs_omap_val", "ov_size"): (4, 4),
+ ("apfs_omap_val", "ov_paddr"): (8, 8),
+
+ ("apfs_superblock", "apfs_magic"): (32, 4),
+ ("apfs_superblock", "apfs_fs_index"): (36, 4),
+ ("apfs_superblock", "apfs_features"): (40, 8),
+ ("apfs_superblock", "apfs_incompatible_features"): (56, 8),
+ ("apfs_superblock", "apfs_unmount_time"): (64, 8),
+ ("apfs_superblock", "apfs_fs_alloc_count"): (88, 8),
+ ("apfs_superblock", "apfs_meta_crypto"): (96, 20),
+ ("apfs_superblock", "apfs_root_tree_type"): (116, 4),
+ ("apfs_superblock", "apfs_omap_oid"): (128, 8),
+ ("apfs_superblock", "apfs_root_tree_oid"): (136, 8),
+ ("apfs_superblock", "apfs_extentref_tree_oid"): (144, 8),
+ ("apfs_superblock", "apfs_snap_meta_tree_oid"): (152, 8),
+ ("apfs_superblock", "apfs_revert_to_xid"): (160, 8),
+ ("apfs_superblock", "apfs_next_obj_id"): (176, 8),
+ ("apfs_superblock", "apfs_num_files"): (184, 8),
+ ("apfs_superblock", "apfs_num_directories"): (192, 8),
+ ("apfs_superblock", "apfs_num_symlinks"): (200, 8),
+ ("apfs_superblock", "apfs_num_other_fsobjects"): (208, 8),
+ ("apfs_superblock", "apfs_num_snapshots"): (216, 8),
+ ("apfs_superblock", "apfs_total_blocks_alloced"): (224, 8),
+ ("apfs_superblock", "apfs_vol_uuid"): (240, 16),
+ ("apfs_superblock", "apfs_last_mod_time"): (256, 8),
+ ("apfs_superblock", "apfs_fs_flags"): (264, 8),
+ ("apfs_superblock", "apfs_formatted_by"): (272, 48),
+ ("apfs_superblock", "apfs_modified_by"): (320, 384),
+ ("apfs_superblock", "apfs_volname"): (704, 256),
+ ("apfs_superblock", "apfs_next_doc_id"): (960, 4),
+ ("apfs_superblock", "apfs_role"): (964, 2),
+
+ ("apfs_btree_node_phys", "btn_flags"): (32, 2),
+ ("apfs_btree_node_phys", "btn_level"): (34, 2),
+ ("apfs_btree_node_phys", "btn_nkeys"): (36, 4),
+ ("apfs_btree_node_phys", "btn_table_space"): (40, 4),
+ ("apfs_btree_node_phys", "btn_free_space"): (44, 4),
+ ("apfs_btree_node_phys", "btn_data"): (56, 0),
+ ("apfs_btree_info", "bt_fixed"): (0, 16),
+ ("apfs_btree_info", "bt_longest_key"): (16, 4),
+ ("apfs_btree_info", "bt_longest_val"): (20, 4),
+ ("apfs_btree_info", "bt_key_count"): (24, 8),
+ ("apfs_btree_info", "bt_node_count"): (32, 8),
+
+ ("apfs_j_inode_val", "parent_id"): (0, 8),
+ ("apfs_j_inode_val", "private_id"): (8, 8),
+ ("apfs_j_inode_val", "create_time"): (16, 8),
+ ("apfs_j_inode_val", "mod_time"): (24, 8),
+ ("apfs_j_inode_val", "change_time"): (32, 8),
+ ("apfs_j_inode_val", "access_time"): (40, 8),
+ ("apfs_j_inode_val", "internal_flags"): (48, 8),
+ ("apfs_j_inode_val", "nchildren"): (56, 4),
+ ("apfs_j_inode_val", "default_protection_class"): (60, 4),
+ ("apfs_j_inode_val", "write_generation_counter"): (64, 4),
+ ("apfs_j_inode_val", "bsd_flags"): (68, 4),
+ ("apfs_j_inode_val", "owner"): (72, 4),
+ ("apfs_j_inode_val", "group"): (76, 4),
+ ("apfs_j_inode_val", "mode"): (80, 2),
+ ("apfs_j_inode_val", "uncompressed_size"): (84, 8),
+ ("apfs_j_inode_val", "xfields"): (92, 0),
+
+ ("apfs_j_drec_hashed_key", "name_len_and_hash"): (8, 4),
+ ("apfs_j_drec_hashed_key", "name"): (12, 0),
+ ("apfs_j_drec_val", "file_id"): (0, 8),
+ ("apfs_j_drec_val", "date_added"): (8, 8),
+ ("apfs_j_drec_val", "flags"): (16, 2),
+
+ ("apfs_j_xattr_key", "name_len"): (8, 2),
+ ("apfs_j_xattr_key", "name"): (10, 0),
+ ("apfs_j_xattr_val", "flags"): (0, 2),
+ ("apfs_j_xattr_val", "xdata_len"): (2, 2),
+ ("apfs_j_xattr_val", "xdata"): (4, 0),
+
+ ("apfs_j_dstream", "size"): (0, 8),
+ ("apfs_j_dstream", "alloced_size"): (8, 8),
+ ("apfs_j_dstream", "default_crypto_id"): (16, 8),
+ ("apfs_j_dstream", "total_bytes_written"): (24, 8),
+ ("apfs_j_dstream", "total_bytes_read"): (32, 8),
+ ("apfs_j_xattr_dstream", "xattr_obj_id"): (0, 8),
+ ("apfs_j_xattr_dstream", "dstream"): (8, 40),
+
+ ("apfs_j_file_extent_key", "logical_addr"): (8, 8),
+ ("apfs_j_file_extent_val", "len_and_flags"): (0, 8),
+ ("apfs_j_file_extent_val", "phys_block_num"): (8, 8),
+ ("apfs_j_file_extent_val", "crypto_id"): (16, 8),
+
+ ("apfs_xf_blob", "xf_num_exts"): (0, 2),
+ ("apfs_xf_blob", "xf_used_data"): (2, 2),
+ ("apfs_xf_blob", "xf_data"): (4, 0),
+ ("apfs_x_field", "x_type"): (0, 1),
+ ("apfs_x_field", "x_flags"): (1, 1),
+ ("apfs_x_field", "x_size"): (2, 2),
+
+ ("apfs_decmpfs_disk_header", "compression_magic"): (0, 4),
+ ("apfs_decmpfs_disk_header", "compression_type"): (4, 4),
+ ("apfs_decmpfs_disk_header", "uncompressed_size"): (8, 8),
+ ("apfs_decmpfs_disk_header", "attr_bytes"): (16, 0),
+}
+
+# structure -> size in bytes, as apfs.py steps over it
+EXPECTED_SIZES = {
+ "apfs_obj_phys": 32,
+ "apfs_prange": 16,
+ "apfs_omap_key": 16,
+ "apfs_omap_val": 16,
+ "apfs_wrapped_meta_crypto_state": 20,
+ "apfs_modified_by": 48,
+ "apfs_nloc": 4,
+ "apfs_kvloc": 8,
+ "apfs_kvoff": 4,
+ "apfs_btree_node_phys": 56,
+ "apfs_btree_info_fixed": 16,
+ "apfs_btree_info": 40,
+ "apfs_j_key": 8,
+ "apfs_j_inode_val": 92,
+ "apfs_j_dstream": 40,
+ "apfs_j_xattr_dstream": 48,
+ "apfs_xf_blob": 4,
+ "apfs_x_field": 4,
+ "apfs_checkpoint_mapping": 40,
+}
+
+
+def main(argv):
+ if len(argv) < 2:
+ print("usage: test_format.py FMT_CHECK_OUTPUT", file=sys.stderr)
+ return 2
+ got_off = {}
+ got_size = {}
+ with open(argv[1]) as f:
+ for line in f:
+ parts = line.rstrip("\n").split("\t")
+ if len(parts) != 3:
+ continue
+ name, a, b = parts
+ if a == "sizeof":
+ got_size[name] = int(b)
+ else:
+ st, _, fld = name.partition(".")
+ got_off[(st, fld)] = (int(a), int(b))
+
+ fails = []
+ for key, (off, size) in sorted(EXPECTED.items()):
+ if key not in got_off:
+ fails.append("%s.%s: not printed by fmt_check" % key)
+ continue
+ c_off, c_size = got_off[key]
+ if c_off != off:
+ fails.append("%s.%s: apfs.py reads at %d, the header puts it at %d"
+ % (key[0], key[1], off, c_off))
+ elif size and c_size != size:
+ fails.append("%s.%s: apfs.py reads %d bytes, the header has %d"
+ % (key[0], key[1], size, c_size))
+ for name, size in sorted(EXPECTED_SIZES.items()):
+ if name not in got_size:
+ fails.append("%s: no size printed by fmt_check" % name)
+ elif got_size[name] != size:
+ fails.append("%s: apfs.py assumes %d bytes, the header is %d"
+ % (name, size, got_size[name]))
+
+ print("checked %d field offsets and %d structure sizes against apfs_format.h"
+ % (len(EXPECTED), len(EXPECTED_SIZES)))
+ if fails:
+ for m in fails:
+ print(" FAIL %s" % m)
+ print("FAILED: %d mismatches" % len(fails))
+ return 1
+ print("OK: the header and apfs.py agree on every one")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/tools/apfs/test_sparse.py b/tools/apfs/test_sparse.py
new file mode 100755
index 0000000..f8d509e
--- /dev/null
+++ b/tools/apfs/test_sparse.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+# The iOS 16.5 root file system has no sparse file in it -- a walk over all 318098 entries
+# finds no inode with INODE_IS_SPARSE or a sparse-bytes extended field -- so the hole
+# handling in read_stream cannot be checked against that image. This checks it against
+# made-up extent lists instead: a gap between two extents, an extent whose physical block
+# is zero, a hole at the front, a hole at the end, and a file with no extents at all.
+#
+# usage: test_sparse.py
+
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import apfs
+
+BS = 4096
+
+
+class FakeBlocks:
+ """Blocks of made-up contents: block n is the byte n, repeated."""
+
+ def __init__(self):
+ self.block_size = BS
+
+ def raw(self, addr, count=1):
+ return b"".join(bytes([a & 0xFF]) * BS for a in range(addr, addr + count))
+
+
+class FakeVolume:
+ """Just enough of a Volume for read_stream: a block source and an extent list."""
+
+ def __init__(self, extents):
+ self._extents = sorted(extents)
+
+ class C:
+ pass
+ self.c = C()
+ self.c.blocks = FakeBlocks()
+ self.c.block_size = BS
+
+ def extents(self, _stream_id):
+ return self._extents
+
+ read_stream = apfs.Volume.read_stream
+
+
+def blk(n, count=1):
+ return b"".join(bytes([a & 0xFF]) * BS for a in range(n, n + count))
+
+
+CASES = [
+ ("one extent, no hole",
+ [(0, BS, 7)], BS, blk(7)),
+ ("a gap between two extents",
+ [(0, BS, 7), (2 * BS, BS, 9)], 3 * BS, blk(7) + b"\0" * BS + blk(9)),
+ ("an extent whose physical block is zero reads as zeros",
+ [(0, BS, 0), (BS, BS, 9)], 2 * BS, b"\0" * BS + blk(9)),
+ ("a hole at the front",
+ [(2 * BS, BS, 5)], 3 * BS, b"\0" * (2 * BS) + blk(5)),
+ ("a hole at the end",
+ [(0, BS, 5)], 3 * BS, blk(5) + b"\0" * (2 * BS)),
+ ("no extents at all",
+ [], 2 * BS, b"\0" * (2 * BS)),
+ ("a multi-block extent",
+ [(0, 3 * BS, 20)], 3 * BS, blk(20, 3)),
+ ("the last extent is cut off by the file's size",
+ [(0, BS, 7), (BS, BS, 8)], BS + 100, blk(7) + blk(8)[:100]),
+ ("a gap of several blocks",
+ [(0, BS, 1), (4 * BS, BS, 2)], 5 * BS,
+ blk(1) + b"\0" * (3 * BS) + blk(2)),
+]
+
+
+def main():
+ fails = 0
+ for name, extents, size, want in CASES:
+ got = FakeVolume(extents).read_stream(0, size)
+ if got == want:
+ print(" ok %s" % name)
+ else:
+ fails += 1
+ where = next((i for i, (a, b) in enumerate(zip(got, want)) if a != b),
+ min(len(got), len(want)))
+ print(" FAIL %s: %d bytes out, wanted %d, first difference at byte %d"
+ % (name, len(got), len(want), where))
+ print("read_stream hole handling: %d cases, %d failed" % (len(CASES), fails))
+ return 1 if fails else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/apfs/verify.py b/tools/apfs/verify.py
new file mode 100755
index 0000000..dc27f00
--- /dev/null
+++ b/tools/apfs/verify.py
@@ -0,0 +1,348 @@
+#!/usr/bin/env python3
+# Check tools/apfs/apfs.py against something that is not us.
+#
+# Two independent references, both already in ios165/:
+#
+# listing ios165/rootfs.slt -- what 7-Zip's own APFS reader saw in the same image
+# (`7z l -slt rootfs.dmg`, made by ios165/fetch.sh). Covers every entry in
+# the volume: path, mode, owner, size, symbolic-link target, inode number.
+#
+# content ios165/rootfs/ -- the files 7-Zip actually extracted, compared byte for
+# byte. This is the one that proves we decompress correctly.
+#
+# usage: verify.py listing IMAGE SLT
+# verify.py content IMAGE REFDIR [-n COUNT] [--all]
+# verify.py sample IMAGE REFDIR (a few dozen files of every kind)
+
+import os
+import random
+import struct
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import apfs
+
+SYSTEM_OBJ_ID_MARK = 0x0FFFFFFF00000000
+
+# ios165/fetch.sh cuts these two fonts down after extracting them, so what is on disk in
+# the reference tree is deliberately not what is in the image
+TRIMMED = {
+ "System/Library/Fonts/CoreAddition/AppleColorEmoji-160px.ttc",
+ "System/Library/Fonts/LanguageSupport/PingFang.ttc",
+}
+
+
+def mode_string(mode):
+ """The same spelling 7-Zip uses, so the two can be compared as text."""
+ kind = {apfs.S_IFDIR: "d", apfs.S_IFLNK: "l", apfs.S_IFREG: "-",
+ apfs.S_IFIFO: "p", apfs.S_IFCHR: "c", apfs.S_IFBLK: "b",
+ apfs.S_IFSOCK: "s"}.get(mode & apfs.S_IFMT, "?")
+ s = kind
+ for who, (r, w, x) in ((6, (0o400, 0o200, 0o100)), (3, (0o40, 0o20, 0o10)),
+ (0, (0o4, 0o2, 0o1))):
+ s += "r" if mode & r else "-"
+ s += "w" if mode & w else "-"
+ if who == 6 and mode & 0o4000:
+ s += "s" if mode & x else "S"
+ elif who == 3 and mode & 0o2000:
+ s += "s" if mode & x else "S"
+ elif who == 0 and mode & 0o1000:
+ s += "t" if mode & x else "T"
+ else:
+ s += "x" if mode & x else "-"
+ return s
+
+
+def read_slt(path):
+ """
+ The entries of a `7z l -slt` listing. Everything before the first entry that has a
+ Mode belongs to the image and the container, not to the file system.
+ """
+ out = {}
+ cur = {}
+ with open(path, encoding="utf-8", errors="surrogateescape") as f:
+ for line in f:
+ line = line.rstrip("\n")
+ if not line:
+ if "Mode" in cur and "Path" in cur:
+ out[cur["Path"]] = cur
+ cur = {}
+ continue
+ if line.startswith("----") or line == "--":
+ if "Mode" in cur and "Path" in cur:
+ out[cur["Path"]] = cur
+ cur = {}
+ continue
+ if " = " in line:
+ k, v = line.split(" = ", 1)
+ cur[k] = v
+ elif line.endswith(" ="):
+ cur[line[:-2]] = ""
+ if "Mode" in cur and "Path" in cur:
+ out[cur["Path"]] = cur
+ return out
+
+
+def build_tree(vol, note=None):
+ """Every path in the volume -> (file_id, d_type), by walking the directory tree."""
+ paths = {}
+ stack = [(apfs.ROOT_DIR_INO_NUM, "")]
+ n = 0
+ while stack:
+ oid, prefix = stack.pop()
+ for name, fid, dt in vol.dir_entries(oid):
+ p = (prefix + "/" + name) if prefix else name
+ paths[p] = (fid, dt)
+ n += 1
+ if dt == 4:
+ stack.append((fid, p))
+ if note and n % 20000 == 0:
+ sys.stderr.write("\r walked %d entries..." % n)
+ sys.stderr.flush()
+ if note:
+ sys.stderr.write("\r walked %d entries. \n" % n)
+ return paths
+
+
+def open_volume(image, want=None):
+ c = apfs.Container(image)
+ c.blocks.cache_limit = 60000 # the whole file-system tree fits, so no evictions
+ v = apfs.pick_volume(c, want)
+ return c, v
+
+
+def cmd_listing(image, slt):
+ print("reference: %s" % slt)
+ ref = read_slt(slt)
+ print(" %d file-system entries in the 7-Zip listing" % len(ref))
+ c, v = open_volume(image)
+ print("volume %r" % v.volname)
+ mine = build_tree(v, note=True)
+ print(" %d entries from our reader" % len(mine))
+
+ only_ref = sorted(set(ref) - set(mine))
+ only_mine = sorted(set(mine) - set(ref))
+ print()
+ print("paths only 7-Zip saw : %d" % len(only_ref))
+ for p in only_ref[:10]:
+ print(" %s" % p)
+ print("paths only we saw : %d" % len(only_mine))
+ for p in only_mine[:10]:
+ print(" %s" % p)
+
+ both = sorted(set(ref) & set(mine))
+ bad = {"mode": [], "size": [], "uid": [], "gid": [], "link": [], "inode": [],
+ "noinode": []}
+ checked = 0
+ for p in both:
+ r = ref[p]
+ fid, dt = mine[p]
+ ino = v.inode(fid)
+ if ino is None:
+ bad["noinode"].append(p)
+ continue
+ checked += 1
+ if mode_string(ino.mode) != r["Mode"]:
+ bad["mode"].append((p, mode_string(ino.mode), r["Mode"]))
+ if (fid & ~SYSTEM_OBJ_ID_MARK) != int(r["iNode"]):
+ bad["inode"].append((p, fid & ~SYSTEM_OBJ_ID_MARK, r["iNode"]))
+ if r.get("User ID") and int(r["User ID"]) != ino.owner:
+ bad["uid"].append((p, ino.owner, r["User ID"]))
+ if r.get("Group ID") and int(r["Group ID"]) != ino.group:
+ bad["gid"].append((p, ino.group, r["Group ID"]))
+ if ino.is_link:
+ got = (ino.symlink_target_bytes() or b"").decode("utf-8", "surrogateescape")
+ if got != r.get("Symbolic Link", ""):
+ bad["link"].append((p, got, r.get("Symbolic Link")))
+ elif ino.is_reg and r.get("Size"):
+ # 7-Zip reports a symbolic link's size including the trailing zero byte, so
+ # only regular files can be compared on size directly
+ if int(r["Size"]) != ino.size:
+ bad["size"].append((p, ino.size, r["Size"]))
+ if checked % 20000 == 0:
+ sys.stderr.write("\r compared %d entries..." % checked)
+ sys.stderr.flush()
+ sys.stderr.write("\r")
+ print()
+ print("compared %d entries that both readers saw:" % checked)
+ for what in ("mode", "size", "uid", "gid", "link", "inode"):
+ rows = bad[what]
+ print(" %-6s differing: %d" % (what, len(rows)))
+ for row in rows[:8]:
+ print(" %s: ours %r, 7-Zip %r" % row)
+ print(" entries with no inode record: %d" % len(bad["noinode"]))
+ for p in bad["noinode"][:8]:
+ print(" %s" % p)
+ print()
+ print("blocks: %d checksums verified, %d bad" % (c.blocks.cksum_checked,
+ c.blocks.cksum_bad))
+ total_bad = sum(len(bad[k]) for k in bad)
+ print("RESULT: %s" % ("everything matched" if total_bad == 0 and not only_ref
+ else "%d differences, %d paths only 7-Zip saw"
+ % (total_bad, len(only_ref))))
+ c.close()
+ return 0 if (total_bad == 0 and not only_ref) else 1
+
+
+def classify(vol, ino):
+ """What kind of file this is, for picking a spread to compare."""
+ if ino.is_link:
+ return "symlink"
+ if not ino.is_reg:
+ return "other"
+ h = ino.decmpfs
+ if h is not None and len(h) >= 16 and \
+ struct.unpack_from("<I", h, 0)[0] == apfs.DECMPFS_MAGIC:
+ return "decmpfs-%d" % struct.unpack_from("<I", h, 4)[0]
+ if ino.is_sparse:
+ return "sparse"
+ if ino.size == 0:
+ return "empty"
+ if ino.size > (1 << 20):
+ return "plain-large"
+ return "plain"
+
+
+def _compare(vol, fid, ref_path):
+ ino = vol.inode(fid)
+ if ino is None:
+ return "no inode record", None
+ try:
+ got = ino.contents()
+ except Exception as e: # noqa: BLE001 - report, do not stop
+ return "read failed: %s" % e, classify(vol, ino)
+ kind = classify(vol, ino)
+ with open(ref_path, "rb") as f:
+ want = f.read()
+ if got == want:
+ return None, kind
+ if len(got) != len(want):
+ return "length %d, reference %d" % (len(got), len(want)), kind
+ for i, (a, b) in enumerate(zip(got, want)):
+ if a != b:
+ return "first difference at byte %d of %d" % (i, len(want)), kind
+ return "differs", kind
+
+
+def cmd_content(image, refdir, limit, do_all, stratified):
+ c, v = open_volume(image)
+ print("volume %r, reference tree %s" % (v.volname, refdir))
+ mine = build_tree(v, note=True)
+
+ # every regular file that exists in both, minus the two fonts fetch.sh rewrites
+ cands = []
+ for root, _dirs, files in os.walk(refdir):
+ for fn in files:
+ full = os.path.join(root, fn)
+ rel = os.path.relpath(full, refdir)
+ if rel in TRIMMED or rel not in mine:
+ continue
+ cands.append((rel, full, mine[rel][0]))
+ print(" %d files present in both the image and the reference tree" % len(cands))
+
+ if stratified:
+ # a few of every kind, smallest to largest, so the sample is not all one shape
+ by_kind = {}
+ rnd = random.Random(20231017)
+ rnd.shuffle(cands)
+ for rel, full, fid in cands:
+ ino = v.inode(fid)
+ if ino is None:
+ continue
+ k = classify(v, ino)
+ by_kind.setdefault(k, [])
+ if len(by_kind[k]) < 200:
+ by_kind[k].append((rel, full, fid, ino.size))
+ pick = []
+ for k in sorted(by_kind):
+ rows = sorted(by_kind[k], key=lambda r: r[3])
+ take = min(len(rows), 12)
+ # the smallest, the largest, and a spread in between
+ idx = sorted({round(i * (len(rows) - 1) / max(1, take - 1))
+ for i in range(take)})
+ for i in idx:
+ pick.append((rows[i][0], rows[i][1], rows[i][2], k))
+ cands = pick
+ print(" stratified sample: %d files over %d kinds" % (len(cands), len(by_kind)))
+ elif not do_all:
+ rnd = random.Random(20231017)
+ rnd.shuffle(cands)
+ cands = cands[:limit]
+ print(" random sample: %d files" % len(cands))
+
+ ok = 0
+ fails = []
+ kinds = {}
+ total_bytes = 0
+ for i, row in enumerate(cands):
+ rel, full, fid = row[0], row[1], row[2]
+ err, kind = _compare(v, fid, full)
+ kinds.setdefault(kind, [0, 0])
+ if err is None:
+ ok += 1
+ kinds[kind][0] += 1
+ total_bytes += os.path.getsize(full)
+ else:
+ kinds[kind][1] += 1
+ fails.append((rel, kind, err))
+ if (i + 1) % 200 == 0:
+ sys.stderr.write("\r compared %d/%d, %d bytes..." % (i + 1, len(cands),
+ total_bytes))
+ sys.stderr.flush()
+ sys.stderr.write("\r")
+ print()
+ print("compared %d files, %d bytes (%.2f GB)"
+ % (len(cands), total_bytes, total_bytes / 1e9))
+ print(" identical: %d differing: %d" % (ok, len(fails)))
+ print(" by kind:")
+ for k in sorted(kinds):
+ good, bad = kinds[k]
+ print(" %-14s %6d identical, %4d differing" % (k, good, bad))
+ if fails:
+ print(" differences (first 25):")
+ for rel, kind, err in fails[:25]:
+ print(" [%s] %s: %s" % (kind, rel, err))
+ print()
+ print("blocks: %d checksums verified, %d bad" % (c.blocks.cksum_checked,
+ c.blocks.cksum_bad))
+ print("RESULT: %s" % ("every compared file is byte-for-byte identical" if not fails
+ else "%d of %d files differ" % (len(fails), len(cands))))
+ c.close()
+ return 0 if not fails else 1
+
+
+def main(argv):
+ limit = 200
+ do_all = False
+ args = []
+ i = 1
+ while i < len(argv):
+ a = argv[i]
+ if a == "-n" and i + 1 < len(argv):
+ limit = int(argv[i + 1])
+ i += 2
+ continue
+ if a == "--all":
+ do_all = True
+ i += 1
+ continue
+ args.append(a)
+ i += 1
+ if len(args) < 3:
+ print("usage: verify.py listing IMAGE SLT\n"
+ " verify.py content IMAGE REFDIR [-n COUNT] [--all]\n"
+ " verify.py sample IMAGE REFDIR", file=sys.stderr)
+ return 2
+ cmd = args[0]
+ if cmd == "listing":
+ return cmd_listing(args[1], args[2])
+ if cmd == "content":
+ return cmd_content(args[1], args[2], limit, do_all, False)
+ if cmd == "sample":
+ return cmd_content(args[1], args[2], limit, False, True)
+ print("verify.py: unknown command %r" % cmd, file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/xnu/files/bsd/miscfs/apfs/apfs_format.h b/xnu/files/bsd/miscfs/apfs/apfs_format.h
new file mode 100644
index 0000000..391df14
--- /dev/null
+++ b/xnu/files/bsd/miscfs/apfs/apfs_format.h
@@ -0,0 +1,755 @@
+/*
+ * APFS on-disk layout, read side.
+ *
+ * Written from Apple's "Apple File System Reference" (2020-06-22), which is the only
+ * description of the format there is. Names and field order follow that document, so
+ * that a reader can hold the two side by side; what the document calls out but we never
+ * read on the way to a file's bytes (the space manager, the reaper, fusion, encryption
+ * rolling, snapshots) is left out rather than copied in unused.
+ *
+ * Everything here is little-endian on disk and is read straight out of a block, so the
+ * structures must match the disk byte for byte. tools/apfs/fmt_check.c prints every
+ * size and field offset in this file and tools/apfs/apfs.py checks its own idea of the
+ * layout against that output -- run tools/apfs/run-tests.sh after touching this file.
+ *
+ * Decompression of file contents (the com.apple.decmpfs attribute) is not part of APFS
+ * and is not in the reference; it is at the end of this file, from bsd/sys/decmpfs.h and
+ * from what the iOS 16.5 root file system actually contains.
+ */
+
+#ifndef _MISCFS_APFS_APFS_FORMAT_H_
+#define _MISCFS_APFS_APFS_FORMAT_H_
+
+#include <stdint.h>
+
+typedef int64_t apfs_paddr_t; /* a block address within the container */
+typedef uint64_t apfs_oid_t; /* an object identifier */
+typedef uint64_t apfs_xid_t; /* a transaction identifier */
+
+/* A run of blocks: pr_block_count blocks starting at pr_start_paddr. */
+struct apfs_prange {
+ apfs_paddr_t pr_start_paddr;
+ uint64_t pr_block_count;
+};
+
+/*
+ * Objects
+ *
+ * Every object that occupies whole blocks starts with this header. o_cksum is
+ * Fletcher-64 over the rest of the block and is the only integrity check we have, so we
+ * verify it on every block we read.
+ */
+#define APFS_MAX_CKSUM_SIZE 8
+
+struct apfs_obj_phys {
+ uint8_t o_cksum[APFS_MAX_CKSUM_SIZE];
+ apfs_oid_t o_oid;
+ apfs_xid_t o_xid;
+ uint32_t o_type; /* storage class and flags in the high half, type in the low */
+ uint32_t o_subtype;
+};
+
+/* o_type: the low half is the type, the high half says how the object is stored */
+#define APFS_OBJECT_TYPE_MASK 0x0000ffff
+#define APFS_OBJECT_TYPE_FLAGS_MASK 0xffff0000
+#define APFS_OBJ_STORAGETYPE_MASK 0xc0000000
+#define APFS_OBJ_VIRTUAL 0x00000000 /* found through an object map */
+#define APFS_OBJ_EPHEMERAL 0x80000000 /* found through a checkpoint map */
+#define APFS_OBJ_PHYSICAL 0x40000000 /* the identifier is the block address */
+#define APFS_OBJ_NOHEADER 0x20000000 /* no apfs_obj_phys at the front */
+#define APFS_OBJ_ENCRYPTED 0x10000000
+#define APFS_OBJ_NONPERSISTENT 0x08000000
+
+#define APFS_OBJECT_TYPE_NX_SUPERBLOCK 0x00000001
+#define APFS_OBJECT_TYPE_BTREE 0x00000002 /* a tree's root node */
+#define APFS_OBJECT_TYPE_BTREE_NODE 0x00000003 /* any other node */
+#define APFS_OBJECT_TYPE_SPACEMAN 0x00000005
+#define APFS_OBJECT_TYPE_SPACEMAN_BITMAP 0x00000008
+#define APFS_OBJECT_TYPE_OMAP 0x0000000b
+#define APFS_OBJECT_TYPE_CHECKPOINT_MAP 0x0000000c
+#define APFS_OBJECT_TYPE_FS 0x0000000d /* a volume superblock */
+#define APFS_OBJECT_TYPE_FSTREE 0x0000000e /* subtype: the file-system tree */
+#define APFS_OBJECT_TYPE_BLOCKREFTREE 0x0000000f /* subtype: the extent reference tree */
+#define APFS_OBJECT_TYPE_SNAPMETATREE 0x00000010
+#define APFS_OBJECT_TYPE_NX_REAPER 0x00000011
+#define APFS_OBJECT_TYPE_EFI_JUMPSTART 0x00000014
+#define APFS_OBJECT_TYPE_INTEGRITY_META 0x0000001e
+#define APFS_OBJECT_TYPE_FEXT_TREE 0x0000001f
+#define APFS_OBJECT_TYPE_INVALID 0x00000000
+
+#define APFS_OID_INVALID 0ULL
+#define APFS_OID_NX_SUPERBLOCK 1ULL
+#define APFS_OID_RESERVED_COUNT 1024
+
+/*
+ * Container
+ *
+ * Block zero holds a copy of the container superblock, but it can be stale. The live one
+ * is the superblock with the largest transaction identifier in the checkpoint descriptor
+ * area (nx_xp_desc_base, nx_xp_desc_blocks blocks long); that copy also names the
+ * checkpoint's extent of descriptor blocks, nx_xp_desc_index..+nx_xp_desc_len.
+ */
+#define APFS_NX_MAGIC 0x4253584e /* 'NXSB', little-endian on disk */
+#define APFS_NX_MAX_FILE_SYSTEMS 100
+#define APFS_NX_EPH_INFO_COUNT 4
+#define APFS_NX_NUM_COUNTERS 32
+#define APFS_NX_DEFAULT_BLOCK_SIZE 4096
+#define APFS_NX_MINIMUM_BLOCK_SIZE 4096
+#define APFS_NX_MAXIMUM_BLOCK_SIZE 65536
+
+struct apfs_nx_superblock {
+ struct apfs_obj_phys nx_o;
+ uint32_t nx_magic;
+ uint32_t nx_block_size;
+ uint64_t nx_block_count;
+
+ uint64_t nx_features;
+ uint64_t nx_readonly_compatible_features;
+ uint64_t nx_incompatible_features;
+
+ uint8_t nx_uuid[16];
+
+ apfs_oid_t nx_next_oid;
+ apfs_xid_t nx_next_xid;
+
+ /* the checkpoint areas: a ring of descriptor blocks and a ring of data blocks */
+ uint32_t nx_xp_desc_blocks;
+ uint32_t nx_xp_data_blocks;
+ apfs_paddr_t nx_xp_desc_base;
+ apfs_paddr_t nx_xp_data_base;
+ uint32_t nx_xp_desc_next;
+ uint32_t nx_xp_data_next;
+ uint32_t nx_xp_desc_index;
+ uint32_t nx_xp_desc_len;
+ uint32_t nx_xp_data_index;
+ uint32_t nx_xp_data_len;
+
+ apfs_oid_t nx_spaceman_oid;
+ apfs_oid_t nx_omap_oid; /* the container's object map, a physical object */
+ apfs_oid_t nx_reaper_oid;
+
+ uint32_t nx_test_type;
+
+ uint32_t nx_max_file_systems;
+ apfs_oid_t nx_fs_oid[APFS_NX_MAX_FILE_SYSTEMS]; /* volume superblocks, virtual */
+ uint64_t nx_counters[APFS_NX_NUM_COUNTERS];
+ struct apfs_prange nx_blocked_out_prange;
+ apfs_oid_t nx_evict_mapping_tree_oid;
+ uint64_t nx_flags;
+ apfs_paddr_t nx_efi_jumpstart;
+ uint8_t nx_fusion_uuid[16];
+ struct apfs_prange nx_keylocker;
+ uint64_t nx_ephemeral_info[APFS_NX_EPH_INFO_COUNT];
+
+ apfs_oid_t nx_test_oid;
+
+ apfs_oid_t nx_fusion_mt_oid;
+ apfs_oid_t nx_fusion_wbc_oid;
+ struct apfs_prange nx_fusion_wbc;
+
+ uint64_t nx_newest_mounted_version;
+
+ struct apfs_prange nx_mkb_locker;
+};
+
+/* nx_incompatible_features: a container we would misread if we ignored these */
+#define APFS_NX_INCOMPAT_VERSION1 0x0000000000000001ULL
+#define APFS_NX_INCOMPAT_VERSION2 0x0000000000000002ULL
+#define APFS_NX_INCOMPAT_FUSION 0x0000000000000100ULL
+
+/*
+ * Checkpoint maps
+ *
+ * Ephemeral objects live in the checkpoint data area rather than at a fixed place, so a
+ * checkpoint's descriptor blocks carry a map from object identifier to block address.
+ * We need this only for the space manager, so the read path mostly skips it.
+ */
+#define APFS_CHECKPOINT_MAP_LAST 0x00000001
+
+struct apfs_checkpoint_mapping {
+ uint32_t cpm_type;
+ uint32_t cpm_subtype;
+ uint32_t cpm_size;
+ uint32_t cpm_pad;
+ apfs_oid_t cpm_fs_oid;
+ apfs_oid_t cpm_oid;
+ apfs_oid_t cpm_paddr;
+};
+
+struct apfs_checkpoint_map_phys {
+ struct apfs_obj_phys cpm_o;
+ uint32_t cpm_flags;
+ uint32_t cpm_count;
+ struct apfs_checkpoint_mapping cpm_map[];
+};
+
+/*
+ * Object maps
+ *
+ * A virtual object identifier means nothing by itself: it has to be looked up in an
+ * object map, which is a B-tree keyed by (identifier, transaction) and whose values give
+ * the block address. The container's map resolves volume superblocks; each volume's map
+ * resolves the nodes of that volume's file-system tree.
+ */
+struct apfs_omap_phys {
+ struct apfs_obj_phys om_o;
+ uint32_t om_flags;
+ uint32_t om_snap_count;
+ uint32_t om_tree_type;
+ uint32_t om_snapshot_tree_type;
+ apfs_oid_t om_tree_oid; /* the map itself, a physical B-tree */
+ apfs_oid_t om_snapshot_tree_oid;
+ apfs_xid_t om_most_recent_snap;
+ apfs_xid_t om_pending_revert_min;
+ apfs_xid_t om_pending_revert_max;
+};
+
+struct apfs_omap_key {
+ apfs_oid_t ok_oid;
+ apfs_xid_t ok_xid;
+};
+
+struct apfs_omap_val {
+ uint32_t ov_flags;
+ uint32_t ov_size;
+ apfs_paddr_t ov_paddr;
+};
+
+#define APFS_OMAP_VAL_DELETED 0x00000001
+#define APFS_OMAP_VAL_SAVED 0x00000002
+#define APFS_OMAP_VAL_ENCRYPTED 0x00000004
+#define APFS_OMAP_VAL_NOHEADER 0x00000008
+#define APFS_OMAP_VAL_CRYPTO_GENERATION 0x00000010
+
+/*
+ * Volumes
+ */
+#define APFS_MAGIC_VOL 0x42535041 /* 'APSB', little-endian on disk */
+#define APFS_MAX_HIST 8
+#define APFS_MODIFIED_NAMELEN 32
+#define APFS_VOLNAME_LEN 256
+
+struct apfs_modified_by {
+ uint8_t id[APFS_MODIFIED_NAMELEN];
+ uint64_t timestamp;
+ apfs_xid_t last_xid;
+};
+
+/* The metadata encryption state; we only read it to check the volume is not encrypted. */
+struct apfs_wrapped_meta_crypto_state {
+ uint16_t major_version;
+ uint16_t minor_version;
+ uint32_t cpflags;
+ uint32_t persistent_class;
+ uint32_t key_os_version;
+ uint16_t key_revision;
+ uint16_t unused;
+} __attribute__((aligned(2), packed));
+
+struct apfs_superblock {
+ struct apfs_obj_phys apfs_o;
+
+ uint32_t apfs_magic;
+ uint32_t apfs_fs_index;
+
+ uint64_t apfs_features;
+ uint64_t apfs_readonly_compatible_features;
+ uint64_t apfs_incompatible_features;
+
+ uint64_t apfs_unmount_time;
+
+ uint64_t apfs_fs_reserve_block_count;
+ uint64_t apfs_fs_quota_block_count;
+ uint64_t apfs_fs_alloc_count;
+
+ struct apfs_wrapped_meta_crypto_state apfs_meta_crypto;
+
+ uint32_t apfs_root_tree_type;
+ uint32_t apfs_extentref_tree_type;
+ uint32_t apfs_snap_meta_tree_type;
+
+ apfs_oid_t apfs_omap_oid; /* this volume's object map, physical */
+ apfs_oid_t apfs_root_tree_oid; /* the file-system tree, virtual */
+ apfs_oid_t apfs_extentref_tree_oid;
+ apfs_oid_t apfs_snap_meta_tree_oid;
+
+ apfs_xid_t apfs_revert_to_xid;
+ apfs_oid_t apfs_revert_to_sblock_oid;
+
+ uint64_t apfs_next_obj_id;
+
+ uint64_t apfs_num_files;
+ uint64_t apfs_num_directories;
+ uint64_t apfs_num_symlinks;
+ uint64_t apfs_num_other_fsobjects;
+ uint64_t apfs_num_snapshots;
+
+ uint64_t apfs_total_blocks_alloced;
+ uint64_t apfs_total_blocks_freed;
+
+ uint8_t apfs_vol_uuid[16];
+ uint64_t apfs_last_mod_time;
+
+ uint64_t apfs_fs_flags;
+
+ struct apfs_modified_by apfs_formatted_by;
+ struct apfs_modified_by apfs_modified_by[APFS_MAX_HIST];
+
+ uint8_t apfs_volname[APFS_VOLNAME_LEN];
+ uint32_t apfs_next_doc_id;
+
+ uint16_t apfs_role;
+ uint16_t reserved;
+
+ apfs_xid_t apfs_root_to_xid;
+ apfs_oid_t apfs_er_state_oid;
+
+ uint64_t apfs_cloneinfo_id_epoch;
+ uint64_t apfs_cloneinfo_xid;
+
+ apfs_oid_t apfs_snap_meta_ext_oid;
+
+ uint8_t apfs_volume_group_id[16];
+
+ apfs_oid_t apfs_integrity_meta_oid;
+
+ apfs_oid_t apfs_fext_tree_oid;
+ uint32_t apfs_fext_tree_type;
+
+ uint32_t reserved_type;
+ apfs_oid_t reserved_oid;
+};
+
+/* apfs_incompatible_features: these change how we read names and extents */
+#define APFS_INCOMPAT_CASE_INSENSITIVE 0x00000001ULL
+#define APFS_INCOMPAT_DATALESS_SNAPS 0x00000002ULL
+#define APFS_INCOMPAT_ENC_ROLLED 0x00000004ULL
+#define APFS_INCOMPAT_NORMALIZATION_INSENSITIVE 0x00000008ULL
+#define APFS_INCOMPAT_INCOMPLETE_RESTORE 0x00000010ULL
+#define APFS_INCOMPAT_SEALED_VOLUME 0x00000020ULL
+
+/* apfs_fs_flags */
+#define APFS_FS_UNENCRYPTED 0x00000001ULL
+#define APFS_FS_ONEKEY 0x00000008ULL
+#define APFS_FS_SPILLEDOVER 0x00000010ULL
+
+/* apfs_role */
+#define APFS_VOL_ROLE_NONE 0x0000
+#define APFS_VOL_ROLE_SYSTEM 0x0001
+#define APFS_VOL_ROLE_USER 0x0002
+#define APFS_VOL_ROLE_RECOVERY 0x0004
+#define APFS_VOL_ROLE_VM 0x0008
+#define APFS_VOL_ROLE_PREBOOT 0x0010
+#define APFS_VOL_ROLE_INSTALLER 0x0020
+#define APFS_VOLUME_ENUM_SHIFT 6
+#define APFS_VOL_ROLE_DATA (1 << APFS_VOLUME_ENUM_SHIFT)
+#define APFS_VOL_ROLE_BASEBAND (2 << APFS_VOLUME_ENUM_SHIFT)
+#define APFS_VOL_ROLE_UPDATE (3 << APFS_VOLUME_ENUM_SHIFT)
+#define APFS_VOL_ROLE_XART (4 << APFS_VOLUME_ENUM_SHIFT)
+#define APFS_VOL_ROLE_HARDWARE (5 << APFS_VOLUME_ENUM_SHIFT)
+#define APFS_VOL_ROLE_BACKUP (6 << APFS_VOLUME_ENUM_SHIFT)
+
+/*
+ * B-trees
+ *
+ * Every tree is one of these node blocks. A node is laid out as: the header, then a
+ * table of contents, then keys growing from the start of the key area forward, then free
+ * space, then values growing from the end of the block backwards. A root node keeps a
+ * struct apfs_btree_info in the last bytes of the block, so the value area of a root node
+ * stops short of it.
+ *
+ * Two layouts of the table of contents: with BTNODE_FIXED_KV_SIZE every key and value is
+ * the same size and an entry is a struct apfs_kvoff (offsets only); otherwise an entry is
+ * a struct apfs_kvloc (offset and length for each).
+ *
+ * Offsets in the table of contents are relative to the start of the key area for keys,
+ * and backwards from the end of the value area for values.
+ */
+#define APFS_BTNODE_ROOT 0x0001
+#define APFS_BTNODE_LEAF 0x0002
+#define APFS_BTNODE_FIXED_KV_SIZE 0x0004
+#define APFS_BTNODE_HASHED 0x0008
+#define APFS_BTNODE_NOHEADER 0x0010
+#define APFS_BTNODE_CHECK_KOFF_INVAL 0x8000
+
+#define APFS_BTOFF_INVALID 0xffff
+
+struct apfs_nloc { /* a location inside a node: offset and length */
+ uint16_t off;
+ uint16_t len;
+};
+
+struct apfs_kvloc { /* a table-of-contents entry, variable sizes */
+ struct apfs_nloc k;
+ struct apfs_nloc v;
+};
+
+struct apfs_kvoff { /* a table-of-contents entry, fixed sizes */
+ uint16_t k;
+ uint16_t v;
+};
+
+struct apfs_btree_node_phys {
+ struct apfs_obj_phys btn_o;
+ uint16_t btn_flags;
+ uint16_t btn_level; /* 0 at the leaves */
+ uint32_t btn_nkeys;
+ struct apfs_nloc btn_table_space; /* the table of contents, within btn_data */
+ struct apfs_nloc btn_free_space; /* the gap between keys and values */
+ struct apfs_nloc btn_key_free_list;
+ struct apfs_nloc btn_val_free_list;
+ uint64_t btn_data[];
+};
+
+#define APFS_BTREE_UINT64_KEYS 0x00000001
+#define APFS_BTREE_SEQUENTIAL_INSERT 0x00000002
+#define APFS_BTREE_ALLOW_GHOSTS 0x00000004
+#define APFS_BTREE_EPHEMERAL 0x00000008
+#define APFS_BTREE_PHYSICAL 0x00000010 /* child identifiers are block addresses */
+#define APFS_BTREE_NONPERSISTENT 0x00000020
+#define APFS_BTREE_KV_NONALIGNED 0x00000040
+#define APFS_BTREE_HASHED 0x00000080
+#define APFS_BTREE_NOHEADER 0x00000100
+
+#define APFS_BTREE_NODE_HASH_SIZE_MAX 64
+#define APFS_BTREE_NODE_SIZE_DEFAULT 4096
+
+struct apfs_btree_info_fixed {
+ uint32_t bt_flags;
+ uint32_t bt_node_size;
+ uint32_t bt_key_size; /* zero unless the keys are a fixed size */
+ uint32_t bt_val_size;
+};
+
+struct apfs_btree_info {
+ struct apfs_btree_info_fixed bt_fixed;
+ uint32_t bt_longest_key;
+ uint32_t bt_longest_val;
+ uint64_t bt_key_count;
+ uint64_t bt_node_count;
+};
+
+/* The value of a non-leaf entry: the child's identifier, and its hash on a sealed volume. */
+struct apfs_btn_index_node_val {
+ apfs_oid_t binv_child_oid;
+ uint8_t binv_child_hash[APFS_BTREE_NODE_HASH_SIZE_MAX];
+};
+
+/*
+ * File-system objects
+ *
+ * A volume's file-system tree holds every kind of record in one tree, keyed by the
+ * identifier of the object the record belongs to and the kind of record. Records sort by
+ * identifier first and kind second, so all the records of one file are together and the
+ * kinds within a file are in the order of the APFS_TYPE_* numbers.
+ */
+struct apfs_j_key {
+ uint64_t obj_id_and_type; /* kind in the top four bits, identifier in the rest */
+} __attribute__((packed));
+
+#define APFS_OBJ_ID_MASK 0x0fffffffffffffffULL
+#define APFS_OBJ_TYPE_MASK 0xf000000000000000ULL
+#define APFS_OBJ_TYPE_SHIFT 60
+
+#define APFS_TYPE_ANY 0
+#define APFS_TYPE_SNAP_METADATA 1
+#define APFS_TYPE_EXTENT 2
+#define APFS_TYPE_INODE 3
+#define APFS_TYPE_XATTR 4
+#define APFS_TYPE_SIBLING_LINK 5
+#define APFS_TYPE_DSTREAM_ID 6
+#define APFS_TYPE_CRYPTO_STATE 7
+#define APFS_TYPE_FILE_EXTENT 8
+#define APFS_TYPE_DIR_REC 9
+#define APFS_TYPE_DIR_STATS 10
+#define APFS_TYPE_SNAP_NAME 11
+#define APFS_TYPE_SIBLING_MAP 12
+#define APFS_TYPE_FILE_INFO 13
+#define APFS_TYPE_MAX_VALID 13
+#define APFS_TYPE_INVALID 15
+
+#define APFS_INVALID_INO_NUM 0
+#define APFS_ROOT_DIR_PARENT 1
+#define APFS_ROOT_DIR_INO_NUM 2
+#define APFS_PRIV_DIR_INO_NUM 3
+#define APFS_SNAP_DIR_INO_NUM 6
+#define APFS_PURGEABLE_DIR_INO_NUM 7
+#define APFS_MIN_USER_INO_NUM 16
+
+/* inode */
+struct apfs_j_inode_key {
+ struct apfs_j_key hdr;
+} __attribute__((packed));
+
+struct apfs_j_inode_val {
+ uint64_t parent_id;
+ uint64_t private_id; /* the data stream's identifier, for a regular file */
+
+ uint64_t create_time; /* nanoseconds since the Unix epoch */
+ uint64_t mod_time;
+ uint64_t change_time;
+ uint64_t access_time;
+
+ uint64_t internal_flags;
+
+ union {
+ int32_t nchildren; /* a directory */
+ int32_t nlink; /* anything else */
+ };
+
+ uint32_t default_protection_class;
+ uint32_t write_generation_counter;
+ uint32_t bsd_flags;
+ uint32_t owner;
+ uint32_t group;
+ uint16_t mode;
+ uint16_t pad1;
+ uint64_t uncompressed_size; /* only with INODE_HAS_UNCOMPRESSED_SIZE */
+ uint8_t xfields[]; /* a struct apfs_xf_blob, if there is anything in it */
+} __attribute__((packed));
+
+#define APFS_INODE_IS_APFS_PRIVATE 0x00000001
+#define APFS_INODE_MAINTAIN_DIR_STATS 0x00000002
+#define APFS_INODE_DIR_STATS_ORIGIN 0x00000004
+#define APFS_INODE_PROT_CLASS_EXPLICIT 0x00000008
+#define APFS_INODE_WAS_CLONED 0x00000010
+#define APFS_INODE_HAS_SECURITY_EA 0x00000040
+#define APFS_INODE_BEING_TRUNCATED 0x00000080
+#define APFS_INODE_HAS_FINDER_INFO 0x00000100
+#define APFS_INODE_IS_SPARSE 0x00000200
+#define APFS_INODE_WAS_EVER_CLONED 0x00000400
+#define APFS_INODE_ACTIVE_FILE_TRIMMED 0x00000800
+#define APFS_INODE_PINNED_TO_MAIN 0x00001000
+#define APFS_INODE_PINNED_TO_TIER2 0x00002000
+#define APFS_INODE_HAS_RSRC_FORK 0x00004000
+#define APFS_INODE_NO_RSRC_FORK 0x00008000
+#define APFS_INODE_ALLOCATION_SPILLEDOVER 0x00010000
+#define APFS_INODE_FAST_PROMOTE 0x00020000
+#define APFS_INODE_HAS_UNCOMPRESSED_SIZE 0x00040000
+#define APFS_INODE_IS_PURGEABLE 0x00080000
+#define APFS_INODE_WANTS_TO_BE_PURGEABLE 0x00100000
+#define APFS_INODE_IS_SYNC_ROOT 0x00200000
+#define APFS_INODE_SNAPSHOT_COW_EXEMPTION 0x00400000
+
+/* directory entry. iOS uses the hashed key; the hash is of the name, case-folded. */
+struct apfs_j_drec_key {
+ struct apfs_j_key hdr;
+ uint16_t name_len; /* including the trailing zero byte */
+ uint8_t name[0];
+} __attribute__((packed));
+
+struct apfs_j_drec_hashed_key {
+ struct apfs_j_key hdr;
+ uint32_t name_len_and_hash;
+ uint8_t name[0];
+} __attribute__((packed));
+
+#define APFS_J_DREC_LEN_MASK 0x000003ff
+#define APFS_J_DREC_HASH_MASK 0xfffff400
+#define APFS_J_DREC_HASH_SHIFT 10
+
+struct apfs_j_drec_val {
+ uint64_t file_id; /* the identifier of the inode this entry names */
+ uint64_t date_added;
+ uint16_t flags; /* the file kind, DT_*, in the low four bits */
+ uint8_t xfields[];
+} __attribute__((packed));
+
+#define APFS_DREC_TYPE_MASK 0x000f
+
+/* d_type values, as in a directory entry */
+#define APFS_DT_UNKNOWN 0
+#define APFS_DT_FIFO 1
+#define APFS_DT_CHR 2
+#define APFS_DT_DIR 4
+#define APFS_DT_BLK 6
+#define APFS_DT_REG 8
+#define APFS_DT_LNK 10
+#define APFS_DT_SOCK 12
+#define APFS_DT_WHT 14
+
+/* directory statistics, on directories that keep them */
+struct apfs_j_dir_stats_val {
+ uint64_t num_children;
+ uint64_t total_size;
+ uint64_t chained_key;
+ uint64_t gen_count;
+} __attribute__((packed));
+
+/* extended attribute. A symbolic link's target is the com.apple.fs.symlink attribute. */
+struct apfs_j_xattr_key {
+ struct apfs_j_key hdr;
+ uint16_t name_len; /* including the trailing zero byte */
+ uint8_t name[0];
+} __attribute__((packed));
+
+struct apfs_j_xattr_val {
+ uint16_t flags;
+ uint16_t xdata_len;
+ uint8_t xdata[0]; /* the value, or a struct apfs_j_xattr_dstream */
+} __attribute__((packed));
+
+#define APFS_XATTR_DATA_STREAM 0x00000001 /* xdata is an apfs_j_xattr_dstream */
+#define APFS_XATTR_DATA_EMBEDDED 0x00000002 /* xdata is the value itself */
+#define APFS_XATTR_FILE_SYSTEM_OWNED 0x00000004
+#define APFS_XATTR_MAX_EMBEDDED_SIZE 3804
+
+#define APFS_SYMLINK_EA_NAME "com.apple.fs.symlink"
+#define APFS_FIRMLINK_EA_NAME "com.apple.fs.firmlink"
+
+/* data stream: the size of a file's contents, and what has been written */
+struct apfs_j_dstream {
+ uint64_t size; /* the logical size, what stat reports */
+ uint64_t alloced_size; /* rounded up to whole blocks */
+ uint64_t default_crypto_id;
+ uint64_t total_bytes_written;
+ uint64_t total_bytes_read;
+} __attribute__((aligned(8), packed));
+
+struct apfs_j_xattr_dstream {
+ uint64_t xattr_obj_id;
+ struct apfs_j_dstream dstream;
+};
+
+struct apfs_j_dstream_id_val {
+ uint32_t refcnt;
+} __attribute__((packed));
+
+/*
+ * file extent: one run of blocks of a file's contents.
+ *
+ * The key's logical_addr is the byte offset within the file, always a whole number of
+ * blocks. A file can have gaps between its extents -- that is a sparse file, and the gap
+ * reads as zeros. phys_block_num zero means a hole as well.
+ */
+struct apfs_j_file_extent_key {
+ struct apfs_j_key hdr;
+ uint64_t logical_addr;
+} __attribute__((packed));
+
+struct apfs_j_file_extent_val {
+ uint64_t len_and_flags; /* length in bytes in the low 56 bits */
+ uint64_t phys_block_num;
+ uint64_t crypto_id;
+} __attribute__((packed));
+
+#define APFS_J_FILE_EXTENT_LEN_MASK 0x00ffffffffffffffULL
+#define APFS_J_FILE_EXTENT_FLAG_MASK 0xff00000000000000ULL
+#define APFS_J_FILE_EXTENT_FLAG_SHIFT 56
+
+/* physical extent, from the extent reference tree */
+struct apfs_j_phys_ext_val {
+ uint64_t len_and_kind; /* block count in the low 60 bits, kind in the top four */
+ uint64_t owning_obj_id;
+ int32_t refcnt;
+} __attribute__((packed));
+
+#define APFS_PEXT_LEN_MASK 0x0fffffffffffffffULL
+#define APFS_PEXT_KIND_MASK 0xf000000000000000ULL
+#define APFS_PEXT_KIND_SHIFT 60
+
+/* hard links: the names an inode is known by */
+struct apfs_j_sibling_key {
+ struct apfs_j_key hdr;
+ uint64_t sibling_id;
+} __attribute__((packed));
+
+struct apfs_j_sibling_val {
+ uint64_t parent_id;
+ uint16_t name_len;
+ uint8_t name[0];
+} __attribute__((packed));
+
+struct apfs_j_sibling_map_val {
+ uint64_t file_id;
+} __attribute__((packed));
+
+/*
+ * Extended fields
+ *
+ * The variable part at the end of an inode or a directory entry: a blob header, then that
+ * many struct apfs_x_field describing the pieces, then the pieces themselves, each padded
+ * out to a multiple of eight bytes.
+ */
+struct apfs_xf_blob {
+ uint16_t xf_num_exts;
+ uint16_t xf_used_data;
+ uint8_t xf_data[];
+};
+
+struct apfs_x_field {
+ uint8_t x_type;
+ uint8_t x_flags;
+ uint16_t x_size;
+};
+
+#define APFS_INO_EXT_TYPE_SNAP_XID 1
+#define APFS_INO_EXT_TYPE_DELTA_TREE_OID 2
+#define APFS_INO_EXT_TYPE_DOCUMENT_ID 3
+#define APFS_INO_EXT_TYPE_NAME 4 /* the name of a hard-linked inode */
+#define APFS_INO_EXT_TYPE_PREV_FSIZE 5
+#define APFS_INO_EXT_TYPE_FINDER_INFO 7
+#define APFS_INO_EXT_TYPE_DSTREAM 8 /* a struct apfs_j_dstream */
+#define APFS_INO_EXT_TYPE_DIR_STATS_KEY 10
+#define APFS_INO_EXT_TYPE_FS_UUID 11
+#define APFS_INO_EXT_TYPE_SPARSE_BYTES 13
+#define APFS_INO_EXT_TYPE_RDEV 14 /* a device number */
+#define APFS_INO_EXT_TYPE_PURGEABLE_FLAGS 15
+#define APFS_INO_EXT_TYPE_ORIG_SYNC_ROOT_ID 16
+
+#define APFS_DREC_EXT_TYPE_SIBLING_ID 1
+
+#define APFS_XF_DATA_DEPENDENT 0x0001
+#define APFS_XF_DO_NOT_COPY 0x0002
+#define APFS_XF_CHILDREN_INHERIT 0x0008
+
+/* file mode bits, as APFS stores them */
+#define APFS_S_IFMT 0170000
+#define APFS_S_IFIFO 0010000
+#define APFS_S_IFCHR 0020000
+#define APFS_S_IFDIR 0040000
+#define APFS_S_IFBLK 0060000
+#define APFS_S_IFREG 0100000
+#define APFS_S_IFLNK 0120000
+#define APFS_S_IFSOCK 0140000
+#define APFS_S_IFWHT 0160000
+
+/*
+ * Compressed file contents
+ *
+ * Not part of APFS and not in Apple's reference. A compressed file carries the attribute
+ * com.apple.decmpfs, whose value starts with this header; where the compressed bytes
+ * themselves are depends on the type. The header is little-endian.
+ *
+ * XNU (bsd/sys/decmpfs.h) names only type 1; the rest live in Apple's closed
+ * AppleFSCompression. The types below are the ones the iOS 16.5 root file system
+ * actually uses -- see tools/apfs/apfs.py, which counts them over the whole volume.
+ *
+ * In the attribute (types 3 and 4 the common pair): the bytes after the header are a
+ * single zlib stream, except that a first byte of 0xff means the rest is the uncompressed
+ * contents as they are. In the resource fork (the com.apple.ResourceFork attribute): the
+ * contents are cut into 64 KB pieces, each its own zlib stream, with a table of their
+ * offsets at the front.
+ */
+#define APFS_DECMPFS_XATTR_NAME "com.apple.decmpfs"
+#define APFS_DECMPFS_MAGIC 0x636d7066 /* 'cmpf' */
+#define APFS_RSRC_FORK_XATTR_NAME "com.apple.ResourceFork"
+
+struct apfs_decmpfs_disk_header {
+ uint32_t compression_magic;
+ uint32_t compression_type;
+ uint64_t uncompressed_size;
+ uint8_t attr_bytes[0];
+} __attribute__((packed));
+
+#define APFS_DECMPFS_TYPE_ZLIB_ATTR 3 /* zlib, bytes in the attribute */
+#define APFS_DECMPFS_TYPE_ZLIB_RSRC 4 /* zlib, bytes in the resource fork */
+#define APFS_DECMPFS_TYPE_RAW_ATTR 9 /* uncompressed, bytes in the attribute */
+#define APFS_DECMPFS_TYPE_RAW_RSRC 10 /* uncompressed, bytes in the resource fork */
+#define APFS_DECMPFS_TYPE_LZFSE_ATTR 11
+#define APFS_DECMPFS_TYPE_LZFSE_RSRC 12
+
+/* the pieces a resource-fork-compressed file is cut into */
+#define APFS_DECMPFS_BLOCK_SIZE 65536
+
+#endif /* _MISCFS_APFS_APFS_FORMAT_H_ */