Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.1

0.6.1 / src / host / os_process.lucb

#==============================================================================================
#
#   os_process - The `os` module's processes: exec, waitpid, pipe, kill, dup and dup2
#
#   DESCRIPTION:
#       Port of quickjs-libc.c lines 3035-3459: build_envp, my_execvpe, os.exec, getpid,
#       waitpid, pipe, kill, dup and dup2. os.exec forks; the child remaps its standard
#       handles, closes the others, changes directory and identity, and execs; the parent
#       waits for it unless `block` is false. None of them is in the Windows `os` table.
#
#==============================================================================================

# mark: exec ====================================================================================

## Free a js_malloc'ed NULL-terminated array of js_malloc'ed strings.
func free_envp(ctx: Context*, envp: CStringEntry*):
    var i: usize = 0
    while let entry = envp[i]:
        js.js_free(ctx, (void*)entry)
        i += 1
    js.js_free(ctx, envp)

## The `key=value` strings of the enumerable string properties of `obj`, js_malloc'ed and
## NULL-terminated.
func build_envp(ctx: Context*, obj: Value) -> CStringEntry*!:
    var tab: PropertyEnum*? = none
    var len: u32 = 0
    try js.js_get_own_property_names(ctx, &tab, &len, obj, js.gpn_string_mask | js.gpn_enum_only)
    defer js.js_free_property_enum(ctx, tab, len)
    let envp = (CStringEntry*)try js.js_mallocz(ctx, memory.size_of(CStringEntry) * ((usize)len + 1))
    errdefer free_envp(ctx, envp)
    let entries = tab else return envp
    for i in 0..<(usize)len:
        let val = try js.js_get_property(ctx, obj, entries[i].atom)
        let text = js.js_to_c_string(ctx, val) catch failure:
            js.js_free_value(ctx, val)
            error(failure.code, failure.message)
        js.js_free_value(ctx, val)
        defer js.js_free_c_string(ctx, text)
        let key = try js.js_atom_to_c_string(ctx, entries[i].atom)
        defer js.js_free_c_string(ctx, key)
        let key_len = cutils.strlen(key)
        let str_len = cutils.strlen(text)
        let pair = (u8*)try js.js_malloc(ctx, key_len + str_len + 2)
        _ = cutils.memcpy(pair, key, key_len)
        pair[key_len] = '='
        _ = cutils.memcpy(pair + (key_len + 1), text, str_len)
        pair[key_len + 1 + str_len] = 0
        envp[i] = pair
    return envp

## execvpe is not available on non GNU systems
func my_execvpe(filename: const u8*, argv: CStringEntry*, envp: CStringEntry*) -> i32:
    if platform.windows:
        return -1
    else:
        let filename_len = cutils.strlen(filename)
        if filename_len == 0:
            c.set_errno(e_noent)
            return -1
        if strchr(filename, (i32)'/') != none:
            return execve(filename, argv, envp)

        var path: const u8* = "/bin:/usr/bin".bytes.data
        if let value = getenv("PATH".bytes.data):
            path = value
        var buf: u8[4096] = ---
        var eacces_error = false
        var p: const u8*? = path
        while let dir = p:
            var path_len: usize = 0
            if let p1 = strchr(dir, (i32)':'):
                p = p1 + 1
                path_len = (usize)(p1 - dir)
            else:
                p = none
                path_len = cutils.strlen(dir)
            # path too long
            if path_len + 1 + filename_len + 1 > path_max:
                continue
            _ = cutils.memcpy(&buf[0], dir, path_len)
            buf[path_len] = '/'
            _ = cutils.memcpy(&buf[path_len + 1], filename, filename_len)
            buf[path_len + 1 + filename_len] = 0

            _ = execve(&buf[0], argv, envp)

            let err = c.errno()
            if err == e_acces:
                eacces_error = true
            elif err != e_noent and err != e_notdir:
                return -1
        if eacces_error:
            c.set_errno(e_acces)
        return -1

## The options of os.exec, read before the fork.
struct ExecOptions:
    var block_flag: bool
    var use_path: bool
    ## the program to run instead of args[0]
    var file: const u8*?
    var cwd: const u8*?
    ## the descriptors that become the child's stdin, stdout and stderr
    var std_fds: i32[3]
    ## the child's environment, none for the parent's
    var envp: CStringEntry*?
    ## the child's user and group, 0xffffffff to keep the parent's
    var uid: u32
    var gid: u32

