Skip to content

Commit

Permalink
Avoid undefined behavior when subtracting tagged pointers (#715)
Browse files Browse the repository at this point in the history
When compiling with HardwareAddressSanitizer, the top byte of pointers
are tagged, hence subtracting two pointers may overflow. Overflow is
undefined behavior for signed integers, resulting in errors such as:
    third_party/nanobind/src/nb_type.cpp:123:50: runtime error: signed integer overflow: -6701078944169102656 - 9079534012674239392 cannot be represented in type 'intptr_t' (aka 'long')

This patch fixes the issue by using unsigned integers, for which
overflow is well-defined.
  • Loading branch information
thurstond authored Sep 12, 2024
1 parent 87a418a commit bceec36
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/nb_type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,10 @@ PyObject *inst_new_ext(PyTypeObject *tp, void *value) {
}

// Compute offset to instance value
int32_t offset = (int32_t) ((intptr_t) value - (intptr_t) self);
// Use uint64_t because subtracting tagged pointers (e.g., with
// HardwareAddressSanitizer) may overflow, which is undefined behavior for
// signed integers.
int32_t offset = (int32_t) ((uintptr_t) value - (uintptr_t) self);

bool direct = (intptr_t) self + offset == (intptr_t) value;
if (NB_UNLIKELY(!direct)) {
Expand Down

0 comments on commit bceec36

Please sign in to comment.