1/*
2 * memory wrappers
3 *
4 * Copyright (c) Artem Bityutskiy, 2007, 2008
5 * Copyright 2001, 2002 Red Hat, Inc.
6 *           2001 David A. Schleef <ds@lineo.com>
7 *           2002 Axis Communications AB
8 *           2001, 2002 Erik Andersen <andersen@codepoet.org>
9 *           2004 University of Szeged, Hungary
10 *           2006 KaiGai Kohei <kaigai@ak.jp.nec.com>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
20 * the GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 */
26
27#ifndef __MTD_UTILS_XALLOC_H__
28#define __MTD_UTILS_XALLOC_H__
29
30#include <stdarg.h>
31#include <stdlib.h>
32#include <string.h>
33
34/*
35 * Mark these functions as unused so that gcc does not emit warnings
36 * when people include this header but don't use every function.
37 */
38
39__attribute__((unused))
40static void *xmalloc(size_t size)
41{
42	void *ptr = malloc(size);
43
44	if (ptr == NULL && size != 0)
45		sys_errmsg_die("out of memory");
46	return ptr;
47}
48
49__attribute__((unused))
50static void *xcalloc(size_t nmemb, size_t size)
51{
52	void *ptr = calloc(nmemb, size);
53
54	if (ptr == NULL && nmemb != 0 && size != 0)
55		sys_errmsg_die("out of memory");
56	return ptr;
57}
58
59__attribute__((unused))
60static void *xzalloc(size_t size)
61{
62	return xcalloc(1, size);
63}
64
65__attribute__((unused))
66static void *xrealloc(void *ptr, size_t size)
67{
68	ptr = realloc(ptr, size);
69	if (ptr == NULL && size != 0)
70		sys_errmsg_die("out of memory");
71	return ptr;
72}
73
74__attribute__((unused))
75static char *xstrdup(const char *s)
76{
77	char *t;
78
79	if (s == NULL)
80		return NULL;
81	t = strdup(s);
82	if (t == NULL)
83		sys_errmsg_die("out of memory");
84	return t;
85}
86
87#ifdef _GNU_SOURCE
88
89__attribute__((unused))
90static int xasprintf(char **strp, const char *fmt, ...)
91{
92	int cnt;
93	va_list ap;
94
95	va_start(ap, fmt);
96	cnt = vasprintf(strp, fmt, ap);
97	va_end(ap);
98
99	if (cnt == -1)
100		sys_errmsg_die("out of memory");
101
102	return cnt;
103}
104#endif
105
106#endif /* !__MTD_UTILS_XALLOC_H__ */
107