LibC: Replace some strncpy() calls with memcpy()

In case we know exactly how many bytes we're copying (and not copying a string
while limiting its length to that of a buffer), memcpy() is a more appropriate
function to call.

Also, fix null-terminating the %c pointer.
This commit is contained in:
Sergey Bugaev 2020-08-25 17:45:27 +03:00 committed by Andreas Kling
parent 34353e18cf
commit 1cdd798ac7
Notes: sideshowbarker 2024-07-19 02:59:23 +09:00

View file

@ -28,6 +28,7 @@
* SUCH DAMAGE.
*
*/
#include <AK/Assertions.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdint.h>
@ -71,10 +72,11 @@ static int _atob(unsigned long* vp, const char* p, int base)
}
if (base == 16 && (q = strchr(p, '.')) != 0) {
if (q - p > (int)sizeof(tmp) - 1)
if (q - p > (ssize_t)sizeof(tmp) - 1)
return 0;
strncpy(tmp, p, q - p);
memcpy(tmp, p, q - p);
tmp[q - p] = '\0';
if (!_atob(&v1, tmp, 16))
return 0;
++q;
@ -144,7 +146,8 @@ int vsscanf(const char* buf, const char* s, va_list ap)
const char* tc;
for (tc = s; isdigit(*s); s++)
;
strncpy(tmp, tc, s - tc);
ASSERT((ssize_t)sizeof(tmp) >= s - tc + 1);
memcpy(tmp, tc, s - tc);
tmp[s - tc] = '\0';
atob((uint32_t*)&width, tmp, 10);
s--;
@ -156,7 +159,8 @@ int vsscanf(const char* buf, const char* s, va_list ap)
if (!width)
width = strcspn(buf, ISSPACE);
if (!noassign) {
strncpy(t = va_arg(ap, char*), buf, width);
// In this case, we have no way to ensure the user buffer is not overflown :(
memcpy(t = va_arg(ap, char*), buf, width);
t[width] = '\0';
}
buf += width;
@ -164,8 +168,8 @@ int vsscanf(const char* buf, const char* s, va_list ap)
if (!width)
width = 1;
if (!noassign) {
strncpy(t = va_arg(ap, char*), buf, width);
t[width] = '\0';
memcpy(t = va_arg(ap, char*), buf, width);
// No null terminator!
}
buf += width;
} else if (strchr("dobxu", *s)) {
@ -192,7 +196,7 @@ int vsscanf(const char* buf, const char* s, va_list ap)
}
}
}
strncpy(tmp, buf, width);
memcpy(tmp, buf, width);
tmp[width] = '\0';
buf += width;
if (!noassign) {