1// Copyright 2018 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//go:build unix 6 7package base 8 9import ( 10 "internal/unsafeheader" 11 "os" 12 "runtime" 13 "syscall" 14 "unsafe" 15) 16 17// TODO(mdempsky): Is there a higher-level abstraction that still 18// works well for iimport? 19 20// MapFile returns length bytes from the file starting at the 21// specified offset as a string. 22func MapFile(f *os.File, offset, length int64) (string, error) { 23 // POSIX mmap: "The implementation may require that off is a 24 // multiple of the page size." 25 x := offset & int64(os.Getpagesize()-1) 26 offset -= x 27 length += x 28 29 buf, err := syscall.Mmap(int(f.Fd()), offset, int(length), syscall.PROT_READ, syscall.MAP_SHARED) 30 runtime.KeepAlive(f) 31 if err != nil { 32 return "", err 33 } 34 35 buf = buf[x:] 36 pSlice := (*unsafeheader.Slice)(unsafe.Pointer(&buf)) 37 38 var res string 39 pString := (*unsafeheader.String)(unsafe.Pointer(&res)) 40 41 pString.Data = pSlice.Data 42 pString.Len = pSlice.Len 43 44 return res, nil 45} 46