github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/link/ld/outbuf_test.go (about) 1 // Copyright 2020 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package ld 6 7 import ( 8 "path/filepath" 9 "runtime" 10 "testing" 11 ) 12 13 // TestMMap ensures that we can actually mmap on every supported platform. 14 func TestMMap(t *testing.T) { 15 switch runtime.GOOS { 16 default: 17 t.Skip("unsupported OS") 18 case "aix", "darwin", "ios", "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "windows": 19 } 20 dir := t.TempDir() 21 filename := filepath.Join(dir, "foo.out") 22 ob := NewOutBuf(nil) 23 if err := ob.Open(filename); err != nil { 24 t.Fatalf("error opening file: %v", err) 25 } 26 defer ob.Close() 27 if err := ob.Mmap(1 << 20); err != nil { 28 t.Errorf("error mmapping file %v", err) 29 } 30 if !ob.isMmapped() { 31 t.Errorf("should be mmapped") 32 } 33 } 34 35 // TestWriteLoc ensures that the math surrounding writeLoc is correct. 36 func TestWriteLoc(t *testing.T) { 37 tests := []struct { 38 bufLen int 39 off int64 40 heapLen int 41 lenToWrite int64 42 expectedHeapLen int 43 writePos int64 44 addressInHeap bool 45 }{ 46 {100, 0, 0, 100, 0, 0, false}, 47 {100, 100, 0, 100, 100, 0, true}, 48 {10, 10, 0, 100, 100, 0, true}, 49 {10, 20, 10, 100, 110, 10, true}, 50 {0, 0, 0, 100, 100, 0, true}, 51 } 52 53 for i, test := range tests { 54 ob := &OutBuf{ 55 buf: make([]byte, test.bufLen), 56 off: test.off, 57 heap: make([]byte, test.heapLen), 58 } 59 pos, buf := ob.writeLoc(test.lenToWrite) 60 if pos != test.writePos { 61 t.Errorf("[%d] position = %d, expected %d", i, pos, test.writePos) 62 } 63 message := "mmapped area" 64 expected := ob.buf 65 if test.addressInHeap { 66 message = "heap" 67 expected = ob.heap 68 } 69 if &buf[0] != &expected[0] { 70 t.Errorf("[%d] expected position to be %q", i, message) 71 } 72 if len(ob.heap) != test.expectedHeapLen { 73 t.Errorf("[%d] expected len(ob.heap) == %d, got %d", i, test.expectedHeapLen, len(ob.heap)) 74 } 75 } 76 } 77 78 func TestIsMmapped(t *testing.T) { 79 tests := []struct { 80 length int 81 expected bool 82 }{ 83 {0, false}, 84 {1, true}, 85 } 86 for i, test := range tests { 87 ob := &OutBuf{buf: make([]byte, test.length)} 88 if v := ob.isMmapped(); v != test.expected { 89 90 t.Errorf("[%d] isMmapped == %t, expected %t", i, v, test.expected) 91 } 92 } 93 }