Debian Codegraph @

src-bin-881/Clash/GHCi/Leak.hs

raw
1 {-# LANGUAGE LambdaCase #-}
2 {-# LANGUAGE RecordWildCards #-}
3
4 module Clash.GHCi.Leak
5 ( LeakIndicators
6 , getLeakIndicators
7 , checkLeakIndicators
8 ) where
9
10 import Control.Monad
11 import Data.Bits
12 import DynFlags ( sTargetPlatform )
13 import Foreign.Ptr (ptrToIntPtr, intPtrToPtr)
14 import GHC
15 import GHC.Ptr (Ptr (..))
16 import Clash.GHCi.Util
17 import HscTypes
18 import Outputable
19 import Platform (target32Bit)
20 import Prelude
21 import System.Mem
22 import System.Mem.Weak
23 import UniqDFM
24
25 -- Checking for space leaks in GHCi. See #15111, and the
26 -- -fghci-leak-check flag.
27
28 data LeakIndicators = LeakIndicators [LeakModIndicators]
29
30 data LeakModIndicators = LeakModIndicators
31 { leakMod :: Weak HomeModInfo
32 , leakIface :: Weak ModIface
33 , leakDetails :: Weak ModDetails
34 , leakLinkable :: Maybe (Weak Linkable)
35 }
36
37 -- | Grab weak references to some of the data structures representing
38 -- the currently loaded modules.
39 getLeakIndicators :: HscEnv -> IO LeakIndicators
40 getLeakIndicators HscEnv{..} =
41 fmap LeakIndicators $
42 forM (eltsUDFM hsc_HPT) $ \hmi@HomeModInfo{..} -> do
43 leakMod <- mkWeakPtr hmi Nothing
44 leakIface <- mkWeakPtr hm_iface Nothing
45 leakDetails <- mkWeakPtr hm_details Nothing
46 leakLinkable <- mapM (`mkWeakPtr` Nothing) hm_linkable
47 return $ LeakModIndicators{..}
48
49 -- | Look at the LeakIndicators collected by an earlier call to
50 -- `getLeakIndicators`, and print messasges if any of them are still
51 -- alive.
52 checkLeakIndicators :: DynFlags -> LeakIndicators -> IO ()
53 checkLeakIndicators dflags (LeakIndicators leakmods) = do
54 performGC
55 forM_ leakmods $ \LeakModIndicators{..} -> do
56 deRefWeak leakMod >>= \case
57 Nothing -> return ()
58 Just hmi ->
59 report ("HomeModInfo for " ++
60 showSDoc dflags (ppr (mi_module (hm_iface hmi)))) (Just hmi)
61 deRefWeak leakIface >>= report "ModIface"
62 deRefWeak leakDetails >>= report "ModDetails"
63 forM_ leakLinkable $ \l -> deRefWeak l >>= report "Linkable"
64 where
65 report :: String -> Maybe a -> IO ()
66 report _ Nothing = return ()
67 report msg (Just a) = do
68 addr <- anyToPtr a
69 putStrLn ("-fghci-leak-check: " ++ msg ++ " is still alive at " ++
70 show (maskTagBits addr))
71
72 tagBits
73 | target32Bit (sTargetPlatform (settings dflags)) = 2
74 | otherwise = 3
75
76 maskTagBits :: Ptr a -> Ptr a
77 maskTagBits p = intPtrToPtr (ptrToIntPtr p .&. complement (shiftL 1 tagBits - 1))