Extracts platform-specific runtime code into its own package (#608)

This moves the platform-specific runtime code (currently only used by
the compiler) into its own package. Specifically, this moves the mmap
logic, and in doing so makes it easier to test, for example new
operating systems.

This also backfills missing RATIONALE about x/sys and hints at a future
possibility to allow a plugin. However, the next step is to get FreeBSD
working natively on the compiler without any additional dependencies.

See #607

Signed-off-by: Adrian Cole <adrian@tetrate.io>
This commit is contained in:
Crypt Keeper
2022-06-01 09:24:02 +08:00
committed by GitHub
parent 0c303258c7
commit e0e9e27326
10 changed files with 143 additions and 88 deletions

View File

@@ -0,0 +1,57 @@
package platform
import (
"crypto/rand"
"io"
"runtime"
"testing"
"github.com/tetratelabs/wazero/internal/testing/require"
)
var testCode, _ = io.ReadAll(io.LimitReader(rand.Reader, 8*1024))
func Test_MmapCodeSegment(t *testing.T) {
requireSupportedOSArch(t)
newCode, err := MmapCodeSegment(testCode)
require.NoError(t, err)
// Verify that the mmap is the same as the original.
require.Equal(t, testCode, newCode)
// TODO: test newCode can executed.
t.Run("panic on zero length", func(t *testing.T) {
captured := require.CapturePanic(func() {
_, _ = MmapCodeSegment(make([]byte, 0))
})
require.EqualError(t, captured, "BUG: MmapCodeSegment with zero length")
})
}
func Test_MunmapCodeSegment(t *testing.T) {
requireSupportedOSArch(t)
// Errors if never mapped
require.Error(t, MunmapCodeSegment(testCode))
newCode, err := MmapCodeSegment(testCode)
require.NoError(t, err)
// First munmap should succeed.
require.NoError(t, MunmapCodeSegment(newCode))
// Double munmap should fail.
require.Error(t, MunmapCodeSegment(newCode))
t.Run("panic on zero length", func(t *testing.T) {
captured := require.CapturePanic(func() {
_ = MunmapCodeSegment(make([]byte, 0))
})
require.EqualError(t, captured, "BUG: MunmapCodeSegment with zero length")
})
}
// requireSupportedOSArch is duplicated also in the compiler package to ensure no cyclic dependency.
func requireSupportedOSArch(t *testing.T) {
if runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64" {
t.Skip()
}
}