Skip to content

Fix undefined behavior in Huffman encoder for single-symbol input - #133

Open
alexey-milovidov wants to merge 1 commit into
szcompressor:masterfrom
ClickHouse:ch-fix-huffman-build-code-shift
Open

Fix undefined behavior in Huffman encoder for single-symbol input#133
alexey-milovidov wants to merge 1 commit into
szcompressor:masterfrom
ClickHouse:ch-fix-huffman-build-code-shift

Conversation

@alexey-milovidov

Copy link
Copy Markdown

Problem

HuffmanEncoder::build_code is invoked with len == 0 for the tree root (see the build_code(huffmanTree->qq[1], 0, 0, 0) call). When the Huffman tree has a single symbol — which happens for constant input data, where every value maps to the same quantization code — the leaf is the root, so the code length is zero and the encoder executes:

(huffmanTree->code[n->c])[0] = out1 << (64 - len);  // out1 << 64 when len == 0

Shifting a 64-bit value by 64 bits is undefined behavior in C++. It aborts under UndefinedBehaviorSanitizer (shift exponent 64 is too large for 64-bit type) and is generally unsafe.

Fix

Handle len == 0 explicitly (a zero-length code is empty, store 0). Also add a symmetric guard for len >= 128 in the other branch, where out2 << (128 - len) would shift by >= 64 (such codes do not fit in 128 bits anyway).

Context

This was found while integrating SZ3 into ClickHouse, where compressing a column of constant floating-point values reliably triggered the crash on a UBSan build: ClickHouse/ClickHouse#108788

build_code is invoked with len == 0 for the tree root. When the Huffman
tree has a single symbol (e.g. constant input data, which yields a single
distinct quantization code), the leaf is the root and the code length is
zero, so out1 << (64 - len) shifts a 64-bit value by 64 bits. That is
undefined behavior and aborts under UndefinedBehaviorSanitizer.

Handle len == 0 explicitly (the code is empty, store 0), and add a
symmetric guard for len >= 128 in the other branch.

Found while integrating SZ3 into ClickHouse:
ClickHouse/ClickHouse#108788
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant