xref: /illumos-gate/usr/src/lib/libdemangle/common/util.c (revision e4fb8a5fd5bb5a5d316430c6ac8f6d33704fcf5d)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright 2017 Jason King
14  * Copyright 2019, Joyent, Inc.
15  */
16 
17 #include <sys/debug.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include "demangle-sys.h"
21 #include "demangle_int.h"
22 
23 void *
24 zalloc(sysdem_ops_t *ops, size_t len)
25 {
26 	void *p = ops->alloc(len);
27 
28 	if (p != NULL)
29 		(void) memset(p, 0, len);
30 
31 #ifdef DEBUG
32 	/*
33 	 * In normal operation, we should never exhaust memory.  Either
34 	 * something's wrong, or the system is so hosed that aborting
35 	 * shouldn't hurt anything, and it gives us a more useful stack
36 	 * trace.
37 	 */
38 	if (p == NULL)
39 		abort();
40 #endif
41 
42 	return (p);
43 }
44 
45 void
46 xfree(sysdem_ops_t *ops, void *p, size_t len)
47 {
48 	if (p == NULL || len == 0)
49 		return;
50 
51 	ops->free(p, len);
52 }
53 
54 void *
55 xrealloc(sysdem_ops_t *ops, void *p, size_t oldsz, size_t newsz)
56 {
57 	if (newsz == oldsz)
58 		return (p);
59 
60 	VERIFY3U(newsz, >, oldsz);
61 
62 	void *temp = zalloc(ops, newsz);
63 
64 	if (temp == NULL)
65 		return (NULL);
66 
67 	if (oldsz > 0) {
68 		(void) memcpy(temp, p, oldsz);
69 		xfree(ops, p, oldsz);
70 	}
71 
72 	return (temp);
73 }
74 
75 char *
76 xstrdup(sysdem_ops_t *ops, const char *src)
77 {
78 	size_t len = strlen(src);
79 	char *str = zalloc(ops, len + 1);
80 
81 	if (str == NULL)
82 		return (NULL);
83 
84 	/* zalloc(len+1) guarantees this will be NUL-terminated */
85 	(void) memcpy(str, src, len);
86 	return (str);
87 }
88 
89 /*ARGSUSED*/
90 static void
91 def_free(void *p, size_t len)
92 {
93 	free(p);
94 }
95 
96 static sysdem_ops_t i_sysdem_ops_default = {
97 	.alloc = malloc,
98 	.free = def_free
99 };
100 sysdem_ops_t *sysdem_ops_default = &i_sysdem_ops_default;
101