dymokomi/luce-js
Source of release 0.6.1
0.6.1 / src / host / module.lucb
#==============================================================================================
#
# host - The QuickJS C library: what a runner and a simple embedder need around the engine
#
# DESCRIPTION:
# Port of the parts of quickjs-libc.c (QuickJS 2026-06-04) that run JavaScript files
# and QuickJS's own tests: the global helpers (print, console.log, scriptArgs), the
# default module loader reading files, the job and timer loop, and the `std` and `os`
# modules on POSIX targets (macOS and Linux), with their processes, pipes, signals,
# read/write handlers and ttys (on Windows, quickjs-libc.c's _WIN32 subset),
# os.Worker (worker threads with their own runtime and their message pipes) and the
# running of precompiled bytecode. Shared-library (.so) modules are native modules
# the embedder registers (native_modules). This fragment holds the imports and the
# state (JSThreadState); the C library bindings are in `libc` and `libc_process`.
#
# QuickJS C library
#
# Copyright (c) 2017-2021 Fabrice Bellard
# Copyright (c) 2017-2021 Charlie Gordon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions: the above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS
# IS", WITHOUT WARRANTY OF ANY KIND.
#
#==============================================================================================
import c
import platform
import sync
import thread
import time
import cutils
import engine as js
from cutils import DynBuf, ListHead
from engine import Context, Runtime, Value, ModuleDef, Atom, CFunctionListEntry
from engine import CFunctionEnum, ClassDef, PropertyEnum, PromiseState
# mark: Per-runtime state =======================================================================
## A read and/or write handler of a file descriptor (JSOSRWHandler).
struct OSRWHandler:
var link: ListHead
var fd: i32
## temporary use in js_os_poll()
var poll_fd_index: i32
## the read (0) and write (1) handlers, null when unset
var rw_func: Value[2]
## A JavaScript handler of a signal (JSOSSignalHandler).
struct OSSignalHandler:
var link: ListHead
var sig_num: i32
var func_: Value
## A pending os.setTimeout or os.sleepAsync (JSOSTimer).
struct OSTimer:
var link: ListHead
var timer_id: i32
var timeout: i64
var func_: Value
## A message posted to a worker or its parent (JSWorkerMessage): the value serialized
## with JS_WriteObject2 in C malloc'ed memory.
struct WorkerMessage:
var link: ListHead
var data: u8*?
var data_len: usize
## list of SharedArrayBuffers, necessary to free the message
var sab_tab: u8*?*?
var sab_tab_len: usize
## The wake-up of a message pipe (JSWaker): a POSIX pipe whose read end is readable while
## messages are queued, or on Windows a manual-reset event signaled while they are.
struct Waker:
var read_fd: i32
var write_fd: i32
## the event (a HANDLE), on Windows only
var handle: void*?
## A queue of messages from one thread to another, shared by both and reference counted
## (JSWorkerMessagePipe).
struct WorkerMessagePipe:
var ref_count: @i32
var mutex: sync.Mutex
## list of WorkerMessage.link
var msg_queue: ListHead
var waker: Waker
## A message port: the receiving end of a pipe with its onmessage handler
## (JSWorkerMessageHandler).
struct WorkerMessageHandler:
var link: ListHead
var recv_pipe: WorkerMessagePipe*?
var on_message_func: Value
## temporary use in js_os_poll()
var poll_fd_index: i32
## A rejected promise without a handler yet (JSRejectedPromiseEntry).
struct RejectedPromiseEntry:
var link: ListHead
var promise: Value
var reason: Value
## The host state of one runtime, its opaque pointer (JSThreadState).
struct ThreadState:
## list of OSRWHandler.link
var os_rw_handlers: ListHead
## list of OSSignalHandler.link
var os_signal_handlers: ListHead
## list of OSTimer.link
var os_timers: ListHead
## list of WorkerMessageHandler.link
var port_list: ListHead
## list of RejectedPromiseEntry.link
var rejected_promise_list: ListHead
## only used in the main thread
var eval_script_recurse: i32
## for setTimeout()
var next_timer_id: i32
# not used in the main thread
var recv_pipe: WorkerMessagePipe*?
var send_pipe: WorkerMessagePipe*?
## the descriptors js_os_poll waits for, poll_fds_size of them allocated (not used on
## Windows)
var poll_fds: PollFd*?
var poll_fds_size: i32
## Waits for and runs one event (js_os_poll); installed when the `os` module is
## initialized. Answers -1 when there are no more events.
type PollFunc = func(Context*) -> i32
## One bit per signal received and not yet handled; set by os_signal_handler.
var os_pending_signals: @u64
var os_poll_func: PollFunc?
## The host state of the runtime of `ctx`, installed by js_std_init_handlers.
func thread_state(rt: Runtime*) -> ThreadState*:
let opaque = js.js_get_runtime_opaque(rt) else trap("host: js_std_init_handlers was not called")
return (ThreadState*)opaque
func js_std_realloc(opaque: void*?, ptr: void*?, size: usize) -> void*?:
let rt = (Runtime*)(opaque else trap("host: dynbuf without runtime"))
return js.js_realloc_rt(rt, ptr, size)
func js_std_dbuf_init(ctx: Context*, s: DynBuf*):
cutils.dbuf_init2(s, js.js_get_runtime(ctx), js_std_realloc)
func my_isdigit(ch: u8) -> bool:
return ch >= '0' and ch <= '9'
## Whether the NUL-terminated `text` ends with `suffix` (has_suffix of cutils.c).
func has_suffix(text: const u8*, suffix: str) -> bool:
let len = cutils.strlen(text)
let slen = suffix.length
return len >= slen and cutils.memcmp(text + (len - slen), suffix.bytes.data, slen) == 0