Skip to content

Commit

Permalink
libc: common: declare strnlen() and strtok_r() in string.h
Browse files Browse the repository at this point in the history
Rules A.4 and A.5 of the coding guidelines allow the POSIX
strnlen() and strtok_r() functions to be used anywhere within
Zephyr, including in the kernel.

These are not part of ISO C and typically require
_POSIX_C_SOURCE to be declared. However, in Zephyr, POSIX
and the interfaces it provides, are optional, and should not
be used to compile the kernel and core components of the
system, which is also specified by Rules A.4 and A.5 of the
coding guidelines.

Declare the POSIX strnlen() function with _POSIX_C_SOURCE or
with _ZEPHYR_SOURCE so that it can be used easily by any
C library (including those without POSIX support or those
without knowledge of _ZEPHYR_SOURCE).

Signed-off-by: Christopher Friedt <cfriedt@meta.com>
  • Loading branch information
cfriedt committed Jan 30, 2024
1 parent 8cf199f commit aa0f8d4
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
30 changes: 30 additions & 0 deletions lib/libc/common/include/string.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright (c) 2024, Meta
*
* SPDX-License-Identifier: Apache-2.0
*/

#ifndef ZEPHYR_LIB_LIBC_COMMON_INCLUDE_STRING_H_
#define ZEPHYR_LIB_LIBC_COMMON_INCLUDE_STRING_H_

#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

#if _POSIX_C_SOURCE >= 200809L || defined(_ZEPHYR_SOURCE)
size_t strnlen(const char *s, size_t maxlen);
#endif

#if _POSIX_C_SOURCE >= 200112L || defined(_ZEPHYR_SOURCE)
char *strtok_r(char *str, const char *sep, char **state);
#endif

#ifdef __cplusplus
}
#endif

#include_next <string.h>

#endif /* ZEPHYR_LIB_LIBC_COMMON_INCLUDE_STRING_H_ */
5 changes: 5 additions & 0 deletions lib/libc/newlib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ zephyr_compile_definitions(_ANSI_SOURCE)
# used by the network stack
zephyr_compile_definitions(__LINUX_ERRNO_EXTENSIONS__)

# define _ZEPHYR_SOURCE so we can get POSIX extensions to ISO C declared in
# lib/libc/common/include/string.h, to satisfy Rule A.4 of Zephyr's Coding
# Guidelines.
zephyr_compile_definitions(_ZEPHYR_SOURCE)

if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
# We are using
# - ${CMAKE_C_LINKER_WRAPPER_FLAG}${CMAKE_LINK_LIBRARY_FLAG}c
Expand Down
4 changes: 0 additions & 4 deletions tests/lib/c_lib/common/src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@
* it guarantee that ALL functionality provided is working correctly.
*/

#ifdef CONFIG_NEWLIB_LIBC
#define _POSIX_C_SOURCE 200809
#endif

#include <zephyr/kernel.h>
#include <zephyr/sys/__assert.h>
#include <zephyr/ztest.h>
Expand Down

0 comments on commit aa0f8d4

Please sign in to comment.