haskell-debugger 0.14.0.0 → 0.15.0.0
raw patch · 77 files changed
+3396/−1530 lines, 77 filesdep ~dapdep ~stmdep ~temporaryPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: dap, stm, temporary, unix
API changes (from Hackage documentation)
- GHC.Debugger.Breakpoint: AntiQuote :: String -> StringPart
- GHC.Debugger.Breakpoint: Literal :: String -> StringPart
- GHC.Debugger.Breakpoint: breakpointStatusInt :: BreakpointStatus -> Int
- GHC.Debugger.Breakpoint: data StringPart
- GHC.Debugger.Breakpoint: findBreakpoint :: Module -> Int -> Maybe Int -> Debugger (Maybe (Int, RealSrcSpan))
- GHC.Debugger.Breakpoint: getActiveBreakpoints :: Maybe AbsFilePath -> Debugger [InternalBreakpointId]
- GHC.Debugger.Breakpoint: getInternalBreaksOf :: BreakpointId -> Debugger [InternalBreakpointId]
- GHC.Debugger.Breakpoint: getModuleByPath :: AbsFilePath -> Debugger (Either SDoc ModuleNodeInfo)
- GHC.Debugger.Breakpoint: parseQC :: String -> String -> [StringPart]
- GHC.Debugger.Breakpoint: registerBreakpoint :: BreakpointId -> BreakpointInfo -> Debugger (Bool, [InternalBreakpointId])
- GHC.Debugger.Breakpoint: unQC :: String -> String -> [StringPart]
- GHC.Debugger.Breakpoint.Map: data BreakpointMap a
- GHC.Debugger.Breakpoint.Map: delete :: InternalBreakpointId -> BreakpointMap a -> BreakpointMap a
- GHC.Debugger.Breakpoint.Map: empty :: BreakpointMap a
- GHC.Debugger.Breakpoint.Map: insert :: InternalBreakpointId -> a -> BreakpointMap a -> BreakpointMap a
- GHC.Debugger.Breakpoint.Map: instance GHC.Debugger.View.Class.DebugView (GHC.Debugger.Breakpoint.Map.BreakpointMap a)
- GHC.Debugger.Breakpoint.Map: instance GHC.Utils.Outputable.Outputable a => GHC.Utils.Outputable.Outputable (GHC.Debugger.Breakpoint.Map.BreakpointMap a)
- GHC.Debugger.Breakpoint.Map: keys :: BreakpointMap a -> [InternalBreakpointId]
- GHC.Debugger.Breakpoint.Map: lookup :: InternalBreakpointId -> BreakpointMap a -> Maybe a
- GHC.Debugger.Breakpoint.Map: lookupModuleIBIs :: Module -> BreakpointMap a -> [InternalBreakpointId]
- GHC.Debugger.Breakpoint.Map: toList :: BreakpointMap a -> [(InternalBreakpointId, a)]
- GHC.Debugger.Interface.Messages: DidContinue :: EvalResult -> Response
- GHC.Debugger.Interface.Messages: DidStep :: EvalResult -> Response
- GHC.Debugger.Interface.Messages: DoContinue :: Command
- GHC.Debugger.Interface.Messages: DoSingleStep :: Command
- GHC.Debugger.Interface.Messages: DoStepLocal :: Command
- GHC.Debugger.Interface.Messages: DoStepOut :: Command
- GHC.Debugger.Monad: BreakpointAfterCount :: Int -> BreakpointStatus
- GHC.Debugger.Monad: BreakpointAfterCountCond :: Int -> String -> BreakpointStatus
- GHC.Debugger.Monad: BreakpointDisabled :: BreakpointStatus
- GHC.Debugger.Monad: BreakpointEnabled :: BreakpointStatus
- GHC.Debugger.Monad: BreakpointInfo :: BreakpointStatus -> BreakpointKind -> BreakpointAction -> BreakpointInfo
- GHC.Debugger.Monad: BreakpointLogAndResume :: String -> BreakpointAction
- GHC.Debugger.Monad: BreakpointStop :: BreakpointAction
- GHC.Debugger.Monad: BreakpointWhenCond :: String -> BreakpointStatus
- GHC.Debugger.Monad: Debugger :: ReaderT DebuggerState Ghc a -> Debugger a
- GHC.Debugger.Monad: DebuggerFailedToLoad :: DebuggerFailedToLoad
- GHC.Debugger.Monad: DebuggerState :: IORef (BreakpointMap BreakpointInfo) -> IORef RuntimeInstancesCache -> IORef ThreadMap -> IORef CompCache -> Maybe UnitId -> LogAction Debugger DebuggerLog -> DebuggerState
- GHC.Debugger.Monad: FailedToLoadFFIInspectModule :: FailedToLoadFFIInspectModule
- GHC.Debugger.Monad: NonFatalException :: String -> String -> NonFatalException
- GHC.Debugger.Monad: ProjectDebugSpec :: FilePath -> FilePath -> FilePath -> [String] -> [String] -> FilePath -> [String] -> ProjectDebugSpec
- GHC.Debugger.Monad: RunDebuggerSettings :: Bool -> Bool -> InterpreterSettings -> RunDebuggerSettings
- GHC.Debugger.Monad: UnsupportedHsDbgViewVersion :: [(Version, Version)] -> Version -> UnsupportedHsDbgViewVersion
- GHC.Debugger.Monad: [absEntryFile] :: ProjectDebugSpec -> FilePath
- GHC.Debugger.Monad: [activeBreakpoints] :: DebuggerState -> IORef (BreakpointMap BreakpointInfo)
- GHC.Debugger.Monad: [actualVersion] :: UnsupportedHsDbgViewVersion -> Version
- GHC.Debugger.Monad: [bpInfoAction] :: BreakpointInfo -> BreakpointAction
- GHC.Debugger.Monad: [bpInfoKind] :: BreakpointInfo -> BreakpointKind
- GHC.Debugger.Monad: [bpInfoStatus] :: BreakpointInfo -> BreakpointStatus
- GHC.Debugger.Monad: [compCache] :: DebuggerState -> IORef CompCache
- GHC.Debugger.Monad: [componentDir] :: ProjectDebugSpec -> FilePath
- GHC.Debugger.Monad: [dbgLogger] :: DebuggerState -> LogAction Debugger DebuggerLog
- GHC.Debugger.Monad: [debugMessage] :: NonFatalException -> String
- GHC.Debugger.Monad: [extraGhcArgs] :: ProjectDebugSpec -> [String]
- GHC.Debugger.Monad: [ghcInvocation] :: ProjectDebugSpec -> [String]
- GHC.Debugger.Monad: [hsDbgViewUnitId] :: DebuggerState -> Maybe UnitId
- GHC.Debugger.Monad: [interpreterSettings] :: RunDebuggerSettings -> InterpreterSettings
- GHC.Debugger.Monad: [libdir] :: ProjectDebugSpec -> FilePath
- GHC.Debugger.Monad: [rootDir] :: ProjectDebugSpec -> FilePath
- GHC.Debugger.Monad: [rtinstancesCache] :: DebuggerState -> IORef RuntimeInstancesCache
- GHC.Debugger.Monad: [supportedVersions] :: UnsupportedHsDbgViewVersion -> [(Version, Version)]
- GHC.Debugger.Monad: [supportsANSIHyperlinks] :: RunDebuggerSettings -> Bool
- GHC.Debugger.Monad: [supportsANSIStyling] :: RunDebuggerSettings -> Bool
- GHC.Debugger.Monad: [threadMap] :: DebuggerState -> IORef ThreadMap
- GHC.Debugger.Monad: [unDebugger] :: Debugger a -> ReaderT DebuggerState Ghc a
- GHC.Debugger.Monad: [units] :: ProjectDebugSpec -> [String]
- GHC.Debugger.Monad: [userMessage] :: NonFatalException -> String
- GHC.Debugger.Monad: annotateDebuggerStackString :: String -> Debugger a -> Debugger a
- GHC.Debugger.Monad: data BreakpointAction
- GHC.Debugger.Monad: data BreakpointInfo
- GHC.Debugger.Monad: data BreakpointStatus
- GHC.Debugger.Monad: data DebuggerFailedToLoad
- GHC.Debugger.Monad: data DebuggerState
- GHC.Debugger.Monad: data FailedToLoadFFIInspectModule
- GHC.Debugger.Monad: data NonFatalException
- GHC.Debugger.Monad: data ProjectDebugSpec
- GHC.Debugger.Monad: data RunDebuggerSettings
- GHC.Debugger.Monad: data UnsupportedHsDbgViewVersion
- GHC.Debugger.Monad: deepseqTerm :: HscEnv -> Term -> IO Term
- GHC.Debugger.Monad: defaultDepth :: Int
- GHC.Debugger.Monad: doDownsweep :: GhcMonad m => Maybe ModuleGraph -> m ModuleGraph
- GHC.Debugger.Monad: doLoad :: GhcMonad m => Maybe ModIfaceCache -> LoadHowMuch -> ModuleGraph -> m SuccessFlag
- GHC.Debugger.Monad: expectRight :: Exception e => Either e a -> Debugger a
- GHC.Debugger.Monad: findHsDebuggerViewUnitId :: Ghc (Maybe UnitId)
- GHC.Debugger.Monad: findOrLoadHaskellDebuggerView :: LogAction IO DebuggerLog -> Ways -> Ghc (UnitId, [ModuleName])
- GHC.Debugger.Monad: getAllLoadedModules :: GhcMonad m => m [ModuleNodeInfo]
- GHC.Debugger.Monad: getAllLoadedModulesWithPaths :: GhcMonad m => m [(AbsFilePath, ModuleNodeInfo)]
- GHC.Debugger.Monad: getHsDebuggerViewUid :: Debugger (Maybe UnitId)
- GHC.Debugger.Monad: initialDebuggerState :: LogAction Debugger DebuggerLog -> Maybe UnitId -> Ghc DebuggerState
- GHC.Debugger.Monad: instance Control.Monad.Catch.MonadCatch GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance Control.Monad.Catch.MonadMask GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance Control.Monad.Catch.MonadThrow GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance Control.Monad.Reader.Class.MonadReader GHC.Debugger.Monad.DebuggerState GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Driver.DynFlags.HasDynFlags GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Driver.Monad.GhcMonad GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Internal.Base.Applicative GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Internal.Base.Functor GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Internal.Base.Monad GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Internal.Classes.Eq GHC.Debugger.Monad.BreakpointAction
- GHC.Debugger.Monad: instance GHC.Internal.Classes.Eq GHC.Debugger.Monad.BreakpointInfo
- GHC.Debugger.Monad: instance GHC.Internal.Classes.Eq GHC.Debugger.Monad.BreakpointStatus
- GHC.Debugger.Monad: instance GHC.Internal.Classes.Ord GHC.Debugger.Monad.BreakpointAction
- GHC.Debugger.Monad: instance GHC.Internal.Classes.Ord GHC.Debugger.Monad.BreakpointStatus
- GHC.Debugger.Monad: instance GHC.Internal.Control.Monad.IO.Class.MonadIO GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.DebuggerFailedToLoad
- GHC.Debugger.Monad: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.FailedToLoadFFIInspectModule
- GHC.Debugger.Monad: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.NonFatalException
- GHC.Debugger.Monad: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.UnsupportedHsDbgViewVersion
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.BreakpointAction
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.BreakpointInfo
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.BreakpointStatus
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.DebuggerFailedToLoad
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.FailedToLoadFFIInspectModule
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.NonFatalException
- GHC.Debugger.Monad: instance GHC.Internal.Show.Show GHC.Debugger.Monad.UnsupportedHsDbgViewVersion
- GHC.Debugger.Monad: instance GHC.Utils.Logger.HasLogger GHC.Debugger.Monad.Debugger
- GHC.Debugger.Monad: instance GHC.Utils.Outputable.Outputable GHC.Debugger.Monad.BreakpointAction
- GHC.Debugger.Monad: instance GHC.Utils.Outputable.Outputable GHC.Debugger.Monad.BreakpointStatus
- GHC.Debugger.Monad: liftGhc :: Ghc a -> Debugger a
- GHC.Debugger.Monad: loadFFIInspect :: LogAction IO DebuggerLog -> Ways -> Ghc ()
- GHC.Debugger.Monad: loadInMemoryModules :: LogAction IO DebuggerLog -> UnitId -> [(ModuleName, StringBuffer)] -> Ghc [SuccessFlag]
- GHC.Debugger.Monad: loadInternal :: LogAction IO DebuggerLog -> Ways -> Ghc ()
- GHC.Debugger.Monad: logSDoc :: Severity -> SDoc -> Debugger ()
- GHC.Debugger.Monad: newtype Debugger a
- GHC.Debugger.Monad: seqTerm :: HscEnv -> Term -> IO Term
- GHC.Debugger.Monad: type DebugRunner (m :: Type -> Type) a = DebugSession m a -> IO a
- GHC.Debugger.Monad: type DebugSession (m :: Type -> Type) a = FilePath -> [String] -> m () -> Ghc a
- GHC.Debugger.Run: addImport :: String -> Debugger EvalResult
- GHC.Debugger.Run: continueToCompletion :: Debugger ExecResult
- GHC.Debugger.Run: doContinue :: Debugger EvalResult
- GHC.Debugger.Run: doEval :: String -> Debugger EvalResult
- GHC.Debugger.Run: doLocalStep :: Debugger EvalResult
- GHC.Debugger.Run: doSingleStep :: Debugger EvalResult
- GHC.Debugger.Run: doStepOut :: Debugger EvalResult
- GHC.Debugger.Run: getRemoteThreadIdFromContext :: Debugger RemoteThreadId
- GHC.Debugger.Run: handleExecResult :: ExecResult -> Debugger EvalResult
- GHC.Debugger.Run: inspectName :: Name -> Debugger (Maybe VarInfo)
- GHC.Debugger.Run: withCurrentBreakEnv :: Debugger a -> Debugger a
- GHC.Debugger.Runtime: expandTerm :: HscEnv -> Term -> IO Term
- GHC.Debugger.Runtime: obtainTerm :: TermKey -> Debugger Term
- GHC.Debugger.Runtime.Thread.Map: emptyThreadMap :: ThreadMap
- GHC.Debugger.Runtime.Thread.Map: insertThreadMap :: Int -> ForeignRef ThreadId -> ThreadMap -> ThreadMap
- GHC.Debugger.Runtime.Thread.Map: lookupThreadMap :: Int -> ThreadMap -> Maybe (ForeignRef ThreadId)
- GHC.Debugger.Runtime.Thread.Map: threadMapToList :: ThreadMap -> [(Int, ForeignRef ThreadId)]
- GHC.Debugger.Runtime.Thread.Map: type ThreadMap = IntMap ForeignRef ThreadId
- GHC.Debugger.Session: resumeExec :: GhcMonad m => SingleStep -> Maybe Int -> m ExecResult
- GHC.Debugger.Session.Interactive: defineNoPrint :: Ghc Name
- GHC.Debugger.Stopped: getTopEnv :: Module -> Debugger TypeEnv
- GHC.Debugger.Stopped: getTopImported :: Module -> Debugger GlobalRdrEnv
- GHC.Debugger.Stopped.Variables: forceTerm :: Term -> Debugger Term
- GHC.Debugger.Stopped.Variables: pprTerm :: Term -> SDoc
+ GHC.Debugger.Data.BreakpointMap: data BreakpointMap a
+ GHC.Debugger.Data.BreakpointMap: delete :: InternalBreakpointId -> BreakpointMap a -> BreakpointMap a
+ GHC.Debugger.Data.BreakpointMap: empty :: BreakpointMap a
+ GHC.Debugger.Data.BreakpointMap: insert :: InternalBreakpointId -> a -> BreakpointMap a -> BreakpointMap a
+ GHC.Debugger.Data.BreakpointMap: instance GHC.Debugger.View.Class.DebugView (GHC.Debugger.Data.BreakpointMap.BreakpointMap a)
+ GHC.Debugger.Data.BreakpointMap: instance GHC.Utils.Outputable.Outputable a => GHC.Utils.Outputable.Outputable (GHC.Debugger.Data.BreakpointMap.BreakpointMap a)
+ GHC.Debugger.Data.BreakpointMap: keys :: BreakpointMap a -> [InternalBreakpointId]
+ GHC.Debugger.Data.BreakpointMap: lookup :: InternalBreakpointId -> BreakpointMap a -> Maybe a
+ GHC.Debugger.Data.BreakpointMap: lookupModuleIBIs :: Module -> BreakpointMap a -> [InternalBreakpointId]
+ GHC.Debugger.Data.BreakpointMap: toList :: BreakpointMap a -> [(InternalBreakpointId, a)]
+ GHC.Debugger.Data.Supervisor: ChildFailed :: Unique -> ThreadId -> SomeException -> ChildFailed
+ GHC.Debugger.Data.Supervisor: Ignore :: OnFailure
+ GHC.Debugger.Data.Supervisor: Propagate :: OnFailure
+ GHC.Debugger.Data.Supervisor: SupervisorShutdown :: Unique -> SupervisorShutdown
+ GHC.Debugger.Data.Supervisor: awaitAll :: Supervisor -> Maybe Int -> IO ()
+ GHC.Debugger.Data.Supervisor: data ChildFailed
+ GHC.Debugger.Data.Supervisor: data OnFailure
+ GHC.Debugger.Data.Supervisor: data Supervisor
+ GHC.Debugger.Data.Supervisor: instance GHC.Internal.Classes.Eq GHC.Debugger.Data.Supervisor.OnFailure
+ GHC.Debugger.Data.Supervisor: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Data.Supervisor.ChildFailed
+ GHC.Debugger.Data.Supervisor: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Data.Supervisor.SupervisorShutdown
+ GHC.Debugger.Data.Supervisor: instance GHC.Internal.Show.Show GHC.Debugger.Data.Supervisor.ChildFailed
+ GHC.Debugger.Data.Supervisor: instance GHC.Internal.Show.Show GHC.Debugger.Data.Supervisor.OnFailure
+ GHC.Debugger.Data.Supervisor: instance GHC.Internal.Show.Show GHC.Debugger.Data.Supervisor.SupervisorShutdown
+ GHC.Debugger.Data.Supervisor: newtype SupervisorShutdown
+ GHC.Debugger.Data.Supervisor: registerForShutdown :: Supervisor -> IO () -> IO ()
+ GHC.Debugger.Data.Supervisor: spawn :: Supervisor -> OnFailure -> IO () -> IO ThreadId
+ GHC.Debugger.Data.Supervisor: throwToParent :: Exception e => Supervisor -> e -> IO ()
+ GHC.Debugger.Data.Supervisor: withSupervisor :: Maybe Int -> (Supervisor -> IO a) -> IO a
+ GHC.Debugger.Data.ThreadMap: deleteThreadMap :: Int -> ThreadMap a -> ThreadMap a
+ GHC.Debugger.Data.ThreadMap: emptyThreadMap :: ThreadMap a
+ GHC.Debugger.Data.ThreadMap: insertThreadMap :: Int -> a -> ThreadMap a -> ThreadMap a
+ GHC.Debugger.Data.ThreadMap: lookupThreadMap :: Int -> ThreadMap a -> Maybe a
+ GHC.Debugger.Data.ThreadMap: threadMapToList :: ThreadMap a -> [(Int, a)]
+ GHC.Debugger.Data.ThreadMap: type ThreadMap a = IntMap a
+ GHC.Debugger.Debuggee: mkInterpreterFlags :: Bool -> String -> [String] -> DynFlags -> DynFlags
+ GHC.Debugger.Interface.Messages: DidResume :: EvalResult -> Response
+ GHC.Debugger.Interface.Messages: DidTerminate :: Bool -> Response
+ GHC.Debugger.Interface.Messages: DoResume :: RemoteThreadId -> ResumeStep -> ResumeTheWorld -> Command
+ GHC.Debugger.Interface.Messages: ResumeJustThisThread :: ResumeTheWorld
+ GHC.Debugger.Interface.Messages: ResumeNoStep :: ResumeStep
+ GHC.Debugger.Interface.Messages: ResumeSingleStep :: ResumeStep
+ GHC.Debugger.Interface.Messages: ResumeStepLocal :: ResumeStep
+ GHC.Debugger.Interface.Messages: ResumeStepOut :: ResumeStep
+ GHC.Debugger.Interface.Messages: ResumeTheWorld :: ResumeTheWorld
+ GHC.Debugger.Interface.Messages: TerminateDebuggee :: Command
+ GHC.Debugger.Interface.Messages: data ResumeStep
+ GHC.Debugger.Interface.Messages: data ResumeTheWorld
+ GHC.Debugger.Monad: KillMode :: CleanupMode
+ GHC.Debugger.Monad: TerminateMode :: CleanupMode
+ GHC.Debugger.Monad: data CleanupMode
+ GHC.Debugger.Monad: interruptible :: Debugger a -> Debugger a
+ GHC.Debugger.Monad: killProcess' :: ProcessHandle -> IO ()
+ GHC.Debugger.Monad: runGhc :: Maybe FilePath -> Ghc a -> IO a
+ GHC.Debugger.Monad: terminateDebuggee :: Debugger Bool
+ GHC.Debugger.Monad.Load: FailedToLoadFFIInspectModule :: FailedToLoadFFIInspectModule
+ GHC.Debugger.Monad.Load: data FailedToLoadFFIInspectModule
+ GHC.Debugger.Monad.Load: doDownsweep :: GhcMonad m => Maybe ModuleGraph -> m ModuleGraph
+ GHC.Debugger.Monad.Load: doLoad :: GhcMonad m => Maybe ModIfaceCache -> LoadHowMuch -> ModuleGraph -> m SuccessFlag
+ GHC.Debugger.Monad.Load: findHsDebuggerViewUnitId :: Ghc (Maybe UnitId)
+ GHC.Debugger.Monad.Load: findOrLoadHaskellDebuggerView :: LogAction IO DebuggerLog -> Ways -> Ghc (UnitId, [ModuleName])
+ GHC.Debugger.Monad.Load: getAllLoadedModules :: GhcMonad m => m [ModuleNodeInfo]
+ GHC.Debugger.Monad.Load: getAllLoadedModulesWithPaths :: GhcMonad m => m [(AbsFilePath, ModuleNodeInfo)]
+ GHC.Debugger.Monad.Load: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.Load.FailedToLoadFFIInspectModule
+ GHC.Debugger.Monad.Load: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Load.FailedToLoadFFIInspectModule
+ GHC.Debugger.Monad.Load: loadFFIInspect :: LogAction IO DebuggerLog -> Ways -> Ghc ()
+ GHC.Debugger.Monad.Load: loadInMemoryModules :: LogAction IO DebuggerLog -> UnitId -> [(ModuleName, StringBuffer)] -> Ghc [SuccessFlag]
+ GHC.Debugger.Monad.Load: loadInternal :: LogAction IO DebuggerLog -> Ways -> Ghc ()
+ GHC.Debugger.Monad.Type: BreakpointAfterCount :: Int -> BreakpointStatus
+ GHC.Debugger.Monad.Type: BreakpointAfterCountCond :: Int -> String -> BreakpointStatus
+ GHC.Debugger.Monad.Type: BreakpointDisabled :: BreakpointStatus
+ GHC.Debugger.Monad.Type: BreakpointEnabled :: BreakpointStatus
+ GHC.Debugger.Monad.Type: BreakpointInfo :: BreakpointStatus -> BreakpointKind -> BreakpointAction -> BreakpointInfo
+ GHC.Debugger.Monad.Type: BreakpointLogAndResume :: String -> BreakpointAction
+ GHC.Debugger.Monad.Type: BreakpointStop :: BreakpointAction
+ GHC.Debugger.Monad.Type: BreakpointWhenCond :: String -> BreakpointStatus
+ GHC.Debugger.Monad.Type: Debugger :: ReaderT DebuggerState Ghc a -> Debugger a
+ GHC.Debugger.Monad.Type: DebuggerFailedToLoad :: DebuggerFailedToLoad
+ GHC.Debugger.Monad.Type: DebuggerState :: IORef (BreakpointMap BreakpointInfo) -> IORef RuntimeInstancesCache -> IORef (ThreadMap (ForeignRef ThreadId)) -> IORef (ThreadMap StoppedThread) -> IORef (InteractiveContext, Int) -> IORef CompCache -> Maybe UnitId -> LogAction IO DebuggerLog -> DebuggerState
+ GHC.Debugger.Monad.Type: NonFatalException :: String -> String -> NonFatalException
+ GHC.Debugger.Monad.Type: ProjectDebugSpec :: FilePath -> FilePath -> FilePath -> [String] -> [String] -> FilePath -> [String] -> ProjectDebugSpec
+ GHC.Debugger.Monad.Type: RunDebuggerSettings :: Bool -> Bool -> InterpreterSettings -> RunDebuggerSettings
+ GHC.Debugger.Monad.Type: StoppedThread :: Resume -> InteractiveContext -> IntMap (InteractiveContext, (ImportsEpoch, Maybe Module)) -> StoppedThread
+ GHC.Debugger.Monad.Type: UnsupportedHsDbgViewVersion :: [(Version, Version)] -> Version -> UnsupportedHsDbgViewVersion
+ GHC.Debugger.Monad.Type: [absEntryFile] :: ProjectDebugSpec -> FilePath
+ GHC.Debugger.Monad.Type: [activeBreakpoints] :: DebuggerState -> IORef (BreakpointMap BreakpointInfo)
+ GHC.Debugger.Monad.Type: [actualVersion] :: UnsupportedHsDbgViewVersion -> Version
+ GHC.Debugger.Monad.Type: [bpInfoAction] :: BreakpointInfo -> BreakpointAction
+ GHC.Debugger.Monad.Type: [bpInfoKind] :: BreakpointInfo -> BreakpointKind
+ GHC.Debugger.Monad.Type: [bpInfoStatus] :: BreakpointInfo -> BreakpointStatus
+ GHC.Debugger.Monad.Type: [breakIC] :: StoppedThread -> InteractiveContext
+ GHC.Debugger.Monad.Type: [compCache] :: DebuggerState -> IORef CompCache
+ GHC.Debugger.Monad.Type: [componentDir] :: ProjectDebugSpec -> FilePath
+ GHC.Debugger.Monad.Type: [dbgLogger] :: DebuggerState -> LogAction IO DebuggerLog
+ GHC.Debugger.Monad.Type: [debugMessage] :: NonFatalException -> String
+ GHC.Debugger.Monad.Type: [extraGhcArgs] :: ProjectDebugSpec -> [String]
+ GHC.Debugger.Monad.Type: [frameICs] :: StoppedThread -> IntMap (InteractiveContext, (ImportsEpoch, Maybe Module))
+ GHC.Debugger.Monad.Type: [ghcInvocation] :: ProjectDebugSpec -> [String]
+ GHC.Debugger.Monad.Type: [globalIC] :: DebuggerState -> IORef (InteractiveContext, Int)
+ GHC.Debugger.Monad.Type: [hsDbgViewUnitId] :: DebuggerState -> Maybe UnitId
+ GHC.Debugger.Monad.Type: [interpreterSettings] :: RunDebuggerSettings -> InterpreterSettings
+ GHC.Debugger.Monad.Type: [libdir] :: ProjectDebugSpec -> FilePath
+ GHC.Debugger.Monad.Type: [resume] :: StoppedThread -> Resume
+ GHC.Debugger.Monad.Type: [rootDir] :: ProjectDebugSpec -> FilePath
+ GHC.Debugger.Monad.Type: [rtinstancesCache] :: DebuggerState -> IORef RuntimeInstancesCache
+ GHC.Debugger.Monad.Type: [supportedVersions] :: UnsupportedHsDbgViewVersion -> [(Version, Version)]
+ GHC.Debugger.Monad.Type: [supportsANSIHyperlinks] :: RunDebuggerSettings -> Bool
+ GHC.Debugger.Monad.Type: [supportsANSIStyling] :: RunDebuggerSettings -> Bool
+ GHC.Debugger.Monad.Type: [threadMap] :: DebuggerState -> IORef (ThreadMap (ForeignRef ThreadId))
+ GHC.Debugger.Monad.Type: [threadResumeMap] :: DebuggerState -> IORef (ThreadMap StoppedThread)
+ GHC.Debugger.Monad.Type: [unDebugger] :: Debugger a -> ReaderT DebuggerState Ghc a
+ GHC.Debugger.Monad.Type: [units] :: ProjectDebugSpec -> [String]
+ GHC.Debugger.Monad.Type: [userMessage] :: NonFatalException -> String
+ GHC.Debugger.Monad.Type: data BreakpointAction
+ GHC.Debugger.Monad.Type: data BreakpointInfo
+ GHC.Debugger.Monad.Type: data BreakpointStatus
+ GHC.Debugger.Monad.Type: data DebuggerFailedToLoad
+ GHC.Debugger.Monad.Type: data DebuggerState
+ GHC.Debugger.Monad.Type: data NonFatalException
+ GHC.Debugger.Monad.Type: data ProjectDebugSpec
+ GHC.Debugger.Monad.Type: data RunDebuggerSettings
+ GHC.Debugger.Monad.Type: data StoppedThread
+ GHC.Debugger.Monad.Type: data UnsupportedHsDbgViewVersion
+ GHC.Debugger.Monad.Type: expectRight :: Exception e => Either e a -> Debugger a
+ GHC.Debugger.Monad.Type: getHsDebuggerViewUid :: Debugger (Maybe UnitId)
+ GHC.Debugger.Monad.Type: initialDebuggerState :: LogAction IO DebuggerLog -> Maybe UnitId -> Ghc DebuggerState
+ GHC.Debugger.Monad.Type: instance Control.Monad.Catch.MonadCatch GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance Control.Monad.Catch.MonadMask GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance Control.Monad.Catch.MonadThrow GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance Control.Monad.Reader.Class.MonadReader GHC.Debugger.Monad.Type.DebuggerState GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Driver.DynFlags.HasDynFlags GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Driver.Monad.GhcMonad GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Base.Applicative GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Base.Functor GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Base.Monad GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Classes.Eq GHC.Debugger.Monad.Type.BreakpointAction
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Classes.Eq GHC.Debugger.Monad.Type.BreakpointInfo
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Classes.Eq GHC.Debugger.Monad.Type.BreakpointStatus
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Classes.Ord GHC.Debugger.Monad.Type.BreakpointAction
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Classes.Ord GHC.Debugger.Monad.Type.BreakpointStatus
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Control.Monad.IO.Class.MonadIO GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.Type.DebuggerFailedToLoad
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.Type.NonFatalException
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Exception.Type.Exception GHC.Debugger.Monad.Type.UnsupportedHsDbgViewVersion
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Type.BreakpointAction
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Type.BreakpointInfo
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Type.BreakpointStatus
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Type.DebuggerFailedToLoad
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Type.NonFatalException
+ GHC.Debugger.Monad.Type: instance GHC.Internal.Show.Show GHC.Debugger.Monad.Type.UnsupportedHsDbgViewVersion
+ GHC.Debugger.Monad.Type: instance GHC.Utils.Logger.HasLogger GHC.Debugger.Monad.Type.Debugger
+ GHC.Debugger.Monad.Type: instance GHC.Utils.Outputable.Outputable GHC.Debugger.Monad.Type.BreakpointAction
+ GHC.Debugger.Monad.Type: instance GHC.Utils.Outputable.Outputable GHC.Debugger.Monad.Type.BreakpointStatus
+ GHC.Debugger.Monad.Type: liftGhc :: Ghc a -> Debugger a
+ GHC.Debugger.Monad.Type: logSDoc :: Severity -> SDoc -> Debugger ()
+ GHC.Debugger.Monad.Type: mkStoppedThread :: Resume -> InteractiveContext -> StoppedThread
+ GHC.Debugger.Monad.Type: newtype Debugger a
+ GHC.Debugger.Monad.Type: type DebugRunner (m :: Type -> Type) a = DebugSession m a -> IO a
+ GHC.Debugger.Monad.Type: type DebugSession (m :: Type -> Type) a = FilePath -> [String] -> m () -> Ghc a
+ GHC.Debugger.Monad.Type: type ImportsEpoch = Int
+ GHC.Debugger.Run: doResume :: RemoteThreadId -> ResumeStep -> ResumeTheWorld -> Debugger EvalResult
+ GHC.Debugger.Run.Eval: addImport :: String -> Debugger EvalResult
+ GHC.Debugger.Run.Eval: doEval :: (ExecResult -> Debugger EvalResult) -> Maybe (RemoteThreadId, Int) -> String -> Debugger EvalResult
+ GHC.Debugger.Run.Eval: instance Control.Monad.Trans.Class.MonadTrans (GHC.Debugger.Run.Eval.ScopeT s)
+ GHC.Debugger.Run.Eval: instance GHC.Internal.Base.Applicative m => GHC.Internal.Base.Applicative (GHC.Debugger.Run.Eval.ScopeT s m)
+ GHC.Debugger.Run.Eval: instance GHC.Internal.Base.Functor m => GHC.Internal.Base.Functor (GHC.Debugger.Run.Eval.ScopeT s m)
+ GHC.Debugger.Run.Eval: instance GHC.Internal.Base.Monad m => Control.Monad.Reader.Class.MonadReader (GHC.Debugger.Run.Eval.Scope s) (GHC.Debugger.Run.Eval.ScopeT s m)
+ GHC.Debugger.Run.Eval: instance GHC.Internal.Base.Monad m => GHC.Internal.Base.Monad (GHC.Debugger.Run.Eval.ScopeT s m)
+ GHC.Debugger.Run.Eval: instance GHC.Internal.Control.Monad.IO.Class.MonadIO m => GHC.Internal.Control.Monad.IO.Class.MonadIO (GHC.Debugger.Run.Eval.ScopeT s m)
+ GHC.Debugger.Run.Handler: handleExecResult :: ExecResult -> Debugger EvalResult
+ GHC.Debugger.Run.Resume: resolveResumeStep :: Resume -> ResumeStep -> Debugger SingleStep
+ GHC.Debugger.Run.Resume: resumeExec :: SingleStep -> Maybe Int -> Resume -> Debugger ExecResult
+ GHC.Debugger.Runtime.Term: deepseqTerm :: HscEnv -> Term -> IO Term
+ GHC.Debugger.Runtime.Term: obtainTerm :: TermKey -> Debugger Term
+ GHC.Debugger.Runtime.Term: seqTerm :: HscEnv -> Term -> IO Term
+ GHC.Debugger.Runtime.Thread.Resume: execBreakResume :: ExecResult -> Debugger Resume
+ GHC.Debugger.Runtime.Thread.Resume: getResumeThreadId :: Resume -> Debugger RemoteThreadId
+ GHC.Debugger.Runtime.Thread.Resume: popResume :: RemoteThreadId -> Debugger Resume
+ GHC.Debugger.Runtime.Thread.Resume: pushResume :: Resume -> Debugger ()
+ GHC.Debugger.Runtime.Thread.Resume: readResume :: RemoteThreadId -> Debugger (Maybe Resume)
+ GHC.Debugger.Runtime.Thread.Resume: readStoppedThread :: RemoteThreadId -> Debugger (Maybe StoppedThread)
+ GHC.Debugger.Session.Builtin: lookupNoPrintConstant :: Ghc Name
+ GHC.Debugger.Stopped: getExceptionInfo :: RemoteThreadId -> Debugger ExceptionInfo
+ GHC.Debugger.Stopped: getStackFrame :: RemoteThreadId -> Int -> Debugger (Maybe DbgStackFrame)
+ GHC.Debugger.Stopped.Variables: idToVarInfo :: Name -> Debugger (Maybe VarInfo)
+ GHC.Debugger.Utils: silenceEOF :: HasCallStack => LogAction IO Text -> Handle -> IO () -> IO ()
- GHC.Debugger.Debuggee: mkExternalInterpreterFlags :: String -> DynFlags -> DynFlags
+ GHC.Debugger.Debuggee: mkExternalInterpreterFlags :: String -> [String] -> DynFlags -> DynFlags
- GHC.Debugger.Interface.Messages: DoEval :: String -> Command
+ GHC.Debugger.Interface.Messages: DoEval :: Maybe (RemoteThreadId, Int) -> String -> Command
- GHC.Debugger.Monad: cleanupInterp :: Ghc ()
+ GHC.Debugger.Monad: cleanupInterp :: LogAction IO DebuggerLog -> CleanupMode -> Ghc Bool
- GHC.Debugger.Run: doEvalCommand :: String -> Debugger EvalResult
+ GHC.Debugger.Run: doEvalCommand :: Maybe (RemoteThreadId, Int) -> String -> Debugger EvalResult
- GHC.Debugger.Utils: forwardHandleToLogger :: Handle -> LogAction IO Text -> IO ()
+ GHC.Debugger.Utils: forwardHandleToLogger :: HasCallStack => LogAction IO Text -> Handle -> LogAction IO Text -> IO ()
Files
- CHANGELOG.md +10/−0
- README.md +18/−2
- haskell-debugger.cabal +50/−17
- haskell-debugger/GHC/Debugger.hs +79/−22
- haskell-debugger/GHC/Debugger/Breakpoint.hs +14/−2
- haskell-debugger/GHC/Debugger/Breakpoint/Map.hs +0/−88
- haskell-debugger/GHC/Debugger/Data/BreakpointMap.hs +88/−0
- haskell-debugger/GHC/Debugger/Data/Supervisor.hs +231/−0
- haskell-debugger/GHC/Debugger/Data/ThreadMap.hs +44/−0
- haskell-debugger/GHC/Debugger/Debuggee.hs +21/−16
- haskell-debugger/GHC/Debugger/Interface/Messages.hs +55/−15
- haskell-debugger/GHC/Debugger/Monad.hs +162/−535
- haskell-debugger/GHC/Debugger/Monad/Load.hs +322/−0
- haskell-debugger/GHC/Debugger/Monad/Type.hs +274/−0
- haskell-debugger/GHC/Debugger/Run.hs +43/−246
- haskell-debugger/GHC/Debugger/Run/Eval.hs +292/−0
- haskell-debugger/GHC/Debugger/Run/Handler.hs +114/−0
- haskell-debugger/GHC/Debugger/Run/Resume.hs +63/−0
- haskell-debugger/GHC/Debugger/Runtime.hs +0/−55
- haskell-debugger/GHC/Debugger/Runtime/Eval.hs +3/−0
- haskell-debugger/GHC/Debugger/Runtime/Instances/Discover.hs +1/−0
- haskell-debugger/GHC/Debugger/Runtime/Internal.hs +9/−1
- haskell-debugger/GHC/Debugger/Runtime/Interpreter/Custom.hs +3/−0
- haskell-debugger/GHC/Debugger/Runtime/Term.hs +109/−0
- haskell-debugger/GHC/Debugger/Runtime/Term/Parser.hs +1/−0
- haskell-debugger/GHC/Debugger/Runtime/Thread.hs +16/−4
- haskell-debugger/GHC/Debugger/Runtime/Thread/Map.hs +0/−42
- haskell-debugger/GHC/Debugger/Runtime/Thread/Resume.hs +84/−0
- haskell-debugger/GHC/Debugger/Session.hs +9/−39
- haskell-debugger/GHC/Debugger/Session/Builtin.hs +30/−12
- haskell-debugger/GHC/Debugger/Session/Interactive.hs +0/−32
- haskell-debugger/GHC/Debugger/Stopped.hs +61/−43
- haskell-debugger/GHC/Debugger/Stopped/Exception.hs +2/−0
- haskell-debugger/GHC/Debugger/Stopped/Frames.hs +4/−0
- haskell-debugger/GHC/Debugger/Stopped/Variables.hs +61/−17
- haskell-debugger/GHC/Debugger/Utils.hs +13/−7
- hdb-dap/Development/Debug/Adapter.hs +14/−6
- hdb-dap/Development/Debug/Adapter/DAPDebuggee.hs +66/−67
- hdb-dap/Development/Debug/Adapter/Evaluation.hs +11/−4
- hdb-dap/Development/Debug/Adapter/Exit.hs +11/−2
- hdb-dap/Development/Debug/Adapter/Handles.hs +10/−20
- hdb-dap/Development/Debug/Adapter/Init.hs +36/−21
- hdb-dap/Development/Debug/Adapter/Proxy.hs +47/−45
- hdb-dap/Development/Debug/Adapter/Server.hs +33/−4
- hdb-dap/Development/Debug/Adapter/Stepping.hs +34/−6
- hdb-dap/Development/Debug/Session/Setup.hs +1/−1
- hdb/Development/Debug/Interactive.hs +30/−17
- hdb/Development/Debug/Options/Parser.hs +16/−3
- hdb/Main.hs +104/−23
- test/golden/T79/T79.ghc-1001.hdb-stdout +0/−1
- test/golden/T79/T79.ghc-914.hdb-stdout +0/−1
- test/golden/T79/T79.hdb-test +1/−1
- test/haskell/Main.hs +38/−3
- test/haskell/Test/DAP.hs +107/−35
- test/haskell/Test/DAP/Init.hs +87/−27
- test/haskell/Test/DAP/Messages.hs +54/−11
- test/haskell/Test/DAP/Messages/Parser.hs +7/−0
- test/haskell/Test/DAP/Orphans.hs +6/−0
- test/haskell/Test/Integration/Basic.hs +80/−2
- test/haskell/Test/Integration/Conditional.hs +2/−2
- test/haskell/Test/Integration/Evaluate.hs +108/−8
- test/haskell/Test/Integration/LogMessage.hs +9/−6
- test/haskell/Test/Integration/RunInTerminal.hs +3/−3
- test/haskell/Test/Integration/Scopes.hs +2/−3
- test/haskell/Test/Integration/StackTrace.hs +3/−5
- test/haskell/Test/Integration/StepOut.hs +7/−7
- test/haskell/Test/Integration/Threads.hs +46/−0
- test/haskell/Test/Utils.hs +6/−1
- test/integration/T325a/T325a.cabal +18/−0
- test/integration/T325a/T325a.hs +12/−0
- test/integration/T325a/cabal.project +1/−0
- test/integration/T325a/hie.yaml +1/−0
- test/integration/T370/T370.cabal +32/−0
- test/integration/T370/T370.hs +31/−0
- test/integration/T370/T370b.hs +8/−0
- test/integration/T370/hie.yaml +2/−0
- test/integration/threads/Main.hs +26/−0
CHANGELOG.md view
@@ -1,5 +1,15 @@ # Revision history for haskell-debugger +## 0.15.0.0 -- 2026-11-23++* Added AI Policy to README+* Added support for evaluation in thread and stack frame context.+* Fixed handling of TERM signals.+* Minimized error messages when a debug session is canceled.+* Surfaced exceptions as DAP errors.+* All debuggee threads are now listed to DAP clients.+* Added `externalInterpreterArgs` to lauch parameters.+ ## 0.14.0.0 -- 2026-09-17 * Added binary distributions intended for on Linux and macOS.
README.md view
@@ -33,12 +33,12 @@ ## Prebuilt release binaries -The `hdb-<version>-<arch>.tar.gz` bindists attached to [GitHub+The `hdb-<version>-ghcup-<arch>.tar.gz` bindists attached to [GitHub Releases](https://github.com/well-typed/haskell-debugger/releases) unpack into a self-contained folder: ```-hdb-<version>-<arch>/+hdb-<version>-ghcup-<arch>/ hdb # wrapper script -- put THIS on PATH, not bin/hdb bin/hdb # the real executable lib/* # bundled dynamic dependencies@@ -115,6 +115,22 @@ Cabal, Stack, custom `hie.yaml`) because it uses [`hie-bios`](https://github.com/haskell/hie-bios) to figure out the right flags to prepare the GHC session with.++# AI Policy++The haskell-debugger uses the [GHC Policy on LLM Contributions](https://gitlab.haskell.org/ghc/ghc/-/wikis/contributing/AI).++Namely, here are the specific policies for LLM contributions to GHC tickets,+merge requests, and reviews. Each is fleshed out in a section in the original+document. There are four policy points (P1-P4) and one preference (P5):+- P1: prioritise people and community+- P2: write MRs that are easy to review+- P3: human authorship and full responsibility+- P4: declare direct use of LLMs+- P5: strong preference: write the final version yourself++The original document also outlines the vision and principles behind the+policy. Do take a look! # Features
haskell-debugger.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.12 name: haskell-debugger-version: 0.14.0.0+version: 0.15.0.0 synopsis: A step-through debugger for GHC Haskell @@ -67,6 +67,10 @@ common warnings ghc-options: -Wall +common multithreaded_cpp+ if flag(multithreaded)+ cpp-options: -DGHC_HAS_MULTITHREADED_DBG+ -- custom-setup -- setup-depends: -- base >= 4.21 && < 5,@@ -82,53 +86,77 @@ default: False manual: True +Flag multithreaded+ description: Compile against ghc with multithreaded debugging support+ default: False+ manual: True+ library- import: warnings- exposed-modules: GHC.Debugger,- GHC.Debugger.Breakpoint,- GHC.Debugger.Breakpoint.Map,+ import: warnings, multithreaded_cpp+ exposed-modules:+ -- Entry point to `execute` debugger commands+ GHC.Debugger,+ GHC.Debugger.Interface.Messages,++ -- Top-level debugger commands GHC.Debugger.Run,+ GHC.Debugger.Run.Eval,+ GHC.Debugger.Run.Handler,+ GHC.Debugger.Run.Resume, GHC.Debugger.Stopped, GHC.Debugger.Stopped.Exception, GHC.Debugger.Stopped.Frames, GHC.Debugger.Stopped.Variables,-- GHC.Debugger.Runtime,+ GHC.Debugger.Breakpoint, + -- Evaluate exprs on the debuggee process GHC.Debugger.Runtime.Eval, GHC.Debugger.Runtime.Eval.RemoteExpr, GHC.Debugger.Runtime.Eval.RemoteExpr.Builtin, + -- Finding debuggee instances at runtime GHC.Debugger.Runtime.Instances, GHC.Debugger.Runtime.Instances.Discover, + -- Compile expressions at runtime GHC.Debugger.Runtime.Compile, GHC.Debugger.Runtime.Compile.Cache, + -- Run in the interpreter process (either to impl custom+ -- commands or via RemoteExpr)+ GHC.Debugger.Runtime.Internal, GHC.Debugger.Runtime.FFIInspect, - GHC.Debugger.Runtime.Term.Parser,+ -- Inspecting runtime terms+ GHC.Debugger.Runtime.Term, GHC.Debugger.Runtime.Term.Key,+ GHC.Debugger.Runtime.Term.Parser, + -- Per-thread information and resumes GHC.Debugger.Runtime.Thread, GHC.Debugger.Runtime.Thread.Stack,- GHC.Debugger.Runtime.Thread.Map,+ GHC.Debugger.Runtime.Thread.Resume, GHC.Debugger.Runtime.Interpreter.Types, GHC.Debugger.Monad,+ GHC.Debugger.Monad.Load,+ GHC.Debugger.Monad.Type, GHC.Debugger.Debuggee, GHC.Debugger.Utils, GHC.Debugger.Utils.Orphans, GHC.Debugger.Session, GHC.Debugger.Session.Builtin,- GHC.Debugger.Session.Interactive,- GHC.Debugger.Interface.Messages,- GHC.Debugger.Runtime.Internal+ + -- Data structures+ GHC.Debugger.Data.BreakpointMap,+ GHC.Debugger.Data.ThreadMap,+ GHC.Debugger.Data.Supervisor, if impl(ghc >= 9.14.2) exposed-modules:+ -- Custom external interpreter GHC.Debugger.Runtime.Interpreter, GHC.Debugger.Runtime.Interpreter.Custom @@ -168,12 +196,15 @@ haskell-debugger-view >= 0.2 && < 1, ghc-stack-annotations >=0.1 && <0.2, rts >= 1 && < 2,+ stm >= 2 && < 3, if !os(windows) build-depends: unix >= 2.8.6 && < 2.9,+ if impl(ghc>=10.1) -- from 10.1, we have much fewer stg_ctoi_t<N>_info hardcoded frames cc-options: -DFEW_TUPLE_FRAMES+ if flag(testing) cpp-options: -DTESTING @@ -221,13 +252,14 @@ implicit-hie ^>=0.1.4.0, transformers >= 0.6 && < 0.7, time,+ temporary >=1.3 && < 1.4, directory >= 1.3.9 && < 1.4, network >= 3.2.8 && < 3.3, network-run >= 0.4.4 && < 0.5, async >= 2.2.5 && < 2.3, text >= 2.1 && < 2.3,- dap >= 0.7 && < 0.8,+ dap >= 0.8 && < 0.9, haskeline >= 0.8 && < 1, optparse-applicative >= 0.18 && < 0.20,@@ -260,13 +292,13 @@ implicit-hie ^>=0.1.4.0, transformers >= 0.6 && < 0.7, time,-+ unix, directory >= 1.3.9 && < 1.4, network >= 3.2.8 && < 3.3, network-run >= 0.4.4 && < 0.5, async >= 2.2.5 && < 2.3, text >= 2.1 && < 2.3,- dap >= 0.7 && < 0.8,+ dap >= 0.8 && < 0.9, haskeline >= 0.8 && < 1, optparse-applicative >= 0.18 && < 0.20,@@ -281,7 +313,7 @@ ghc-options: -fkeep-cafs test-suite haskell-debugger-test- import: warnings+ import: warnings, multithreaded_cpp default-language: GHC2021 -- other-extensions: type: exitcode-stdio-1.0@@ -308,7 +340,8 @@ Test.Integration.Conditional, Test.Integration.Evaluate, Test.Integration.StackTrace,- Test.Integration.SelfDebug+ Test.Integration.SelfDebug,+ Test.Integration.Threads build-depends: base >=4.14, async,
haskell-debugger/GHC/Debugger.hs view
@@ -1,12 +1,22 @@ {-# LANGUAGE CPP, NamedFieldPuns, TupleSections, LambdaCase, DuplicateRecordFields, RecordWildCards, TupleSections, ViewPatterns, TypeApplications, ScopedTypeVariables, BangPatterns #-}-module GHC.Debugger where -import GHC.Debugger.Breakpoint-import GHC.Debugger.Run-import GHC.Debugger.Stopped-import GHC.Debugger.Stopped.Exception (getExceptionInfo)++-- | Entry point to execute debugging commands+module GHC.Debugger+ (+ -- * Execute debugger commands+ execute++ -- * Re-export command types+ , module GHC.Debugger.Interface.Messages++ ) where++import qualified GHC.Debugger.Breakpoint as Break+import qualified GHC.Debugger.Run as Run+import qualified GHC.Debugger.Stopped as Stopped import GHC.Debugger.Monad import GHC.Debugger.Interface.Messages @@ -17,20 +27,67 @@ -- | Execute the given debugger command in the current 'Debugger' session execute :: Command -> Debugger Response execute = \case- ClearFunctionBreakpoints -> DidClearBreakpoints <$ clearBreakpoints Nothing- ClearModBreakpoints fp -> DidClearBreakpoints <$ clearBreakpoints (Just fp)- SetBreakpoint{brk, hitCount, condition, logMessage} ->- DidSetBreakpoint <$> setBreakpoint brk (condBreakEnableStatus hitCount condition) (maybe BreakpointStop (BreakpointLogAndResume . logMessageExpression) logMessage)- DelBreakpoint bp -> DidRemoveBreakpoint <$> setBreakpoint bp BreakpointDisabled BreakpointStop- GetBreakpointsAt bp -> DidGetBreakpoints <$> getBreakpointsAt bp- GetThreads -> GotThreads <$> getThreads- GetStacktrace i -> GotStacktrace <$> getStacktrace i- GetScopes threadId frameIx -> GotScopes <$> getScopes threadId frameIx- GetVariables threadId frameIx varRef -> GotVariables <$> getVariables threadId frameIx varRef- GetExceptionInfo threadId -> GotExceptionInfo <$> getExceptionInfo threadId- DoEval exp_s -> DidEval <$> doEvalCommand exp_s- DoContinue -> DidContinue <$> doContinue- DoSingleStep -> DidStep <$> doSingleStep- DoStepOut -> DidStep <$> doStepOut- DoStepLocal -> DidStep <$> doLocalStep- DebugExecution { entryPoint, entryFile, runArgs } -> DidExec <$> debugExecution entryFile entryPoint runArgs++ ------------------------------------------------------------------------------+ -- GHC.Debugger.Breakpoint+ ------------------------------------------------------------------------------++ ClearFunctionBreakpoints -> DidClearBreakpoints <$+ Break.clearBreakpoints Nothing+ ClearModBreakpoints fp -> DidClearBreakpoints <$+ Break.clearBreakpoints (Just fp)+ SetBreakpoint{brk, hitCount, condition, logMessage} -> DidSetBreakpoint <$>+ Break.setBreakpoint brk+ (Break.condBreakEnableStatus hitCount condition)+ (maybe BreakpointStop (BreakpointLogAndResume . Break.logMessageExpression) logMessage)+ DelBreakpoint bp -> DidRemoveBreakpoint <$>+ Break.setBreakpoint bp BreakpointDisabled BreakpointStop+ GetBreakpointsAt bp -> DidGetBreakpoints <$>+ Break.getBreakpointsAt bp++ ------------------------------------------------------------------------------+ -- GHC.Debugger.Stopped+ ------------------------------------------------------------------------------++ GetThreads -> GotThreads <$>+ Stopped.getThreads -- should this really be in Stopped?+ GetStacktrace i -> GotStacktrace <$>+ Stopped.getStacktrace i+ GetScopes threadId frameIx -> GotScopes <$>+ Stopped.getScopes threadId frameIx+ GetVariables threadId frameIx varRef -> GotVariables <$>+ Stopped.getVariables threadId frameIx varRef+ GetExceptionInfo threadId -> GotExceptionInfo <$>+ Stopped.getExceptionInfo threadId++ ------------------------------------------------------------------------------+ -- GHC.Debugger.Run+ ------------------------------------------------------------------------------++ DoEval mfid exp_s -> DidEval <$>+ Run.doEvalCommand mfid exp_s++ -- TODO: We shouldn't block waiting for the result of these operations, because that means we can never resume/step two threads simultaneously.+ -- Recall we take things to evaluate from the message queue, but we execute them serially. Here we should do something like `forkIO $ reply`+ -- We need an async model that sets them off running and replies once the answer comes back+ -- We should just do this in the dap side thread which is running serially+ --+ -- Even more generally, I think when we read an handleExecResult we should+ -- probably clear the MVar as soon as possible so we can receive as many paused+ -- thread hits as possible and emit thread paused events.+ DoResume tid step world -> DidResume <$>+ Run.doResume tid step world++ DebugExecution { entryPoint, entryFile, runArgs } -> DidExec <$>+ Run.debugExecution entryFile entryPoint runArgs++ -----------------------------------------------------------------------------+ -- GHC.Debugger.Monad+ -----------------------------------------------------------------------------++ -- TODO: will only work on a running debuggee once the GHC.Debugger.Run+ -- operations are made non-blocking. Until then, the only way to terminate a+ -- running debugee is to kill the main debugger thread.+ --+ -- This Command can already be used to fully terminate a stopped debuggee though.+ TerminateDebuggee -> DidTerminate <$> terminateDebuggee
haskell-debugger/GHC/Debugger/Breakpoint.hs view
@@ -1,8 +1,20 @@ {-# LANGUAGE CPP, NamedFieldPuns, TupleSections, LambdaCase, DuplicateRecordFields, RecordWildCards, TupleSections, ViewPatterns, TypeApplications, ScopedTypeVariables, BangPatterns #-}-module GHC.Debugger.Breakpoint where +-- | Set/unset breakpoints in the debuggee program+module GHC.Debugger.Breakpoint+ (+ -- * Set/unset and get breakpoints+ clearBreakpoints+ , setBreakpoint+ , getBreakpointsAt++ -- ** Conditional breakpoints and logpoints+ , condBreakEnableStatus+ , logMessageExpression+ ) where+ import Prelude hiding ((<>)) import Control.Exception import Control.Monad@@ -29,7 +41,7 @@ import GHC.Debugger.Session import GHC.Debugger.Utils import GHC.Debugger.Interface.Messages-import qualified GHC.Debugger.Breakpoint.Map as BM+import qualified GHC.Debugger.Data.BreakpointMap as BM import Data.Function import System.Directory (getCurrentDirectory) import GHC.Debugger.Session.Builtin (debuggerRuntimeInternalModName)
− haskell-debugger/GHC/Debugger/Breakpoint/Map.hs
@@ -1,88 +0,0 @@-{-# LANGUAGE NamedFieldPuns, DeriveFunctor, DerivingStrategies, GeneralizedNewtypeDeriving #-}--- | Meant to be qualified with @import qualified GHC.Debugger.Breakpoint.Map as BM@-module GHC.Debugger.Breakpoint.Map- ( BreakpointMap- , insert- , lookup- , delete- , empty- , lookupModuleIBIs- , keys- , toList- ) where--import Prelude hiding (lookup)-import qualified GHC-import GHC.Unit.Module.Env-import GHC.ByteCode.Breakpoints-import GHC.Utils.Outputable (Outputable)-import qualified Data.IntMap as IM-import GHC.Debugger.View.Class-import GHC.Debugger.Utils (showModule)---- | A map keyed by 'InternalBreakpointId'-newtype BreakpointMap a = BreakpointMap (ModuleEnv (IM.IntMap a))- deriving newtype Outputable--insert :: GHC.InternalBreakpointId -> a -> BreakpointMap a -> BreakpointMap a-insert InternalBreakpointId{ibi_info_mod, ibi_info_index}- x (BreakpointMap bm0) = BreakpointMap $- case lookupModuleEnv bm0 ibi_info_mod of- Nothing ->- extendModuleEnv bm0 ibi_info_mod $- IM.singleton ibi_info_index x- Just im ->- extendModuleEnv bm0 ibi_info_mod $- IM.insert ibi_info_index x im--lookup :: GHC.InternalBreakpointId -> BreakpointMap a -> Maybe a-lookup InternalBreakpointId{ibi_info_mod, ibi_info_index}- (BreakpointMap bm0) = do- lookupModuleEnv bm0 ibi_info_mod- >>= IM.lookup ibi_info_index--delete :: GHC.InternalBreakpointId -> BreakpointMap a -> BreakpointMap a-delete InternalBreakpointId{ibi_info_mod, ibi_info_index}- (BreakpointMap bm0) =- case lookupModuleEnv bm0 ibi_info_mod of- Nothing -> BreakpointMap bm0- Just im -> BreakpointMap $- extendModuleEnv bm0 ibi_info_mod $- IM.delete ibi_info_index im--empty :: BreakpointMap a-empty = BreakpointMap emptyModuleEnv---- | Retrieves all 'InternalBreakpointId's for a given 'Module'--- Note: The internal breakpoints of a module are not necessarily the same as--- the source-level breakpoints, so this shouldn't be used to get all internal--- breakpoints with source-level occurrences in the given module.-lookupModuleIBIs :: GHC.Module -> BreakpointMap a -> [InternalBreakpointId]-lookupModuleIBIs m (BreakpointMap bm) =- case lookupModuleEnv bm m of- Nothing -> []- Just im ->- [ InternalBreakpointId m bix- | bix <- IM.keys im- ]--keys :: BreakpointMap a -> [InternalBreakpointId]-keys (BreakpointMap bm) =- [ InternalBreakpointId m bix- | (m, im) <- moduleEnvToList bm- , bix <- IM.keys im- ]--toList :: BreakpointMap a -> [(InternalBreakpointId, a)]-toList (BreakpointMap bm) =- [ (InternalBreakpointId m bix, a)- | (m, im) <- moduleEnvToList bm- , (bix, a) <- IM.toList im- ]--instance DebugView (BreakpointMap a) where- debugValue (BreakpointMap b) = simpleValue "BreakpointMap" (not $ isEmptyModuleEnv b)- debugFields bm = pure $ VarFields- [ (showModule ibi_info_mod ++ "(" ++ show ibi_info_index ++ ")", VarFieldValue v)- | (InternalBreakpointId{ibi_info_mod, ibi_info_index}, v) <- toList bm- ]
+ haskell-debugger/GHC/Debugger/Data/BreakpointMap.hs view
@@ -0,0 +1,88 @@+{-# LANGUAGE NamedFieldPuns, DeriveFunctor, DerivingStrategies, GeneralizedNewtypeDeriving #-}+-- | Meant to be qualified with @import qualified GHC.Debugger.Breakpoint.Map as BM@+module GHC.Debugger.Data.BreakpointMap+ ( BreakpointMap+ , insert+ , lookup+ , delete+ , empty+ , lookupModuleIBIs+ , keys+ , toList+ ) where++import Prelude hiding (lookup)+import qualified GHC+import GHC.Unit.Module.Env+import GHC.ByteCode.Breakpoints+import GHC.Utils.Outputable (Outputable)+import qualified Data.IntMap as IM+import GHC.Debugger.View.Class+import GHC.Debugger.Utils (showModule)++-- | A map keyed by 'InternalBreakpointId'+newtype BreakpointMap a = BreakpointMap (ModuleEnv (IM.IntMap a))+ deriving newtype Outputable++insert :: GHC.InternalBreakpointId -> a -> BreakpointMap a -> BreakpointMap a+insert InternalBreakpointId{ibi_info_mod, ibi_info_index}+ x (BreakpointMap bm0) = BreakpointMap $+ case lookupModuleEnv bm0 ibi_info_mod of+ Nothing ->+ extendModuleEnv bm0 ibi_info_mod $+ IM.singleton ibi_info_index x+ Just im ->+ extendModuleEnv bm0 ibi_info_mod $+ IM.insert ibi_info_index x im++lookup :: GHC.InternalBreakpointId -> BreakpointMap a -> Maybe a+lookup InternalBreakpointId{ibi_info_mod, ibi_info_index}+ (BreakpointMap bm0) = do+ lookupModuleEnv bm0 ibi_info_mod+ >>= IM.lookup ibi_info_index++delete :: GHC.InternalBreakpointId -> BreakpointMap a -> BreakpointMap a+delete InternalBreakpointId{ibi_info_mod, ibi_info_index}+ (BreakpointMap bm0) =+ case lookupModuleEnv bm0 ibi_info_mod of+ Nothing -> BreakpointMap bm0+ Just im -> BreakpointMap $+ extendModuleEnv bm0 ibi_info_mod $+ IM.delete ibi_info_index im++empty :: BreakpointMap a+empty = BreakpointMap emptyModuleEnv++-- | Retrieves all 'InternalBreakpointId's for a given 'Module'+-- Note: The internal breakpoints of a module are not necessarily the same as+-- the source-level breakpoints, so this shouldn't be used to get all internal+-- breakpoints with source-level occurrences in the given module.+lookupModuleIBIs :: GHC.Module -> BreakpointMap a -> [InternalBreakpointId]+lookupModuleIBIs m (BreakpointMap bm) =+ case lookupModuleEnv bm m of+ Nothing -> []+ Just im ->+ [ InternalBreakpointId m bix+ | bix <- IM.keys im+ ]++keys :: BreakpointMap a -> [InternalBreakpointId]+keys (BreakpointMap bm) =+ [ InternalBreakpointId m bix+ | (m, im) <- moduleEnvToList bm+ , bix <- IM.keys im+ ]++toList :: BreakpointMap a -> [(InternalBreakpointId, a)]+toList (BreakpointMap bm) =+ [ (InternalBreakpointId m bix, a)+ | (m, im) <- moduleEnvToList bm+ , (bix, a) <- IM.toList im+ ]++instance DebugView (BreakpointMap a) where+ debugValue (BreakpointMap b) = simpleValue "BreakpointMap" (not $ isEmptyModuleEnv b)+ debugFields bm = pure $ VarFields+ [ (showModule ibi_info_mod ++ "(" ++ show ibi_info_index ++ ")", VarFieldValue v)+ | (InternalBreakpointId{ibi_info_mod, ibi_info_index}, v) <- toList bm+ ]
+ haskell-debugger/GHC/Debugger/Data/Supervisor.hs view
@@ -0,0 +1,231 @@+{-# LANGUAGE LambdaCase #-}++-- | Scoped thread supervision.+--+-- * The thread that calls 'withSupervisor' is the parent. When the body+-- returns, throws, or the parent is killed, every supervised thread is+-- sent 'SupervisorShutdown', and the parent waits up to the grace+-- period for them to finish.+--+-- * Children spawned with 'Propagate' report their failure to the parent+-- as an asynchronous 'ChildFailed'. Every exception counts as a failure+-- except this supervisor's own 'SupervisorShutdown'. Nothing is+-- propagated once shutdown has started.+--+-- * 'registerForShutdown' makes an existing thread get killed on shutdown,+-- without the supervisor waiting for its cleanup or propagating its+-- failures.+--+-- Requires the threaded RTS.+module GHC.Debugger.Data.Supervisor+ ( Supervisor+ , OnFailure (..)+ , ChildFailed (..)+ , SupervisorShutdown (..)+ , withSupervisor+ , spawn+ , registerForShutdown+ , awaitAll+ , throwToParent+ ) where++import Control.Applicative ((<|>))+import Control.Concurrent+import Control.Concurrent.STM+import Control.Exception+import Control.Monad+import Data.IORef+import qualified Data.Set as Set+import Data.Unique+import System.Mem.Weak (deRefWeak)++------------------------------------------------------------------------+-- Types++data OnFailure = Propagate | Ignore+ deriving (Eq, Show)++data Supervisor = Supervisor+ { supId :: Unique+ , parent :: ThreadId+ , stopping :: TVar Bool+ -- ^ shutdown initiated+ , workers :: TVar (Set.Set ThreadId)+ -- ^ spawned children still alive+ , inFlight :: TVar Int+ -- ^ children currently delivering 'ChildFailed'+ }++-- | Thrown to the parent when a 'Propagate' child fails.+data ChildFailed = ChildFailed Unique ThreadId SomeException++instance Show ChildFailed where+ show (ChildFailed _ t e) = "ChildFailed " ++ show t ++ " " ++ show e++instance Exception ChildFailed where+ toException = asyncExceptionToException+ fromException = asyncExceptionFromException+ displayException (ChildFailed _ t e) =+ "supervised thread " ++ show t ++ " failed: " ++ displayException e++-- | Thrown to supervised threads on shutdown. Never propagated by the+-- supervisor that sent it.+newtype SupervisorShutdown = SupervisorShutdown Unique++instance Show SupervisorShutdown where+ show _ = "SupervisorShutdown"++instance Exception SupervisorShutdown where+ toException = asyncExceptionToException+ fromException = asyncExceptionFromException+ displayException _ = "supervisor shutdown"++------------------------------------------------------------------------+-- Lifecycle++-- | Run the body with a fresh supervisor whose parent is the calling+-- thread. The grace period is in microseconds.+withSupervisor :: Maybe Int -> (Supervisor -> IO a) -> IO a+withSupervisor graceMicros =+ bracket newSupervisor (`shutdown` graceMicros)++newSupervisor :: IO Supervisor+newSupervisor =+ Supervisor <$> newUnique <*> myThreadId <*> newTVarIO False+ <*> newTVarIO Set.empty <*> newTVarIO 0++-- | Not exported: runs masked from withSupervisor's bracket.+shutdown :: Supervisor -> Maybe Int -> IO ()+shutdown sup graceMicros = do+ -- uninterruptible atomic block, because it doesn't retry+ tids <- atomically $ do+ writeTVar (stopping sup) True+ Set.toList <$> readTVar (workers sup)+ forM_ tids $ \t -> forkIO (throwTo t (SupervisorShutdown (supId sup)))+ foreignFailure <- newIORef Nothing+ waitDoneWorkers <- mkWaitDone sup graceMicros+ let+ waitDone = do+ -- in-flight propagations always complete promptly, so no deadline+ readTVar (inFlight sup) >>= check . (== 0)+ waitDoneWorkers+ -- interruptible atomic block: only resilient to ChildFailed and SupervisorShutdown exceptions+ loop = atomically waitDone `catches`+ [ Handler $ \cf@(ChildFailed u _ _) -> do+ when (u /= supId sup) $+ modifyIORef' foreignFailure (<|> Just (toException cf))+ loop+ , Handler $ \sd@(SupervisorShutdown u) -> do+ when (u /= supId sup) $ -- should never be equal+ modifyIORef' foreignFailure (<|> Just (toException sd))+ loop+ ]+ loop+ readIORef foreignFailure >>= mapM_ throwIO++mkWaitDone :: Supervisor -> Maybe Int -> IO (STM ())+mkWaitDone sup mgraceMicros = do+ deadlineDone <- case mgraceMicros of+ Nothing -> pure (pure False)+ Just micros -> registerDelay micros >>= \d -> pure (readTVar d)++ pure $ do+ workers <- readTVar (workers sup)+ check (Set.null workers) `orElse` (check =<< deadlineDone)++throwToParent :: Exception e => Supervisor -> e -> IO ()+throwToParent sup e = throwTo (parent sup) e+------------------------------------------------------------------------+-- Children++spawn :: Supervisor -> OnFailure -> IO () -> IO ThreadId+spawn sup onFail action = mask_ $ do+ tid <- forkIOWithUnmask $ \unmask -> do+ tid <- myThreadId+ registered <- atomically $ do+ s <- readTVar (stopping sup)+ unless s $ modifyTVar' (workers sup) (Set.insert tid)+ pure (not s)+ when registered $+ (do r <- try (unmask action)+ case r of+ Left e | onFail == Propagate, not (isOwnShutdown sup e) ->+ propagate sup tid e+ _ -> pure ())+ `finally` atomically (modifyTVar' (workers sup) (Set.delete tid))+ -- only return after worker is registered+ atomically $ do+ s <- readTVar (stopping sup)+ when (not s) $ readTVar (workers sup) >>= check . Set.member tid+ pure tid+++-- | Runs the given action after spawning a watcher thread in the given Supervisor.+--+-- The watcher redirects the SupervisorShutdown exception to the current thread,+-- then waits for it to exit this call.+--+-- If the action returns before a supervisor shutdown then the watcher is killed instead.+registerForShutdown :: Supervisor -> IO () -> IO ()+registerForShutdown sup m = do+ tid <- myThreadId+ when (tid == parent sup) $+ throwIO (userError "registerForShutdown: the parent cannot register")+ m_done <- newEmptyMVar+ flip finally (putMVar m_done ()) $ do+ wtid <- mkWeakThreadId tid+ -- Nothing: undecided; Just True: watcher armed; Just False: disarmed+ armed <- newTVarIO Nothing+ watcher <- spawn sup Ignore $+ (do ok <- atomically $ readTVar armed >>= \case+ Nothing -> writeTVar armed (Just True) >> pure True+ Just _ -> pure False+ when ok $ forever (threadDelay maxBound))+ `finally` do+ a <- readTVarIO armed+ when (a == Just True) $ do+ deRefWeak wtid >>= mapM_ (`throwTo` SupervisorShutdown (supId sup)) >> takeMVar m_done+ gaveUp <- atomically $ readTVar armed >>= \case+ Just _ -> pure False+ Nothing -> do+ readTVar (stopping sup) >>= check+ writeTVar armed (Just False)+ pure True+ when gaveUp $ throwIO (SupervisorShutdown (supId sup))+ -- We want to stop the watcher before returning, so we disarm it and kill it.+ -- Disarming is necessary because the watcher could still be sleeping.+ --+ -- The `uninterruptibleMask_` is to prevent the watcher from killing us at the very end.+ -- The watcher is interruptible most of the time, so we will not be blocking for long.+ m `finally` (atomically (writeTVar armed (Just False)) >> uninterruptibleMask_ (killThread watcher))++-- | Waits for all threads spawned by this supervisor to terminate.+awaitAll :: Supervisor -> Maybe Int -> IO ()+awaitAll sup graceMicros = join $ atomically <$> mkWaitDone sup graceMicros++------------------------------------------------------------------------+-- Internals++-- | Propagates an exception from a child to the parent. Must be called masked.+--+-- Ideally this would be `throwTo`, but there's a race with the parent returning+-- from `withSupervisor`: if the grace period expires, `withSupervisor` could+-- return before the delivery of the propagated exception, which now would kill+-- the parent thread, instead of the child having been killed.+--+-- To avoid that race we increment the `inFlight` count here, so that `shutdown` can+-- wait for the delivery.+propagate :: Supervisor -> ThreadId -> SomeException -> IO ()+propagate sup tid e = do+ go <- atomically $ do+ s <- readTVar (stopping sup)+ unless s $ modifyTVar' (inFlight sup) (+ 1)+ pure (not s)+ when go $+ throwTo (parent sup) (ChildFailed (supId sup) tid e)+ `finally` atomically (modifyTVar' (inFlight sup) (subtract 1))++isOwnShutdown :: Supervisor -> SomeException -> Bool+isOwnShutdown sup e = case fromException e of+ Just (SupervisorShutdown u) -> u == supId sup+ Nothing -> False
+ haskell-debugger/GHC/Debugger/Data/ThreadMap.hs view
@@ -0,0 +1,44 @@+-- | A map to track and manage the debuggee runtime threads+module GHC.Debugger.Data.ThreadMap+ ( ThreadMap+ , emptyThreadMap++ -- * Operations+ , insertThreadMap+ , lookupThreadMap+ , deleteThreadMap++ , threadMapToList++ -- can we detect when a thread has died? what happens if we have a reference+ -- to a ThreadId which has been GC'd?+ ) where++import Data.Coerce++import qualified Data.IntMap as IM++-- | A thread map maintains a mapping between the int thread identifier, which+-- uniquely identifies a thread spawned by the debuggee, and the (possibly+-- remote) reference to the thread (i.e. the corresponding ThreadId)+type ThreadMap a = IM.IntMap a++-- | Insert a remote 'ThreadId' at this unique Int thread identifier+insertThreadMap :: Int -> a -> ThreadMap a -> ThreadMap a+insertThreadMap = IM.insert++-- | Lookup a remote 'ThreadId' by its unique Int identifier+lookupThreadMap :: Int -> ThreadMap a -> Maybe a+lookupThreadMap = IM.lookup++-- | Insert a remote 'ThreadId' at this unique Int thread identifier+deleteThreadMap :: Int -> ThreadMap a -> ThreadMap a+deleteThreadMap = IM.delete++-- | > It's empty, what did you expect?+emptyThreadMap :: ThreadMap a+emptyThreadMap = IM.empty++-- | Get all the remote thread references from the ThreadMap+threadMapToList :: ThreadMap a -> [(Int, a)]+threadMapToList = coerce . IM.toList
haskell-debugger/GHC/Debugger/Debuggee.hs view
@@ -57,23 +57,26 @@ } mkInternalInterpreterFlags :: DynFlags -> DynFlags-mkExternalInterpreterFlags :: String -> DynFlags -> DynFlags-(mkInternalInterpreterFlags, mkExternalInterpreterFlags) = (mkInterpreterFlags True "", mkInterpreterFlags False)- where- mkInterpreterFlags :: Bool -> String -> DynFlags -> DynFlags- mkInterpreterFlags preferInternalInterpreter externalInterpreterProg df = df- -- Enable the external interpreter by default! See #169- -- See Note [Custom external interpreter]- & enableExternalInterpreter preferInternalInterpreter- -- Ext interp is the same program as this, with "--external-interpreter"- -- (this is ignored on GHC 9.14, see Note [Custom external interpreter])- & setPgmI externalInterpreterProg- -- ideally, we'd set "external-interpreter" *before* the file- -- descriptors. since there's no way to do that yet, we just have- -- some logic in main to detect [writefd, readfd, --external-interpreter]- & addOptI "--external-interpreter"+mkInternalInterpreterFlags = mkInterpreterFlags True "" [] +mkExternalInterpreterFlags :: String -> [String] -> DynFlags -> DynFlags+mkExternalInterpreterFlags = mkInterpreterFlags False +mkInterpreterFlags :: Bool -> String -> [String] -> DynFlags -> DynFlags+mkInterpreterFlags preferInternalInterpreter externalInterpreterProg extraArgs df = df+ -- Enable the external interpreter by default! See #169+ -- See Note [Custom external interpreter]+ & enableExternalInterpreter preferInternalInterpreter+ -- Ext interp is the same program as this, with "--external-interpreter"+ -- (this is ignored on GHC 9.14, see Note [Custom external interpreter])+ & setPgmI externalInterpreterProg+ -- ideally, we'd set "external-interpreter" *before* the file+ -- descriptors. since there's no way to do that yet, we just have+ -- some logic in main to detect [writefd, readfd, --external-interpreter, extraArgs...]+ & addOptI "--external-interpreter"+ & \d -> foldl (flip addOptI) d extraArgs++ mkInternalInterpreterSetup :: LogAction IO DebuggerLog -> DynFlags -> Ghc a -> Ghc a mkInternalInterpreterSetup _ dflags mainGhcThread = do when (gopt Opt_ExternalInterpreter dflags) $ do@@ -117,6 +120,8 @@ { std_in , std_out , std_err+ -- We want to send sigINT, and System.Process makes you target the whole group.+ , create_group = True -- Override executable path -- See Note [Custom external interpreter] #if MIN_VERSION_ghc(9,15,0)@@ -201,7 +206,7 @@ Nothing -> pure Inherit -- the same program invoked with `external-interpreter` serves as the external interpreter thisProg <- getExecutablePath- pure InterpreterSettings { interpreterFlags = mkExternalInterpreterFlags thisProg+ pure InterpreterSettings { interpreterFlags = mkExternalInterpreterFlags thisProg [] , interpreterSetup = mkExternalInterpreterSubProcessSetup stdinStream Inherit Inherit (const $ pure ()) }
haskell-debugger/GHC/Debugger/Interface/Messages.hs view
@@ -93,23 +93,28 @@ -- we're stopped at rather than all variables in scope. | GetVariables RemoteThreadId Int{-stack frame positional ix-} VariableReference - -- | Evaluate an expression at the current breakpoint.- | DoEval String- -- | Get information about the current exception (if any) on a thread. | GetExceptionInfo RemoteThreadId - -- | Continue executing from the current breakpoint- | DoContinue-- -- | Step local, which executes until next breakpoint in the same function.- | DoStepLocal-- -- | Single step always to the next breakpoint. Used for "step-in".- | DoSingleStep+ -- | Evaluate an expression at the current breakpoint.+ --+ -- When the frame id is given, the expression is run in the context of that frame.+ | DoEval (Maybe (RemoteThreadId, Int{-stack frame positional ix-})) String - -- | Step out to the breakpoint immediately following a return.- | DoStepOut+ -- | Resume the paused thread using the given 'ResumeStep' and 'ResumeTheWorld' options.+ -- See the respective haddocks for details.+ --+ -- Examples:+ --+ -- - To "global continue": @DoResume <active tid> ResumeNoStep ResumeTheWorld@+ -- (in this case, the active tid is of no consequence, but still passed)+ --+ -- - To "single-thread step in": @DoResume <a tid> ResumeSingleStep ResumeJustThisThread@+ --+ -- - To "global step-next": @DoResume <a tid> ResumeStepLocal ResumeTheWorld@;+ -- All threads will be resumed and the specified thread will break at the+ -- next local breakpoint.+ | DoResume RemoteThreadId ResumeStep ResumeTheWorld -- | Execute a prog with debugging enabled. Breaks on the existing breakpoints. --@@ -120,6 +125,41 @@ -- Haskell function arguments. | DebugExecution { entryPoint :: EntryPoint, entryFile :: AbsFilePath, runArgs :: [String] } + -- | Request the debuggee to stop.+ --+ -- Does not forcibly kill the debuggee, reports whether it actually stopped instead.+ | TerminateDebuggee++-- | The type of stepping to do when resuming a thread.+data ResumeStep+ = ResumeNoStep -- ^ No stepping, i.e. just resume/continue the thread.+ | ResumeSingleStep -- ^ Single step, i.e. stop at the immediate next breakpoint+ | ResumeStepLocal -- ^ Step to the next breakpoint on the same function at the source level+ | ResumeStepOut -- ^ Step out to the case continuation to which the thread+ -- returns from the current function++-- | Describes whether to resume all threads besides the specified one.+-- In the default stop-the-world mode, pause/continue should resume all threads+-- when we resume and pause all threads when we hit a breakpoint. When in+-- non-stop-the-world mode, only the specified thread gets resumed.+--+-- Important:+--+-- - When 'ResumeJustThisThread' is used, the debugger mode is toggled to+-- non-stop-the-world, so, when that thread hits a breakpoint, it is only+-- reported for that thread.+--+-- - When 'ResumeTheWorld' is used, the debugger mode is toggled to+-- stop-the-world (regardless of threads having just been resumed with+-- 'ResumeJustThisThread'). From that point on, until 'ResumeJustThisThread'+-- is used again, all breakpoints hit pause all threads in addition to the+-- one that hit the breakpoint.+data ResumeTheWorld+ -- | Resume only the specified thread and toggle the non-stop-the-world mode+ = ResumeJustThisThread+ -- | Resume all threads in addition to the specified one and toggle stop-the-world mode+ | ResumeTheWorld+ -- | An entry point for program execution. data EntryPoint = MainEntry { mainName :: Maybe String } | FunctionEntry { fnName :: String } deriving (Show)@@ -266,9 +306,9 @@ | DidRemoveBreakpoint BreakFound | DidGetBreakpoints (Maybe SourceSpan) | DidClearBreakpoints- | DidContinue EvalResult- | DidStep EvalResult+ | DidResume EvalResult | DidExec EvalResult+ | DidTerminate Bool | GotThreads [DebuggeeThread] | GotStacktrace [DbgStackFrame] | GotScopes [ScopeInfo]
haskell-debugger/GHC/Debugger/Monad.hs view
@@ -13,30 +13,34 @@ {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE NondecreasingIndentation #-} -module GHC.Debugger.Monad where+module GHC.Debugger.Monad+ ( module GHC.Debugger.Monad+ , module GHC.Debugger.Monad.Type+ , module GHC.Debugger.Monad.Load+ )+where import Control.Concurrent-import Control.Exception import qualified Data.Foldable as Foldable import Control.Monad import Control.Monad.Catch as MC import Control.Monad.IO.Class import Control.Monad.Reader import Data.Function-import Data.IORef import Data.Maybe-import qualified Data.Set as Set-import Data.Version (makeVersion, showVersion) import Prelude hiding (mod) #ifdef MIN_VERSION_unix import System.Posix.Signals #endif-import qualified Data.List as L import qualified Data.List.NonEmpty as NonEmpty-import qualified GHC.Conc.Sync as C+import System.Process (terminateProcess, interruptProcessGroupOf, getPid, ProcessHandle)+import System.Timeout (timeout)+import System.IO.Error (isEOFError, isResourceVanishedError)+import Control.Exception -import GHC-import GHC.Data.StringBuffer+import qualified GHC.Conc.Sync as C+import GHC hiding (runGhc)+import GHC.Runtime.Interpreter.Types import GHC.Driver.Config.Diagnostic import GHC.Driver.Config.Logger import GHC.Driver.DynFlags as GHC@@ -44,148 +48,43 @@ import GHC.Driver.Monad import GHC.Driver.Errors import GHC.Driver.Errors.Types-import GHC.Driver.Main import GHC.Driver.Make-import GHC.Driver.Ppr import GHC.Driver.Session (parseDynamicFlagsCmdLine)-import GHC.Runtime.Eval-import GHC.Runtime.Heap.Inspect import GHC.Runtime.Interpreter as GHCi import GHC.Runtime.Loader as GHC import GHC.Runtime.Context as GHCi import GHC.Types.Error-import GHC.Types.SourceError import GHC.Unit.Module.Graph-import GHC.Unit.State import GHC.Unit.Types import qualified GHC.Utils.Logger as GHC import GHC.Utils.Outputable as GHC import qualified GHC.LanguageExtensions as LangExt -import GHC.Debugger.Interface.Messages import GHC.Debugger.Session import GHC.Debugger.Session.Builtin-import GHC.Debugger.Session.Interactive-import GHC.Debugger.Runtime.Compile.Cache-import qualified GHC.Debugger.Breakpoint.Map as BM-import qualified GHC.Debugger.Runtime.Thread.Map as TM import Colog.Core as Logger -import {-# SOURCE #-} GHC.Debugger.Runtime.Instances.Discover (RuntimeInstancesCache, emptyRuntimeInstancesCache) import GHC.Stack.Annotation-import GHC.Platform.Ways import GHC.Unit.Home.Graph import GHC.Debugger.Utils.Orphans () -- bring orphan instances to everything which uses `Debugger`-import System.Directory (getCurrentDirectory) import GHC.Debugger.Debuggee import GHC.Plugins (HasCallStack) import Data.Bifunctor-import qualified GHC.Unit.Module.Graph as GHC---- | A debugger action.-newtype Debugger a = Debugger { unDebugger :: ReaderT DebuggerState GHC.Ghc a }- deriving ( Functor, Applicative, Monad, MonadIO- , MonadThrow, MonadCatch, MonadMask- , GHC.HasDynFlags, MonadReader DebuggerState )--data BreakpointInfo = BreakpointInfo- { bpInfoStatus :: !BreakpointStatus- , bpInfoKind :: !BreakpointKind- , bpInfoAction :: !BreakpointAction- }- deriving (Eq,Show)---- | State required to run the debugger.------ - Keep track of active breakpoints to easily unset them all.-data DebuggerState = DebuggerState- { activeBreakpoints :: IORef (BM.BreakpointMap BreakpointInfo)- -- ^ Maps a 'InternalBreakpointId' in Trie representation (map of Module to map of Int) to the- -- 'BreakpointStatus' it was activated with.-- , rtinstancesCache :: IORef RuntimeInstancesCache- -- ^ RuntimeInstancesCache-- , threadMap :: IORef TM.ThreadMap- -- ^ 'ThreadMap' for threads spawned by the debuggee-- , compCache :: IORef CompCache- -- ^ Cache loaded and compiled expressions.-- , hsDbgViewUnitId :: Maybe UnitId- -- ^ The unit-id of the companion @haskell-debugger-view@ unit, used for- -- user-defined and built-in custom debug visualisations of values (e.g.- -- for Strings or IntMap).- --- -- If the user depends on @haskell-debugger-view@ in its transitive- -- closure, then we should use that exact unit which was solved by Cabal.- -- The built-in instances and additional instances be available for the- -- 'DebugView' class found in that unit. We can find the exact unit of- -- the module by looking for @haskell-debugger-view@ in the module graph.- --- -- If the user does not depend on @haskell-debugger-view@ in any way,- -- then we create our own unit and try to load the- -- @haskell-debugger-view@ modules directly into it. As long as loading- -- succeeds, the 'DebugView' class from this custom unit can be used to- -- find the built-in instances for types like @'String'@- --- -- If the user explicitly disabled custom views, use @Nothing@.-- , dbgLogger :: LogAction Debugger DebuggerLog- -- ^ See Note [Debugger, debuggee, and DAP logs]- }--instance GHC.HasLogger Debugger where- getLogger = liftGhc GHC.getLogger--instance GHC.GhcMonad Debugger where- getSession = liftGhc GHC.getSession- setSession s = liftGhc $ GHC.setSession s---- | Enabling/Disabling a breakpoint-data BreakpointStatus- -- | Breakpoint is disabled- --- -- Note: this must be the first constructor s.t.- -- @BreakpointDisabled < {BreakpointEnabled, BreakpointAfterCount}@- = BreakpointDisabled- -- | Breakpoint is enabled- | BreakpointEnabled- -- | Breakpoint is disabled the first N times and enabled afterwards- | BreakpointAfterCount Int- -- | Breakpoint is enabled when condition evaluates to true- | BreakpointWhenCond String- -- | Breakpoint is disabled the first N times the condition evaluates to- -- true and enabled in the next time it is true- | BreakpointAfterCountCond Int String- deriving (Eq, Ord, Show)--instance Outputable BreakpointStatus where ppr = text . show---- | What to do when a breakpoint is enabled-data BreakpointAction- -- | Evaluation is stopped, typical behaviour- = BreakpointStop- {- | A log message is printed and then evaluation resumes.- The @String@ is an expression that takes care of interpolation and printing the log message.- -}- | BreakpointLogAndResume String- deriving (Eq, Ord, Show)--instance Outputable BreakpointAction where ppr = text . show+import GHC.Debugger.Monad.Type+import GHC.Debugger.Monad.Load+import GHCi.Message+import Data.Binary.Get+import qualified Data.Text as T+import Data.IORef+import GHC.Utils.Panic (panic)+import Control.Concurrent.Async+import Data.Coerce -------------------------------------------------------------------------------- -- Operations -------------------------------------------------------------------------------- --- | Additional settings configuring the debugger-data RunDebuggerSettings = RunDebuggerSettings- { supportsANSIStyling :: Bool- , supportsANSIHyperlinks :: Bool- , interpreterSettings :: InterpreterSettings- }- -- | Run a 'Debugger' action on a session constructed by a 'DebugRunner' -- -- INVARIANT: The initUniqSupply has already been initialized.@@ -199,31 +98,15 @@ runDebugger l debugRunner conf action = annotateCallStackIO $ do debugRunner $ \ rootDir extraGhcArgs loadHomeUnit -> runDebuggerAction l rootDir extraGhcArgs conf loadHomeUnit action -type DebugSession m a- = FilePath -- ^ project root dir- -> [String] -- ^ extra ghc args- -> m () -- ^ action to load debugee home units- -> Ghc a--type DebugRunner m a = DebugSession m a -> IO a--data ProjectDebugSpec = ProjectDebugSpec- { rootDir :: FilePath- -- ^ Project root directory- , componentDir :: FilePath- -- ^ Root dir of the loaded 'ComponentOptions'.- -- Important for multi-package cabal projects, as packages are not in the- -- root of the cradle, but in some sub-directory.- , libdir :: FilePath- -- ^ The libdir (given with -B as an arg)- , units :: [String]- -- ^ The list of units included in the invocation- , ghcInvocation :: [String]- -- ^ The full ghc invocation (as constructed by hie-bios flags)- , absEntryFile :: FilePath- -- ^ Path to the main function- , extraGhcArgs :: [String]- }+runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.+ -> Ghc a -- ^ The action to perform.+ -> IO a+runGhc mb_top_dir ghc = do+ ref <- newIORef (panic "empty session")+ let session = Session ref+ flip unGhc session $ do -- withSignalHandlers $ do -- catch ^C+ initGhcMonad mb_top_dir+ withCleanupSession ghc -- | Construct a session from paths and flags inferred from the debugee's project. withProjectDebugSession@@ -232,15 +115,7 @@ -> DebugRunner m a withProjectDebugSession ProjectDebugSpec{ghcInvocation = ghcI, ..} k = do let ghcInvocation = filter (\case ('-':'B':_) -> False; _ -> True) ghcI- GHC.runGhc (Just libdir) $ do-#ifdef MIN_VERSION_unix- -- Workaround #4162- -- FIXME: setup reasonable handlers to run cleanupSession for every debugger thread, because runGhc's `withSignalHandlers` is not it.- _ <- liftIO $ installHandler sigINT Default Nothing- _ <- liftIO $ installHandler sigQUIT Default Nothing- _ <- liftIO $ installHandler sigTERM Default Nothing- _ <- liftIO $ installHandler sigHUP Default Nothing-#endif+ runGhc (Just libdir) $ do k rootDir extraGhcArgs $ do dflags2 <- getSessionDynFlags @@ -268,7 +143,7 @@ -> Debugger a -> Ghc a runDebuggerAction l rootDir extraGhcArgs conf loadHomeUnit (Debugger action)- = flip MC.finally cleanupInterp $+ = flip MC.finally (cleanupInterp l KillMode) $ -- See Note [Shutting down the external interpreter] do dflags0 <- GHC.getSessionDynFlags@@ -403,11 +278,11 @@ code <- compileExprRemote $ moduleNameString debuggerRuntimeInternalModName ++ ".setLineBuffering" liftIO $ evalIO interp code - noPrint <- defineNoPrint+ noPrint <- lookupNoPrintConstant modifySession (\hsc_env -> hsc_env {hsc_IC = GHCi.setInteractivePrintName (hsc_IC hsc_env) noPrint}) runReaderT action- =<< initialDebuggerState (liftLogIO l)+ =<< initialDebuggerState l (if loadedBuiltinModNames == [] then Nothing else Just hdv_uid)@@ -424,109 +299,19 @@ liftIO $ C.labelThread thId lbl pure x --- | Throws exception when module fails to load.-loadInternal- :: LogAction IO DebuggerLog- -> Ways- -> Ghc ()-loadInternal l buildWays = do- let ghcLog = liftLogIO l - dflags <- getDynFlags- addInMemoryDebuggerInternalUnit (setDynFlagWays buildWays dflags)- let uid = debuggerInternalUnitId- successes <- loadInMemoryModules l uid modsToLoad- forM_ (zip successes modsToLoad) $ \case- (Failed,(modName,_)) -> do- ghcLog <& DebuggerLog Logger.Debug- (LogFailedToCompileBuiltinModule modName)- liftIO $ fail "Failed to load DebuggerInternal Module"- (Succeeded,_) ->- return ()- where- modsToLoad =- [(debuggerRuntimeInternalModName,debuggerRuntimeInternalContents)]--#if !MIN_VERSION_ghc(9,14,2)-data FailedToLoadFFIInspectModule = FailedToLoadFFIInspectModule- deriving Show-instance Exception FailedToLoadFFIInspectModule---- | Throws exception when module fails to load.--- Needed for GHC.Debugger.Runtime.Interpreter.Legacy-loadFFIInspect- :: LogAction IO DebuggerLog- -> Ways- -> Ghc ()-loadFFIInspect l buildWays = do- let ghcLog = liftLogIO l-- dflags <- getDynFlags- uid <- addInMemoryFFIInspectUnit [baseUnitId dflags] (setDynFlagWays buildWays dflags)-- successes <- loadInMemoryModules l uid modsToLoad- forM_ (zip successes modsToLoad) $ \case- (Failed,(modName,_)) -> do- ghcLog <& DebuggerLog Logger.Debug- (LogFailedToCompileBuiltinModule modName)- liftIO $ throwIO FailedToLoadFFIInspectModule- (Succeeded,_) ->- return ()- where- modsToLoad =- [(debuggerRuntimeFFIInspectModName,debuggerRuntimeFFIInspectContents)]-#endif--findOrLoadHaskellDebuggerView :: LogAction IO DebuggerLog- -> Ways- -> Ghc (UnitId, [ModuleName])-findOrLoadHaskellDebuggerView l buildWays = do- let ghcLog = liftLogIO l- hsc_env <- getSession-- -- Try to find or load the built-in classes from `haskell-debugger-view`- findHsDebuggerViewUnitId >>= \case- Nothing -> (hsDebuggerViewInMemoryUnitId,) <$> do- -- Not imported by any module: no custom views. Therefore, the builtin- -- ones haven't been loaded. In this case, we will load the package ourselves.-- -- Add the custom unit to the HUG- let base_dep_uids = graphsUnits hsc_env- addInMemoryHsDebuggerViewUnit base_dep_uids . setDynFlagWays buildWays =<< getDynFlags-- -- Load unit modules using in-memory contents.- let- -- Don't try to load instances whose packages are not even in the- -- module graph.- (instanceMods,skipped) = L.partition (\ (_modName,_modContent,pkgName) -> any ((pkgName `L.isPrefixOf`) . unitIdString) base_dep_uids)- debuggerViewInstancesMods- modsToLoad =- (debuggerViewClassModName,debuggerViewClassContents)- : [ (modName,modContent)- | (modName, modContent, _pkgName) <- instanceMods]-- forM_ skipped $ \(modName,_,pkgName) ->- ghcLog <& DebuggerLog Logger.Debug- (LogSkippingViewModuleNoPkg modName pkgName (map unitIdString base_dep_uids))-- successes <- loadInMemoryModules l hsDebuggerViewInMemoryUnitId modsToLoad-- fmap catMaybes . forM (zip successes modsToLoad) $ \case- (Failed,(modName,_)) -> do- ghcLog <& DebuggerLog Logger.Debug- (LogFailedToCompileBuiltinModule modName)- return $ Nothing- (Succeeded,(modName,_)) ->- return $ Just modName-- Just uid -> do- -- TODO: We assume for now that if you depended on- -- @haskell-debugger-view@, then you also depend on all its transitive- -- dependencies (containers, text, ...), thus can load all custom- -- views. Hence all `debuggerViewBuiltinMods`. In the future, we- -- may want to guard all dependencies behind cabal flags that the user- -- can tweak when depending on `haskell-debugger-view`.- return (uid, map fst debuggerViewBuiltinMods)+-- | Runs action in a separate thread so current thread is interruptible even if+-- the action uses `uninterruptibleMask`.+interruptible :: Debugger a -> Debugger a+interruptible m = Debugger $ ReaderT $ \ st -> Ghc $ \ioref -> do+ -- Cannot use `withAsync` because it calls uninterruptibleCancel+ MC.mask $ \ restore -> do+ a <- async (restore $ coerce m st ioref)+ restore (wait a) `MC.catchNoPropagate` \e -> do+ -- we forkIO the cancel to avoid getting stuck trying to interrupt+ -- uninterruptable code.+ _ <- forkIO $ cancelWith a (e :: ExceptionWithContext SomeException)+ rethrowIO e {- Note [Shutting down the external interpreter]@@ -549,6 +334,8 @@ not a child of this process (which will happen in the runInTerminal external interpreter case). `getProcessExitCode` should error with `ECHILD` in this case (see `man 2 wait`), even if it doesn't yet (see process#359).+Note that `getProcessExitCode` is also called when handling any I/O or parsing+error during communication with the external interpreter. Therefore, the debugger must step in and make sure the external interpreter is exited cleanly, WITHOUT resorting to `getProcessExitCode`. To this effect, we@@ -557,6 +344,30 @@ `withCleanupSession`, which will now do Nothing because we set `InterpPending`, and beyond). +To get the external interpreter (EI) to shutdown cleanly we adopt this sequence:+1. Interrupt the EI process.+ - Delivers UserInterrupt to whatever is being evaluated, or gets ignored.+2. Send `Shutdown`+3. Check for EOF from EI's Pipe. This is done by reading from it with a 1s timeout.+ a. If EOF then EI must have closed the pipe while shutting down: success.+ b. Otherwise, repeat steps 1-3 but send sigKILL if we reach 3.b again.++EI sets up signal handlers so that an interrupt is redirected as an+UserInterrupt exception to its server loop thread. Then two things can happen:+- if waiting for debuggee to stop running, the UserInterrupt+ will be redirected to the user code thread.+- otherwise, the UserInterrupt will be ignored.++In the first case, the debuggee might just ignore the UserInterrupt, in which+case the server loop is again stuck waiting for the debuggee to end. Repeating+step 1 of our sequence is meant to help with that.+Note this will not help if the server loop is blocked while delivering the first+UserInterrupt to the debuggee though, because the throwTo is done without+unmasking.++The sequence is modified for `terminateDebuggee` to just report the status+rather signal with `sigKILL` when reaching 3.b again.+ Note [Must explicitly expose module graph units] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ `interactiveGhcDebugger` is our "current home unit", so its@@ -612,30 +423,103 @@ See also #283 -} +terminateDebuggee :: Debugger Bool+terminateDebuggee = do+ l <- asks dbgLogger+ liftGhc $ cleanupInterp (liftLogIO l) TerminateMode++data CleanupMode = TerminateMode | KillMode+ -- | See Note [Shutting down the external interpreter]-cleanupInterp :: Ghc ()-cleanupInterp = do+-- Can be called from main debug thread to try and stop debuggee/interp process.+-- Reports whether we can presume success.+-- Escalates to sigKILL if called with True.+cleanupInterp :: LogAction IO DebuggerLog -> CleanupMode -> Ghc Bool+cleanupInterp l mode = do interp <- hscInterp <$> getSession case interpInstance interp of- InternalInterp -> pure ()- ExternalInterp ext -> liftIO $ withExtInterpStatus ext $ \mstate -> do- MC.mask $ \_restore -> modifyMVar_ mstate $ \state -> do+ InternalInterp -> do+ pure True+ ExternalInterp ext -> do+ liftIO $ withExtInterpStatus ext $ \mstate -> do+ MC.mask $ \restore -> modifyMVar mstate $ \state -> do case state of- InterpPending -> pure state -- already stopped- InterpRunning i -> do+ InterpPending -> pure (state,True) -- already stopped+ InterpRunning i -> (`MC.onException` finalTry i) $ do+ tryStoppingExtInterp restore i $+ -- a second interrupt has a chance to reset main loop even with stubborn debuggee,+ -- c.f. redirectInterrupts.+ tryStoppingExtInterp restore i $ finalTry i+ where+ finalTry i+ | KillMode <- mode = do+ killProcess' i.instProcess.interpHandle+ success+ | otherwise = pure (InterpRunning i,False)+ success = do+ pure (InterpPending,True)+ tryStoppingExtInterp restore i keepGoing = do -- Can't use `getProcessExitCode` because the interp process is -- not necessarily a child of this process (runInTerminal case).- -- Just unconditionally try to send the message.- sendMessage i Shutdown- pure InterpPending -annotateDebuggerStackString :: String -> Debugger a -> Debugger a-annotateDebuggerStackString s (Debugger m) = Debugger $ do- r <- ReaderT $ \val -> do- withUnliftGhc $ \ unlift ->- annotateStackStringIO s (unlift $ runReaderT m val)- pure r+ -- This hopefully interrupts the debuggee.+ interruptProcessGroupOf i.instProcess.interpHandle + -- The Pipe type does not expose the Handle, so we can't confirm the+ -- IOError is from the pipe in the catches below.+ -- TODO: We could stash the Handles somewhere since we create them ourselves though.+ let isPipeClosedError (fromException -> Just e)+ = isEOFError e || isResourceVanishedError e+ -- any other IOError to include?+ isPipeClosedError _ = False++ let+ handlePipeException m k = do+ er <- MC.try m+ case er of+ Right r -> k r+ Left x+ | isPipeClosedError x -> do+ l <& DebuggerSessionLog Debug (T.pack $ displayExceptionWithInfo x)+ success+ | otherwise -> do+ l <& DebuggerSessionLog Debug (T.pack $ displayExceptionWithInfo x)+ keepGoing++ -- However, we do use writePipe/readPipe directly, to avoid parsing+ -- errors and the exception handling in sendMessage.+ let pipe = i.instProcess.interpPipe++ -- We `writePipe` rather than `sendMessage` to avoid the exception+ -- handling logic in the latter.+ handlePipeException (writePipe pipe (putMessage Shutdown)) $ \() -> do++ -- We wrote Shutdown, which does not send a reply.+ --+ -- Now we read to see EOF, which should indicate the+ -- interpreter closed the socket and is shutting down.+ --+ -- We give the interpreter 1s to close the socket, otherwise we escalate.+ handlePipeException (timeout 1_000_000 (restore $ readPipe pipe getRemainingLazyByteString)) $ \case+ Nothing -> do+ keepGoing+ (Just bs) -> do+ -- We read to the end of the pipe, catching EOF?+ -- I don't believe this ever happens, but it would be a success.+ l <& DebuggerSessionLog Debug (T.pack $ "cleanupInterp: Read bytes: " ++ show bs)+ success++killProcess' :: ProcessHandle -> IO ()+#ifdef MIN_VERSION_unix+killProcess' h = do+ mpid <- getPid h+ case mpid of+ Just pid -> signalProcess killProcess pid+ Nothing -> terminateProcess h+#else+killProcess' h = terminateProcess h -- TODO: sigKILL on POSIX.+#endif+ -- | Variant of GHC's parseDynamicFlags which interprets paths relative to first arg. parseDynamicFlagsWithRootDir :: MonadIO m@@ -781,260 +665,3 @@ -} -------------------------------------------------------------------------------- --- | Run downsweep on the currently set targets (see @hsc_targets@)-doDownsweep :: GhcMonad m- => Maybe ModuleGraph -- ^ Re-use existing module graph which was already summarised- -> m ModuleGraph -- ^ Module graph constructed from current set targets-doDownsweep reuse_mg = do- hsc_env <- getSession- let msg = batchMultiMsg- (errs_base, mod_graph) <- liftIO $- downsweep- hsc_env mkUnknownDiagnostic (Just msg)- (maybe [] mgModSummaries reuse_mg)-#if MIN_VERSION_ghc(10,1,0)- reuse_mg-#endif- [] False- when (not $ null errs_base) $ do- -- Print the errors to the user, rather than just throwing. When using DAP,- -- outputting to the logger the error is what displays it in the "Debug- -- Console" rather than "Output" DAP log.- logger <- getLogger- dflags <- hsc_dflags <$> getSession- let ghc_errs = fmap GhcDriverMessage (unionManyMessages errs_base)- liftIO $ printMessages logger (initPrintConfig dflags) (initDiagOpts dflags) ghc_errs-#if MIN_VERSION_ghc(9,15,0)- throwErrors (initSourceErrorContext dflags) ghc_errs-#else- throwErrors ghc_errs-#endif- return mod_graph--doLoad :: GhcMonad m => Maybe ModIfaceCache -> LoadHowMuch -> ModuleGraph -> m SuccessFlag-doLoad if_cache how_much mg = do- let msg = batchMultiMsg- load' if_cache how_much mkUnknownDiagnostic (Just msg) mg---loadInMemoryModules ::- LogAction IO DebuggerLog- -> UnitId- -> [(ModuleName,StringBuffer)] -> Ghc [SuccessFlag]-loadInMemoryModules l uid ts = do- tgts <- forM ts $ \(modName,modContents) ->- liftIO $ makeInMemoryTarget uid modName modContents- GHC.setTargets tgts- mod_graph <- hsc_mod_graph <$> GHC.getSession- dvc_mod_graph <- doDownsweep (Just mod_graph)- let new_mod_graph-#if MIN_VERSION_ghc(10,1,0)- -- new API allows extending an existing graph.- = dvc_mod_graph-#else- = mkModuleGraph $ mg_mss dvc_mod_graph ++ mg_mss mod_graph-#endif- modifySession $ GHC.setModuleGraph new_mod_graph-- restore_logger <- GHC.getLogger- dflags <- getSessionDynFlags- GHC.modifyLogger $- -- Emit it all as Debug-level debugger logs- GHC.pushLogHook $ const $ \_ _ _ sdoc ->- l <& DebuggerLog Logger.Debug (LogSDoc dflags sdoc)-- -- Might not make sense to keep going if the first fails, but we expect all of- -- them to succeed, and it's not that many more modules.- s <- forM tgts $ \ tgt -> compileModuleWithDepsInHpt tgt >>= \case- Nothing -> pure Succeeded- Just e -> do- liftLogIO l <& DebuggerLog Logger.Debug (LogSDoc dflags $ text (show e))- pure Failed-- -- Restore logger- GHC.modifyLogger $- GHC.pushLogHook (const $ GHC.putLogMsg restore_logger)-- return s------------------------------------------------------------------------------------- * Finding Debugger View------------------------------------------------------------------------------------- | Fetch the @haskell-debugger-view@ unit-id from the environment.--- @Nothing@ means custom debugger views are disabled.-getHsDebuggerViewUid :: Debugger (Maybe UnitId)-getHsDebuggerViewUid = asks hsDbgViewUnitId---- | Try to find the @haskell-debugger-view@ unit-id in the transitive closure,--- or, otherwise, return the a custom unit for which we'll load the--- @haskell-debugger-view@ modules in it (essentially preparing an in-memory--- version of the library to find the built-in instances in).------ See also comment on the @'hsDbgViewUnitId'@ field of @'DebuggerState'@-findHsDebuggerViewUnitId :: GHC.Ghc (Maybe UnitId)-findHsDebuggerViewUnitId = do- hsc_env <- getSession- let unitState = hsc_units hsc_env-- -- Note: linear in the module graph but only happens once.- let potential_units = graphsUnits hsc_env- -- Note: the intermediate set is expected to be small (<= 2).- let hskl_dbgr_vws = Set.toList . Set.fromList $- [ uid- | uid <- potential_units- , let uid_s = unitIdString uid- , "haskell-debugger-view" `L.isPrefixOf` uid_s- || "hskll-dbggr-vw" `L.isPrefixOf` uid_s- || "haskell-debug_" `L.isPrefixOf` uid_s- ]-- -- If the haskell-debugger-view is in the dependency graph, it must have- -- one of the versions the debugger is known to support:- supported_ranges -- [min, max(- = [ (makeVersion [0, 2], makeVersion [0, 3]) ]-- case hskl_dbgr_vws of- [hdv_uid] -> do- -- In transitive closure, use that one.- -- Check that the version is in supported range.- case lookupUnit unitState (RealUnit (Definite hdv_uid)) of- Just unitInfo -> do- let version = unitPackageVersion unitInfo- if any (\(l,h) -> l <= version && version < h) supported_ranges- then return (Just hdv_uid)- else throwM UnsupportedHsDbgViewVersion{supportedVersions=supported_ranges, actualVersion=version}- Nothing- | "inplace" `L.isSuffixOf` unitIdString hdv_uid- -- will be built as a target later- -> return (Just hdv_uid)- Nothing ->- error "Could not find unit info for haskell-debugger-view"- [] -> do- return Nothing- _ -> do- error $ "Multiple unit-ids found for haskell-debugger-view in the transitive closure?!" ++ showSDocUnsafe (withPprStyle (PprDump alwaysQualify) (ppr hskl_dbgr_vws))------------------------------------------------------------------------------------- Utilities------------------------------------------------------------------------------------- | Initialize a 'DebuggerState'-initialDebuggerState :: LogAction Debugger DebuggerLog -> Maybe UnitId -> GHC.Ghc DebuggerState-initialDebuggerState l hsDbgViewUid =- DebuggerState <$> liftIO (newIORef BM.empty)- <*> liftIO (newIORef emptyRuntimeInstancesCache)- <*> liftIO (newIORef TM.emptyThreadMap)- <*> liftIO (newIORef emptyCompCache)- <*> pure hsDbgViewUid- <*> pure l---- | Lift a 'Ghc' action into a 'Debugger' one.-liftGhc :: GHC.Ghc a -> Debugger a-liftGhc = Debugger . ReaderT . const--data DebuggerFailedToLoad = DebuggerFailedToLoad-instance Exception DebuggerFailedToLoad-instance Show DebuggerFailedToLoad where- show DebuggerFailedToLoad = "Failed to compile and load user project."--data UnsupportedHsDbgViewVersion = UnsupportedHsDbgViewVersion- { supportedVersions :: [ (Version, Version) ]- , actualVersion :: Version- }-instance Exception UnsupportedHsDbgViewVersion-instance Show UnsupportedHsDbgViewVersion where- show (UnsupportedHsDbgViewVersion supported actual) =- "Cannot use unsupported haskell-debugger-view version found in the transitive closure: " ++ showVersion actual ++- " (supported: " ++ L.intercalate ", " (map (\(l,h) -> showVersion l ++ " <= && < " ++ showVersion h) supported) ++ ")"--data NonFatalException = NonFatalException { userMessage :: String, debugMessage :: String }- deriving Show--instance Exception NonFatalException---expectRight :: Exception e => Either e a -> Debugger a-expectRight s = case s of- Left e -> do- logSDoc Logger.Error (text $ displayException e)- liftIO $ throwIO $ NonFatalException { userMessage = displayException e, debugMessage = displayExceptionWithInfo $ toException e }- Right a -> do- pure a------------------------------------------------------------------------------------- * Modules------------------------------------------------------------------------------------- | List all loaded modules 'ModSummary's-getAllLoadedModules :: GHC.GhcMonad m => m [GHC.ModuleNodeInfo]-getAllLoadedModules =- (mgInfos . mg_mss <$> GHC.getModuleGraph) >>=- filterM (\ms -> GHC.isLoadedModule (moduleNodeInfoUnitId ms) (moduleNodeInfoModuleName ms))- where- mgInfos xs = [ info | ModuleNode _ info <- xs ]--getAllLoadedModulesWithPaths :: GHC.GhcMonad m =>- m [(AbsFilePath,GHC.ModuleNodeInfo)]-getAllLoadedModulesWithPaths = do- ghcCwd <- mkAbsolute <$> liftIO getCurrentDirectory- -- TODO: cache?- map (\ m -> (absoluteSourcePath ghcCwd m, m)) <$> getAllLoadedModules- where- absoluteSourcePath :: AbsFilePath -> ModuleNodeInfo -> AbsFilePath- absoluteSourcePath ghcCwdDir ms- = ghcCwdDir /> (fromMaybe (error $ "missing source path: " ++ show (moduleNodeInfoModuleName ms)) $ ml_hs_file (moduleNodeInfoLocation ms))------------------------------------------------------------------------------------- * Forcing laziness------------------------------------------------------------------------------------- | The depth determines how much of the runtime structure is traversed.--- @obtainTerm@ and friends handle fetching arbitrarily nested data structures--- so we only depth enough to get to the next level of subterms.-defaultDepth :: Int-defaultDepth = 2---- | Evaluate a suspended Term to WHNF.------ Used in @'getVariables'@ to reply to a variable introspection request.-seqTerm :: HscEnv -> Term -> IO Term-seqTerm hsc_env term = do- let- interp = hscInterp hsc_env- unit_env = hsc_unit_env hsc_env- case term of- Suspension{val, ty} -> do-#if MIN_VERSION_ghc(9,15,0)- r <- GHCi.seqHValue interp unit_env (hsc_logger hsc_env) val-#else- r <- GHCi.seqHValue interp unit_env val-#endif- () <- fromEvalResult r- let- forceThunks = False {- whether to force the thunk subterms -}- forceDepth = defaultDepth- cvObtainTerm hsc_env forceDepth forceThunks ty val- NewtypeWrap{wrapped_term} -> do- wrapped_term' <- seqTerm hsc_env wrapped_term- return term{wrapped_term=wrapped_term'}- _ -> return term---- | Evaluate a Term to NF-deepseqTerm :: HscEnv -> Term -> IO Term-deepseqTerm hsc_env t = case t of- Suspension{} -> do t' <- seqTerm hsc_env t- deepseqTerm hsc_env t'- Term{subTerms} -> do subTerms' <- mapM (deepseqTerm hsc_env) subTerms- return t{subTerms = subTerms'}- NewtypeWrap{wrapped_term}- -> do wrapped_term' <- deepseqTerm hsc_env wrapped_term- return t{wrapped_term = wrapped_term'}- _ -> do seqTerm hsc_env t---logSDoc :: Logger.Severity -> SDoc -> Debugger ()-logSDoc sev doc = do- dflags <- getDynFlags- l <- asks dbgLogger- l <& DebuggerLog sev (LogSDoc dflags doc)
+ haskell-debugger/GHC/Debugger/Monad/Load.hs view
@@ -0,0 +1,322 @@+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE MultilineStrings #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE NondecreasingIndentation #-}++module GHC.Debugger.Monad.Load+where++import Control.Monad+import Control.Monad.Catch as MC+import Control.Monad.IO.Class+import Data.Function+import Data.Maybe+import qualified Data.Set as Set+import Data.Version (makeVersion)+import Prelude hiding (mod)+#ifdef MIN_VERSION_unix+#endif+import qualified Data.List as L++import GHC+import GHC.Data.StringBuffer+import GHC.Driver.Config.Diagnostic+import GHC.Driver.DynFlags as GHC+import GHC.Driver.Env as GHC+import GHC.Driver.Monad+import GHC.Driver.Errors+import GHC.Driver.Errors.Types+import GHC.Driver.Main+import GHC.Driver.Make+import GHC.Driver.Ppr+import GHC.Types.Error+import GHC.Types.SourceError+import GHC.Unit.Module.Graph+import GHC.Unit.State+import GHC.Unit.Types+import qualified GHC.Utils.Logger as GHC+import GHC.Utils.Outputable as GHC++import GHC.Debugger.Session+import GHC.Debugger.Session.Builtin++import Colog.Core as Logger++import GHC.Platform.Ways+import GHC.Debugger.Utils.Orphans () -- bring orphan instances to everything which uses `Debugger`+import GHC.Debugger.Debuggee+import GHC.Debugger.Monad.Type+import qualified GHC.Unit.Module.Graph as GHC+import GHC.Debugger.Interface.Messages (AbsFilePath, mkAbsolute, (/>))+import System.Directory (getCurrentDirectory)+++-- | Throws exception when module fails to load.+loadInternal+ :: LogAction IO DebuggerLog+ -> Ways+ -> Ghc ()+loadInternal l buildWays = do+ let ghcLog = liftLogIO l++ dflags <- getDynFlags+ addInMemoryDebuggerInternalUnit (setDynFlagWays buildWays dflags)+ let uid = debuggerInternalUnitId+ successes <- loadInMemoryModules l uid modsToLoad+ forM_ (zip successes modsToLoad) $ \case+ (Failed,(modName,_)) -> do+ ghcLog <& DebuggerLog Logger.Debug+ (LogFailedToCompileBuiltinModule modName)+ liftIO $ fail "Failed to load DebuggerInternal Module"+ (Succeeded,_) ->+ return ()+ where+ modsToLoad =+ [(debuggerRuntimeInternalModName,debuggerRuntimeInternalContents)]++#if !MIN_VERSION_ghc(9,14,2)+data FailedToLoadFFIInspectModule = FailedToLoadFFIInspectModule+ deriving Show+instance Exception FailedToLoadFFIInspectModule++-- | Throws exception when module fails to load.+-- Needed for GHC.Debugger.Runtime.Interpreter.Legacy+loadFFIInspect+ :: LogAction IO DebuggerLog+ -> Ways+ -> Ghc ()+loadFFIInspect l buildWays = do+ let ghcLog = liftLogIO l++ dflags <- getDynFlags+ uid <- addInMemoryFFIInspectUnit [baseUnitId dflags] (setDynFlagWays buildWays dflags)++ successes <- loadInMemoryModules l uid modsToLoad+ forM_ (zip successes modsToLoad) $ \case+ (Failed,(modName,_)) -> do+ ghcLog <& DebuggerLog Logger.Debug+ (LogFailedToCompileBuiltinModule modName)+ throwM FailedToLoadFFIInspectModule+ (Succeeded,_) ->+ return ()+ where+ modsToLoad =+ [(debuggerRuntimeFFIInspectModName,debuggerRuntimeFFIInspectContents)]+#endif++findOrLoadHaskellDebuggerView :: LogAction IO DebuggerLog+ -> Ways+ -> Ghc (UnitId, [ModuleName])+findOrLoadHaskellDebuggerView l buildWays = do+ let ghcLog = liftLogIO l+ hsc_env <- getSession++ -- Try to find or load the built-in classes from `haskell-debugger-view`+ findHsDebuggerViewUnitId >>= \case+ Nothing -> (hsDebuggerViewInMemoryUnitId,) <$> do+ -- Not imported by any module: no custom views. Therefore, the builtin+ -- ones haven't been loaded. In this case, we will load the package ourselves.++ -- Add the custom unit to the HUG+ let base_dep_uids = graphsUnits hsc_env+ addInMemoryHsDebuggerViewUnit base_dep_uids . setDynFlagWays buildWays =<< getDynFlags++ -- Load unit modules using in-memory contents.+ let+ -- Don't try to load instances whose packages are not even in the+ -- module graph.+ (instanceMods,skipped) = L.partition (\ (_modName,_modContent,pkgName) -> any ((pkgName `L.isPrefixOf`) . unitIdString) base_dep_uids)+ debuggerViewInstancesMods+ modsToLoad =+ (debuggerViewClassModName,debuggerViewClassContents)+ : [ (modName,modContent)+ | (modName, modContent, _pkgName) <- instanceMods]++ forM_ skipped $ \(modName,_,pkgName) ->+ ghcLog <& DebuggerLog Logger.Debug+ (LogSkippingViewModuleNoPkg modName pkgName (map unitIdString base_dep_uids))++ successes <- loadInMemoryModules l hsDebuggerViewInMemoryUnitId modsToLoad++ fmap catMaybes . forM (zip successes modsToLoad) $ \case+ (Failed,(modName,_)) -> do+ ghcLog <& DebuggerLog Logger.Debug+ (LogFailedToCompileBuiltinModule modName)+ return $ Nothing+ (Succeeded,(modName,_)) ->+ return $ Just modName++ Just uid -> do+ -- TODO: We assume for now that if you depended on+ -- @haskell-debugger-view@, then you also depend on all its transitive+ -- dependencies (containers, text, ...), thus can load all custom+ -- views. Hence all `debuggerViewBuiltinMods`. In the future, we+ -- may want to guard all dependencies behind cabal flags that the user+ -- can tweak when depending on `haskell-debugger-view`.+ return (uid, map fst debuggerViewBuiltinMods)++++--------------------------------------------------------------------------------++-- | Run downsweep on the currently set targets (see @hsc_targets@)+doDownsweep :: GhcMonad m+ => Maybe ModuleGraph -- ^ Re-use existing module graph which was already summarised+ -> m ModuleGraph -- ^ Module graph constructed from current set targets+doDownsweep reuse_mg = do+ hsc_env <- getSession+ let msg = batchMultiMsg+ (errs_base, mod_graph) <- liftIO $+ downsweep+ hsc_env mkUnknownDiagnostic (Just msg)+ (maybe [] mgModSummaries reuse_mg)+#if MIN_VERSION_ghc(10,1,0)+ reuse_mg+#endif+ [] False+ when (not $ null errs_base) $ do+ -- Print the errors to the user, rather than just throwing. When using DAP,+ -- outputting to the logger the error is what displays it in the "Debug+ -- Console" rather than "Output" DAP log.+ logger <- getLogger+ dflags <- hsc_dflags <$> getSession+ let ghc_errs = fmap GhcDriverMessage (unionManyMessages errs_base)+ liftIO $ printMessages logger (initPrintConfig dflags) (initDiagOpts dflags) ghc_errs+#if MIN_VERSION_ghc(9,15,0)+ throwErrors (initSourceErrorContext dflags) ghc_errs+#else+ throwErrors ghc_errs+#endif+ return mod_graph++doLoad :: GhcMonad m => Maybe ModIfaceCache -> LoadHowMuch -> ModuleGraph -> m SuccessFlag+doLoad if_cache how_much mg = do+ let msg = batchMultiMsg+ load' if_cache how_much mkUnknownDiagnostic (Just msg) mg+++loadInMemoryModules ::+ LogAction IO DebuggerLog+ -> UnitId+ -> [(ModuleName,StringBuffer)] -> Ghc [SuccessFlag]+loadInMemoryModules l uid ts = do+ tgts <- forM ts $ \(modName,modContents) ->+ liftIO $ makeInMemoryTarget uid modName modContents+ GHC.setTargets tgts+ mod_graph <- hsc_mod_graph <$> GHC.getSession+ dvc_mod_graph <- doDownsweep (Just mod_graph)+ let new_mod_graph+#if MIN_VERSION_ghc(10,1,0)+ -- new API allows extending an existing graph.+ = dvc_mod_graph+#else+ = mkModuleGraph $ mg_mss dvc_mod_graph ++ mg_mss mod_graph+#endif+ modifySession $ GHC.setModuleGraph new_mod_graph++ restore_logger <- GHC.getLogger+ dflags <- getSessionDynFlags+ GHC.modifyLogger $+ -- Emit it all as Debug-level debugger logs+ GHC.pushLogHook $ const $ \_ _ _ sdoc ->+ l <& DebuggerLog Logger.Debug (LogSDoc dflags sdoc)++ -- Might not make sense to keep going if the first fails, but we expect all of+ -- them to succeed, and it's not that many more modules.+ s <- forM tgts $ \ tgt -> compileModuleWithDepsInHpt tgt >>= \case+ Nothing -> pure Succeeded+ Just e -> do+ liftLogIO l <& DebuggerLog Logger.Debug (LogSDoc dflags $ text (show e))+ pure Failed++ -- Restore logger+ GHC.modifyLogger $+ GHC.pushLogHook (const $ GHC.putLogMsg restore_logger)++ return s++--------------------------------------------------------------------------------+-- * Finding Debugger View+--------------------------------------------------------------------------------++-- | Try to find the @haskell-debugger-view@ unit-id in the transitive closure,+-- or, otherwise, return the a custom unit for which we'll load the+-- @haskell-debugger-view@ modules in it (essentially preparing an in-memory+-- version of the library to find the built-in instances in).+--+-- See also comment on the @'hsDbgViewUnitId'@ field of @'DebuggerState'@+findHsDebuggerViewUnitId :: GHC.Ghc (Maybe UnitId)+findHsDebuggerViewUnitId = do+ hsc_env <- getSession+ let unitState = hsc_units hsc_env++ -- Note: linear in the module graph but only happens once.+ let potential_units = graphsUnits hsc_env+ -- Note: the intermediate set is expected to be small (<= 2).+ let hskl_dbgr_vws = Set.toList . Set.fromList $+ [ uid+ | uid <- potential_units+ , let uid_s = unitIdString uid+ , "haskell-debugger-view" `L.isPrefixOf` uid_s+ || "hskll-dbggr-vw" `L.isPrefixOf` uid_s+ || "haskell-debug_" `L.isPrefixOf` uid_s+ ]++ -- If the haskell-debugger-view is in the dependency graph, it must have+ -- one of the versions the debugger is known to support:+ supported_ranges -- [min, max(+ = [ (makeVersion [0, 2], makeVersion [0, 3]) ]++ case hskl_dbgr_vws of+ [hdv_uid] -> do+ -- In transitive closure, use that one.+ -- Check that the version is in supported range.+ case lookupUnit unitState (RealUnit (Definite hdv_uid)) of+ Just unitInfo -> do+ let version = unitPackageVersion unitInfo+ if any (\(l,h) -> l <= version && version < h) supported_ranges+ then return (Just hdv_uid)+ else throwM UnsupportedHsDbgViewVersion{supportedVersions=supported_ranges, actualVersion=version}+ Nothing+ | "inplace" `L.isSuffixOf` unitIdString hdv_uid+ -- will be built as a target later+ -> return (Just hdv_uid)+ Nothing ->+ error "Could not find unit info for haskell-debugger-view"+ [] -> do+ return Nothing+ _ -> do+ error $ "Multiple unit-ids found for haskell-debugger-view in the transitive closure?!" ++ showSDocUnsafe (withPprStyle (PprDump alwaysQualify) (ppr hskl_dbgr_vws))++--------------------------------------------------------------------------------+-- * Modules+--------------------------------------------------------------------------------++-- | List all loaded modules 'ModSummary's+getAllLoadedModules :: GHC.GhcMonad m => m [GHC.ModuleNodeInfo]+getAllLoadedModules =+ (mgInfos . mg_mss <$> GHC.getModuleGraph) >>=+ filterM (\ms -> GHC.isLoadedModule (moduleNodeInfoUnitId ms) (moduleNodeInfoModuleName ms))+ where+ mgInfos xs = [ info | ModuleNode _ info <- xs ]++getAllLoadedModulesWithPaths :: GHC.GhcMonad m =>+ m [(AbsFilePath,GHC.ModuleNodeInfo)]+getAllLoadedModulesWithPaths = do+ ghcCwd <- mkAbsolute <$> liftIO getCurrentDirectory+ -- TODO: cache?+ map (\ m -> (absoluteSourcePath ghcCwd m, m)) <$> getAllLoadedModules+ where+ absoluteSourcePath :: AbsFilePath -> ModuleNodeInfo -> AbsFilePath+ absoluteSourcePath ghcCwdDir ms+ = ghcCwdDir /> (fromMaybe (error $ "missing source path: " ++ show (moduleNodeInfoModuleName ms)) $ ml_hs_file (moduleNodeInfoLocation ms))
+ haskell-debugger/GHC/Debugger/Monad/Type.hs view
@@ -0,0 +1,274 @@+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE ViewPatterns #-}+{-# LANGUAGE MultilineStrings #-}+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE NondecreasingIndentation #-}++module GHC.Debugger.Monad.Type where++import Control.Concurrent+import Control.Exception+import Control.Monad+import Control.Monad.Catch as MC+import Control.Monad.IO.Class+import Control.Monad.Reader+import Data.Function+import Data.IORef+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IM+import Data.Maybe+import Data.Version (showVersion)+import Prelude hiding (mod)+import qualified Data.List as L++import GHC+import GHC.Driver.DynFlags as GHC+import GHC.Driver.Env+import GHC.Runtime.Context+import GHC.Types.Error+import GHC.Unit.State+import GHC.Unit.Types+import qualified GHC.Utils.Logger as GHC+import GHC.Utils.Outputable as GHC++import GHC.Debugger.Interface.Messages+import GHC.Debugger.Runtime.Compile.Cache+import qualified GHC.Debugger.Data.BreakpointMap as BM+import qualified GHC.Debugger.Data.ThreadMap as TM++import Colog.Core as Logger++import {-# SOURCE #-} GHC.Debugger.Runtime.Instances.Discover (RuntimeInstancesCache, emptyRuntimeInstancesCache)+import GHC.Debugger.Utils.Orphans () -- bring orphan instances to everything which uses `Debugger`+import GHC.Debugger.Debuggee+import GHCi.RemoteTypes++-- | A debugger action.+newtype Debugger a = Debugger { unDebugger :: ReaderT DebuggerState GHC.Ghc a }+ deriving ( Functor, Applicative, Monad, MonadIO+ , MonadThrow, MonadCatch, MonadMask+ , GHC.HasDynFlags, MonadReader DebuggerState )++data BreakpointInfo = BreakpointInfo+ { bpInfoStatus :: !BreakpointStatus+ , bpInfoKind :: !BreakpointKind+ , bpInfoAction :: !BreakpointAction+ }+ deriving (Eq,Show)++-- | Identifies a given state of the 'globalIC' imports.+--+-- We do not want to call 'setContext' more than necessary, so we tag stored+-- 'InteractiveContext's with the ImportsEpoch of the global scope they were based on.+type ImportsEpoch = Int++data StoppedThread = StoppedThread+ { resume :: !Resume+ , breakIC :: !InteractiveContext+ -- ^ InteractiveContext captured at the time of pushResume.+ , frameICs :: !(IntMap (InteractiveContext,(ImportsEpoch,Maybe Module)))+ -- ^ Current InteractiveContext per frame index, stored alongside @Resume@+ -- so they get dropped at the same time. The @Maybe Module@ is the source+ -- module of the frame breakpoint, if any.+ }+++mkStoppedThread :: Resume -> InteractiveContext -> StoppedThread+mkStoppedThread resume ic = StoppedThread{ frameICs = IM.empty, breakIC = ic{ic_resume = []}+ , .. }+++-- | State required to run the debugger.+--+-- - Keep track of active breakpoints to easily unset them all.+data DebuggerState = DebuggerState+ { activeBreakpoints :: IORef (BM.BreakpointMap BreakpointInfo)+ -- ^ Maps a 'InternalBreakpointId' in Trie representation (map of Module to map of Int) to the+ -- 'BreakpointStatus' it was activated with.++ , rtinstancesCache :: IORef RuntimeInstancesCache+ -- ^ RuntimeInstancesCache++ , threadMap :: IORef (TM.ThreadMap (ForeignRef ThreadId))+ -- ^ 'ThreadMap' for threads spawned by the debuggee++ , threadResumeMap :: IORef (TM.ThreadMap StoppedThread)+ -- ^ If a thread is currently stopped on a breakpoint, this map will+ -- contain its resume context (from which we can resume the thread),+ -- also contains frame specific 'InteractiveContext's, created as needed.++ , globalIC :: IORef (InteractiveContext,Int)+ -- ^ 'InteractiveContext' for DoEval without a specified frame. Its+ -- `ic_imports` are imported into the frame specific+ -- 'InteractiveContext's.++ , compCache :: IORef CompCache+ -- ^ Cache loaded and compiled expressions.++ , hsDbgViewUnitId :: Maybe UnitId+ -- ^ The unit-id of the companion @haskell-debugger-view@ unit, used for+ -- user-defined and built-in custom debug visualisations of values (e.g.+ -- for Strings or IntMap).+ --+ -- If the user depends on @haskell-debugger-view@ in its transitive+ -- closure, then we should use that exact unit which was solved by Cabal.+ -- The built-in instances and additional instances be available for the+ -- 'DebugView' class found in that unit. We can find the exact unit of+ -- the module by looking for @haskell-debugger-view@ in the module graph.+ --+ -- If the user does not depend on @haskell-debugger-view@ in any way,+ -- then we create our own unit and try to load the+ -- @haskell-debugger-view@ modules directly into it. As long as loading+ -- succeeds, the 'DebugView' class from this custom unit can be used to+ -- find the built-in instances for types like @'String'@+ --+ -- If the user explicitly disabled custom views, use @Nothing@.++ , dbgLogger :: LogAction IO DebuggerLog+ -- ^ See Note [Debugger, debuggee, and DAP logs]+ }++instance GHC.HasLogger Debugger where+ getLogger = liftGhc GHC.getLogger++instance GHC.GhcMonad Debugger where+ getSession = liftGhc GHC.getSession+ setSession s = liftGhc $ GHC.setSession s++-- | Enabling/Disabling a breakpoint+data BreakpointStatus+ -- | Breakpoint is disabled+ --+ -- Note: this must be the first constructor s.t.+ -- @BreakpointDisabled < {BreakpointEnabled, BreakpointAfterCount}@+ = BreakpointDisabled+ -- | Breakpoint is enabled+ | BreakpointEnabled+ -- | Breakpoint is disabled the first N times and enabled afterwards+ | BreakpointAfterCount Int+ -- | Breakpoint is enabled when condition evaluates to true+ | BreakpointWhenCond String+ -- | Breakpoint is disabled the first N times the condition evaluates to+ -- true and enabled in the next time it is true+ | BreakpointAfterCountCond Int String+ deriving (Eq, Ord, Show)++instance Outputable BreakpointStatus where ppr = text . show++-- | What to do when a breakpoint is enabled+data BreakpointAction+ -- | Evaluation is stopped, typical behaviour+ = BreakpointStop+ {- | A log message is printed and then evaluation resumes.+ The @String@ is an expression that takes care of interpolation and printing the log message.+ -}+ | BreakpointLogAndResume String+ deriving (Eq, Ord, Show)++instance Outputable BreakpointAction where ppr = text . show++--------------------------------------------------------------------------------+-- Runner Types+--------------------------------------------------------------------------------++-- | Additional settings configuring the debugger+data RunDebuggerSettings = RunDebuggerSettings+ { supportsANSIStyling :: Bool+ , supportsANSIHyperlinks :: Bool+ , interpreterSettings :: InterpreterSettings+ }++type DebugSession m a+ = FilePath -- ^ project root dir+ -> [String] -- ^ extra ghc args+ -> m () -- ^ action to load debugee home units+ -> Ghc a++type DebugRunner m a = DebugSession m a -> IO a++data ProjectDebugSpec = ProjectDebugSpec+ { rootDir :: FilePath+ -- ^ Project root directory+ , componentDir :: FilePath+ -- ^ Root dir of the loaded 'ComponentOptions'.+ -- Important for multi-package cabal projects, as packages are not in the+ -- root of the cradle, but in some sub-directory.+ , libdir :: FilePath+ -- ^ The libdir (given with -B as an arg)+ , units :: [String]+ -- ^ The list of units included in the invocation+ , ghcInvocation :: [String]+ -- ^ The full ghc invocation (as constructed by hie-bios flags)+ , absEntryFile :: FilePath+ -- ^ Path to the main function+ , extraGhcArgs :: [String]+ }++--------------------------------------------------------------------------------+-- Utilities+--------------------------------------------------------------------------------++-- | Initialize a 'DebuggerState'+initialDebuggerState :: LogAction IO DebuggerLog -> Maybe UnitId -> GHC.Ghc DebuggerState+initialDebuggerState l hsDbgViewUid = do+ ic <- hsc_IC <$> getSession+ DebuggerState <$> liftIO (newIORef BM.empty)+ <*> liftIO (newIORef emptyRuntimeInstancesCache)+ <*> liftIO (newIORef TM.emptyThreadMap)+ <*> liftIO (newIORef TM.emptyThreadMap)+ <*> liftIO (newIORef (ic,0))+ <*> liftIO (newIORef emptyCompCache)+ <*> pure hsDbgViewUid+ <*> pure l++-- | Fetch the @haskell-debugger-view@ unit-id from the environment.+-- @Nothing@ means custom debugger views are disabled.+getHsDebuggerViewUid :: Debugger (Maybe UnitId)+getHsDebuggerViewUid = asks hsDbgViewUnitId++-- | Lift a 'Ghc' action into a 'Debugger' one.+liftGhc :: GHC.Ghc a -> Debugger a+liftGhc = Debugger . ReaderT . const++data DebuggerFailedToLoad = DebuggerFailedToLoad+instance Exception DebuggerFailedToLoad+instance Show DebuggerFailedToLoad where+ show DebuggerFailedToLoad = "Failed to compile and load user project."++data UnsupportedHsDbgViewVersion = UnsupportedHsDbgViewVersion+ { supportedVersions :: [ (Version, Version) ]+ , actualVersion :: Version+ }+instance Exception UnsupportedHsDbgViewVersion+instance Show UnsupportedHsDbgViewVersion where+ show (UnsupportedHsDbgViewVersion supported actual) =+ "Cannot use unsupported haskell-debugger-view version found in the transitive closure: " ++ showVersion actual +++ " (supported: " ++ L.intercalate ", " (map (\(l,h) -> showVersion l ++ " <= && < " ++ showVersion h) supported) ++ ")"++data NonFatalException = NonFatalException { userMessage :: String, debugMessage :: String }+ deriving Show++instance Exception NonFatalException++expectRight :: Exception e => Either e a -> Debugger a+expectRight s = case s of+ Left e -> do+ logSDoc Logger.Error (text $ displayException e)+ liftIO $ throwIO $ NonFatalException { userMessage = displayException e, debugMessage = displayExceptionWithInfo $ toException e }+ Right a -> do+ pure a++logSDoc :: Logger.Severity -> SDoc -> Debugger ()+logSDoc sev doc = do+ dflags <- getDynFlags+ l <- asks dbgLogger+ liftLogIO l <& DebuggerLog sev (LogSDoc dflags doc)
haskell-debugger/GHC/Debugger/Run.hs view
@@ -9,59 +9,50 @@ {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ViewPatterns #-}-module GHC.Debugger.Run where +-- | Start debugging a program, evaluate statements, and resume stopped threads.+module GHC.Debugger.Run+ (+ -- * Start debugging a program+ debugExecution++ -- * Resume stopped program+ , doResume++ -- * Interactive evaluation+ , doEvalCommand+ ) where+ import GHC.Utils.Outputable-import Control.Monad.IO.Class-import Control.Monad.Catch-import Control.Monad.Reader-import Data.IORef import Data.Maybe import GHC qualified import GHC (- ExecOptions (..),- ExecResult (..),- execStmt', ForeignHValue,- GhciLStmt,- GhcPs, InteractiveImport (..),- ModSummary (..),- Name,- parseImportDecl,- SingleStep (..),- SrcSpan (..),- StmtLR (..),- unLoc, mkHsString, nlList, nlHsLit, )-import GHC.Plugins (SourceError) import qualified GHC.Plugins as GHC import GHC.Unit.Types-import GHC.Driver.DynFlags as GHC-import GHC.Driver.Main (hscParseStmtWithLocation) import GHC.Driver.Monad as GHC-import GHC.Driver.Env as GHC-import qualified GHC.Driver.Config.Parser as GHC-import GHC.Runtime.Debugger.Breakpoints as GHC import qualified GHCi.Message as GHCi-import qualified GHC.Data.Strict as Strict -import GHC.Debugger.Stopped.Variables import GHC.Debugger.Monad-import GHC.Debugger.Utils import GHC.Debugger.Interface.Messages import Colog.Core as Logger-import qualified GHC.Debugger.Breakpoint.Map as BM-import GHC.Debugger.Runtime.Thread-import GHC.Debugger.Session (setInteractiveDebuggerDynFlags, getInteractiveDebuggerDynFlags, resumeExec)+import GHC.Debugger.Runtime.Thread.Resume+import GHC.Debugger.Session (getInteractiveDebuggerDynFlags) import Data.List (find) import GHC.Unit.Module.Graph as GHC import GHC.Debugger.Session.Builtin (runInternal, debuggerRuntimeInternalModName)+import GHC.Runtime.Eval.Types +import GHC.Debugger.Run.Resume+import GHC.Debugger.Run.Handler+import GHC.Driver.Config.Parser+import GHC.Debugger.Run.Eval -------------------------------------------------------------------------------- -- * Evaluation@@ -104,6 +95,9 @@ logSDoc Logger.Debug "Compiled wrapper." exec_res <- GHC.execStmt entryExp exOpts+#ifdef GHC_HAS_MULTITHREADED_DBG+ { execIsolateMode = GHC.MultiThreadedBreaks } -- yeah!+#endif logSDoc Logger.Debug $ "Executed entryExp: " <+> text entryExp @@ -124,7 +118,7 @@ `GHC.mkHsApp` nlList (map nlHsString args') where nlHsString = nlHsLit . mkHsString- evalWrapper' :: GHC.LHsExpr GhcPs+ evalWrapper' :: GHC.LHsExpr GHC.GhcPs evalWrapper' = GHC.nlHsVar $ GHC.mkRdrQual debuggerRuntimeInternalModName (GHC.mkVarOcc "evalWrapper") @@ -137,225 +131,28 @@ error $ "findUnitIdOfEntryFile: no unit id found for: " ++ unAbs afp ++ "\nCandidates were:\n" ++ unlines (map show norms) Just (_,summary) -> pure summary --- | Resume execution of the stopped debuggee program-doContinue :: Debugger EvalResult-doContinue = do- resumeExec RunToCompletion Nothing- >>= handleExecResult---- | Resume execution but only take a single step.-doSingleStep :: Debugger EvalResult-doSingleStep = do- resumeExec SingleStep Nothing+doResume :: RemoteThreadId -> ResumeStep -> ResumeTheWorld -> Debugger EvalResult+doResume tid step _stop_world = do+ resume <- popResume tid+ ss <- resolveResumeStep resume step+ -- TODO: stop_world toggles global hit breakpoints mode (todo: look at mode+ -- to determine how to stop) and here run all the threads accordingly.+ -- TODO: for the first iteration, simply call pause on all threads (except+ -- for those with specific debugger labels); but pause will only set step_in,+ -- and won't be able to pause compiled threads, but that is follow up work.+ resumeExec ss Nothing resume >>= handleExecResult -doStepOut :: Debugger EvalResult-doStepOut = do- mb_span <- getCurrentBreakSpan- case mb_span of- Nothing ->- resumeExec (GHC.StepOut Nothing) Nothing- >>= handleExecResult- Just loc -> do- md <- fromMaybe (error "doStepOut") <$> getCurrentBreakModule- ticks <- fromMaybe (error "doLocalStep:getTicks") <$> makeModuleLineMap md- let current_toplevel_decl = enclosingTickSpan ticks loc- resumeExec (GHC.StepOut (Just (RealSrcSpan current_toplevel_decl Strict.Nothing))) Nothing- >>= handleExecResult---- | Resume execution but stop at the next tick within the same function.------ To do a local step, we get the SrcSpan of the current suspension state and--- get its 'enclosingTickSpan' to use as a filter for breakpoints in the call--- to 'resumeExec'. Execution will only stop at breakpoints whose span matches--- this enclosing span.-doLocalStep :: Debugger EvalResult-doLocalStep = do- mb_span <- getCurrentBreakSpan- case mb_span of- Nothing -> error "not stopped at a breakpoint?!"- Just (UnhelpfulSpan _) -> do- liftIO $ putStrLn "Stopped at an exception. Forcing step into..."- resumeExec SingleStep Nothing >>= handleExecResult- Just loc -> do- md <- fromMaybe (error "doLocalStep") <$> getCurrentBreakModule- -- TODO: Cache moduleLineMap?- ticks <- fromMaybe (error "doLocalStep:getTicks") <$> makeModuleLineMap md- let current_toplevel_decl = enclosingTickSpan ticks loc- resumeExec (LocalStep (RealSrcSpan current_toplevel_decl mempty)) Nothing >>= handleExecResult- -- | Generalized `doEval` that also handles `imports`-doEvalCommand :: String -> Debugger EvalResult-doEvalCommand expr = do+doEvalCommand :: Maybe (RemoteThreadId, Int)+ -- ^ If Just, evaluate the expression in a context where the variables+ -- from the given thread at frame index are available.+ -- If Nothing, it evaluates in the stored globalIC.+ -> String+ -> Debugger EvalResult+doEvalCommand mtid expr = do dflags <- getInteractiveDebuggerDynFlags- let pflags = GHC.initParserOpts dflags+ let pflags = initParserOpts dflags if GHC.isStmt pflags expr- then doEval expr+ then doEval handleExecResult mtid expr else addImport expr---- | Parses input as an import declaration and applies it to the interactive context.-addImport :: String -> Debugger EvalResult-addImport s = handleError $ do- cxt <- GHC.getContext- idecl <- parseImportDecl s- GHC.setContext $ IIDecl idecl : cxt- pure $ EvalCompleted "" "" Nothing NoVariables- where- handleError m = m `catch` \ (e::SourceError) -> do- pure $ EvalAbortedWith $ displayException e---- | Evaluate expression. Includes context of breakpoint if stopped at one (the current interactive context).-doEval :: String -> Debugger EvalResult-doEval expr = withCurrentBreakEnv $ do- excr <- (Right <$> exec expr GHC.execOptions) `catch` \(e::SomeException) -> pure (Left (displayException e))- case excr of- Left err -> pure $ EvalAbortedWith err- Right (k, ExecBreak{}) -> fmap (addSourceKind k) $ continueToCompletion >>= handleExecResult- Right (k, r@ExecComplete{}) -> fmap (addSourceKind k) $ handleExecResult r- where- exec input exec_opts@ExecOptions{..} = do- hsc_env <- getSession-- mb_stmt <-- liftIO $- runInteractiveHsc hsc_env $- hscParseStmtWithLocation execSourceFile execLineNumber input-- case mb_stmt of- -- empty statement / comment- Nothing -> return (IsStmt, ExecComplete (Right []) 0)- Just stmt -> (,) <$> stmtKind stmt <*> execStmt' stmt input exec_opts-- stmtKind (stmt :: GhciLStmt GhcPs) = do- pure $ case unLoc stmt of- BodyStmt{} -> IsExpr- _ -> IsStmt-- addSourceKind :: SourceKind -> EvalResult -> EvalResult- addSourceKind k EvalCompleted{..} = EvalCompleted{resultSourceKind = Just k, ..}- addSourceKind _ r = r---- | Resume execution with single step mode 'RunToCompletion', skipping all breakpoints we hit, until we reach 'ExecComplete'.------ We use this in 'doEval' because we want to ignore breakpoints in expressions given at the prompt.-continueToCompletion :: Debugger GHC.ExecResult-continueToCompletion = do- execr <- resumeExec GHC.RunToCompletion Nothing- case execr of- GHC.ExecBreak{} -> continueToCompletion- GHC.ExecComplete{} -> return execr---- | @withCurrentBreakEnv m@ executes @m@ with the imports, language, and language--- extensions of the current breakpoint source module.------ If we are not stopped at a breakpoint @m@ is executed with no change.-withCurrentBreakEnv :: Debugger a -> Debugger a-withCurrentBreakEnv m = do- mmodl <- getCurrentBreakModule- case mmodl of- Nothing -> m- Just breakModule -> do- ic_dyn_flags <- getInteractiveDebuggerDynFlags- break_dyn_flags <- ms_hspp_opts <$> GHC.getModSummary breakModule- old_context <- GHC.getContext- setInteractiveDebuggerDynFlags $ adjustFlags ic_dyn_flags break_dyn_flags- GHC.setContext (IIModule breakModule : old_context)- x <- m- GHC.setContext old_context- setInteractiveDebuggerDynFlags ic_dyn_flags- return x- where- -- Possibly we might want to include more from the module's DynFlags.- -- However some are likely to mess with the REPL, e.g. Opt_WarnTypeDefaults,- -- Opt_HideAllPackages, Opt_NoIt. See discussion at- -- https://github.com/well-typed/haskell-debugger/pull/230#discussion_r2986758826- adjustFlags :: DynFlags -> DynFlags -> DynFlags- adjustFlags ic modl = ic- { extensions = extensions modl- , extensionFlags = extensionFlags modl- , language = language modl- }---- | Turn a GHC's 'ExecResult' into an 'EvalResult' response-handleExecResult :: GHC.ExecResult -> Debugger EvalResult-handleExecResult = \case- ExecComplete {execResult} -> do- case execResult of- Left e -> return (EvalException (show e) "SomeException")- Right [] -> return (EvalCompleted "" "" Nothing NoVariables) -- Evaluation completed without binding any result.- Right (n:_ns) -> inspectName n >>= \case- Just VarInfo{varValue, varType, varRef} -> do- return (EvalCompleted varValue varType Nothing varRef)- Nothing -> liftIO $ fail "doEval failed"- ExecBreak {breakNames = _, breakPointId = Nothing} -> do- -- Stopped at an exception- -- TODO: force the exception to display string with Backtrace?- rt_id <- getRemoteThreadIdFromContext- return EvalStopped{ breakId = Nothing- , breakThread = rt_id }- ExecBreak {breakNames = _, breakPointId = Just bid} -> do- let performAction BreakpointStop = do-- rt_id <- getRemoteThreadIdFromContext- return EvalStopped{ breakId = Just bid- , breakThread = rt_id }- performAction (BreakpointLogAndResume logExpr) = do- let evalFailedMsg e = text $ unlines ["Evaluation of log message expression failed with " ++ e- , "Expr: " ++ logExpr- , "Ignoring..."]- doEval' logExpr evalFailedMsg $ \ _ _ -> resume-- bm <- liftIO . readIORef =<< asks activeBreakpoints- case BM.lookup bid bm of- -- When stepping (`GHC.resumeExec SingleStep` or similar), we will typically stop at locations not explicitly enabled by the user (i.e. not registered in `activeBreakpoints`).- Nothing -> performAction BreakpointStop- Just BreakpointInfo{bpInfoStatus = status, bpInfoAction = action} -> do- case status of- -- todo: BreakpointAfterCountCond is not handled yet.- BreakpointAfterCountCond{} -> performAction action- BreakpointWhenCond cond -> do- let evalFailedMsg e = text $ "Evaluation of conditional breakpoint expression failed with " ++ e ++ "\nIgnoring..."-- doEval' cond evalFailedMsg $ \ resultVal resultType -> do- if resultType == "Bool" then do- if resultVal == "True" then do- performAction action- else- resume- else do- logSDoc Logger.Warning (evalFailedMsg "\"expression resultType is != Bool\"")- resume- BreakpointDisabled -> resume- -- The counting is handled by @GHC.setupBreakpoint@- BreakpointAfterCount _ -> performAction action- BreakpointEnabled -> performAction action- where- doEval' expr evalFailedMsg k = doEval expr >>= \case- EvalStopped{} -> error "impossible for doEval"- EvalCompleted { resultVal, resultType } ->- k resultVal resultType- EvalException { resultVal } -> do- logSDoc Logger.Warning (evalFailedMsg resultVal)- resume- EvalAbortedWith e -> do- logSDoc Logger.Warning (evalFailedMsg e)- resume- resume = resumeExec GHC.RunToCompletion Nothing >>= handleExecResult---- | Get the value and type of a given 'Name' as rendered strings in 'VarInfo'.-inspectName :: Name -> Debugger (Maybe VarInfo)-inspectName n = do- GHC.lookupName n >>= \case- Nothing -> do- liftIO . putStrLn =<< display (text "Failed to lookup name: " <+> ppr n)- pure Nothing- Just tt -> Just <$> do- fam_envs <- getFamInstEnvs'- tyThingToVarInfo fam_envs tt--getRemoteThreadIdFromContext :: Debugger RemoteThreadId-getRemoteThreadIdFromContext = do- GHC.getResumeContext >>= \case- resume1:_ ->- getRemoteThreadIdFromRemoteContext $ GHC.resumeContext resume1- _ -> error "No resumes but stopped?!?"
+ haskell-debugger/GHC/Debugger/Run/Eval.hs view
@@ -0,0 +1,292 @@+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE LambdaCase #-}+{-# OPTIONS_GHC -Wno-unused-matches #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE DerivingVia #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE GADTs #-}++-- | Evaluating string-expressions in the context of the source program.+-- This is what is used to evaluate expressions at the REPL while stopped.+--+-- In contrast, @GHC.Debugger.Runtime.Eval@ is for evaluating any and all+-- expressions in the (external) interpreter for the debugger purposes (rather+-- than directly the user's).+module GHC.Debugger.Run.Eval+ ( doEval, addImport+ ) where+import GHC.Debugger.Interface.Messages+import GHC.Debugger.Monad+import GHC.Debugger.Session+import GHC.Debugger.Runtime.Thread.Resume+import GHC.Debugger.Run.Resume+import Control.Exception+import GHC.Runtime.Eval hiding (resumeExec)+import GHC.Hs+import GHC.Driver.Session+import GHC.Runtime.Context+import qualified GHC+import GHC.Unit.Module.ModSummary+import GHC.ByteCode.Breakpoints+import GHC.Driver.Monad+import Control.Monad+import GHC.Driver.Env+import GHC.Driver.Main+import GHC.Types.SrcLoc+import Control.Monad.Catch as MC+import Data.Function+import GHC.Debugger.Utils+import GHC.Debugger.Stopped+import GHC.Debugger.Stopped.Frames+import GHC (TyThing (AnId))+import GHC.Debugger.Data.ThreadMap+import Data.IORef+import Control.Monad.Reader+import qualified Data.IntMap.Strict as IM+import Colog.Core+import Data.List+import GHC.Types.DefaultEnv+import GHC.Core.InstEnv (emptyInstEnv)+import GHC.Types.SourceError+import GHC.TypeLits (Symbol)+import Data.Kind (Type)+import GHC.Unit++-- | Parses input as an import declaration and applies it to the global interactive context.+addImport :: String -> Debugger EvalResult+addImport s = handleError $ withGlobalIC $ do+ idecl <- lift $ parseImportDecl s+ imports <- getGlobalImports+ -- frame evaluation scopes will update their imports to match these when needed.+ setGlobalImports (IIDecl idecl : imports)+ pure $ EvalCompleted "" "" Nothing NoVariables+ where+ handleError m = m `MC.catch` \ (e::SourceError) -> do+ pure $ EvalAbortedWith $ displayException e++-- | Evaluate expression including the interactive context at the breakpoint+-- the given thread is currently stopped at. If the thread is not stopped, the+-- expression is evaluated in the global context.+doEval :: (ExecResult -> Debugger EvalResult)+ -- ^ How to handle a result from evaluation.+ -- Typically this is 'GHC.Debugger.Run.Handler.handleExecResult'.+ -> Maybe (RemoteThreadId, Int)+ -> String+ -> Debugger EvalResult+doEval handleExecResult scope expr = withThreadBreakEnv scope $ do+ excr <- (Right <$> exec expr execOptions) `MC.catch` \(e::SomeException) -> pure (Left (displayException e))+ case excr of+ Left err -> pure $ EvalAbortedWith err+ Right (k, br@ExecBreak{}) -> fmap (addSourceKind k) $ execBreakResume br >>= continueToCompletion >>= handleExecResult+ Right (k, r@ExecComplete{}) -> fmap (addSourceKind k) $ handleExecResult r+ where+ exec :: String -> ExecOptions -> Debugger (SourceKind, ExecResult)+ exec input exec_opts@ExecOptions{..} = do+ hsc_env <- getSession++ mb_stmt <-+ liftIO $+ runInteractiveHsc hsc_env $+ hscParseStmtWithLocation execSourceFile execLineNumber input++ case mb_stmt of+ -- empty statement / comment+ Nothing -> return (IsStmt, ExecComplete (Right []) 0)+ Just stmt -> (,) <$> stmtKind stmt <*> execStmt' stmt input exec_opts++ stmtKind (stmt :: GhciLStmt GhcPs) = do+ pure $ case unLoc stmt of+ BodyStmt{} -> IsExpr+ _ -> IsStmt++ addSourceKind :: SourceKind -> EvalResult -> EvalResult+ addSourceKind k EvalCompleted{..} = EvalCompleted{resultSourceKind = Just k, ..}+ addSourceKind _ r = r++-- | Pre-condition: inner action does not alter imports.+withThreadBreakEnv :: Maybe (RemoteThreadId, Int) -> Debugger a -> Debugger a+withThreadBreakEnv Nothing m = withGlobalIC $ lift $ do+ x <- m+ ic <- hsc_IC <$> getSession+ (_,gen) <- getGlobalIC+ setGlobalIC (ic,gen)+ pure x+withThreadBreakEnv q@(Just (tid, frame_index)) m = do+ let debugLog (d :: SDoc) = logSDoc Debug (text $ intercalate " " $ lines $ showPprUnsafe $ text "withThreadBreakEnv:" <+> d)+ debugLog (text (show q))+ readStoppedThread tid >>= \case+ Nothing -> do+ throwM $ NonFatalException { userMessage = "Evaluation only supported in stopped threads.", debugMessage = "withThreadBreakEnv: " ++ show q}+ Just st -> do+ debugLog (text "found st")+ withTempInteractiveContext (Frame tid frame_index) $ do+ persistThisFrameIC <- setICOfFrame tid frame_index st++ x <- lift m++ -- persists any additions by `m`, e.g. `it`.+ persistThisFrameIC++ pure x++--------------------------------------------------------------+-- * ScopeT+--------------------------------------------------------------++data Scope :: Symbol -> Type where+ Global :: Scope "global"+ Frame :: RemoteThreadId -> Int -> Scope "frame"++-- | Keeps track of which "scope" we are evaluating in.+--+-- If it's a "frame" scope we assume the thread is stopped.+newtype ScopeT (s :: Symbol) (m :: Type -> Type) a = ScopeT {unsafeUnScopeT :: Scope s -> m a}+ deriving (Functor, Applicative, Monad, MonadIO, MonadReader (Scope s)) via ReaderT (Scope s) m+ deriving MonadTrans via ReaderT (Scope s)++getGlobalImports :: ScopeT "global" Debugger [InteractiveImport]+getGlobalImports = ic_imports . hsc_IC <$> lift getSession++setGlobalImports :: [InteractiveImport] -> ScopeT "global" Debugger ()+setGlobalImports imports = lift $ do+ (gic,gen) <- getGlobalIC+ GHC.setContext imports+ -- we write only here so we know setContext with the extra argument works.+ new_gic <- hsc_IC <$> getSession+ setGlobalIC (new_gic,gen+1)++withGlobalIC :: ScopeT "global" Debugger a -> Debugger a+withGlobalIC m = withTempInteractiveContext Global $ do+ (gic,_) <- lift getGlobalIC+ lift $ modifySession (\ s -> s {hsc_IC = gic})+ m++setICOfFrame :: RemoteThreadId -> Int -> StoppedThread -> ScopeT "frame" Debugger (ScopeT "frame" Debugger ())+setICOfFrame tid frame_index StoppedThread{..}+ | Just (ic,(gen,extra)) <- IM.lookup frame_index frameICs+ = do+ lift $ modifySession (\ s -> s {hsc_IC = ic})+ refreshImports (Just gen) extra+ | otherwise = do+ let warn (d :: SDoc) = logSDoc Colog.Core.Warning (text "Evaluating in " <+> text (show (tid,frame_index)) <+> text ":" <+> d)+ hug <- hsc_HUG <$> lift getSession+ mibi <- lift $ do+ if frame_index == 0 then do+ modifySession (\ s -> s {hsc_IC = breakIC})+ -- resume is only relevant for frame_index == 0.+ mibi <- case resumeBreakpointId resume of+ Just ibi -> pure (Just ibi)+ Nothing -> ((.breakId) =<<) <$> getStackFrame tid frame_index+ pure mibi+ else do+ getStackFrame tid frame_index >>= \case+ Nothing -> do+ warn $ text "Could not retrieve stack frame, no bindings added to the scope."+ pure Nothing+ Just fr -> do+ addBindingsIfNew . map AnId =<< getStackFrameBindings fr+ pure fr.breakId+ case mibi of+ Nothing -> do+ lift $ warn $ text "Could not retrieve breakpoint id, no break module added to the scope."+ refreshImports Nothing Nothing+ Just ibi -> do+ breakModule <- getBreakSourceMod ibi <$> readIModBreaks hug ibi & liftIO+ lift $ addModuleDynFlags breakModule+ refreshImports Nothing (Just breakModule)+ where+ addBindingsIfNew tythings = do+ s <- getSession+ let ic = hsc_IC s+ setSession $ s{hsc_IC = extendInteractiveContextWithTyThings ic tythings }+ addModuleDynFlags breakModule = do+ ic_dyn_flags <- getInteractiveDebuggerDynFlags+ break_dyn_flags <- ms_hspp_opts <$> GHC.getModSummary breakModule+ setInteractiveDebuggerDynFlags $ adjustFlags ic_dyn_flags break_dyn_flags++ -- Possibly we might want to include more from the module's DynFlags.+ -- However some are likely to mess with the REPL, e.g. Opt_WarnTypeDefaults,+ -- Opt_HideAllPackages, Opt_NoIt. See discussion at+ -- https://github.com/well-typed/haskell-debugger/pull/230#discussion_r2986758826+ adjustFlags :: DynFlags -> DynFlags -> DynFlags+ adjustFlags ic modl = ic+ { extensions = extensions modl+ , extensionFlags = extensionFlags modl+ , language = language modl+ }++refreshImports :: Maybe ImportsEpoch -> Maybe Module -> ScopeT "frame" Debugger (ScopeT "frame" Debugger ())+refreshImports gen m = do+ (gic,gen') <- lift getGlobalIC+ lclImports <- ic_imports . hsc_IC <$> lift getSession+ let extra = case m of+ Nothing -> []+ Just modl -> [IIModule modl]+ let hasImport = case m of+ Nothing -> True+ Just modl -> case lclImports of+ (IIModule mod':_) -> modl == mod'+ _ -> False+ unless (gen == Just gen' && hasImport) $ do+ lift $ GHC.setContext (extra ++ ic_imports gic)+ let w = storeFrameIC (gen',m)+ w+ pure w++storeFrameIC :: (GhcMonad m, MonadReader DebuggerState m) => (ImportsEpoch,Maybe Module) -> ScopeT "frame" m ()+storeFrameIC imports_spec = do+ s <- ask+ let Frame tid frame_index = s+ ic <- hsc_IC <$> lift getSession+ trm_ref <- lift $ asks threadResumeMap+ liftIO $+ modifyIORef' trm_ref $ \tm -> do+ let rtid = (remoteThreadIntRef tid)+ case lookupThreadMap rtid tm of+ Just StoppedThread{..} ->+ insertThreadMap rtid+ (StoppedThread {frameICs = IM.insert frame_index (ic,imports_spec) frameICs,..})+ tm+ Nothing -> tm++--------------------------------------------------+--- Utils+--------------------------------------------------++-- | Resume execution with single step mode 'RunToCompletion', skipping all breakpoints we hit, until we reach 'ExecComplete'.+--+-- We use this in 'doEval' because we want to ignore breakpoints in expressions given at the prompt.+continueToCompletion :: Resume -> Debugger ExecResult+continueToCompletion r = do+ execr <- resumeExec RunToCompletion Nothing r+ case execr of+ br@ExecBreak{} -> execBreakResume br >>= continueToCompletion+ ExecComplete{} -> return execr++getGlobalIC :: Debugger (InteractiveContext, ImportsEpoch)+getGlobalIC = do+ gicRef <- asks globalIC+ liftIO $ readIORef gicRef++setGlobalIC :: (InteractiveContext, ImportsEpoch) -> Debugger ()+setGlobalIC x = do+ gicRef <- asks globalIC+ liftIO $ writeIORef gicRef x++extendInteractiveContextWithTyThings :: InteractiveContext -> [TyThing] -> InteractiveContext+extendInteractiveContextWithTyThings ictxt new_tythings+ | null new_tythings = ictxt+ | otherwise+ = extendInteractiveContext ictxt new_tythings emptyInstEnv [] emptyDefaultEnv (ic_fix_env ictxt)++withTempInteractiveContext :: GhcMonad m => Scope s -> ScopeT s m b -> m b+withTempInteractiveContext scope m = do+ let acquire = do+ ic <- hsc_IC <$> getSession+ dflags <- getInteractiveDebuggerDynFlags+ pure (ic,dflags)+ release (ic,dflags) = do+ modifySession (\ s -> s {hsc_IC = ic})+ setInteractiveDebuggerDynFlags dflags+ MC.bracket acquire release $ const (unsafeUnScopeT m scope)
+ haskell-debugger/GHC/Debugger/Run/Handler.hs view
@@ -0,0 +1,114 @@+{-# LANGUAGE BangPatterns #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE ViewPatterns #-}++-- | Determine how the debugger handles a breakpoint being hit+module GHC.Debugger.Run.Handler+ ( handleExecResult+ ) where++import GHC.Utils.Outputable+import Control.Monad.IO.Class+import Control.Monad.Reader+import Data.IORef++import GHC (+ ExecResult (..),+ SingleStep (..),+ )++import Colog.Core as Logger+import GHC.Runtime.Eval.Types++import GHC.Debugger.Interface.Messages+import GHC.Debugger.Monad+import GHC.Debugger.Run.Resume+import GHC.Debugger.Runtime.Thread.Resume++import qualified GHC.Debugger.Data.BreakpointMap as BM+import GHC.Debugger.Run.Eval+import GHC.Debugger.Stopped.Variables++--------------------------------------------------------------------------------++-- | Turn a GHC's 'ExecResult' into an 'EvalResult' response+handleExecResult :: GHC.ExecResult -> Debugger EvalResult+handleExecResult = \case+ ExecComplete {execResult} -> do+ case execResult of+ Left e -> return (EvalException (show e) "SomeException")+ Right [] -> return (EvalCompleted "" "" Nothing NoVariables) -- Evaluation completed without binding any result.+ Right (n:_ns) -> idToVarInfo n >>= \case+ Just VarInfo{varValue, varType, varRef} -> do+ return (EvalCompleted varValue varType Nothing varRef)+ Nothing -> liftIO $ fail "doEval failed"+ br@ExecBreak {breakPointId = Nothing} -> do+ -- Stopped at an exception+ -- TODO: force the exception to display string with Backtrace?+ res <- execBreakResume br+ pushResume res+ rt_id <- getResumeThreadId res+ return EvalStopped{ breakId = Nothing+ , breakThread = rt_id }+ br@ExecBreak {breakPointId = Just bid} -> do++ res <- execBreakResume br+ pushResume res+ rt_id <- getResumeThreadId res++ let performAction BreakpointStop = do+ return EvalStopped{ breakId = Just bid+ , breakThread = rt_id }+ performAction (BreakpointLogAndResume logExpr) = do+ let evalFailedMsg e = text $ unlines ["Evaluation of log message expression failed with " ++ e+ , "Expr: " ++ logExpr+ , "Ignoring..."]+ doEval' logExpr evalFailedMsg rt_id $ \ _ _ -> resume rt_id++ bm <- liftIO . readIORef =<< asks activeBreakpoints+ case BM.lookup bid bm of+ -- When stepping (`GHC.resumeExec SingleStep` or similar), we will+ -- typically stop at locations not explicitly enabled by the user (i.e.+ -- not registered in `activeBreakpoints`).+ Nothing -> performAction BreakpointStop+ Just BreakpointInfo{bpInfoStatus = status, bpInfoAction = action} -> do+ case status of+ -- todo: BreakpointAfterCountCond is not handled yet.+ BreakpointAfterCountCond{} -> performAction action+ BreakpointWhenCond cond -> do+ let evalFailedMsg e = text $ "Evaluation of conditional breakpoint expression failed with " ++ e ++ "\nIgnoring..."++ doEval' cond evalFailedMsg rt_id $ \ resultVal resultType -> do+ if resultType == "Bool" then do+ if resultVal == "True" then do+ performAction action+ else+ resume rt_id+ else do+ logSDoc Logger.Warning (evalFailedMsg "\"expression resultType is != Bool\"")+ resume rt_id+ BreakpointDisabled -> resume rt_id+ -- The counting is handled by @GHC.setupBreakpoint@+ BreakpointAfterCount _ -> performAction action+ BreakpointEnabled -> performAction action+ where+ doEval' expr evalFailedMsg rt_id k = do+ doEval handleExecResult (Just (rt_id, 0)) expr >>= \case+ EvalStopped{} -> error "impossible for doEval"+ EvalCompleted { resultVal, resultType } ->+ k resultVal resultType+ EvalException { resultVal } -> do+ logSDoc Logger.Warning (evalFailedMsg resultVal)+ resume rt_id+ EvalAbortedWith e -> do+ logSDoc Logger.Warning (evalFailedMsg e)+ resume rt_id+ resume rt_id = popResume rt_id >>= resumeExec GHC.RunToCompletion Nothing >>= handleExecResult
+ haskell-debugger/GHC/Debugger/Run/Resume.hs view
@@ -0,0 +1,63 @@+{-# LANGUAGE LambdaCase #-}+module GHC.Debugger.Run.Resume+ ( resolveResumeStep+ , resumeExec+ ) where++import GHC.Runtime.Eval hiding (resumeExec)+import GHC.Debugger.Monad+import GHC.Debugger.Interface.Messages+import GHC.Driver.Monad+import GHC.Driver.Env+import GHC.ByteCode.Breakpoints+import GHC.Runtime.Debugger.Breakpoints+import Data.Maybe+import GHC.Types.SrcLoc+import Data.Function+import qualified GHC.Runtime.Eval as GHC++-- | Construct the 'SingleStep' resume option for a paused thread from its+-- 'Resume' info and the type of step to do.+resolveResumeStep :: Resume -> ResumeStep -> Debugger SingleStep+resolveResumeStep r = \case+ ResumeNoStep -> pure RunToCompletion+ ResumeSingleStep -> pure SingleStep+ ResumeStepLocal+ | Nothing <- rbid -- exception+ -> pure SingleStep+ | Just ibi <- rbid+ -> do+ spn <- enclosing_decl ibi+ pure LocalStep { breakAt = RealSrcSpan spn mempty }+ ResumeStepOut+ | Nothing <- rbid+ -> pure StepOut { initiatedFrom = Nothing }+ | Just ibi <- rbid+ -> do+ spn <- enclosing_decl ibi+ pure StepOut { initiatedFrom = Just (RealSrcSpan spn mempty) }+ where+ rbid = resumeBreakpointId r+ loc = resumeSpan r+ -- To do a local step, we get the SrcSpan of the current suspension state+ -- and get its 'enclosingTickSpan' to use as a filter for breakpoints in+ -- the call to 'resumeExec'. Execution will only stop at breakpoints whose+ -- span matches this enclosing span.+ enclosing_decl ibi = do+ hug <- hsc_HUG <$> getSession+ brks <- readIModBreaks hug ibi & liftIO+ let md = getBreakSourceMod ibi brks+ ticks <- fromMaybe (error "doLocalStep:getTicks") <$> makeModuleLineMap md+ pure $ enclosingTickSpan ticks loc++-- | Wrap around GHC's "odd behavior"?+resumeExec :: SingleStep -> Maybe Int -> Resume -> Debugger ExecResult+resumeExec a b _resume = do++#ifdef GHC_HAS_MULTITHREADED_DBG+ v <- GHC.resumeExec a MultiThreadedBreaks b _resume+#else+ v <- GHC.resumeExec a b+#endif++ pure v
− haskell-debugger/GHC/Debugger/Runtime.hs
@@ -1,55 +0,0 @@-{-# LANGUAGE OrPatterns, GADTs, LambdaCase, NamedFieldPuns, TemplateHaskellQuotes #-}-module GHC.Debugger.Runtime where--import Control.Monad.Reader--import GHC-import GHC.Utils.Outputable-import GHC.Runtime.Eval-import GHC.Runtime.Heap.Inspect--import GHC.Debugger.Runtime.Term.Key-import GHC.Debugger.Monad---- | Obtain the runtime 'Term' from a 'TermKey'.------ The 'TermKey' will be looked up in the 'TermCache' to avoid recomputing the--- 'Term' if possible. On a cache miss the Term will be reconstructed from--- scratch and stored in the cache.-obtainTerm :: TermKey -> Debugger Term-obtainTerm key = do- hsc_env <- getSession- -- Recursively get terms until we hit the desired key.- case key of- FromId i -> GHC.obtainTermFromId defaultDepth False{-don't force-} i- FromPath k pf -> do- term <- obtainTerm k- liftIO $ expandTerm hsc_env $ case term of- Term{dc=Right _, subTerms} -> case pf of- PositionalIndex ix -> subTerms !! (ix-1)- LabeledField n _ -> subTerms !! (n-1)- NewtypeWrap{wrapped_term} ->- wrapped_term -- regardless of PathFragment- RefWrap{wrapped_term} ->- wrapped_term -- regardless of PathFragment- _ -> error ("Unexpected term for the given TermKey because <term> should have been expanded before and we're getting a path fragment!\n" ++ showPprUnsafe (ppr key <+> ppr k <+> ppr pf))- FromCustomTerm _key _name ctm -> do- -- For custom terms return them straightaway.- liftIO $ expandTerm hsc_env ctm----- | Before returning a 'Term' we want to expand its heap representation up to the 'defaultDepth'------ For 'Id's, this is done by 'GHC.obtainTermFromId'. For other 'TermKey's this--- function should be used-expandTerm :: HscEnv -> Term -> IO Term-expandTerm hsc_env term = case term of- Term{val, ty} -> cvObtainTerm hsc_env defaultDepth False ty val- RefWrap{wrapped_term} -> do- wt' <- expandTerm hsc_env wrapped_term- return term{wrapped_term=wt'}- NewtypeWrap{wrapped_term} -> do- wt' <- expandTerm hsc_env wrapped_term- return term{wrapped_term=wt'}- Suspension{val, ty} -> cvObtainTerm hsc_env defaultDepth False ty val- Prim{} -> return term
haskell-debugger/GHC/Debugger/Runtime/Eval.hs view
@@ -21,6 +21,9 @@ import GHC.Driver.Env import GHC.Driver.Config import Control.Monad.IO.Class+#if MIN_VERSION_ghc(10,1,0)+import GHC.Runtime.Eval.Types+#endif import qualified GHC.Runtime.Interpreter as Interp import GHC.Debugger.Monad
haskell-debugger/GHC/Debugger/Runtime/Instances/Discover.hs view
@@ -20,6 +20,7 @@ import GHC #if MIN_VERSION_ghc(10,1,0) import GHC.Builtin.KnownKeys (ioTyConKey)+import GHC.Runtime.Eval.Types #else import GHC.Builtin.Names #endif
haskell-debugger/GHC/Debugger/Runtime/Internal.hs view
@@ -5,7 +5,6 @@ {-# LANGUAGE LambdaCase #-} module GHC.Debugger.Runtime.Internal ( module GHC.Debugger.Runtime.Internal- , GHC.evalWrapper , Prelude.concat , Prelude.putStrLn )@@ -19,6 +18,7 @@ import Data.List import GHC.Base (returnIO) import qualified System.IO+import GHC.Conc -- | Some extensions can mess with [] and (:) syntax, so we setup these plain -- function aliases.@@ -29,6 +29,14 @@ cons :: a -> [a] -> [a] cons = (:) +-- | Wraps GHC's evalWrapper for wrapping the execution of a 'main' in the+-- interpreter, but first labels the thread "Debuggee Main" (since it'll be+-- executing the debuggee main thread)+evalWrapper :: String -> [String] -> IO a -> IO a+evalWrapper progName args m = do+ mid <- myThreadId+ labelThread mid "Debuggee Main"+ GHC.evalWrapper progName args m -- Need to be careful not to create extra thunks in the returned `HValue`s, but -- also avoid forcing the inside of a `Box`.
haskell-debugger/GHC/Debugger/Runtime/Interpreter/Custom.hs view
@@ -138,6 +138,9 @@ = do xs <- NoShow <$> mkRemoteRef bcoArgs -- TODO: change ghc upstream so this offset is available from CgBreakInfo.+ -- WARNING: This currently makes traversing the stack O(n^2), since+ -- bcoArgsOffset needs to walk the stack until here and we do it for every+ -- RetBCO frame. Changing it upstream would fix this asymptotic too. let offset = FFIInspect.bcoArgsOffset ss frameIx fmap (\ ibi -> StackFrameBreakpointInfo ibi (DbgStackFrameBCOArgs xs offset)) <$> (lookupBCOBreakpoint =<< Heap.getClosureData bco_hval) stackFrameInfo _ _
+ haskell-debugger/GHC/Debugger/Runtime/Term.hs view
@@ -0,0 +1,109 @@+{-# LANGUAGE OrPatterns, GADTs, LambdaCase, NamedFieldPuns, TemplateHaskellQuotes #-}+module GHC.Debugger.Runtime.Term+ ( obtainTerm+ , seqTerm+ , deepseqTerm+ ) where++import Control.Monad.Reader++import GHC+import GHC.Utils.Outputable+import GHC.Runtime.Eval+import GHC.Runtime.Heap.Inspect++import GHC.Debugger.Runtime.Term.Key+import GHC.Debugger.Monad+import GHC.Plugins+import qualified GHC.Runtime.Interpreter as GHCi+import GHC.Runtime.Interpreter (fromEvalResult)++-- | Obtain the runtime 'Term' from a 'TermKey'.+--+-- The 'TermKey' will be looked up in the 'TermCache' to avoid recomputing the+-- 'Term' if possible. On a cache miss the Term will be reconstructed from+-- scratch and stored in the cache.+obtainTerm :: TermKey -> Debugger Term+obtainTerm key = do+ hsc_env <- getSession+ -- Recursively get terms until we hit the desired key.+ case key of+ FromId i -> GHC.obtainTermFromId defaultDepth False{-don't force-} i+ FromPath k pf -> do+ term <- obtainTerm k+ liftIO $ expandTerm hsc_env $ case term of+ Term{dc=Right _, subTerms} -> case pf of+ PositionalIndex ix -> subTerms !! (ix-1)+ LabeledField n _ -> subTerms !! (n-1)+ NewtypeWrap{wrapped_term} ->+ wrapped_term -- regardless of PathFragment+ RefWrap{wrapped_term} ->+ wrapped_term -- regardless of PathFragment+ _ -> error ("Unexpected term for the given TermKey because <term> should have been expanded before and we're getting a path fragment!\n" ++ showPprUnsafe (ppr key <+> ppr k <+> ppr pf))+ FromCustomTerm _key _name ctm -> do+ -- For custom terms return them straightaway.+ liftIO $ expandTerm hsc_env ctm+++-- | Before returning a 'Term' we want to expand its heap representation up to the 'defaultDepth'+--+-- For 'Id's, this is done by 'GHC.obtainTermFromId'. For other 'TermKey's this+-- function should be used+expandTerm :: HscEnv -> Term -> IO Term+expandTerm hsc_env term = case term of+ Term{val, ty} -> cvObtainTerm hsc_env defaultDepth False ty val+ RefWrap{wrapped_term} -> do+ wt' <- expandTerm hsc_env wrapped_term+ return term{wrapped_term=wt'}+ NewtypeWrap{wrapped_term} -> do+ wt' <- expandTerm hsc_env wrapped_term+ return term{wrapped_term=wt'}+ Suspension{val, ty} -> cvObtainTerm hsc_env defaultDepth False ty val+ Prim{} -> return term++--------------------------------------------------------------------------------+-- * Forcing laziness+--------------------------------------------------------------------------------++-- | The depth determines how much of the runtime structure is traversed.+-- @obtainTerm@ and friends handle fetching arbitrarily nested data structures+-- so we only depth enough to get to the next level of subterms.+defaultDepth :: Int+defaultDepth = 2++-- | Evaluate a suspended Term to WHNF.+--+-- Used in @'getVariables'@ to reply to a variable introspection request.+seqTerm :: HscEnv -> Term -> IO Term+seqTerm hsc_env term = do+ let+ interp = hscInterp hsc_env+ unit_env = hsc_unit_env hsc_env+ case term of+ Suspension{val, ty} -> do+#if MIN_VERSION_ghc(9,15,0)+ r <- GHCi.seqHValue interp unit_env (hsc_logger hsc_env) val+#else+ r <- GHCi.seqHValue interp unit_env val+#endif+ () <- fromEvalResult r+ let+ forceThunks = False {- whether to force the thunk subterms -}+ forceDepth = defaultDepth+ cvObtainTerm hsc_env forceDepth forceThunks ty val+ NewtypeWrap{wrapped_term} -> do+ wrapped_term' <- seqTerm hsc_env wrapped_term+ return term{wrapped_term=wrapped_term'}+ _ -> return term++-- | Evaluate a Term to NF+deepseqTerm :: HscEnv -> Term -> IO Term+deepseqTerm hsc_env t = case t of+ Suspension{} -> do t' <- seqTerm hsc_env t+ deepseqTerm hsc_env t'+ Term{subTerms} -> do subTerms' <- mapM (deepseqTerm hsc_env) subTerms+ return t{subTerms = subTerms'}+ NewtypeWrap{wrapped_term}+ -> do wrapped_term' <- deepseqTerm hsc_env wrapped_term+ return t{wrapped_term = wrapped_term'}+ _ -> do seqTerm hsc_env t
haskell-debugger/GHC/Debugger/Runtime/Term/Parser.hs view
@@ -26,6 +26,7 @@ import qualified GHC.Debugger.Runtime.Eval.RemoteExpr as Remote import qualified GHC.Debugger.Runtime.Compile as Comp+import GHC.Debugger.Runtime.Term (seqTerm) -- | The main entry point for running the 'TermParser'. obtainParsedTerm
haskell-debugger/GHC/Debugger/Runtime/Thread.hs view
@@ -8,7 +8,8 @@ -- TODO -- - [] Consider caching once and forall the expressions we dynamically compile and load in this module. module GHC.Debugger.Runtime.Thread- ( getRemoteThreadIdFromRemoteContext+ (+ getRemoteThreadIdFromRemoteContext , getRemoteThreadId , listAllLiveRemoteThreads @@ -24,22 +25,26 @@ import Data.IORef import GHC.Conc.Sync +#ifdef GHC_HAS_MULTITHREADED_DBG+#else+import GHC.Runtime.Heap.Inspect+import GHCi.Message+#endif+ #if MIN_VERSION_ghc(10,1,0) import GHC.Builtin.WiredIn.Types #else import GHC.Builtin.Types #endif-import GHC.Runtime.Heap.Inspect import GHC.Utils.Outputable -import GHCi.Message import GHCi.RemoteTypes import Colog.Core as Logger import GHC.Debugger.Monad import GHC.Debugger.Interface.Messages import GHC.Debugger.Runtime.Term.Parser-import GHC.Debugger.Runtime.Thread.Map+import GHC.Debugger.Data.ThreadMap import GHC.Debugger.Runtime.Interpreter.Types import qualified GHC.Debugger.Runtime.Eval.RemoteExpr as Remote@@ -51,7 +56,13 @@ import qualified GHC.Debugger.Runtime.Interpreter.Legacy as Debuggee #endif +#ifdef GHC_HAS_MULTITHREADED_DBG+-- Shim to keep rest of codebase as is despite resumeContext now being just ForeignRef ThreadId+getRemoteThreadIdFromRemoteContext :: ForeignRef ThreadId -> Debugger RemoteThreadId+getRemoteThreadIdFromRemoteContext = getRemoteThreadId+#else -- | Get a 'RemoteThreadId' from a remote 'ResumeContext' gotten from an 'ExecBreak'+-- (in 10.2 'ResumeContext' is gone, now it's just the 'ThreadId') getRemoteThreadIdFromRemoteContext :: ForeignRef (ResumeContext [HValueRef]) -> Debugger RemoteThreadId getRemoteThreadIdFromRemoteContext fctxt = do -- Get the ResumeContext term and fetch the resumeContextThreadId field@@ -64,6 +75,7 @@ Right Term{val=threadIdVal} -> do getRemoteThreadId (castForeignRef threadIdVal) _ -> liftIO $ fail "Expected threadIdTerm to be a Term!"+#endif -- | Call 'listThreads' on the (possibly) remote debuggee process to get the -- list of threads running on the debuggee. Filter by running threads
− haskell-debugger/GHC/Debugger/Runtime/Thread/Map.hs
@@ -1,42 +0,0 @@--- | A map to track and manage the debuggee runtime threads-module GHC.Debugger.Runtime.Thread.Map- ( ThreadMap- , emptyThreadMap-- -- * Operations- , insertThreadMap- , lookupThreadMap-- , threadMapToList-- -- can we detect when a thread has died? what happens if we have a reference- -- to a ThreadId which has been GC'd?- ) where--import Control.Concurrent-import Data.Coerce--import GHCi.RemoteTypes-import qualified Data.IntMap as IM---- | A thread map maintains a mapping between the int thread identifier, which--- uniquely identifies a thread spawned by the debuggee, and the (possibly--- remote) reference to the thread (i.e. the corresponding ThreadId)-type ThreadMap = IM.IntMap (ForeignRef ThreadId)---- | Insert a remote 'ThreadId' at this unique Int thread identifier-insertThreadMap :: Int -> ForeignRef ThreadId -> ThreadMap -> ThreadMap-insertThreadMap = IM.insert---- | Lookup a remote 'ThreadId' by its unique Int identifier-lookupThreadMap :: Int -> ThreadMap -> Maybe (ForeignRef ThreadId)-lookupThreadMap = IM.lookup---- | > It's empty, what did you expect?-emptyThreadMap :: ThreadMap-emptyThreadMap = IM.empty---- | Get all the remote thread references from the ThreadMap-threadMapToList :: ThreadMap -> [(Int, ForeignRef ThreadId)]-threadMapToList = coerce . IM.toList-
+ haskell-debugger/GHC/Debugger/Runtime/Thread/Resume.hs view
@@ -0,0 +1,84 @@+{-# LANGUAGE LambdaCase, ViewPatterns, CPP #-}+{-# LANGUAGE RecordWildCards #-}+module GHC.Debugger.Runtime.Thread.Resume where++import GHC.Debugger.Interface.Messages+import GHC.Runtime.Eval+import GHC.Debugger.Monad+import Data.IORef+import Control.Monad.Reader+import Data.Function+import GHC.Debugger.Runtime.Thread+import GHC.Debugger.Data.ThreadMap+import GHC (GhcMonad (getSession))+import GHC.Driver.Env++-- | Pop the resume for this thread off+popResume :: RemoteThreadId -> Debugger Resume+popResume rti = do+ trm_ref <- asks threadResumeMap+ readResume rti >>= \case+ Nothing -> error "Trying to pop the resume of a thread which isn't running?"+ Just tr -> do+ modifyIORef' trm_ref (deleteThreadMap (remoteThreadIntRef rti)) & liftIO+ pure tr++-- | Push the resume for its thread to the mapping keeps track of which threads+-- are paused+pushResume :: Resume -> Debugger ()+pushResume resume = do+ trm_ref <- asks threadResumeMap+ rti <- getResumeThreadId resume+ breakIC <- hsc_IC <$> getSession+ liftIO $+ modifyIORef' trm_ref $+ insertThreadMap (remoteThreadIntRef rti) (mkStoppedThread resume breakIC)++-- | Get the 'Resume' a given stopped thread is currently at.+-- Returns Nothing if we're no longer stopped at this thread+--+-- See Note [Don't crash if not stopped] for why we may try to get the resume+-- of a thread we're no longer stopped at.+readResume :: RemoteThreadId -> Debugger (Maybe Resume)+readResume tid = fmap resume <$> readStoppedThread tid++readStoppedThread :: RemoteThreadId -> Debugger (Maybe StoppedThread)+readStoppedThread (remoteThreadIntRef -> rti) = do+ trm_ref <- asks threadResumeMap+ trm <- readIORef trm_ref & liftIO+ case lookupThreadMap rti trm of+ Nothing -> pure Nothing+ Just tr -> pure (Just tr)++getResumeThreadId :: Resume -> Debugger RemoteThreadId+#ifdef GHC_HAS_MULTITHREADED_DBG+getResumeThreadId = getRemoteThreadId . resumeContext+#else+getResumeThreadId = getRemoteThreadIdFromRemoteContext . resumeContext+#endif++-- | Get the 'Resume' associated to the given breakpoint result 'ExecBreak'.+--+-- On GHCs with better multi-threaded debugger support (>= 10.1), the 'Resume'+-- associated to a breakpoint is returned directly in 'ExecBreak'.+--+-- On older GHCs, the breakpoint resume is pushed to `ic_resume` context as+-- soon as it is hit.+--+-- WARNING: if we can hit and detect more breakpoints simultaneously, looking at+-- the head of ic_resume will be wrong. And there's no information we can use+-- to uniquely identify the right Resume in `ic_resume` for this breakpoint.+-- FIXME: Therefore, we shouldn't look for breakpoints simultaneously in 9.14.2?+-- Either that, or copy all the code over which returns the ExecBreak and+-- modify it (ie copy `handleRunStatus`).+execBreakResume :: ExecResult -> Debugger Resume+#ifdef GHC_HAS_MULTITHREADED_DBG+execBreakResume ExecBreak{breakResume} = pure breakResume+#else+execBreakResume ExecBreak{} =+ getResumeContext >>= \case+ r:_ -> pure r+ [] -> error "execBreakResume: stopped at a break but the resume context is empty?!"+#endif+execBreakResume ExecComplete{} =+ error "execBreakResume: expected ExecBreak but got ExecComplete"
haskell-debugger/GHC/Debugger/Session.hs view
@@ -32,7 +32,6 @@ setPgmI, addOptI, setDynFlagWays, makeDynFlagsAbsoluteOverall,- resumeExec, exposeModGraphUnitsInInteractiveGhcDebuggerUnit, graphsUnits, compileModuleWithDepsInHpt,@@ -94,7 +93,7 @@ import qualified Data.Set as Set import Data.Maybe import GHC.Types.Target (InputFileBuffer)-import GHC (SingleStep, ExecResult, ModSummary (ms_hspp_opts), ideclPkgQual, ImportDecl, GhcPs)+import GHC (ModSummary (ms_hspp_opts), ideclPkgQual, ImportDecl, GhcPs) import Data.Set (Set) import qualified GHC.Unit as GHC import GHC.Unit.Module.Graph (mg_mss, ModuleGraphNode (..), mnKey)@@ -111,6 +110,7 @@ import GHC.Plugins (SourceError, try, RawPkgQual (..), HasCallStack, FastString, mkFastString, lookupUnitId) #if MIN_VERSION_ghc(10,1,0) import GHC.Types.SourceText (SourceText (..))+import GHC.Driver.CmdLine as GHC #else import GHC.Types.SourceText (StringLiteral(..), SourceText (..)) #endif@@ -130,7 +130,12 @@ -> FilePath -- ^ root dir, see Note [Root Directory] -> m (NonEmpty.NonEmpty (DynFlags, [GHC.Target])) parseHomeUnitArguments cfp compRoot units theOpts dflags rootDir = do- ((theOpts',_errs,_warns),_units) <- GHC.processCmdLineP [] [] (map noLoc theOpts)+#if MIN_VERSION_ghc(10,1,0)+ let noFlags = GHC.mkFlagSpecTrie []+#else+ let noFlags = []+#endif+ ((theOpts',_errs,_warns),_units) <- GHC.processCmdLineP noFlags [] (map noLoc theOpts) case NonEmpty.nonEmpty units of Just us -> initMulti us Nothing -> do@@ -421,7 +426,7 @@ -> IO [TargetDetails] -- For a target module we consider all the import paths fromTargetId is exts unitId (GHC.TargetModule modName) ctts = do- let fps = [i </> moduleNameSlashes modName -<.> ext <> boot+ let fps = [i </> GHC.moduleNameSlashes modName -<.> ext <> boot | ext <- exts , i <- is , boot <- ["", "-boot"]@@ -741,41 +746,6 @@ -- | See Note [ UniqSupply is process global ] initUniqSupplyIO :: IO () initUniqSupplyIO = GHC.initUniqSupply 0 1---- ------------------------------------------------------------------------------- Wrappers around GHC's odd behavior--- ------------------------------------------------------------------------------resumeExec :: GhcMonad m => SingleStep -> Maybe Int -> m ExecResult-resumeExec a b = do- -- IC's ic_imports field is not kept in sync with ic_gre_cache, so we could do- -- this call later, but why rely on that.- imports <- GHC.getContext-- v <- GHC.resumeExec a b-- -- To have interactive imports persist after a `continue` command we have to- -- work around how GHC.resumeExec handles the InteractiveContext (IC).- --- -- GHC.resumeExec resets the scope of the IC (i.e. ic_gre_cache) to what it- -- was before the last ExecBreak.- --- -- It makes sense for GHC.resumeExec to remove from the IC scope the- -- breakpoint locals and anything that could have been defined with them, in- -- fact they are also unloaded.- --- -- The way it's done though also rollbacks any import statements that were- -- executed since the last ExecBreak. The only fix is to reimport everything- -- again.- --- -- Note: GHC.setContext recomputes the scope of the interactive imports from- -- scratch everytime. Considering `runDebugger` adds the whole home unit to- -- the interactive imports this might become a bottleneck. GHC does not keep- -- any reference to the scope containing just the imports, so we would have to- -- cache it ourselves (and then extend it with the cached scope of- -- ic_tythings, i.e. igre_prompt_env (c.f. replaceImportEnv)).- GHC.setContext imports- pure v -- ---------------------------------------------------------------------------- -- Utils that we need, but don't want to incur an additional dependency for.
haskell-debugger/GHC/Debugger/Session/Builtin.hs view
@@ -4,31 +4,40 @@ -- | Built-in units and modules module GHC.Debugger.Session.Builtin- ( -- * Built-in mods+ ( -- * HsDebuggerView unit+ -- ** Modules debuggerViewBuiltinMods , debuggerViewInstancesMods+ -- Note:+ -- Don't export instances mods individually to make sure we get warnings if+ -- we add new modules but forget to put any part of them there. , debuggerViewClassModName, debuggerViewClassContents- -- * In memory unit+ -- ** In memory unit , hsDebuggerViewInMemoryUnitId , addInMemoryHsDebuggerViewUnit- , makeInMemoryTarget- , runInternal + -- * DebuggerInternal unit+ -- ** Modules+ , debuggerRuntimeInternalModName, debuggerRuntimeInternalContents+ , debuggerRuntimeInternalModule+ -- ** In memory unit , debuggerInternalUnitId- , addInMemoryDebuggerInternalUnit- , debuggerRuntimeInternalContents- , debuggerRuntimeInternalModName , debuggerRuntimeInternalUnit- , debuggerRuntimeInternalModule+ , addInMemoryDebuggerInternalUnit+ -- ** Utils+ , lookupNoPrintConstant+ , runInternal #if !MIN_VERSION_ghc(9,14,2)+ -- * FFIInspect unit+ -- ** Modules+ , debuggerRuntimeFFIInspectModName, debuggerRuntimeFFIInspectContents+ -- ** In memory unit , addInMemoryFFIInspectUnit , hsDebuggerFFIInspectUnitId- , debuggerRuntimeFFIInspectModName, debuggerRuntimeFFIInspectContents #endif- -- Note:- -- Don't export instances mods individually to make sure we get warnings if- -- we add new modules but forget to put any part of them there.+ -- * Helpers+ , makeInMemoryTarget ) where @@ -55,6 +64,8 @@ import qualified GHC.LanguageExtensions as LangExt import GHC.Runtime.Context (InteractiveContext(..), emptyInteractiveContext) import Control.Monad.Catch (finally)+import GHC.Iface.Env (lookupNameCache)+import GHC.Types.Name (mkVarOcc) -------------------------------------------------------------------------------- -- * Built-in Modules@@ -197,6 +208,13 @@ return () +-- | Gives @Name@ of a strict @noPrintConstant :: a -> IO ()@+lookupNoPrintConstant :: Ghc Name+lookupNoPrintConstant = do+ hsc_env <- getSession+ let debuggerInternalUnit = RealUnit (Definite debuggerInternalUnitId)+ liftIO $ lookupNameCache (hsc_NC hsc_env) (mkModule debuggerInternalUnit debuggerRuntimeInternalModName)+ (mkVarOcc "noPrintConstant") addInMemoryUnit :: GhcMonad m => UnitId -- ^ The unit-id for the unit to add
− haskell-debugger/GHC/Debugger/Session/Interactive.hs
@@ -1,32 +0,0 @@-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE ViewPatterns #-}-{-# LANGUAGE MultilineStrings #-}-{-# LANGUAGE BangPatterns #-}-{-# LANGUAGE CPP #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE NamedFieldPuns #-}-{-# LANGUAGE OverloadedRecordDot #-}-{-# LANGUAGE TupleSections #-}-{-# LANGUAGE TemplateHaskell #-}-{-# LANGUAGE TypeApplications #-}-module GHC.Debugger.Session.Interactive where--import Control.Monad.IO.Class--#if MIN_VERSION_ghc(9,15,0)-import GHC.Linker.Types (modifyHomePackageBytecodeState)-#endif-import GHC-import GHC.Driver.Env-import GHC.Iface.Env (lookupNameCache)-import GHC.Debugger.Session.Builtin-import GHC.Plugins (mkVarOcc, Definite (Definite), GenUnit (RealUnit))---- | Defines a strict @noPrintConstant :: a -> IO ()@ while taking care not to introduce its OccName into scope.-defineNoPrint :: Ghc Name-defineNoPrint = do- hsc_env <- getSession- let debuggerInternalUnit = RealUnit (Definite debuggerInternalUnitId)- liftIO $ lookupNameCache (hsc_NC hsc_env) (mkModule debuggerInternalUnit debuggerRuntimeInternalModName)- (mkVarOcc "noPrintConstant")
haskell-debugger/GHC/Debugger/Stopped.hs view
@@ -1,8 +1,20 @@ {-# LANGUAGE CPP, NamedFieldPuns, TupleSections, LambdaCase, DuplicateRecordFields, RecordWildCards, TupleSections, ViewPatterns, TypeApplications, ScopedTypeVariables, BangPatterns, MultiWayIf, OverloadedRecordDot #-}-module GHC.Debugger.Stopped where +-- | Query information about the debuggee when a thread is stopped+module GHC.Debugger.Stopped+ (+ -- * Query information about the stopped debuggee threads+ getThreads+ , getStacktrace+ , getScopes+ , getVariables+ , getExceptionInfo+ , getStackFrame+ ) where++import Data.Function import Control.Monad import Control.Monad.Reader import Data.IORef@@ -24,20 +36,28 @@ import GHC.Utils.Outputable as Ppr import qualified GHC.Unit.Home.Graph as HUG +import GHC.Debugger.Data.ThreadMap+ import GHC.Debugger.Stopped.Exception import GHC.Debugger.Stopped.Frames import GHC.Debugger.Stopped.Variables-import GHC.Debugger.Runtime+import GHC.Debugger.Runtime.Term import GHC.Debugger.Runtime.Thread import GHC.Debugger.Runtime.Thread.Stack-import GHC.Debugger.Runtime.Thread.Map import GHC.Debugger.Monad import GHC.Debugger.Interface.Messages import qualified GHC.Debugger.Interface.Messages as DbgStackFrame (DbgStackFrame(..)) import GHC.Debugger.Utils import qualified Colog.Core as Logger import System.Directory (getCurrentDirectory)+import Data.List+import GHC.Debugger.Runtime.Thread.Resume+import GHC.Runtime.Context (icInScopeTTs) +#if MIN_VERSION_ghc(10,1,0)+import GHC.Debugger.Runtime.Thread.Resume+#endif+ {- Note [Don't crash if not stopped] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -64,46 +84,30 @@ getThreads :: Debugger [DebuggeeThread] getThreads = do- -- TODO: we want something more like 'listThreads', but ensure that we only- -- report the threads of the debuggee (and not the debugger, if they- -- are the same process). Perhaps the solution is to not allow them to be in- -- the same process, in which case 'listThreads' would be correct as is by- -- construction.- --- -- For now, we approximate by just listing out the ThreadsMap, under the- -- assumption the debugger client will only care about threads we've already- -- stopped at (which are the only ones we've inserted in the threads map),- -- but for full multi threaded debugging we need the listThreads.- --- -- tmap <- liftIO . readIORef =<< asks threadMap- -- let (t_ids, remote_refs) = unzip (threadMapToList tmap)- --- -- Oh, try the listThreads just for fun.- (t_ids, t_infos) <- unzip <$> listAllLiveRemoteThreads+ thds <- listAllLiveRemoteThreads let- _mkDebuggeeThread tid tinfo+ mkDebuggeeThread tid tinfo = DebuggeeThread { tId = tid , tName = tinfo.threadInfoLabel+ -- TODO: display thread status, but without displaying+ -- "BlockedOnMVar" when its the dbg resume MVar }- _all_threads- = zipWith _mkDebuggeeThread t_ids t_infos+ all_threads+ = [ mkDebuggeeThread t_id t_info+ | (t_id, t_info) <- thds - -- TODO: We ignore _all_threads and report only the main execution thread for now.- -- See #138 for progress on Multi-threaded debugging.- GHC.getResumeContext >>= \case- [] ->- -- See Note [Don't crash if not stopped]- return []- r:_ -> do- r_tid <- getRemoteThreadIdFromRemoteContext (GHC.resumeContext r)- return- [ DebuggeeThread- { tId = r_tid- , tName = Just "Main Thread"- }+ -- hide "helper" interpreter process threads+ , case t_info.threadInfoLabel of+ Just "TimerManager" -> False+ Just "Ext. Interpreter Server" -> False+ Just "main of Ext. Interpreter Server" -> False+ Just (take 9 -> "IOManager") -> False+ _ -> True ] + return all_threads+ -------------------------------------------------------------------------------- -- * Stack trace --------------------------------------------------------------------------------@@ -162,11 +166,21 @@ } -- Add the latest resume context at the head.- head_frame <- GHC.getResumeContext >>= \case+ head_frame <-+#if MIN_VERSION_ghc(10,1,0)+ readResume req_tid >>= \case+ Nothing ->+#else+ GHC.getResumeContext >>= \case [] ->+#endif -- See Note [Don't crash if not stopped] return Nothing+#if MIN_VERSION_ghc(10,1,0)+ Just r -> do+#else r:_ -> do+#endif let resumeSpanR = GHC.resumeSpan r mRealSpan = realSrcSpanToSourceSpan cwd <$> srcSpanToRealSrcSpan resumeSpanR firstSpan = DbgStackFrame.sourceSpan <$> listToMaybe decoded_frames@@ -262,6 +276,11 @@ -- (b) ONLY the variable requested -- (c) The fields of the variable requested but NOT the original variable +getStackFrame :: RemoteThreadId -> Int{-stack frame index-} -> Debugger (Maybe DbgStackFrame)+getStackFrame threadId frameIx = do+ frames <- getStacktrace threadId+ pure $ frames !? frameIx+ -- | Get variables using a variable/variables reference. -- -- When the request forces a variable, return 'ForcedVariable'. Otherwise return@@ -290,7 +309,7 @@ -- It is a "lazy" DAP variable: our reply can ONLY include -- this single variable. - term' <- forceTerm term+ term' <- seqTerm hsc_env term & liftIO vi <- termToVarInfo fam_envs key term' @@ -308,12 +327,11 @@ -- (VARR)(a) from here onwards LocalVariables -> fmap VariableFields $ do- vars <- if frameIx == 0- then- -- top frame vars already bound when stopping- GHC.getBindings- else- map AnId <$> getStackFrameBindings frame+ st <- if frameIx == 0 then readStoppedThread threadId else pure Nothing+ vars <- case st of+ Just StoppedThread{..}+ -> pure (GHC.Runtime.Context.icInScopeTTs breakIC)+ _ -> map AnId <$> getStackFrameBindings frame mapM (tyThingToVarInfo fam_envs) vars ModuleVariables
haskell-debugger/GHC/Debugger/Stopped/Exception.hs view
@@ -30,6 +30,8 @@ -- | Retrieve structured exception information for the requested thread when -- the debugger is currently stopped on an exception. getExceptionInfo :: RemoteThreadId -> Debugger ExceptionInfo+ -- The only context in which it is excusable to use getResumeContext with+ -- latest GHC because we haven't yet per-thread exception breakpoints upstream. getExceptionInfo req_tid = GHC.getResumeContext >>= \case [] -> return defaultExceptionInfo r:_ -> do
haskell-debugger/GHC/Debugger/Stopped/Frames.hs view
@@ -218,7 +218,11 @@ case mb_new_ty of Nothing -> return hsc_env Just new_ty -> do+#ifdef GHC_HAS_MULTITHREADED_DBG+ case GHC.improveRTTIType old_ty new_ty of+#else case GHC.improveRTTIType hsc_env old_ty new_ty of+#endif Nothing -> warnPprTrace True (":print failed to calculate the " ++ "improvement for a type") (vcat [ text "id" <+> ppr id'
haskell-debugger/GHC/Debugger/Stopped/Variables.hs view
@@ -2,8 +2,23 @@ DuplicateRecordFields, RecordWildCards, TupleSections, ViewPatterns, TypeApplications, ScopedTypeVariables, BangPatterns, DerivingVia, TypeAbstractions, DataKinds #-}-module GHC.Debugger.Stopped.Variables where +-- | Construct information about variables and other things from Ids/TyThings/Terms.+module GHC.Debugger.Stopped.Variables+ (++ -- * Info from Id/TyThing+ idToVarInfo+ , tyThingToVarInfo++ -- * Info from Terms+ , termToVarInfo+ , termVarFields++ -- * Context+ , getFamInstEnvs'+ ) where+ import Control.Monad.Reader import qualified Colog.Core as Logger @@ -22,11 +37,34 @@ import GHC.Debugger.Monad import GHC.Debugger.Interface.Messages-import GHC.Debugger.Runtime import GHC.Debugger.Runtime.Instances+import GHC.Debugger.Runtime.Term import GHC.Debugger.Runtime.Term.Key import GHC.Debugger.Utils +--------------------------------------------------------------------------------+-- Id/TyThing+--------------------------------------------------------------------------------++-- | Get the value and type of a given 'Id' as rendered strings in 'VarInfo'.+#ifdef GHC_HAS_MULTITHREADED_DBG+idToVarInfo :: Id -> Debugger (Maybe VarInfo)+idToVarInfo (GHC.AnId -> tt) = Just <$> do+ fam_envs <- getFamInstEnvs'+ tyThingToVarInfo fam_envs tt+#else+-- this is no longer needed in HEAD since ExecBreaks now return Ids.+idToVarInfo :: Name -> Debugger (Maybe VarInfo)+idToVarInfo n = do+ GHC.lookupName n >>= \case+ Nothing -> do+ liftIO . putStrLn =<< display (text "Failed to lookup name: " <+> ppr n)+ pure Nothing+ Just tt -> Just <$> do+ fam_envs <- getFamInstEnvs'+ tyThingToVarInfo fam_envs tt+#endif+ -- | 'TyThing' to 'VarInfo'. The 'Bool' argument indicates whether to force the -- value of the thing (as in @True = :force@, @False = :print@) tyThingToVarInfo :: FamInstEnvs -> TyThing -> Debugger VarInfo@@ -46,6 +84,10 @@ term <- obtainTerm key termToVarInfo fam_envs key term +--------------------------------------------------------------------------------+-- Terms+--------------------------------------------------------------------------------+ -- | Construct the VarInfos of the fields ('VarFields') of the given 'TermKey'/'Term' -- -- This is used to come up with terms for the fields of an already `seq`ed@@ -97,8 +139,10 @@ _ -> return (VarFields []) --- | Construct a 'VarInfo' from the given 'Name' of the variable and the 'Term' it binds--- The @FamInstEnvs@ is used to look through newtypes and type families when checking if suspensions are of function type.+-- | Construct a 'VarInfo' from the given 'TermKey' of the variable and the 'Term' it binds+--+-- The @FamInstEnvs@ is used to look through newtypes and type families when+-- checking if suspensions are of function type. termToVarInfo :: FamInstEnvs -> TermKey -> Term -> Debugger VarInfo termToVarInfo fam_envs key term0 = do -- Make a VarInfo for a term@@ -198,6 +242,10 @@ unwrapNewtype (NewtypeWrap {wrapped_term}) = unwrapNewtype wrapped_term unwrapNewtype x = x +--------------------------------------------------------------------------------+-- Context+--------------------------------------------------------------------------------+ -- | Thin wrapper around @tcGetFamInstEnvs@, using @runTcInteractive@ getFamInstEnvs' :: Debugger FamInstEnvs getFamInstEnvs' = do@@ -218,22 +266,18 @@ $$ ppr err_msgs return emptyFamInstEnvs -pprTerm :: Term -> SDoc-pprTerm t = case t of+--------------------------------------------------------------------------------+-- Utils+--------------------------------------------------------------------------------++_ppr_term :: Term -> SDoc+_ppr_term t = case t of Term{dc,subTerms} -> annotate "T:" $- either text ppr dc <+> ppr (map pprTerm subTerms)+ either text ppr dc <+> ppr (map _ppr_term subTerms) Prim{valRaw} -> annotate "P:" $ ppr valRaw Suspension{bound_to,ctype} -> annotate "S:" $ ppr bound_to <+> text (show ctype) NewtypeWrap{dc,wrapped_term} ->- annotate "N:" $ either text ppr dc <+> pprTerm wrapped_term- RefWrap{wrapped_term} -> annotate "R:" $ pprTerm wrapped_term+ annotate "N:" $ either text ppr dc <+> _ppr_term wrapped_term+ RefWrap{wrapped_term} -> annotate "R:" $ _ppr_term wrapped_term where annotate tag d = parens $ text tag <+> ppr (ty t) <+> text "∋" <+> d---- | Forces a term to WHNF------ The term is updated in the cache at the given key.-forceTerm :: Term -> Debugger Term-forceTerm term = do- hsc_env <- getSession- liftIO $ seqTerm hsc_env term
haskell-debugger/GHC/Debugger/Utils.hs view
@@ -12,6 +12,7 @@ import Control.Applicative import Control.Exception import System.IO+import System.IO.Error import GHC import GHC.Data.FastString@@ -26,20 +27,25 @@ import Colog.Core as Logger import GHC.Debugger.Interface.Messages+import GHC.Stack -------------------------------------------------------------------------------- -- * Handle utils -------------------------------------------------------------------------------- +silenceEOF :: HasCallStack => LogAction IO T.Text -> Handle -> IO () -> IO ()+silenceEOF l h m = do+ m `catchNoPropagate`+ \x@(ExceptionWithContext _ctx e) -> do+ if isEOFError e && ioeGetHandle e == Just h+ then l <& (T.pack $ "Ignored EOF exception: \n" ++ displayExceptionWithInfo (toException x) ++ "\n" ++ prettyCallStack callStack)+ else rethrowIO x+ -- | Read output from the given handle and write it to the given -- log action (forever).-forwardHandleToLogger :: Handle -> LogAction IO T.Text -> IO ()-forwardHandleToLogger read_h logger = do- forwarding `catch` -- handles read EOF- \(_e::SomeException) -> do- -- Cleanly exit on exception- -- print _e- return ()+forwardHandleToLogger :: HasCallStack => LogAction IO T.Text -> Handle -> LogAction IO T.Text -> IO ()+forwardHandleToLogger l read_h logger = do+ silenceEOF l read_h forwarding where forwarding = forever $ do -- Mask exceptions to avoid being killed between reading
hdb-dap/Development/Debug/Adapter.hs view
@@ -1,12 +1,13 @@+{-# OPTIONS_GHC -Wno-orphans #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-}+{-# LANGUAGE DerivingStrategies #-} module Development.Debug.Adapter where import Control.Concurrent-import Control.Monad (void)+import Control.Monad.Catch import Control.Monad.Error.Class (MonadError(..)) import Control.Monad.IO.Class (MonadIO(..))-import Control.Monad.Trans.Control (liftBaseDiscard) import qualified Data.IntSet as IS import qualified Data.Map as Map import qualified Data.IntMap as IM@@ -21,6 +22,9 @@ type DebugAdaptorCont = Adaptor DebugAdaptorState () type DebugAdaptorX r = Adaptor DebugAdaptorState r () +deriving newtype instance MonadThrow (Adaptor a b)+deriving newtype instance MonadCatch (Adaptor a b)+ -- | Debugger state: -- -- * Keep a mapping from DAP breakpoint ids to internal breakpoint ids@@ -53,10 +57,14 @@ fail a = sendError (ErrorMessage (T.pack a)) Nothing safeDestroyDebugSession :: Adaptor app request ()-safeDestroyDebugSession = void $ do- -- Without forkIO we might kill ourselves first and not kill anything else.- liftBaseDiscard forkIO $- destroyDebugSession `catchError` \ e -> liftIO $ putStrLn ("safeDestroyDebugSession: ignoring missing session: " ++ show e)+safeDestroyDebugSession = do+ destroyDebugSession `catchError` \ e -> liftIO $ putStrLn ("safeDestroyDebugSession: ignoring missing session: " ++ show e)++-- | Thrown from commandDisconnect so the DAP lib disconnects from client.+data DisconnectDAPClientCleanly = DisconnectDAPClientCleanly+ deriving Show++instance Exception DisconnectDAPClientCleanly -------------------------------------------------------------------------------- -- * Utilities
hdb-dap/Development/Debug/Adapter/DAPDebuggee.hs view
@@ -20,14 +20,13 @@ import System.Process import qualified Data.ByteString as BS import qualified Data.Text as T-import qualified Data.Text.IO as T import qualified Data.Text.Encoding as T import Control.Monad.Trans import System.IO+import System.IO.Temp import Control.Monad.Catch import Control.Exception (throwIO, IOException) import Control.Concurrent-import Control.Concurrent.Async (concurrently_) import Control.Monad import Data.Functor.Contravariant @@ -43,6 +42,8 @@ import Network.Socket (socketPort, close) import GHC.Debugger.Debuggee as Debugger import GHC.Debugger.Utils (forwardHandleToLogger)+import qualified Data.HashMap.Strict as HM+import System.Directory (removeFile) data DAPDebuggee = DAPDebuggee { dapdInterpreterSettings :: InterpreterSettings@@ -55,8 +56,8 @@ } -internalNoInTerminalDAPD :: Applicative f => f DAPDebuggee-internalNoInTerminalDAPD+internalNoInTerminalDAPD :: Applicative f => LogAction IO DAPSessionLog -> f DAPDebuggee+internalNoInTerminalDAPD l -- Not using the terminal proxy, but we still want to output our own -- stdout/err (from the internal interpreter) as console events. = do@@ -64,36 +65,41 @@ { interpreterFlags = mkInternalInterpreterFlags , interpreterSetup = mkInternalInterpreterSetup }+ let ld = contramap (ForwardingThreadLog . flip WithSeverity Debug) l pure $ DAPDebuggee interpSettings (pure ())- [ stdoutCaptureThread Nothing, stderrCaptureThread Nothing ]+ [ stdoutCaptureThread ld (const $ pure ()), stderrCaptureThread ld (const $ pure ()) ] (pure ()) -externalNoInTerminalDAPD :: MonadIO f => FilePath -> f DAPDebuggee-externalNoInTerminalDAPD hdbProg = do+externalNoInTerminalDAPD :: MonadIO f => LogAction IO DAPSessionLog -> FilePath -> [String] -> f DAPDebuggee+externalNoInTerminalDAPD l hdbProg extraInterpArgs = do iserv_handles <- liftIO newEmptyMVar let interpSettings = InterpreterSettings- { interpreterFlags = mkExternalInterpreterFlags hdbProg+ { interpreterFlags = mkExternalInterpreterFlags hdbProg extraInterpArgs , interpreterSetup = mkExternalInterpreterSubProcessSetup CreatePipe CreatePipe CreatePipe (putMVar iserv_handles) }+ ld = contramap (ForwardingThreadLog . flip WithSeverity Debug) l pure $ DAPDebuggee interpSettings (pure ())- [\ withAdaptor -> fwdThread iserv_handles (LogAction $ withAdaptor . Output.stdout) (LogAction $ withAdaptor . Output.stderr)+ [ \ withAdaptor -> annotateStackStringIO "External interpreter stdout forwarding" $ do+ (_,Just out,_,_) <- readMVar iserv_handles+ forwardHandleToLogger ld out (LogAction $ withAdaptor . Output.stdout)+ , \ withAdaptor -> annotateStackStringIO "External interpreter stderr forwarding" $ do+ (_,_,Just err,_) <- readMVar iserv_handles+ forwardHandleToLogger ld err (LogAction $ withAdaptor . Output.stderr)+ , \ _withAdaptor -> annotateStackStringIO "External interpreter waiting for process termination" $ do+ (_,_,_,p) <- readMVar iserv_handles+ code <- waitForProcess p+ ld <& "External interpreter process exit code: " <> T.show code ] (pure ())- where- fwdThread iserv_handles logOut logErr = annotateStackStringIO "External interpreter forwarding parent thread" $ do- (_, Just serv_out, Just serv_err, _) <- takeMVar iserv_handles- concurrently_- (annotateStackStringIO "External interpreter stderr forwarding" $ forwardHandleToLogger serv_err logErr)- (annotateStackStringIO "External interpreter stdout forwarding" $ forwardHandleToLogger serv_out logOut) -externalInTerminalDAPD :: MonadIO m => FilePath -> m DAPDebuggee-externalInTerminalDAPD hdbProg+externalInTerminalDAPD :: MonadIO m => LogAction IO DAPSessionLog -> FilePath -> [String] -> m DAPDebuggee+externalInTerminalDAPD _l hdbProg extraInterpArgs -- No additional bookkeeping is needed in this case because GHC will -- naturally have to wait for the external interpreter in order to start execution = liftIO $ do@@ -101,18 +107,21 @@ bracketOnError openSocketAvailablePort Network.Socket.close $ \ sock -> do let interpSettings = InterpreterSettings- { interpreterFlags = mkExternalInterpreterFlags hdbProg+ -- The process is spawned by the DAP client (runInTerminal below), so the+ -- extra args are passed there rather than through these flags.+ { interpreterFlags = mkExternalInterpreterFlags hdbProg [] , interpreterSetup = mkExternalInterpreterFromIOSetup $ annotateStackStringIO "Waiting for an external interpreter run-in-terminal process" $ extInterpFromListeningSocket sock } extInterpPort <- liftIO $ socketPort sock+ tempfile <- liftIO $ emptySystemTempFile "hdb-session.tmp" pure $ DAPDebuggee interpSettings (pure ()) -- When session is killed the socket is closed too.- [\ _ -> forever (threadDelay 100_000_000) `finally` Network.Socket.close sock]+ [\ _ -> forever (threadDelay 100_000_000) `finally` Network.Socket.close sock `finally` removeFile tempfile ] (sendRunInTerminalReverseRequest RunInTerminalRequestArguments { runInTerminalRequestArgumentsKind = Just RunInTerminalRequestArgumentsKindIntegrated@@ -120,19 +129,22 @@ , runInTerminalRequestArgumentsCwd = "" , runInTerminalRequestArgumentsArgs = [T.pack hdbProg, "external-interpreter", "--port", T.pack (show extInterpPort)]- , runInTerminalRequestArgumentsEnv = Nothing+ ++ map T.pack extraInterpArgs+ , runInTerminalRequestArgumentsEnv = Just $ HM.singleton sessionFileEnvVar $ T.pack tempfile , runInTerminalRequestArgumentsArgsCanBeInterpretedByShell = False }) internalInTerminalDAPD :: LogAction IO DAPSessionLog -> FilePath -> Adaptor DebugAdaptorState r DAPDebuggee-internalInTerminalDAPD l hdbProg = do- (syncProxyIn, syncProxyOut, syncProxyErr)- <- liftIO $ (,,) <$> newChan <*> newChan <*> newChan- proxyClientReady <- liftIO $ newEmptyMVar-- (serverPort, serverProxyThread) <- liftIO $- mkServerSideHdbProxy (contramap RunProxyServerLog l)- syncProxyIn syncProxyOut syncProxyErr proxyClientReady+internalInTerminalDAPD l hdbProg = liftIO $ do+ proxyClientReady <- newEmptyMVar+ bracketOnError openSocketAvailablePort close $ \ sock -> do+ serverPort <- socketPort sock+ serverProxyThread <- do+ let ld = contramap (ForwardingThreadLog . flip WithSeverity Debug) l+ writeIn <- stdinForwardAction+ pure $ \debugAdapter -> do+ mkServerSideHdbProxy (contramap RunProxyServerLog l) sock+ writeIn (\ k -> stdoutCaptureThread ld k debugAdapter) (\ k -> stderrCaptureThread ld k debugAdapter) proxyClientReady let interpSettings = InterpreterSettings { interpreterFlags = mkInternalInterpreterFlags , interpreterSetup = mkInternalInterpreterSetup@@ -140,23 +152,21 @@ waitForDebuggee = -- Only start executing after proxy client connects succesfully (#95) takeMVar proxyClientReady+ tempfile <- liftIO $ emptySystemTempFile "hdb-session.tmp" pure $ DAPDebuggee interpSettings waitForDebuggee- [ const serverProxyThread- -- Setup capturing of the process' own stdout and forwarding of the process' own stdin,- -- but only because we're using the internal interpreter!- , stdinForwardThread syncProxyIn- , stdoutCaptureThread (Just syncProxyOut)- , stderrCaptureThread (Just syncProxyErr)- ]+ [ \ dap -> serverProxyThread dap `finally` removeFile tempfile ] -- When using the internal interpreter and 'runInTerminal' is supported -- (the 'RunProxyInTerminal' case), we ask the DAP client to launch the -- `hdb proxy` attached to the user's terminal. The proxy forwards -- input/output from the user terminal to the debugger+debuggee shared process- (sendRunProxyInTerminal hdbProg serverPort)+ (sendRunProxyInTerminal hdbProg serverPort $ HM.singleton sessionFileEnvVar $ T.pack tempfile) +sessionFileEnvVar :: T.Text+sessionFileEnvVar = "SESSIONFILE"+ -------------------------------------------------------------------------------- -- * Logging --------------------------------------------------------------------------------@@ -165,18 +175,15 @@ = DAPSessionSetupLog (WithSeverity SessionSetupLog) | DAPDebuggerLog Debugger.DebuggerLog | RunProxyServerLog (WithSeverity T.Text)-+ | ForwardingThreadLog (WithSeverity T.Text) -------------------------------------------------------------------------------- -- * Capturing stdout, stderr, and writing to self stdin -------------------------------------------------------------------------------- -- | Hijack the current process stdin and forward to it the messages from the given channel-stdinForwardThread :: Chan BS.ByteString -> (DebugAdaptorCont () -> IO ()) -> IO ()-stdinForwardThread syncIn _withAdaptor = do- tid <- myThreadId- labelThread tid "Stdin Forward Thread"-+stdinForwardAction :: IO (BS.ByteString -> IO ())+stdinForwardAction = do -- We need to hijack stdin to write to it -- 1. Create a new pipe from writeEnd->readEnd@@ -186,8 +193,7 @@ _ <- hDuplicateTo readEnd stdin hClose readEnd -- we'll never need to read from readEnd - forever $ do- i <- readChan syncIn+ pure $ \ i -> do -- 3. Write to write-end of the pipe BS.hPut writeEnd i >> hFlush writeEnd @@ -195,38 +201,31 @@ -- NOTE, redirecting the stdout handle is a process-global operation. So this thread -- will capture ANY stdout the debuggee emits. Therefore you should never directly -- write to stdout, but always write to the appropiate handle.-stdoutCaptureThread :: Maybe (Chan BS.ByteString) -> (DebugAdaptorCont () -> IO ()) -> IO ()-stdoutCaptureThread msyncOut withAdaptor = do+stdoutCaptureThread :: LogAction IO T.Text -> (BS.ByteString -> IO ()) -> (DebugAdaptorCont () -> IO ()) -> IO ()+stdoutCaptureThread l msyncOut withAdaptor = do tid <- myThreadId labelThread tid "Stdout Capture Thread"- withInterceptedStdout $ \_ interceptedStdout -> do- forever $ do- line <- liftIO $ T.hGetLine interceptedStdout- case msyncOut of- Nothing -> pure ()- Just syncOut -> writeChan syncOut $ T.encodeUtf8 (line <> T.pack "\n")-- -- Always output to Debug Console- catch- (withAdaptor $ Output.stdout line)- (\(_ :: IOException) ->- throwIO (FailedToWriteToAdaptor line))+ withInterceptedStdout $ \_ -> forwardingCaptured l msyncOut (withAdaptor . Output.stdout) -- | Like 'stdoutCaptureThread' but for stderr-stderrCaptureThread :: Maybe (Chan BS.ByteString) -> (DebugAdaptorCont () -> IO ()) -> IO ()-stderrCaptureThread msyncErr withAdaptor = do+stderrCaptureThread :: LogAction IO T.Text -> (BS.ByteString -> IO ()) -> (DebugAdaptorCont () -> IO ()) -> IO ()+stderrCaptureThread l msyncErr withAdaptor = do tid <- myThreadId labelThread tid "Stderr Capture Thread"- withInterceptedStderr $ \_ interceptedStderr -> do- forever $ do- line <- liftIO $ T.hGetLine interceptedStderr- case msyncErr of- Nothing -> pure ()- Just syncErr -> writeChan syncErr $ T.encodeUtf8 (line <> "\n")+ withInterceptedStderr $ \_ -> forwardingCaptured l msyncErr (withAdaptor . Output.stderr) +forwardingCaptured+ :: LogAction IO T.Text -- ^ debug msg+ -> (BS.ByteString -> IO ()) -- ^ send to proxy+ -> (T.Text -> IO ()) -- ^ send to DAP. + -> Handle -- ^ captured Handle+ -> IO ()+forwardingCaptured l proxy debugConsole intercepted =+ forwardHandleToLogger l intercepted $ LogAction $ \ line -> do+ proxy $ T.encodeUtf8 (line <> "\n") -- Always output to Debug Console catch- (withAdaptor $ Output.stderr line)+ (debugConsole line) (\(_ :: IOException) -> throwIO (FailedToWriteToAdaptor line))
hdb-dap/Development/Debug/Adapter/Evaluation.hs view
@@ -37,8 +37,16 @@ -- | Command for evaluation (includes evaluation-on-hover) commandEvaluate :: DebugAdaptor () commandEvaluate = do- EvaluateArguments {evaluateArgumentsFrameId=_todo{-evaluate expression in specific frame-}, ..} <- getArguments+ EvaluateArguments {evaluateArgumentsFrameId=mdapFrameId, ..} <- getArguments+ sfMap <- stackFrameMap <$> getDebugSession + DidEval er <-+ case mdapFrameId >>= (`IM.lookup` sfMap) of+ Just (StackFrameIx tid frameId) -> do+ sendSync (DoEval (Just (tid, frameId)) (T.unpack evaluateArgumentsExpression))+ Nothing -> do+ sendSync (DoEval Nothing (T.unpack evaluateArgumentsExpression))+ let simpleEvalResp res ty = EvaluateResponse { evaluateResponseResult = res , evaluateResponseType = ty@@ -49,7 +57,6 @@ , evaluateResponseMemoryReference = Nothing } - DidEval er <- sendSync (DoEval (T.unpack evaluateArgumentsExpression)) case er of EvalStopped{} -> error "impossible, execution is resumed automatically for 'DoEval'" EvalAbortedWith e ->@@ -114,7 +121,7 @@ EvalStopped {breakId = Nothing, breakThread} -> sendStoppedEvent defaultStoppedEvent {- stoppedEventAllThreadsStopped = True+ stoppedEventAllThreadsStopped = False -- TODO: Allow configuring "YES" , stoppedEventReason = StoppedEventReasonException , stoppedEventHitBreakpointIds = [] , stoppedEventThreadId = Just $ remoteThreadIntRef breakThread@@ -123,7 +130,7 @@ DAS{breakpointMap} <- getDebugSession sendStoppedEvent defaultStoppedEvent {- stoppedEventAllThreadsStopped = True+ stoppedEventAllThreadsStopped = False -- TODO: Allow configuring "YES", as above. -- could be more precise here by saying "function breakpoint" rather than always "breakpoint" , stoppedEventReason = if stepping then StoppedEventReasonStep
hdb-dap/Development/Debug/Adapter/Exit.hs view
@@ -24,15 +24,23 @@ import DAP import Development.Debug.Adapter+import Development.Debug.Adapter.Interface (sendSync)+import GHC.Debugger.Interface.Messages (Command(TerminateDebuggee), Response (DidTerminate))+import Control.Monad (when)+import Control.Monad.Catch -- | Command terminate (1a) -- -- Terminate the *debuggee* gracefully commandTerminate :: DebugAdaptor () commandTerminate = do- destroyDebugSession -- kills debugger GHC session (which handles stopping the debuggee ext-interp too)+ DidTerminate b <- sendSync TerminateDebuggee+ when b $ do+ safeDestroyDebugSession+ sendTerminatedEvent (TerminatedEvent False) -- we're done debugging now!+ -- the response only acknowledges the command,+ -- does not imply successful termination. sendTerminateResponse- sendTerminatedEvent (TerminatedEvent False) -- we're done debugging now! -- | Command disconnect (1b) --@@ -43,3 +51,4 @@ -- ignore error if session has already been destroyed (e.g. client sends disconnect after terminate) safeDestroyDebugSession sendDisconnectResponse+ throwM DisconnectDAPClientCleanly
hdb-dap/Development/Debug/Adapter/Handles.hs view
@@ -19,6 +19,7 @@ import System.Process import Control.Exception import Control.Concurrent.Async+import GHC.Debugger.Utils (forwardHandleToLogger) handleLogger :: Handle -> IO (LogAction IO T.Text) handleLogger out_handle = do@@ -51,27 +52,29 @@ -- | Intercept stderr, and spawn a thread which forwards the input -- onwards using the supplied IO action.-withInterceptedStderrForwarding :: (T.Text -> IO ())+withInterceptedStderrForwarding :: LogAction IO T.Text+ -> (T.Text -> IO ()) -- ^ All stderr input that is intercepted is forwarded to this thread -> (Handle -> IO ()) -- ^ The continuation receives the REAL STDERR -> IO ()-withInterceptedStderrForwarding write_stderr k = do+withInterceptedStderrForwarding l write_stderr k = do withInterceptedStderr $ \realStderr interceptedStderr -> do- withAsync (forwardingThread write_stderr interceptedStderr) $ \_ -> do+ withAsync (forwardHandleToLogger l interceptedStderr (LogAction write_stderr)) $ \_ -> do k realStderr -- | Intercept stdout, and spawn a thread which forwards the input -- onwards using the supplied IO action. withInterceptedStdoutForwarding :: (T.Text -> IO ()) -- ^ All stdout input that is intercepted is forwarded to this thread- -> (Handle -> IO ())+ -> (Handle -> IO (LogAction IO T.Text, IO ())) -- ^ The continuation receives the REAL STDOUT -> IO ()-withInterceptedStdoutForwarding write_stdout k = do+withInterceptedStdoutForwarding write_stdout mkC = do withInterceptedStdout $ \realStdout interceptedStdout -> do- withAsync (forwardingThread write_stdout interceptedStdout) $ \_ ->- k realStdout+ (l,cont) <- mkC realStdout+ withAsync (forwardHandleToLogger l interceptedStdout (LogAction write_stdout)) $ \_ ->+ cont -------------------------------------------------------------------------------- -- Auxiliary@@ -113,19 +116,6 @@ hFlush originalHandle hDuplicateTo realHandle originalHandle hClose realHandle---- | Thread to read from the intercepted stdout pipe and forward onwards-forwardingThread :: (T.Text -> IO ()) -> Handle -> IO ()-forwardingThread write_action fromPipe = loop- where- loop = do- eof <- hIsEOF fromPipe- if eof- then return ()- else do- line <- T.hGetLine fromPipe- write_action line- loop withPipe :: (Handle -> Handle -> IO r) -> IO r withPipe action = bracket createPipe closeBoth (uncurry action)
hdb-dap/Development/Debug/Adapter/Init.hs view
@@ -23,9 +23,10 @@ import qualified Data.Text as T import qualified System.Process as P import Control.Exception (displayExceptionWithInfo, ExceptionWithContext (ExceptionWithContext), AsyncException (..))-import Control.Monad (when)+import Control.Monad (when, void) import Control.Monad.Except import Control.Monad.Trans+import Control.Monad.Trans.Control (liftBaseDiscard) import Data.Function import Data.Maybe import Data.UUID.V4 qualified as UUID@@ -55,6 +56,8 @@ import Development.Debug.Session.Setup import GHC.Debugger.Debuggee as Debugger import Development.Debug.Adapter.DAPDebuggee+import GHC.Debugger.Monad+import GHC.Debugger.Data.Supervisor -------------------------------------------------------------------------------- -- * Client@@ -78,6 +81,9 @@ -- ^ Additional arguments to pass to the GHC invocation inferred by hie-bios for this project , cradleFile :: Maybe FilePath -- ^ specify cradle file rather than let it be inferred from @entryFile@, relative to @projectRoot@.+ , externalInterpreterArgs :: Maybe [String]+ -- ^ Extra arguments to append to the external interpreter invocation. No+ -- effect when using the internal interpreter. } deriving stock (Show, Eq, Generic) deriving anyclass FromJSON @@ -98,9 +104,9 @@ -- | Initialize debugger -- -- Returns @()@ if successful, throws @InitFailed@ otherwise-initDebugger :: LogAction IO (T.Text,DAPSessionLog) -> DAPServerConf -> InterpreterChoice+initDebugger :: LogAction IO (T.Text,DAPSessionLog) -> Supervisor -> DAPServerConf -> InterpreterChoice -> LaunchArgs -> DebugAdaptor ()-initDebugger l0 servConf interpChoice+initDebugger l0 mainScope servConf interpChoice LaunchArgs{ __sessionId , projectRoot = givenRoot , entryFile = entryFileMaybe@@ -108,6 +114,7 @@ , entryArgs = fromMaybe [] -> entryArgs , extraGhcArgs = fromMaybe [] -> extraGhcArgs , cradleFile+ , externalInterpreterArgs = fromMaybe [] -> externalInterpreterArgs } = do syncRequests <- liftIO newEmptyMVar syncResponses <- liftIO newEmptyMVar@@ -155,7 +162,7 @@ dbgLog <- liftIO $ createDebuggerLogger l dapLogger writeDAPOutput - dapd <- initDAPDebuggee l (hdbProgram servConf) interpChoice+ dapd <- initDAPDebuggee l (hdbProgram servConf) interpChoice externalInterpreterArgs let defaultRunConf = Debugger.RunDebuggerSettings@@ -165,9 +172,8 @@ } absEntryFile = projectRoot /> entryFile daState = DAS{entryFile=absEntryFile,waitForDebuggee = dapdWaitForDebuggee dapd,..}-- registerNewDebugSession sessionId daState $ map (destroyDebugSessionOnException l) $- [ \withAdaptor -> do+ ld = contramap (ForwardingThreadLog . flip WithSeverity Debug) l+ thrds = [ \withAdaptor -> do -- The info here is already taken into account in debugRunner. let GhcInvocation libdir units args = ghcInvocation withAdaptor $@@ -177,12 +183,16 @@ , "args: " <> unwords args ] debuggerThread dbgLog debugRunner defaultRunConf syncRequests syncResponses- , \withAdaptor -> forwardHandleToLogger readDAPOutput $+ , \withAdaptor -> forwardHandleToLogger ld readDAPOutput $ LogAction (\msg -> withAdaptor (Output.neutral msg))- ]- ++- dapdThreads dapd-+ ]+ +++ dapdThreads dapd+ registerNewDebugSession sessionId daState $ (:[]) $ destroyDebugSessionOnException l $ \withAdaptor -> do+ registerForShutdown mainScope $ do+ withSupervisor Nothing $ \sessionScope -> do+ mapM_ (spawn sessionScope Propagate) $ map ($ withAdaptor) thrds+ awaitAll sessionScope Nothing dapdAfterRegister dapd destroyDebugSessionOnException :: LogAction IO DAPSessionLog@@ -199,20 +209,23 @@ _ -> do withAdaptor $ do sendTerminatedEvent (TerminatedEvent False)- safeDestroyDebugSession+ -- Without forkIO we might kill ourselves first and not kill anything else.+ void $ liftBaseDiscard forkIO $+ safeDestroyDebugSession initDAPDebuggee :: LogAction IO DAPSessionLog -> FilePath -> InterpreterChoice+ -> [String] -> DebugAdaptor DAPDebuggee-initDAPDebuggee _ _ InterpreterChoice{runInTerminal = False, internal = True}- = internalNoInTerminalDAPD-initDAPDebuggee _ hdbProg InterpreterChoice{runInTerminal = False, internal = False}- = externalNoInTerminalDAPD hdbProg-initDAPDebuggee _ hdbProg InterpreterChoice{internal = False, runInTerminal = True}- = externalInTerminalDAPD hdbProg-initDAPDebuggee l hdbProg InterpreterChoice{runInTerminal = True, internal = True}+initDAPDebuggee l _ InterpreterChoice{runInTerminal = False, internal = True} _+ = internalNoInTerminalDAPD l+initDAPDebuggee l hdbProg InterpreterChoice{runInTerminal = False, internal = False} extraInterpArgs+ = externalNoInTerminalDAPD l hdbProg extraInterpArgs+initDAPDebuggee l hdbProg InterpreterChoice{internal = False, runInTerminal = True} extraInterpArgs+ = externalInTerminalDAPD l hdbProg extraInterpArgs+initDAPDebuggee l hdbProg InterpreterChoice{runInTerminal = True, internal = True} _ = internalInTerminalDAPD l hdbProg @@ -241,7 +254,9 @@ labelThread tid "Main Debugger Thread" let loop = do req <- takeMVar requests & liftIO- resp <- try (Debugger.execute req)+ -- TODO: remove once interpCmd stops calling `uninterruptibleMask`+ -- while waiting for a reply.+ resp <- interruptible $ try (Debugger.execute req) case resp of Right x -> do liftIO (putMVar replies x)
hdb-dap/Development/Debug/Adapter/Proxy.hs view
@@ -44,6 +44,7 @@ import Development.Debug.Adapter import qualified Control.Exception as E import GHC.Debugger.Interface.Messages (unAbs)+import Data.Text (Text) -- | Fork a new thread to run the server-side of the proxy. --@@ -56,56 +57,53 @@ -- 2.1 Read stdin from the socket and push it to a Chan -- 2.1 Read from a stdout Chan and write to the socket mkServerSideHdbProxy :: LogAction IO (WithSeverity T.Text)- -> Chan BS8.ByteString- -> Chan BS8.ByteString- -> Chan BS8.ByteString- -> MVar ()- -> IO (PortNumber, IO ())-mkServerSideHdbProxy l dbIn dbOut dbErr client_conn_signal =- bracketOnError openSocketAvailablePort close $ \ sock -> do-- port <- socketPort sock-- return $ (port,) $ do+ -> Socket+ -> (BS8.ByteString -> IO ())+ -> ((BS8.ByteString -> IO ()) -> IO ())+ -> ((BS8.ByteString -> IO ()) -> IO ())+ -> MVar ()+ -> IO ()+mkServerSideHdbProxy l sock dbIn dbOut dbErr client_conn_signal = do ignoreIOException $ do myThreadId >>= \tid -> labelThread tid "Debug/Adapter/Proxy: TCP Server"+ port <- socketPort sock runTCPServerWithSocket' sock $ \scket -> do + -- The proxy is machine-local, so we don't need the delays of TCP.+ setSocketOption scket NoDelay 1+ infoMsg (T.pack $ "Connected to client on port " ++ show port ++ "...!") putMVar client_conn_signal () -- signal ready (see #95) race_ (race_ (-- Read stdout from chan and write to socket- ignoreIOException $ do- labelMe "Debug/Adapter/Proxy: Forward stdout"- forever $ do- bs <- readChan dbOut+ ignoreIOException $ dbOut $ \ bs -> do debugMsg (T.pack $ "Writing to socket: " ++ BS8.unpack bs) NBS.sendAll scket bs) (-- Read stderr from chan and write to socket- ignoreIOException $ do- labelMe "Debug/Adapter/Proxy: Forward stderr"- forever $ do- bs <- readChan dbErr+ ignoreIOException $ dbErr $ \ bs -> do debugMsg (T.pack $ "Writing to socket (from stderr): " ++ BS8.unpack bs) NBS.sendAll scket bs)) (-- Read stdin from socket and write to chan let- loop = do+ loop = join $ mask_ $ do bs <- NBS.recv scket 4096 if BS8.null bs then do debugMsg (T.pack "Connection to client was closed.")- close scket+ -- Let runTCPServer close scket.+ pure $ pure () else do debugMsg (T.pack $ "Read from socket: " ++ BS8.unpack bs)- writeChan dbIn bs >> loop+ dbIn bs+ pure loop in ignoreIOException $ do labelMe "Debug/Adapter/Proxy: Read stdin" loop) where+ -- TODO: more specific catching? ignoreIOException a = catch a $ \(e::IOException) -> infoMsg (T.pack $ "Ignoring connection broken to proxy client: " ++ show e) debugMsg msg = l <& WithSeverity msg Debug@@ -116,12 +114,14 @@ runTCPServerWithSocket' :: Socket -> (Socket -> IO a1) -> IO a2 runTCPServerWithSocket' sock server = do let- serverLoop = forever $ E.bracketOnError (accept sock) (close . fst) $+ gClose conn = gracefulClose conn 5000+ serverLoop = E.bracketOnError (accept sock) (gClose . fst) $ \(conn, _peer) ->+ -- TODO: what is mask_ achieving here? does it mean we can drop E.bracketOnError? mask_ $ withAsyncWithUnmask (\ unmask -> unmask (labelMe "TCP Server handler" >> server conn)- `finally` gracefulClose conn 5000)+ `finally` gClose conn) (const serverLoop) serverLoop @@ -171,34 +171,36 @@ Nothing -> pure () Just inv -> putStrLn $ "Running the debugger input/output proxy for the following debuggee execution:\n\n\n " ++ inv ++ "\n\n"+ let settings = defaultSettings { settingsOpenClientSocket = openClientSocketWithOptions [(NoDelay,1)] } - catch (- runTCPClient "127.0.0.1" (show port) $ \sock -> do+ runTCPClientWithSettings settings "127.0.0.1" (show port) $ \sock -> do -- Forward stdin to sock concurrently_- (catch (forever $ do- str <- BS8.hGetLine stdin- NBS.sendAll sock (str <> BS8.pack "\n")- ) $ \(_e::IOException) -> return ()) -- connection dropped, just exit.+ (handleIOError (pure ()) $ -- connection dropped or stdin closed, just stop.+ forever $ mask_ $ do+ str <- BS8.hGetLine stdin+ NBS.sendAll sock (str <> BS8.pack "\n")) (-- Forward stdout from sock- catch (forever $ do- msg <- NBS.recv sock 4096- if BS8.null msg- then do- l <& WithSeverity (T.pack "Exiting...") Info- close sock- exitSuccess- else BS8.hPut stdout msg >> hFlush stdout- ) $ \(_e::IOException) -> return ()) -- connection dropped, just exit.-- ) $ \(_e::IOException) -> do- hPutStrLn stderr "Failed to connect to debugger server proxy -- did the debuggee compile and start running successfully?"+ handleIOError (pure ()) $ -- connection dropped, just stop.+ forever $ mask_ $ do+ msg <- NBS.recv sock 4096+ if BS8.null msg+ then do+ l <& WithSeverity (T.pack "Exiting...") Info+ -- Let runTCPClient* do it gracefully.+ -- close sock+ exitSuccess+ else+ BS8.hPut stdout msg >> hFlush stdout+ )+ where+ handleIOError k m = catch m (\(_e :: IOException) -> k) -- | Send a 'runInTerminal' reverse request to the DAP client -- with the @hdb proxy@ invocation-sendRunProxyInTerminal :: FilePath -> PortNumber -> DebugAdaptor ()-sendRunProxyInTerminal hdbProg port = do+sendRunProxyInTerminal :: FilePath -> PortNumber -> H.HashMap Text Text -> DebugAdaptor ()+sendRunProxyInTerminal hdbProg port env = do DAS { entryFile , entryPoint , entryArgs@@ -211,6 +213,6 @@ , runInTerminalRequestArgumentsTitle = Just debuggee_inv , runInTerminalRequestArgumentsCwd = "" , runInTerminalRequestArgumentsArgs = [T.pack hdbProg, "proxy", "--port", T.pack (show port)]- , runInTerminalRequestArgumentsEnv = Just (H.singleton "DEBUGGEE_INVOCATION" debuggee_inv)+ , runInTerminalRequestArgumentsEnv = Just (H.singleton "DEBUGGEE_INVOCATION" debuggee_inv <> env ) , runInTerminalRequestArgumentsArgsCanBeInterpretedByShell = False }
hdb-dap/Development/Debug/Adapter/Server.hs view
@@ -43,6 +43,10 @@ import qualified GHC.Utils.Logger as GHC import GHC.Debugger.Debuggee (DebuggerLog(..)) import qualified GHC.Plugins as GHC+import Control.Monad.Catch+import Control.Exception+import Data.String+import GHC.Debugger.Data.Supervisor -------------------------------------------------------------------------@@ -109,7 +113,21 @@ , supportsSteppingGranularity = False , supportsInstructionBreakpoints = False , supportsExceptionFilterOptions = False+#if MIN_VERSION_ghc(9,14,3)+ , supportsSingleThreadExecutionRequests = True+#else+ -- GHC before 9.14.3 used a global break action with a single resume MVar+ -- that was shared across all threads, leading to all kinds of+ -- unpredictable behavior. That, and the resume context wasn't returned+ -- when hitting a breakpoint (just pushed to a global `ic_resume`), so we+ -- couldn't use the right `Resume` context per-thread.+ --+ -- TL;DR we can't support proper multi-threaded debugging with 9.14.2, so+ -- no point in having per-thread requests either. Note: this doesn't+ -- prevent the debuggee from launching threads -- unexpected things will+ -- still happen. , supportsSingleThreadExecutionRequests = False+#endif } ServerConfig <$> do fromMaybe hostDefault <$> lookupEnv "DAP_HOST"@@ -117,6 +135,13 @@ <*> pure capabilities <*> pure True +respondWithErrorOnException :: Adaptor app request a -> Adaptor app request a+respondWithErrorOnException m = m `Control.Monad.Catch.catch` \ e -> do+ unless (isJust $ fromException @DisconnectDAPClientCleanly e) $ do+ sendError (fromString (displayExceptionWithInfo e)) Nothing+ safeDestroyDebugSession+ throwM e+ -------------------------------------------------------------------------------- -- * Talk --------------------------------------------------------------------------------@@ -125,12 +150,13 @@ -- The core logic of communicating between the client <-> adaptor <-> debugger -- is implemented in this function. talk :: LogAction IO DAPLog+ -> Supervisor -> DAPServerConf -> Bool -- ^ Prefer internal interpreter -> Command -> DebugAdaptor () ---------------------------------------------------------------------------------talk l servConf prefer_internal_interpreter = \ case+talk l tids servConf prefer_internal_interpreter = \ case CommandInitialize -> do sendInitializeResponse --------------------------------------------------------------------------------@@ -146,7 +172,7 @@ let runInTerminal = fromMaybe False $ supportsRunInTerminalRequest =<< clientCaps #endif - initDebugger (cmapM (\ (sId,x) -> DAPSessionLog sId <$> myThreadId <*> pure x) l) servConf+ initDebugger (cmapM (\ (sId,x) -> DAPSessionLog sId <$> myThreadId <*> pure x) l) tids servConf InterpreterChoice {runInTerminal, internal = prefer_internal_interpreter} launch_args @@ -237,9 +263,9 @@ -- -- See Note [UniqueSupply is process global]. runHDBServer :: LogAction IO DAPLog -> DAPServerConf -> IO ()-runHDBServer l servConf@DAPServerConf{ dapServerConfig = config } = do+runHDBServer l servConf@DAPServerConf{ dapServerConfig = config } = withSupervisor Nothing $ \ scope -> do runDAPServerWithLogger (contramap DAPLibraryLog l) config- (talk l servConf False)+ (talk l scope servConf False) (ack l ) --------------------------------------------------------------------------------@@ -250,6 +276,7 @@ = DAPSessionLog !SessionId !ThreadId DAPSessionLog | DAPLaunchLog (WithSeverity T.Text) | DAPLibraryLog DAP.DAPLog+ | DAPStdoutForwardingLog (WithSeverity T.Text) logSessionLog :: Show a => LogAction IO Text -> Severity -> WithSeverity a -> IO () logSessionLog l threshold (WithSeverity msg sev)@@ -304,7 +331,9 @@ (DAPSessionSetupLog sessionLog) -> logSessionLog l1 threshold sessionLog (DAPDebuggerLog debuggerLog) -> logDebuggerLog logGhcLog1 l1 threshold debuggerLog (RunProxyServerLog sev_msg) -> defaultLog l1 threshold sev_msg+ (ForwardingThreadLog sev_msg) -> defaultLog l1 threshold sev_msg DAPLaunchLog sev_msg -> defaultLog (cmapM renderWithTimestamp l) threshold sev_msg+ DAPStdoutForwardingLog sev_msg -> defaultLog (cmapM renderWithTimestamp l) threshold sev_msg DAPLibraryLog t | convert t.severity >= threshold -> l <& DAP.renderDAPLog t | otherwise -> pure ()
hdb-dap/Development/Debug/Adapter/Stepping.hs view
@@ -1,4 +1,11 @@-module Development.Debug.Adapter.Stepping where+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE LambdaCase #-}+module Development.Debug.Adapter.Stepping+ ( commandContinue+ , commandNext+ , commandStepIn+ , commandStepOut+ ) where import DAP @@ -10,27 +17,39 @@ commandContinue :: DebugAdaptor () commandContinue = do+ ContinueArguments {..} <- getArguments+ let rtw = bool_single_thrd continueArgumentsSingleThread+ let rsm = DoResume (RemoteThreadId continueArgumentsThreadId) ResumeNoStep rtw resetObjectReferences- DidContinue er <- sendInterleaved DoContinue $- sendContinueResponse (ContinueResponse True)+ DidResume er <- sendInterleaved rsm $+ sendContinueResponse (ContinueResponse (maybe True not continueArgumentsSingleThread)) handleEvalResult False er commandNext :: DebugAdaptor () commandNext = do+ NextArguments {..} <- getArguments+ let rtw = bool_single_thrd nextArgumentsSingleThread+ let rsm = DoResume (RemoteThreadId nextArgumentsThreadId) ResumeStepLocal rtw resetObjectReferences- DidStep er <- sendInterleaved DoStepLocal sendNextResponse+ DidResume er <- sendInterleaved rsm sendNextResponse handleEvalResult True er commandStepIn :: DebugAdaptor () commandStepIn = do+ StepInArguments {..} <- getArguments+ let rtw = bool_single_thrd stepInArgumentsSingleThread+ let rsm = DoResume (RemoteThreadId stepInArgumentsThreadId) ResumeSingleStep rtw resetObjectReferences- DidStep er <- sendInterleaved DoSingleStep sendStepInResponse+ DidResume er <- sendInterleaved rsm sendStepInResponse handleEvalResult True er commandStepOut :: DebugAdaptor () commandStepOut = do+ StepOutArguments {..} <- getArguments+ let rtw = bool_single_thrd stepOutArgumentsSingleThread+ let rsm = DoResume (RemoteThreadId stepOutArgumentsThreadId) ResumeStepOut rtw resetObjectReferences- DidStep er <- sendInterleaved DoStepOut sendStepOutResponse+ DidResume er <- sendInterleaved rsm sendStepOutResponse handleEvalResult True er --------------------------------------------------------------------------------@@ -43,3 +62,12 @@ , breakpointMap = mempty , variablesMap = mempty }++bool_single_thrd :: Maybe Bool -> ResumeTheWorld+bool_single_thrd = bool_mby ResumeJustThisThread ResumeTheWorld++bool_mby :: a {- if Just True -} -> a {- if Nothing or Just False -} -> Maybe Bool -> a+bool_mby l r = \case+ Nothing -> r+ Just False -> r+ Just True -> l
hdb-dap/Development/Debug/Session/Setup.hs view
@@ -206,7 +206,7 @@ unwrapCradleResult :: MonadError String m => [Char] -> HIE.CradleLoadResult a -> m a unwrapCradleResult m = \case HIE.CradleNone -> throwError $ "HIE.CradleNone\n" ++ m- HIE.CradleFail err -> throwError $ unlines (HIE.cradleErrorStderr err) ++ "\n" ++ m+ HIE.CradleFail err -> throwError $ show err ++ "\n" ++ m HIE.CradleSuccess x -> return x extractUnits :: [String] -> ([String], [String])
hdb/Development/Debug/Interactive.hs view
@@ -21,6 +21,7 @@ import GHC.Debugger import Control.Monad import Data.List (intercalate)+import Data.Maybe (fromJust) import qualified Data.Maybe as Maybe import GHC.Debugger.Debuggee (DebuggerLog) @@ -134,14 +135,19 @@ printResponse :: Response -> InteractiveDM () printResponse = \case- DidEval er -> outputEvalResult er+ DidEval er -> outputStrLn (showEvalResult er)+ -- don't remember thread context for eval requests+ --+ -- FIXME: we should track which threads we've started and which have been+ -- stopped per-thread rather than with a global one, then we could do+ -- this more uniformly. DidSetBreakpoint bf -> outputStrLn $ show bf DidRemoveBreakpoint bf -> outputStrLn $ show bf DidGetBreakpoints mb_span -> outputStrLn $ show mb_span DidClearBreakpoints -> outputStrLn "Cleared all breakpoints."- DidContinue er -> outputEvalResult er- DidStep er -> printEvalResult er+ DidResume er -> outputEvalResult er DidExec er -> outputEvalResult er+ DidTerminate b -> outputStrLn $ if b then "Terminated." else "Could not terminate." GotThreads threads -> outputStrLn $ show threads GotStacktrace stackframes -> outputStrLn $ show stackframes GotScopes scopeinfos -> outputStrLn $ show scopeinfos@@ -152,7 +158,17 @@ Initialised -> pure () where outputEvalResult er = do- outputStrLn (showEvalResult er)+ case er of+ EvalStopped{breakThread} -> do+ cmd <- lift $ gets runLastCommand+ if isStepCmd cmd then do+ -- Always print the stopped scope if stopped?+ -- FIXME: Figure out the CLI interface.+ out <- lift . lift $ execute (GetScopes breakThread 0)+ printResponse out+ else do+ outputStrLn (showEvalResult er)+ _ -> outputStrLn (showEvalResult er) maybeShowException er rememberThreadContext er @@ -163,7 +179,7 @@ rememberThreadContext er = case er of EvalCompleted{} -> lift $ modify' (\ ctx -> ctx { runCurrentThread = Nothing } )- EvalException{} -> pure () -- TODO: why does this not have a thread associated?+ EvalException{} -> pure () -- TODO: exceptions are still not signaling per-thread EvalStopped{breakThread} -> lift $ modify' (\ ctx -> ctx { runCurrentThread = Just breakThread } ) EvalAbortedWith{} -> lift $ modify' (\ ctx -> ctx { runCurrentThread = Nothing } ) @@ -189,13 +205,10 @@ _ -> outputStrLn ("Unexpected response when fetching fields for " ++ varName) >> pure [] fetchFields _ _ _ = pure [] -printEvalResult :: EvalResult -> InteractiveDM ()-printEvalResult EvalStopped{..} = do- out <- lift . lift $ execute (GetScopes breakThread 0)- printResponse out- when (breakId == Nothing) $- showExceptionDetails breakThread-printEvalResult er = outputStrLn $ showEvalResult er+ isStepCmd (Just (DoResume _ s _))+ | ResumeNoStep <- s = False+ | otherwise = True+ isStepCmd _ = False showEvalResult :: EvalResult -> String showEvalResult (EvalCompleted{..}) = resultVal@@ -318,23 +331,23 @@ ( progDesc "Run the debuggee" ) ) <> Options.Applicative.command "next"- ( info (pure $ Do DoStepLocal)+ ( info (pure $ Do $ DoResume (fromJust ctx.runCurrentThread) ResumeStepLocal ResumeTheWorld) ( progDesc "Step over to the next line" ) ) <> Options.Applicative.command "step"- ( info (pure $ Do DoSingleStep)+ ( info (pure $ Do $ DoResume (fromJust ctx.runCurrentThread) ResumeSingleStep ResumeTheWorld) ( progDesc "Step-in to the next immediate location" ) ) <> Options.Applicative.command "finish"- ( info (pure $ Do DoStepOut)+ ( info (pure $ Do $ DoResume (fromJust ctx.runCurrentThread) ResumeStepOut ResumeTheWorld) ( progDesc "Step-out of the current function into the caller/its continuation" ) ) <> Options.Applicative.command "continue"- ( info (pure $ Do DoContinue)+ ( info (pure $ Do $ DoResume (fromJust ctx.runCurrentThread) ResumeNoStep ResumeTheWorld) ( progDesc "Continue executing from the current breakpoint" ) ) <> Options.Applicative.command "print"- ( info (Do . DoEval . unwords <$> many (argument str ( metavar "EXPRESSION"+ ( info (Do . DoEval ((,0) <$> ctx.runCurrentThread) . unwords <$> many (argument str ( metavar "EXPRESSION" <> help "Expression to evaluate in the current context" ))) ( progDesc "Evaluate an expression in the current context" ) ) <>
hdb/Development/Debug/Options/Parser.hs view
@@ -9,6 +9,7 @@ import Options.Applicative hiding (command) import Data.Version+import System.Environment (getArgs) import qualified Options.Applicative import qualified Paths_haskell_debugger as P @@ -195,6 +196,18 @@ -- | Parse command line arguments parseHdbOptions :: IO HdbOptions-parseHdbOptions = customExecParser- defaultPrefs{prefShowHelpOnError = True, prefShowHelpOnEmpty = True}- hdbParserInfo+parseHdbOptions = do+ args <- normalizeExternalInterpreterArgs <$> getArgs+ handleParseResult $ execParserPure+ defaultPrefs{prefShowHelpOnError = True, prefShowHelpOnEmpty = True}+ hdbParserInfo+ args++-- | Rewrite the arguments GHC passes when spawning the custom external+-- interpreter (@\<writefd\> \<readfd\> --external-interpreter [extra args...]@)+-- into the canonical @external-interpreter \<writefd\> \<readfd\> [extra args...]@+-- form, so 'extInterpParser' handles it. See Note [Custom external interpreter].+normalizeExternalInterpreterArgs :: [String] -> [String]+normalizeExternalInterpreterArgs (writeFd : readFd : "--external-interpreter" : rest) =+ "external-interpreter" : writeFd : readFd : rest+normalizeExternalInterpreterArgs args = args
hdb/Main.hs view
@@ -5,7 +5,6 @@ import System.Process import System.Environment-import Control.Exception (bracket, uninterruptibleMask, bracketOnError) import Control.Exception.Backtrace import DAP@@ -37,15 +36,31 @@ import qualified GHCi.Message as GHCi import GHC.Debugger.Monad (RunDebuggerSettings(..))+import Development.Debug.Adapter.DAPDebuggee (sessionFileEnvVar) import Development.Debug.Options (HdbOptions(..)) import Development.Debug.Options.Parser (parseHdbOptions) import Development.Debug.Adapter.Proxy import Development.Debug.Interactive+ import GHC.Stack.Annotation (annotateCallStackIO) import GHC.Utils.Logger (defaultLogActionWithHandles) import Development.Debug.Session.Setup (hieDebugRunner) import GHC.Debugger.Debuggee (mkCliInterpreterSettings) import GHC.Debugger.Session (initUniqSupplyIO)+import GHC.Conc (labelThread)+import Control.Concurrent+import Control.Concurrent.Async+import Control.Exception+import Control.Monad (when, join, void)+import qualified Colog.Core as Logger+import Data.List (isPrefixOf)+import System.Directory (doesFileExist)+import System.IO.Error+#ifdef MIN_VERSION_unix+import System.Posix.Signals+#endif+import System.Timeout (timeout)+import GHC.Debugger.Data.Supervisor #if MIN_VERSION_ghc(9,15,0) import GHC.Debugger.Runtime.Interpreter.Custom (dbgInterpCmdHandler)@@ -54,20 +69,14 @@ -------------------------------------------------------------------------------- main :: IO ()-main = do+main = handleSigTermTopLevel $ do setBacktraceMechanismState CostCentreBacktrace False setBacktraceMechanismState HasCallStackBacktrace True - allArgs <- getArgs- hdbOpts <- case allArgs of- [writeFd, readFd, "--external-interpreter"] ->- -- Special case to detect --external-interpreter in the third- -- position. If we could specify -opti options to put *before* the- -- descriptors we could get rid of this.- pure (HdbExternalInterpreter (read writeFd) (read readFd) Error)- _ -> parseHdbOptions+ hdbOpts <- parseHdbOptions case hdbOpts of- HdbDAPServer{port, internalInterpreter, disableIpeBacktraces} -> do+ HdbDAPServer{port, internalInterpreter, disableIpeBacktraces} -> withSupervisor Nothing $ \ scope -> do+ setBacktraceMechanismState IPEBacktrace (not disableIpeBacktraces) config <- getConfig port -- the same program invoked with `external-interpreter` serves as the external interpreter@@ -84,8 +93,9 @@ redirectRealStdout internalInterpreter $ \realStdout -> do hSetBuffering realStdout LineBuffering l <- contramap DAPLog <$> mainLogger hdbOpts.verbosity realStdout- runDAPServerWithLogger (contramap DAPLibraryLog l) config- (talk l servConf internalInterpreter)+ let ld = contramap (DAPStdoutForwardingLog . flip WithSeverity Debug) l+ pure . (ld,) $ runDAPServerWithLogger (contramap DAPLibraryLog l) config+ (respondWithErrorOnException . talk l scope servConf internalInterpreter) (ack l ) HdbCLI{..} -> do setBacktraceMechanismState IPEBacktrace (not disableIpeBacktraces)@@ -101,22 +111,32 @@ , interpreterSettings = cliInterpSettings } runIDM (contramap InteractiveLog l) entryPoint entryFile entryArgs extraGhcArgs cradleFile runConf debugInteractive- HdbProxy{port} -> do+ HdbProxy{port} -> handleNoHostServer $ do setBacktraceMechanismState IPEBacktrace True l <- mainLogger hdbOpts.verbosity stdout- runInTerminalHdbProxy (contramap RunProxyClientLog l) port- HdbExternalInterpreter{writeFd, readFd} -> do+ runInTerminalHdbProxy (contramap RunProxyClientLog l) port `onConnectionError` throwIO NoHostServer+ HdbExternalInterpreter{writeFd, readFd} -> labelEIMain $ flip withStubbornAsync wait $ do inh <- GHCi.readGhcHandle (show readFd) outh <- GHCi.readGhcHandle (show writeFd) runExternalInterpreterServer inh outh hdbOpts.verbosity- HdbExternalInterpreterPort{port} -> do+ HdbExternalInterpreterPort{port} -> labelEIMain $ flip withStubbornAsync wait $ handleNoHostServer $ do pid <- getCurrentPid- withExternalInterpreterPort (fromIntegral port) $ \h -> do+ let l = externalLogger hdbOpts.verbosity+ withExternalInterpreterPort l (fromIntegral port) $ \h -> do hPutStrLn h (show pid) hFlush h runExternalInterpreterServer h h hdbOpts.verbosity where+ labelEIMain m = do+ mid <- myThreadId+ labelThread mid "main of Ext. Interpreter Server"+ m+ externalLogger verbosity =+ filterBySeverity verbosity getSeverity+ $ getMsg Logger.>$< Logger.logStringStderr runExternalInterpreterServer inh outh verbosity = do+ mid <- myThreadId+ labelThread mid "Ext. Interpreter Server" GHCi.installSignalHandlers pipe <- GHCi.mkPipeFromHandles inh outh let verbose = verbosity <= Info -- Debug || Info@@ -130,10 +150,18 @@ -- we cannot allow any async exceptions while communicating, because -- we will lose sync in the protocol, hence uninterruptibleMask. - withExternalInterpreterPort :: PortNumber -> (Handle -> IO a) -> IO a- withExternalInterpreterPort port k = do- bracket (mkHandleFromPortSock "127.0.0.1" port) hClose $ \ h -> do+ withExternalInterpreterPort :: LogAction IO (WithSeverity String) -> PortNumber -> (Handle -> IO a) -> IO a+ withExternalInterpreterPort l port k = do+ bracket (mkHandleFromPortSock "127.0.0.1" port) hCloseGracefully $ \ h -> do annotateCallStackIO $ k h+ where+ hCloseGracefully h = do+ catchNoPropagate (hClose h) $ \ x@(ExceptionWithContext _ e) ->+ if ioeGetLocation e == "hClose" && ioeGetHandle e == Just h+ then l <& ("withExternalInterpreterPort: "+ ++ displayExceptionWithInfo (toException x))+ `WithSeverity` Logger.Debug+ else rethrowIO x mkHandleFromPortSock :: HostName -> PortNumber -> IO Handle mkHandleFromPortSock host port = do@@ -146,7 +174,7 @@ (\sock -> do -- Don't delay, avoids batching setSocketOption sock NoDelay 1- connect sock (addrAddress addr)+ connect sock (addrAddress addr) `onConnectionError` throwIO NoHostServer h <- socketToHandle sock ReadWriteMode hSetBuffering h NoBuffering return h)@@ -167,8 +195,61 @@ withInterceptedStdoutForwarding (\interceptedOut -> T.hPutStrLn stderr ("[INTERCEPTED STDOUT] " <> interceptedOut)) (\realStdout -> k realStdout)- | otherwise = k stdout+ | otherwise = join $ snd <$> k stdout +handleSigTermTopLevel :: IO () -> IO ()+handleSigTermTopLevel m = flip catch (\ SigTerm -> return ()) $ do+ mainTid <- myThreadId+#ifdef MIN_VERSION_unix+ _ <- installHandler sigTERM (Catch $ throwTo mainTid SigTerm) Nothing+#endif+ m++data SigTerm = SigTerm+ deriving Show++instance Exception SigTerm where+ toException = asyncExceptionToException+ fromException = asyncExceptionFromException++-- | Like @withAsync@ but using `timeout 1s cancel/cancelWith` to cleanup the+-- Async than cancelUninterruptible.+withStubbornAsync :: IO a -> (Async a -> IO b) -> IO b+withStubbornAsync m k =+ mask $ \restore -> do+ a <- async m+ x <- restore (k a) `catchNoPropagate` \ (e :: ExceptionWithContext SomeException) -> do+ -- might shutdown an evaluation more gently than just exiting+ -- restore is needed for the timeout to work properly.+ void $ timeout 1_000_000 (restore $ cancelWith a e)+ rethrowIO e+ void $ timeout 1_000_000 (restore $ cancel a)+ return x++handleNoHostServer :: IO () -> IO ()+handleNoHostServer m =+ catch m $ \NoHostServer -> do+ ms <- lookupEnv $ T.unpack sessionFileEnvVar+ let fallback = hPutStrLn stderr "Could not connect to debug adapter server. Check Haskell Debugger logs to determine what went wrong."+ case ms of+ Nothing -> fallback+ Just s -> do+ b <- doesFileExist s+ when b $ fallback++onConnectionError :: IO () -> IO () -> IO ()+onConnectionError m k =+ catchNoPropagate m $ \case+ ExceptionWithContext _ e+ | isDoesNotExistError e+ && "Network.Socket.connect:" `isPrefixOf` ioeGetLocation e+ -> k+ x -> rethrowIO x++data NoHostServer = NoHostServer+ deriving Show++instance Exception NoHostServer --------------------------------------------------------------------------------
test/golden/T79/T79.ghc-1001.hdb-stdout view
@@ -1,5 +1,4 @@ cabal init ... > cabal-init.log 2>1- [1 of 2] Compiling Main ( <TEMPORARY-DIRECTORY>/app/Main.hs, <TEMPORARY-DIRECTORY>/.hdb-cache/<CACHE-ENTRY>/Main.gbc )[T79-tmp-0.1.0.0-inplace-T79-tmp] (hdb) Hello, Haskell! ()
test/golden/T79/T79.ghc-914.hdb-stdout view
@@ -1,5 +1,4 @@ cabal init ... > cabal-init.log 2>1- [1 of 2] Compiling Main ( <TEMPORARY-DIRECTORY>/app/Main.hs, interpreted )[T79-tmp-0.1.0.0-inplace-T79-tmp] (hdb) Hello, Haskell! ()
test/golden/T79/T79.hdb-test view
@@ -1,6 +1,6 @@ #We don't care to test the output of cabal init, but it might be helpful for debugging. LOGFILE=cabal-init.log-echo "cabal init ... > $LOGFILE 2>1\n" && cabal init -m -n -d base -p T79-tmp > $LOGFILE 2>1 && $HDB app/Main.hs <<'EOF'+echo "cabal init ... > $LOGFILE 2>1" && cabal init -m -n -d base -p T79-tmp > $LOGFILE 2>1 && $HDB app/Main.hs <<'EOF' run exit EOF
test/haskell/Main.hs view
@@ -1,7 +1,7 @@-{-# LANGUAGE LambdaCase, OverloadedStrings, ViewPatterns, QuasiQuotes, CPP #-}+{-# LANGUAGE LambdaCase, OverloadedStrings, ViewPatterns, QuasiQuotes, CPP, RecordWildCards #-} module Main (main) where -import Data.List (isSuffixOf, isInfixOf)+import Data.List (isSuffixOf, isInfixOf, stripPrefix) import qualified Data.Set as Set import Text.RE.TDFA.Text.Lazy import Text.Printf@@ -20,6 +20,7 @@ import Control.Exception import Test.Tasty+import Test.Tasty.Runners qualified as Tasty import Test.Tasty.ExpectedFailure import Test.Tasty.Golden as G import Test.Tasty.Golden.Advanced as G@@ -39,6 +40,7 @@ import Test.Integration.Evaluate (evaluateTests) import Test.Integration.StackTrace (stackTraceTests) import Test.Integration.SelfDebug (selfDebugTests)+import Test.Integration.Threads (threadsTests) import Test.Utils import qualified Data.Char as C import qualified Data.Text as T@@ -77,7 +79,8 @@ let intinterp_goldens = map (mkTest ("--internal-interpreter " ++ baseFlags)) testsForInternal let individualTimeout = 5*60*1_000_000 - defaultMain $ localOption (mkTimeout individualTimeout) $+ defaultMain $ localOption (mkTimeout individualTimeout) $ wrapTest+ (fmap $ deleteLongDescOnSuccess . relabelExpectedFail . showExceptionsWithInfo) $ testGroup "Tests" [ testGroup "Golden tests" default_goldens ,@@ -105,7 +108,39 @@ , evaluateTests , stackTraceTests , selfDebugTests+ , threadsTests ]+++showExceptionsWithInfo :: Tasty.Result -> Tasty.Result+showExceptionsWithInfo x@Tasty.Result{..} =+ case resultOutcome of+ Tasty.Failure (Tasty.TestThrewException e) ->+ x { Tasty.resultDescription = "Exception: " ++ displayExceptionWithInfo e+ }+ _ -> x+++-- | No reason to see lots of output for a Success (e.g. an expected failure)+deleteLongDescOnSuccess :: Tasty.Result -> Tasty.Result+deleteLongDescOnSuccess = silenceDiff+ where+ silenceDiff x@Tasty.Result{..} =+ case resultOutcome of+ Tasty.Success -> Tasty.Result{Tasty.resultDescription = (if null resultShortDescription then id else const "") resultDescription, ..}+ Tasty.Failure{} -> x++-- | Replaces "FAIL" with "ExpectedFail" at the start of the short description of a Success.+--+-- This way only a Failure's short description will start with "FAIL", and will+-- be easier to tell apart in logs.+relabelExpectedFail :: Tasty.Result -> Tasty.Result+relabelExpectedFail r@Tasty.Result{..} =+ case resultOutcome of+ Tasty.Failure{} -> r+ Tasty.Success -> case stripPrefix "FAIL" resultShortDescription of+ Nothing -> r+ Just rest -> Tasty.Result{resultShortDescription = "ExpectedFail" ++ rest, ..} -- | Receives as an argument the path to the @*.hdb-test@ which contains the -- shell invocation for running
test/haskell/Test/DAP.hs view
@@ -42,9 +42,24 @@ -- fill as needed; some parts of the highest level DSL will prefer NOT to be sync. next, stepIn :: TestDAP ()-next = void . sync $ nextRequest @Value @Value Null-stepIn = void . sync $ stepInRequest @Value @Value Null+next = nextThread =<< getCurrentActiveThread+stepIn = stepInThread =<< getCurrentActiveThread +nextThread, stepInThread :: Int -> TestDAP ()+nextThread tid = void . sync $ nextRequest @NextArguments @Value $+ NextArguments+ { DAP.nextArgumentsThreadId = tid+ , DAP.nextArgumentsSingleThread = Nothing+ , DAP.nextArgumentsGranularity = Nothing+ }+stepInThread tid = void . sync $ stepInRequest @StepInArguments @Value $+ StepInArguments+ { stepInArgumentsThreadId = tid+ , stepInArgumentsSingleThread = Nothing+ , stepInArgumentsTargetId = Nothing+ , stepInArgumentsGranularity = Nothing+ }+ threads :: TestDAP [Thread] threads = do Response{responseBody=Just ThreadsResponse{threads=ts}} <- sync threadsRequest@@ -206,6 +221,7 @@ data VarsView = VarsView { varsViewDesc :: String , varsViewVars :: M.Map T.Text [Variable] }+ deriving Show mkVarsView :: String -> [Variable] -> VarsView mkVarsView ctxDesc vs = VarsView@@ -232,17 +248,17 @@ fetchScopeVarsOfFrame :: Int -> T.Text -> TestDAP VarsView fetchScopeVarsOfFrame frameIx scopeName_ = do- Response{responseBody=Just ThreadsResponse{threads=t:_}} <- sync threadsRequest- Response{responseBody=Just StackTraceResponse{stackFrames=frames}} <- sync $ stackTraceRequest $- StackTraceArguments- { DAP.stackTraceArgumentsThreadId = threadId t- , DAP.stackTraceArgumentsStartFrame = Nothing- , DAP.stackTraceArgumentsLevels = Nothing- , DAP.stackTraceArgumentsFormat = Nothing- }+ tid <- getCurrentActiveThread++ ts <- Test.DAP.threads+ unless (tid `elem` map threadId ts) $+ liftIO $ assertFailure $+ "current active thread (" ++ show tid +++ ")is no longer in the listed threads: " ++ show ts++ frames <- Test.DAP.stackTrace tid Just fr <- pure $ frames List.!? frameIx- Response{responseBody=Just ScopesResponse{scopes=scs}} <- sync $ scopesRequest $- ScopesArguments { DAP.scopesArgumentsFrameId = stackFrameId fr }+ scs <- Test.DAP.scopes (stackFrameId fr) case List.find ((== scopeName_) . scopeName) scs of Nothing -> liftIO $ assertFailure $ "fetchScopeVars: scope " ++ show scopeName_@@ -251,6 +267,27 @@ vs <- fetchChildren (scopeVariablesReference sc) pure $ mkVarsView ("scope " ++ show scopeName_) vs +fetchVarsOfFrame :: StackFrame -> T.Text -> TestDAP VarsView+fetchVarsOfFrame fr scopeName_ = do+ scs <- Test.DAP.scopes (stackFrameId fr)+ case List.find ((== scopeName_) . scopeName) scs of+ Nothing -> liftIO $ assertFailure $+ "fetchScopeVars: scope " ++ show scopeName_+ ++ " not found (" ++ show (map scopeName scs) ++ ")"+ Just sc -> do+ vs <- fetchChildren (scopeVariablesReference sc)+ pure $ mkVarsView ("scope " ++ show scopeName_) vs++varsViewOfScopes :: [Scope] -> T.Text -> TestDAP VarsView+varsViewOfScopes scs scopeName_ =+ case List.find ((== scopeName_) . scopeName) scs of+ Nothing -> liftIO $ assertFailure $+ "fetchScopeVars: scope " ++ show scopeName_+ ++ " not found (" ++ show (map scopeName scs) ++ ")"+ Just sc -> do+ vs <- fetchChildren (scopeVariablesReference sc)+ pure $ mkVarsView ("scope " ++ show scopeName_) vs+ fetchLocalVars :: TestDAP VarsView fetchLocalVars = fetchScopeVars "Locals" @@ -336,16 +373,28 @@ _ <- sync $ continueRequest @_ @Value ContinueArguments { DAP.continueArgumentsThreadId = tid- , DAP.continueArgumentsSingleThread = False+ , DAP.continueArgumentsSingleThread = Just False } pure () -evaluate :: T.Text -> TestDAP EvaluateResponse-evaluate expr = do+-- | Evaluate the expression at the currently stopped breakpoint.+-- Will yield wrong results if used when not stopped+evaluateAtBreak :: T.Text -> TestDAP EvaluateResponse+evaluateAtBreak expr = do+ fr:_ <- stackTrace =<< getCurrentActiveThread+ evaluateAt expr (Just (stackFrameId fr))++evaluateAt :: T.Text -> Maybe Int -> TestDAP EvaluateResponse+evaluateAt expr fid = do Response{responseBody=Just r} <- sync $ evaluateRequest $ EvaluateArguments { DAP.evaluateArgumentsExpression = expr- , DAP.evaluateArgumentsFrameId = Nothing+ , DAP.evaluateArgumentsFrameId = fid+ -- VSCode and Vim always set the frame id when there's a breakpoint at+ -- which we're evaluating the expression.+ -- If a DAP client doesn't specify the frame, the current breakpoint+ -- variables and imports at that module are not available.+ -- The testsuite driver here works similarly , DAP.evaluateArgumentsContext = Nothing , DAP.evaluateArgumentsFormat = Nothing }@@ -356,7 +405,7 @@ _ <- sync $ stepOutRequest @_ @Value StepOutArguments { DAP.stepOutArgumentsThreadId = tid- , DAP.stepOutArgumentsSingleThread = False+ , DAP.stepOutArgumentsSingleThread = Just False , DAP.stepOutArgumentsGranularity = Nothing } pure ()@@ -378,6 +427,14 @@ liftIO $ assertBool "disconnect response should indicate success" responseSuccess return () +terminate :: TestDAP ()+terminate = do+ Response{responseSuccess} <- sync $ terminateRequest @_ @Value $ Just+ TerminateArguments+ {DAP.terminateArgumentsRestart = False}+ liftIO $ assertBool "disconnect response should indicate success" responseSuccess+ return ()+ -------------------------------------------------------------------------------- -- ** Convenience methods (based on vscode-debugadapter-node/testSupport) --------------------------------------------------------------------------------@@ -415,6 +472,22 @@ ("assertOutput: expecting " ++ show expected ++ " but got " ++ show outputs) (any (T.isInfixOf expected) outputs) +-- | Wait for an output event that contains the given text, dropping all other+-- events, and return the output of the output events up to and including it.+--+-- Unlike 'assertOutput', this also sees output that arrives after the+-- terminated event. A thread of its own forwards the debuggee's stdout, so+-- the debuggee's last lines can come after that event.+waitForOutput :: HasCallStack => T.Text -> TestDAP T.Text+waitForOutput expected = go []+ where+ go acc = do+ Event{eventBody} <- waitFiltering EventTy "output"+ let out = outputEventOutput $ fromMaybe (error "waitForOutput:fromMaybe") eventBody+ if expected `T.isInfixOf` out+ then pure $ T.concat $ reverse (out : acc)+ else go (out : acc)+ assertFullOutput :: HasCallStack => T.Text -> TestDAP () assertFullOutput expected = assertFullOutputWith (expected <> " \\in full_output") (T.isInfixOf expected) @@ -434,36 +507,34 @@ -- * Waiting for messages -------------------------------------------------------------------------------- -data MsgType = EventTy | ResponseTy | ReverseRequestTy- deriving Show--msgChan :: MsgType -> TestDAPClientContext -> TChan Value-msgChan ty TestDAPClientContext{..} = case ty of- EventTy -> clientEvents- ResponseTy -> clientResponses- ReverseRequestTy -> clientReverseRequests- msgMatch :: MsgType -> String -> MessageMatch msgMatch ty s = case ty of EventTy -> eventMatch s ResponseTy -> responseMatch s ReverseRequestTy -> reverseRequestMatch s -waitFiltering_ :: MsgType -> String -> TestDAP ()+waitFiltering_ :: HasCallStack => MsgType -> String -> TestDAP () waitFiltering_ ty s = void $ waitFiltering @Value ty s -- | Drop messages of the given type until a message with the given -- eventType/command is found. The matching message is returned. -- FIXME: Timeouts on waiting, to avoid hanging forever in the testsuite!!-waitFiltering :: forall a. FromJSON a => MsgType -> String -> TestDAP a-waitFiltering ty s = do- ch <- asks (msgChan ty)- let mm = msgMatch ty s+waitFiltering :: forall a. (HasCallStack, FromJSON a) => MsgType -> String -> TestDAP a+waitFiltering ty s = waitFiltering' ty (msgMatch ty s)++waitFiltering' :: forall a. (HasCallStack, FromJSON a) => MsgType -> MessageMatch -> TestDAP a+waitFiltering' ty mm = do+ ctx <- ask let loop = do- v <- atomically $ readTChan ch -- block waiting for input+ v <- atomically $ readMessage ctx ty -- block waiting for input if messageMatchMatches mm v then case fromJSON @a v of- Error e -> error $ "waitFiltering: Failed to parse message MATCHING " ++ s ++ ":" ++ show ty ++ " with error: " ++ e ++ "\nFull message was: " ++ show v+ Error e -> error $ unwords+ [ "waitFiltering: Failed to parse message of type", show ty+ , "MATCHING", messageMatchDescription mm+ , "with error:", e+ , "\nFull message was: ", show v+ ] Success x -> return x else loop liftIO loop@@ -473,13 +544,14 @@ -- -- The non-matching message is not consumed, nor returned, and will be kept in -- the messages buffer.-waitAccumulating :: forall a. FromJSON a => MsgType -> String -> TestDAP [a]+waitAccumulating :: forall a. (HasCallStack, FromJSON a) => MsgType -> String -> TestDAP [a] waitAccumulating ty s = do+ ctx <- ask ch <- asks (msgChan ty) let mm = msgMatch ty s let loop acc = do r <- atomically $ do- v <- readTChan ch+ v <- readMessage ctx ty if messageMatchMatches mm v then case fromJSON @a v of Error e -> error $ "waitAccumulating: Failed to parse MATCHING message body with error: " ++ e ++ "\nFull message was: " ++ show v
test/haskell/Test/DAP/Init.hs view
@@ -4,13 +4,12 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE MultiWayIf #-} module Test.DAP.Init where ---------------------------------------------------------------------------- import Data.Maybe-import Data.List (isInfixOf) import Control.Exception hiding (handle)-import qualified Control.Exception as E import Network.Run.TCP import Network.Socket (Family(AF_INET), SockAddr(SockAddrInet, SockAddrInet6), SocketOption(ReuseAddr), SocketType(Stream), bind, close, defaultProtocol, getSocketName, setSocketOption, socket, socketToHandle, tupleToHostAddress) import System.IO@@ -20,18 +19,26 @@ import System.FilePath ((</>), (<.>)) import qualified System.Process as P ----------------------------------------------------------------------------+import GHC.Debugger.Utils (silenceEOF) import Test.DAP.Messages import Control.Concurrent.STM import Control.Concurrent.Async import Control.Monad.Reader import Control.Monad import Data.Aeson.Types-import Test.Tasty.HUnit (assertFailure)+import Test.Tasty.HUnit (assertFailure, HUnitFailure (..)) import DAP.Server (readPayload) import qualified Control.Monad.Catch import Test.Utils (withHermeticDir)-import DAP.Types (OutputEvent (..))+import DAP.Types (OutputEvent (..), StoppedEvent (..)) import Test.DAP.Messages.Parser+import DAP.Log (LogAction(..))+import qualified Data.Text as T+import qualified Data.Text.IO as T+import System.IO.Error (ioeGetLocation)+import Data.List (isPrefixOf)+import Control.Exception.Annotation+import Control.Exception.Context -------------------------------------------------------------------------------- -- * Launch the DAP server process (what we're testing)@@ -40,7 +47,9 @@ data TestDAPServer = TestDAPServer { testDAPServerPort :: Int , testDAPServerCleanup :: IO ()- , testDAPServerFlushOutput :: IO ()+ , testDAPServerOutput :: String+ , testDAPServerTestDir :: FilePath+ , testDAPServerPaths :: (String,String) } -- | Launch an @hdb server@ for tests on a random local port and capture stdout.@@ -66,18 +75,21 @@ pid <- fromMaybe 0 <$> P.getPid p writeFile (nameTemplate <.> "pid") (show pid) - let flushServerOutput = do- putStrLn "\n--- SERVER OUTPUT ---"- putStrLn $ "See: " ++ testDir- putStrLn $ "Might need: KEEP_TEMP_DIRS=True"- putStrLn "---------------------\n"+ let flushServerOutput = unlines+ [ ""+ , "--- SERVER OUTPUT ---"+ , "See: " ++ testDir+ , "Might need: KEEP_TEMP_DIRS=True"+ , "---------------------"+ ] pure TestDAPServer { testDAPServerPort = testPort- , testDAPServerFlushOutput = flushServerOutput+ , testDAPServerOutput = flushServerOutput , testDAPServerCleanup = do P.cleanupProcess (Just hin, Just hout, Just herr, p)-+ , testDAPServerPaths = (nameTemplate <.> "out", nameTemplate <.> "err")+ , testDAPServerTestDir = testDir } -- | Prefer this to startTestDAPServer@@ -111,24 +123,61 @@ withTestDAPServerClient :: TestDAPServer -> TestDAP a -> IO a withTestDAPServerClient = withTestDAPServerClientWith False (\_ _ -> pure Nothing) +data ServerMessages = ServerMessages { server_output :: String, server_err :: String }+ deriving Show+instance ExceptionAnnotation ServerMessages where+ displayExceptionAnnotation ServerMessages{..} =+ unlines $ [server_output, server_err]+ --- | Connect a test client to a running 'TestDAPServer', with retry semantics --- and server log flushing on failure. withTestDAPServerClientWith :: Bool {-^ Announce support for runInTerminal? -} -> (String -> Value -> IO (Maybe Value)) -> TestDAPServer -> TestDAP a -> IO a-withTestDAPServerClientWith clientSupportsRunInTerminal clientHandleNoSuccess server continue = do- runClient `E.onException` testDAPServerFlushOutput server+withTestDAPServerClientWith clientSupportsRunInTerminal clientHandleNoSuccess server continue = addServerOutput runClient where+ addServerOutput m = catchNoPropagate m $ (rethrowIO =<<) . annotate+ annotate = \case+ (ExceptionWithContext ctx e) -> do+ ann <- lookupEnv "PRINT_FULL_SERVER_OUTPUT" >>= \case+ Nothing -> do+ let server_output = testDAPServerOutput server+ let server_err = ""+ pure ServerMessages{..}+ Just{} -> do+ let (out,err) = testDAPServerPaths server+ let bracketWithPath path s =+ concat ["--- ", path, " ---\n", s, "--- END ", path, " ---\n"]+ server_output <- (testDAPServerOutput server ++) . bracketWithPath out <$> readFile out+ server_err <- bracketWithPath err <$> readFile err+ pure ServerMessages{..}++ -- HUnitFailure is special cased by `testCase` which disregards the+ -- exception context, so we embed the output in the message.+ let e' | Just (HUnitFailure srcpos msg) <- fromException e+ = toException $ HUnitFailure srcpos (msg ++ "\n" ++ displayExceptionAnnotation ann)+ | otherwise+ = e+ pure $ ExceptionWithContext (addExceptionAnnotation ann ctx) e'+ runClient = do withNewClient (testDAPServerPort server) $ \clientHandle -> do+ clientCurrentActiveThread <- newIORef 0 clientNextSeqRef <- newIORef 1 clientReverseRequests <- newTChanIO clientResponses <- newTChanIO clientEvents <- newTChanIO clientFullOutput <- newTVarIO []+ clientConnectionClosed <- newTVarIO False let ctx = TestDAPClientContext{..}- either id (\() -> error "handleServerTestDAP unexpectedly returned") <$> race- (runTestDAP continue ctx)- (runTestDAP handleServerTestDAP ctx)+ let logger = LogAction $ T.appendFile (testDAPServerTestDir server </> "test_client" <.> "out")+ -- The drainer thread can correctly return early if the connection is+ -- closed.+ --+ -- `continue` could still be working on what we drained so far, or+ -- whatever else, so we don't want to kill it yet.+ withAsync (runTestDAP (handleServerTestDAP logger) ctx) $ \ drainer -> do+ link drainer+ runTestDAP continue ctx -- | Spawns a new mock client that connects to the mock server. withNewClient :: forall a. Int -- ^ Port@@ -143,26 +192,34 @@ where retry_handlers = skipAsyncExceptions ++- [const $ Control.Monad.Catch.Handler $ \ (e :: IOException) -> return $ "Network.Socket.connect" `isInfixOf` show e]+ [const $ Control.Monad.Catch.Handler $ \ (e :: IOException) -> return $ "Network.Socket.connect" `isPrefixOf` ioeGetLocation e ] -------------------------------------------------------------------------------- -- ** Handle server responses, events, and reverse requests -------------------------------------------------------------------------------- -- | Forever: read messages from handle and write them either to clientNonEvents or clientEvents-handleServerTestDAP :: TestDAP ()-handleServerTestDAP = do+handleServerTestDAP :: LogAction IO T.Text -> TestDAP ()+handleServerTestDAP l = do TestDAPClientContext{..} <- ask- forever $ do+ -- we do not set clientConnectionClosed to True on an exception so we don't+ -- create a race between reporting the exception originated here and the one+ -- the TChan consumers might throw when the connections closes.+ -- The actual Handle is closed upstream.+ (>> liftIO (atomically $ writeTVar clientConnectionClosed True)) $+ silenceEOFTextDAP l clientHandle $ forever $ do payload <- nextPayload liftIO $ case parseMaybe parseType payload of Just "event" -> do- let mtxt = fromJSON @(Event OutputEvent) payload- atomically $ do- writeTChan clientEvents payload- case mtxt of- Success (Event _ (Just txt)) -> modifyTVar' clientFullOutput (outputEventOutput txt:)- _ -> pure ()+ atomically $ writeTChan clientEvents payload+ if | Success (Event _ (Just txt))+ <- fromJSON @(Event OutputEvent) payload+ -> atomically $ modifyTVar' clientFullOutput (outputEventOutput txt:)+ | Success (Event _ (Just StoppedEvent{..}))+ <- fromJSON @(Event StoppedEvent) payload+ -> writeIORef clientCurrentActiveThread (fromMaybe 0 stoppedEventThreadId)+ | otherwise+ -> pure () Just "response" -> -- Fail immediately if the server reports failure, even if the test -- is blocked waiting for some other specific message --@@ -195,3 +252,6 @@ else do msg <- o .:? "message" .!= "DAP response had success: false (no message)" pure (msg :: String)++silenceEOFTextDAP :: LogAction IO T.Text -> Handle -> TestDAP () -> TestDAP ()+silenceEOFTextDAP l h m = TestDAP $ \ r -> silenceEOF l h $ runTestDAP m r
test/haskell/Test/DAP/Messages.hs view
@@ -7,16 +7,18 @@ module Test.DAP.Messages where ---------------------------------------------------------------------------- import Control.Concurrent.Async+import Control.Concurrent.STM import Control.Monad.IO.Class+import Control.Monad.Catch import Data.Aeson import Data.Aeson.Types import Control.Monad.Reader import qualified Data.ByteString as BS import System.IO import Data.IORef+import GHC.Stack ---------------------------------------------------------------------------- import DAP.Utils-import Control.Concurrent.STM import qualified Data.Text as T import Test.DAP.Messages.Parser ----------------------------------------------------------------------------@@ -36,6 +38,8 @@ -- ^ Collect event messages sent by server , clientReverseRequests :: TChan Value -- ^ Collect reverse requests messages sent by server+ , clientConnectionClosed :: TVar Bool+ -- ^ Is the connection with the server closed? If so, no more messages will be added to the TChans. , clientFullOutput :: TVar [T.Text] -- ^ The full output is available here in reverse order (from most recent to oldest output strings). --@@ -52,10 +56,21 @@ -- ^ How to handle a response with success: false? If this function returns -- @Just val@ something then execution will resume with the returned @val@ -- rather than aborting.+ , clientCurrentActiveThread :: IORef Int+ -- ^ When a breakpoint is hit, it reports the thread which hit the breakpoint+ -- and we store that and consider it to be the the currently active thread.+ --+ -- In a multi-threaded scenario where many threads are resumed simultaneously,+ -- the current active thread may vary a lot (receiving many StoppedEvents) but+ -- at that point why are you using commands which rely on the current active+ -- thread (the global buttons)?+ --+ -- (Note: the StoppedEvents to update this are caught directly in the+ -- message handler thread) } newtype TestDAP a = TestDAP { runTestDAP :: TestDAPClientContext -> IO a }- deriving (Functor, Applicative, Monad, MonadIO, MonadFail, MonadReader TestDAPClientContext) via (ReaderT TestDAPClientContext IO)+ deriving (Functor, Applicative, Monad, MonadIO, MonadFail, MonadReader TestDAPClientContext, MonadThrow, MonadCatch, MonadMask) via (ReaderT TestDAPClientContext IO) -------------------------------------------------------------------------------- -- * Message primitives@@ -93,18 +108,46 @@ BS.hPutStr clientHandle $ encodeBaseProtocolMessage (object ("seq" .= (revReqSeqNum + 1) : filter ((/= "seq") . fst) message)) -waitForResponse :: TestDAP Value+data TestDAPClientConnectionClosed = TestDAPClientConnectionClosed+ deriving Show+instance Exception TestDAPClientConnectionClosed++data MsgType = EventTy | ResponseTy | ReverseRequestTy+ deriving Show++msgChan :: MsgType -> TestDAPClientContext -> TChan Value+msgChan ty TestDAPClientContext{..} = case ty of+ EventTy -> clientEvents+ ResponseTy -> clientResponses+ ReverseRequestTy -> clientReverseRequests++readMessage :: HasCallStack => TestDAPClientContext -> MsgType -> STM Value+readMessage ctx@TestDAPClientContext{..} ty = do+ let c = msgChan ty ctx+ m <- tryReadTChan c+ case m of+ Nothing -> do+ readTVar clientConnectionClosed >>= \case+ True -> throwSTM TestDAPClientConnectionClosed+ False -> retry+ Just msg -> pure msg++waitForResponse :: HasCallStack => TestDAP Value waitForResponse = do- TestDAPClientContext{..} <- ask- liftIO $ atomically $ readTChan clientResponses+ ctx <- ask+ liftIO $ atomically $ readMessage ctx ResponseTy -waitForReverseRequest :: TestDAP Value+waitForReverseRequest :: HasCallStack => TestDAP Value waitForReverseRequest = do- TestDAPClientContext{..} <- ask- liftIO $ atomically $ readTChan clientReverseRequests+ ctx <- ask+ liftIO $ atomically $ readMessage ctx ReverseRequestTy -waitForEvent :: TestDAP Value+waitForEvent :: HasCallStack => TestDAP Value waitForEvent = do- TestDAPClientContext{..} <- ask- liftIO $ atomically $ readTChan clientEvents+ ctx <- ask+ liftIO $ atomically $ readMessage ctx EventTy +-- | See 'clientCurrentActiveThread'+getCurrentActiveThread :: TestDAP Int+getCurrentActiveThread = do+ liftIO . readIORef =<< asks clientCurrentActiveThread
test/haskell/Test/DAP/Messages/Parser.hs view
@@ -52,6 +52,13 @@ pure ((typ :: String) == "request" && (command :: String) == commandExpected) ) v +stdoutMatch :: String -> MessageMatch+stdoutMatch outputExpected = subsetMatch+ [ "type" .= ("event" :: String)+ , "event" .= ("output" :: String)+ , "body" .= object [ "output" .= outputExpected+ , "category" .= ("stdout" :: String) ]+ ] -------------------------------------------------------------------------------- -- * Message parsers --------------------------------------------------------------------------------
test/haskell/Test/DAP/Orphans.hs view
@@ -182,6 +182,9 @@ instance ToJSON NextArguments where toJSON = genericToJSONWithModifier +instance ToJSON StepInArguments where+ toJSON = genericToJSONWithModifier+ instance ToJSON StackFrameFormat where toJSON = genericToJSONWithModifier @@ -196,6 +199,9 @@ instance ToJSON DisconnectArguments where toJSON = genericToJSONWithModifier++instance ToJSON TerminateArguments where+ toJSON = genericToJSONWithModifier instance ToJSON VariablesArguments where toJSON VariablesArguments{..} = object $
test/haskell/Test/Integration/Basic.hs view
@@ -5,11 +5,18 @@ {-# LANGUAGE RecordWildCards #-} module Test.Integration.Basic (basicTests) where +import qualified Control.Monad.Catch as MC import Control.Monad.Reader+import qualified Data.List as List+import Data.Aeson (Value)+import Data.Either (isLeft)+import System.FilePath+import System.Timeout import Test.DAP import Test.DAP.Messages.Parser import Test.Tasty import Test.Tasty.HUnit+import Test.Tasty.ExpectedFailure (expectFailBecause) import qualified DAP basicTests :: TestTree@@ -31,6 +38,16 @@ [ testCase "breakpoints in two modules (#297)" multiModuleStandaloneBreakpoints , testCase "breakpoints in two modules (flipped) (#297)" multiModuleStandaloneBreakpoints2 ]+ , testGroup "Ending session"+ [ expectFailBecause "DAP thread stuck waiting for EvalResult" $+ testGroup "debuggee idle"+ [ testCase "disconnect promptly" debuggeeIdleDisconnectTest+ , testCase "terminate promptly" debuggeeIdleTerminateTest+ ]+ , testCase "debuggee idle testcase loads" debuggeeIdleTestSetupTest+ ]+ , testCase "report error when projectRoot does not exist" reportErrorForMissingDirectory+ , testCase "throws exception when no more messages" throwsExceptionWhenNoMoreMessages ] basicForConfig :: TestName -> FilePath -> FilePath -> TestTree@@ -109,7 +126,7 @@ _ <- sync $ setLineBreakpoints test_dir "Helper.hs" [5] _ <- sync configurationDone assertStoppedLocation DAP.StoppedEventReasonBreakpoint 7- continueThread 0+ continueThread =<< getCurrentActiveThread assertStoppedLocation DAP.StoppedEventReasonBreakpoint 5 disconnect @@ -125,6 +142,67 @@ _ <- sync $ setLineBreakpoints test_dir "Main.hs" [7] _ <- sync configurationDone assertStoppedLocation DAP.StoppedEventReasonBreakpoint 7- continueThread 0+ continueThread =<< getCurrentActiveThread assertStoppedLocation DAP.StoppedEventReasonBreakpoint 5 disconnect++debuggeeIdleDisconnectTest :: IO ()+debuggeeIdleDisconnectTest = debuggeeIdleTestSetup $ do+ disconnect+ waitFiltering_ EventTy "terminated"+ assertFullOutput "debuggee shutting down"++debuggeeIdleTerminateTest :: IO ()+debuggeeIdleTerminateTest = debuggeeIdleTestSetup $ do+ terminate+ waitFiltering_ EventTy "terminated"+ assertFullOutput "debuggee shutting down"++debuggeeIdleTestSetupTest :: IO ()+debuggeeIdleTestSetupTest = debuggeeIdleTestSetup $ do+ (_ :: Value) <- waitFiltering' EventTy (stdoutMatch "Started\n")+ pure ()++debuggeeIdleTestSetup :: TestDAP () -> IO ()+debuggeeIdleTestSetup test = do+ let projectRoot = "test/integration/T325a"+ let entryFile = "T325a.hs"+ withTestDAPServer projectRoot [] $ \test_dir server ->+ withTestDAPServerClient server $ do+ let cfg = mkLaunchConfig test_dir entryFile+ _ <- sync $ launchWith cfg+ waitFiltering_ EventTy "initialized"+ _ <- sync configurationDone+ withTimeout test+ where+ -- we do our own timeout check as it's part of the spec and plays better+ -- with withTestDAPServerClient+ withTimeout (TestDAP m) = TestDAP $ \ env -> do+ x <- timeout 5_000_000 $ m env+ case x of+ Just a -> pure a+ Nothing -> assertFailure "Timeout after 5s"++reportErrorForMissingDirectory :: IO ()+reportErrorForMissingDirectory = do+ withTestDAPServer "test/integration/T44" [] $ \test_dir server ->+ withTestDAPServerClientWith False checkErrorResponse server $ do+ let cfg = mkLaunchConfig (test_dir </> "missing") "Main.hs"+ Response{responseSuccess} <- sync $ launchWith cfg+ liftIO $ assertBool+ "Expected launch to fail because of a not existing directory, but got success: true"+ (not responseSuccess)++ where+ checkErrorResponse errMsg v = do+ assertBool ("unexpected error msg: " ++ errMsg)+ ("Couldn't execute ghc --numeric-version" `List.isInfixOf` errMsg)+ return (Just v)++throwsExceptionWhenNoMoreMessages :: IO ()+throwsExceptionWhenNoMoreMessages = do+ withTestDAPServer "test/integration/T44" [] $ \_test_dir server ->+ withTestDAPServerClient server $ do+ disconnect+ e <- MC.try @_ @TestDAPClientConnectionClosed $ waitFiltering_ EventTy "stopped"+ liftIO $ assertBool "got () instead of exception" $ isLeft e
test/haskell/Test/Integration/Conditional.hs view
@@ -29,7 +29,7 @@ { sourceBreakpointLine = 13 , sourceBreakpointCondition = Just "im IM.! 0 == 2" } -- Continuing just once is sufficient for it to exit now- (continueThread 0)+ (continueThread =<< getCurrentActiveThread) hitCount :: Assertion hitCount =@@ -41,7 +41,7 @@ } -- Unlike conditional expression, we hit the breakpoint every time -- after the ignore count, so run this twice- (continueThread 0 >> continueThread 0)+ ((continueThread =<< getCurrentActiveThread) >> (continueThread =<< getCurrentActiveThread)) testWith :: Bool -> SourceBreakpoint -> TestDAP () -> Assertion testWith needsForcing bp afterCheck =
test/haskell/Test/Integration/Evaluate.hs view
@@ -1,10 +1,11 @@ -- | Evaluate request tests ported from the NodeJS testsuite. {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-} module Test.Integration.Evaluate (evaluateTests) where import Control.Monad.IO.Class (liftIO)-import Data.List (isInfixOf)+import Data.List (isInfixOf, sort) import Test.DAP import Test.Tasty import Test.Tasty.HUnit@@ -12,6 +13,11 @@ import Test.Tasty.ExpectedFailure #endif import qualified DAP+import DAP.Types+import Control.Monad+import Data.Maybe+import Test.Tasty.ExpectedFailure+import Data.Text (Text) evaluateTests :: TestTree evaluateTests =@@ -24,9 +30,103 @@ , testCase "Imported module bindings available in evaluate context (issue #233)" evaluateImportedBindings , testCase "Bindings from other modules not available in evaluate context (issue #233)"- evaluateImportedBindingsNotInOtherModule+ evaluateImportedBindingsNotInOtherModule+ ,+#ifndef GHC_HAS_MULTITHREADED_DBG+ ignoreTestBecause "Multiple stopped threads not fully supported" $+#endif+ testCase "Evaluate from multiple stopped threads"+ evaluateMultiThreaded+ , testGroup "scope from earlier stack frames (issue #370)"+ [ testCase "multiple stack frames" stackFramesTest+ , testCase "RetBCO waiting for unboxed tuple" stackFramesUnboxedTupleTest+ ]+ , testGroup "global eval"+ [ testCase "evaluate after resume" evaluateAfterResume+ ] ] +evaluateAfterResume :: IO ()+evaluateAfterResume = do+ withTestDAPServer "test/integration/T370" [] $ \test_dir server ->+ withTestDAPServerClient server $ do+ let cfg = mkLaunchConfig test_dir "T370b.hs"+ hitBreakpointIn cfg "T370b.hs" 6++ continueThread =<< getCurrentActiveThread++ -- Evaluating without stackframe: only global scope.+ res0 <- evaluateAt "x" Nothing+ assertEqualResult res0 "<interactive>:1:1: error: [GHC-88464] Variable not in scope: x"++ res1 <- evaluateAtBreak "x"+ assertEqualResult res1 "\"foo\""++ disconnect++evaluateMultiThreaded :: Assertion+evaluateMultiThreaded =+ withTestDAPServer "test/integration/T370" [] $ \test_dir server ->+ withTestDAPServerClient server $ do+ let cfg@LaunchConfig{..} = mkLaunchConfig test_dir "T370.hs"+ _ <- sync $ launchWith cfg+ waitFiltering_ EventTy "initialized"+ _ <- sync $ setLineBreakpoints lcProjectRoot (fromMaybe undefined lcEntryFile) [22,28]+ _ <- sync configurationDone++ waitFiltering_ EventTy "stopped"+ ts <- Test.DAP.threads+ resps <- fmap catMaybes . forM ts $ \ t -> do+ frs <- stackTrace (threadId t)+ case frs of+ [] -> pure Nothing+ (fr:_) -> Just <$> evaluateAt "x" (Just (stackFrameId fr))+ let results = sort $ map DAP.evaluateResponseResult resps+ liftIO $ assertEqual ("Results: " ++ show results) ["0","2"] results+ disconnect++stackFramesTest :: Assertion+stackFramesTest = stackFramesTestGen "test/integration/T160"++stackFramesTestGen :: FilePath -> Assertion+stackFramesTestGen path =+ withTestDAPServer path [] $ \test_dir server ->+ withTestDAPServerClient server $ do+ let cfg = mkLaunchConfig test_dir "Main.hs"+ hitBreakpointIn cfg "X.hs" 22+ frames <- stackTrace =<< getCurrentActiveThread++ -- Evaluating without stackframe: only global scope.+ res0 <- evaluateAt "b" Nothing+ assertEqualResult res0 "<interactive>:1:1: error: [GHC-88464] Variable not in scope: b"++ res1 <- evaluateAt "head xs" (Just $ stackFrameId (frames !! 1))+ assertEqualResult res1 "1"++ res2 <- evaluateAt "s" (Just $ stackFrameId (frames !! 2))+ assertEqualResult res2 "\"hello\""++ res3 <- evaluateAt "x" (Just $ stackFrameId (frames !! 3))+ assertEqualResult res3 "5"++ disconnect++assertEqualResult :: (HasCallStack, MonadIO m) => EvaluateResponse -> Text -> m ()+assertEqualResult res x = liftIO $ assertEqual (show res) x (DAP.evaluateResponseResult res)++stackFramesUnboxedTupleTest :: Assertion+stackFramesUnboxedTupleTest =+ withTestDAPServer "test/integration/T160" [] $ \test_dir server ->+ withTestDAPServerClient server $ do+ let cfg = mkLaunchConfig test_dir "Main.hs"+ hitBreakpointIn cfg "X.hs" 27+ frames <- stackTrace =<< getCurrentActiveThread++ res <- evaluateAt "x" (Just $ stackFrameId (frames !! 1))+ assertEqualResult res "1"++ disconnect+ evaluateStructured :: Assertion evaluateStructured = withTestDAPServer "test/integration/T116" [] $ \test_dir server ->@@ -34,7 +134,7 @@ let cfg = mkLaunchConfig test_dir "T116.hs" hitBreakpointWith cfg 13 - resp <- evaluate "IM.delete 0 (IM.insert 0 'a' (IM.insert 1 'b' IM.empty))"+ resp <- evaluateAtBreak "IM.delete 0 (IM.insert 0 'a' (IM.insert 1 'b' IM.empty))" liftIO $ assertEqual "result is IntMap" "IntMap" (DAP.evaluateResponseResult resp) respChildren <- fetchChildren (DAP.evaluateResponseVariablesReference resp) -- fixme: it'd be good to re-use the VarViews structure here, but that's specialized to Variables for now@@ -54,11 +154,11 @@ hitBreakpointWith cfg 15 -- sort is imported from Data.List- sortResp <- evaluate "show (sort xs)"+ sortResp <- evaluateAtBreak "show (sort xs)" liftIO $ assertEqual "sort xs result" "\"[1,1,2,3,4,5,6,9]\"" (DAP.evaluateResponseResult sortResp) -- Map is a qualified import- mapResp <- evaluate "show (Map.lookup \"a\" m)"+ mapResp <- evaluateAtBreak "show (Map.lookup \"a\" m)" liftIO $ assertEqual "Map.lookup result" "\"Just 1\"" (DAP.evaluateResponseResult mapResp) disconnect@@ -80,15 +180,15 @@ _ <- assertStoppedLocation DAP.StoppedEventReasonBreakpoint 15 -- Stopped in T233.hs which imports Data.List and Data.Map.Strict as Map- sortResp <- evaluate "show (sort xs)"+ sortResp <- evaluateAtBreak "show (sort xs)" liftIO $ assertEqual "sort xs result" "\"[1,1,2,3,4,5,6,9]\"" (DAP.evaluateResponseResult sortResp) -- Resume and stop at breakpoint in Other.hs, which does not import Map- continueThread 0+ continueThread =<< getCurrentActiveThread _ <- assertStoppedLocation DAP.StoppedEventReasonBreakpoint 4 -- Map is not imported in Other.hs; evaluating Map.fromList should fail- mapFailResp <- evaluate "Map.fromList [(1,'a')]"+ mapFailResp <- evaluateAtBreak "Map.fromList [(1,'a')]" let result = DAP.evaluateResponseResult mapFailResp liftIO $ assertBool ("expected 'not in scope' error for Map.fromList, got: " ++ show result)
test/haskell/Test/Integration/LogMessage.hs view
@@ -7,10 +7,8 @@ import Test.DAP import Test.Tasty import Test.Tasty.HUnit-import Data.Maybe (fromMaybe) import qualified Data.Text as T-import DAP (SourceBreakpoint(..), defaultSourceBreakpoint, OutputEvent (..))-import Test.DAP.Messages.Parser (Event(..))+import DAP (SourceBreakpoint(..), defaultSourceBreakpoint) logMessageTests :: TestTree logMessageTests =@@ -46,12 +44,13 @@ { sourceBreakpointLine = 18 , sourceBreakpointLogMessage = Just (T.pack tmpl) } logMessageTestSetup [] [bp] $ do- assertOutput (T.pack expected)+ output <- programOutput+ liftIO $ assertBool ("expecting " ++ show expected ++ " but got " ++ show output) $+ T.pack expected `T.isInfixOf` output conditionTest :: IO () conditionTest = logMessageTestSetup [] bps $ do- events <- waitAccumulating EventTy "output"- let output = T.concat $ map (outputEventOutput . fromMaybe (error "conditionTest:fromMaybe") . eventBody) events+ output <- programOutput liftIO $ assertBool "logged when False" $ not $ "DO NOT LOG" `T.isInfixOf` output@@ -69,6 +68,10 @@ , sourceBreakpointCondition = Just "True" , sourceBreakpointLogMessage = Just "DO LOG" } ]++-- | The output up to the line that T113 prints last.+programOutput :: TestDAP T.Text+programOutput = waitForOutput "goodbye" logMessageTestSetup :: [String] -> [SourceBreakpoint] -> TestDAP a -> IO () logMessageTestSetup flags bps check =
test/haskell/Test/Integration/RunInTerminal.hs view
@@ -60,7 +60,9 @@ liftIO $ hFlush err_h (Just rit_in, Nothing, Nothing, rit_p) <- liftIO $ P.createProcess (P.shell invocation)- {P.cwd = Just test_dir, P.std_in = P.CreatePipe, P.std_out = P.UseHandle out_h, P.std_err = P.UseHandle err_h}+ {P.cwd = Just test_dir, P.std_in = P.CreatePipe, P.std_out = P.UseHandle out_h, P.std_err = P.UseHandle err_h+ -- cleanupInterp sends sigINT to whole group.+ , P.create_group = True} Just rit_pid <- liftIO $ P.getPid rit_p pure ((rit_in, rit_p), fromIntegral rit_pid)) @@ -105,8 +107,6 @@ ("The stderr of the runInTerminal process shouldn't have any errors, but has: " ++ err_str ++ "\nStdout: " ++ out_str) (not ("GHCi.Message.readPipe:" `isInfixOf` err_str) && not ("Uncaught exception" `isInfixOf` err_str)) - -- -- Kill the process- P.terminateProcess rit_p where addRITEnv :: Maybe (H.HashMap T.Text T.Text) -> T.Text
test/haskell/Test/Integration/Scopes.hs view
@@ -9,7 +9,7 @@ #ifdef mingw32_HOST_OS import Test.Tasty.ExpectedFailure #endif-import DAP (threadId, stackFrameId, scopeName, scopeExpensive)+import DAP (stackFrameId, scopeName, scopeExpensive) import Data.List (find) import qualified Data.Text as T @@ -30,8 +30,7 @@ _ <- hitBreakpointWith (mkLaunchConfig test_dir "Main.hs") 6 - thread:_ <- threads- frame:_ <- stackTrace (threadId thread)+ frame:_ <- stackTrace =<< getCurrentActiveThread scps <- scopes (stackFrameId frame) let lookupExpensive n = scopeExpensive <$> find ((== T.pack n) . scopeName) scps
test/haskell/Test/Integration/StackTrace.hs view
@@ -11,7 +11,7 @@ import Test.Tasty.ExpectedFailure #endif import qualified Data.Text as Text-import DAP (threadId, stackFrameName)+import DAP (stackFrameName) stackTraceTests :: TestTree stackTraceTests =@@ -29,8 +29,7 @@ withTestDAPServerClient server $ do let cfg = mkLaunchConfig test_dir "app/Main.hs" hitBreakpointWith cfg 9- t:_ <- threads- frames <- stackTrace (threadId t)+ frames <- stackTrace =<< getCurrentActiveThread let names = map stackFrameName frames liftIO $ do -- Contains the interpreter frame@@ -47,8 +46,7 @@ withTestDAPServerClient server $ do let cfg = mkLaunchConfig test_dir "app/Main.hs" hitBreakpointWith cfg 15- t:_ <- threads- frames <- stackTrace (threadId t)+ frames <- stackTrace =<< getCurrentActiveThread let names = map stackFrameName frames liftIO $ do -- Contains the stack annotations
test/haskell/Test/Integration/StepOut.hs view
@@ -40,23 +40,23 @@ simpleStepOutCase :: Assertion simpleStepOutCase = withCommon "MainC.hs" 9 [] $ do- stepOut 0+ stepOut =<< getCurrentActiveThread assertStoppedLocation StoppedEventReasonStep 5 disconnect withoutTailCalls :: Assertion withoutTailCalls = withCommon "MainA.hs" 10 optFlags $ do -- foo to bar- stepOut 0+ stepOut =<< getCurrentActiveThread assertStoppedLocation StoppedEventReasonStep 20- stepOut 0+ stepOut =<< getCurrentActiveThread -- bar back to foo assertStoppedLocation StoppedEventReasonStep 14- stepOut 0+ stepOut =<< getCurrentActiveThread -- back to main assertStoppedLocation StoppedEventReasonStep 5 -- exit- stepOut 0+ stepOut =<< getCurrentActiveThread disconnect -- Mimics GHC's T26042c@@ -65,8 +65,8 @@ -- step out of foo True and observe that we have skipped its call in bar, -- and the call of bar in foo False. -- we go straight to `main`.- stepOut 0+ stepOut =<< getCurrentActiveThread assertStoppedLocation StoppedEventReasonStep 5 -- stepping out again exits- stepOut 0+ stepOut =<< getCurrentActiveThread disconnect
+ test/haskell/Test/Integration/Threads.hs view
@@ -0,0 +1,46 @@+-- | Multi-threaded debugging tests.+--+-- Checks that, while stopped, the debugger reports exactly the debuggee's own+-- threads (the main thread and the labelled workers) and none of the helper+-- threads used by the interpreter itself.+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+module Test.Integration.Threads (threadsTests) where++import Control.Monad.IO.Class (liftIO)+import Data.List (sort)+import qualified Data.Text as T++import Test.DAP+import Test.Tasty+import Test.Tasty.HUnit+#ifdef mingw32_HOST_OS+import Test.Tasty.ExpectedFailure+#endif+import qualified DAP++threadsTests :: TestTree+threadsTests =+#ifdef mingw32_HOST_OS+ ignoreTestBecause "Needs to be fixed for Windows (#199)" $+#endif+ testGroup "DAP.Integration.Threads"+ [ testCase "only the debuggee threads are listed" onlyDebuggeeThreadsAreListed+ ]++onlyDebuggeeThreadsAreListed :: Assertion+onlyDebuggeeThreadsAreListed =+ withTestDAPServer "test/integration/threads" [] $ \test_dir server ->+ withTestDAPServerClient server $ do++ hitBreakpointWith (mkLaunchConfig test_dir "Main.hs") 25 -- break after spawning the workers++ -- listing all threads should display all the debuggee threads (main + 4 workers)+ -- and no internal helper threads like IOManager or ext interpreter server+ names <- sort . map DAP.threadName <$> threads+ liftIO $ assertEqual "reported threads" expectedThreadNames names++ disconnect+ where+ expectedThreadNames =+ sort ("Debuggee Main" : ["Worker " <> T.pack (show i) | i <- [1 .. 4 :: Int]])
test/haskell/Test/Utils.hs view
@@ -1,6 +1,6 @@ module Test.Utils where -import Control.Monad (when)+import Control.Monad (when, unless) import Data.List (isInfixOf) import System.Directory (doesFileExist,doesDirectoryExist) import System.FilePath@@ -13,10 +13,15 @@ -> FilePath -- ^ Test dir -> (FilePath -> IO r) -- ^ Continuation receives hermetic test dir (in temporary dir) -> IO r+withHermeticDir _keep src _k+ | hasTrailingPathSeparator src+ = fail $ "src dir ends with a path separator, won't work the same on macOS: " ++ src withHermeticDir keep src k = do withTestTmpDir keep $ \dest -> do P.callCommand $ "cp -r " ++ src ++ " " ++ dest let destTestDir = dest </> takeBaseName src+ b <- doesDirectoryExist destTestDir+ unless b $ fail $ "destTestDir does not exist " ++ show destTestDir -- Some test projects reference @./haskell-debugger-view@ in their -- @cabal.project@. If such a dir is expected, copy the in-tree -- @haskell-debugger-view@ there so that cabal can resolve it when
+ test/integration/T325a/T325a.cabal view
@@ -0,0 +1,18 @@+cabal-version: 3.14+name: T325a+version: 0.1.0.0+license: NONE+author: Andrea Vezzosi+maintainer: andrea@well-typed.com+build-type: Simple+extra-doc-files: CHANGELOG.md++common warnings+ ghc-options: -Wall++executable T325+ import: warnings+ main-is: T325a.hs+ build-depends: base+ hs-source-dirs: .+ default-language: GHC2024
+ test/integration/T325a/T325a.hs view
@@ -0,0 +1,12 @@+module T325a where++import Control.Concurrent+import Control.Monad+import Control.Exception+import System.IO+main :: IO ()+main = do+ hSetBuffering stdout LineBuffering+ putStrLn "Started"+ forever (threadDelay 1_000_000)+ `finally` putStrLn "debuggee shutting down"
+ test/integration/T325a/cabal.project view
@@ -0,0 +1,1 @@+packages: .
+ test/integration/T325a/hie.yaml view
@@ -0,0 +1,1 @@+{"cradle":{"cabal": null}}
+ test/integration/T370/T370.cabal view
@@ -0,0 +1,32 @@+cabal-version: 3.0+name: T370+version: 0.1.0.0+-- synopsis:+-- description:+license: BSD-3-Clause+license-file: LICENSE+author: Andrea Vezzosi+maintainer: andrea@well-typed.com+-- copyright:+build-type: Simple++-- extra-source-files:++common extensions+ default-language: GHC2021++common ghc-options+ ghc-options: -Wall -Widentities++common rts-options+ ghc-options: -rtsopts -threaded "-with-rtsopts=-N"++library+ import: extensions+ import: ghc-options+ exposed-modules: T370, T370b+ -- other-modules:+ -- other-extensions:+ build-depends: base+ hs-source-dirs: .+ default-language: Haskell2010
+ test/integration/T370/T370.hs view
@@ -0,0 +1,31 @@+module T370 where+import Control.Concurrent+import Control.Concurrent.MVar++main :: IO ()+main = do+ v0 <- newEmptyMVar+ v1 <- newEmptyMVar+ v2 <- newEmptyMVar+ forkIO $ f 0 >>= putMVar v0+ forkIO $ f 2 >>= putMVar v2+ takeMVar v0+ takeMVar v1+ takeMVar v2++f :: Int -> IO ()+f n | n < 2 = g n+ | otherwise = h n++g :: Int -> IO ()+g x = do+ print x+ print (x*2)+ pure ()++h :: Int -> IO ()+h x = do+ print x+ print (x*2)+ pure ()+
+ test/integration/T370/T370b.hs view
@@ -0,0 +1,8 @@+module T370b where++main :: IO ()+main = do+ x <- pure "foo"+ pure ()+ print x+ main
+ test/integration/T370/hie.yaml view
@@ -0,0 +1,2 @@+cradle:+ cabal:
+ test/integration/threads/Main.hs view
@@ -0,0 +1,26 @@+module Main where++import Control.Concurrent+import Control.Monad+import GHC.Conc+import System.IO++worker :: Int -> IO ()+worker n = do+ putStrLn $ "Worker " ++ show n ++ " starting"+ threadDelay 500000 -- 0.5s+ putStrLn $ "Worker " ++ show n ++ " midpoint"+ threadDelay 700000 -- 0.7s+ putStrLn $ "Worker " ++ show n ++ " done"+ worker n++setLabel :: String -> IO ()+setLabel s = myThreadId >>= \tid -> labelThread tid s++main :: IO ()+main = do+ hSetBuffering stdout LineBuffering+ putStrLn "Main: spawning workers"+ tids <- forM [1..4] $ \i -> forkIO (setLabel ("Worker " ++ show i) >> worker i)+ putStrLn $ "Main: spawned " ++ show (length tids) ++ " workers"+ forever $ threadDelay 1000000