1 /*- 2 * Copyright (c) 2006, 2008, 2009, 2013 3 * mirabilos <m (at) mirbsd.org> 4 * Copyright (c) 1998 Todd C. Miller <Todd.Miller (at) courtesan.com> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 #include "sh.h" 20 21 __RCSID("$MirOS: src/bin/mksh/strlcpy.c,v 1.10 2015/11/29 17:05:02 tg Exp $"); 22 23 /* 24 * Copy src to string dst of size siz. At most siz-1 characters 25 * will be copied. Always NUL terminates (unless siz == 0). 26 * Returns strlen(src); if retval >= siz, truncation occurred. 27 */ 28 #undef strlcpy 29 size_t 30 strlcpy(char *dst, const char *src, size_t siz) 31 { 32 const char *s = src; 33 34 if (siz == 0) 35 goto traverse_src; 36 37 /* copy as many chars as will fit */ 38 while (--siz && (*dst++ = *s++)) 39 ; 40 41 /* not enough room in dst */ 42 if (siz == 0) { 43 /* safe to NUL-terminate dst since we copied <= siz-1 chars */ 44 *dst = '\0'; 45 traverse_src: 46 /* traverse rest of src */ 47 while (*s++) 48 ; 49 } 50 51 /* count does not include NUL */ 52 return ((size_t)(s - src - 1)); 53 } 54