linux

package module
v0.0.0-...-c0222f5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2025 License: MPL-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package linux provides a VerboseStyle Linux system call API.

Index

Constants

View Source
const FileRelativeToWorkingDirectory = -100 // AT_FDCWD

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API struct {
	Read          FuncRead
	Write         FuncWrite
	Open          FuncOpen
	Close         FuncClose
	Stat          FuncStat
	FileStat      FuncFileStat
	LinkStat      FuncLinkStat
	Poll          FuncPoll
	Seek          FuncSeek
	MemoryMap     FuncMemoryMap
	ProtectMemory FuncProtectMemory
	Heap          FuncHeap
}

API specification of the entire Linux API, you can create a subset of this API.

func Native

func Native() *API

type Bytes

type Bytes = int64
const MaxRead Bytes = 0x7ffff000

MaxRead is the maximum number of bytes that can be read in a single call to File.Read.

type CloseError

type CloseError Error[struct {
	BadFile        CloseError `bad file descriptor`     // file is not valid.
	Interrupted    CloseError `interrupted system call` // close was interrupted by a signal.
	IO             CloseError `I/O error`               // an I/O error occurred.
	QuotaExhausted CloseError `disk quota exceeded`     // user's quota of space has run out, can be returned on close when IO is being buffered.
	NoMoreSpace    CloseError `no space left on device` // device has no more space, can be returned on close when IO is being buffered.
}]

CloseError returned by [API.Close] operations.

type DeviceID

type DeviceID uint64

type ErrMethods

type ErrMethods[T any] byte

func (ErrMethods[T]) Error

func (n ErrMethods[T]) Error() string

func (ErrMethods[T]) Types

func (n ErrMethods[T]) Types() T

type Error

type Error[T any] struct{ ErrMethods[T] }

type File

type File struct {
	Linux      *API
	Descriptor FileDescriptor
	Closed     atomic.Bool
}

File opened with API.

func (*File) Close

func (f *File) Close() error

Close the file.

func (*File) MapIntoMemory

func (f *File) MapIntoMemory(mtype MapType, prot MemoryProtection, flags Map) (MappedMemory, error)

MapIntoMemory maps the entire file into memory and returns it.

func (*File) Read

func (f *File) Read(p []byte) (int, error)

Read implements io.Reader

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (int64, error)

Seek implements io.Seeker

func (*File) Stat

func (f *File) Stat() (FileHeader, error)

Stat returns metadata for the file located at the given path.

func (*File) Write

func (f *File) Write(p []byte) (int, error)

Write implements io.Writer

type FileAccessMode

type FileAccessMode int

FileAccessMode request opening the file read-only, write-only, or read/write, respectively.

const (
	FileAccessReadOnly  FileAccessMode = syscall.O_RDONLY // enable reads
	FileAccessWriteOnly FileAccessMode = syscall.O_WRONLY // enable writes
	FileAccessReadWrite FileAccessMode = syscall.O_RDWR   // enable both reads and writes
)

type FileCreationFlags

type FileCreationFlags int

FileCreationFlags affect the semantics of the [Kernel.Open] operation.

const (
	FileCloseOnExecute   FileCreationFlags = 0x80000  // close the file automatically on [Kernel.Execute].
	FileCreateIfNeeded   FileCreationFlags = 0x40     // create the file if it does not exist.
	FileAssertDirectory  FileCreationFlags = 0x10000  // fail to open if the path is not a directory.
	FileAssertCreation   FileCreationFlags = 0x80     // fail to open if the file already exists.
	FileIsNotTheTerminal FileCreationFlags = 0x100    // if the pathname is a terminal, it shouldn't become the controlling terminal for the process.
	FileTrapSymbolicLink FileCreationFlags = 0x20000  // if the trailing component is a symbolic link, don't follow it, open it directly.
	FileTemporaryInside  FileCreationFlags = 0x410000 // creates an unnamed temporary file inside the provided directory
	FileTruncatedToZero  FileCreationFlags = 0x200    // resets the file to length 0, writes will overwrite any existing content.
)

type FileDescriptor

type FileDescriptor int32

FileDescriptor identifies an open file for the process.

type FileHeader

