xref: /linux-6.15/lib/list_debug.c (revision 54acd439)
1 /*
2  * Copyright 2006, Red Hat, Inc., Dave Jones
3  * Released under the General Public License (GPL).
4  *
5  * This file contains the linked list validation for DEBUG_LIST.
6  */
7 
8 #include <linux/export.h>
9 #include <linux/list.h>
10 #include <linux/bug.h>
11 #include <linux/kernel.h>
12 #include <linux/rculist.h>
13 
14 /*
15  * Check that the data structures for the list manipulations are reasonably
16  * valid. Failures here indicate memory corruption (and possibly an exploit
17  * attempt).
18  */
19 
20 bool __list_add_valid(struct list_head *new, struct list_head *prev,
21 		      struct list_head *next)
22 {
23 	if (unlikely(next->prev != prev)) {
24 		WARN(1, "list_add corruption. next->prev should be prev (%p), but was %p. (next=%p).\n",
25 			prev, next->prev, next);
26 		return false;
27 	}
28 	if (unlikely(prev->next != next)) {
29 		WARN(1, "list_add corruption. prev->next should be next (%p), but was %p. (prev=%p).\n",
30 			next, prev->next, prev);
31 		return false;
32 	}
33 	if (unlikely(new == prev || new == next)) {
34 		WARN(1, "list_add double add: new=%p, prev=%p, next=%p.\n",
35 			new, prev, next);
36 		return false;
37 	}
38 	return true;
39 }
40 EXPORT_SYMBOL(__list_add_valid);
41 
42 void __list_del_entry(struct list_head *entry)
43 {
44 	struct list_head *prev, *next;
45 
46 	prev = entry->prev;
47 	next = entry->next;
48 
49 	if (WARN(next == LIST_POISON1,
50 		"list_del corruption, %p->next is LIST_POISON1 (%p)\n",
51 		entry, LIST_POISON1) ||
52 	    WARN(prev == LIST_POISON2,
53 		"list_del corruption, %p->prev is LIST_POISON2 (%p)\n",
54 		entry, LIST_POISON2) ||
55 	    WARN(prev->next != entry,
56 		"list_del corruption. prev->next should be %p, "
57 		"but was %p\n", entry, prev->next) ||
58 	    WARN(next->prev != entry,
59 		"list_del corruption. next->prev should be %p, "
60 		"but was %p\n", entry, next->prev))
61 		return;
62 
63 	__list_del(prev, next);
64 }
65 EXPORT_SYMBOL(__list_del_entry);
66 
67 /**
68  * list_del - deletes entry from list.
69  * @entry: the element to delete from the list.
70  * Note: list_empty on entry does not return true after this, the entry is
71  * in an undefined state.
72  */
73 void list_del(struct list_head *entry)
74 {
75 	__list_del_entry(entry);
76 	entry->next = LIST_POISON1;
77 	entry->prev = LIST_POISON2;
78 }
79 EXPORT_SYMBOL(list_del);
80