github.com/gagliardetto/golang-go@v0.0.0-20201020153340-53909ea70814/cmd/compile/internal/gc/mapfile_mmap.go (about)

     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  // +build darwin dragonfly freebsd linux netbsd openbsd
     6  
     7  package gc
     8  
     9  import (
    10  	"os"
    11  	"reflect"
    12  	"syscall"
    13  	"unsafe"
    14  )
    15  
    16  // TODO(mdempsky): Is there a higher-level abstraction that still
    17  // works well for iimport?
    18  
    19  // mapFile returns length bytes from the file starting at the
    20  // specified offset as a string.
    21  func mapFile(f *os.File, offset, length int64) (string, error) {
    22  	// POSIX mmap: "The implementation may require that off is a
    23  	// multiple of the page size."
    24  	x := offset & int64(os.Getpagesize()-1)
    25  	offset -= x
    26  	length += x
    27  
    28  	buf, err := syscall.Mmap(int(f.Fd()), offset, int(length), syscall.PROT_READ, syscall.MAP_SHARED)
    29  	keepAlive(f)
    30  	if err != nil {
    31  		return "", err
    32  	}
    33  
    34  	buf = buf[x:]
    35  	pSlice := (*reflect.SliceHeader)(unsafe.Pointer(&buf))
    36  
    37  	var res string
    38  	pString := (*reflect.StringHeader)(unsafe.Pointer(&res))
    39  
    40  	pString.Data = pSlice.Data
    41  	pString.Len = pSlice.Len
    42  
    43  	return res, nil
    44  }
    45  
    46  // keepAlive is a reimplementation of runtime.KeepAlive, which wasn't
    47  // added until Go 1.7, whereas we need to compile with Go 1.4.
    48  var keepAlive = func(interface{}) {}