type FileHeader struct {
	Device      DeviceID
	IndexNode   IndexNode
	HardLinks   uint64
	Permissions FilePermissions
	User        UserID
	Group       GroupID

	Special    DeviceID
	Size       Bytes
	BlockSize  Bytes
	BlockCount int64

	AccessedAt         Time
	ModifiedAt         Time
	ModifiedMetadataAt Time
	// contains filtered or unexported fields
}

FileHeader returned by [API.Stat] provides a representation of the metadata that the filesystem records on the file.

type FilePermissions

type FilePermissions uint32

FilePermissions mode bits.

const (
	FileReadableByUser   FilePermissions = syscall.S_IRUSR // file is readable by its owner
	FileReadableByGroup  FilePermissions = syscall.S_IRGRP // file is readable by its group
	FileReadableByOthers FilePermissions = syscall.S_IROTH // file is readable by others

	FileWritableByUser   FilePermissions = syscall.S_IWUSR // file is writable by its owner
	FileWritableByGroup  FilePermissions = syscall.S_IWGRP // file is writable by its group
	FileWritableByOthers FilePermissions = syscall.S_IWOTH // file is writable by others

	FileExecutableByUser   FilePermissions = syscall.S_IXUSR // file is executable by its owner
	FileExecutableByGroup  FilePermissions = syscall.S_IXGRP // file is executable by its group
	FileExecutableByOthers FilePermissions = syscall.S_IXOTH // file is executable by others

	FileExecutesAsOwner FilePermissions = syscall.S_ISUID // file will be executed as if it were executed by the owner of the file
	FileExecutesAsGroup FilePermissions = syscall.S_ISGID // file will be executed as if it were executed by the group of the file

	FilesInheritGroup  FilePermissions = syscall.S_ISGID // files created in this directory inherit their group ID from the directory
	FilesLockedToOwner FilePermissions = syscall.S_ISVTX // files in this directory can only be renamed or deleted by owners.

	DirectorySearchableByUser   FilePermissions = syscall.S_IXUSR // directory is searchable by its owner
	DirectorySearchableByGroup  FilePermissions = syscall.S_IXGRP // directory is searchable by its group
	DirectorySearchableByOthers FilePermissions = syscall.S_IXOTH // directory is searchable by others
)

type FileStatusFlags

type FileStatusFlags int

FileStatusFlags affect the semantics of subsequent I/O operations. These can be retrieved and (in some cases) modified; see [File.Status] for details.

const (
	FileAppend                FileStatusFlags = 0x400    // append data to the end of the file when writing.
	FileAsync                 FileStatusFlags = 0x2000   // emit [SignalIO] whenever input or output becomes available.
	FileDirect                FileStatusFlags = 0x4000   // avoid cache where possible and use underlying hardware directly
	FileSyncData              FileStatusFlags = 0x1000   // all [File.Write] operations are automatically followed by a [File.SyncData].
	FileDoNotUpdateAccessTime FileStatusFlags = 0x40000  // request that the access time of the file is not updated on [File.Read]
	FileNonBlocking           FileStatusFlags = 0x800    // return "resource temporarily unavailable" if a read/write would block
	FilePath                  FileStatusFlags = 0x200000 // file is opened as a reference-only, no read/write operations are allowed.
	FileSync                  FileStatusFlags = 0x101000 // all [File.Write] operations are automatically followed by a [File.Sync].
)

type FileToPoll

type FileToPoll struct {
	File   FileDescriptor // file descriptor to wait for events on.
	Notify Poll           // requested notifications to wait for.
	Result Poll           // filled in by [API.Poll].
	// contains filtered or unexported fields
}

FileToPoll is used for [API.Poll] and configures which events to wait for.

type FuncClose

type FuncClose func(fd FileDescriptor) error

FuncClose a previously opened file.

type FuncFileStat

type FuncFileStat func(fd FileDescriptor) (FileHeader, error)

FuncFileStat returns metadata for the given file descriptor.

type FuncHeap

type FuncHeap func(addr unsafe.Pointer) (unsafe.Pointer, error)

FuncHeap can be used to adjust the heap of the process, as such it can be used as a general memory allocation mechanism. Unsafe to use when GODEBUG=sbrk=1. A nil pointer returns the current end of the heap.

