Blob


1 /* Author: Tatu Ylonen <ylo@cs.hut.fi>
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 * All rights reserved
4 * Versions of malloc and friends that check their results, and never return
5 * failure (they call fatal if they encounter an error).
6 *
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
12 */
14 #include <sys/types.h>
16 #include <stddef.h>
17 #include <stdlib.h>
18 #include <string.h>
20 #include "log.h"
21 #include "twind.h"
23 void *
24 xmalloc(size_t size)
25 {
26 void *ptr;
28 if (size == 0)
29 fatal("xmalloc: zero size");
30 ptr = calloc(1, size);
31 if (ptr == NULL)
32 fatal("xmalloc: out of memory (allocating %zu bytes)", size);
33 return ptr;
34 }
36 char *
37 xstrdup(const char *str)
38 {
39 size_t len;
40 char *cp;
42 len = strlen(str) + 1;
43 cp = xmalloc(len);
44 strlcpy(cp, str, len);
45 return cp;
46 }
48 /*
49 * Copyright (c) 1998, 2015 Todd C. Miller <millert@openbsd.org>
50 *
51 * Permission to use, copy, modify, and distribute this software for any
52 * purpose with or without fee is hereby granted, provided that the above
53 * copyright notice and this permission notice appear in all copies.
54 *
55 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
56 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
57 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
58 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
59 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
60 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
61 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
62 */
65 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) &&\
66 !defined(__DragonFly__)
67 /*
68 * Copy string src to buffer dst of size dsize. At most dsize-1
69 * chars will be copied. Always NUL terminates (unless dsize == 0).
70 * Returns strlen(src); if retval >= dsize, truncation occurred.
71 */
72 size_t
73 strlcpy(char *dst, const char *src, size_t dsize)
74 {
75 const char *osrc = src;
76 size_t nleft = dsize;
78 /* Copy as many bytes as will fit. */
79 if (nleft != 0) {
80 while (--nleft != 0) {
81 if ((*dst++ = *src++) == '\0')
82 break;
83 }
84 }
86 /* Not enough room in dst, add NUL and traverse rest of src. */
87 if (nleft == 0) {
88 if (dsize != 0)
89 *dst = '\0'; /* NUL-terminate dst */
90 while (*src++)
91 ;
92 }
94 return(src - osrc - 1); /* count does not include NUL */
95 }
96 #endif /* __BSD__ */