SQLite 溢出页边界:载荷多一个字节,本页保留量为何骤降

10-10 5阅读

SQLite 溢出页边界:载荷多一个字节,本页保留量为何骤降

配图为模型生成的概念示意,非真实数据库截图。

在五百一十二字节页的 SQLite 文件里,一条记录的总载荷从 477 增至 478 字节,本页保留的载荷可能从 477 降到 39。多出的数据并不是简单“塞到页满为止,再写下一页”。若离线工具用 min(载荷大小, 本页上限) 推测边界,就会在错误的位置读取溢出页指针。

一、先分清载荷、可用页大小和页类型

本文只讨论普通 rowid 表的表 B-tree 叶子单元,即页类型 0x0d。依据官方文件格式第 1.6 节,P 表示整个单元的载荷字节数,包含记录头,不等于某个 SQL BLOB 的长度。U 是页大小减去页尾保留区的字节数;不要再从 U 中扣除 B-tree 页头或第一页的数据库头。

索引页使用不同上限;WITHOUT ROWID 表采用索引 B-tree,也不能直接套用下述表叶子公式。这里的边界由文件格式决定,不是看当前页还剩多少空闲空间再临时选择。解释单元之前,应先确认页类型。

二、超过上限后,还要计算余数

先令 X=U-35。P 不超过 X 时,载荷全部保存在本页;否则先计算 M=((U-12)*32)//255-23,再计算 K=M+(P-M)%(U-4)。K 不超过 X 就保留 K,否则退回 M。除法必须向下取整,不能使用浮点四舍五入。

当 U=512 时,X=477、M=39、每个溢出页最多承载 508 字节。P=478 算得 K=478,超过 X,所以只留下 39;P=985 算得 K=477,留下 477 后正好溢出 508;P=986 又退回 39。这个周期性跳变正是简单取最小值算法无法表达的部分。

三、用真实数据库核对,而非只验算公式

下面的完整脚本先提供纯整数计算函数,再用标准库 sqlite3 创建六个临时数据库。按page_size 设置规则,在建表前指定页大小;每个数据库只有一行、一个 BLOB,并在提交和关闭连接后读取文件快照,避免把仍在 WAL 中的数据误当作主文件内容。

from pathlib import Path
import sqlite3
import tempfile
import unittest

BUDGET = 1 << 20


def local_payload(payload_size, usable_size):
    """Table b-tree leaf cells only, not index or WITHOUT ROWID cells."""
    if type(payload_size) is not int or type(usable_size) is not int:
        raise TypeError("sizes must be integers, not bool")
    if not 0 <= payload_size <= BUDGET or not 480 <= usable_size <= 65536:
        raise ValueError("invalid usable size or local payload budget exceeded")
    maximum = usable_size - 35
    if payload_size <= maximum:
        return payload_size
    minimum = ((usable_size - 12) * 32) // 255 - 23
    candidate = minimum + (payload_size - minimum) % (usable_size - 4)
    return candidate if candidate <= maximum else minimum


def varint(data, offset, end):
    value = 0
    for i in range(9):
        if offset >= end:
            raise ValueError("truncated varint")
        byte = data[offset]
        offset += 1
        if i == 8:
            return (value << 8) | byte, offset
        value = (value << 7) | (byte & 127)
        if byte < 128:
            return value, offset
    raise AssertionError("unreachable")


def read_fixture(data, root):
    """Only our closed 512-byte-page, one-cell, rowid=1 fixture snapshot."""
    if type(data) is not bytes or len(data) > BUDGET:
        raise ValueError("fixture must be bounded bytes")
    if len(data) < 1024 or len(data) % 512:
        raise ValueError("truncated fixture")
    if data[:16] != b"SQLite format 3\x00" or data[16:18] != b"\x02\x00" or data[20]:
        raise ValueError("fixture requires 512-byte pages and zero reserved bytes")
    pages = len(data) // 512
    if type(root) is not int or not 2 <= root <= pages:
        raise ValueError("invalid fixture root")
    start = (root - 1) * 512
    if data[start] != 13 or int.from_bytes(data[start + 3:start + 5], "big") != 1:
        raise ValueError("fixture requires one table leaf cell")
    cell = int.from_bytes(data[start + 8:start + 10], "big")
    if not 10 <= cell < 512:
        raise ValueError("cell offset out of bounds")
    size, pos = varint(data, start + cell, start + 512)
    rowid, pos = varint(data, pos, start + 512)
    if rowid != 1:
        raise ValueError("fixture rowid must be 1")
    local = local_payload(size, 512)
    spill = size > local
    if pos + local + (4 if spill else 0) > start + 512:
        raise ValueError("cell extends past page")
    result = bytearray(data[pos:pos + local])
    page = int.from_bytes(data[pos + local:pos + local + 4], "big") if spill else 0
    seen, chain = {1, root}, []
    while len(result) < size:
        if not 1 <= page <= pages or page in seen:
            raise ValueError("invalid or cyclic overflow chain")
        seen.add(page)
        chain.append(page)
        begin = (page - 1) * 512
        following = int.from_bytes(data[begin:begin + 4], "big")
        count = min(508, size - len(result))
        result.extend(data[begin + 4:begin + 4 + count])
        page = following
    if page:
        raise ValueError("overflow chain continues after payload")
    return size, local, bytes(result), chain


