wa-lang.org/wazero@v1.0.2/internal/platform/mmap_test.go (about)

     1  package platform
     2  
     3  import (
     4  	"bytes"
     5  	"crypto/rand"
     6  	"io"
     7  	"testing"
     8  
     9  	"wa-lang.org/wazero/internal/testing/require"
    10  )
    11  
    12  var testCodeBuf, _ = io.ReadAll(io.LimitReader(rand.Reader, 8*1024))
    13  
    14  func Test_MmapCodeSegment(t *testing.T) {
    15  	if !CompilerSupported() {
    16  		t.Skip()
    17  	}
    18  
    19  	testCodeReader := bytes.NewReader(testCodeBuf)
    20  	newCode, err := MmapCodeSegment(testCodeReader, testCodeReader.Len())
    21  	require.NoError(t, err)
    22  	// Verify that the mmap is the same as the original.
    23  	require.Equal(t, testCodeBuf, newCode)
    24  	// TODO: test newCode can executed.
    25  
    26  	t.Run("panic on zero length", func(t *testing.T) {
    27  		captured := require.CapturePanic(func() {
    28  			_, _ = MmapCodeSegment(bytes.NewBuffer(make([]byte, 0)), 0)
    29  		})
    30  		require.EqualError(t, captured, "BUG: MmapCodeSegment with zero length")
    31  	})
    32  }
    33  
    34  func Test_MunmapCodeSegment(t *testing.T) {
    35  	if !CompilerSupported() {
    36  		t.Skip()
    37  	}
    38  
    39  	// Errors if never mapped
    40  	require.Error(t, MunmapCodeSegment(testCodeBuf))
    41  
    42  	testCodeReader := bytes.NewReader(testCodeBuf)
    43  	newCode, err := MmapCodeSegment(testCodeReader, testCodeReader.Len())
    44  	require.NoError(t, err)
    45  	// First munmap should succeed.
    46  	require.NoError(t, MunmapCodeSegment(newCode))
    47  	// Double munmap should fail.
    48  	require.Error(t, MunmapCodeSegment(newCode))
    49  
    50  	t.Run("panic on zero length", func(t *testing.T) {
    51  		captured := require.CapturePanic(func() {
    52  			_ = MunmapCodeSegment(make([]byte, 0))
    53  		})
    54  		require.EqualError(t, captured, "BUG: MunmapCodeSegment with zero length")
    55  	})
    56  }