or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cpu.mdexecabs.mdindex.mdplan9.mdunix.mdwindows.md
tile.json

tessl/golang-golang-org-x-sys

Supplemental Go packages for low-level interactions with the operating system

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/golang.org/x/sys@v0.38.0

To install, run

npx @tessl/cli install tessl/golang-golang-org-x-sys@0.38.0

index.mddocs/

golang.org/x/sys

Low-level operating system primitives for Go programs.

Package Information

  • Module: golang.org/x/sys
  • Version: v0.38.0
  • Repository: https://github.com/golang/sys
  • License: BSD-3-Clause

Overview

The golang.org/x/sys repository holds supplemental Go packages for low-level interactions with the operating system. It provides access to system calls, OS-specific functionality, and CPU feature detection across different platforms.

This package is particularly useful for:

  • Systems programming requiring direct OS interaction
  • Low-level network programming
  • Process management and security
  • Hardware feature detection
  • Building portable abstractions over OS-specific functionality

Core Imports

import (
    "golang.org/x/sys/cpu"      // CPU feature detection
    "golang.org/x/sys/execabs"  // Secure command execution
    "golang.org/x/sys/plan9"    // Plan 9 system calls
    "golang.org/x/sys/unix"     // Unix/Linux system calls
    "golang.org/x/sys/windows"  // Windows system calls
)

Package Structure

The repository contains five main packages:

1. cpu - CPU Feature Detection

Import: golang.org/x/sys/cpu

Implements processor feature detection for various CPU architectures including x86/AMD64, ARM/ARM64, PowerPC, RISC-V, s390x, MIPS, and LoongArch.

Key Features:

  • Runtime CPU feature detection
  • Architecture-specific capability querying
  • SIMD instruction set detection
  • Cryptographic hardware acceleration detection

View Full Documentation

2. execabs - Secure Command Execution

Import: golang.org/x/sys/execabs

A drop-in replacement for os/exec that requires PATH lookups to find absolute paths, preventing execution of programs from the current directory.

Key Features:

  • Secure command execution
  • Protection against current directory attacks
  • Compatible API with os/exec
  • Enhanced security for build tools and scripts

View Full Documentation

3. plan9 - Plan 9 System Calls

Import: golang.org/x/sys/plan9

Provides low-level access to Plan 9 operating system primitives, including file operations, process management, and namespace manipulation using Plan 9's unique bind and mount semantics.

Key Features:

  • 42 functions for system operations
  • 6 types for system structures (Dir, Qid, Waitmsg, etc.)
  • 127 constants for Plan 9-specific flags
  • File and directory operations
  • Process management and waiting
  • Namespace bind and mount operations
  • Environment variable handling
  • Plan 9 stat protocol support

View Full Documentation

4. unix - Unix/Linux System Calls

Import: golang.org/x/sys/unix

Provides low-level access to Unix and Linux system calls, supporting multiple Unix-like operating systems including Linux, FreeBSD, macOS, OpenBSD, NetBSD, and Solaris.

Key Features:

  • 419 functions for system operations
  • 263 types for system structures
  • Thousands of constants for system calls
  • File and directory operations
  • Process and thread management
  • Network and socket operations
  • Memory management
  • Security and capabilities

View Full Documentation

5. windows - Windows System Calls

Import: golang.org/x/sys/windows

Contains an interface to the low-level Windows operating system primitives, wrapping the Windows API for Go programs.

Key Features:

  • 701 functions for Windows operations
  • 255 types for Windows structures
  • Comprehensive Windows API coverage
  • File and process management
  • Security and access control
  • Registry operations
  • Service management
  • Network operations

View Full Documentation

Capabilities

CPU Feature Detection

The cpu package allows runtime detection of processor capabilities:

package main

import (
    "fmt"
    "golang.org/x/sys/cpu"
)

func main() {
    if cpu.X86.HasAVX2 {
        fmt.Println("AVX2 available - using optimized code path")
    }

    if cpu.ARM64.HasNEON {
        fmt.Println("NEON available - using SIMD acceleration")
    }
}

Supported Architectures:

  • x86/AMD64 (SSE, AVX, AVX-512, AES-NI, etc.)
  • ARM/ARM64 (NEON, Crypto Extensions, SVE)
  • PowerPC64 (POWER8, POWER9)
  • RISC-V 64 (Vector extensions, Crypto)
  • s390x (IBM Z features)
  • MIPS64 (MSA)
  • LoongArch64

Learn more about CPU detection →

Secure Command Execution

The execabs package provides secure alternatives to os/exec:

package main

import (
    "log"
    "golang.org/x/sys/execabs"
)

