Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.46.0

0.46.0 / src / std / os / module.lucb

#==============================================================================================
#
#   os - The operating system's view of the process
#
#   DESCRIPTION:
#       Its environment, working directory, identity and host (§16.6). Text comes back as `str`
#       views of C storage that the system owns; copy what must outlive the next call.
#
#==============================================================================================
import c
import memory
import windows_text
import platform
extern func getenv(variable: c.str) -> c.str?
extern func setenv(variable: c.str, value: c.str, overwrite: i32) -> i32
extern func unsetenv(variable: c.str) -> i32
extern func getcwd(buffer: u8*, size: usize) -> c.str?
extern func readlink(path: c.str, buffer: void*, capacity: usize) -> isize
extern func mac_executable_path as "_NSGetExecutablePath"(buffer: u8*, size: u32*) -> i32
extern func chdir(path: c.str) -> i32
extern func getpid() -> i32
extern func getppid() -> i32
extern func gethostname(buffer: u8*, size: usize) -> i32
extern func c_exit as "exit"(code: i32) -> never
extern func sysconf(option: i32) -> i64
extern func getentropy(buffer: void*, count: usize) -> i32
extern func BCryptGenRandom(algorithm: void*?, buffer: u8*, count: u32, flags: u32) -> i32

## Fill bytes from the operating system's cryptographic random generator.
## A failure is reported; weak process IDs or timestamps are never substituted.
pub func random_bytes(buffer: u8[]) -> !:
    var offset: usize = 0
    while offset < buffer.length:
        let count = buffer.length - offset if buffer.length - offset < 256 else 256
        var result: i32 = 0
        if platform.windows:
            result = BCryptGenRandom(none, &buffer[offset], (u32)count, 2)
        else:
            result = getentropy(&buffer[offset], count)
        if result != 0:
            error(failed, "operating system randomness is unavailable")
        offset += count

## An operating-system call failed.
pub let failed: ErrorCode = ErrorCode.package(12)

## The target, as constants a program branches on: `if os.arm64:`, `if os.linux and
## os.x86_64:` (§19.5); the compiler decides them from `--target`, so the branch a target
## rules out is pruned (§19.6).
pub let arm64: bool = platform.arm64
## Whether the target architecture is x86-64.
pub let x86_64: bool = platform.x86_64
## Whether the target operating system is macOS.
pub let macos: bool = platform.macos
## Whether the target operating system is Linux.
pub let linux: bool = platform.linux
## Whether the target operating system is Windows.
pub let windows: bool = platform.windows
## Whether the target is a POSIX system.
pub let posix: bool = platform.posix
## The width of a pointer on the target, in bits.
pub let pointer_bits: u32 = platform.pointer_bits
## The target triple.
pub let name: str = platform.name
## The instruction-set level the program was compiled for (`--cpu`, §19.5): on x86-64, 1
## to 4 for x86-64-v1 to v4; on arm64, 1 for NEON, 2 for SVE.
pub let cpu_level: u32 = platform.cpu_level

## The instruction-set level of the processor this program runs on, in the same scale:
## what it may dispatch to at run time. On x86-64 `cpuid` answers; on arm64 the level is
## NEON until the system reports SVE.
# mark: Machine and process ===================================================================

## The microarchitecture level (§19.5) the CPU running this process supports.
pub func cpu_level_running() -> u32:
    if platform.x86_64:
        return x86_level()
    return 1

## x86-64: SSE4.2 and POPCNT make v2; AVX2, FMA, and BMI2 make v3; AVX-512F makes v4.
func x86_level() -> u32:
    var c1: u32 = 0
    var b7: u32 = 0
    asm x86_64 (in("eax") 1u32, out("ecx") c1, out("eax") _, out("ebx") _, out("edx") _, options(nostack)):
        cpuid
    asm x86_64 (in("eax") 7u32, in("ecx") 0u32, out("ebx") b7, out("eax") _, out("ecx") _, out("edx") _, options(nostack)):
        cpuid
    let sse42 = (c1 & (1 << 20)) != 0
    let popcnt = (c1 & (1 << 23)) != 0
    let fma = (c1 & (1 << 12)) != 0
    # the operating system saves the wide registers only with `OSXSAVE` set
    let osxsave = (c1 & (1 << 27)) != 0
    let avx2 = (b7 & (1 << 5)) != 0
    let bmi2 = (b7 & (1 << 8)) != 0
    let avx512f = (b7 & (1 << 16)) != 0
    if not (sse42 and popcnt):
        return 1
    if not (avx2 and fma and bmi2 and osxsave):
        return 2
    return 4 if avx512f else 3

