From e3774034e9e2e77d1f92a4b8ea00776b0daeb899 Mon Sep 17 00:00:00 2001 From: Christopher Dykes Date: Thu, 31 Mar 2016 10:14:42 -0700 Subject: [PATCH] Fix the portability implementation of strndup Summary:It was mistakenly assuming the length passed in included the null terminator. This also makes the portability implementation of `strndup` available to OSX and FreeBSD, where they weren't present, and where HHVM had a wrapper for them. This also removes the extra pair of conditions around `memrchr`, as the main define should always be getting set. Reviewed By: yfeldblum Differential Revision: D3116467 fb-gh-sync-id: 243dd4dace219efab2c2bf2f383202e70fbec4de fbshipit-source-id: 243dd4dace219efab2c2bf2f383202e70fbec4de --- folly/portability/String.cpp | 19 ++++++++++--------- folly/portability/String.h | 13 +++++++------ 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/folly/portability/String.cpp b/folly/portability/String.cpp index eae93f5e..e48076b1 100755 --- a/folly/portability/String.cpp +++ b/folly/portability/String.cpp @@ -16,7 +16,7 @@ #include -#if !FOLLY_HAVE_MEMRCHR || defined(_WIN32) || defined(__APPLE__) +#if !FOLLY_HAVE_MEMRCHR extern "C" void* memrchr(const void* s, int c, size_t n) { for (auto p = ((const char*)s) + n - 1; p >= (const char*)s; p--) { if (*p == (char)c) { @@ -27,23 +27,24 @@ extern "C" void* memrchr(const void* s, int c, size_t n) { } #endif -#ifdef _WIN32 -#include - -extern "C" { -char* strndup(const char* a, size_t len) { +#if defined(_WIN32) || defined(__APPLE__) || defined(__FreeBSD__) +extern "C" char* strndup(const char* a, size_t len) { auto neededLen = strlen(a); if (neededLen > len) { - neededLen = len - 1; + neededLen = len; } char* buf = (char*)malloc((neededLen + 1) * sizeof(char)); + if (!buf) { + return nullptr; + } memcpy(buf, a, neededLen); buf[neededLen] = '\0'; return buf; } +#endif -char* strtok_r(char* str, char const* delim, char** ctx) { +#ifdef _WIN32 +extern "C" char* strtok_r(char* str, char const* delim, char** ctx) { return strtok_s(str, delim, ctx); } -} #endif diff --git a/folly/portability/String.h b/folly/portability/String.h index 5dd8a654..0d235559 100755 --- a/folly/portability/String.h +++ b/folly/portability/String.h @@ -17,17 +17,18 @@ #pragma once #include +#include #include -#if !FOLLY_HAVE_MEMRCHR || defined(_WIN32) || defined(__APPLE__) -#include +#if !FOLLY_HAVE_MEMRCHR extern "C" void* memrchr(const void* s, int c, size_t n); #endif +#if defined(_WIN32) || defined(__APPLE__) || defined(__FreeBSD__) +extern "C" char* strndup(const char* a, size_t len); +#endif + #ifdef _WIN32 -extern "C" { -char* strndup(const char* a, size_t len); -char* strtok_r(char* str, char const* delim, char** ctx); -} +extern "C" char* strtok_r(char* str, char const* delim, char** ctx); #endif -- 2.34.1