Skip to content

Commit

Permalink
Fix a segmentation fault with Python 3.10.1
Browse files Browse the repository at this point in the history
Problem: After upgrading to Python 3.10.1 and reinstalling PtGhci, I
started getting segfaults on initialization.

Solution: According to a note in
https://docs.python.org/3/c-api/init.html#before-python-initialization,
`Py_GetPath` should not be called before `Py_Initialize`, but PtGhci
does so anyway. The solution is simply to print debugging info after
Python is initialized.

I also removed some extraneous whitespace I found in Main while
debugging this.
  • Loading branch information
heitor-lassarote committed Dec 22, 2021
1 parent bbb3c5f commit 89df601
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 6 deletions.
5 changes: 1 addition & 4 deletions app/Main.hs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

module Main where

import Foreign.C.Types
Expand Down Expand Up @@ -29,7 +28,6 @@ main = do
lookupEnv "PTGHCI_ENGINE_MODE" >>= \case
Just _ -> runEngineMode env sockets
Nothing -> runPythonInProc env sockets


-- | The normal way we run -- Python interpreter runs prompt-toolkit loop
-- in-process.
Expand All @@ -50,10 +48,9 @@ runPythonInProc env sockets = do
runEngineMode :: Env -> Sockets -> IO ()
runEngineMode env sockets = do
sockAddrs <- socketEndpoints sockets

-- Print the socket addresses so Python knows how to connect
print sockAddrs >> hFlush stdout

(appThread, quitApp) <- runApp env sockets
wait appThread `finally` quitApp

4 changes: 2 additions & 2 deletions src/Language/Haskell/PtGhci/StartPy.hs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ startPythonApp env (requestAddr, controlAddr, iopubAddr) = do
setEnv "PTGHCI_REQUEST_ADDR" requestAddr
setEnv "PTGHCI_CONTROL_ADDR" controlAddr
setEnv "PTGHCI_IOPUB_ADDR" iopubAddr
printDebugInfo env
s <- newCString $ unlines [ "import os, sys"
,"from ptghci.app import App"
,"app = App()"
Expand All @@ -48,6 +47,7 @@ startPythonApp env (requestAddr, controlAddr, iopubAddr) = do
where
runPy s done = do
pyInitialize
printDebugInfo env
res <- pyRunSimpleString s
when (res == -1) $
logerr env $ "Python exited with an exception"
Expand All @@ -72,7 +72,7 @@ startPythonApp env (requestAddr, controlAddr, iopubAddr) = do

printDebugInfo :: Env -> IO ()
printDebugInfo env = do
debug env $ "Python thread starting"
debug env $ "Python thread started"
pyVer <- pyGetVersion >>= peekCString
pyPath <- pyGetPath >>= peekCWString
debug env $ "Python version " ++ pyVer
Expand Down

0 comments on commit 89df601

Please sign in to comment.