D-Bus 空数组为什么仍可能有填充:at 的长度字段与绝对偏移实测
配图为AI生成概念示意,非真实截图。
一个 D-Bus 数组没有元素,长度字段已经写成 0,为什么解析器还要向前移动?答案取决于元素类型和当前偏移。对于 UINT64 数组 at,从 8 字节边界开始编码时,四字节长度后仍有四字节填充;从偏移 4 开始时,长度字段结束后刚好对齐,便不需要这四字节。
因此“空数组总占八字节”和“长度为零就立刻结束”都不适合作为解析规则。本文只研究 at 的线格式,用六个固定十六进制向量和 96 组偏移组合验证这一点。
1. 数组有两个不同的对齐要求
D-Bus 官方规范的 Marshaling 章节规定对齐以消息开始位置为基准。数组先按 4 字节边界存放 UINT32 长度,再根据元素类型调整首元素起点。UINT64 类型 t 要求 8 字节对齐,at 就是这种元素组成的数组。
这里的长度 n 表示元素编码区的字节数,不是元素数量,也不包含长度字段到首元素起点之间的填充。对本文固定宽度的 at,n 等于元素数乘以 8。不要把这个公式推广到字符串数组等可变宽类型。
2. 用偏移 0 和 4 拆解空数组
下面的 0 和 4 都是相对于整个消息起点的绝对偏移。示意图不是完整 D-Bus 消息:没有消息固定头、字段数组或有效消息类型,只画出正在研究的 body 片段。
情况 A:数组从绝对偏移 0 开始 [0..3] 00 00 00 00 n = 0 [4..7] 00 00 00 00 对齐到 8,即使没有元素也保留 [8] 下一个值可以开始 情况 B:数组从绝对偏移 4 开始 [4..7] 00 00 00 00 n = 0,结束位置已经对齐到 8 [8] 下一个值可以开始
A 的数组编码片段长 8 字节,B 只有 4 字节;两者的 n 都是零。这个差异来自起点,而非字节序。真实 D-Bus body 从 8 字节边界开始,所以测试从 0 起的片段也可以平移到其他 8 的倍数,保持相同的对齐关系。
3. 非空数组也不能把填充计入 n
从偏移 0 写入一个值 5,小端编码如下:
08 00 00 00 | 00 00 00 00 | 05 00 00 00 00 00 00 00 长度 n=8 对齐填充4字节 UINT64元素8字节
数组片段共 16 字节,但 n 仍是 8。若误把填充算进 n,就会让接收端多读四字节,将后一个字段吞进数组。测试在数组后追加 7F 作为 BYTE 哨兵,因为 BYTE 不需要额外对齐;解码完数组后,返回位置必须恰好指向这个哨兵。
大端情况下 n 编成 00 00 00 08,值 5 编成七个零再接 05;填充位置不因大小端改变。对齐与整数端序应分别处理。
4. 编码与解码都按绝对位置计算
计算需要补的零字节数可以写成 (-position) % alignment。先对齐到 4,读写长度;再对齐到 8,读写元素区。第二次对齐不应包在 if n > 0 分支里,因为空数组同样要求执行。
不要把数组切片开头当成新的绝对零点。本例 encode_at 明确接收 start,decode_at 接收包含前缀占位字节的数据以及绝对位置 pos。它们便能区分偏移 0 与 4 的情况。
5. 完整可复制的 Python 实验
保存为 test.py,执行 python3 test.py。代码使用 Python 3.9 或更高版本及标准库,不连接系统总线或会话总线,也不会发送消息。它只是 at body 片段的演示器,不实现完整 D-Bus 消息、类型签名解析、鉴权或其他容器。
协议规定数组长度最多 64 MiB;示例额外采用 1 MiB 的教学资源上限。该较小限制是代码策略,并非修改协议。解码器在分配元素列表前检查长度、8 的倍数约束、填充零值和输入剩余空间。
"""D-Bus body fragment demo, restricted to at (array of UINT64).
Positions are absolute offsets in the message; prefix bytes are placeholders.
Python 3.9+, standard library only. No bus connection is made.
"""
import struct
ARRAY_LIMIT = 1 << 26
DEMO_LIMIT = 1 << 20
def pad_count(pos, alignment):
return (-pos) % alignment
def encode_at(values, start, endian):
if endian not in ('<', '>') or start < 0:
raise ValueError('bad endian or start')
n = len(values) * 8
if n > min(ARRAY_LIMIT, DEMO_LIMIT):
raise ValueError('array exceeds size policy')
out = bytearray(b'\x00' * pad_count(start, 4))
out.extend(struct.pack(endian + 'I', n))
out.extend(b'\x00' * pad_count(start + len(out), 8))
for value in values:
out.extend(struct.pack(endian + 'Q', value))
return bytes(out)
def skip_padding(data, pos, alignment):
end = pos + pad_count(pos, alignment)
if end > len(data):
raise ValueError('truncated alignment padding')
if any(data[pos:end]):
raise ValueError('nonzero alignment padding')
return end
def decode_at(data, pos, endian):
if endian not in ('<', '>') or not 0 <= pos <= len(data):
raise ValueError('bad endian or offset')
pos = skip_padding(data, pos, 4)
if len(data) - pos < 4:
raise ValueError('truncated array length')
n = struct.unpack_from(endian + 'I', data, pos)[0]
pos += 4
if n > ARRAY_LIMIT or n > DEMO_LIMIT:
raise ValueError('array exceeds size policy')
if n % 8:
raise ValueError('at data length must be divisible by 8')
# This runs even when n == 0.
pos = skip_padding(data, pos, 8)
end = pos + n
if end > len(data):
raise ValueError('truncated array data')
values = [struct.unpack_from(endian + 'Q', data, p)[0]
for p in range(pos, end, 8)]
return values, end
def rejects(label, data, pos=0):
try:
decode_at(data, pos, '<')
except ValueError as exc:
print('REJECT', label + ':', exc)
else:
raise AssertionError(label)
def main():
# Literal expected byte strings do not call the encoder to derive expectations.
vectors = [
('<', 0, [], '0000000000000000'),
('<', 4, [], '00000000'),
('<', 0, [5], '08000000000000000500000000000000'),
('>', 0, [5], '00000008000000000000000000000005'),
('<', 4, [5, 6], '1000000005000000000000000600000000000000'),
('>', 4, [5, 6], '0000001000000000000000050000000000000006'),
]
for endian, start, values, expected in vectors:
encoded = encode_at(values, start, endian)
assert encoded.hex() == expected
data = b'\xaa' * start + encoded + b'\x7f'
decoded, end = decode_at(data, start, endian)
assert decoded == values and data[end] == 0x7f and end == len(data)-1
print('VECTOR', endian, 'start=' + str(start), 'values=' + str(values),
'bytes=' + str(len(encoded)), 'next=' + str(end), encoded.hex())
# All alignment residues and both byte orders.
for start in range(16):
for endian in ('<', '>'):
for values in ([], [0], [1, 2, (1 << 64)-1]):
encoded = encode_at(values, start, endian)
data = bytes(start) + encoded
decoded, end = decode_at(data, start, endian)
assert decoded == values and end == len(data)
print('ROUNDTRIP 96 combinations passed')
rejects('missing empty-array padding', bytes(4))
rejects('nonzero padding', bytes(4) + b'\x01\x00\x00\x00')
rejects('wrong UINT64 byte count', struct.pack('<I', 4) + bytes(8))
rejects('short element', struct.pack('<I', 8) + bytes(4) + bytes(7))
rejects('oversize declaration', struct.pack('<I', ARRAY_LIMIT+8))
print('PASS: fixed vectors, offset matrix and malformed fragments')
if __name__ == '__main__':
main()6. 实际运行输出
VECTOR < start=0 values=[] bytes=8 next=8 0000000000000000 VECTOR < start=4 values=[] bytes=4 next=8 00000000 VECTOR < start=0 values=[5] bytes=16 next=16 08000000000000000500000000000000 VECTOR > start=0 values=[5] bytes=16 next=16 00000008000000000000000000000005 VECTOR < start=4 values=[5, 6] bytes=20 next=24 1000000005000000000000000600000000000000 VECTOR > start=4 values=[5, 6] bytes=20 next=24 0000001000000000000000050000000000000006 ROUNDTRIP 96 combinations passed REJECT missing empty-array padding: truncated alignment padding REJECT nonzero padding: nonzero alignment padding REJECT wrong UINT64 byte count: at data length must be divisible by 8 REJECT short element: truncated array data REJECT oversize declaration: array exceeds size policy PASS: fixed vectors, offset matrix and malformed fragments
第一、二行是最关键的对照:bytes 从 8 变为 4,next 却都等于 8。它们分别从 0 和 4 开始,正好解释同一“空数组”为何占用不同字节数。
后面的矩阵覆盖 16 个起点、两种端序和三种元素列表,共 96 组。固定向量直接写出预期十六进制,没有调用编码器来生成自己的预期结果;矩阵再补充往返一致性。这里没有调用独立 D-Bus 库,测试结论仅针对本文这个受限实现,不能宣称已经通过完整协议互操作测试。
7. 错误输入为什么应当拒绝
missing empty-array padding:只给四字节零长度,从偏移 0 开始还缺必要填充。
nonzero padding:用于对齐的字节必须为零,不能把非零值当成无害垃圾跳过。
wrong UINT64 byte count:at 的 n=4 不足以描述完整的八字节元素。
short element:声明八字节元素,却只提供七字节。
oversize declaration:先检查资源限制,避免用不可信长度创建巨大对象。
示例不会依据前缀占位数据推断实际 D-Bus 字段。接入完整解析器时,还要核对消息体长度、签名、头部合法性和全部嵌套边界。若实际消息被截断,不能只因为当前字段已经返回一个位置,就推断整个消息有效。
结语
at 的数组长度只负责描述元素数据区,绝对偏移负责决定对齐填充。这两件事彼此独立。空数组依然要完成首元素对齐,但最终多出几个字节必须现场计算。读写顺序保持“对齐4、长度、对齐8、元素”,就不会因 n=0 漏掉必要步骤。
参考规范
D-Bus Specification 0.43:Byte order and alignment、Marshalling containers 与 Summary of D-Bus marshalling。准备时已打开官方页面,特别核对空数组仍需首元素对齐的条款。


