Skip to content

bf_set_ui when LIMB_BITS == 32 and shift = 0 depends on undefined behavior #131

@ailisp

Description

@ailisp

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions