forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvmworker.ts
More file actions
213 lines (196 loc) · 6.24 KB
/
vmworker.ts
File metadata and controls
213 lines (196 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import { DebugInfo, parseStackFrame } from "@devicescript/compiler"
import { ChildProcess, fork, spawn } from "node:child_process"
import { isVerbose, verboseLog, wrapColor } from "./command"
import {
addReqHandler,
DevToolsClient,
devtoolsIface,
sendOutput,
} from "./sidedata"
import {
OutputFrom,
SideStartVmReq,
SideStartVmResp,
SideStopVmReq,
SideStopVmResp,
} from "./sideprotocol"
let worker: ChildProcess & { isSelfKill?: boolean }
export function waitForEvent<T>(
ms: number,
f: (cb: (v?: T) => void) => void
): Promise<T | undefined> {
let done = false
return new Promise<T>(resolve => {
const resolveWrapped = (v: T) => {
if (!done) {
done = true
resolve(v)
}
}
f(resolveWrapped)
setTimeout(() => resolveWrapped(undefined), ms)
})
}
export function lineBuffer(cb: (lines: string[]) => void) {
let acc = ""
let to: any
const flush = () => {
to = null
if (acc) {
const lines = [acc]
acc = ""
cb(lines)
}
}
return (str: string) => {
if (str.includes("\r")) str = str.replace(/\r/g, "")
if (acc) str = acc + str
if (str.includes("\n")) {
const lines = str.split("\n")
acc = lines.pop()
cb(lines)
} else {
acc = str
}
if (to) clearTimeout(to)
if (acc) to = setTimeout(flush, 200)
}
}
export async function stopVmWorker() {
const w = worker
worker = null
if (w) {
verboseLog(`vmworker: stopping`)
try {
w.isSelfKill = true
if (w.exitCode === null && w.signalCode === null) {
w.kill()
await waitForEvent(500, f => w.on("exit", f))
}
w.kill("SIGKILL")
} catch (e) {
verboseLog(`vmworker: kill error: ` + e)
}
}
}
function stripColors(str: string) {
return str.replace(/\x1B\[[0-9;]+m/g, "")
}
export function overrideConsoleDebug() {
const condbg = console.debug
console.debug = (...args: any[]) => {
const cl = devtoolsIface?.mainClient
if (
args.length == 1 &&
typeof args[0] == "string" &&
args[0].startsWith("DEV: ")
) {
let line = stripColors(args[0]).slice(5)
if (cl) sendOutput(cl, "dev", [line])
line = line.replace(/^DM \(\d+\): ?/, "")
if (line) printDmesg(devtoolsIface.lastOKBuild?.dbg, "DEV", line)
} else {
let str = ""
for (const a of args) {
if (str) str += " "
str += a
}
if (cl) sendOutput(cl, "verbose", [stripColors(str)])
else {
if (isVerbose) condbg(wrapColor(90, stripColors(str)))
}
}
}
}
export function printDmesg(dbg: DebugInfo, pref: string, line: string) {
const m = /^\s*([\*\!\?>#]) (.*)/.exec(line)
if (m) {
let [_full, marker, text] = m
if (dbg) text = parseStackFrame(dbg, text).markedLine
if (marker == "!") text = wrapColor(91, text)
else if (marker == ">") text = wrapColor(95, text)
else if (marker == "?") text = wrapColor(34, text)
else if (marker == "#") {
const [tm, obj] = text.split(" ", 2)
text = tm + "ms " + wrapColor(92, obj)
} else text = wrapColor(33, text)
console.log(pref + "> " + text)
return true
} else if (isVerbose) {
line = line.trim()
if (isVerbose <= 1 && /^(wifi:|free memory)/.test(line)) return false
console.log(wrapColor(90, "V> " + line))
return true
} else {
return false
}
}
export async function startVmWorker(
req: SideStartVmReq,
sender: DevToolsClient
) {
const args = req.data
await stopVmWorker()
if (args.nativePath) {
const vargs = ["-w", "8082"]
if (args.gcStress) vargs.push("-X")
if (args.deviceId) vargs.push("-d:" + args.deviceId)
if (args.clearFlash) vargs.push("-N")
if (args.stateless) vargs.push("-n")
console.debug("starting", args.nativePath, vargs.join(" "))
worker = spawn(args.nativePath, vargs, {
shell: false,
})
} else {
const vargs = ["vm", "--devtools"]
if (args.deviceId) vargs.push("--device-id", args.deviceId)
if (args.gcStress) vargs.push("--gc-stress")
if (args.stateless) vargs.push("--stateless")
if (args.clearFlash) vargs.push("--clear-flash")
console.debug("starting", __filename, vargs.join(" "))
worker = fork(__filename, vargs, { silent: true })
}
worker.stdin.end()
worker.stdout.setEncoding("utf-8")
worker.stderr.setEncoding("utf-8")
let auxOutput: string[] = []
const worker0 = worker
worker.on("exit", (code, signal) => {
const msg = `Exit code: ${code} ${signal ?? ""}`
sendLines(worker0.isSelfKill ? "vm" : "vm-err", [msg])
if (!worker0.isSelfKill) {
auxOutput.push(msg)
for (const m of auxOutput) console.log("VMERR> " + wrapColor(91, m))
}
})
function sendLines(kind: OutputFrom, lines: string[]) {
sendOutput(sender, kind, lines)
for (const l of lines) {
let printed = false
if (l.startsWith(" "))
printed = printDmesg(
devtoolsIface.lastOKBuild?.dbg,
"VM",
l.slice(4)
)
else if (kind == "vm-err") {
console.log("VMERR> " + wrapColor(91, l))
printed = true
}
if (!printed) {
auxOutput.push(l)
if (auxOutput.length > 100) auxOutput = auxOutput.slice(50)
}
}
}
function buffered(kind: OutputFrom) {
return lineBuffer(lines => sendLines(kind, lines))
}
worker.stdout.on("data", buffered("vm"))
worker.stderr.on("data", buffered("vm-err"))
return {}
}
export function initVMCmds() {
addReqHandler<SideStartVmReq, SideStartVmResp>("startVM", startVmWorker)
addReqHandler<SideStopVmReq, SideStopVmResp>("stopVM", stopVmWorker)
}