type FuncLinkStat

type FuncLinkStat func(name Path) (FileHeader, error)

FuncLinkStat returns metadata for the symbolic link located at the given path.

type FuncMemoryMap

type FuncMemoryMap func(addr unsafe.Pointer, length int, prot MemoryProtection, mtype MapType, flags Map, fd FileDescriptor, offset uintptr) (MappedMemory, error)

FuncMemoryMap maps the specified file into memory, using the optionally specified pointer as a hint on where to map it in. If addr is nil, a suitable address is chosen by the kernel. Offset must be a multiple of the system's page size. When files are large, this will be more efficient than reading the file into memory. If fd is -1 and MapAnonymous is used, [MapIntoMemory] can be used as a general memory allocation mechanism.

type FuncOpen

type FuncOpen func(name Path, mode FileAccessMode, flag FileCreationFlags, status FileStatusFlags, perm FilePermissions) (File, error)

FuncOpen the file located at the given path, a number of flags are available, see the respective types for more information.

type FuncPoll

type FuncPoll func(files []FileToPoll, timeout time.Duration) (int, error)

FuncPoll waits for events on the given files to poll and returns the index of the next file that has events available. Timeout has millisecond precision.

type FuncProtectMemory

type FuncProtectMemory func(addr unsafe.Pointer, length int, prot MemoryProtection) error

FuncProtectMemory changes the memory protection of any pages within the given memory region. The addr must be page-aligned.

type FuncRead

type FuncRead func(fd FileDescriptor, buf []byte) (int, error)

FuncRead bytes from fd into the given buffer, returns the number of bytes read which may be fewer than len(buf).

type FuncSeek

type FuncSeek func(fd FileDescriptor, offset int64, whence Seek) (int64, error)

FuncSeek changes the offset of the file descriptor to the given offset.

type FuncStat

type FuncStat func(name Path) (FileHeader, error)

FuncStat returns metadata for the file located at the given path.

type FuncWrite

type FuncWrite func(fd FileDescriptor, buf []byte) (int, error)

FuncWrite bytes from the given buffer to fd, returns the number of bytes written which may be fewer than len(buf).

type GroupID

type GroupID uint32

type HeapError

type HeapError Error[struct {
	OutOfMemory HeapError `cannot allocate memory` // no more memory available.
}]

HeapError returned by [API.Heap] operations.

type IndexNode

type IndexNode uint64

type Map

type Map int // used by [API.MapFileIntoMemory]
const (
	MapAnonymous        Map = 0x20       // file must be -1, just allocate anonymous memory.
	Map32Bit            Map = 0x40       // allocate memory in the first 4GB of the address space.
	MapExactAddress     Map = 0x10       // addr must be page-aligned and will be used directly.
	MapExactAddressOnce Map = 0x100000   // like [MapExactAddress] but goroutine-safe.
	MapGrowsDown        Map = 0x100      // touching the first page will grow the mapping down by a single page/
	MapHugeTables       Map = 0x40000    // use huge pages.
	MapHuge2MB          Map = 0x54000000 // use 2MB huge pages.
	MapHuge1GB          Map = 0x78000000 // use 1GB huge pages.
	MapKeepAwayFromSwap Map = 0x2000     // lock the pages in physical memory (do not swap).
	MapDoNotReserveSwap Map = 0x4000     // do not reserve swap space.
	MapPopulate         Map = 0x8000     // eagerly load the file into the map.
	MapStack            Map = 0x20000    // ensure memory is suitably setup to use for a stack.
	MapSync             Map = 0x80000    // for files that support direct mapping of persistent memory.
	MapUninitialized    Map = 0x4000000  // don't zero out pages, subject to the system secutiry policy.
)

type MapError

