Commit 6cf93e4
committed
Fix use-after-free race in socket driver close
https://ampcode.com/threads/T-019cb8b8-9e4c-7316-9566-c7e3f5f2b6db
Fix a use-after-free race condition in the generic_unix socket driver's close
handler, detected by Valgrind during CI gen_tcp tests.
The close handler in socket_consume_mailbox used a two-phase locking pattern:
it acquired the glb->listeners lock to NULL-out the socket_data listener
pointers, released it, then called sys_unregister_listener (which re-acquires
the lock) to remove the listener from the linked list. Between the unlock and
re-lock, the event loop thread could also unlink the same listener node via
process_listener_handler after the callback returned NULL. The subsequent
list_remove in sys_unregister_listener then operated on stale prev/next
pointers, corrupting the list or writing to freed memory.
The fix makes the pointer detach and list unlink atomic under a single lock hold
by introducing sys_unregister_listener_nolock — a variant that assumes the
caller already holds the glb->listeners write lock. The close handler now
NULLs the pointers, unlinks the listeners, and releases the lock before freeing
the memory.
This pattern is specific to generic_unix; ESP32 and RP2 use a single global
listener for the socket driver subsystem and are not affected.
Signed-off-by: Peter M <petermm@gmail.com>1 parent e2dda4e commit 6cf93e4
2 files changed
+19
-16
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
47 | 47 | | |
48 | 48 | | |
49 | 49 | | |
| 50 | + | |
| 51 | + | |
50 | 52 | | |
51 | 53 | | |
52 | 54 | | |
| |||
1194 | 1196 | | |
1195 | 1197 | | |
1196 | 1198 | | |
1197 | | - | |
1198 | | - | |
1199 | | - | |
1200 | | - | |
1201 | | - | |
1202 | | - | |
| 1199 | + | |
| 1200 | + | |
| 1201 | + | |
| 1202 | + | |
| 1203 | + | |
| 1204 | + | |
1203 | 1205 | | |
1204 | 1206 | | |
1205 | 1207 | | |
1206 | 1208 | | |
1207 | 1209 | | |
1208 | | - | |
1209 | 1210 | | |
1210 | | - | |
1211 | | - | |
1212 | | - | |
1213 | | - | |
1214 | | - | |
1215 | | - | |
1216 | | - | |
| 1211 | + | |
1217 | 1212 | | |
1218 | 1213 | | |
1219 | | - | |
1220 | | - | |
| 1214 | + | |
1221 | 1215 | | |
| 1216 | + | |
| 1217 | + | |
| 1218 | + | |
1222 | 1219 | | |
1223 | 1220 | | |
1224 | 1221 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
698 | 698 | | |
699 | 699 | | |
700 | 700 | | |
| 701 | + | |
| 702 | + | |
| 703 | + | |
| 704 | + | |
| 705 | + | |
| 706 | + | |
701 | 707 | | |
702 | 708 | | |
703 | 709 | | |
| |||
0 commit comments