def fixture(payload_size):
    # All selected sizes below have a three-byte one-BLOB record header.
    blob = bytes(i % 251 for i in range(payload_size - 3))
    with tempfile.TemporaryDirectory() as folder:
        path = Path(folder) / "sample.db"
        db = sqlite3.connect(path)
        try:
            db.execute("PRAGMA page_size=512")
            db.execute("PRAGMA journal_mode=DELETE")
            db.execute("CREATE TABLE t(b BLOB)")
            db.execute("INSERT INTO t(rowid,b) VALUES(1,?)", (blob,))
            db.commit()
            root = db.execute("SELECT rootpage FROM sqlite_schema WHERE name='t'").fetchone()[0]
            if db.execute("SELECT b FROM t").fetchone()[0] != blob:
                raise AssertionError("SQLite round trip failed")
        finally:
            db.close()
        return path.read_bytes(), root, blob


class PayloadTests(unittest.TestCase):
    def test_threshold_drop(self):
        self.assertEqual(local_payload(477, 512), 477)
        self.assertEqual(local_payload(478, 512), 39)
        self.assertEqual(local_payload(985, 512), 477)
        self.assertEqual(local_payload(986, 512), 39)

    def test_invalid_arguments(self):
        for p, u in ((-1, 512), (BUDGET + 1, 512), (1, 479), (1, 65537)):
            with self.assertRaises(ValueError):
                local_payload(p, u)
        for p, u in ((True, 512), (1, False), (1.0, 512)):
            with self.assertRaises(TypeError):
                local_payload(p, u)

    def test_usable_size_and_zero_payload(self):
        for u in (480, 511, 512, 4096, 65536):
            self.assertEqual(local_payload(0, u), 0)
            self.assertEqual(local_payload(u - 35, u), u - 35)

    def test_real_sqlite_files(self):
        for size in (477, 478, 547, 985, 986, 1500):
            data, root, blob = fixture(size)
            total, local, record, chain = read_fixture(data, root)
            self.assertEqual(total, size)
            header, pos = varint(record, 0, len(record))
            serial, pos = varint(record, pos, header)
            self.assertEqual((header, pos, serial), (3, 3, 12 + 2 * len(blob)))
            self.assertEqual(record[header:], blob)
            self.assertEqual(len(chain), (size - local + 507) // 508)
            print("SQLite fixture: P={}, local={}, overflow_pages={}".format(
                size, local, len(chain)))

    def test_truncated_file(self):
        data, root, _ = fixture(478)
        for damaged in (data[:-1], data[:512], b"x" * 1024):
            with self.assertRaises(ValueError):
                read_fixture(damaged, root)

    def test_cycle_and_early_chain_end(self):
        data, root, _ = fixture(986)
        _, _, _, chain = read_fixture(data, root)
        for following in (chain[0], 0, len(data) // 512 + 1):
            damaged = bytearray(data)
            pos = (chain[0] - 1) * 512
            damaged[pos:pos + 4] = following.to_bytes(4, "big")
            with self.assertRaises(ValueError):
                read_fixture(bytes(damaged), root)

    def test_chain_too_long(self):
        data, root, _ = fixture(478)
        _, _, _, chain = read_fixture(data, root)
        damaged = bytearray(data)
        pos = (chain[-1] - 1) * 512
        damaged[pos:pos + 4] = root.to_bytes(4, "big")
        with self.assertRaises(ValueError):
            read_fixture(bytes(damaged), root)

    def test_bad_page_kind_and_cell_pointer(self):
        data, root, _ = fixture(477)
        start = (root - 1) * 512
        for offset, replacement in ((start, b"\x0a"), (start + 8, b"\x01\xff")):
            damaged = bytearray(data)
            damaged[offset:offset + len(replacement)] = replacement
            with self.assertRaises(ValueError):
                read_fixture(bytes(damaged), root)

    def test_formula_invariants(self):
        count = 0
        for usable in (480, 511, 512, 4096, 65536):
            minimum = ((usable - 12) * 32) // 255 - 23
            for size in range(10000):
                local = local_payload(size, usable)
                if size <= usable - 35:
                    self.assertEqual(local, size)
                else:
                    self.assertTrue(minimum <= local <= usable - 35)
                    self.assertTrue(local == minimum or (size - local) % (usable - 4) == 0)
                count += 1
        print("formula invariant cases:", count, "PASS")


if __name__ == "__main__":
    print("SQLite runtime:", sqlite3.sqlite_version)
    unittest.main(verbosity=2)

四、指针占四字节,但不属于载荷

本页载荷之后仅在发生溢出时存在四字节页号,采用大端。官方格式第 1.7 节还规定,每个溢出页开头四字节指向下一页,尾页用零结束;后面才存载荷。因此重组时应按剩余字节数截取,不能把指针或末页未使用空间拼进记录。

实跑使用 SQLite 3.53.1,九项测试全部通过,并检查五万组公式性质。六个真实文件分别覆盖无溢出、刚越界、恰满溢出页与多页链;重组后还核对记录头中的 BLOB 类型及原始内容。反例覆盖文件截断、错误页类型、单元越界、提前结束、循环页链及多余后继页。

read_fixture 刻意只接受五百一十二字节页、无保留区、已知根页上的单一叶子单元与 rowid=1,并设置一兆字节预算。计算函数支持合法 U 数值范围,但不负责证明页大小与保留区组合有效;输入 U 应来自已验证的元数据。本例不遍历整棵树、不处理 WAL,也不是通用数据库恢复工具。

实务中先用页类型选公式,再定位本地载荷和溢出指针,最后按总 P 约束重组长度。这样既能解释存储突变,也能减少因边界算错而误读页号的风险。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。