type MapError Error[struct {
	AccessDenied  MapError `permission denied`                     // non-regular file or [FileAccessMode] is incompatible with [MemoryProtection]
	Locked        MapError `resource temporarily unavailable`      // file is locked, or too much locked memory in-use.
	BadFile       MapError `bad file descriptor`                   // file is not valid and [MapAnonymous] not set.
	AlreadyExists MapError `file exists`                           // [MapExactAddressOnce] is set and the address is already mapped.
	Invalid       MapError `invalid argument`                      // addr, length or offset is invalid and/or [MapType] missing.
	TooManyFiles  MapError `too many open files`                   // process has too many files open.
	Unsupported   MapError `no such device`                        // file system does not support mapping.
	OutOfMemory   MapError `cannot allocate memory`                // kernel is out of memory, and/or addr exceeds the virtual address space.
	Overflow      MapError `value too large for defined data type` // resulting offset is too large to fit in an int64.
	NotPermitted  MapError `operation not permitted`               // file is not readable or writable, and/or process huge page capabilities.
}]

MapError returned by [API.MapFileIntoMemory] operations.

type MapType

type MapType int // used by [API.MapFileIntoMemory]
const (
	MapShared              MapType = 0x01 // persist writes back to the file.
	MapPrivate             MapType = 0x02 // copy-on-write memory.
	MapSharedValidateFlags MapType = 0x03 // [MapShared] + validate flags.
)

type MappedMemory

type MappedMemory interface {
	io.ReaderAt
	io.WriterAt
	io.Closer

	Len() int

	UnsafePointer() unsafe.Pointer
}

MappedMemory from a File.

type MemoryProtection

type MemoryProtection int // use by [API.MapFileIntoMemory] abd [API.ProtectMemory]
const (
	MemoryNotAccessible  MemoryProtection = 0x0 // no access allowed.
	MemoryAllowReads     MemoryProtection = 0x1 // read access allowed.
	MemoryAllowWrites    MemoryProtection = 0x2 // write access allowed.
	MemoryAllowExecution MemoryProtection = 0x4 // execute access allowed.
	MemoryAllowAtomics   MemoryProtection = 0x8 // atomic operations allowed.
)

type OpenError

type OpenError Error[struct {
	AccessDenied   OpenError `permission denied`                // one of the directories is missing the search/execute permission bit, or wrong user.
	BadFile        OpenError `bad file descriptor`              // file is not valid.
	Busy           OpenError `device or resource busy`          // file is mounted and cannot be opened.
	QuotaExhausted OpenError `disk quota exceeded`              // user's quota of space has run out.
	AlreadyExists  OpenError `file exists`                      // file already exists and [FileCreateIfNeeded] and [FileAssertCreation] were used.
	Fault          OpenError `bad address`                      // pathname is outside your accessible address space.
	FileTooLarge   OpenError `file too large`                   // file exceeds architecture file size limit.
	NotPermitted   OpenError `operation not permitted`          // permissions missing.
	ReadOnly       OpenError `read-only file system`            // file is on a read-only filesystem and write access was requested.
	FileInUse      OpenError `file in use`                      // file is in use.
	WouldBlock     OpenError `resource temporarily unavailable` // file requested as non-blocking and the open would block, try again later.
}]

OpenError returned by [API.Open] operations.

type Path

type Path string

type Poll

type Poll int16

Poll events that can be polled for.

const (
	PollHasReadAvailable        Poll = 0x001  // chance to try [File.Read]
	PollHasPriority             Poll = 0x002  // priority has been passed to the file.
	PollHasWriteAvailable       Poll = 0x004  // chance to try [File.Write]
	PollHasPeerFinishedWriting  Poll = 0x2000 // remote socket peer shutdown write side.
	PollHasPeerConnectionClosed Poll = 0x010  // remote socket peer closed connection.

	PollHasError          Poll = 0x008 // only available in [FileToPoll.Result]
	PollHasInvalidRequest Poll = 0x020 // only available in [FileToPoll.Result]
)

type PollError

type PollError Error[struct {
	Fault       PollError `bad address`             // files to poll is nil or points out of the accessible address space.
	Interrupted PollError `interrupted system call` // poll was interrupted by a signal.
	Invalid     PollError `invalid argument`        // too many files to poll or the timeout is invalid.
	OutOfMemory PollError `cannot allocate memory`  // kernel is out of memory
}]

PollError returned by [API.Poll] operations.

type ProtectMemoryError

type ProtectMemoryError Error[struct {
	AccessDenied ProtectMemoryError `permission denied`      // mapped file [FileAccessMode] is incompatible with [MemoryProtection].
	Invalid      ProtectMemoryError `invalid argument`       // addr is not aligned to page size, is invalid or flags are invalid.
	OutOfMemory  ProtectMemoryError `cannot allocate memory` // kernel is out of memory
}]

