From c433d2a5e858f0a06a22bf87be2740fd88db91ae Mon Sep 17 00:00:00 2001 From: Andrzej Rybczak Date: Mon, 25 Nov 2024 20:14:34 +0100 Subject: [PATCH] Fix memory leak in getaddrinfo and make it async exception safe https://github.com/haskell/network/pull/587 removed the call to `c_freeaddrinfo` in `getaddrinfo`. This restores it and in addition makes the function async exception safe. --- Network/Socket/Info.hsc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Network/Socket/Info.hsc b/Network/Socket/Info.hsc index c70109f7..a7eadeed 100644 --- a/Network/Socket/Info.hsc +++ b/Network/Socket/Info.hsc @@ -7,6 +7,7 @@ module Network.Socket.Info where +import Control.Exception (mask, onException) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as NE import Foreign.Marshal.Alloc (alloca, allocaBytes) @@ -274,11 +275,12 @@ getAddrInfoNE hints node service = alloc getaddrinfo maybeWith with filteredHints $ \c_hints -> alloca $ \ptr_ptr_addrs -> body c_node c_service c_hints ptr_ptr_addrs - getaddrinfo c_node c_service c_hints ptr_ptr_addrs = do + getaddrinfo c_node c_service c_hints ptr_ptr_addrs = mask $ \release -> do ret <- c_getaddrinfo c_node c_service c_hints ptr_ptr_addrs if ret == 0 then do ptr_addrs <- peek ptr_ptr_addrs - ais <- followAddrInfo ptr_addrs + ais <- release (followAddrInfo ptr_addrs) `onException` c_freeaddrinfo ptr_addrs + c_freeaddrinfo ptr_addrs return ais else do err <- gai_strerror ret