diff options
author | Sergey Bugaev <bugaevc@serenityos.org> | 2020-08-25 17:45:27 +0300 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-08-30 17:35:27 +0200 |
commit | 1cdd798ac7b7be2d0fddb7e858828310c25723f0 (patch) | |
tree | c766618ac69fa0fb5b75e14c8fb6b30e6622f87d /Libraries/LibC | |
parent | 34353e18cf693ca027ea32b2c253eead8701a01c (diff) | |
download | serenity-1cdd798ac7b7be2d0fddb7e858828310c25723f0.zip |
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.
Diffstat (limited to 'Libraries/LibC')
-rw-r--r-- | Libraries/LibC/scanf.cpp | 18 |
1 files 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 <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) { |