## `_SC_NPROCESSORS_ONLN`: 58 on macOS, 84 on Linux.
let processors_online: i32 = 58 if platform.macos else 84

## The processors available to this process, at least one.
pub func cpus() -> u32:
    if platform.windows:
        let count = GetActiveProcessorCount(65535)
        return count if count > 0 else 1
    let n = sysconf(processors_online)
    return (u32)n if n > 0 else 1

## The host's memory page size in bytes.
pub func page_size() -> usize:
    return memory.page_size()

## The value of an environment variable, or none when it is not set. Copy a view
## that must survive another env call on this thread or an environment mutation.
pub func env(variable: c.str) -> str?:
    if platform.windows:
        return windows_env(variable)
    let value = getenv(variable) else return none
    return (str)value

## Set an environment variable for this process and the ones it starts.
pub func set_env(variable: c.str, value: c.str) -> !:
    if platform.windows:
        let key = try windows_text.wide(variable, failed)
        defer free(key)
        let text = try windows_text.wide(value, failed)
        defer free(text)
        if SetEnvironmentVariableW(key.data, text.data) == 0:
            error(failed, "the environment variable cannot be set")
        return
    if setenv(variable, value, 1) != 0:
        error(failed, "the environment variable cannot be set")

## Remove environment variable `variable`.
pub func unset_env(variable: c.str) -> !:
    if platform.windows:
        let key = try windows_text.wide(variable, failed)
        defer free(key)
        if SetEnvironmentVariableW(key.data, none) == 0 and GetLastError() != 203:
            error(failed, "the environment variable cannot be unset")
        return
    if unsetenv(variable) != 0:
        error(failed, "the environment variable cannot be unset")

## The working directory, in storage from the current allocator.
pub func cwd() -> str!:
    if platform.windows:
        return try windows_cwd()
    let buffer = try new u8[4096] ---
    errdefer free(buffer)
    let found = getcwd(buffer.data, buffer.length)
    if found == none:
        error(failed, "the working directory cannot be read")
    let path = found else trap("unreachable")
    return (str)path

## The path of this program's executable as the loader saw it, in an allocation of the
## current allocator, NUL-terminated for the C calls a path goes to.
pub func executable() -> str!:
    if platform.windows:
        return try windows_executable()
    let buffer = try new u8[4096] ---
    errdefer free(buffer)
    var count: usize = 0
    if platform.macos:
        var size: u32 = 4096
        if mac_executable_path(buffer.data, &size) != 0:
            error(failed, "the executable path cannot be read")
        while count < buffer.length and buffer[count] != 0:
            count += 1
    else:
        let read = readlink("/proc/self/exe", buffer.data, buffer.length - 1)
        if read < 0:
            error(failed, "the executable path cannot be read")
        count = (usize)read
    buffer[count] = 0
    return (str)buffer[..<count]

## Change the process's working directory to `path`.
pub func change_dir(path: c.str) -> !:
    if platform.windows:
        let text = try windows_text.wide(path, failed)
        defer free(text)
        if SetCurrentDirectoryW(text.data) == 0:
            error(failed, "the directory cannot be entered")
        return
    if chdir(path) != 0:
        error(failed, "the directory cannot be entered")

## The process identifier.
pub func pid() -> i32:
    if platform.windows:
        return (i32)GetCurrentProcessId()
    return getpid()

## The parent process's identifier.
pub func parent_pid() -> i32:
    if platform.windows:
        return windows_parent_pid()
    return getppid()

## The host's name, in storage from the current allocator.
pub func hostname() -> str!:
    if platform.windows:
        var host_text: u16[256]
        var count: u32 = 256
        if GetComputerNameW(&host_text[0], &count) == 0:
            error(failed, "the host name cannot be read")
        return try windows_text.narrow(host_text[..<(usize)count], failed)
    let buffer = try new u8[256] ---
    errdefer free(buffer)
    if gethostname(buffer.data, buffer.length) != 0:
        error(failed, "the host name cannot be read")
    var n: usize = 0
    while n < buffer.length and buffer[n] != 0:
        n += 1
    return (str)buffer[..<n]

## Stop the process with `code`, running no deferred work.
pub func exit(code: i32) -> never:
    c_exit(code)