Skip to content

Commit

Permalink
Fix potential memory leak of tev->e_list by reordering list_add befor…
Browse files Browse the repository at this point in the history
…e epoll_ctl

This commit addresses a potential memory leak in tgt_event_add related to
tev->e_list. Previously, epoll_ctl(EPOLL_CTL_ADD) was called before
list_add. This sequence could lead to a race condition where the epoll event
is registered and immediately triggered, leading to EPOLL_CTL_DEL and
list_del being called before list_add, resulting in the event being removed
from epoll but never added to the list, causing a memory leak after calling
list_add (Because no one will call list_del to remove this tev->e_list anymore).

To prevent this, list_add is now called before epoll_ctl(EPOLL_CTL_ADD).
This ensures that the tev->e_list is added to the list before any
epoll events can be triggered, allowing proper cleanup by list_del in case
of an early EPOLL_CTL_DEL.

This change ensures the integrity of the event management system by preventing
memory leaks associated with tev->e_list during event registration.

Signed-off-by: JK Chen <[email protected]>
  • Loading branch information
jkchen1095 committed Aug 10, 2024
1 parent 0984d21 commit 8a41c08
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions usr/tgtd.c
Original file line number Diff line number Diff line change
Expand Up @@ -217,12 +217,13 @@ int tgt_event_add(int fd, int events, event_handler_t handler, void *data)
memset(&ev, 0, sizeof(ev));
ev.events = events;
ev.data.ptr = tev;
list_add(&tev->e_list, &tgt_events_list);
err = epoll_ctl(ep_fd, EPOLL_CTL_ADD, fd, &ev);
if (err) {
eprintf("Cannot add fd, %m\n");
list_del(&tev->e_list);
free(tev);
} else
list_add(&tev->e_list, &tgt_events_list);
}

return err;
}
Expand Down

0 comments on commit 8a41c08

Please sign in to comment.