add missing error checking for various allocations
Bug: None
Test: `make check` passes
Change-Id: I4a60cca7167b61f61e2987a1c2bff05b53b31238
diff --git a/minijail0_cli.c b/minijail0_cli.c
index c3da5de..22da7fd 100644
--- a/minijail0_cli.c
+++ b/minijail0_cli.c
@@ -29,6 +29,30 @@
#define IDMAP_LEN 32U
#define DEFAULT_TMP_SIZE (64 * 1024 * 1024)
+/*
+ * A malloc() that aborts on failure. We only implement this in the CLI as
+ * the library should return ENOMEM errors when allocations fail.
+ */
+static void *xmalloc(size_t size)
+{
+ void *ret = malloc(size);
+ if (!ret) {
+ perror("malloc() failed");
+ exit(1);
+ }
+ return ret;
+}
+
+static char *xstrdup(const char *s)
+{
+ char *ret = strdup(s);
+ if (!ret) {
+ perror("strdup() failed");
+ exit(1);
+ }
+ return ret;
+}
+
static void set_user(struct minijail *j, const char *arg, uid_t *out_uid,
gid_t *out_gid)
{
@@ -289,7 +313,7 @@
static char *build_idmap(id_t id, id_t lowerid)
{
int ret;
- char *idmap = malloc(IDMAP_LEN);
+ char *idmap = xmalloc(IDMAP_LEN);
ret = snprintf(idmap, IDMAP_LEN, "%d %d 1", id, lowerid);
if (ret < 0 || (size_t)ret >= IDMAP_LEN) {
free(idmap);
@@ -487,12 +511,7 @@
rewind(f);
filter->len = filter_size / sizeof(struct sock_filter);
- filter->filter = malloc(filter_size);
- if (!filter->filter) {
- fclose(f);
- fprintf(stderr, "failed to allocate memory for filter: %m");
- exit(1);
- }
+ filter->filter = xmalloc(filter_size);
if (fread(filter->filter, sizeof(struct sock_filter), filter->len, f) !=
filter->len) {
fclose(f);
@@ -820,7 +839,7 @@
uidmap = NULL;
}
if (optarg)
- uidmap = strdup(optarg);
+ uidmap = xstrdup(optarg);
break;
case 'M':
set_gidmap = 1;
@@ -829,7 +848,7 @@
gidmap = NULL;
}
if (optarg)
- gidmap = strdup(optarg);
+ gidmap = xstrdup(optarg);
break;
case 'a':
if (0 != minijail_use_alt_syscall(j, optarg)) {