func main() {
    // Secure: will not execute from current directory
    cmd := execabs.Command("git", "status")
    output, err := cmd.Output()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(output))
}

Security Benefits:

  • Prevents current directory attacks
  • Requires absolute PATH resolution
  • Drop-in replacement for os/exec
  • Essential for security-critical applications

Learn more about secure execution →

Plan 9 System Programming

The plan9 package provides access to Plan 9 operating system primitives:

package main

import (
    "fmt"
    "golang.org/x/sys/plan9"
)

func main() {
    // Open file
    fd, err := plan9.Open("/lib/namespace", plan9.O_RDONLY)
    if err != nil {
        panic(err)
    }
    defer plan9.Close(fd)

    // Read with system call
    buf := make([]byte, 1024)
    n, err := plan9.Read(fd, buf)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Read %d bytes\n", n)
}

Major Capabilities:

  • File and directory operations
  • Process management and waiting
  • Namespace manipulation (bind, mount, unmount)
  • Environment variable access
  • Plan 9 stat protocol (Dir, Qid)
  • Process notes (Plan 9's signal mechanism)

Learn more about Plan 9 system calls →

Unix System Programming

The unix package provides comprehensive Unix/Linux system call access:

package main

import (
    "fmt"
    "golang.org/x/sys/unix"
)

func main() {
    // Open file
    fd, err := unix.Open("/etc/hosts", unix.O_RDONLY, 0)
    if err != nil {
        panic(err)
    }
    defer unix.Close(fd)

    // Read with system call
    buf := make([]byte, 1024)
    n, err := unix.Read(fd, buf)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Read %d bytes\n", n)
}

Major Capabilities:

  • File and directory operations
  • Process and thread management
  • Network programming (sockets, epoll)
  • Memory management (mmap, mprotect)
  • Security (capabilities, SELinux)
  • inotify and fanotify
  • Namespaces and cgroups
  • eBPF and seccomp

Learn more about Unix system calls →

Windows System Programming

The windows package provides comprehensive Windows API access:

package main

import (
    "fmt"
    "golang.org/x/sys/windows"
)

func main() {
    // Get current user
    token, err := windows.OpenCurrentProcessToken()
    if err != nil {
        panic(err)
    }
    defer token.Close()

    user, err := token.GetTokenUser()
    if err != nil {
        panic(err)
    }

    account, domain, _, err := user.User.Sid.LookupAccount("")
    if err != nil {
        panic(err)
    }

    fmt.Printf("User: %s\\%s\n", domain, account)
}

Major Capabilities:

  • File and process operations
  • Security and access control (SIDs, ACLs, tokens)
  • Registry access
  • Service management
  • Named pipes and IOCP
  • Console operations
  • Certificate and cryptography
  • Network operations (WinSock)
  • COM interop

Learn more about Windows system calls →

Basic Usage

Installation

go get golang.org/x/sys

Platform-Specific Code

Use build tags to write platform-specific code:

//go:build linux
// +build linux

package mypackage

import "golang.org/x/sys/unix"

func platformSpecific() {
    // Linux-specific code using unix package
    unix.Sync()
}
//go:build windows
// +build windows

package mypackage

import "golang.org/x/sys/windows"

func platformSpecific() {
    // Windows-specific code using windows package
    windows.FlushFileBuffers(handle)
}

Cross-Platform Abstractions

Build cross-platform functionality using both packages:

package mypackage

import (
    "runtime"
    "golang.org/x/sys/plan9"
    "golang.org/x/sys/unix"
    "golang.org/x/sys/windows"
)

func GetProcessID() uint32 {
    switch runtime.GOOS {
    case "linux", "darwin", "freebsd":
        return uint32(unix.Getpid())
    case "windows":
        return windows.GetCurrentProcessId()
    case "plan9":
        return uint32(plan9.Getpid())
    default:
        return 0
    }
}

API Organization

CPU Package

  • Constants: IsBigEndian
  • Variables: Architecture-specific feature structs (X86, ARM64, PPC64, etc.)
  • Types: CacheLinePad

Full CPU API Reference →

Execabs Package

  • Variables: ErrNotFound
  • Functions: Command, CommandContext, LookPath
  • Types: Cmd, Error, ExitError (aliases)

Full Execabs API Reference →

Plan9 Package

  • Constants: 127 Plan 9 constants (open modes, rfork flags, mount flags, etc.)
  • Variables: 20 variables (file descriptors, errors)
  • Functions: 42 system call wrappers
  • Types: 6 system structures (Dir, Qid, Waitmsg, Timespec, Timeval, Note)

Full Plan9 API Reference →

Unix Package

  • Constants: Thousands of system constants (file modes, signals, socket options, etc.)
  • Functions: 419 system call wrappers
  • Types: 263 system structures (Stat_t, Sockaddr, Epoll, etc.)

Full Unix API Reference →

Windows Package

  • Constants: Thousands of Windows constants (error codes, access rights, flags, etc.)
  • Functions: 701 Windows API wrappers
  • Types: 255 Windows structures (Handle, SID, ACL, Token, etc.)

Full Windows API Reference →

Performance Considerations

CPU Feature Detection

  • Feature detection happens once at program startup
  • Flags are cached in global variables
  • Zero runtime overhead after initialization
  • Use for selecting optimal code paths

System Call Overhead

  • Direct system call wrappers have minimal overhead
  • Consider batching operations when possible
  • Use async I/O (epoll on Linux, IOCP on Windows) for high-performance networking
  • Memory map files for large file operations

Memory Management

  • System calls often require pre-allocated buffers
  • Reuse buffers when possible to reduce allocations
  • Be mindful of buffer sizes for optimal performance

Security Considerations

Execabs Usage

  • Always use execabs instead of os/exec for security-critical applications
  • Prevents execution of malicious binaries in current directory
  • Essential for build tools, CI/CD systems, and deployment scripts

Unix Security

  • Proper capability management
  • Secure file permissions
  • SELinux and AppArmor integration
  • Namespace isolation

Windows Security

  • Proper ACL configuration
  • Token and privilege management
  • Secure impersonation
  • Certificate validation

Common Patterns

Error Handling

Both unix and windows packages use errno-style error handling:

fd, err := unix.Open(path, unix.O_RDONLY, 0)
if err != nil {
    if err == unix.ENOENT {
        // File not found
    } else if err == unix.EACCES {
        // Permission denied
    }
    return err
}
defer unix.Close(fd)

Resource Management

Always use defer for cleanup:

// Unix
fd, err := unix.Open(path, unix.O_RDONLY, 0)
if err != nil {
    return err
}
defer unix.Close(fd)

// Windows
handle, err := windows.CreateFile(...)
if err != nil {
    return err
}
defer windows.CloseHandle(handle)

String Conversions

Unix (UTF-8)

// Go strings are already UTF-8
fd, err := unix.Open("/etc/hosts", unix.O_RDONLY, 0)

Windows (UTF-16)

// Convert to UTF-16
filename, err := windows.UTF16PtrFromString("C:\\test.txt")
if err != nil {
    return err
}

handle, err := windows.CreateFile(filename, ...)

Best Practices

  1. Use Higher-Level Packages When Possible: Prefer os, net, and time packages for portable code

  2. Platform-Specific Code: Use build tags to separate platform-specific implementations

  3. Error Handling: Always check and handle errors from system calls

  4. Resource Cleanup: Use defer to ensure handles and file descriptors are closed

  5. Buffer Management: Pre-allocate buffers of appropriate size and reuse when possible

  6. Security: Follow principle of least privilege for capabilities, tokens, and permissions

  7. Testing: Test platform-specific code on actual target platforms

  8. Documentation: Refer to OS documentation (man pages, MSDN) for detailed behavior

Compatibility

Unix Package Support

  • Linux: Full support (primary target)
  • macOS/Darwin: Full support
  • FreeBSD: Full support
  • OpenBSD: Full support
  • NetBSD: Full support
  • Solaris/Illumos: Full support
  • AIX: Supported

Windows Package Support

  • Windows 10: Full support
  • Windows 11: Full support
  • Windows Server 2016+: Full support
  • Windows Server 2019+: Full support

CPU Package Support

All major architectures: x86/AMD64, ARM/ARM64, PowerPC64, RISC-V, s390x, MIPS, LoongArch

Migration from syscall Package

The golang.org/x/sys packages are intended to replace the frozen syscall package from the standard library:

// Old (syscall package - frozen)
import "syscall"
fd, err := syscall.Open("/etc/hosts", syscall.O_RDONLY, 0)

// New (golang.org/x/sys/unix - actively maintained)
import "golang.org/x/sys/unix"
fd, err := unix.Open("/etc/hosts", unix.O_RDONLY, 0)

Benefits of migration:

  • Active development and bug fixes
  • New system call support
  • Better platform coverage
  • More complete API

Contributing

The golang.org/x/sys repository is part of the Go project:

Contributions must follow the Go contribution guidelines.

License

BSD-3-Clause License

Related Packages

  • os - Higher-level file and process operations
  • net - Higher-level networking
  • time - Higher-level time operations
  • runtime - Go runtime and garbage collector interface
  • unsafe - Low-level memory operations

Additional Resources

Version History

  • v0.38.0 (Current): Latest release with comprehensive API coverage
  • Earlier versions available in the Git repository history

Getting Help