From 1cdd798ac7b7be2d0fddb7e858828310c25723f0 Mon Sep 17 00:00:00 2001 From: Sergey Bugaev Date: Tue, 25 Aug 2020 17:45:27 +0300 Subject: [PATCH] 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. --- Libraries/LibC/scanf.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Libraries/LibC/scanf.cpp b/Libraries/LibC/scanf.cpp index 83a202f04a..a1e162f886 100644 --- a/Libraries/LibC/scanf.cpp +++ b/Libraries/LibC/scanf.cpp @@ -28,6 +28,7 @@ * SUCH DAMAGE. * */ +#include #include #include #include @@ -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) {