xref: /freebsd/sys/libkern/strlcpy.c (revision e38b830780d47a9014e09015c4acdb1a3f6d3416)
1*e38b8307SConrad Meyer /*	$OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $	*/
2a41df9e3SWarner Losh 
3*e38b8307SConrad Meyer /*
4*e38b8307SConrad Meyer  * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
5a41df9e3SWarner Losh  *
6299ff0d7SXin LI  * Permission to use, copy, modify, and distribute this software for any
7299ff0d7SXin LI  * purpose with or without fee is hereby granted, provided that the above
8299ff0d7SXin LI  * copyright notice and this permission notice appear in all copies.
9a41df9e3SWarner Losh  *
10299ff0d7SXin LI  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11299ff0d7SXin LI  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12299ff0d7SXin LI  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13299ff0d7SXin LI  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14299ff0d7SXin LI  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15299ff0d7SXin LI  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16299ff0d7SXin LI  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17a41df9e3SWarner Losh  */
18a41df9e3SWarner Losh 
19de5fe5d5SDavid E. O'Brien #include <sys/cdefs.h>
20de5fe5d5SDavid E. O'Brien __FBSDID("$FreeBSD$");
21a41df9e3SWarner Losh 
22a41df9e3SWarner Losh #include <sys/types.h>
23105d189bSPeter Wemm #include <sys/libkern.h>
24a41df9e3SWarner Losh 
25a41df9e3SWarner Losh /*
26*e38b8307SConrad Meyer  * Copy string src to buffer dst of size dsize.  At most dsize-1
27*e38b8307SConrad Meyer  * chars will be copied.  Always NUL terminates (unless dsize == 0).
28*e38b8307SConrad Meyer  * Returns strlen(src); if retval >= dsize, truncation occurred.
29a41df9e3SWarner Losh  */
30299ff0d7SXin LI size_t
31*e38b8307SConrad Meyer strlcpy(char * __restrict dst, const char * __restrict src, size_t dsize)
32a41df9e3SWarner Losh {
33*e38b8307SConrad Meyer 	const char *osrc = src;
34*e38b8307SConrad Meyer 	size_t nleft = dsize;
35a41df9e3SWarner Losh 
36*e38b8307SConrad Meyer 	/* Copy as many bytes as will fit. */
37*e38b8307SConrad Meyer 	if (nleft != 0) {
38*e38b8307SConrad Meyer 		while (--nleft != 0) {
39*e38b8307SConrad Meyer 			if ((*dst++ = *src++) == '\0')
40d64292d2SWarner Losh 				break;
41299ff0d7SXin LI 		}
42a41df9e3SWarner Losh 	}
43a41df9e3SWarner Losh 
44*e38b8307SConrad Meyer 	/* Not enough room in dst, add NUL and traverse rest of src. */
45*e38b8307SConrad Meyer 	if (nleft == 0) {
46*e38b8307SConrad Meyer 		if (dsize != 0)
47*e38b8307SConrad Meyer 			*dst = '\0';		/* NUL-terminate dst */
48*e38b8307SConrad Meyer 		while (*src++)
49d64292d2SWarner Losh 			;
50d64292d2SWarner Losh 	}
51d64292d2SWarner Losh 
52*e38b8307SConrad Meyer 	return(src - osrc - 1);	/* count does not include NUL */
53a41df9e3SWarner Losh }
54