func free_exec_options(ctx: Context*, options: ExecOptions*):
    js.js_free_c_string(ctx, options.file)
    js.js_free_c_string(ctx, options.cwd)
    if let envp = options.envp:
        free_envp(ctx, envp)

## Set `*pres` to the string property `option` of `obj` when it is defined.
func get_string_option(ctx: Context*, pres: const u8*?*, obj: Value, option: str) -> !:
    let val = try js.js_get_property_str(ctx, obj, option)
    defer js.js_free_value(ctx, val)
    if not js.js_is_undefined(val):
        *pres = try js.js_to_c_string(ctx, val)

## Set `*pres` to the int32 property `option` of `obj` when it is defined.
func get_int32_option(ctx: Context*, pres: i32*, obj: Value, option: str) -> !:
    let val = try js.js_get_property_str(ctx, obj, option)
    defer js.js_free_value(ctx, val)
    if not js.js_is_undefined(val):
        try js.js_to_int32(ctx, pres, val)

## Set `*pres` to the uint32 property `option` of `obj` when it is defined.
func get_uint32_option(ctx: Context*, pres: u32*, obj: Value, option: str) -> !:
    let val = try js.js_get_property_str(ctx, obj, option)
    defer js.js_free_value(ctx, val)
    if not js.js_is_undefined(val):
        try js.js_to_uint32(ctx, pres, val)

## Read the options object of os.exec into `options`.
func get_exec_options(ctx: Context*, obj: Value, options: ExecOptions*) -> !:
    try get_bool_option(ctx, &options.block_flag, obj, "block")
    try get_bool_option(ctx, &options.use_path, obj, "usePath")
    try get_string_option(ctx, &options.file, obj, "file")
    try get_string_option(ctx, &options.cwd, obj, "cwd")

    # stdin/stdout/stderr handles
    try get_int32_option(ctx, &options.std_fds[0], obj, "stdin")
    try get_int32_option(ctx, &options.std_fds[1], obj, "stdout")
    try get_int32_option(ctx, &options.std_fds[2], obj, "stderr")

    let val = try js.js_get_property_str(ctx, obj, "env")
    defer js.js_free_value(ctx, val)
    if not js.js_is_undefined(val):
        options.envp = try build_envp(ctx, val)

    try get_uint32_option(ctx, &options.uid, obj, "uid")
    try get_uint32_option(ctx, &options.gid, obj, "gid")

## The child side of os.exec: set up the process and exec, or exit with status 127.
func exec_child(exec_argv: CStringEntry*, options: const ExecOptions*) -> never:
    if platform.windows:
        trap("os.exec is not in the Windows table")
    else:
        # remap the stdin/stdout/stderr handles if necessary
        for i in 0..<3:
            if options.std_fds[i] != (i32)i:
                if dup2(options.std_fds[i], (i32)i) < 0:
                    _exit(127)

        # Close the file handles manually, limit to 1024 to avoid costly loop on linux Alpine
        # where sysconf(_SC_OPEN_MAX) returns a huge value 1048576. (QuickJS calls closefrom(3)
        # where the C library has it, which closes the same handles.)
        let fd_max = cutils.min_int((i32)sysconf(sc_open_max), 1024)
        var fd: i32 = 3
        while fd < fd_max:
            _ = close(fd)
            fd += 1

        if let cwd = options.cwd:
            if chdir(cwd) < 0:
                _exit(127)
        if options.gid != 0xffffffff:
            if setgid(options.gid) < 0:
                _exit(127)
        if options.uid != 0xffffffff:
            if setuid(options.uid) < 0:
                _exit(127)

        var file = exec_argv[0] else _exit(127)
        if let name = options.file:
            file = name
        var envp = environment()
        if let env = options.envp:
            envp = env
        if options.use_path:
            _ = my_execvpe(file, exec_argv, envp)
        else:
            _ = execve(file, exec_argv, envp)
        _exit(127)

