Browse Source

[malloc] Avoid immediately clobbering reference count when freeing memory

Rearrange the fields in struct memory_block (without altering
MIN_MEMBLOCK_SIZE) so that the "count" field of a reference-counted
object is left intact when the memory containing the object is freed.
This allows for the possibility of detecting reference-counting errors
such as double-freeing.

Signed-off-by: Michael Brown <mcb30@ipxe.org>
tags/v1.20.1
Michael Brown 14 years ago
parent
commit
13e4b9ec49
1 changed files with 14 additions and 2 deletions
  1. 14
    2
      src/core/malloc.c

+ 14
- 2
src/core/malloc.c View File

25
 #include <ipxe/io.h>
25
 #include <ipxe/io.h>
26
 #include <ipxe/list.h>
26
 #include <ipxe/list.h>
27
 #include <ipxe/init.h>
27
 #include <ipxe/init.h>
28
+#include <ipxe/refcnt.h>
28
 #include <ipxe/malloc.h>
29
 #include <ipxe/malloc.h>
29
 
30
 
30
 /** @file
31
 /** @file
35
 
36
 
36
 /** A free block of memory */
37
 /** A free block of memory */
37
 struct memory_block {
38
 struct memory_block {
38
-	/** List of free blocks */
39
-	struct list_head list;
40
 	/** Size of this block */
39
 	/** Size of this block */
41
 	size_t size;
40
 	size_t size;
41
+	/** Padding
42
+	 *
43
+	 * This padding exists to cover the "count" field of a
44
+	 * reference counter, in the common case where a reference
45
+	 * counter is the first element of a dynamically-allocated
46
+	 * object.  It avoids clobbering the "count" field as soon as
47
+	 * the memory is freed, and so allows for the possibility of
48
+	 * detecting reference counting errors.
49
+	 */
50
+	char pad[ offsetof ( struct refcnt, count ) +
51
+		  sizeof ( ( ( struct refcnt * ) NULL )->count ) ];
52
+	/** List of free blocks */
53
+	struct list_head list;
42
 };
54
 };
43
 
55
 
44
 #define MIN_MEMBLOCK_SIZE \
56
 #define MIN_MEMBLOCK_SIZE \

Loading…
Cancel
Save