From ecc4f838db18336c4afbc6dabb1a8edbc6d8bbd0 Mon Sep 17 00:00:00 2001 From: Dimitri van Heesch Date: Mon, 23 Dec 2019 14:13:29 +0100 Subject: Fix for use of non portable strnstr function (part 2) --- src/portable.cpp | 32 ++++++++++++++++++++++++++++++-- src/portable.h | 2 +- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/portable.cpp b/src/portable.cpp index 9927c45..3ee1081 100644 --- a/src/portable.cpp +++ b/src/portable.cpp @@ -476,13 +476,41 @@ void Portable::setShortDir(void) #endif } +/* Return the first occurrence of NEEDLE in HAYSTACK. */ +static const char * portable_memmem (const char *haystack, size_t haystack_len, + const char *needle, size_t needle_len) +{ + const char *const last_possible = haystack + haystack_len - needle_len; + + if (needle_len == 0) + // The first occurrence of the empty string should to occur at the beginning of the string. + { + return haystack; + } + + // Sanity check + if (haystack_len < needle_len) + { + return 0; + } + + for (const char *begin = haystack; begin <= last_possible; ++begin) + { + if (begin[0] == needle[0] && !memcmp(&begin[1], needle + 1, needle_len - 1)) + { + return begin; + } + } + + return 0; +} -char *Portable::strnstr(const char *haystack, const char *needle, size_t haystack_len) +const char *Portable::strnstr(const char *haystack, const char *needle, size_t haystack_len) { size_t needle_len = strnlen(needle, haystack_len); if (needle_len < haystack_len || !needle[needle_len]) { - char *x = static_cast(memmem(haystack, haystack_len, needle, needle_len)); + const char *x = portable_memmem(haystack, haystack_len, needle, needle_len); if (x && !memchr(haystack, 0, x - haystack)) { return x; diff --git a/src/portable.h b/src/portable.h index be73435..771108e 100644 --- a/src/portable.h +++ b/src/portable.h @@ -42,7 +42,7 @@ namespace Portable bool isAbsolutePath(const char *fileName); void correct_path(void); void setShortDir(void); - char * strnstr(const char *haystack, const char *needle, size_t haystack_len); + const char * strnstr(const char *haystack, const char *needle, size_t haystack_len); } -- cgit v0.12