[Lguest] [RFC 5/6] lguest: exit decently if memory allocation fails

Sakari Ailus sakari.ailus at iki.fi
Sun Sep 2 02:07:47 EST 2012


malloc(3) was being used to allocate memory in various places but its return
value wasn't checked. Do that.

Signed-off-by: Sakari Ailus <sakari.ailus at iki.fi>
---
 tools/lguest/lguest.c |   19 +++++++++++++++++++
 1 files changed, 19 insertions(+), 0 deletions(-)

diff --git a/tools/lguest/lguest.c b/tools/lguest/lguest.c
index a903631..b316b8f 100644
--- a/tools/lguest/lguest.c
+++ b/tools/lguest/lguest.c
@@ -1027,6 +1027,9 @@ static void create_thread(struct virtqueue *vq)
 	unsigned long args[] = { LHREQ_EVENTFD,
 				 vq->config.pfn*getpagesize(), 0 };
 
+	if (!stack)
+		err(1, "can't allocate stack in create_thread");
+
 	/* Create a zero-initialized eventfd. */
 	vq->eventfd = eventfd(0, 0);
 	if (vq->eventfd < 0)
@@ -1199,6 +1202,9 @@ static void add_virtqueue(struct device *dev, unsigned int num_descs,
 	struct virtqueue **i, *vq = malloc(sizeof(*vq));
 	void *p;
 
+	if (!vq)
+		err(1, "can't allocate struct virtqueue");
+
 	/* First we need some memory for this virtqueue. */
 	pages = (vring_size(num_descs, LGUEST_VRING_ALIGN) + getpagesize() - 1)
 		/ getpagesize();
@@ -1292,6 +1298,9 @@ static struct device *new_device(const char *name, u16 type)
 {
 	struct device *dev = malloc(sizeof(*dev));
 
+	if (!dev)
+		err(1, "can't allocate struct device");
+
 	/* Now we populate the fields one at a time. */
 	dev->desc = new_dev_desc(type);
 	dev->name = name;
@@ -1338,6 +1347,8 @@ static void setup_console(void)
 
 	/* We store the console state in dev->priv, and initialize it. */
 	dev->priv = malloc(sizeof(struct console_abort));
+	if (!dev->priv)
+		err(1, "can't allocate struct console_abort");
 	((struct console_abort *)dev->priv)->count = 0;
 
 	/*
@@ -1509,6 +1520,9 @@ static void setup_tun_net(char *arg)
 	struct virtio_net_config virtio_conf;
 	bool has_virtio_conf = false;
 
+	if (!net_info)
+		err(1, "can't allocate struct net_info");
+
 	net_info->tunfd = get_tun_device(tapif);
 
 	/* First we create a new network device. */
@@ -1718,6 +1732,8 @@ static void setup_block_file(const char *filename)
 
 	/* Allocate the room for our own bookkeeping */
 	vblk = dev->priv = malloc(sizeof(*vblk));
+	if (!vblk)
+		err(1, "can't allocate struct vblk_info");
 
 	/* First we open the file and store the length. */
 	vblk->fd = open_or_die(filename, O_RDWR|O_LARGEFILE);
@@ -1791,6 +1807,9 @@ static void setup_rng(void)
 	struct device *dev;
 	struct rng_info *rng_info = malloc(sizeof(*rng_info));
 
+	if (!rng_info)
+		err(1, "can't allocate struct rng_info");
+
 	/* Our device's privat info simply contains the /dev/random fd. */
 	rng_info->rfd = open_or_die("/dev/random", O_RDONLY);
 
-- 
1.7.2.5



More information about the Lguest mailing list