Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.1

0.6.1 / src / host / os_module.lucb

#==============================================================================================
#
#   os_module - The `os` module: file descriptors, ttys, read/write handlers and signals
#
#   DESCRIPTION:
#       Port of quickjs-libc.c lines 1735-1830 (open, close, seek, read, write, isatty),
#       1879-1937 (ttyGetWinSize, ttySetRaw), 1939-1983 (remove, rename) and 1985-2130
#       (is_main_thread, setReadHandler, setWriteHandler, signal), with the _WIN32
#       branches of open, the ttys (the console) and remove. The timers and js_os_poll are in
#       `os_poll`, the file system in `os_files`, the processes in `os_process` and the
#       module's table in `os_tables`.
#
#==============================================================================================

# mark: File descriptors ========================================================================

func js_os_open(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let filename = try js.js_to_c_string(ctx, argv[0])
    defer js.js_free_c_string(ctx, filename)
    var flags: i32 = 0
    try js.js_to_int32(ctx, &flags, argv[1])
    var mode: i32 = 0o666
    if argc >= 3 and not js.js_is_undefined(argv[2]):
        try js.js_to_int32(ctx, &mode, argv[2])
    if platform.windows:
        # force binary mode by default
        if (flags & o_text) == 0:
            flags |= o_binary
    let ret = js_get_errno((i64)c_open(filename, flags, mode))
    return js.js_new_int32((i32)ret)

func js_os_close(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    return js.js_new_int32((i32)js_get_errno((i64)close(fd)))

func js_os_seek(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    let is_bigint = js.js_is_big_int(argv[1])
    var pos: i64 = 0
    try js.js_to_int64_ext(ctx, &pos, argv[1])
    var whence: i32 = 0
    try js.js_to_int32(ctx, &whence, argv[2])
    var ret = fd_seek(fd, pos, whence)
    if ret == -1:
        ret = -(i64)c.errno()
    if is_bigint:
        return try js.js_new_bigint64(ctx, ret)
    return js.js_new_int64(ret)

## os.read (magic 0) and os.write (magic 1): `(fd, buffer, position, length)`.
func js_os_read_write(ctx: Context*, this_val: Value, argc: i32, argv: Value*, magic: i32) -> Value!:
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    var pos: u64 = 0
    try js.js_to_index(ctx, &pos, argv[2])
    var len: u64 = 0
    try js.js_to_index(ctx, &len, argv[3])
    var size: usize = 0
    let buf = try js.js_get_array_buffer(ctx, &size, argv[1])
    if pos + len > (u64)size:
        try js.js_throw_range_error(ctx, "read/write array buffer overflow")
    let data = buf else return js.js_new_int64(0)
    var ret: i64 = 0
    if magic != 0:
        ret = js_get_errno(fd_write(fd, data + (usize)pos, (usize)len))
    else:
        ret = js_get_errno(fd_read(fd, data + (usize)pos, (usize)len))
    return js.js_new_int64(ret)

func js_os_isatty(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    return js.js_new_bool(isatty(fd) != 0)

# mark: ttys ====================================================================================

func js_os_tty_get_win_size(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    if platform.windows:
        return try js_os_tty_get_win_size_windows(ctx, fd)
    else:
        var ws: WinSize
        if ioctl(fd, tiocgwinsz, &ws) == 0 and ws.ws_col >= 4 and ws.ws_row >= 4:
            let obj = try js.js_new_array(ctx)
            _ = js.js_define_property_value_uint32(ctx, obj, 0, js.js_new_int32((i32)ws.ws_col), js.prop_c_w_e) catch: recover false
            _ = js.js_define_property_value_uint32(ctx, obj, 1, js.js_new_int32((i32)ws.ws_row), js.prop_c_w_e) catch: recover false
            return obj
        return js.js_null()

## The terminal state before os.ttySetRaw, restored at exit (a `struct termios`).
var oldtty: u8[128]

func term_exit():
    if not platform.windows:
        _ = tcsetattr(0, tcsanow, &oldtty[0])

## Clear the bits `clear` and set the bits `set` of the tcflag_t `index` of `tty`.
func termios_update_flag(tty: u8*, index: usize, clear: u32, set: u32):
    let p = tty + termios_flag_offset(index)
    cutils.put_u32(p, (cutils.get_u32(p) & ~clear) | set)

# XXX: should add a way to go back to normal mode
func js_os_tty_set_raw(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    if platform.windows:
        js_os_tty_set_raw_windows(fd)
    else:
        tty_set_raw_posix(fd)
    return js.js_undefined()

## ttySetRaw on a POSIX terminal: termios in raw mode, restored at exit.
func tty_set_raw_posix(fd: i32):
    if not platform.windows:
        var tty: u8[128]
        _ = tcgetattr(fd, &tty[0])
        oldtty = tty

        termios_update_flag(&tty[0], 0, tc_ignbrk | tc_brkint | tc_parmrk | tc_istrip | tc_inlcr | tc_igncr | tc_icrnl | tc_ixon, 0)
        termios_update_flag(&tty[0], 1, 0, tc_opost)
        termios_update_flag(&tty[0], 3, tc_echo | tc_echonl | tc_icanon | tc_iexten, 0)
        termios_update_flag(&tty[0], 2, tc_csize | tc_parenb, 0)
        termios_update_flag(&tty[0], 2, 0, tc_cs8)
        tty[termios_cc_offset + tc_vmin] = 1
        tty[termios_cc_offset + tc_vtime] = 0

        _ = tcsetattr(fd, tcsanow, &tty[0])

        _ = atexit(term_exit)

func js_os_remove(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let filename = try js.js_to_c_string(ctx, argv[0])
    var ret: i64 = 0
    if platform.windows:
        var st: u8[56] = ---
        if win_stat64(filename, &st[0]) == 0 and (stat_info(&st[0]).mode & s_ifmt) == s_ifdir:
            ret = (i64)win_rmdir(filename)
        else:
            ret = (i64)win_unlink(filename)
    else:
        ret = (i64)remove(filename)
    ret = js_get_errno(ret)
    js.js_free_c_string(ctx, filename)
    return js.js_new_int32((i32)ret)

# The Windows ttys: the console behind the descriptor's handle.

func js_os_tty_get_win_size_windows(ctx: Context*, fd: i32) -> Value!:
    if platform.windows:
        let handle = (void*?)(usize)win_get_osfhandle(fd)
        var info: u8[22] = ---
        if GetConsoleScreenBufferInfo(handle, &info[0]) == 0:
            return js.js_null()
        let obj = try js.js_new_array(ctx)
        _ = js.js_define_property_value_uint32(ctx, obj, 0, js.js_new_int32(cutils.get_i16(&info[0])), js.prop_c_w_e) catch: recover false
        _ = js.js_define_property_value_uint32(ctx, obj, 1, js.js_new_int32(cutils.get_i16(&info[2])), js.prop_c_w_e) catch: recover false
        return obj
    else:
        return js.js_null()

func js_os_tty_set_raw_windows(fd: i32):
    if platform.windows:
        var handle = (void*?)(usize)win_get_osfhandle(fd)
        _ = SetConsoleMode(handle, enable_window_input | enable_virtual_terminal_input)
        _ = win_setmode(fd, o_binary)
        if fd == 0:
            handle = (void*?)(usize)win_get_osfhandle(1)  # corresponding output
            _ = SetConsoleMode(handle, enable_processed_output | enable_wrap_at_eol_output | enable_virtual_terminal_processing)

func js_os_rename(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let oldpath = try js.js_to_c_string(ctx, argv[0])
    defer js.js_free_c_string(ctx, oldpath)
    let newpath = try js.js_to_c_string(ctx, argv[1])
    defer js.js_free_c_string(ctx, newpath)
    return js.js_new_int32((i32)js_get_errno((i64)rename(oldpath, newpath)))

# mark: Read/write handlers =====================================================================

## Whether `rt` runs on the main thread rather than in a worker.
func is_main_thread(rt: Runtime*) -> bool:
    let ts = thread_state(rt)
    return ts.recv_pipe == none

## The read/write handler whose list link is `el`.
func rw_handler_of(el: ListHead*) -> OSRWHandler*:
    return (OSRWHandler*)((u8*)el - memory.offset_of(OSRWHandler, link))

func find_rh(ts: ThreadState*, fd: i32) -> OSRWHandler*?:
    var el = ts.os_rw_handlers.next else return none
    while el != &ts.os_rw_handlers:
        let rh = rw_handler_of(el)
        if rh.fd == fd:
            return rh
        el = el.next else return none
    return none

func free_rw_handler(rt: Runtime*, rh: OSRWHandler*):
    cutils.list_del(&rh.link)
    for i in 0..<2:
        js.js_free_value_rt(rt, rh.rw_func[i])
    js.js_free_rt(rt, rh)

## os.setReadHandler (magic 0) and os.setWriteHandler (magic 1): `(fd, func)`; a null
## `func` removes the handler.
func js_os_set_read_handler(ctx: Context*, this_val: Value, argc: i32, argv: Value*, magic: i32) -> Value!:
    let rt = js.js_get_runtime(ctx)
    let ts = thread_state(rt)
    let index = (usize)magic
    var fd: i32 = 0
    try js.js_to_int32(ctx, &fd, argv[0])
    let func_ = argv[1]
    if js.js_is_null(func_):
        if let rh = find_rh(ts, fd):
            js.js_free_value(ctx, rh.rw_func[index])
            rh.rw_func[index] = js.js_null()
            if js.js_is_null(rh.rw_func[0]) and js.js_is_null(rh.rw_func[1]):
                # remove the entry
                free_rw_handler(js.js_get_runtime(ctx), rh)
    else:
        if not js.js_is_function(ctx, func_):
            try js.js_throw_type_error(ctx, "not a function")
        var found = find_rh(ts, fd)
        if found == none:
            let rh = (OSRWHandler*)try js.js_mallocz(ctx, memory.size_of(OSRWHandler))
            rh.fd = fd
            rh.rw_func[0] = js.js_null()
            rh.rw_func[1] = js.js_null()
            cutils.list_add_tail(&rh.link, &ts.os_rw_handlers)
            found = rh
        let rh = found else return js.js_undefined()
        js.js_free_value(ctx, rh.rw_func[index])
        rh.rw_func[index] = js.js_dup_value(ctx, func_)
    return js.js_undefined()

# mark: Signals =================================================================================

## The signal handler whose list link is `el`.
func signal_handler_of(el: ListHead*) -> OSSignalHandler*:
    return (OSSignalHandler*)((u8*)el - memory.offset_of(OSSignalHandler, link))

func find_sh(ts: ThreadState*, sig_num: i32) -> OSSignalHandler*?:
    var el = ts.os_signal_handlers.next else return none
    while el != &ts.os_signal_handlers:
        let sh = signal_handler_of(el)
        if sh.sig_num == sig_num:
            return sh
        el = el.next else return none
    return none

func free_sh(rt: Runtime*, sh: OSSignalHandler*):
    cutils.list_del(&sh.link)
    js.js_free_value_rt(rt, sh.func_)
    js.js_free_rt(rt, sh)

## The C signal handler: only records the signal, which js_os_poll handles.
func os_signal_handler(sig_num: i32):
    os_pending_signals |= (u64)1 << (u64)sig_num

## os.signal(sig_num, func): a function handles the signal in the event loop, null restores
## the default action and undefined ignores the signal.
func js_os_signal(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    let rt = js.js_get_runtime(ctx)
    let ts = thread_state(rt)
    if not is_main_thread(rt):
        try js.js_throw_type_error(ctx, "signal handler can only be set in the main thread")

    var sig_num: u32 = 0
    try js.js_to_uint32(ctx, &sig_num, argv[0])
    if sig_num >= 64:
        try js.js_throw_range_error(ctx, "invalid signal number")
    let func_ = argv[1]
    # func = null: SIG_DFL, func = undefined, SIG_IGN
    if js.js_is_null(func_) or js.js_is_undefined(func_):
        if let sh = find_sh(ts, (i32)sig_num):
            free_sh(js.js_get_runtime(ctx), sh)
        var handler: void*? = none  # SIG_DFL
        if not js.js_is_null(func_):
            handler = sig_ign()
        _ = c_signal((i32)sig_num, handler)
    else:
        if not js.js_is_function(ctx, func_):
            try js.js_throw_type_error(ctx, "not a function")
        var found = find_sh(ts, (i32)sig_num)
        if found == none:
            let sh = (OSSignalHandler*)try js.js_mallocz(ctx, memory.size_of(OSSignalHandler))
            sh.sig_num = (i32)sig_num
            sh.func_ = js.js_undefined()
            cutils.list_add_tail(&sh.link, &ts.os_signal_handlers)
            found = sh
        let sh = found else return js.js_undefined()
        js.js_free_value(ctx, sh.func_)
        sh.func_ = js.js_dup_value(ctx, func_)
        _ = c_signal((i32)sig_num, (void*)os_signal_handler)
    return js.js_undefined()