1 /* @(#)jmem.c	1.13 15/05/10 Copyright 1998-2015 J. Schilling */
2 #include <schily/mconfig.h>
3 #ifndef lint
4 static	UConst char sccsid[] =
5 	"@(#)jmem.c	1.13 15/05/10 Copyright 1998-2015 J. Schilling";
6 #endif
7 /*
8  *	Memory handling with error checking
9  *
10  *	Copyright (c) 1998-2015 J. Schilling
11  */
12 /*
13  * The contents of this file are subject to the terms of the
14  * Common Development and Distribution License, Version 1.0 only
15  * (the "License").  You may not use this file except in compliance
16  * with the License.
17  *
18  * See the file CDDL.Schily.txt in this distribution for details.
19  * A copy of the CDDL is also available via the Internet at
20  * http://www.opensource.org/licenses/cddl1.txt
21  *
22  * When distributing Covered Code, include this CDDL HEADER in each
23  * file and include the License file CDDL.Schily.txt from this distribution.
24  */
25 
26 #include <schily/stdio.h>
27 #include <schily/stdlib.h>
28 #include <schily/unistd.h>
29 #include <schily/string.h>
30 #include <schily/standard.h>
31 #include <schily/jmpdefs.h>
32 #include <schily/schily.h>
33 #include <schily/nlsdefs.h>
34 
35 EXPORT	int	__jmexval	__PR((int exval));
36 EXPORT	void	*__jmalloc	__PR((size_t size, char *msg, sigjmps_t *jmp));
37 EXPORT	void	*__jrealloc	__PR((void *ptr, size_t size, char *msg, sigjmps_t *jmp));
38 EXPORT	char	*__jsavestr	__PR((const char *s, sigjmps_t *jmp));
39 
40 LOCAL	int	jmexval;
41 
42 EXPORT	int
__jmexval(exval)43 __jmexval(exval)
44 	int	exval;
45 {
46 	int	ret = jmexval;
47 
48 	jmexval = exval;
49 
50 	return (ret);
51 }
52 
53 EXPORT void *
__jmalloc(size,msg,jmp)54 __jmalloc(size, msg, jmp)
55 	size_t		size;
56 	char		*msg;
57 	sigjmps_t	*jmp;
58 {
59 	void	*ret;
60 
61 	ret = malloc(size);
62 	if (ret == NULL) {
63 		int	err = geterrno();
64 
65 		errmsg(gettext("Cannot allocate memory for %s.\n"), msg);
66 		if (jmexval)
67 			err = jmexval;
68 		if (jmp == JM_EXIT)
69 			comexit(err);
70 		if (jmp != NULL)
71 			siglongjmp(jmp->jb, 1);
72 	}
73 	return (ret);
74 }
75 
76 EXPORT void *
__jrealloc(ptr,size,msg,jmp)77 __jrealloc(ptr, size, msg, jmp)
78 	void		*ptr;
79 	size_t		size;
80 	char		*msg;
81 	sigjmps_t	*jmp;
82 {
83 	void	*ret;
84 
85 	if (ptr == NULL)
86 		ret = malloc(size);
87 	else
88 		ret = realloc(ptr, size);
89 	if (ret == NULL) {
90 		int	err = geterrno();
91 
92 		errmsg(gettext("Cannot realloc memory for %s.\n"), msg);
93 		if (jmexval)
94 			err = jmexval;
95 		if (jmp == JM_EXIT)
96 			comexit(err);
97 		if (jmp != NULL)
98 			siglongjmp(jmp->jb, 1);
99 	}
100 	return (ret);
101 }
102 
103 EXPORT char *
__jsavestr(s,jmp)104 __jsavestr(s, jmp)
105 	const char	*s;
106 	sigjmps_t		*jmp;
107 {
108 	char	*ret = __jmalloc(strlen(s)+1, "saved string", jmp);
109 
110 	if (ret != NULL)
111 		strcpy(ret, s);
112 	return (ret);
113 }
114