File size: 2,361 Bytes
d7a5f2f | 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 | // Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build darwin || freebsd || linux || (netbsd && go1.25)
package ld
import (
"errors"
"os"
"path/filepath"
"runtime"
"syscall"
"testing"
)
func TestFallocate(t *testing.T) {
dir := t.TempDir()
filename := filepath.Join(dir, "a.out")
out := NewOutBuf(nil)
err := out.Open(filename)
if err != nil {
t.Fatalf("Open file failed: %v", err)
}
defer out.Close()
// Try fallocate first.
for {
err = out.fallocate(1 << 10)
if errors.Is(err, errors.ErrUnsupported) || err == errNoFallocate { // The underlying file system may not support fallocate
t.Skip("fallocate is not supported")
}
if err == syscall.EINTR {
continue // try again
}
if err != nil {
t.Fatalf("fallocate failed: %v", err)
}
break
}
// Mmap 1 MiB initially, and grow to 2 and 3 MiB.
// Check if the file size and disk usage is expected.
for _, sz := range []int64{1 << 20, 2 << 20, 3 << 20} {
err = out.Mmap(uint64(sz))
if err != nil {
t.Fatalf("Mmap failed: %v", err)
}
stat, err := os.Stat(filename)
if err != nil {
t.Fatalf("Stat failed: %v", err)
}
if got := stat.Size(); got != sz {
t.Errorf("unexpected file size: got %d, want %d", got, sz)
}
if runtime.GOOS == "darwin" {
// Check the number of allocated blocks on Darwin. On Linux (and
// perhaps BSDs), stat's Blocks field may not be portable as it
// is an implementation detail of the file system. On Darwin, it
// is documented as "the actual number of blocks allocated for
// the file in 512-byte units".
// The check is introduced when fixing a Darwin-specific bug. On
// Darwin, the file allocation syscall is a bit tricky. On Linux
// and BSDs, it is more straightforward and unlikely to go wrong.
// Given these two reasons, only check it on Darwin.
//
// The number of blocks must be enough for the requested size.
// We used to require an exact match, but it appears that
// some file systems allocate a few extra blocks in some cases.
// See issue #41127.
if got, want := stat.Sys().(*syscall.Stat_t).Blocks, (sz+511)/512; got < want {
t.Errorf("unexpected disk usage: got %d blocks, want at least %d", got, want)
}
}
out.munmap()
}
}
|