Implement cs_strnlen for Mac OS X portability (#2889)

Replace strnlen() call with a simple loop to find the bounded string
length. strnlen() is POSIX.1-2008 and not available on older platforms
like Mac OS X Leopard (10.5).

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
AutoJanitor 2026-04-08 04:50:31 -05:00 committed by GitHub
parent ada8e412c9
commit 4ab9943ce8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 23 additions and 1 deletions

View file

@ -6,6 +6,8 @@
#include <stddef.h>
#include "../../../utils.h"
#define MAX_ASM_TXT_MEM 1024
#define X86_16 0
#define X86_32 1

View file

@ -17,7 +17,7 @@ char *cs_strndup(const char *s, size_t n)
if (!s) {
return NULL;
}
size_t l = strnlen(s, n);
size_t l = cs_strnlen(s, n);
if (l == SIZE_MAX) {
return NULL;
}

15
utils.c
View file

@ -47,6 +47,21 @@ char *cs_strdup(const char *str)
return (char *)memmove(new, str, len);
}
// Portable strnlen replacement for platforms that lack it
// (e.g. Mac OS X 10.5 Leopard).
size_t cs_strnlen(const char *str, size_t n)
{
if (!str)
return 0;
size_t l = 0;
while (l < n && str[l] != '\0')
l++;
return l;
}
// we need this since Windows doesn't have snprintf()
int cs_snprintf(char *buffer, size_t size, const char *fmt, ...)
{

View file

@ -26,6 +26,11 @@ unsigned int count_positive8(const unsigned char *list);
char *cs_strdup(const char *str);
// Portable strnlen replacement. Returns the length of @str,
// up to a maximum of @n. Needed because strnlen() is not
// available on all platforms (e.g. Mac OS X 10.5 Leopard).
size_t cs_strnlen(const char *str, size_t n);
#define MIN(x, y) ((x) < (y) ? (x) : (y))
// we need this since Windows doesn't have snprintf()