VPP-152: mheap_alloc returns 0 when the requested heap size is too small 21/1621/2
authorPierre Pfister <ppfister@cisco.com>
Fri, 17 Jun 2016 12:30:02 +0000 (13:30 +0100)
committerDave Barach <openvpp@barachs.net>
Sun, 19 Jun 2016 13:31:59 +0000 (13:31 +0000)
mheap_alloc allocates memory_size bytes of memory and returns
a page-aligned memory space prefixed with a word-aligned
header of type mheap_t.

This header includes the actual usable space size, but
when the requested size is too small, the computed size
was incorrect (infinite).

mheap_alloc now returns 0 in such cases.

With help from Yoann Desmouceaux.

Change-Id: I00af63d573d6939aca53dbe7ff612b726bd8f0df
Signed-off-by: Pierre Pfister <ppfister@cisco.com>
vppinfra/vppinfra/mheap.c
vppinfra/vppinfra/mheap.h

index cd8672e..6163d0b 100644 (file)
@@ -874,6 +874,15 @@ void * mheap_alloc_with_flags (void * memory, uword memory_size, uword flags)
     h = uword_to_pointer (ah, void *);
     v = mheap_vector (h);
 
+    if (PREDICT_FALSE(memory + memory_size < v)) {
+       /*
+        * This will happen when the requested memory_size is too
+        * small to cope with the heap header and/or memory alignment.
+        */
+       clib_mem_vm_free(memory, memory_size);
+       return 0;
+    }
+
     size = memory + memory_size - v;
   }
 
index c9eb60d..a40c26c 100644 (file)
 always_inline void * mheap_get (void * v, uword size, uword * offset_return)
 { return mheap_get_aligned (v, size, 0, 0, offset_return); }
 
-/* Create allocation heap of given size. */
+/* Create allocation heap of given size.
+ * The actual usable size is smaller than the requested size.
+ * memory_bytes must be greater than mheap_page_size + sizeof (mheap_t) + 16.
+ * Otherwise, allocation may fail and return 0.
+ */
 void * mheap_alloc (void * memory, uword memory_bytes);
 void * mheap_alloc_with_flags (void * memory, uword memory_bytes, uword flags);