packages feed

haskell-debugger-0.15.0.0: hdb/Main.hs

{-# LANGUAGE OverloadedStrings, OverloadedRecordDot, CPP, DeriveAnyClass,
   DeriveGeneric, DerivingVia, LambdaCase, RecordWildCards, ViewPatterns,
   DataKinds #-}
module Main where

import System.Process
import System.Environment
import Control.Exception.Backtrace

import DAP

import Development.Debug.Adapter.Init
import Development.Debug.Adapter.Handles
import Development.Debug.Adapter.Server
import Colog.Core

import System.IO
  ( hFlush
  , hClose
  , hPutStrLn
  , hSetBuffering
  , BufferMode(..)
  , Handle

  , IOMode(ReadWriteMode)
  )
import qualified Data.Text as T
import qualified Data.Text.IO as T
import GHC.IO.Handle.FD
import Data.Functor.Contravariant
import Network.Socket hiding (Debug)

import qualified GHCi.Server as GHCi
import qualified GHCi.Signals as GHCi
import qualified GHCi.Utils as GHCi
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)
#endif

--------------------------------------------------------------------------------

main :: IO ()
main = handleSigTermTopLevel $ do
  setBacktraceMechanismState CostCentreBacktrace False
  setBacktraceMechanismState HasCallStackBacktrace True

  hdbOpts <- parseHdbOptions
  case hdbOpts of
    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
      hdbProgram <- getExecutablePath

      -- See Note [UniqueSupply is process global]
      initUniqSupplyIO

      let servConf = DAPServerConf
            { getDebugRunner = hieDebugRunner
            , hdbProgram
            , dapServerConfig = config
            }
      redirectRealStdout internalInterpreter $ \realStdout -> do
        hSetBuffering realStdout LineBuffering
        l <- contramap DAPLog <$> mainLogger hdbOpts.verbosity realStdout
        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)

        -- See Note [UniqueSupply is process global]
        initUniqSupplyIO

        l <- mainLogger hdbOpts.verbosity stdout
        cliInterpSettings <- mkCliInterpreterSettings internalInterpreter debuggeeStdin
        let runConf = RunDebuggerSettings
              { supportsANSIStyling = True -- todo: check!!
              , supportsANSIHyperlinks = False
              , interpreterSettings = cliInterpSettings }
        runIDM (contramap InteractiveLog l) entryPoint entryFile entryArgs extraGhcArgs cradleFile
          runConf debugInteractive
    HdbProxy{port} -> handleNoHostServer $ do
        setBacktraceMechanismState IPEBacktrace True
        l <- mainLogger hdbOpts.verbosity stdout
        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} -> labelEIMain $ flip withStubbornAsync wait $ handleNoHostServer $ do
      pid <- getCurrentPid
      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
#if MIN_VERSION_ghc(9,14,2)
      uninterruptibleMask $ \restore -> do
        GHCi.servWithCustom verbose hook pipe restore dbgInterpCmdHandler
#else
      uninterruptibleMask $ GHCi.serv verbose hook pipe
#endif
      where hook = return -- empty hook
        -- we cannot allow any async exceptions while communicating, because
        -- we will lose sync in the protocol, hence uninterruptibleMask.

    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
      let hints = defaultHints { addrSocketType = Stream }
      addr:_ <- getAddrInfo (Just hints) (Just host) (Just (show port))

      Control.Exception.bracketOnError
        (socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr))
        close
        (\sock -> do
            -- Don't delay, avoids batching
            setSocketOption sock NoDelay 1
            connect sock (addrAddress addr) `onConnectionError` throwIO NoHostServer
            h <- socketToHandle sock ReadWriteMode
            hSetBuffering h NoBuffering
            return h)

    -- When using the internal interpreter in DAP mode, we can't write to
    -- stdout directly because there will also be a thread forwarding the
    -- debuggee stdout by capturing it from stdout (and we'd get into a loop
    -- trying to forward what we're writing).
    --
    -- The redirection we use requires hDuplicateTo which isn't supported on
    -- Windows (ghc#22146), so using the internal interpreter on Windows
    -- currently unsupported.
    --
    -- When using the external interpreter, the debuggee output is read from
    -- its process handle directly, so this is unnecessary.
    redirectRealStdout internalInterpreter k
      | internalInterpreter =
        withInterceptedStdoutForwarding
          (\interceptedOut -> T.hPutStrLn stderr ("[INTERCEPTED STDOUT] " <> interceptedOut))
          (\realStdout -> k realStdout)
      | 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


--------------------------------------------------------------------------------
-- * Logging
--------------------------------------------------------------------------------

data MainLog
  = InteractiveLog InteractiveLog
  | RunProxyClientLog (WithSeverity T.Text)
  | DAPLog DAPLog

-- | Given the severity threshold from which we start logging, create a base
-- logger for consuming the top-level debugger logs ('MainLog').
-- Outputs to given handle.
mainLogger :: Severity -> Handle -> IO (LogAction IO MainLog)
mainLogger threshold h = do
  l <- handleLogger h
  let logGhcLog = defaultLogActionWithHandles h h
  pure $ LogAction $ \case
    InteractiveLog (ISessionSetupLog sessionLog) -> logSessionLog l threshold sessionLog
    InteractiveLog (IDebuggerLog debuggerLog)    -> logDebuggerLog logGhcLog l threshold debuggerLog
    RunProxyClientLog sev_msg -> defaultLog l threshold sev_msg
    DAPLog dapLog -> logDAPLog logGhcLog l threshold <& dapLog