From 476ccc9f6bc0d292f0336132670de0dfacee7aef Mon Sep 17 00:00:00 2001 From: ISSOtm Date: Mon, 2 Sep 2019 02:09:59 +0200 Subject: [PATCH] Fix undefined behavior in yyunputstr Refer to comment at lexer.c:100 for more info --- src/asm/lexer.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/asm/lexer.c b/src/asm/lexer.c index 212a1f06..ae7781bb 100644 --- a/src/asm/lexer.c +++ b/src/asm/lexer.c @@ -97,11 +97,17 @@ void yyunputstr(const char *s) len = strlen(s); - pLexBuffer -= len; - - if (pLexBuffer < pLexBufferRealStart) + /* + * It would be undefined behavior to subtract `len` from pLexBuffer and + * potentially have it point outside of pLexBufferRealStart's buffer, + * this is why the check is done this way. + * Refer to https://github.com/rednex/rgbds/pull/411#discussion_r319779797 + */ + if (pLexBuffer - pLexBufferRealStart < len) fatalerror("Buffer safety margin exceeded"); + pLexBuffer -= len; + memcpy(pLexBuffer, s, len); }