Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ffi): fix Rust dangling pointer #5230

Merged
merged 5 commits into from
Jun 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions cli/internal/ffi/ffi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ffi

import (
"testing"

"gotest.tools/v3/assert"
)

// This test is here to verify that we correctly handle zero length buffers
// with null data pointers.
func Test_EmptyBuffer(t *testing.T) {
buffer := toBuffer(nil)
bytes := toBytes(buffer)
assert.DeepEqual(t, bytes, []byte{})
}
17 changes: 17 additions & 0 deletions cli/internal/fs/recursive_copy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package fs

import (
"testing"

"github.com/vercel/turbo/cli/internal/turbopath"
"gotest.tools/v3/assert"
)

func Test_RecursiveCopyCopiesFiles(t *testing.T) {
base := turbopath.AbsoluteSystemPath(t.TempDir())
src := base.UntypedJoin("src")
err := src.Mkdir(0775)
assert.NilError(t, err, "mkdir")
err = RecursiveCopy(src, base.UntypedJoin("dst"))
assert.NilError(t, err, "recursive copy")
}
26 changes: 23 additions & 3 deletions crates/turborepo-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,16 @@ pub extern "C" fn free_buffer(buffer: Buffer) {

impl<T: prost::Message> From<T> for Buffer {
fn from(value: T) -> Self {
let mut bytes = ManuallyDrop::new(value.encode_to_vec());
let data = bytes.as_mut_ptr();
let len = bytes.len() as u32;
let len = value.encoded_len() as u32;
let data = match len {
// Check if the message will have a non-zero length to avoid returning
// a dangling pointer to Go.
0 => std::ptr::null_mut(),
_ => {
let mut bytes = ManuallyDrop::new(value.encode_to_vec());
bytes.as_mut_ptr()
}
};
Buffer { len, data }
}
}
Expand Down Expand Up @@ -341,3 +348,16 @@ pub extern "C" fn glob(buffer: Buffer) -> Buffer {
}
.into()
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn test_empty_message_has_null_ptr() {
let message = proto::RecursiveCopyResponse { error: None };
let buffer = Buffer::from(message);
assert_eq!(buffer.len, 0);
assert_eq!(buffer.data, std::ptr::null_mut());
}
}
Loading