packages feed

haskell-debugger-0.15.0.0: hdb-dap/Development/Debug/Adapter/DAPDebuggee.hs

{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NondecreasingIndentation #-}

-- | TODO: This module should be called Launch.
module Development.Debug.Adapter.DAPDebuggee where

#if !MIN_VERSION_ghc(9,15,0)
-- no longer needs to be imported from here in 9.15
import GHC.Conc.Sync (labelThread)
#endif

import GHC.IO.Handle
import GHC.Stack.Annotation (annotateStackStringIO)
import System.Process
import qualified Data.ByteString as BS
import qualified Data.Text 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.Monad
import Data.Functor.Contravariant

import Development.Debug.Adapter
import Colog.Core as Logger
import qualified Development.Debug.Adapter.Output as Output


import DAP
import Development.Debug.Adapter.Handles
import Development.Debug.Session.Setup
import Development.Debug.Adapter.Proxy
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
  , dapdWaitForDebuggee :: IO ()
  , dapdThreads :: [(DebugAdaptorCont () -> IO ()) -> IO ()]
  -- ^ Additional threads to register for this session depending on the process
  -- we're running through `runInTerminal` (see 'interpreterInit').
  , dapdAfterRegister :: DebugAdaptor ()
  -- ^ additional commands to run after registering the session.
  }


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
    let interpSettings = InterpreterSettings
          { interpreterFlags = mkInternalInterpreterFlags
          , interpreterSetup = mkInternalInterpreterSetup
          }
    let ld = contramap (ForwardingThreadLog . flip WithSeverity Debug) l
    pure $
      DAPDebuggee
        interpSettings
        (pure ())
        [ stdoutCaptureThread ld (const $ pure ()), stderrCaptureThread ld (const $ pure ()) ]
        (pure ())

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 extraInterpArgs
        , interpreterSetup = mkExternalInterpreterSubProcessSetup CreatePipe CreatePipe CreatePipe (putMVar iserv_handles)
        }
      ld = contramap (ForwardingThreadLog . flip WithSeverity Debug) l
  pure $
    DAPDebuggee
      interpSettings
      (pure ())
      [ \ 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 ())

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
  -- We keep the socket open so we claim the port.
  bracketOnError openSocketAvailablePort Network.Socket.close $ \ sock -> do
  let
    interpSettings = InterpreterSettings
      -- 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 `finally` removeFile tempfile ]
    (sendRunInTerminalReverseRequest
      RunInTerminalRequestArguments
        { runInTerminalRequestArgumentsKind = Just RunInTerminalRequestArgumentsKindIntegrated
        , runInTerminalRequestArgumentsTitle = Nothing
        , runInTerminalRequestArgumentsCwd = ""
        , runInTerminalRequestArgumentsArgs =
            [T.pack hdbProg, "external-interpreter", "--port", T.pack (show extInterpPort)]
            ++ 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 = 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
          }
        waitForDebuggee =
          -- Only start executing after proxy client connects succesfully (#95)
          takeMVar proxyClientReady
    tempfile <- liftIO $ emptySystemTempFile "hdb-session.tmp"
    pure $ DAPDebuggee
      interpSettings
      waitForDebuggee
      [ \ 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 $ HM.singleton sessionFileEnvVar $ T.pack tempfile)

sessionFileEnvVar :: T.Text
sessionFileEnvVar = "SESSIONFILE"

--------------------------------------------------------------------------------
-- * Logging
--------------------------------------------------------------------------------
type SessionId = T.Text
data DAPSessionLog
  = 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
stdinForwardAction :: IO (BS.ByteString -> IO ())
stdinForwardAction = do
  -- We need to hijack stdin to write to it

  -- 1. Create a new pipe from writeEnd->readEnd
  (readEnd, writeEnd) <- createPipe

  -- 2. Substitute the read-end of the pipe by stdin
  _ <- hDuplicateTo readEnd stdin
  hClose readEnd -- we'll never need to read from readEnd

  pure $ \ i -> do
    -- 3. Write to write-end of the pipe
    BS.hPut writeEnd i >> hFlush writeEnd

-- | This thread captures stdout from the debuggee and sends it to the client.
-- 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 :: LogAction IO T.Text -> (BS.ByteString -> IO ()) -> (DebugAdaptorCont () -> IO ()) -> IO ()
stdoutCaptureThread l msyncOut withAdaptor = do
  tid <- myThreadId
  labelThread tid "Stdout Capture Thread"
  withInterceptedStdout $ \_ -> forwardingCaptured l msyncOut (withAdaptor . Output.stdout)

-- | Like 'stdoutCaptureThread' but for stderr
stderrCaptureThread :: LogAction IO T.Text -> (BS.ByteString -> IO ()) -> (DebugAdaptorCont () -> IO ()) -> IO ()
stderrCaptureThread l msyncErr withAdaptor = do
  tid <- myThreadId
  labelThread tid "Stderr Capture Thread"
  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
        (debugConsole line)
        (\(_ :: IOException) ->
          throwIO (FailedToWriteToAdaptor line))

newtype FailedToWriteToAdaptor = FailedToWriteToAdaptor T.Text
instance Show FailedToWriteToAdaptor where
  show (FailedToWriteToAdaptor t) = "Failed to write to debug adapter: " ++ T.unpack t
instance Exception FailedToWriteToAdaptor