@@ -76,6 +76,7 @@ import Graphics.Win32.Misc
76
76
import Graphics.Win32.GDI.Types (COLORREF )
77
77
78
78
import GHC.IO (bracket )
79
+ import GHC.IO.Exception (IOException (.. ), IOErrorType (OtherError ), ioError )
79
80
import Foreign.Ptr (plusPtr )
80
81
import Foreign.C.Types (CWchar )
81
82
import Foreign.C.String (withCWString , CWString )
@@ -171,15 +172,18 @@ getEnv name =
171
172
withCWString name $ \ c_name -> withTStringBufferLen maxLength $ \ (buf, len) -> do
172
173
let c_len = fromIntegral len
173
174
c_len' <- c_GetEnvironmentVariableW c_name buf c_len
174
- if c_len' == 0
175
- then do
176
- err_code <- getLastError
177
- if err_code == eERROR_ENVVAR_NOT_FOUND
178
- then return Nothing
179
- else errorWin " GetEnvironmentVariableW"
180
- else do
181
- let len' = fromIntegral c_len'
182
- Just <$> peekTStringLen (buf, len')
175
+ case c_len' of
176
+ 0 -> do
177
+ err_code <- getLastError
178
+ if err_code == eERROR_ENVVAR_NOT_FOUND
179
+ then return Nothing
180
+ else errorWin " GetEnvironmentVariableW"
181
+ _ | c_len' > fromIntegral maxLength ->
182
+ -- shouldn't happen, because we provide maxLength
183
+ ioError (IOError Nothing OtherError " GetEnvironmentVariableW" (" Unexpected return code: " <> show c_len') Nothing Nothing )
184
+ | otherwise -> do
185
+ let len' = fromIntegral c_len'
186
+ Just <$> peekTStringLen (buf, len')
183
187
where
184
188
-- according to https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getenvironmentvariablew
185
189
maxLength :: Int
0 commit comments