Skip to content

Commit 7133a6c

Browse files
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 <reg>, <this>, <_begin>" in the disassembled output, followed by an overwrite if <reg> turns out to be _bufend. After this change, there is only one store instruction to <_begin> per function.
1 parent cc0a8ea commit 7133a6c

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

cores/esp8266/cbuf.h

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ class cbuf {
6262
if(getSize() == 0) return -1;
6363

6464
char result = *_begin;
65-
if(++_begin == _bufend) _begin = _buf;
65+
_begin = wrap_if_bufend(_begin + 1);
6666
return static_cast<int>(result);
6767
}
6868

@@ -78,16 +78,15 @@ class cbuf {
7878
dst += top_size;
7979
}
8080
memcpy(dst, _begin, size_to_read);
81-
_begin += size_to_read;
82-
if(_begin == _bufend) _begin = _buf;
81+
_begin = wrap_if_bufend(_begin + size_to_read);
8382
return size_read;
8483
}
8584

8685
size_t write(char c) {
8786
if(room() == 0) return 0;
8887

8988
*_end = c;
90-
if(++_end == _bufend) _end = _buf;
89+
_end = wrap_if_bufend(_end + 1);
9190
return 1;
9291
}
9392

@@ -103,8 +102,7 @@ class cbuf {
103102
src += top_size;
104103
}
105104
memcpy(_end, src, size_to_write);
106-
_end += size_to_write;
107-
if(_end == _bufend) _end = _buf;
105+
_end = wrap_if_bufend(_end + size_to_write);
108106
return size_written;
109107
}
110108

@@ -114,6 +112,10 @@ class cbuf {
114112
}
115113

116114
private:
115+
inline char* wrap_if_bufend(char* ptr) {
116+
return (ptr == _bufend) ? _buf : ptr;
117+
}
118+
117119
size_t _size;
118120
char* _buf;
119121
char* _bufend;

0 commit comments

Comments
 (0)