/* Test for string function add boundaries of usable memory.
Copyright (C) 1996-2025 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#define _GNU_SOURCE 1
/* Make sure we don't test the optimized inline functions if we want to
test the real implementation. */
#undef __USE_STRING_INLINES
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/param.h>
#ifndef CHAR
# define L(c) c
# define CHAR char
# define MEMSET memset
# define STRLEN strlen
# define STRNLEN strnlen
# define STRCHR strchr
# define STRRCHR strrchr
# define STRCPY strcpy
# define STRNCPY strncpy
# define MEMCMP memcmp
# define STPCPY stpcpy
# define STPNCPY stpncpy
# define MEMCPY memcpy
# define MEMPCPY mempcpy
# define MEMCHR memchr
# define STRCMP strcmp
# define STRNCMP strncmp
#endif
#define STRINGIFY(s) STRINGIFY2 (s)
#define STRINGIFY2(s) #s
int
do_test (void)
{
size_t size = sysconf (_SC_PAGESIZE);
size_t nchars = size / sizeof (CHAR);
CHAR *adr;
CHAR *dest;
int result = 0;
adr = (CHAR *) mmap (NULL, 3 * size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
dest = (CHAR *) mmap (NULL, 3 * size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON, -1, 0);
if (adr == MAP_FAILED || dest == MAP_FAILED)
{
if (errno == ENOSYS)
puts ("No test, mmap not available.");
else
{
printf ("mmap failed: %m");
result = 1;
}
}
else
{
size_t inner, middle, outer, nchars64, max128;
if (nchars > 64)
nchars64 = nchars - 64;
else
nchars64 = 0;
if (nchars > 128)
max128 = nchars - 128;
else
max128 = 0;
mprotect (adr, size, PROT_NONE);
mprotect (adr + 2 * nchars, size, PROT_NONE);
adr += nchars;
mprotect (dest, size, PROT_NONE);
mprotect (dest + 2 * nchars, size, PROT_NONE);
dest += nchars;
MEMSET (adr, L('T'), nchars);
/* strlen/wcslen test */
for (outer = nchars - 1; outer >= max128; --outer)
{
for (inner = MAX (outer, nchars64); inner < nchars; ++inner)
{
adr[inner] = L('\0');
if (STRLEN (&adr[outer]) != (size_t) (inner - outer))
{
printf ("%s flunked for outer = %zu, inner = %zu\n",
STRINGIFY (STRLEN), outer, inner);
result = 1;
}
adr[inner] = L('T');
}
if (outer == 0)
break;
}
/* strnlen/wcsnlen test */
for (