mirror of
https://git.tartarus.org/simon/putty.git
synced 2025-07-17 11:00:59 -05:00
Extra-secure versions of sgrowarray and strbuf.
These versions, distinguished by the _nm suffix on their names, avoid using realloc to grow the array, in case it moves the block and leaves a copy of the data in the freed memory at the old address. (The suffix 'nm' stands for 'no moving'.) Instead, the array is grown by making a new allocation, manually copying the data over, and carefully clearing the old block before freeing it. (An alternative would be to give this code base its own custom heap in which the ordinary realloc takes care about this kind of thing, but I don't really feel like going to that much effort!)
This commit is contained in:
13
memory.c
13
memory.c
@ -8,6 +8,7 @@
|
||||
|
||||
#include "defs.h"
|
||||
#include "puttymem.h"
|
||||
#include "misc.h"
|
||||
|
||||
void *safemalloc(size_t n, size_t size)
|
||||
{
|
||||
@ -72,7 +73,7 @@ void safefree(void *ptr)
|
||||
}
|
||||
|
||||
void *safegrowarray(void *ptr, size_t *allocated, size_t eltsize,
|
||||
size_t oldlen, size_t extralen)
|
||||
size_t oldlen, size_t extralen, bool secret)
|
||||
{
|
||||
/* The largest value we can safely multiply by eltsize */
|
||||
assert(eltsize > 0);
|
||||
@ -108,7 +109,15 @@ void *safegrowarray(void *ptr, size_t *allocated, size_t eltsize,
|
||||
increment = maxincr;
|
||||
|
||||
size_t newsize = oldsize + increment;
|
||||
void *toret = saferealloc(ptr, newsize, eltsize);
|
||||
void *toret;
|
||||
if (secret) {
|
||||
toret = safemalloc(newsize, eltsize);
|
||||
memcpy(toret, ptr, oldsize * eltsize);
|
||||
smemclr(ptr, oldsize * eltsize);
|
||||
sfree(ptr);
|
||||
} else {
|
||||
toret = saferealloc(ptr, newsize, eltsize);
|
||||
}
|
||||
*allocated = newsize;
|
||||
return toret;
|
||||
}
|
||||
|
Reference in New Issue
Block a user