github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/pkg/memio/seek.go (about)

     1  // Copyright 2012-2019 the u-root 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 linux,!arm,!arm64
     6  
     7  package memio
     8  
     9  import (
    10  	"encoding/binary"
    11  	"io"
    12  	"os"
    13  
    14  	"github.com/u-root/u-root/pkg/ubinary"
    15  )
    16  
    17  var memPath = "/dev/mem"
    18  
    19  func pathRead(path string, addr int64, data UintN) error {
    20  	f, err := os.OpenFile(path, os.O_RDONLY, 0)
    21  	if err != nil {
    22  		return err
    23  	}
    24  	defer f.Close()
    25  
    26  	if _, err := f.Seek(addr, io.SeekStart); err != nil {
    27  		return err
    28  	}
    29  	return binary.Read(f, ubinary.NativeEndian, data)
    30  }
    31  
    32  // Read reads data from physical memory at address addr. On x86 platforms,
    33  // this uses the seek+read syscalls. On arm platforms, this uses mmap.
    34  func Read(addr int64, data UintN) error {
    35  	return pathRead(memPath, addr, data)
    36  }
    37  
    38  func pathWrite(path string, addr int64, data UintN) error {
    39  	f, err := os.OpenFile(path, os.O_WRONLY, 0)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	defer f.Close()
    44  
    45  	if _, err := f.Seek(addr, io.SeekStart); err != nil {
    46  		return err
    47  	}
    48  	return binary.Write(f, ubinary.NativeEndian, data)
    49  }
    50  
    51  // Write writes data to physical memory at address addr. On x86 platforms, this
    52  // uses the seek+read syscalls. On arm platforms, this uses mmap.
    53  func Write(addr int64, data UintN) error {
    54  	return pathWrite(memPath, addr, data)
    55  }