silver-ymz commented on code in PR #8744:
URL: https://github.com/apache/opendal/pull/8744#discussion_r4660486696


##########
bindings/haskell/src/lib.rs:
##########
@@ -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())),

Review Comment:
   [P2] Reject object names that contain a NUL instead of rewriting them
   
   `lister_next` uses diagnostic escaping for object names, replacing a NUL 
with a literal `\0`. That makes two distinct keys look identical to Haskell. If 
a caller uses the listed name to read or delete the object, it can target the 
other key. Since the current FFI cannot pass a NUL-containing path unchanged, 
return an explicit conversion error instead of a rewritten name.



##########
bindings/haskell/haskell-src/OpenDAL.hs:
##########
@@ -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

Review Comment:
   [P2] Free logger callbacks that Rust does not take ownership of
   
   A second logging-enabled `newOperator` allocates a callback with `wrapLogFn` 
before Rust rejects the duplicate registration. Haskell never frees that 
callback, so each retry leaks it and the captured `LogAction`. Have Rust report 
whether it took ownership separately from the constructor result: logger 
registration can succeed even if operator construction later fails.



##########
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

Review Comment:
   [P2] Make the cleanup test fail when a native free is missing
   
   Removing `freeString` from `parseError` would leave every `NotFound` 
assertion passing. `performGC` cannot reclaim the strings allocated by Rust. 
Verify at least one error path in CI with a native allocation counter or a leak 
checker so the test fails if the free is removed.



##########
bindings/haskell/src/lib.rs:
##########
@@ -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");

Review Comment:
   [P2] Encode operator configuration explicitly as UTF-8
   
   Rust now rejects non-UTF-8 configuration, but Haskell still uses the 
locale-dependent `withCString`. For example, with a Latin-1 locale and a 
`memory` root of `café`, operator construction previously succeeded with a 
replacement character and now returns `FFIError`. Encode config keys and values 
explicitly as UTF-8 on the Haskell side and keep Rust's validation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to