From 610b4c95da8d4eacbb41ff4818204d3ac7cfaf5e Mon Sep 17 00:00:00 2001 From: Charlie Gordon Date: Sun, 3 Mar 2024 11:30:41 +0100 Subject: [PATCH] Fix UB on memcpy and float conversion - add `memcpy_no_ub()` to allow copying 0 bytes from or to null pointers - avoid converting out of range floats. --- cutils.h | 7 +++++++ quickjs.c | 11 ++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cutils.h b/cutils.h index ff2d3fb62..11246e3ce 100644 --- a/cutils.h +++ b/cutils.h @@ -26,6 +26,7 @@ #define CUTILS_H #include +#include #include #define likely(x) __builtin_expect(!!(x), 1) @@ -64,6 +65,12 @@ char *pstrcat(char *buf, int buf_size, const char *s); int strstart(const char *str, const char *val, const char **ptr); int has_suffix(const char *str, const char *suffix); +/* Prevent UB when n == 0 and (src == NULL or dest == NULL) */ +static inline void memcpy_no_ub(void *dest, const void *src, size_t n) { + if (n) + memcpy(dest, src, n); +} + static inline int max_int(int a, int b) { if (a > b) diff --git a/quickjs.c b/quickjs.c index b5634fb42..ebf45a988 100644 --- a/quickjs.c +++ b/quickjs.c @@ -33390,8 +33390,8 @@ static JSValue js_create_function(JSContext *ctx, JSFunctionDef *fd) } } else { b->vardefs = (void *)((uint8_t*)b + vardefs_offset); - memcpy(b->vardefs, fd->args, fd->arg_count * sizeof(fd->args[0])); - memcpy(b->vardefs + fd->arg_count, fd->vars, fd->var_count * sizeof(fd->vars[0])); + memcpy_no_ub(b->vardefs, fd->args, fd->arg_count * sizeof(fd->args[0])); + memcpy_no_ub(b->vardefs + fd->arg_count, fd->vars, fd->var_count * sizeof(fd->vars[0])); } b->var_count = fd->var_count; b->arg_count = fd->arg_count; @@ -53999,9 +53999,10 @@ static JSValue js_typed_array_indexOf(JSContext *ctx, JSValueConst this_val, } else if (tag == JS_TAG_FLOAT64) { d = JS_VALUE_GET_FLOAT64(argv[0]); - // XXX: should fix UB - v64 = d; - is_int = (v64 == d); + if (d >= INT64_MIN && d < 0x1p63) { + v64 = d; + is_int = (v64 == d); + } } else if (tag == JS_TAG_BIG_INT) { JSBigFloat *p1 = JS_VALUE_GET_PTR(argv[0]);