ProtectMemoryError returned by [API.ProtectMemory] operations.

type ReadError

type ReadError Error[struct {
	WouldBlock  ReadError `resource temporarily unavailable` // file requested as non-blocking and the read would block, try again later.
	BadFile     ReadError `bad file descriptor`              // file is not valid.
	Fault       ReadError `bad address`                      // buffer is outside the accessible address space.
	Interrupted ReadError `interrupted system call`          // read was interrupted by a signal.
	Invalid     ReadError `invalid argument`                 // file is not suitable for reading.
	IO          ReadError `I/O error`                        // an I/O error occurred.
	Directory   ReadError `is a directory`                   // directories cannot be read.
}]

ReadError returned by [API.Read], File.Read operations.

type Seek

type Seek int

Seek is used for [API.Seek] to specify where and whence to seek.

const (
	SeekRelativeToStart Seek = 0 // seek relative to the start of the file.
	SeekRelative        Seek = 1 // seek relative to the current offset of the file.
	SeekRelativeToEnd   Seek = 2 // seek relative to the end of the file.
	SeekHole            Seek = 4 // seek to the next hole greater than or equal to the given offset.
	SeekData            Seek = 3 // seek to the next data greater than or equal to the given offset.
)

type SeekError

type SeekError Error[struct {
	BadFile  SeekError `bad file descriptor`                   // file is not valid.
	Invalid  SeekError `invalid argument`                      // invalid whence or resulting offset out of bounds.
	NotFound SeekError `no such device or address`             // [SeekData] or [SeekHole] could not find a suitable offset within bounds.
	Overflow SeekError `value too large for defined data type` // resulting offset is too large to fit in an int64.
	Illegal  SeekError `illegal seek`                          // pipes/sockets are not seekable.
}]

SeekError returned by [API.Seek] operations.

type StatError

type StatError Error[struct {
	DoesNotExist     StatError `no such file or directory`             // an element in the path does not exist.
	AccessDenied     StatError `permission denied`                     // one of the directories is missing the search/execute permission bit.
	BadFile          StatError `bad file descriptor`                   // file is not valid.
	Fault            StatError `bad address`                           // path string is corrupted.
	Invalid          StatError `invalid argument`                      // invalid flags
	Loop             StatError `too many levels of symbolic links`     // recursion limit reached.
	NameTooLong      StatError `file name too long`                    // unsupported file name
	OutOfMemory      StatError `cannot allocate memory`                // kernel is out of memory
	NotDirectory     StatError `not a directory`                       // a component of the path prefix is not a directory.
	StatFileTooLarge StatError `value too large for defined data type` // file size is 64 bits and the system is 32 bits.
}]

StatError returned by [API.Stat], [API.StatLink] and [API.StatFile] operations.

type Time

type Time struct {
	Seconds int64
	Nanos   int64
	// contains filtered or unexported fields
}

type UserID

type UserID uint32

type WriteError

type WriteError Error[struct {
	WouldBlock     WriteError `resource temporarily unavailable` // file requested as non-blocking and the write would block, try again later.
	BadFile        WriteError `bad file descriptor`              // file is not valid.
	NoDestination  WriteError `destination address required`     // files is a datagram socket and requires a destination address.
	QuotaExhausted WriteError `disk quota exceeded`              // user's quota of space has run out.
	Fault          WriteError `bad address`                      // buffer is outside the accessible address space.
	TooMuch        WriteError `file too large`                   // file exceeds the maximum file size.
	Interrupted    WriteError `interrupted system call`          // write was interrupted by a signal.
	Invalid        WriteError `invalid argument`                 // file is not suitable for writing.
	IO             WriteError `I/O error`                        // an I/O error occurred.
	NoMoreSpace    WriteError `no space left on device`          // device has no more space.
	NotPermitted   WriteError `operation not permitted`          // file is not open for writing.
	BrokenPipe     WriteError `broken pipe`                      // write to a closed pipe with no readers.
}]

WriteError returned by [API.Write], File.Write operations.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL