+-- return our temporary directory within tmp_dir, creating one if we
+-- don't have one yet
+getTempDir :: DynFlags -> IO FilePath
+getTempDir dflags@(DynFlags{tmpDir=tmp_dir})
+ = do mapping <- readIORef v_DirsToClean
+ case lookupFM mapping tmp_dir of
+ Nothing ->
+ do x <- getProcessID
+ let prefix = tmp_dir ++ "/ghc" ++ show x ++ "_"
+ mkTempDir x
+ = let dirname = prefix ++ show x
+ in do createDirectory dirname
+ let mapping' = addToFM mapping tmp_dir dirname
+ writeIORef v_DirsToClean mapping'
+ debugTraceMsg dflags 2 (ptext SLIT("Created temporary directory:") <+> text dirname)
+ return dirname
+ `IO.catch` \e ->
+ if isAlreadyExistsError e
+ then mkTempDir (x+1)
+ else ioError e
+ mkTempDir 0
+ Just d -> return d
+