This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 830416c29e fix(bindings/haskell): repair FFI memory ownership and 
cleanup paths (#8744)
830416c29e is described below

commit 830416c29ee76ddc2b5d97316673d9af87ebadc6
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 07:07:50 2026 +0800

    fix(bindings/haskell): repair FFI memory ownership and cleanup paths (#8744)
    
    * fix(bindings/haskell): repair FFI memory ownership and cleanup paths
    
    Every Rust allocation handed to Haskell across the FFI boundary is now
    released by an exported Rust function instead of leaking or being freed
    by the wrong allocator:
    
    - FFIResult data_ptr: handle results pass the boxed handle directly;
      string results pass the CString pointer; inline values get matching
      free_byteslice/free_bool/free_metadata exports so the box and payload
      are released together.
    - error_message CStrings on failure paths are released via free_string.
    - ByteSlice now stores a Box<[u8]> so free_byteslice rebuilds the exact
      allocation layout (the old Vec::from_raw_parts used len for capacity).
    - blocking_write/writer_write copy caller buffers with
      slice::from_raw_parts instead of wrapping foreign memory in Vec.
    - CString::new().unwrap() calls that could panic across FFI on interior
      NUL bytes now escape them; null path/scheme/config inputs return
      FFIResult::err instead of UB; blocking::Operator::new errors are
      reported instead of unwrapped.
    - Haskell side frees via finally/onException so resources are released
      even when exceptions are thrown, and uses the Rust free functions
      instead of C free().
    
    Closes #8743
    
    * fix(bindings/haskell): harden FFI cleanup against exceptions and aliasing
    
    - ByteSlice::from_vec uses Box::into_raw so the leaked pointer keeps its
      provenance instead of outliving a moved Box via as_mut_ptr.
    - Every FFI result-processing block on the Haskell side runs under
      mask_, closing the async-exception window where data_ptr or
      error_message could leak, and making handle finalizer registration
      atomic with the onException fallback (no double-free on interruption).
    - via_map_ffi reports an FFIError for null or non-UTF-8 config
      keys/values instead of silently substituting empty strings.
    - ffi_result_layout_matches_abi derives its expectation from usize.
    
    Review feedback on #8744.
---
 bindings/haskell/haskell-src/OpenDAL.hs     | 224 ++++-----
 bindings/haskell/haskell-src/OpenDAL/FFI.hs |  27 +-
 bindings/haskell/opendal.cabal              |   2 +-
 bindings/haskell/src/lib.rs                 | 742 +++++++++++++++++++---------
 bindings/haskell/src/logger.rs              |   4 +-
 bindings/haskell/src/result.rs              | 128 ++++-
 bindings/haskell/src/types.rs               | 278 ++++++++---
 bindings/haskell/test/ResourceTest.hs       | 151 ++++++
 bindings/haskell/test/Spec.hs               |   4 +-
 9 files changed, 1095 insertions(+), 465 deletions(-)

diff --git a/bindings/haskell/haskell-src/OpenDAL.hs 
b/bindings/haskell/haskell-src/OpenDAL.hs
index 8d8f377ac2..c1492c2682 100644
--- a/bindings/haskell/haskell-src/OpenDAL.hs
+++ b/bindings/haskell/haskell-src/OpenDAL.hs
@@ -75,6 +75,7 @@ module OpenDAL
 where
 
 import Colog (LogAction, Message, Msg (Msg), (<&))
+import Control.Exception (finally, mask_, onException)
 import Control.Monad.Except (ExceptT, MonadError, MonadTrans, runExceptT, 
throwError)
 import Control.Monad.Reader (MonadIO, MonadReader, ReaderT, ask, liftIO, 
runReaderT)
 import Control.Monad.Trans (MonadTrans (lift))
@@ -82,6 +83,7 @@ import Data.ByteString (ByteString)
 import qualified Data.ByteString as BS
 import Data.HashMap.Strict (HashMap)
 import qualified Data.HashMap.Strict as HashMap
+import Data.Maybe (fromMaybe)
 import Data.String (IsString (fromString))
 import Data.Text (pack)
 import Data.Time (UTCTime, parseTimeM, zonedTimeToUTC)
@@ -304,7 +306,9 @@ instance (MonadIO m) => MonadOperation (OperatorT m) where
 -- helper functions
 
 byteSliceToByteString :: ByteSlice -> IO ByteString
-byteSliceToByteString (ByteSlice bsDataPtr len) = BS.packCStringLen 
(bsDataPtr, fromIntegral len)
+byteSliceToByteString (ByteSlice bsDataPtr len)
+  | bsDataPtr == nullPtr || len == 0 = return BS.empty
+  | otherwise = BS.packCStringLen (bsDataPtr, fromIntegral len)
 
 parseErrorCode :: Int -> ErrorCode
 parseErrorCode 1 = FFIError
@@ -328,32 +332,42 @@ parseEntryMode 0 = File
 parseEntryMode 1 = Dir
 parseEntryMode _ = Unknown
 
-parseCString :: CString -> IO (Maybe String)
-parseCString value | value == nullPtr = return Nothing
-parseCString value = do
-  value' <- peekCString value
-  free value
-  return $ Just value'
-
-parseString :: CString -> IO String
-parseString value = do
-  value' <- peekCString value
-  free value
-  return value'
+maybePeekCString :: CString -> IO (Maybe String)
+maybePeekCString value | value == nullPtr = return Nothing
+maybePeekCString value = Just <$> peekCString value
+
+-- | Peek a Rust-owned `CString` and release it through Rust's `free_string`.
+-- The pointer is always released, even when `peekCString` throws.
+-- Every byte allocated by Rust must be freed by a Rust function; calling C
+-- `free` on it is an allocator mismatch.
+parseOwnedCString :: CString -> IO (Maybe String)
+parseOwnedCString value
+  | value == nullPtr = return Nothing
+  | otherwise = (Just <$> peekCString value) `finally` freeString value
+
+-- | Convert a failed `FFIResult` into an `OpenDALError`, releasing the
+-- Rust-owned `errorMessage` buffer through `free_string`.
+parseError :: FFIResult a -> IO OpenDALError
+parseError ffiResult = do
+  let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
+  errMsg <- fromMaybe "" <$> parseOwnedCString (errorMessage ffiResult)
+  return $ OpenDALError code errMsg
 
 parseTime :: String -> Maybe UTCTime
 parseTime time = zonedTimeToUTC <$> parseTimeM True defaultTimeLocale 
"%Y-%m-%dT%H:%M:%S%Q%z" time
 
+-- | Peek the fields of a Rust `Metadata`. The caller releases the whole
+-- struct through `free_metadata`, so fields are peeked but never freed here.
 parseFFIMetadata :: FFIMetadata -> IO Metadata
 parseFFIMetadata (FFIMetadata mode cacheControl contentDisposition 
contentLength contentMD5 contentType eTag lastModified) = do
   let mode' = parseEntryMode $ fromIntegral mode
-  cacheControl' <- parseCString cacheControl
-  contentDisposition' <- parseCString contentDisposition
+  cacheControl' <- maybePeekCString cacheControl
+  contentDisposition' <- maybePeekCString contentDisposition
   let contentLength' = toInteger contentLength
-  contentMD5' <- parseCString contentMD5
-  contentType' <- parseCString contentType
-  eTag' <- parseCString eTag
-  lastModified' <- (>>= parseTime) <$> parseCString lastModified
+  contentMD5' <- maybePeekCString contentMD5
+  contentType' <- maybePeekCString contentType
+  eTag' <- maybePeekCString eTag
+  lastModified' <- (>>= parseTime) <$> maybePeekCString lastModified
   return $
     Metadata
       { mMode = mode',
@@ -408,7 +422,11 @@ newOperator (OperatorConfig scheme hashMap maybeLogger) = 
do
       withMany withCString (map snd keysAndValues) $ \cValues ->
         allocaArray (length keysAndValues) $ \cKeysPtr ->
           allocaArray (length keysAndValues) $ \cValuesPtr ->
-            alloca $ \ffiResultPtr -> do
+            alloca $ \ffiResultPtr -> mask_ $ do
+              -- Once Rust registers the logger the callback is owned by the
+              -- global Rust logger for the rest of the process. We
+              -- deliberately never call freeHaskellFunPtr: if registration
+              -- succeeded, freeing it would leave a dangling pointer.
               logFnPtr <- case maybeLogger of
                 Just logger -> wrapLogFn (logFn logger)
                 Nothing -> return nullFunPtr
@@ -418,12 +436,12 @@ newOperator (OperatorConfig scheme hashMap maybeLogger) = 
do
               ffiResult <- peek ffiResultPtr
               if ffiCode ffiResult == 0
                 then do
-                  op <- Operator <$> newForeignPtr c_free_operator (dataPtr 
ffiResult)
+                  op <-
+                    Operator
+                      <$> newForeignPtr c_free_operator (dataPtr ffiResult)
+                      `onException` freeOperator (dataPtr ffiResult)
                   return $ Right op
-                else do
-                  let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-                  errMsg <- peekCString (errorMessage ffiResult)
-                  return $ Left $ OpenDALError code errMsg
+                else Left <$> parseError ffiResult
   where
     logFn logger enumSeverity cStr = do
       str <- peekCString cStr
@@ -438,126 +456,103 @@ newOperator (OperatorConfig scheme hashMap maybeLogger) 
= do
 readOpRaw :: Operator -> String -> IO (Either OpenDALError ByteString)
 readOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_read opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then do
-          byteslice <- peek $ dataPtr ffiResult
-          byte <- byteSliceToByteString byteslice
-          c_free_byteslice (bsData byteslice) (bsLen byteslice)
+          byte <-
+            (peek (dataPtr ffiResult) >>= byteSliceToByteString)
+              `finally` freeByteSlice (dataPtr ffiResult)
           return $ Right byte
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | Write bytes into given path.
 writeOpRaw :: Operator -> String -> ByteString -> IO (Either OpenDALError ())
 writeOpRaw (Operator op) path byte = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
     BS.useAsCStringLen byte $ \(cByte, len) ->
-      alloca $ \ffiResultPtr -> do
+      alloca $ \ffiResultPtr -> mask_ $ do
         c_blocking_write opptr cPath cByte (fromIntegral len) ffiResultPtr
         ffiResult <- peek ffiResultPtr
         if ffiCode ffiResult == 0
           then return $ Right ()
-          else do
-            let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-            errMsg <- peekCString (errorMessage ffiResult)
-            return $ Left $ OpenDALError code errMsg
+          else Left <$> parseError ffiResult
 
 -- | Check if this path exists or not.
 isExistOpRaw :: Operator -> String -> IO (Either OpenDALError Bool)
 isExistOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_is_exist opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then do
-          val <- peek $ dataPtr ffiResult
+          val <- peek (dataPtr ffiResult) `finally` freeBool (dataPtr 
ffiResult)
           let isExist = val /= 0
           return $ Right isExist
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | Create a dir at given path.
 createDirOpRaw :: Operator -> String -> IO (Either OpenDALError ())
 createDirOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_create_dir opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then return $ Right ()
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | Copy a file from srcPath to dstPath.
 copyOpRaw :: Operator -> String -> String -> IO (Either OpenDALError ())
 copyOpRaw (Operator op) srcPath dstPath = withForeignPtr op $ \opptr ->
   withCString srcPath $ \cSrcPath ->
     withCString dstPath $ \cDstPath ->
-      alloca $ \ffiResultPtr -> do
+      alloca $ \ffiResultPtr -> mask_ $ do
         c_blocking_copy opptr cSrcPath cDstPath ffiResultPtr
         ffiResult <- peek ffiResultPtr
         if ffiCode ffiResult == 0
           then return $ Right ()
-          else do
-            let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-            errMsg <- peekCString (errorMessage ffiResult)
-            return $ Left $ OpenDALError code errMsg
+          else Left <$> parseError ffiResult
 
 -- | Rename a file from srcPath to dstPath.
 renameOpRaw :: Operator -> String -> String -> IO (Either OpenDALError ())
 renameOpRaw (Operator op) srcPath dstPath = withForeignPtr op $ \opptr ->
   withCString srcPath $ \cSrcPath ->
     withCString dstPath $ \cDstPath ->
-      alloca $ \ffiResultPtr -> do
+      alloca $ \ffiResultPtr -> mask_ $ do
         c_blocking_rename opptr cSrcPath cDstPath ffiResultPtr
         ffiResult <- peek ffiResultPtr
         if ffiCode ffiResult == 0
           then return $ Right ()
-          else do
-            let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-            errMsg <- peekCString (errorMessage ffiResult)
-            return $ Left $ OpenDALError code errMsg
+          else Left <$> parseError ffiResult
 
 -- | Delete given path.
 deleteOpRaw :: Operator -> String -> IO (Either OpenDALError ())
 deleteOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_delete opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then return $ Right ()
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | Get given path's metadata without cache directly.
 statOpRaw :: Operator -> String -> IO (Either OpenDALError Metadata)
 statOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_stat opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then do
-          ffimatadata <- peek $ dataPtr ffiResult
-          metadata <- parseFFIMetadata ffimatadata
+          metadata <-
+            (peek (dataPtr ffiResult) >>= parseFFIMetadata)
+              `finally` freeMetadata (dataPtr ffiResult)
           return $ Right metadata
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | List current dir path.
 -- This function will create a new handle to list entries.
@@ -565,18 +560,17 @@ statOpRaw (Operator op) path = withForeignPtr op $ \opptr 
->
 listOpRaw :: Operator -> String -> IO (Either OpenDALError Lister)
 listOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_list opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then do
-          ffilister <- peek $ dataPtr ffiResult
-          lister <- Lister <$> newForeignPtr c_free_lister ffilister
+          lister <-
+            Lister
+              <$> newForeignPtr c_free_lister (dataPtr ffiResult)
+              `onException` freeLister (dataPtr ffiResult)
           return $ Right lister
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | List dir in flat way.
 -- Also, this function can be used to list a prefix.
@@ -584,98 +578,81 @@ listOpRaw (Operator op) path = withForeignPtr op $ \opptr 
->
 scanOpRaw :: Operator -> String -> IO (Either OpenDALError Lister)
 scanOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_scan opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then do
-          ffilister <- peek $ dataPtr ffiResult
-          lister <- Lister <$> newForeignPtr c_free_lister ffilister
+          lister <-
+            Lister
+              <$> newForeignPtr c_free_lister (dataPtr ffiResult)
+              `onException` freeLister (dataPtr ffiResult)
           return $ Right lister
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | Get operator info (scheme).
 operatorInfoRaw :: Operator -> IO (Either OpenDALError String)
 operatorInfoRaw (Operator op) = withForeignPtr op $ \opptr ->
-  alloca $ \ffiResultPtr -> do
+  alloca $ \ffiResultPtr -> mask_ $ do
     c_operator_info opptr ffiResultPtr
     ffiResult <- peek ffiResultPtr
     if ffiCode ffiResult == 0
-      then do
-        val <- peek $ dataPtr ffiResult
-        Right <$> parseString val
-      else do
-        let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-        errMsg <- peekCString (errorMessage ffiResult)
-        return $ Left $ OpenDALError code errMsg
+      then Right . fromMaybe "" <$> parseOwnedCString (dataPtr ffiResult)
+      else Left <$> parseError ffiResult
 
 -- | Get next entry path from `Lister`.
 nextLister :: Lister -> IO (Either OpenDALError (Maybe String))
 nextLister (Lister lister) = withForeignPtr lister $ \listerptr ->
-  alloca $ \ffiResultPtr -> do
+  alloca $ \ffiResultPtr -> mask_ $ do
     c_lister_next listerptr ffiResultPtr
     ffiResult <- peek ffiResultPtr
     if ffiCode ffiResult == 0
-      then do
-        val <- peek $ dataPtr ffiResult
-        Right <$> parseCString val
-      else do
-        let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-        errMsg <- peekCString (errorMessage ffiResult)
-        return $ Left $ OpenDALError code errMsg
+      then Right <$> parseOwnedCString (dataPtr ffiResult)
+      else Left <$> parseError ffiResult
 
 
 -- | Writes bytes into given writer.
 writerWrite :: Writer -> ByteString -> IO (Either OpenDALError ())
 writerWrite (Writer writer) byte = withForeignPtr writer $ \writerptr ->
   BS.useAsCStringLen byte $ \(cByte, len) ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_writer_write writerptr cByte (fromIntegral len) ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then return $ Right ()
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 -- | Closes given writer.
 writerClose :: Writer -> IO (Either OpenDALError Metadata)
 writerClose (Writer writer) = withForeignPtr writer $ \writerptr ->
-  alloca $ \ffiResultPtr -> do
+  alloca $ \ffiResultPtr -> mask_ $ do
     c_writer_close writerptr ffiResultPtr
     ffiResult <- peek ffiResultPtr
     if ffiCode ffiResult == 0
       then do
-        ffimatadata <- peek $ dataPtr ffiResult
-        metadata <- parseFFIMetadata ffimatadata
+        metadata <-
+          (peek (dataPtr ffiResult) >>= parseFFIMetadata)
+            `finally` freeMetadata (dataPtr ffiResult)
         return $ Right metadata
-      else do
-        let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-        errMsg <- peekCString (errorMessage ffiResult)
-        return $ Left $ OpenDALError code errMsg
+      else Left <$> parseError ffiResult
 
 -- | Create a new writer for given path with specified options.
 writerOpRaw :: Operator -> String -> WriterOption -> IO (Either OpenDALError 
Writer)
 writerOpRaw (Operator op) path writerOption = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       if woAppend writerOption
         then c_blocking_writer_append opptr cPath ffiResultPtr
         else c_blocking_writer opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then do
-          ffiwriter <- peek $ dataPtr ffiResult
-          writer <- Writer <$> newForeignPtr c_free_writer ffiwriter
+          writer <-
+            Writer
+              <$> newForeignPtr c_free_writer (dataPtr ffiResult)
+              `onException` freeWriter (dataPtr ffiResult)
           return $ Right writer
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
 
 
 
@@ -683,12 +660,9 @@ writerOpRaw (Operator op) path writerOption = 
withForeignPtr op $ \opptr ->
 removeAllOpRaw :: Operator -> String -> IO (Either OpenDALError ())
 removeAllOpRaw (Operator op) path = withForeignPtr op $ \opptr ->
   withCString path $ \cPath ->
-    alloca $ \ffiResultPtr -> do
+    alloca $ \ffiResultPtr -> mask_ $ do
       c_blocking_remove_all opptr cPath ffiResultPtr
       ffiResult <- peek ffiResultPtr
       if ffiCode ffiResult == 0
         then return $ Right ()
-        else do
-          let code = parseErrorCode $ fromIntegral $ ffiCode ffiResult
-          errMsg <- peekCString (errorMessage ffiResult)
-          return $ Left $ OpenDALError code errMsg
+        else Left <$> parseError ffiResult
diff --git a/bindings/haskell/haskell-src/OpenDAL/FFI.hs 
b/bindings/haskell/haskell-src/OpenDAL/FFI.hs
index d52bf823c0..38d511c2f4 100644
--- a/bindings/haskell/haskell-src/OpenDAL/FFI.hs
+++ b/bindings/haskell/haskell-src/OpenDAL/FFI.hs
@@ -139,7 +139,15 @@ foreign import ccall "wrapper"
 
 foreign import ccall "&free_operator" c_free_operator :: FunPtr (Ptr 
RawOperator -> IO ())
 
-foreign import ccall "free_byteslice" c_free_byteslice :: Ptr CChar -> CSize 
-> IO ()
+foreign import ccall "free_operator" freeOperator :: Ptr RawOperator -> IO ()
+
+foreign import ccall "free_byteslice" freeByteSlice :: Ptr ByteSlice -> IO ()
+
+foreign import ccall "free_bool" freeBool :: Ptr CBool -> IO ()
+
+foreign import ccall "free_string" freeString :: CString -> IO ()
+
+foreign import ccall "free_metadata" freeMetadata :: Ptr FFIMetadata -> IO ()
 
 foreign import ccall "blocking_read" c_blocking_read :: Ptr RawOperator -> 
CString -> Ptr (FFIResult ByteSlice) -> IO ()
 
@@ -157,20 +165,21 @@ foreign import ccall "blocking_delete" c_blocking_delete 
:: Ptr RawOperator -> C
 
 foreign import ccall "blocking_stat" c_blocking_stat :: Ptr RawOperator -> 
CString -> Ptr (FFIResult FFIMetadata) -> IO ()
 
-foreign import ccall "blocking_list" c_blocking_list :: Ptr RawOperator -> 
CString -> Ptr (FFIResult (Ptr RawLister)) -> IO ()
+foreign import ccall "blocking_list" c_blocking_list :: Ptr RawOperator -> 
CString -> Ptr (FFIResult RawLister) -> IO ()
 
-foreign import ccall "blocking_scan" c_blocking_scan :: Ptr RawOperator -> 
CString -> Ptr (FFIResult (Ptr RawLister)) -> IO ()
+foreign import ccall "blocking_scan" c_blocking_scan :: Ptr RawOperator -> 
CString -> Ptr (FFIResult RawLister) -> IO ()
 
-foreign import ccall "lister_next" c_lister_next :: Ptr RawLister -> Ptr 
(FFIResult CString) -> IO ()
+foreign import ccall "lister_next" c_lister_next :: Ptr RawLister -> Ptr 
(FFIResult CChar) -> IO ()
 
 foreign import ccall "&free_lister" c_free_lister :: FunPtr (Ptr RawLister -> 
IO ())
 
+foreign import ccall "free_lister" freeLister :: Ptr RawLister -> IO ()
 
-foreign import ccall "operator_info" c_operator_info :: Ptr RawOperator -> Ptr 
(FFIResult CString) -> IO ()
+foreign import ccall "operator_info" c_operator_info :: Ptr RawOperator -> Ptr 
(FFIResult CChar) -> IO ()
 
-foreign import ccall "blocking_writer" c_blocking_writer :: Ptr RawOperator -> 
CString -> Ptr (FFIResult (Ptr RawWriter)) -> IO ()
+foreign import ccall "blocking_writer" c_blocking_writer :: Ptr RawOperator -> 
CString -> Ptr (FFIResult RawWriter) -> IO ()
 
-foreign import ccall "blocking_writer_append" c_blocking_writer_append :: Ptr 
RawOperator -> CString -> Ptr (FFIResult (Ptr RawWriter)) -> IO ()
+foreign import ccall "blocking_writer_append" c_blocking_writer_append :: Ptr 
RawOperator -> CString -> Ptr (FFIResult RawWriter) -> IO ()
 
 foreign import ccall "writer_write" c_writer_write :: Ptr RawWriter -> Ptr 
CChar -> CSize -> Ptr (FFIResult ()) -> IO ()
 
@@ -178,4 +187,6 @@ foreign import ccall "writer_close" c_writer_close :: Ptr 
RawWriter -> Ptr (FFIR
 
 foreign import ccall "&free_writer" c_free_writer :: FunPtr (Ptr RawWriter -> 
IO ())
 
-foreign import ccall "blocking_remove_all" c_blocking_remove_all :: Ptr 
RawOperator -> CString -> Ptr (FFIResult ()) -> IO ()
\ No newline at end of file
+foreign import ccall "free_writer" freeWriter :: Ptr RawWriter -> IO ()
+
+foreign import ccall "blocking_remove_all" c_blocking_remove_all :: Ptr 
RawOperator -> CString -> Ptr (FFIResult ()) -> IO ()
diff --git a/bindings/haskell/opendal.cabal b/bindings/haskell/opendal.cabal
index 4aab144043..1014ca6ff6 100644
--- a/bindings/haskell/opendal.cabal
+++ b/bindings/haskell/opendal.cabal
@@ -81,7 +81,7 @@ test-suite opendal-test
     import:           base
     type:             exitcode-stdio-1.0
     main-is:          Spec.hs
-    other-modules:    BasicTest, WriterTest, ErrorTest, PerformanceTest
+    other-modules:    BasicTest, WriterTest, ErrorTest, PerformanceTest, 
ResourceTest
     hs-source-dirs:   test
     build-depends:
         opendal,
diff --git a/bindings/haskell/src/lib.rs b/bindings/haskell/src/lib.rs
index 231306d40e..f1ece91a7e 100644
--- a/bindings/haskell/src/lib.rs
+++ b/bindings/haskell/src/lib.rs
@@ -21,8 +21,6 @@ mod types;
 
 use std::collections::HashMap;
 use std::ffi::CStr;
-use std::ffi::CString;
-use std::mem;
 use std::os::raw::c_char;
 use std::sync::LazyLock;
 
@@ -35,6 +33,7 @@ use opendal::blocking;
 use result::FFIResult;
 use types::ByteSlice;
 use types::Metadata;
+use types::into_raw_c_string;
 
 static RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
     tokio::runtime::Builder::new_multi_thread()
@@ -43,18 +42,28 @@ static RUNTIME: LazyLock<tokio::runtime::Runtime> = 
LazyLock::new(|| {
         .unwrap()
 });
 
+/// Convert a caller-provided, possibly null, C string argument into `&str`.
+///
+/// Returns `None` for a null pointer or non UTF-8 content so callers can
+/// report an `FFIResult::err` instead of dereferencing an invalid pointer.
+unsafe fn c_str_arg<'a>(ptr: *const c_char) -> Option<&'a str> {
+    unsafe {
+        if ptr.is_null() {
+            return None;
+        }
+        CStr::from_ptr(ptr).to_str().ok()
+    }
+}
+
 /// # Safety
 ///
-/// * The `keys`, `values`, `len` are valid from `HashMap`.
-/// * The memory pointed to by `scheme` contain a valid nul terminator at the 
end of
-///   the string.
-/// * The `result` is a valid pointer, and has available memory to write to.
+/// * `scheme` points to a nul-terminated string, or is null.
+/// * When `len > 0`, `keys` and `values` point to arrays of `len` valid
+///   nul-terminated strings.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 ///
 /// # Panics
 ///
-/// * If `keys` or `values` are not valid pointers.
-/// * If `len` is not the same for `keys` and `values`.
-/// * If `log_level` is not a valid value passed by haskell.
 /// * If `callback` is not a valid function pointer.
 /// * If `result` is not a valid pointer.
 #[unsafe(no_mangle)]
@@ -67,27 +76,48 @@ pub unsafe extern "C" fn via_map_ffi(
     result: *mut FFIResult<od::blocking::Operator>,
 ) {
     unsafe {
-        let scheme = match CStr::from_ptr(scheme).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let scheme = match c_str_arg(scheme) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert scheme to string");
                 return;
             }
         };
 
-        let keys_vec = std::slice::from_raw_parts(keys, len);
-        let values_vec = std::slice::from_raw_parts(values, len);
+        if len > 0 && (keys.is_null() || values.is_null()) {
+            *result = FFIResult::err("Config keys/values are null");
+            return;
+        }
+
+        let keys_vec = if len == 0 {
+            &[][..]
+        } else {
+            std::slice::from_raw_parts(keys, len)
+        };
+        let values_vec = if len == 0 {
+            &[][..]
+        } else {
+            std::slice::from_raw_parts(values, len)
+        };
 
-        let map = keys_vec
-            .iter()
-            .zip(values_vec.iter())
-            .map(|(&k, &v)| {
-                (
-                    CStr::from_ptr(k).to_string_lossy().into_owned(),
-                    CStr::from_ptr(v).to_string_lossy().into_owned(),
-                )
-            })
-            .collect::<HashMap<String, String>>();
+        let mut map = HashMap::with_capacity(len);
+        for (&k, &v) in keys_vec.iter().zip(values_vec.iter()) {
+            let key = match c_str_arg(k) {
+                Some(s) => s.to_string(),
+                None => {
+                    *result = FFIResult::err("Config key is not a valid 
string");
+                    return;
+                }
+            };
+            let value = match c_str_arg(v) {
+                Some(s) => s.to_string(),
+                None => {
+                    *result = FFIResult::err("Config value is not a valid 
string");
+                    return;
+                }
+            };
+            map.insert(key, value);
+        }
 
         if let Some(callback) = callback
             && let Err(e) = log::set_boxed_logger(Box::new(HsLogger { callback 
}))
@@ -109,8 +139,10 @@ pub unsafe extern "C" fn via_map_ffi(
 
                 let handle = RUNTIME.handle();
                 let _enter = handle.enter();
-                let op = od::blocking::Operator::new(operator).unwrap();
-                FFIResult::ok(op)
+                match od::blocking::Operator::new(operator) {
+                    Ok(op) => FFIResult::ok(op),
+                    Err(e) => FFIResult::err_with_source("Failed to create 
blocking Operator", e),
+                }
             }
             Err(e) => FFIResult::err_with_source("Failed to create Operator", 
e),
         };
@@ -121,11 +153,8 @@ pub unsafe extern "C" fn via_map_ffi(
 
 /// # Safety
 ///
-/// * `operator` is a valid pointer to a `blocking::Operator`.
-///
-/// # Panics
-///
-/// * If `operator` is not a valid pointer.
+/// * `operator` is a valid pointer to a `blocking::Operator` created by
+///   `via_map_ffi`, or null.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn free_operator(operator: *mut od::blocking::Operator) {
     unsafe {
@@ -138,13 +167,10 @@ pub unsafe extern "C" fn free_operator(operator: *mut 
od::blocking::Operator) {
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` must be released with `free_byteslice`, on failure
+///   `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_read(
     op: *mut od::blocking::Operator,
@@ -159,9 +185,9 @@ pub unsafe extern "C" fn blocking_read(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -176,19 +202,29 @@ pub unsafe extern "C" fn blocking_read(
     }
 }
 
+/// Copy a caller-provided byte buffer into an owned `Vec<u8>`.
+///
+/// The buffer is borrowed for the duration of the call only; returning the
+/// slice itself across the FFI boundary would let Rust free memory it does
+/// not own.
+unsafe fn copy_bytes<'a>(bytes: *const c_char, len: usize) -> Option<&'a [u8]> 
{
+    unsafe {
+        if len == 0 {
+            return Some(&[]);
+        }
+        if bytes.is_null() {
+            return None;
+        }
+        Some(std::slice::from_raw_parts(bytes as *const u8, len))
+    }
+}
+
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `bytes` is a valid pointer to a byte array.
-/// * `len` is the length of `bytes`.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `bytes` is not a valid pointer, or `len` is more than the length of 
`bytes`.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `bytes` points to a byte array of `len` bytes, or is null when `len == 
0`.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_write(
     op: *mut od::blocking::Operator,
@@ -205,38 +241,38 @@ pub unsafe extern "C" fn blocking_write(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
         };
 
-        let bytes = Vec::from_raw_parts(bytes as *mut u8, len, len);
+        let bytes = match copy_bytes(bytes, len) {
+            Some(b) => b.to_vec(),
+            None => {
+                *result = FFIResult::err("Invalid bytes buffer");
+                return;
+            }
+        };
 
-        let res = match op.write(path_str, bytes.clone()) {
+        let res = match op.write(path_str, bytes) {
             Ok(_) => FFIResult::ok(()),
             Err(e) => FFIResult::err_with_source("Failed to write", e),
         };
 
         *result = res;
-
-        // bytes memory is controlled by Haskell, we can't drop it here
-        mem::forget(bytes);
     }
 }
 
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` must be released with `free_bool`, on failure
+///   `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_is_exist(
     op: *mut od::blocking::Operator,
@@ -251,9 +287,9 @@ pub unsafe extern "C" fn blocking_is_exist(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -271,13 +307,8 @@ pub unsafe extern "C" fn blocking_is_exist(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_create_dir(
     op: *mut od::blocking::Operator,
@@ -292,9 +323,9 @@ pub unsafe extern "C" fn blocking_create_dir(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -312,14 +343,8 @@ pub unsafe extern "C" fn blocking_create_dir(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path_from` is a valid pointer to a nul terminated string.
-/// * `path_to` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path_from` and `path_to` point to nul-terminated strings, or are null.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_copy(
     op: *mut od::blocking::Operator,
@@ -335,17 +360,17 @@ pub unsafe extern "C" fn blocking_copy(
             &mut *op
         };
 
-        let path_from_str = match CStr::from_ptr(path_from).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_from_str = match c_str_arg(path_from) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert source path to 
string");
                 return;
             }
         };
 
-        let path_to_str = match CStr::from_ptr(path_to).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_to_str = match c_str_arg(path_to) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert destination path 
to string");
                 return;
             }
@@ -363,14 +388,8 @@ pub unsafe extern "C" fn blocking_copy(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path_from` is a valid pointer to a nul terminated string.
-/// * `path_to` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path_from` and `path_to` point to nul-terminated strings, or are null.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_rename(
     op: *mut od::blocking::Operator,
@@ -386,17 +405,17 @@ pub unsafe extern "C" fn blocking_rename(
             &mut *op
         };
 
-        let path_from_str = match CStr::from_ptr(path_from).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_from_str = match c_str_arg(path_from) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert source path to 
string");
                 return;
             }
         };
 
-        let path_to_str = match CStr::from_ptr(path_to).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_to_str = match c_str_arg(path_to) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert destination path 
to string");
                 return;
             }
@@ -414,13 +433,8 @@ pub unsafe extern "C" fn blocking_rename(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_delete(
     op: *mut od::blocking::Operator,
@@ -435,9 +449,9 @@ pub unsafe extern "C" fn blocking_delete(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -455,13 +469,10 @@ pub unsafe extern "C" fn blocking_delete(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` must be released with `free_metadata`, on failure
+///   `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_stat(
     op: *mut od::blocking::Operator,
@@ -476,9 +487,9 @@ pub unsafe extern "C" fn blocking_stat(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -496,18 +507,15 @@ pub unsafe extern "C" fn blocking_stat(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` is a boxed `blocking::Lister` released by `free_lister`, on
+///   failure `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_list(
     op: *mut od::blocking::Operator,
     path: *const c_char,
-    result: *mut FFIResult<*mut blocking::Lister>,
+    result: *mut FFIResult<blocking::Lister>,
 ) {
     unsafe {
         let op = if op.is_null() {
@@ -517,16 +525,16 @@ pub unsafe extern "C" fn blocking_list(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
         };
 
         let res = match op.lister(path_str) {
-            Ok(lister) => FFIResult::ok(Box::into_raw(Box::new(lister))),
+            Ok(lister) => FFIResult::ok(lister),
             Err(e) => FFIResult::err_with_source("Failed to list", e),
         };
 
@@ -537,18 +545,15 @@ pub unsafe extern "C" fn blocking_list(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` is a boxed `blocking::Lister` released by `free_lister`, on
+///   failure `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_scan(
     op: *mut od::blocking::Operator,
     path: *const c_char,
-    result: *mut FFIResult<*mut blocking::Lister>,
+    result: *mut FFIResult<blocking::Lister>,
 ) {
     unsafe {
         let op = if op.is_null() {
@@ -558,9 +563,9 @@ pub unsafe extern "C" fn blocking_scan(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -573,7 +578,7 @@ pub unsafe extern "C" fn blocking_scan(
                 ..Default::default()
             },
         ) {
-            Ok(lister) => FFIResult::ok(Box::into_raw(Box::new(lister))),
+            Ok(lister) => FFIResult::ok(lister),
             Err(e) => FFIResult::err_with_source("Failed to scan", e),
         };
 
@@ -583,17 +588,15 @@ pub unsafe extern "C" fn blocking_scan(
 
 /// # Safety
 ///
-/// * `lister` is a valid pointer to a `BlockingLister`.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `lister` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `lister` is a valid pointer to a `blocking::Lister`.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` is a `CString` released by `free_string`, or null when the
+///   lister is exhausted; on failure `error_message` must be released with
+///   `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn lister_next(
     lister: *mut blocking::Lister,
-    result: *mut FFIResult<*const c_char>,
+    result: *mut FFIResult<c_char>,
 ) {
     unsafe {
         let lister = if lister.is_null() {
@@ -604,12 +607,9 @@ pub unsafe extern "C" fn lister_next(
         };
 
         let res = match lister.next() {
-            Some(Ok(item)) => {
-                let res = types::leak_str(item.path());
-                FFIResult::ok(res)
-            }
+            Some(Ok(item)) => 
FFIResult::ok_with_ptr(into_raw_c_string(item.path())),
             Some(Err(e)) => FFIResult::err_with_source("Failed to get next 
item", e),
-            None => FFIResult::ok(std::ptr::null()),
+            None => FFIResult::none(),
         };
 
         *result = res;
@@ -618,11 +618,8 @@ pub unsafe extern "C" fn lister_next(
 
 /// # Safety
 ///
-/// * `lister` is a valid pointer to a `BlockingLister`.
-///
-/// # Panics
-///
-/// * If `lister` is not a valid pointer.
+/// * `lister` is a valid pointer to a `blocking::Lister` created by
+///   `blocking_list` or `blocking_scan`, or null.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn free_lister(lister: *mut blocking::Lister) {
     unsafe {
@@ -637,16 +634,13 @@ pub unsafe extern "C" fn free_lister(lister: *mut 
blocking::Lister) {
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` is a `CString` released by `free_string`, on failure
+///   `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn operator_info(
     op: *mut od::blocking::Operator,
-    result: *mut FFIResult<*const c_char>,
+    result: *mut FFIResult<c_char>,
 ) {
     unsafe {
         let op = if op.is_null() {
@@ -659,15 +653,7 @@ pub unsafe extern "C" fn operator_info(
         let info = op.info();
         let scheme_str = info.scheme().to_string();
 
-        let res = match CString::new(scheme_str) {
-            Ok(c_string) => {
-                let ptr = c_string.into_raw() as *const c_char;
-                FFIResult::ok(ptr)
-            }
-            Err(_) => FFIResult::err("Failed to convert scheme to C string"),
-        };
-
-        *result = res;
+        *result = FFIResult::ok_with_ptr(into_raw_c_string(&scheme_str));
     }
 }
 
@@ -676,13 +662,8 @@ pub unsafe extern "C" fn operator_info(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_remove_all(
     op: *mut od::blocking::Operator,
@@ -697,9 +678,9 @@ pub unsafe extern "C" fn blocking_remove_all(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -728,18 +709,15 @@ pub unsafe extern "C" fn blocking_remove_all(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` is a boxed `blocking::Writer` released by `free_writer`, on
+///   failure `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_writer(
     op: *mut od::blocking::Operator,
     path: *const c_char,
-    result: *mut FFIResult<*mut blocking::Writer>,
+    result: *mut FFIResult<blocking::Writer>,
 ) {
     unsafe {
         let op = if op.is_null() {
@@ -749,16 +727,16 @@ pub unsafe extern "C" fn blocking_writer(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
         };
 
         let res = match op.writer(path_str) {
-            Ok(writer) => FFIResult::ok(Box::into_raw(Box::new(writer))),
+            Ok(writer) => FFIResult::ok(writer),
             Err(e) => FFIResult::err_with_source("Failed to create writer", e),
         };
 
@@ -771,18 +749,15 @@ pub unsafe extern "C" fn blocking_writer(
 /// # Safety
 ///
 /// * `op` is a valid pointer to a `blocking::Operator`.
-/// * `path` is a valid pointer to a nul terminated string.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `op` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `path` points to a nul-terminated string, or is null.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` is a boxed `blocking::Writer` released by `free_writer`, on
+///   failure `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn blocking_writer_append(
     op: *mut od::blocking::Operator,
     path: *const c_char,
-    result: *mut FFIResult<*mut blocking::Writer>,
+    result: *mut FFIResult<blocking::Writer>,
 ) {
     unsafe {
         let op = if op.is_null() {
@@ -792,9 +767,9 @@ pub unsafe extern "C" fn blocking_writer_append(
             &mut *op
         };
 
-        let path_str = match CStr::from_ptr(path).to_str() {
-            Ok(s) => s,
-            Err(_) => {
+        let path_str = match c_str_arg(path) {
+            Some(s) => s,
+            None => {
                 *result = FFIResult::err("Failed to convert path to string");
                 return;
             }
@@ -807,7 +782,7 @@ pub unsafe extern "C" fn blocking_writer_append(
         };
 
         let res = match op.writer_options(path_str, opts) {
-            Ok(writer) => FFIResult::ok(Box::into_raw(Box::new(writer))),
+            Ok(writer) => FFIResult::ok(writer),
             Err(e) => FFIResult::err_with_source("Failed to create append 
writer", e),
         };
 
@@ -820,15 +795,8 @@ pub unsafe extern "C" fn blocking_writer_append(
 /// # Safety
 ///
 /// * `writer` is a valid pointer to a `blocking::Writer`.
-/// * `bytes` is a valid pointer to a byte array.
-/// * `len` is the length of `bytes`.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `writer` is not a valid pointer.
-/// * If `bytes` is not a valid pointer, or `len` is more than the length of 
`bytes`.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `bytes` points to a byte array of `len` bytes, or is null when `len == 
0`.
+/// * `result` is a valid pointer with space for one `FFIResult`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn writer_write(
     writer: *mut blocking::Writer,
@@ -844,17 +812,20 @@ pub unsafe extern "C" fn writer_write(
             &mut *writer
         };
 
-        let bytes = Vec::from_raw_parts(bytes as *mut u8, len, len);
+        let bytes = match copy_bytes(bytes, len) {
+            Some(b) => b.to_vec(),
+            None => {
+                *result = FFIResult::err("Invalid bytes buffer");
+                return;
+            }
+        };
 
-        let res = match writer.write(bytes.clone()) {
+        let res = match writer.write(bytes) {
             Ok(_) => FFIResult::ok(()),
             Err(e) => FFIResult::err_with_source("Failed to write with 
writer", e),
         };
 
         *result = res;
-
-        // bytes memory is controlled by Haskell, we can't drop it here
-        mem::forget(bytes);
     }
 }
 
@@ -863,12 +834,9 @@ pub unsafe extern "C" fn writer_write(
 /// # Safety
 ///
 /// * `writer` is a valid pointer to a `blocking::Writer`.
-/// * `result` is a valid pointer, and has available memory to write to
-///
-/// # Panics
-///
-/// * If `writer` is not a valid pointer.
-/// * If `result` is not a valid pointer, or does not have available memory to 
write to.
+/// * `result` is a valid pointer with space for one `FFIResult`. On success
+///   `data_ptr` must be released with `free_metadata`, on failure
+///   `error_message` must be released with `free_string`.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn writer_close(
     writer: *mut blocking::Writer,
@@ -895,11 +863,8 @@ pub unsafe extern "C" fn writer_close(
 ///
 /// # Safety
 ///
-/// * `writer` is a valid pointer to a `blocking::Writer`.
-///
-/// # Panics
-///
-/// * If `writer` is not a valid pointer.
+/// * `writer` is a valid pointer to a `blocking::Writer` created by
+///   `blocking_writer` or `blocking_writer_append`, or null.
 #[unsafe(no_mangle)]
 pub unsafe extern "C" fn free_writer(writer: *mut blocking::Writer) {
     unsafe {
@@ -908,3 +873,292 @@ pub unsafe extern "C" fn free_writer(writer: *mut 
blocking::Writer) {
         }
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::ffi::CStr;
+    use std::ptr;
+    use types::{free_bool, free_byteslice, free_metadata, free_string};
+
+    fn memory_operator() -> *mut od::blocking::Operator {
+        let operator = od::Operator::via_iter("memory", 
HashMap::new()).unwrap();
+        let handle = RUNTIME.handle();
+        let _enter = handle.enter();
+        let op = od::blocking::Operator::new(operator).unwrap();
+        Box::into_raw(Box::new(op))
+    }
+
+    #[test]
+    fn ffi_result_layout_matches_abi() {
+        // code (padded to usize) + data_ptr + error_message.
+        assert_eq!(
+            std::mem::size_of::<FFIResult<()>>(),
+            std::mem::size_of::<usize>() * 3
+        );
+    }
+
+    #[test]
+    fn via_map_ffi_rejects_null_config_entry() {
+        unsafe {
+            let scheme = c"memory";
+            let keys: [*const c_char; 1] = [ptr::null()];
+            let values: [*const c_char; 1] = [c"/".as_ptr()];
+
+            let mut result = FFIResult::<od::blocking::Operator>::default();
+            via_map_ffi(
+                scheme.as_ptr(),
+                keys.as_ptr(),
+                values.as_ptr(),
+                1,
+                None,
+                &mut result,
+            );
+            assert_eq!(result.code, result::FFIErrorCode::FFIError);
+            assert!(result.data_ptr.is_null());
+            assert!(!result.error_message.is_null());
+            free_string(result.error_message);
+        }
+    }
+
+    #[test]
+    fn via_map_ffi_rejects_null_config_arrays() {
+        unsafe {
+            let scheme = c"memory";
+            let mut result = FFIResult::<od::blocking::Operator>::default();
+            via_map_ffi(
+                scheme.as_ptr(),
+                ptr::null(),
+                ptr::null(),
+                2,
+                None,
+                &mut result,
+            );
+            assert_eq!(result.code, result::FFIErrorCode::FFIError);
+            free_string(result.error_message);
+        }
+    }
+
+    #[test]
+    fn via_map_ffi_builds_memory_operator() {
+        unsafe {
+            let scheme = c"memory";
+            let mut result = FFIResult::<od::blocking::Operator>::default();
+            via_map_ffi(
+                scheme.as_ptr(),
+                ptr::null(),
+                ptr::null(),
+                0,
+                None,
+                &mut result,
+            );
+            assert_eq!(result.code, result::FFIErrorCode::Ok);
+            assert!(!result.data_ptr.is_null());
+            free_operator(result.data_ptr);
+        }
+    }
+
+    #[test]
+    fn write_then_read_roundtrip_releases_all_buffers() {
+        unsafe {
+            let op = memory_operator();
+            let path = c"ffi-test/file.bin";
+
+            let payload: Vec<u8> = (0u8..=255).collect();
+            let mut write_result = FFIResult::<()>::default();
+            blocking_write(
+                op,
+                path.as_ptr(),
+                payload.as_ptr() as *const c_char,
+                payload.len(),
+                &mut write_result,
+            );
+            assert_eq!(write_result.code, result::FFIErrorCode::Ok);
+
+            let mut read_result = FFIResult::<ByteSlice>::default();
+            blocking_read(op, path.as_ptr(), &mut read_result);
+            assert_eq!(read_result.code, result::FFIErrorCode::Ok);
+            assert!(!read_result.data_ptr.is_null());
+            let slice = &*read_result.data_ptr;
+            assert_eq!(slice.len, payload.len());
+            let view = std::slice::from_raw_parts(slice.data as *const u8, 
slice.len);
+            assert_eq!(view, payload.as_slice());
+            free_byteslice(read_result.data_ptr);
+
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn read_empty_write_roundtrip() {
+        unsafe {
+            let op = memory_operator();
+            let path = c"ffi-test/empty.bin";
+
+            let mut write_result = FFIResult::<()>::default();
+            blocking_write(op, path.as_ptr(), ptr::null(), 0, &mut 
write_result);
+            assert_eq!(write_result.code, result::FFIErrorCode::Ok);
+
+            let mut read_result = FFIResult::<ByteSlice>::default();
+            blocking_read(op, path.as_ptr(), &mut read_result);
+            assert_eq!(read_result.code, result::FFIErrorCode::Ok);
+            assert_eq!((*read_result.data_ptr).len, 0);
+            free_byteslice(read_result.data_ptr);
+
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn read_missing_key_returns_error_and_message_is_freed() {
+        unsafe {
+            let op = memory_operator();
+            let path = c"ffi-test/missing";
+
+            let mut read_result = FFIResult::<ByteSlice>::default();
+            blocking_read(op, path.as_ptr(), &mut read_result);
+            assert_eq!(read_result.code, result::FFIErrorCode::NotFound);
+            assert!(read_result.data_ptr.is_null());
+            assert!(!read_result.error_message.is_null());
+            free_string(read_result.error_message);
+
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn null_operator_reports_error_instead_of_crashing() {
+        unsafe {
+            let path = c"file";
+            let mut read_result = FFIResult::<ByteSlice>::default();
+            blocking_read(ptr::null_mut(), path.as_ptr(), &mut read_result);
+            assert_eq!(read_result.code, result::FFIErrorCode::FFIError);
+            free_string(read_result.error_message);
+        }
+    }
+
+    #[test]
+    fn is_exist_result_is_released_by_free_bool() {
+        unsafe {
+            let op = memory_operator();
+            let path = c"ffi-test/exists";
+            let mut write_result = FFIResult::<()>::default();
+            blocking_write(op, path.as_ptr(), c"x".as_ptr(), 1, &mut 
write_result);
+            assert_eq!(write_result.code, result::FFIErrorCode::Ok);
+
+            let mut exists_result = FFIResult::<bool>::default();
+            blocking_is_exist(op, path.as_ptr(), &mut exists_result);
+            assert_eq!(exists_result.code, result::FFIErrorCode::Ok);
+            assert!(*exists_result.data_ptr);
+            free_bool(exists_result.data_ptr);
+
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn stat_result_is_released_by_free_metadata() {
+        unsafe {
+            let op = memory_operator();
+            let path = c"ffi-test/meta";
+            let mut write_result = FFIResult::<()>::default();
+            blocking_write(op, path.as_ptr(), c"abc".as_ptr(), 3, &mut 
write_result);
+            assert_eq!(write_result.code, result::FFIErrorCode::Ok);
+
+            let mut stat_result = FFIResult::<Metadata>::default();
+            blocking_stat(op, path.as_ptr(), &mut stat_result);
+            assert_eq!(stat_result.code, result::FFIErrorCode::Ok);
+            assert_eq!((*stat_result.data_ptr).content_length, 3);
+            free_metadata(stat_result.data_ptr);
+
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn operator_info_returns_owned_scheme_string() {
+        unsafe {
+            let op = memory_operator();
+            let mut info_result = FFIResult::<c_char>::default();
+            operator_info(op, &mut info_result);
+            assert_eq!(info_result.code, result::FFIErrorCode::Ok);
+            assert_eq!(CStr::from_ptr(info_result.data_ptr).to_bytes(), 
b"memory");
+            free_string(info_result.data_ptr);
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn list_and_next_release_every_allocation() {
+        unsafe {
+            let op = memory_operator();
+            let path_a = c"ffi-list/a";
+            let path_b = c"ffi-list/b";
+            let dir = c"ffi-list/";
+            for path in [path_a, path_b] {
+                let mut write_result = FFIResult::<()>::default();
+                blocking_write(op, path.as_ptr(), c"x".as_ptr(), 1, &mut 
write_result);
+                assert_eq!(write_result.code, result::FFIErrorCode::Ok);
+            }
+
+            let mut list_result = FFIResult::<blocking::Lister>::default();
+            blocking_list(op, dir.as_ptr(), &mut list_result);
+            assert_eq!(list_result.code, result::FFIErrorCode::Ok);
+            let lister = list_result.data_ptr;
+            assert!(!lister.is_null());
+
+            let mut paths = Vec::new();
+            loop {
+                let mut next_result = FFIResult::<c_char>::default();
+                lister_next(lister, &mut next_result);
+                assert_eq!(next_result.code, result::FFIErrorCode::Ok);
+                if next_result.data_ptr.is_null() {
+                    break;
+                }
+                paths.push(
+                    CStr::from_ptr(next_result.data_ptr)
+                        .to_string_lossy()
+                        .into_owned(),
+                );
+                free_string(next_result.data_ptr);
+            }
+            assert!(paths.contains(&"ffi-list/a".to_string()));
+            assert!(paths.contains(&"ffi-list/b".to_string()));
+
+            free_lister(lister);
+            free_operator(op);
+        }
+    }
+
+    #[test]
+    fn writer_roundtrip_releases_all_buffers() {
+        unsafe {
+            let op = memory_operator();
+            let path = c"ffi-test/writer";
+
+            let mut writer_result = FFIResult::<blocking::Writer>::default();
+            blocking_writer(op, path.as_ptr(), &mut writer_result);
+            assert_eq!(writer_result.code, result::FFIErrorCode::Ok);
+            let writer = writer_result.data_ptr;
+            assert!(!writer.is_null());
+
+            let payload = c"hello writer";
+            let mut write_result = FFIResult::<()>::default();
+            writer_write(
+                writer,
+                payload.as_ptr(),
+                payload.count_bytes(),
+                &mut write_result,
+            );
+            assert_eq!(write_result.code, result::FFIErrorCode::Ok);
+
+            let mut close_result = FFIResult::<Metadata>::default();
+            writer_close(writer, &mut close_result);
+            assert_eq!(close_result.code, result::FFIErrorCode::Ok);
+            free_metadata(close_result.data_ptr);
+
+            free_writer(writer);
+            free_operator(op);
+        }
+    }
+}
diff --git a/bindings/haskell/src/logger.rs b/bindings/haskell/src/logger.rs
index 930c6cd523..68ab6f28fd 100644
--- a/bindings/haskell/src/logger.rs
+++ b/bindings/haskell/src/logger.rs
@@ -29,7 +29,9 @@ impl log::Log for HsLogger {
 
     fn log(&self, record: &log::Record) {
         let msg = format!("{}", record.args());
-        let c_str_msg = CString::new(msg).unwrap();
+        // Interior NUL bytes would make CString::new fail and panic across
+        // the FFI boundary; escape them instead of aborting the process.
+        let c_str_msg = CString::new(msg.replace('\0', 
"\\0")).unwrap_or_default();
         let c_level = match record.level() {
             log::Level::Debug => 0,
             log::Level::Info => 1,
diff --git a/bindings/haskell/src/result.rs b/bindings/haskell/src/result.rs
index e9f12affea..b176f0f7a1 100644
--- a/bindings/haskell/src/result.rs
+++ b/bindings/haskell/src/result.rs
@@ -15,22 +15,39 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use std::ffi::CString;
 use std::ffi::c_char;
 use std::ptr;
 
 use ::opendal as od;
 
+use crate::types::into_raw_c_string;
+
+/// Result value returned by every exported FFI function through a caller
+/// provided out pointer.
+///
+/// Ownership contract for `data_ptr` on success (`code == Ok`):
+///
+/// - For handle results the pointer itself is the owned resource and is
+///   released by its dedicated finalizer (`free_operator`, `free_lister`,
+///   `free_writer`).
+/// - For string results the pointer is a `CString` released by `free_string`.
+/// - For inline value results (`ByteSlice`, `Metadata`, `bool`) the pointer
+///   is a `Box<T>` released together with the payload by the matching
+///   `free_byteslice`, `free_metadata` or `free_bool` function.
+///
+/// `error_message` is a `CString` on failure and must be released by
+/// `free_string`. Every allocation owned by a `FFIResult` is allocated by Rust
+/// and must be freed by the matching Rust function, never by C `free()`.
 #[repr(C)]
 #[derive(Debug)]
 pub struct FFIResult<T> {
-    code: FFIErrorCode,
-    data_ptr: *mut T,
-    error_message: *mut c_char,
+    pub(crate) code: FFIErrorCode,
+    pub(crate) data_ptr: *mut T,
+    pub(crate) error_message: *mut c_char,
 }
 
 #[repr(C)]
-#[derive(Debug)]
+#[derive(Debug, PartialEq, Eq)]
 pub enum FFIErrorCode {
     Ok = 0,
     FFIError = 1,
@@ -49,7 +66,22 @@ pub enum FFIErrorCode {
     RangeNotSatisfied = 14,
 }
 
+impl<T> Default for FFIResult<T> {
+    fn default() -> Self {
+        FFIResult {
+            code: FFIErrorCode::FFIError,
+            data_ptr: ptr::null_mut(),
+            error_message: ptr::null_mut(),
+        }
+    }
+}
+
 impl<T> FFIResult<T> {
+    /// Box `data` and transfer the box to the caller through `data_ptr`.
+    ///
+    /// For results where `T` is a handle or `c_char`, prefer `ok_with_ptr`
+    /// so `data_ptr` is the resource itself instead of a leaked
+    /// `Box<*mut T>` wrapper.
     pub fn ok(data: T) -> Self {
         FFIResult {
             code: FFIErrorCode::Ok,
@@ -58,22 +90,42 @@ impl<T> FFIResult<T> {
         }
     }
 
+    /// Report success while handing `data_ptr` itself to the caller.
+    ///
+    /// Used when the payload is already the owned resource: `CString`
+    /// results from `lister_next` and `operator_info`. Opaque handles are
+    /// passed through `ok`, which boxes them into `data_ptr` directly.
+    pub fn ok_with_ptr(data_ptr: *mut T) -> Self {
+        FFIResult {
+            code: FFIErrorCode::Ok,
+            data_ptr,
+            error_message: ptr::null_mut(),
+        }
+    }
+
+    /// Report success without a payload, e.g. the end of a `Lister`.
+    pub fn none() -> Self {
+        FFIResult {
+            code: FFIErrorCode::Ok,
+            data_ptr: ptr::null_mut(),
+            error_message: ptr::null_mut(),
+        }
+    }
+
     pub fn err(error_message: &str) -> Self {
-        let c_string = CString::new(error_message).unwrap();
         FFIResult {
             code: FFIErrorCode::FFIError,
             data_ptr: ptr::null_mut(),
-            error_message: c_string.into_raw(),
+            error_message: into_raw_c_string(error_message),
         }
     }
 
     pub fn err_with_source(error_message: &str, source: od::Error) -> Self {
         let msg = format!("{error_message}, source error: {source}");
-        let c_string = CString::new(msg).unwrap();
         FFIResult {
             code: source.kind().into(),
             data_ptr: ptr::null_mut(),
-            error_message: c_string.into_raw(),
+            error_message: into_raw_c_string(&msg),
         }
     }
 }
@@ -102,6 +154,8 @@ impl From<od::ErrorKind> for FFIErrorCode {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use crate::types::free_string;
+    use std::ffi::CStr;
 
     #[test]
     fn error_kind_conversion_preserves_public_error_kinds() {
@@ -118,4 +172,60 @@ mod tests {
             FFIErrorCode::Conflict
         ));
     }
+
+    #[test]
+    fn err_result_carries_message_owned_by_free_string() {
+        let result: FFIResult<()> = FFIResult::err("something went wrong");
+        assert_eq!(result.code, FFIErrorCode::FFIError);
+        assert!(result.data_ptr.is_null());
+        assert!(!result.error_message.is_null());
+        unsafe {
+            let msg = CStr::from_ptr(result.error_message).to_string_lossy();
+            assert!(msg.contains("something went wrong"));
+            free_string(result.error_message);
+        }
+    }
+
+    #[test]
+    fn err_result_sanitizes_interior_nul_bytes() {
+        // An error message containing NUL bytes used to abort the process
+        // through CString::new(..).unwrap(). It must now be escaped instead.
+        let result: FFIResult<()> = FFIResult::err("a\0b");
+        assert!(!result.error_message.is_null());
+        unsafe {
+            let msg = CStr::from_ptr(result.error_message);
+            assert_eq!(msg.to_bytes(), b"a\\0b");
+            free_string(result.error_message);
+        }
+    }
+
+    #[test]
+    fn err_with_source_maps_error_kind() {
+        let source = od::Error::new(od::ErrorKind::NotFound, "no such key");
+        let result: FFIResult<()> = FFIResult::err_with_source("Failed to 
read", source);
+        assert_eq!(result.code, FFIErrorCode::NotFound);
+        unsafe {
+            let msg = CStr::from_ptr(result.error_message).to_string_lossy();
+            assert!(msg.contains("Failed to read"));
+            assert!(msg.contains("no such key"));
+            free_string(result.error_message);
+        }
+    }
+
+    #[test]
+    fn ok_with_ptr_passes_the_pointer_through() {
+        let s = into_raw_c_string("hello");
+        let result = FFIResult::<c_char>::ok_with_ptr(s);
+        assert_eq!(result.code, FFIErrorCode::Ok);
+        assert_eq!(result.data_ptr, s);
+        unsafe { free_string(result.data_ptr) };
+    }
+
+    #[test]
+    fn none_result_has_no_payload() {
+        let result = FFIResult::<c_char>::none();
+        assert_eq!(result.code, FFIErrorCode::Ok);
+        assert!(result.data_ptr.is_null());
+        assert!(result.error_message.is_null());
+    }
 }
diff --git a/bindings/haskell/src/types.rs b/bindings/haskell/src/types.rs
index 0e17c366b0..1fd5e6d976 100644
--- a/bindings/haskell/src/types.rs
+++ b/bindings/haskell/src/types.rs
@@ -17,47 +17,108 @@
 
 use std::ffi::CString;
 use std::ffi::c_char;
+use std::ptr;
 
 use ::opendal as od;
 
 #[repr(C)]
 #[derive(Debug)]
 pub struct ByteSlice {
-    data: *mut c_char,
-    len: usize,
+    pub(crate) data: *mut c_char,
+    pub(crate) len: usize,
 }
 
 impl ByteSlice {
+    /// Transfer `vec` to the caller inside a `ByteSlice`.
+    ///
+    /// The vector is converted into a boxed slice first so the allocation
+    /// length matches the reported `len` exactly; `free_byteslice` relies on
+    /// this to rebuild the same `Box<[u8]>`.
     pub fn from_vec(vec: Vec<u8>) -> Self {
-        let data = vec.as_ptr() as *mut c_char;
-        let len = vec.len();
-
-        // Leak the memory to pass the ownership to Haskell
-        std::mem::forget(vec);
+        let boxed = vec.into_boxed_slice();
+        let len = boxed.len();
+        // Hand the whole allocation over: `into_raw` keeps the raw pointer's
+        // provenance where `as_mut_ptr` + `mem::forget` would not.
+        let data = Box::into_raw(boxed) as *mut u8 as *mut c_char;
 
         ByteSlice { data, len }
     }
+}
 
-    /// # Safety
-    ///
-    /// * `ptr` is a valid pointer to a `ByteSlice`.
-    ///
-    /// # Panics
-    ///
-    /// * If `ptr` is not a valid pointer.
-    #[unsafe(no_mangle)]
-    pub unsafe extern "C" fn free_byteslice(ptr: *mut c_char, len: usize) {
-        unsafe {
-            if !ptr.is_null() {
-                drop(Vec::from_raw_parts(ptr, len, len));
-            }
+/// Free a `ByteSlice` produced by `FFIResult<ByteSlice>`: first the payload
+/// buffer, then the boxed `ByteSlice` itself.
+///
+/// # Safety
+///
+/// * `ptr` must be null or a `data_ptr` taken from an `FFIResult<ByteSlice>`
+///   that has not been freed yet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn free_byteslice(ptr: *mut ByteSlice) {
+    unsafe {
+        if ptr.is_null() {
+            return;
+        }
+        let slice = Box::from_raw(ptr);
+        if !slice.data.is_null() {
+            drop(Box::from_raw(ptr::slice_from_raw_parts_mut(
+                slice.data as *mut u8,
+                slice.len,
+            )));
+        }
+    }
+}
+
+/// Free a `bool` produced by `FFIResult<bool>`.
+///
+/// # Safety
+///
+/// * `ptr` must be null or a `data_ptr` taken from an `FFIResult<bool>` that
+///   has not been freed yet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn free_bool(ptr: *mut bool) {
+    unsafe {
+        if !ptr.is_null() {
+            drop(Box::from_raw(ptr));
+        }
+    }
+}
+
+/// Free a nul-terminated string produced by this library: `error_message`
+/// fields, `FFIResult<c_char>` payloads and `Metadata` string fields.
+///
+/// # Safety
+///
+/// * `ptr` must be null or a pointer returned by `into_raw_c_string` /
+///   `CString::into_raw` in this crate that has not been freed yet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn free_string(ptr: *mut c_char) {
+    unsafe {
+        if !ptr.is_null() {
+            drop(CString::from_raw(ptr));
         }
     }
 }
 
-impl From<&mut ByteSlice> for Vec<u8> {
-    fn from(val: &mut ByteSlice) -> Self {
-        unsafe { Vec::from_raw_parts(val.data as *mut u8, val.len, val.len) }
+/// Free a `Metadata` produced by `FFIResult<Metadata>`: every string field,
+/// then the boxed `Metadata` itself.
+///
+/// # Safety
+///
+/// * `ptr` must be null or a `data_ptr` taken from an `FFIResult<Metadata>`
+///   that has not been freed yet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn free_metadata(ptr: *mut Metadata) {
+    unsafe {
+        if ptr.is_null() {
+            return;
+        }
+        let metadata = Box::from_raw(ptr);
+        free_string(metadata.cache_control);
+        free_string(metadata.content_disposition);
+        free_string(metadata.content_md5);
+        free_string(metadata.content_type);
+        free_string(metadata.etag);
+        free_string(metadata.last_modified);
     }
 }
 
@@ -72,14 +133,14 @@ pub enum EntryMode {
 #[repr(C)]
 #[derive(Debug)]
 pub struct Metadata {
-    mode: EntryMode,
-    cache_control: *const c_char,
-    content_disposition: *const c_char,
-    content_length: u64,
-    content_md5: *const c_char,
-    content_type: *const c_char,
-    etag: *const c_char,
-    last_modified: *const c_char,
+    pub(crate) mode: EntryMode,
+    pub(crate) cache_control: *mut c_char,
+    pub(crate) content_disposition: *mut c_char,
+    pub(crate) content_length: u64,
+    pub(crate) content_md5: *mut c_char,
+    pub(crate) content_type: *mut c_char,
+    pub(crate) etag: *mut c_char,
+    pub(crate) last_modified: *mut c_char,
 }
 
 impl From<od::Metadata> for Metadata {
@@ -90,60 +151,125 @@ impl From<od::Metadata> for Metadata {
             od::EntryMode::Unknown => EntryMode::Unknown,
         };
 
-        let cache_control = match val.cache_control() {
-            Some(s) => unsafe { leak_str(s) },
-            None => std::ptr::null(),
-        };
+        Metadata {
+            mode,
+            cache_control: val
+                .cache_control()
+                .map_or(ptr::null_mut(), into_raw_c_string),
+            content_disposition: val
+                .content_disposition()
+                .map_or(ptr::null_mut(), into_raw_c_string),
+            content_length: val.content_length(),
+            content_md5: val.content_md5().map_or(ptr::null_mut(), 
into_raw_c_string),
+            content_type: val
+                .content_type()
+                .map_or(ptr::null_mut(), into_raw_c_string),
+            etag: val.etag().map_or(ptr::null_mut(), into_raw_c_string),
+            last_modified: val
+                .last_modified()
+                .map_or(ptr::null_mut(), |s| 
into_raw_c_string(&s.to_string())),
+        }
+    }
+}
 
-        let content_disposition = match val.content_disposition() {
-            Some(s) => unsafe { leak_str(s) },
-            None => std::ptr::null(),
-        };
+/// Convert `s` into a `CString` and leak it, transferring ownership to the
+/// caller. The returned pointer must be released with `free_string`.
+///
+/// Interior NUL bytes are escaped as `\0` so this function never fails and
+/// never aborts the process on adversarial input.
+pub(crate) fn into_raw_c_string(s: &str) -> *mut c_char {
+    let s = if s.contains('\0') {
+        s.replace('\0', "\\0")
+    } else {
+        s.to_string()
+    };
+    match CString::new(s) {
+        Ok(s) => s.into_raw(),
+        Err(_) => ptr::null_mut(),
+    }
+}
 
-        let content_length = val.content_length();
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::ffi::CStr;
 
-        let content_md5 = match val.content_md5() {
-            Some(s) => unsafe { leak_str(s) },
-            None => std::ptr::null(),
-        };
+    #[test]
+    fn byteslice_roundtrip_preserves_bytes() {
+        let payload: Vec<u8> = (0u8..=255).collect();
+        let slice = ByteSlice::from_vec(payload.clone());
+        assert_eq!(slice.len, payload.len());
+        unsafe {
+            let view = std::slice::from_raw_parts(slice.data as *const u8, 
slice.len);
+            assert_eq!(view, payload.as_slice());
+            free_byteslice(Box::into_raw(Box::new(slice)));
+        }
+    }
 
-        let content_type = match val.content_type() {
-            Some(s) => unsafe { leak_str(s) },
-            None => std::ptr::null(),
-        };
+    #[test]
+    fn byteslice_empty_roundtrip() {
+        let slice = ByteSlice::from_vec(Vec::new());
+        assert_eq!(slice.len, 0);
+        unsafe { free_byteslice(Box::into_raw(Box::new(slice))) };
+    }
 
-        let etag = match val.etag() {
-            Some(s) => unsafe { leak_str(s) },
-            None => std::ptr::null(),
-        };
+    #[test]
+    fn byteslice_free_null_is_noop() {
+        unsafe {
+            free_byteslice(ptr::null_mut());
+        }
+    }
 
-        let last_modified = match val.last_modified() {
-            Some(s) => unsafe { leak_str(s.to_string().as_str()) },
-            None => std::ptr::null(),
-        };
+    #[test]
+    fn bool_result_roundtrip() {
+        let data_ptr = Box::into_raw(Box::new(true));
+        unsafe {
+            assert!(*data_ptr);
+            free_bool(data_ptr);
+            free_bool(ptr::null_mut());
+        }
+    }
 
-        Metadata {
-            mode,
-            cache_control,
-            content_disposition,
-            content_length,
-            content_md5,
-            content_type,
-            etag,
-            last_modified,
+    #[test]
+    fn c_string_roundtrip_and_escaping() {
+        unsafe {
+            let ptr = into_raw_c_string("with space and 'quotes'");
+            assert_eq!(
+                CStr::from_ptr(ptr).to_str().unwrap(),
+                "with space and 'quotes'"
+            );
+            free_string(ptr);
+
+            let escaped = into_raw_c_string("a\0b");
+            assert_eq!(CStr::from_ptr(escaped).to_bytes(), b"a\\0b");
+            free_string(escaped);
+
+            free_string(ptr::null_mut());
         }
     }
-}
 
-// Leak the memory to pass the ownership to Haskell
-// Please note that haskell should free the memory after using it
-pub unsafe fn leak_str(s: &str) -> *const c_char {
-    let s = match CString::new(s) {
-        Ok(s) => s,
-        Err(_) => return std::ptr::null(),
-    };
+    #[test]
+    fn metadata_free_releases_every_field() {
+        let mut builder = od::MetadataBuilder::file(42);
+        builder
+            .cache_control("no-cache")
+            .content_disposition("attachment")
+            .content_md5("md5")
+            .content_type("text/plain")
+            .etag("etag");
+        let ffi = Metadata::from(builder.build());
+        let ptr = Box::into_raw(Box::new(ffi));
+        unsafe {
+            assert_eq!((*ptr).content_length, 42);
+            free_metadata(ptr);
+            free_metadata(ptr::null_mut());
+        }
+    }
 
-    let ptr = s.as_ptr();
-    std::mem::forget(s);
-    ptr
+    #[test]
+    fn metadata_free_with_null_fields() {
+        let ffi = Metadata::from(od::MetadataBuilder::unknown().build());
+        let ptr = Box::into_raw(Box::new(ffi));
+        unsafe { free_metadata(ptr) };
+    }
 }
diff --git a/bindings/haskell/test/ResourceTest.hs 
b/bindings/haskell/test/ResourceTest.hs
new file mode 100644
index 0000000000..e4dc84b414
--- /dev/null
+++ b/bindings/haskell/test/ResourceTest.hs
@@ -0,0 +1,151 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF licenses this file
+-- to you under the Apache License, Version 2.0 (the
+-- "License"); you may not use this file except in compliance
+-- with the License.  You may obtain a copy of the License at
+--
+--   http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied.  See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+-- | Exercise the FFI resource cleanup paths: repeated operations, error
+-- branches, lister exhaustion and ForeignPtr finalizers. A leaked or
+-- mismatched free typically shows up as a crash or heap corruption under
+-- repetition, especially after forcing the garbage collector.
+module ResourceTest (resourceTests) where
+
+import Control.Monad.IO.Class (MonadIO, liftIO)
+import qualified Data.ByteString as BS
+import OpenDAL
+import System.Mem (performGC)
+import Test.Tasty
+import Test.Tasty.HUnit
+
+resourceTests :: TestTree
+resourceTests =
+  testGroup
+    "Resource Cleanup Tests"
+    [ testCase "testRepeatedReadOps" testRepeatedReadOps,
+      testCase "testRepeatedErrorPaths" testRepeatedErrorPaths,
+      testCase "testReadEmptyFile" testReadEmptyFile,
+      testCase "testRepeatedStatOps" testRepeatedStatOps,
+      testCase "testListerExhaustion" testListerExhaustion,
+      testCase "testForeignPtrFinalizers" testForeignPtrFinalizers,
+      testCase "testRepeatedWriterClose" testRepeatedWriterClose
+    ]
+
+testRepeatedReadOps :: Assertion
+testRepeatedReadOps = do
+  Right op <- newOperator "memory"
+  writeOpRaw op "rr" "v" ?= Right ()
+  -- Every read allocates a ByteSlice plus its wrapper; freeing must match on
+  -- every iteration, not just the first.
+  mapM_
+    (\i -> readOpRaw op "rr" ?= Right "v")
+    ([1 .. 200] :: [Int])
+  performGC
+
+testRepeatedErrorPaths :: Assertion
+testRepeatedErrorPaths = do
+  Right op <- newOperator "memory"
+  -- Each iteration allocates an error_message CString that must be released
+  -- through free_string, on raw and monadic paths alike.
+  mapM_
+    ( \i -> do
+        Left err <- readOpRaw op ("missing-" ++ show i)
+        errorCode err @?= NotFound
+    )
+    ([1 .. 100] :: [Int])
+  runOp op (readOp "missing") >>= \case
+    Left err -> errorCode err @?= NotFound
+    Right _ -> assertFailure "Expected NotFound error"
+  performGC
+
+testReadEmptyFile :: Assertion
+testReadEmptyFile = do
+  Right op <- newOperator "memory"
+  -- Zero-length ByteSlice: freeing an empty buffer must not crash.
+  writeOpRaw op "empty" "" ?= Right ()
+  readOpRaw op "empty" ?= Right BS.empty
+  statOpRaw op "empty" >>= \case
+    Right meta -> mContentLength meta @?= 0
+    Left err -> assertFailure $ "stat failed: " ++ show err
+
+testRepeatedStatOps :: Assertion
+testRepeatedStatOps = do
+  Right op <- newOperator "memory"
+  writeOpRaw op "stat-me" "12345" ?= Right ()
+  -- Each stat allocates a Metadata box plus CString fields, all released by
+  -- free_metadata.
+  mapM_
+    ( \i ->
+        statOpRaw op "stat-me" >>= \case
+          Right meta -> mContentLength meta @?= 5
+          Left err -> assertFailure $ "stat failed: " ++ show err
+    )
+    ([1 .. 100] :: [Int])
+  performGC
+
+testListerExhaustion :: Assertion
+testListerExhaustion = do
+  Right op <- newOperator "memory"
+  writeOpRaw op "res-dir/a" "1" ?= Right ()
+  writeOpRaw op "res-dir/b" "2" ?= Right ()
+  Right lister <- listOpRaw op "res-dir/"
+  items <- collectAll lister
+  assertBool "expected a in listing" ("res-dir/a" `elem` items)
+  assertBool "expected b in listing" ("res-dir/b" `elem` items)
+  -- Next after exhaustion must keep returning Right Nothing without
+  -- allocating or crashing.
+  nextLister lister ?= Right Nothing
+  where
+    collectAll l = go []
+      where
+        go acc = do
+          r <- nextLister l
+          case r of
+            Right (Just p) -> go (p : acc)
+            Right Nothing -> return acc
+            Left err -> assertFailure $ "lister error: " ++ show err
+
+testForeignPtrFinalizers :: Assertion
+testForeignPtrFinalizers = do
+  -- Scope every handle so the GC can run its finalizer; a mismatched
+  -- allocator or double-free would crash here.
+  do
+    Right op <- newOperator "memory"
+    Right lister <- listOpRaw op "/"
+    Right writer <- writerOpRaw op "gc-file" defaultWriterOption
+    writerWrite writer "x" ?= Right ()
+    _ <- nextLister lister
+    return ()
+  performGC
+  performGC
+
+testRepeatedWriterClose :: Assertion
+testRepeatedWriterClose = do
+  Right op <- newOperator "memory"
+  -- Each writerClose returns a Metadata box released by free_metadata; the
+  -- writer itself is released by the ForeignPtr finalizer.
+  mapM_
+    ( \i -> do
+        Right writer <- writerOpRaw op ("wr-" ++ show i) defaultWriterOption
+        writerWrite writer "data" ?= Right ()
+        writerClose writer >>= \case
+          Right meta -> mContentLength meta @?= 4
+          Left err -> assertFailure $ "close failed: " ++ show err
+    )
+    ([1 .. 50] :: [Int])
+  performGC
+
+-- helper function
+
+(?=) :: (MonadIO m, Eq a, Show a) => m a -> a -> m ()
+result ?= expected = result >>= liftIO . (@?= expected)
diff --git a/bindings/haskell/test/Spec.hs b/bindings/haskell/test/Spec.hs
index 9e1f00c2f8..93eb21ad36 100644
--- a/bindings/haskell/test/Spec.hs
+++ b/bindings/haskell/test/Spec.hs
@@ -19,6 +19,7 @@ import BasicTest
 import WriterTest
 import ErrorTest
 import PerformanceTest
+import ResourceTest
 import Test.Tasty
 import Test.Tasty.Ingredients.Basic (consoleTestReporter)
 
@@ -31,5 +32,6 @@ main =
       [ basicTests,
         writerTests,
         errorTests,
-        performanceTests
+        performanceTests,
+        resourceTests
       ]
\ No newline at end of file

Reply via email to