xref: /illumos-gate/usr/src/lib/libuutil/common/uu_alloc.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include "libuutil_common.h"
26 
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 
32 void *
33 uu_zalloc(size_t n)
34 {
35 	void *p = malloc(n);
36 
37 	if (p == NULL) {
38 		uu_set_error(UU_ERROR_SYSTEM);
39 		return (NULL);
40 	}
41 
42 	(void) memset(p, 0, n);
43 
44 	return (p);
45 }
46 
47 void
48 uu_free(void *p)
49 {
50 	free(p);
51 }
52 
53 char *
54 uu_strdup(const char *str)
55 {
56 	char *buf = NULL;
57 
58 	if (str != NULL) {
59 		size_t sz;
60 
61 		sz = strlen(str) + 1;
62 		buf = uu_zalloc(sz);
63 		if (buf != NULL)
64 			(void) memcpy(buf, str, sz);
65 	}
66 	return (buf);
67 }
68 
69 /*
70  * Duplicate up to n bytes of a string.  Kind of sort of like
71  * strdup(strlcpy(s, n)).
72  */
73 char *
74 uu_strndup(const char *s, size_t n)
75 {
76 	size_t len;
77 	char *p;
78 
79 	len = strnlen(s, n);
80 	p = uu_zalloc(len + 1);
81 	if (p == NULL)
82 		return (NULL);
83 
84 	if (len > 0)
85 		(void) memcpy(p, s, len);
86 	p[len] = '\0';
87 
88 	return (p);
89 }
90 
91 /*
92  * Duplicate a block of memory.  Combines malloc with memcpy, much as
93  * strdup combines malloc, strlen, and strcpy.
94  */
95 void *
96 uu_memdup(const void *buf, size_t sz)
97 {
98 	void *p;
99 
100 	p = uu_zalloc(sz);
101 	if (p == NULL)
102 		return (NULL);
103 	(void) memcpy(p, buf, sz);
104 	return (p);
105 }
106 
107 char *
108 uu_msprintf(const char *format, ...)
109 {
110 	va_list args;
111 	char attic[1];
112 	uint_t M, m;
113 	char *b;
114 
115 	va_start(args, format);
116 	M = vsnprintf(attic, 1, format, args);
117 	va_end(args);
118 
119 	for (;;) {
120 		m = M;
121 		if ((b = uu_zalloc(m + 1)) == NULL)
122 			return (NULL);
123 
124 		va_start(args, format);
125 		M = vsnprintf(b, m + 1, format, args);
126 		va_end(args);
127 
128 		if (M == m)
129 			break;		/* sizes match */
130 
131 		uu_free(b);
132 	}
133 
134 	return (b);
135 }
136