1 // SPDX-License-Identifier: GPL-2.0
3 * This is for all the tests relating directly to heap memory, including
4 * page allocation and slab allocations.
7 #include <linux/slab.h>
8 #include <linux/sched.h>
11 * This tries to stay within the next largest power-of-2 kmalloc cache
12 * to avoid actually overwriting anything important if it's not detected
15 void lkdtm_OVERWRITE_ALLOCATION(void)
18 u32
*data
= kmalloc(len
, GFP_KERNEL
);
22 data
[1024 / sizeof(u32
)] = 0x12345678;
26 void lkdtm_WRITE_AFTER_FREE(void)
31 * The slub allocator uses the first word to store the free
32 * pointer in some configurations. Use the middle of the
33 * allocation to avoid running into the freelist
35 size_t offset
= (len
/ sizeof(*base
)) / 2;
37 base
= kmalloc(len
, GFP_KERNEL
);
40 pr_info("Allocated memory %p-%p\n", base
, &base
[offset
* 2]);
41 pr_info("Attempting bad write to freed memory at %p\n",
44 base
[offset
] = 0x0abcdef0;
45 /* Attempt to notice the overwrite. */
46 again
= kmalloc(len
, GFP_KERNEL
);
49 pr_info("Hmm, didn't get the same memory range.\n");
52 void lkdtm_READ_AFTER_FREE(void)
57 * The slub allocator uses the first word to store the free
58 * pointer in some configurations. Use the middle of the
59 * allocation to avoid running into the freelist
61 size_t offset
= (len
/ sizeof(*base
)) / 2;
63 base
= kmalloc(len
, GFP_KERNEL
);
65 pr_info("Unable to allocate base memory.\n");
69 val
= kmalloc(len
, GFP_KERNEL
);
71 pr_info("Unable to allocate val memory.\n");
78 pr_info("Value in memory before free: %x\n", base
[offset
]);
82 pr_info("Attempting bad read from freed memory\n");
85 /* Good! Poisoning happened, so declare a win. */
86 pr_info("Memory correctly poisoned (%x)\n", saw
);
89 pr_info("Memory was not poisoned\n");
94 void lkdtm_WRITE_BUDDY_AFTER_FREE(void)
96 unsigned long p
= __get_free_page(GFP_KERNEL
);
98 pr_info("Unable to allocate free page\n");
102 pr_info("Writing to the buddy page before free\n");
103 memset((void *)p
, 0x3, PAGE_SIZE
);
106 pr_info("Attempting bad write to the buddy page after free\n");
107 memset((void *)p
, 0x78, PAGE_SIZE
);
108 /* Attempt to notice the overwrite. */
109 p
= __get_free_page(GFP_KERNEL
);
114 void lkdtm_READ_BUDDY_AFTER_FREE(void)
116 unsigned long p
= __get_free_page(GFP_KERNEL
);
121 pr_info("Unable to allocate free page\n");
125 val
= kmalloc(1024, GFP_KERNEL
);
127 pr_info("Unable to allocate val memory.\n");
136 pr_info("Value in memory before free: %x\n", base
[0]);
138 pr_info("Attempting to read from freed memory\n");
141 /* Good! Poisoning happened, so declare a win. */
142 pr_info("Memory correctly poisoned (%x)\n", saw
);
145 pr_info("Buddy page was not poisoned\n");