]>
git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - drivers/misc/lkdtm_heap.c
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
);
20 data
[1024 / sizeof(u32
)] = 0x12345678;
24 void lkdtm_WRITE_AFTER_FREE(void)
29 * The slub allocator uses the first word to store the free
30 * pointer in some configurations. Use the middle of the
31 * allocation to avoid running into the freelist
33 size_t offset
= (len
/ sizeof(*base
)) / 2;
35 base
= kmalloc(len
, GFP_KERNEL
);
36 pr_info("Allocated memory %p-%p\n", base
, &base
[offset
* 2]);
37 pr_info("Attempting bad write to freed memory at %p\n",
40 base
[offset
] = 0x0abcdef0;
41 /* Attempt to notice the overwrite. */
42 again
= kmalloc(len
, GFP_KERNEL
);
45 pr_info("Hmm, didn't get the same memory range.\n");
48 void lkdtm_READ_AFTER_FREE(void)
53 * The slub allocator uses the first word to store the free
54 * pointer in some configurations. Use the middle of the
55 * allocation to avoid running into the freelist
57 size_t offset
= (len
/ sizeof(*base
)) / 2;
59 base
= kmalloc(len
, GFP_KERNEL
);
61 pr_info("Unable to allocate base memory.\n");
65 val
= kmalloc(len
, GFP_KERNEL
);
67 pr_info("Unable to allocate val memory.\n");
74 pr_info("Value in memory before free: %x\n", base
[offset
]);
78 pr_info("Attempting bad read from freed memory\n");
81 /* Good! Poisoning happened, so declare a win. */
82 pr_info("Memory correctly poisoned (%x)\n", saw
);
85 pr_info("Memory was not poisoned\n");
90 void lkdtm_WRITE_BUDDY_AFTER_FREE(void)
92 unsigned long p
= __get_free_page(GFP_KERNEL
);
94 pr_info("Unable to allocate free page\n");
98 pr_info("Writing to the buddy page before free\n");
99 memset((void *)p
, 0x3, PAGE_SIZE
);
102 pr_info("Attempting bad write to the buddy page after free\n");
103 memset((void *)p
, 0x78, PAGE_SIZE
);
104 /* Attempt to notice the overwrite. */
105 p
= __get_free_page(GFP_KERNEL
);
110 void lkdtm_READ_BUDDY_AFTER_FREE(void)
112 unsigned long p
= __get_free_page(GFP_KERNEL
);
117 pr_info("Unable to allocate free page\n");
121 val
= kmalloc(1024, GFP_KERNEL
);
123 pr_info("Unable to allocate val memory.\n");
132 pr_info("Value in memory before free: %x\n", base
[0]);
134 pr_info("Attempting to read from freed memory\n");
137 /* Good! Poisoning happened, so declare a win. */
138 pr_info("Memory correctly poisoned (%x)\n", saw
);
141 pr_info("Buddy page was not poisoned\n");