1 /*
2  * Copyright (c) 2018 Red Hat, Inc. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License, version 2,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * Authors:
17  *   Martin Sehnoutka <msehnout@redhat.com>
18  */
19 
20 #define _GNU_SOURCE
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdarg.h>
25 #include <errno.h>
26 
safe_asprintf(char ** strp,const char * fmt,...)27 int __attribute__((__format__(printf, 2, 3))) safe_asprintf(char **strp, const char *fmt, ...)
28 {
29 	int ret;
30 	va_list args;
31 
32 	va_start(args, fmt);
33 	ret = vasprintf(&(*strp), fmt, args);
34 	va_end(args);
35 	if (ret < 0) {
36 		fprintf(stderr, "Memory allocation failure\n");
37 		exit(1);
38 	}
39 	return ret;
40 }
41 
safe_atoi(const char * s,int * ret_i)42 int safe_atoi(const char *s, int *ret_i)
43 {
44 	char *x = NULL;
45 	long l;
46 
47 	errno = 0;
48 	l = strtol(s, &x, 0);
49 
50 	if (!x || x == s || *x || errno)
51 		return errno > 0 ? -errno : -EINVAL;
52 
53 	if ((long)(int)l != l)
54 		return -ERANGE;
55 
56 	*ret_i = (int)l;
57 	return 0;
58 }
59 
60 /*!
61   \fn char safe_strdup(const char *s)
62   \brief strdup(3) that checks memory allocation or fail
63 
64   This function does the same as strdup(3) with additional memory allocation
65   check.  When check fails the function will cause program to exit.
66 
67   \param string to be duplicated
68   \return allocated duplicate
69 */
safe_strdup(const char * str)70 extern char __attribute__((warn_unused_result)) *safe_strdup(const char *str)
71 {
72 	char *ret;
73 
74 	if (!str)
75 		return NULL;
76 
77 	ret = strdup(str);
78 	if (!ret) {
79 		fprintf(stderr, "Memory allocation failure\n");
80 		exit(1);
81 	}
82 	return ret;
83 }
84