Path: blob/main/core/kernel/src/wasm/posix/time.ts
1068 views
const dateFormat = require("date-format");1import { notImplemented } from "./util";23export default function time({ child_process, memory, os }) {4return {5// int adjtime (const struct timeval *, struct timeval *);6adjtime() {7// TODO: similar to clock_settime below... but really maybe not necessary since8// cowasm should be pretty sandboxed!9notImplemented("TODO: implement adjtime");10},11settimeofday() {12notImplemented("TODO: settimeofday");13},14// int clock_settime(clockid_t clk_id, const struct timespec *tp);15clock_settime(_clk_id: number, timespec: number): number {16if (child_process.spawnSync == null) {17throw Error("clock_settime is not supported on this platform");18}19// NOTE: We assume the clk_id is CLOCK_REALTIME without a check.2021const view = new DataView(memory.buffer);22const tv_sec = view.getUint32(timespec, true);23// we ignore nanoseconds here; the date commands aren't that precise anyways.2425let cmd,26cmd2 = "",27args,28args2 = [];2930switch (os.platform?.()) {31case "darwin":32// date -f "%s" "1660173350" # <-- number of seconds.33cmd = "date";34args = ["-f", "%s", `${tv_sec}`];35break;36case "linux":37// date --date='@2147483647' # <-- number of seconds38cmd = "date";39args = [`--set=@${tv_sec}`];40break;41case "win32":42const dateTime = new Date(1000 * tv_sec);43cmd = "date";44args = [dateFormat("m/d/yyyy", dateTime)];45cmd2 = "time";46args = [dateFormat("HH:MM:ss", dateTime)];47break;48default:49throw Error(50`clock_settime not supported on platform = ${os.platform?.()}`51);52}53const { status, stderr } = child_process.spawnSync(cmd, args);54if (status) {55throw Error(`clock_settime failed - ${stderr}`);56}57if (cmd2) {58const { status, stderr } = child_process.spawnSync(cmd2, args2);59if (status) {60throw Error(`clock_settime failed - ${stderr}`);61}62}63return 0;64},65};66}676869