From cb9823d21c0abff876a14b0a355afc36ab54213c Mon Sep 17 00:00:00 2001 From: CPunch Date: Mon, 14 Mar 2022 12:06:32 -0500 Subject: [PATCH] Refactored VLAs to support macrohard --- lib/include/lmem.h | 10 ++++++++++ lib/src/lsocket.c | 7 +++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/include/lmem.h b/lib/include/lmem.h index 57941ff..289027f 100644 --- a/lib/include/lmem.h +++ b/lib/include/lmem.h @@ -5,6 +5,16 @@ #define GROW_FACTOR 2 +/* microsoft strikes again with their lack of support for VLAs */ +#if _MSC_VER +#define VLA(type, var, sz) type var = laikaM_malloc(sizeof(type)*sz); +#define ENDVLA(var) laikaM_free(var); +#else +#define VLA(type, var, sz) type var[sz]; +/* stubbed */ +#define ENDVLA(var) +#endif + #define laikaM_malloc(sz) laikaM_realloc(NULL, sz) #define laikaM_free(buf) laikaM_realloc(buf, 0) diff --git a/lib/src/lsocket.c b/lib/src/lsocket.c index f0ad78e..84c236b 100644 --- a/lib/src/lsocket.c +++ b/lib/src/lsocket.c @@ -239,7 +239,7 @@ uint8_t laikaS_readByte(struct sLaika_socket *sock) { void laikaS_readInt(struct sLaika_socket *sock, void *buf, size_t sz) { if (sock->flipEndian) { - uint8_t tmp[sz]; /* allocate tmp buffer to hold data while we switch endianness */ + VLA(uint8_t, tmp, sz); /* allocate tmp buffer to hold data while we switch endianness */ int k; laikaS_read(sock, (void*)tmp, sz); @@ -247,6 +247,8 @@ void laikaS_readInt(struct sLaika_socket *sock, void *buf, size_t sz) { /* copy tmp buffer to user buffer, flipping endianness */ for (k = 0; k < sz; k++) *(uint8_t*)(buf + k) = tmp[sz - k - 1]; + + ENDVLA(tmp); } else { /* just a wrapper for laikaS_read */ laikaS_read(sock, buf, sz); @@ -255,7 +257,7 @@ void laikaS_readInt(struct sLaika_socket *sock, void *buf, size_t sz) { void laikaS_writeInt(struct sLaika_socket *sock, void *buf, size_t sz) { if (sock->flipEndian) { - uint8_t tmp[sz]; /* allocate tmp buffer to hold data while we switch endianness */ + VLA(uint8_t, tmp, sz); /* allocate tmp buffer to hold data while we switch endianness */ int k; /* copy user buffer to tmp buffer, flipping endianness */ @@ -263,6 +265,7 @@ void laikaS_writeInt(struct sLaika_socket *sock, void *buf, size_t sz) { tmp[k] = *(uint8_t*)(buf + (sz - k - 1)); laikaS_write(sock, (void*)tmp, sz); + ENDVLA(tmp); } else { /* just a wrapper for laikaS_write */ laikaS_write(sock, buf, sz);