## Free the arguments os.exec converted.
func free_exec_argv(ctx: Context*, exec_argv: CStringEntry*, exec_argc: u32):
    for i in 0..<(usize)exec_argc:
        js.js_free_c_string(ctx, exec_argv[i])
    js.js_free(ctx, exec_argv)

## exec(args[, options]) -> exitcode
func js_os_exec(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    if platform.windows:
        return js.js_undefined()  # not in the Windows table
    else:
        let args = argv[0]
        var exec_argc: u32 = 0
        try get_uint32_option(ctx, &exec_argc, args, "length")
        # arbitrary limit to avoid overflow
        if exec_argc < 1 or exec_argc > 65535:
            try js.js_throw_type_error(ctx, "invalid number of arguments")
        let exec_argv = (CStringEntry*)try js.js_mallocz(ctx, memory.size_of(CStringEntry) * ((usize)exec_argc + 1))
        defer free_exec_argv(ctx, exec_argv, exec_argc)
        for i in 0..<exec_argc:
            let val = try js.js_get_property_uint32(ctx, args, i)
            let text = js.js_to_c_string(ctx, val) catch failure:
                js.js_free_value(ctx, val)
                error(failure.code, failure.message)
            js.js_free_value(ctx, val)
            exec_argv[(usize)i] = text
        exec_argv[(usize)exec_argc] = none

        var options = ExecOptions(block_flag = true, use_path = true, file = none, cwd = none,
                                  std_fds = [0, 1, 2], envp = none, uid = 0xffffffff, gid = 0xffffffff)
        defer free_exec_options(ctx, &options)
        # get the options, if any
        if argc >= 2:
            try get_exec_options(ctx, argv[1], &options)

        let pid = fork()
        if pid < 0:
            try js.js_throw_type_error(ctx, "fork error")
        if pid == 0:
            # child
            exec_child(exec_argv, &options)
        # parent
        var ret: i32 = pid
        if options.block_flag:
            while true:
                var status: i32 = 0
                if waitpid(pid, &status, 0) == pid:
                    if w_if_exited(status):
                        ret = w_exit_status(status)
                        break
                    elif w_if_signaled(status):
                        ret = -w_term_sig(status)
                        break
        return js.js_new_int32(ret)

# mark: Process identity and descriptors ========================================================

## getpid() -> pid
func js_os_getpid(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    return js.js_new_int32(getpid())

## waitpid(pid, block) -> [pid, status]
func js_os_waitpid(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    if platform.windows:
        return js.js_undefined()  # not in the Windows table
    else:
        var pid: i32 = 0
        try js.js_to_int32(ctx, &pid, argv[0])
        var options: i32 = 0
        try js.js_to_int32(ctx, &options, argv[1])

        var status: i32 = 0
        var ret = waitpid(pid, &status, options)
        if ret < 0:
            ret = -c.errno()
            status = 0

        let obj = try js.js_new_array(ctx)
        _ = js.js_define_property_value_uint32(ctx, obj, 0, js.js_new_int32(ret), js.prop_c_w_e) catch: recover false
        _ = js.js_define_property_value_uint32(ctx, obj, 1, js.js_new_int32(status), js.prop_c_w_e) catch: recover false
        return obj

## pipe() -> [read_fd, write_fd] or null if error
func js_os_pipe(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    if platform.windows:
        return js.js_undefined()  # not in the Windows table
    else:
        var pipe_fds: i32[2] = [0, 0]
        if pipe(&pipe_fds[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(pipe_fds[0]), js.prop_c_w_e) catch: recover false
        _ = js.js_define_property_value_uint32(ctx, obj, 1, js.js_new_int32(pipe_fds[1]), js.prop_c_w_e) catch: recover false
        return obj

## kill(pid, sig)
func js_os_kill(ctx: Context*, this_val: Value, argc: i32, argv: Value*) -> Value!:
    if platform.windows:
        return js.js_undefined()  # not in the Windows table
    else:
        var pid: i32 = 0
        try js.js_to_int32(ctx, &pid, argv[0])
        var sig: i32 = 0
        try js.js_to_int32(ctx, &sig, argv[1])
        return js.js_new_int32((i32)js_get_errno((i64)kill(pid, sig)))

## dup(fd)
func js_os_dup(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)dup(fd)))

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