xref: /netbsd-src/external/bsd/ntp/dist/libntp/emalloc.c (revision b8867d0ef6bae1e13100812ac6a6f543f1115d0c)
1 /*	$NetBSD: emalloc.c,v 1.2 2012/02/04 16:31:02 christos Exp $	*/
2 
3 /*
4  * emalloc - return new memory obtained from the system.  Belch if none.
5  */
6 #include <config.h>
7 #include "ntp_types.h"
8 #include "ntp_malloc.h"
9 #include "ntp_syslog.h"
10 #include "ntp_stdlib.h"
11 
12 
13 /*
14  * When using the debug MS CRT allocator, each allocation stores the
15  * callsite __FILE__ and __LINE__, which is then displayed at process
16  * termination, to track down leaks.  We don't want all of our
17  * allocations to show up as coming from emalloc.c, so we preserve the
18  * original callsite's source file and line using macros which pass
19  * __FILE__ and __LINE__ as parameters to these routines.
20  * Other debug malloc implementations can be used by defining
21  * EREALLOC_IMPL() as ports/winnt/include/config.h does.
22  */
23 
24 void *
25 ereallocz(
26 	void *	ptr,
27 	size_t	newsz,
28 	size_t	priorsz,
29 	int	zero_init
30 #ifdef EREALLOC_CALLSITE		/* ntp_malloc.h */
31 			 ,
32 	const char *	file,
33 	int		line
34 #endif
35 	)
36 {
37 	char *	mem;
38 	size_t	allocsz;
39 
40 	if (0 == newsz)
41 		allocsz = 1;
42 	else
43 		allocsz = newsz;
44 
45 	mem = EREALLOC_IMPL(ptr, allocsz, file, line);
46 	if (NULL == mem) {
47 		msyslog_term = TRUE;
48 #ifndef EREALLOC_CALLSITE
49 		msyslog(LOG_ERR, "fatal out of memory (%lu bytes)",
50 			(u_long)newsz);
51 #else
52 		msyslog(LOG_ERR,
53 			"fatal out of memory %s line %d (%lu bytes)",
54 			file, line, (u_long)newsz);
55 #endif
56 		exit(1);
57 	}
58 
59 	if (zero_init && newsz > priorsz)
60 		zero_mem(mem + priorsz, newsz - priorsz);
61 
62 	return mem;
63 }
64 
65 
66 char *
67 estrdup_impl(
68 	const char *	str
69 #ifdef EREALLOC_CALLSITE
70 			   ,
71 	const char *	file,
72 	int		line
73 #endif
74 	)
75 {
76 	char *	copy;
77 	size_t	bytes;
78 
79 	bytes = strlen(str) + 1;
80 	copy = ereallocz(NULL, bytes, 0, FALSE
81 #ifdef EREALLOC_CALLSITE
82 			 , file, line
83 #endif
84 			 );
85 	memcpy(copy, str, bytes);
86 
87 	return copy;
88 }
89 
90 
91 #if 0
92 #ifndef EREALLOC_CALLSITE
93 void *
94 emalloc(size_t newsz)
95 {
96 	return ereallocz(NULL, newsz, 0, FALSE);
97 }
98 #endif
99 #endif
100 
101