浏览代码

[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 年前
父节点
当前提交
13e4b9ec49
共有 1 个文件被更改,包括 14 次插入2 次删除
  1. 14
    2
      src/core/malloc.c

+ 14
- 2
src/core/malloc.c 查看文件

@@ -25,6 +25,7 @@ FILE_LICENCE ( GPL2_OR_LATER );
25 25
 #include <ipxe/io.h>
26 26
 #include <ipxe/list.h>
27 27
 #include <ipxe/init.h>
28
+#include <ipxe/refcnt.h>
28 29
 #include <ipxe/malloc.h>
29 30
 
30 31
 /** @file
@@ -35,10 +36,21 @@ FILE_LICENCE ( GPL2_OR_LATER );
35 36
 
36 37
 /** A free block of memory */
37 38
 struct memory_block {
38
-	/** List of free blocks */
39
-	struct list_head list;
40 39
 	/** Size of this block */
41 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 56
 #define MIN_MEMBLOCK_SIZE \

正在加载...
取消
保存