github.com/cloudwego/iasm@v0.2.0/repl/mem.go (about)

     1  //
     2  // Copyright 2024 CloudWeGo Authors
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  //
    16  
    17  package repl
    18  
    19  import (
    20      `os`
    21      `reflect`
    22      `syscall`
    23      `unsafe`
    24  )
    25  
    26  type _Memory struct {
    27      size uint64
    28      addr uintptr
    29  }
    30  
    31  func (self _Memory) p() (v unsafe.Pointer) {
    32      *(*uintptr)(unsafe.Pointer(&v)) = self.addr
    33      return
    34  }
    35  
    36  func (self _Memory) buf() (v []byte) {
    37      p := (*reflect.SliceHeader)(unsafe.Pointer(&v))
    38      p.Cap = int(self.size)
    39      p.Len = int(self.size)
    40      p.Data = self.addr
    41      return
    42  }
    43  
    44  const (
    45      _AP  = syscall.MAP_ANON  | syscall.MAP_PRIVATE
    46      _RWX = syscall.PROT_READ | syscall.PROT_WRITE | syscall.PROT_EXEC
    47  )
    48  
    49  var (
    50      _PageSize = uint64(os.Getpagesize())
    51  )
    52  
    53  func mmap(nb uint64) (_Memory, error) {
    54      nb = (((nb - 1) / _PageSize) + 1) * _PageSize
    55      mm, _, err := syscall.RawSyscall6(syscall.SYS_MMAP, 0, uintptr(nb), _RWX, _AP, 0, 0)
    56  
    57      /* check for errors */
    58      if err != 0 {
    59          return _Memory{}, err
    60      } else {
    61          return _Memory { addr: mm, size: nb }, nil
    62      }
    63  }
    64  
    65  func munmap(m _Memory) error {
    66      if _, _, err := syscall.RawSyscall(syscall.SYS_MUNMAP, m.addr, uintptr(m.size), 0); err != 0 {
    67          return err
    68      } else {
    69          return nil
    70      }
    71  }