Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/compile/internal/typecheck/mapfile_mmap.go

Documentation: cmd/compile/internal/typecheck

     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 darwin || dragonfly || freebsd || linux || netbsd || openbsd
     6  // +build darwin dragonfly freebsd linux netbsd openbsd
     7  
     8  package typecheck
     9  
    10  import (
    11  	"os"
    12  	"reflect"
    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.
    22  func 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  	keepAlive(f)
    31  	if err != nil {
    32  		return "", err
    33  	}
    34  
    35  	buf = buf[x:]
    36  	pSlice := (*reflect.SliceHeader)(unsafe.Pointer(&buf))
    37  
    38  	var res string
    39  	pString := (*reflect.StringHeader)(unsafe.Pointer(&res))
    40  
    41  	pString.Data = pSlice.Data
    42  	pString.Len = pSlice.Len
    43  
    44  	return res, nil
    45  }
    46  
    47  // keepAlive is a reimplementation of runtime.KeepAlive, which wasn't
    48  // added until Go 1.7, whereas we need to compile with Go 1.4.
    49  var keepAlive = func(interface{}) {}
    50  

View as plain text