bf_set_ui when LIMB_BITS == 32 and shift = 0 depends on undefined behavior
This expression in libbf.c, function bf_set_ui, when LIMB_BITS == 32 and shift = 0:
(a0 >> (LIMB_BITS - shift))
becomes
(a0 >> 32)
And a0 is uint32_t, according to C99 and C17 spec (for bitwise shift):
If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
So shifting it for 32 bit is an undefined behavior, and it did produce wrong result in our JS-on-Wasm runtime based on quickjs.
A quick snippet to repro:
void *realloc2(void *opaque, void *ptr, size_t size) {
return realloc(ptr, size);
}
bf_t a;
bf_context_t ctx;
bf_context_init(&ctx, realloc2, NULL);
bf_init(&ctx, &a);
bf_set_ui(&a, 0x8b0a00a425000000ul);
uint64_t ret=0;
bf_get_uint64(&ret, &a);
// ret is 0xaf0a00a425000000
Note that the above ret depends on the compiler and the compiler flags. A minimum repro to this undefined behavior:
#define LIMB_BITS 32
#include <stdio.h>
#include <stdint.h>
uint32_t opaque(uint32_t x) {
return x == 0x3;
}
int main() {
uint32_t temp = 7;
uint32_t x = 0x8b0a00a4;
uint32_t k = LIMB_BITS - opaque(x) * LIMB_BITS;
temp = temp >> k;
printf("%d\n", k); // 32
printf("%d\n", temp);
printf("%d\n", temp>>32);
}
On my system, gcc, gcc -Os, clang and clang -Oz produced different result.
same as #133