github.com/wencode/hack@v0.2.9/mmap/mmap_unix.go (about)

     1  // +build darwin linux
     2  
     3  package mmap
     4  
     5  import "golang.org/x/sys/unix"
     6  
     7  func Mmap(fd, prot, offset, len int) (MapBuf, error) {
     8  	var (
     9  		flags  = unix.MAP_SHARED
    10  		s_prot = unix.PROT_READ
    11  	)
    12  	if prot&RDWR != 0 {
    13  		s_prot |= unix.PROT_WRITE
    14  	}
    15  	if prot&COW != 0 {
    16  		s_prot |= unix.PROT_WRITE
    17  		flags = unix.MAP_PRIVATE
    18  	}
    19  	if prot&EXEC != 0 {
    20  		s_prot |= unix.PROT_EXEC
    21  	}
    22  	if fd < 0 {
    23  		// The mapping is not backed by any file;
    24  		// it contents are initialize to zero.
    25  		// the fd and offset arguments are ignored.
    26  		flags |= unix.MAP_ANON
    27  	}
    28  
    29  	buf, err := unix.Mmap(fd, int64(offset), len, s_prot, flags)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	return MapBuf(buf), nil
    34  }
    35  
    36  func (mb MapBuf) Unmap() error {
    37  	return unix.Munmap([]byte(mb))
    38  }
    39  
    40  func (mb MapBuf) Mlock() error {
    41  	return unix.Mlock([]byte(mb))
    42  }
    43  
    44  func (mb MapBuf) Munlock() error {
    45  	return unix.Munlock([]byte(mb))
    46  }
    47  
    48  func (mb MapBuf) Sync() error {
    49  	return unix.Msync([]byte(mb), unix.MS_ASYNC)
    50  }