Line data Source code
1 : // SPDX-License-Identifier: LGPL-2.1-or-later
2 : /* Append a null-terminated string to another string, with length checking.
3 : * Copyright (C) 2016 Free Software Foundation, Inc.
4 : * This file is part of the GNU C Library.
5 : */
6 :
7 : /* adapted for Quagga from glibc patch submission originally from
8 : * Florian Weimer <fweimer@redhat.com>, 2016-05-18 */
9 :
10 : #ifdef HAVE_CONFIG_H
11 : #include "config.h"
12 : #endif
13 :
14 : #include <stdint.h>
15 : #include <string.h>
16 :
17 : #ifndef HAVE_STRLCAT
18 : #undef strlcat
19 :
20 : size_t strlcat(char *__restrict dest,
21 : const char *__restrict src, size_t destsize);
22 :
23 60 : size_t strlcat(char *__restrict dest,
24 : const char *__restrict src, size_t destsize)
25 : {
26 60 : size_t src_length = strlen(src);
27 :
28 : /* Our implementation strlcat supports dest == NULL if size == 0
29 : (for consistency with snprintf and strlcpy), but strnlen does
30 : not, so we have to cover this case explicitly. */
31 60 : if (destsize == 0)
32 : return src_length;
33 :
34 60 : size_t dest_length = strnlen(dest, destsize);
35 60 : if (dest_length != destsize) {
36 : /* Copy at most the remaining number of characters in the
37 : destination buffer. Leave for the NUL terminator. */
38 60 : size_t to_copy = destsize - dest_length - 1;
39 : /* But not more than what is available in the source string. */
40 60 : if (to_copy > src_length)
41 : to_copy = src_length;
42 :
43 60 : char *target = dest + dest_length;
44 60 : memcpy(target, src, to_copy);
45 60 : target[to_copy] = '\0';
46 : }
47 :
48 : /* If the sum wraps around, we have more than SIZE_MAX + 2 bytes in
49 : the two input strings (including both null terminators). If each
50 : byte in the address space can be assigned a unique size_t value
51 : (which the static_assert checks), then by the pigeonhole
52 : principle, the two input strings must overlap, which is
53 : undefined. */
54 60 : _Static_assert(sizeof(uintptr_t) == sizeof(size_t),
55 : "theoretical maximum object size covers address space");
56 60 : return dest_length + src_length;
57 : }
58 : #endif /* HAVE_STRLCAT */
|