+-- Left: full path name of a .o file, including trailing .o
+-- Right: "unadorned" name of a .DLL/.so
+-- e.g. On unix "qt" denotes "libqt.so"
+-- On WinDoze "burble" denotes "burble.DLL"
+-- addDLL is platform-specific and adds the lib/.so/.DLL
+-- suffixes platform-dependently; we don't do that here.
+--
+-- For dynamic objects only, try to find the object file in all the
+-- directories specified in v_Library_Paths before giving up.
+
+type LibrarySpec
+ = Either FilePath String
+
+showLS (Left nm) = "(static) " ++ nm
+showLS (Right nm) = "(dynamic) " ++ nm
+
+linkPackages :: [LibrarySpec] -> [PackageConfig] -> IO ()
+linkPackages cmdline_lib_specs pkgs
+ = do sequence_ [ linkPackage (name p `elem` loaded) p | p <- reverse pkgs ]
+ lib_paths <- readIORef v_Library_paths
+ mapM_ (preloadLib lib_paths) cmdline_lib_specs
+ where
+ -- packages that are already linked into GHCi
+ loaded = [ "concurrent", "posix", "text", "util" ]
+
+ preloadLib :: [String] -> LibrarySpec -> IO ()
+ preloadLib lib_paths lib_spec
+ = do putStr ("Loading object " ++ showLS lib_spec ++ " ... ")
+ case lib_spec of
+ Left static_ish
+ -> do b <- preload_static lib_paths static_ish
+ putStrLn (if b then "done" else "not found")
+ Right dll_unadorned
+ -> -- We add "" to the set of paths to try, so that
+ -- if none of the real paths match, we force addDLL
+ -- to look in the default dynamic-link search paths.
+ do b <- preload_dynamic (lib_paths++[""]) dll_unadorned
+ when (not b) (cantFind lib_paths lib_spec)
+ putStrLn "done"
+
+ cantFind :: [String] -> LibrarySpec -> IO ()
+ cantFind paths spec
+ = do putStr ("failed.\nCan't find " ++ showLS spec
+ ++ " in directories:\n"
+ ++ unlines (map (" "++) paths) )
+ give_up
+
+ -- not interested in the paths in the static case.
+ preload_static paths name
+ = do b <- doesFileExist name
+ if not b then return False
+ else loadObj name >> return True
+
+ preload_dynamic [] name
+ = return False
+ preload_dynamic (path:paths) rootname
+ = do maybe_errmsg <- addDLL path rootname
+ if maybe_errmsg /= nullPtr
+ then preload_dynamic paths rootname
+ else return True
+
+ give_up
+ = (throwDyn . CmdLineError)
+ "user specified .o/.so/.DLL could not be loaded."
+
+
+linkPackage :: Bool -> PackageConfig -> IO ()