-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_safety_test.go
More file actions
81 lines (65 loc) · 2.11 KB
/
memory_safety_test.go
File metadata and controls
81 lines (65 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package simba
import (
"runtime"
"testing"
"github.com/miretskiy/simba/internal/ffi"
)
// TestMemorySafety validates that SIMBA properly handles memory ownership
// across FFI boundaries by ensuring slices remain alive during foreign calls.
func TestMemorySafety(t *testing.T) {
// Test with a reasonably sized buffer to ensure the Rust code
// has time to access the memory
data := make([]byte, 1024)
for i := range data {
data[i] = byte(i % 256)
}
// Force garbage collection before the FFI call to maximize the chance
// of detecting use-after-free if memory safety is broken
runtime.GC()
runtime.GC() // Call twice to be thorough
// This should work correctly with our runtime.KeepAlive calls
sum1 := ffi.SumU8_32(data)
sum2 := ffi.SumU8_64(data)
// Verify the results are consistent and reasonable
if sum1 != sum2 {
t.Errorf("SumU8_32 and SumU8_64 produced different results: %d vs %d", sum1, sum2)
}
// Expected sum: 0+1+2+...+255+0+1+2+...+255+... (4 full cycles)
expectedSum := uint32(4 * (255 * 256 / 2)) // 4 * 32640 = 130560
if sum1 != expectedSum {
t.Errorf("SumU8 result %d doesn't match expected %d", sum1, expectedSum)
}
// Test other functions to ensure they all have proper memory safety
isASCII := ffi.IsASCII32([]byte("Hello, World!"))
if !isASCII {
t.Error("ASCII test failed on valid ASCII string")
}
// Test LUT functions
lut := &[256]byte{}
for i := range lut {
lut[i] = 1 // Mark all bytes as valid
}
runtime.GC()
runtime.GC()
valid := ffi.AllBytesInSet32(data, lut)
if !valid {
t.Error("AllBytesInSet32 should return true when all bytes are marked valid in LUT")
}
// Test mapping functions
dst := make([]byte, len(data))
for i := range lut {
lut[i] = byte(255 - i) // Invert mapping
}
runtime.GC()
runtime.GC()
ffi.MapBytes32(dst, data, lut)
// Verify the mapping worked
for i, b := range data {
expected := byte(255 - int(b))
if dst[i] != expected {
t.Errorf("MapBytes32 failed at index %d: got %d, expected %d", i, dst[i], expected)
break
}
}
t.Logf("Memory safety test completed successfully - all FFI calls preserved slice data correctly")
}