From 7133a6c1f99b74986586c56a9a2ab7013cdc7cb9 Mon Sep 17 00:00:00 2001 From: Christopher Pascoe Date: Mon, 7 Dec 2015 00:23:46 -0800 Subject: [PATCH] Ensure that we never write an out of bounds value (_bufend) to _begin or _end, even temporarily. Testing: - Boot tested, ran basic serial I/O code Notes: - Before this change, there are instruction like "s32i.n , , <_begin>" in the disassembled output, followed by an overwrite if turns out to be _bufend. After this change, there is only one store instruction to <_begin> per function. --- cores/esp8266/cbuf.h | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/cores/esp8266/cbuf.h b/cores/esp8266/cbuf.h index fee98a94b..ce3ac5c64 100644 --- a/cores/esp8266/cbuf.h +++ b/cores/esp8266/cbuf.h @@ -62,7 +62,7 @@ class cbuf { if(getSize() == 0) return -1; char result = *_begin; - if(++_begin == _bufend) _begin = _buf; + _begin = wrap_if_bufend(_begin + 1); return static_cast(result); } @@ -78,8 +78,7 @@ class cbuf { dst += top_size; } memcpy(dst, _begin, size_to_read); - _begin += size_to_read; - if(_begin == _bufend) _begin = _buf; + _begin = wrap_if_bufend(_begin + size_to_read); return size_read; } @@ -87,7 +86,7 @@ class cbuf { if(room() == 0) return 0; *_end = c; - if(++_end == _bufend) _end = _buf; + _end = wrap_if_bufend(_end + 1); return 1; } @@ -103,8 +102,7 @@ class cbuf { src += top_size; } memcpy(_end, src, size_to_write); - _end += size_to_write; - if(_end == _bufend) _end = _buf; + _end = wrap_if_bufend(_end + size_to_write); return size_written; } @@ -114,6 +112,10 @@ class cbuf { } private: + inline char* wrap_if_bufend(char* ptr) { + return (ptr == _bufend) ? _buf : ptr; + } + size_t _size; char* _buf; char* _bufend;