diff --git a/bios/seabios.bin b/bios/seabios.bin index 5c17cbd..8c9ab8f 100644 Binary files a/bios/seabios.bin and b/bios/seabios.bin differ diff --git a/bios/vgabios.bin b/bios/vgabios.bin index e1b6db4..bd393e2 100644 Binary files a/bios/vgabios.bin and b/bios/vgabios.bin differ diff --git a/src/constants.ts b/src/constants.ts index 877d7c8..d327a44 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -30,4 +30,7 @@ export const IPC_COMMANDS = { // Else APP_QUIT: "APP_QUIT", GET_STATE_PATH: "GET_STATE_PATH", + GET_SMB_SHARE_PATH: "GET_SMB_SHARE_PATH", + SET_SMB_SHARE_PATH: "SET_SMB_SHARE_PATH", + PICK_FOLDER: "PICK_FOLDER", }; diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 6c6fc58..e61e3c0 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -1,7 +1,9 @@ -import { ipcMain, app } from "electron"; +import { ipcMain, app, dialog, BrowserWindow } from "electron"; import * as path from "path"; +import * as fs from "fs"; import { IPC_COMMANDS } from "../constants"; +import { settings } from "./settings"; export function setupIpcListeners() { ipcMain.handle(IPC_COMMANDS.GET_STATE_PATH, () => { @@ -11,4 +13,34 @@ export function setupIpcListeners() { ipcMain.handle(IPC_COMMANDS.APP_QUIT, () => { app.quit(); }); + + ipcMain.handle(IPC_COMMANDS.GET_SMB_SHARE_PATH, () => { + return settings.get("smbSharePath"); + }); + + ipcMain.handle(IPC_COMMANDS.SET_SMB_SHARE_PATH, (_e, p: unknown) => { + // The only legitimate caller is the folder picker, which can't return + // a non-existent path — but the renderer has nodeIntegration so any + // code there can call this IPC. Reject anything that isn't an existing + // directory; otherwise SmbSession's realpathSync throws inside a TCP + // callback on next launch and the share silently never connects. + if (typeof p !== "string") return false; + let real: string; + try { + real = fs.realpathSync(p); + if (!fs.statSync(real).isDirectory()) return false; + } catch { + return false; + } + settings.set("smbSharePath", real); + return true; + }); + + ipcMain.handle(IPC_COMMANDS.PICK_FOLDER, async (e) => { + const win = BrowserWindow.fromWebContents(e.sender); + const result = await dialog.showOpenDialog(win!, { + properties: ["openDirectory"], + }); + return result.canceled ? null : result.filePaths[0]; + }); } diff --git a/src/main/settings.ts b/src/main/settings.ts index f843a0b..e35ce25 100644 --- a/src/main/settings.ts +++ b/src/main/settings.ts @@ -6,12 +6,14 @@ export interface Settings { isFileServerEnabled: boolean; isFileServerShowingHiddenFiles: boolean; isFileServerShowingSystemHiddenFiles: boolean; + smbSharePath: string; } const DEFAULT_SETTINGS: Settings = { isFileServerEnabled: true, isFileServerShowingHiddenFiles: false, isFileServerShowingSystemHiddenFiles: false, + smbSharePath: app.getPath("downloads"), }; class SettingsManager { @@ -53,7 +55,7 @@ class SettingsManager { return this.data[key]; } - set(key: keyof Settings, value: any): void { + set(key: K, value: Settings[K]): void { this.data[key] = value; this.save(); } diff --git a/src/renderer/card-settings.tsx b/src/renderer/card-settings.tsx index 9083c06..2a16c47 100644 --- a/src/renderer/card-settings.tsx +++ b/src/renderer/card-settings.tsx @@ -6,8 +6,11 @@ interface CardSettingsProps { bootFromScratch: () => void; setFloppy: (file: File) => void; setCdrom: (cdrom: File) => void; + setSmbSharePath: (path: string) => void; + pickFolder: () => Promise; floppy?: File; cdrom?: File; + smbSharePath: string; } interface CardSettingsState { @@ -45,6 +48,8 @@ export class CardSettings extends React.Component<
{this.renderFloppy()}
+ {this.renderSmbShare()} +
{this.renderState()} @@ -90,6 +95,34 @@ export class CardSettings extends React.Component< ); } + public renderSmbShare() { + const { smbSharePath } = this.props; + + return ( +
+ Network Share +

+ A folder on your computer is exposed inside Windows 95 as a + network drive. From inside Windows, open Start → Run and type{" "} + \\HOST\HOST to browse it, or use Map Network Drive to + give it a drive letter. +

+

+ Shared folder: {smbSharePath} +

+ +
+ ); + } + public renderFloppy() { const { floppy } = this.props; diff --git a/src/renderer/debug-harness.ts b/src/renderer/debug-harness.ts new file mode 100644 index 0000000..e224494 --- /dev/null +++ b/src/renderer/debug-harness.ts @@ -0,0 +1,265 @@ +// Autonomous boot probe. Started from emulator.tsx when WIN95_PROBE=1. +// Writes status + screenshot to /tmp so an outer loop can read them +// without DevTools or CDP. + +import * as fs from "fs"; + +const STATUS_FILE = "/tmp/win95-probe.json"; +const SCREEN_FILE = "/tmp/win95-screen.png"; +const TICK_MS = 5000; + +interface ProbeStatus { + ts: string; + uptimeSec: number; + phase: "init" | "running" | "text-mode" | "splash" | "desktop" | "done"; + cpuRunning: boolean; + instructionCounter: number; + instructionDelta: number; + textScreen: string; + textHash: string; + gfxW: number; + gfxH: number; + dominantColor: string; + verdict: "" | "SUCCESS" | "FAIL_IOS" | "FAIL_KRNL386" | "FAIL_VXDLINK" | "FAIL_PROTECTION" | "FAIL_SPLASH_HANG" | "FAIL_HUNG" | "FAIL_OTHER"; +} + +let startTime = 0; +let lastInstr = 0; +let lastTextHash = ""; +let stableTextTicks = 0; + +// XT scancodes (set 1). Win95 doesn't have Win+R — that landed in Win98. +// Ctrl+Esc opens Start, then R is the underlined mnemonic for "Run...". +const SC = { + CTRL_DN: [0x1d], CTRL_UP: [0x9d], + ESC_DN: [0x01], ESC_UP: [0x81], + R_DN: [0x13], R_UP: [0x93], + ENTER_DN: [0x1c], ENTER_UP: [0x9c], + BACKSLASH_DN: [0x2b], BACKSLASH_UP: [0xab], +}; + +function sendChord(emu: any, ...keys: { dn: number[]; up: number[] }[]) { + for (const k of keys) emu.keyboard_send_scancodes(k.dn); + setTimeout(() => { + for (let i = keys.length - 1; i >= 0; i--) emu.keyboard_send_scancodes(keys[i].up); + }, 60); +} + +function sendKey(emu: any, dn: number[], up: number[]) { + emu.keyboard_send_scancodes(dn); + setTimeout(() => emu.keyboard_send_scancodes(up), 50); +} + +/** Replay a list of actions: {type:"keys",dn,up} | {type:"text",text} | {type:"wait",ms} */ +function runScript(emu: any, steps: any[]) { + let i = 0; + const next = () => { + if (i >= steps.length) { console.log("[probe] script done"); return; } + const s = steps[i++]; + if (s.type === "wait") { setTimeout(next, s.ms); return; } + if (s.type === "keys") { sendKey(emu, s.dn, s.up); setTimeout(next, 200); return; } + if (s.type === "chord") { sendChord(emu, ...s.keys); setTimeout(next, 200); return; } + if (s.type === "text") { + // keyboard_send_text handles ASCII → scancode for us + emu.keyboard_send_text(s.text); + setTimeout(next, 100 + s.text.length * 30); + return; + } + next(); + }; + next(); +} + +export function startProbe(emulator: any) { + startTime = Date.now(); + console.log("[probe] writing to", STATUS_FILE); + + // WIN95_PROBE_SCRIPT=\\HOST → after desktop, send Win+R, type, Enter + const scriptCmd = process.env.WIN95_PROBE_SCRIPT; + let scriptArmed = !!scriptCmd; + + const tick = () => { + try { + const s = collectStatus(emulator); + fs.writeFileSync(STATUS_FILE, JSON.stringify(s, null, 2)); + + // Try to capture a screenshot — this can fail if the screen adapter + // isn't ready yet, so we swallow that. + try { + const img: HTMLImageElement = emulator.screen_make_screenshot(); + // The Image has a data: URL src; decode it to bytes + if (img && img.src && img.src.startsWith("data:image/png;base64,")) { + const b64 = img.src.slice("data:image/png;base64,".length); + fs.writeFileSync(SCREEN_FILE, Buffer.from(b64, "base64")); + } + } catch {} + + // Once at desktop, fire the keyboard script (once). The 8s settle is + // for the "Welcome to Windows 95" tip dialog to be dismissable — + // we send Esc first to clear it. + if (scriptArmed && s.phase === "desktop" && s.uptimeSec > 8) { + scriptArmed = false; + console.log("[probe] desktop detected, running script:", scriptCmd); + runScript(emulator, [ + { type: "wait", ms: 3000 }, + { type: "keys", dn: SC.ESC_DN, up: SC.ESC_UP }, // dismiss any dialog + { type: "wait", ms: 1000 }, + { type: "keys", dn: SC.ESC_DN, up: SC.ESC_UP }, // again, for safety + { type: "wait", ms: 1000 }, + { type: "chord", keys: [ + { dn: SC.CTRL_DN, up: SC.CTRL_UP }, + { dn: SC.ESC_DN, up: SC.ESC_UP }, + ]}, // Ctrl+Esc → Start + { type: "wait", ms: 1200 }, + { type: "keys", dn: SC.R_DN, up: SC.R_UP }, // Run mnemonic + { type: "wait", ms: 1000 }, + // keyboard_send_text can't reliably do backslash, so we interleave: + // scancode for each \ segment, text for each name segment. + // WIN95_PROBE_SCRIPT='HOST/HOST' → types \\HOST\HOST (we use / as + // the segment separator in the env var to dodge shell escaping hell) + ...scriptCmd!.split("/").flatMap((seg, i) => [ + ...(i === 0 + ? [{ type: "keys", dn: SC.BACKSLASH_DN, up: SC.BACKSLASH_UP }, + { type: "wait", ms: 60 }, + { type: "keys", dn: SC.BACKSLASH_DN, up: SC.BACKSLASH_UP }] + : [{ type: "keys", dn: SC.BACKSLASH_DN, up: SC.BACKSLASH_UP }]), + { type: "wait", ms: 60 }, + { type: "text", text: seg }, + { type: "wait", ms: 100 }, + ]), + { type: "wait", ms: 400 }, + { type: "keys", dn: SC.ENTER_DN, up: SC.ENTER_UP }, + ]); + } + + if (s.verdict) { + console.log("[probe] VERDICT:", s.verdict); + fs.writeFileSync(STATUS_FILE.replace(".json", ".done"), s.verdict); + } + } catch (e) { + console.log("[probe] tick error:", e); + } + }; + + tick(); + setInterval(tick, TICK_MS); +} + +function collectStatus(emulator: any): ProbeStatus { + const uptimeSec = (Date.now() - startTime) / 1000; + + // CPU activity — instruction counter is u32 in wasm, wraps every ~4B + let instr = 0, running = false; + try { instr = emulator.get_instruction_counter() || 0; } catch {} + try { running = emulator.is_running(); } catch {} + const instrDelta = (instr - lastInstr) >>> 0; + lastInstr = instr; + + // Text screen — only meaningful in text mode (BIOS, DOS, BSOD). + // In graphics mode this returns garbage or empty. + let textScreen = ""; + try { + const screen = emulator.screen_adapter || emulator.v86?.screen_adapter; + if (screen) { + const rows = screen.get_text_screen?.() || []; + textScreen = rows.map((r: string) => r.trimEnd()).join("\n").trim(); + } + } catch {} + + // VGA state tells us everything: in graphics or text, and at what resolution. + // Win95 splash: 320×400. Win95 desktop: ≥640×480. + // Old v86 builds (pre-2025) don't expose screen_width/screen_height — fall + // back to the rendered canvas dimensions so the bisect harness works across + // versions. + let inGraphics = false, gfxW = 0, gfxH = 0; + try { + const vga = emulator.v86?.cpu?.devices?.vga; + if (vga) { + inGraphics = !!vga.graphical_mode; + gfxW = vga.screen_width || 0; + gfxH = vga.screen_height || 0; + } + } catch {} + if (gfxW === 0) { + try { + const canvas = document.querySelector("#emulator canvas") as HTMLCanvasElement | null; + if (canvas && canvas.width > 0) { + gfxW = canvas.width; + gfxH = canvas.height; + // Canvas exists with content → assume graphics. Text mode uses a div. + const textDiv = document.querySelector("#emulator div") as HTMLElement | null; + inGraphics = canvas.style.display !== "none" && + (!textDiv || textDiv.style.display === "none"); + } + } catch {} + } + + // Sample the framebuffer to identify which screen we're on. + // Splash is sky-blue gradient (R~120 G~175 B~215). Desktop is teal (0,128,128). + let dominantColor = ""; + if (inGraphics) { + try { + const canvas = document.querySelector("#emulator canvas") as HTMLCanvasElement | null; + if (canvas) { + const ctx = canvas.getContext("2d")!; + const cx = Math.floor(canvas.width / 2); + const cy = Math.floor(canvas.height / 3); // upper-third → sky on splash, taskbar-free on desktop + const px = ctx.getImageData(cx, cy, 1, 1).data; + dominantColor = `${px[0]},${px[1]},${px[2]}`; + } + } catch {} + } + + const textHash = hashStr(textScreen); + if (!inGraphics && textHash === lastTextHash && textScreen) stableTextTicks++; + else stableTextTicks = 0; + lastTextHash = textHash; + + const hasMeaningfulText = !inGraphics && textScreen.length > 20 && /[A-Za-z]{4,}/.test(textScreen); + const atSplash = inGraphics && gfxW > 0 && gfxW < 640; + const atDesktop = inGraphics && gfxW >= 640; + + const phase: ProbeStatus["phase"] = + !running ? "init" : + atDesktop ? "desktop" : + atSplash ? "splash" : + hasMeaningfulText ? "text-mode" : + "running"; + + let verdict: ProbeStatus["verdict"] = ""; + const t = inGraphics ? "" : textScreen.toLowerCase(); + + if (t.includes("krnl386")) verdict = "FAIL_KRNL386"; + else if (t.includes("vxd dynamic link")) verdict = "FAIL_VXDLINK"; + else if (t.includes("initializing device ios") && t.includes("protection error")) verdict = "FAIL_IOS"; + else if (t.includes("windows protection error")) verdict = "FAIL_PROTECTION"; + // Stuck at splash for >70s with CPU spinning → IDE IRQ never fired + else if (atSplash && uptimeSec > 70) verdict = "FAIL_SPLASH_HANG"; + // Stuck on text for 40s + else if (stableTextTicks >= 8 && instrDelta > 1_000_000) verdict = "FAIL_HUNG"; + // CPU dead + else if (running && instrDelta < 1000 && uptimeSec > 30) verdict = "FAIL_HUNG"; + // Made it to ≥640×480 graphics → desktop reached. But if a keyboard + // script is running, hold off — the outer harness reads the SMB log + // directly and we just keep the app alive. + else if (atDesktop && uptimeSec > 30 && !process.env.WIN95_PROBE_SCRIPT) verdict = "SUCCESS"; + // Timeout + else if (uptimeSec > 180) verdict = "FAIL_OTHER"; + + return { + ts: new Date().toISOString(), + uptimeSec: Math.round(uptimeSec), + phase, cpuRunning: running, + instructionCounter: instr, + instructionDelta: instrDelta, + textScreen: textScreen.slice(0, 2000), + textHash, gfxW, gfxH, dominantColor, + verdict, + }; +} + +function hashStr(s: string): string { + let h = 5381; + for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0; + return (h >>> 0).toString(16); +} diff --git a/src/renderer/emulator.tsx b/src/renderer/emulator.tsx index 7765880..13fde46 100644 --- a/src/renderer/emulator.tsx +++ b/src/renderer/emulator.tsx @@ -12,6 +12,14 @@ import { EmulatorInfo } from "./emulator-info"; import { getStatePath } from "./utils/get-state-path"; import { Win95Window } from "./app"; import { resetState } from "./utils/reset-state"; +import { setupSmbShare } from "./smb"; +import { startProbe } from "./debug-harness"; + +const PROBE = process.env.WIN95_PROBE === "1"; +const PROBE_OPTS: Record = (() => { + try { return JSON.parse(process.env.WIN95_PROBE_OPTS || "{}"); } + catch { return {}; } +})(); declare let window: Win95Window; @@ -21,6 +29,7 @@ export interface EmulatorState { scale: number; floppyFile?: File; cdromFile?: File; + smbSharePath: string; isBootingFresh: boolean; isCursorCaptured: boolean; isInfoDisplayed: boolean; @@ -41,11 +50,12 @@ export class Emulator extends React.Component<{}, EmulatorState> { this.bootFromScratch = this.bootFromScratch.bind(this); this.state = { - isBootingFresh: false, + isBootingFresh: PROBE, isCursorCaptured: false, isRunning: false, currentUiCard: "start", isInfoDisplayed: true, + smbSharePath: "", // We can start pretty large // If it's too large, it'll just grow until it hits borders scale: 2, @@ -54,6 +64,16 @@ export class Emulator extends React.Component<{}, EmulatorState> { this.setupInputListeners(); this.setupIpcListeners(); this.setupUnloadListeners(); + + ipcRenderer.invoke(IPC_COMMANDS.GET_SMB_SHARE_PATH).then((p: string) => { + this.setState({ smbSharePath: p }); + }); + + if (PROBE) { + // Skip the start card; boot fresh immediately. The 100ms delay + // lets React mount the #emulator div first. + setTimeout(() => this.bootFromScratch(), 100); + } } /** @@ -194,9 +214,15 @@ export class Emulator extends React.Component<{}, EmulatorState> { this.setState({ floppyFile })} setCdrom={(cdromFile) => this.setState({ cdromFile })} + setSmbSharePath={(smbSharePath) => { + this.setState({ smbSharePath }); + ipcRenderer.invoke(IPC_COMMANDS.SET_SMB_SHARE_PATH, smbSharePath); + }} + pickFolder={() => ipcRenderer.invoke(IPC_COMMANDS.PICK_FOLDER)} bootFromScratch={this.bootFromScratch} floppy={floppyFile} cdrom={cdromFile} + smbSharePath={this.state.smbSharePath} /> ); } else { @@ -316,10 +342,26 @@ export class Emulator extends React.Component<{}, EmulatorState> { boot_order: 0x132, }; + // PROBE_OPTS lets the outer harness override options without rebuilding + // (e.g. WIN95_PROBE_OPTS='{"acpi":false,"disable_jit":true}') + Object.assign(options, PROBE_OPTS); + console.log(`🚜 Starting emulator with options`, options); window["emulator"] = new V86(options); + // Serve a host folder over SMB on port 139. Read-only, traversal/symlink + // guarded. In Win95: Start → Run → \\HOST\HOST. The env var wins so the + // probe harness can point at a fixture dir without touching settings. + const smbRoot = process.env.WIN95_SMB_SHARE || this.state.smbSharePath; + if (smbRoot) { + setupSmbShare(window["emulator"], smbRoot); + } + + if (PROBE) { + startProbe(window["emulator"]); + } + // New v86 instance this.setState({ emulator: window["emulator"], diff --git a/src/renderer/lib/build/v86.wasm b/src/renderer/lib/build/v86.wasm index fa976b0..b2b740e 100755 Binary files a/src/renderer/lib/build/v86.wasm and b/src/renderer/lib/build/v86.wasm differ diff --git a/src/renderer/lib/libv86.js b/src/renderer/lib/libv86.js index 486038d..209ff2a 100644 --- a/src/renderer/lib/libv86.js +++ b/src/renderer/lib/libv86.js @@ -1,45 +1,169 @@ -;(function(){'use strict';function aa(a,b){return(a||0===a?a+"":"").padEnd(b," ")}function k(a,b,c,d){return new Proxy({},{get:function(e,f){e=new a(b.buffer,c,d);const g=e[f];if("function"===typeof g)return g.bind(e);/^\d+$/.test(f);return g},set:function(e,f,g){/^\d+$/.test(f);(new a(b.buffer,c,d))[f]=g;return!0}})}function y(a,b){a=(a?a.toString(16):"").toUpperCase();return"0x"+(a||0===a?a+"":"").padStart(b||1,"0")}var ba; -if("undefined"!==typeof crypto&&crypto.getRandomValues){const a=new Int32Array(1);ba=function(){crypto.getRandomValues(a);return a[0]}}else if("undefined"!==typeof require){const a=require("crypto");ba=function(){return a.randomBytes(4).readInt32LE(0)}}else"undefined"!==typeof process&&import("node:crypto").then(a=>{ba=function(){return a.randomBytes(4).readInt32LE(0)}});var ca; -if("function"===typeof Math.clz32)ca=function(a){return 31-Math.clz32(a)};else{for(var da=new Int8Array(256),ea=0,ha=-2;256>ea;ea++)ea&ea-1||ha++,da[ea]=ha;ca=function(a){a>>>=0;var b=a>>>16;if(b){var c=b>>>8;return c?24+da[c]:16+da[b]}return(c=a>>>8)?8+da[c]:da[a]}}function ia(a){return 1>=a?1:1<<1+ca(a-1)} -function ka(a){var b=new Uint8Array(a),c,d;this.length=0;this.push=function(e){this.length!==a&&this.length++;b[d]=e;d=d+1&a-1};this.shift=function(){if(this.length){var e=b[c];c=c+1&a-1;this.length--;return e}return-1};this.peek=function(){return this.length?b[c]:-1};this.clear=function(){this.length=d=c=0};this.clear()}function la(a){this.size=a;this.data=new Float32Array(a);this.length=this.end=this.start=0} -la.prototype.push=function(a){this.length===this.size?this.start=this.start+1&this.size-1:this.length++;this.data[this.end]=a;this.end=this.end+1&this.size-1};la.prototype.shift=function(){if(this.length){var a=this.data[this.start];this.start=this.start+1&this.size-1;this.length--;return a}}; -la.prototype.shift_block=function(a){var b=new Float32Array(a);a>this.length&&(a=this.length);var c=this.start+a,d=this.data.subarray(this.start,c);b.set(d);c>=this.size&&(c-=this.size,b.set(this.data.subarray(0,c),d.length));this.start=c;this.length-=a;return b};la.prototype.peek=function(){if(this.length)return this.data[this.start]};la.prototype.clear=function(){this.length=this.end=this.start=0}; -function ma(a){"number"===typeof a?this.view=new Uint8Array(a+7>>3):a instanceof ArrayBuffer&&(this.view=new Uint8Array(a))}ma.prototype.set=function(a,b){const c=a>>3;a=1<<(a&7);this.view[c]=b?this.view[c]|a:this.view[c]&~a};ma.prototype.get=function(a){return this.view[a>>3]>>(a&7)&1};ma.prototype.get_buffer=function(){return this.view.buffer};var oa,pa; -if("undefined"===typeof XMLHttpRequest||"undefined"!==typeof process&&process.versions&&process.versions.node){let a;oa=async function(b,c){a||(a=await import("node:fs/promises"));if(c.range){b=await a.open(b,"r");const d=Buffer.allocUnsafe(c.range.length);try{await b.read({buffer:d,position:c.range.start})}finally{await b.close()}c.done&&c.done(new Uint8Array(d))}else b=await a.readFile(b,{encoding:c.as_json?"utf-8":null}),b=c.as_json?JSON.parse(b):(new Uint8Array(b)).buffer,c.done(b)};pa=async function(b){a|| -(a=await import("node:fs/promises"));return(await a.stat(b)).size}}else oa=async function(a,b,c){function d(){const l=c||0;setTimeout(()=>{oa(a,b,l+1)},1E3*([1,1,2,3,5,8,13,21][l]||34))}var e=new XMLHttpRequest;e.open(b.method||"get",a,!0);e.responseType=b.as_json?"json":"arraybuffer";if(b.headers)for(var f=Object.keys(b.headers),g=0;ge.status&&d();else if(e.response){if(b.range){const l=e.getResponseHeader("Content-Encoding");l&&"identity"!==l&&console.error("Server sent Content-Encoding in response to ranged request", -{filename:a,enc:l})}b.done&&b.done(e.response,e)}};e.onerror=function(l){console.error("Loading the image "+a+" failed",l);d()};b.progress&&(e.onprogress=function(l){b.progress(l)});e.send(null)},pa=async function(a){return new Promise((b,c)=>{oa(a,{done:(d,e)=>{d=e.getResponseHeader("Content-Range")||"";(e=d.match(/\/(\d+)\s*$/))?b(+e[1]):c(Error("`Range: bytes=...` header not supported (Got `"+d+"`)"))},headers:{Range:"bytes=0-0","X-Accept-Encoding":"identity"}})})}; -function qa(a,b,c){return String.fromCharCode(...(new Uint8Array(a.buffer,b>>>0,c>>>0)))} -const ra={cp437:" \u263a\u263b\u2665\u2666\u2663\u2660\u2022\u25d8\u25cb\u25d9\u2642\u2640\u266a\u266b\u263c\u25ba\u25c4\u2195\u203c\u00b6\u00a7\u25ac\u21a8\u2191\u2193\u2192\u2190\u221f\u2194\u25b2\u25bc !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00a2\u00a3\u00a5\u20a7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u2310\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580\u03b1\u00df\u0393\u03c0\u03a3\u03c3\u00b5\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0 ",cp858:"\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00f8\u00a3\u00d8\u00d7\u0192\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u00ae\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb\u2591\u2592\u2593\u2502\u2524\u00c1\u00c2\u00c0\u00a9\u2563\u2551\u2557\u255d\u00a2\u00a5\u2510\u2514\u2534\u252c\u251c\u2500\u253c\u00e3\u00c3\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u00a4\u00f0\u00d0\u00ca\u00cb\u00c8\u20ac\u00cd\u00ce\u00cf\u2518\u250c\u2588\u2584\u00a6\u00cc\u2580\u00d3\u00df\u00d4\u00d2\u00f5\u00d5\u00b5\u00fe\u00de\u00da\u00db\u00d9\u00fd\u00dd\u00af\u00b4\u00ad\u00b1\u2017\u00be\u00b6\u00a7\u00f7\u00b8\u00b0\u00a8\u00b7\u00b9\u00b3\u00b2\u25a0 "}; -ra.cp858=ra.cp437.slice(0,128)+ra.cp858;ra.ascii=ra.cp437.split("").map((a,b)=>31b?a:".").join("");function sa(a){return a&&ra[a]?ra[a]:ra.cp437};function ua(){}function va(){};function wa(a,b){function c(w){w=w.toString(16);return"#"+"0".repeat(6-w.length)+w}function d(w){var u=256*na,H=8*R,K=Ta?Ta.canvas:null;K&&K.width===u&&K.height===H||(K?(K.width=u,K.height=H):(K=new OffscreenCanvas(u,H),Ta=K.getContext("2d")),Kb=Ta.createImageData(u,H));const Q=Kb.data;let P=0,S;H=Lb?function(Z){S=S||Z;Q[P+3]=Z;Q[P+7]=Z;P+=8}:function(Z){S=S||Z;Q[P+3]=Z;P+=4};K=32-R;const ja=u*(R-1)*4;u=4*(na-u*R);const fa=1020*na;for(let Z=0,Ea=0;2048>Z;++Z,Ea+=K,P+=u){const Fa=Z%256;Z&&!Fa&&(P+= -ja);S=!1;for(let La=0;La>=1)H(Ma&ta?255:0);Mb&&H(Nb&&192<=Fa&&223>=Fa&&Ma&1?255:0)}fc[Z]=S?1:0}Ta.putImageData(Kb,0,0)}function e(w,u,H,K){if(u&&H){w.style.width="";w.style.height="";K&&(w.style.transform="");var Q=w.getBoundingClientRect();K?w.style.transform=(1===u?"":" scaleX("+u+")")+(1===H?"":" scaleY("+H+")"):(0===u%1&&0===H%1?(g.style.imageRendering="crisp-edges",g.style.imageRendering="pixelated",g.style["-ms-interpolation-mode"]="nearest-neighbor"): -(g.style.imageRendering="",g.style["-ms-interpolation-mode"]=""),K=window.devicePixelRatio||1,0!==K%1&&(u/=K,H/=K));1!==u&&(w.style.width=Q.width*u+"px");1!==H&&(w.style.height=Q.height*H+"px")}}const f=a.container;this.screen_fill_buffer=b;console.assert(f,"options.container must be provided");this.FLAG_BLINKING=1;this.FLAG_FONT_PAGE_B=2;let g=f.getElementsByTagName("canvas")[0];g||(g=document.createElement("canvas"),f.appendChild(g));const h=g.getContext("2d",{alpha:!1});let l=f.getElementsByTagName("div")[0]; -l||(l=document.createElement("div"),f.appendChild(l));const m=document.createElement("div");var n,p,q=void 0!==a.scale?a.scale:1,r=void 0!==a.scale?a.scale:1,x=1,C,t,A,M,v,L,T,Ta,Kb,fc=new Int8Array(2048),R,na,Mb,Lb,Nb,Ob=0,Pb=0,sb,gc=0,tb,Qb,ub,Rb=sa(a.encoding),vb=0,Sb=!1;this.init=function(){m.classList.add("cursor");m.style.position="absolute";m.style.backgroundColor="#ccc";m.style.width="7px";m.style.display="inline-block";this.set_mode(!1);this.set_size_text(80,25);2===t&&this.set_size_graphical(720, -400,720,400);this.set_scale(q,r);this.timer()};this.make_screenshot=function(){const w=new Image;if(1===t||2===t)w.src=g.toDataURL("image/png");else{const u=[9,16],H=document.createElement("canvas");H.width=M*u[0];H.height=v*u[1];const K=H.getContext("2d");K.imageSmoothingEnabled=!1;K.font=window.getComputedStyle(l).font;K.textBaseline="top";for(let Q=0;Qthis.update_screen())};this.update_screen=function(){Sb||(0===t?this.update_text():1===t?this.update_graphical():this.update_graphical_text()); -this.timer()};this.update_text=function(){for(var w=0;wu;)l.removeChild(l.firstChild);for(;l.childNodes.length=w&&2*w>20)+" MB ...");this.buffer=new ArrayBuffer(a.size);this.onprogress=this.onload=void 0}za.prototype.load=function(){this.load_next(0)}; -za.prototype.load_next=function(a){var b=new FileReader;b.onload=function(d){d=new Uint8Array(d.target.result);(new Uint8Array(this.buffer,a)).set(d);this.load_next(a+4194304)}.bind(this);if(this.onprogress)this.onprogress({loaded:a,total:this.byteLength,lengthComputable:!0});if(aY;++Y,Aa+=J,P+=v){const Ba=Y%256;Y&&!Ba&&(P+= +ha);T=!1;for(let Ia=0;Ia>=1)F(Ja&sa?255:0);ub&&F(vb&&192<=Ba&&223>=Ba&&Ja&1?255:0)}Mb[Y]=T?1:0}Oa.putImageData(sb,0,0)}function e(y,v,F,J){if(v&&F){y.style.width="";y.style.height="";J&&(y.style.transform="");var Q=y.getBoundingClientRect();J?y.style.transform=(1===v?"":" scaleX("+v+")")+(1===F?"":" scaleY("+F+")"):(0===v%1&&0===F%1?(f.style.imageRendering="crisp-edges",f.style.imageRendering="pixelated",f.style["-ms-interpolation-mode"]="nearest-neighbor"): +(f.style.imageRendering="",f.style["-ms-interpolation-mode"]=""),J=window.devicePixelRatio||1,0!==J%1&&(v/=J,F/=J));1!==v&&(y.style.width=Q.width*v+"px");1!==F&&(y.style.height=Q.height*F+"px")}}const g=a.container;this.screen_fill_buffer=b;console.assert(g,"options.container must be provided");this.FLAG_BLINKING=1;this.FLAG_FONT_PAGE_B=2;var f=g.getElementsByTagName("canvas")[0],h=f.getContext("2d",{alpha:!1}),l=g.getElementsByTagName("div")[0],m=document.createElement("div"),n,p,q=void 0!==a.scale? +a.scale:1,r=void 0!==a.scale?a.scale:1,A=1,w,u,G,z,I,R,na,Oa,sb,Mb=new Int8Array(2048),S,ma,ub,tb,vb,wb=0,xb=0,eb,Nb=0,fb,yb,gb,zb=[],hb=zb,ib=0,Ab=!1;this.init=function(){const y=new Uint16Array([32,9786,9787,9829,9830,9827,9824,8226,9688,9675,9689,9794,9792,9834,9835,9788,9658,9668,8597,8252,182,167,9644,8616,8593,8595,8594,8592,8735,8596,9650,9660]),v=new Uint16Array([8962,199,252,233,226,228,224,229,231,234,235,232,239,238,236,196,197,201,230,198,244,246,242,251,249,255,214,220,162,163,165,8359, +402,225,237,243,250,241,209,170,186,191,8976,172,189,188,161,171,187,9617,9618,9619,9474,9508,9569,9570,9558,9557,9571,9553,9559,9565,9564,9563,9488,9492,9524,9516,9500,9472,9532,9566,9567,9562,9556,9577,9574,9568,9552,9580,9575,9576,9572,9573,9561,9560,9554,9555,9579,9578,9496,9484,9608,9604,9612,9616,9600,945,223,915,960,931,963,181,964,934,920,937,948,8734,966,949,8745,8801,177,8805,8804,8992,8993,247,8776,176,8729,183,8730,8319,178,9632,160]);for(var F=0,J;256>F;F++)J=126F?y[F]: +F,zb.push(String.fromCharCode(J));m.classList.add("cursor");m.style.position="absolute";m.style.backgroundColor="#ccc";m.style.width="7px";m.style.display="inline-block";this.set_mode(!1);this.set_size_text(80,25);2===u&&this.set_size_graphical(720,400,720,400);this.set_scale(q,r);this.timer()};this.make_screenshot=function(){const y=new Image;if(1===u||2===u)y.src=f.toDataURL("image/png");else{const v=[9,16],F=document.createElement("canvas");F.width=z*v[0];F.height=I*v[1];const J=F.getContext("2d"); +J.imageSmoothingEnabled=!1;J.font=window.getComputedStyle(l).font;J.textBaseline="top";for(let Q=0;Qthis.update_screen())};this.update_screen=function(){Ab||(0===u?this.update_text():1===u?this.update_graphical():this.update_graphical_text());this.timer()};this.update_text=function(){for(var y=0;yv;)l.removeChild(l.firstChild);for(;l.childNodes.length=y&&2*y{}},notification:{initial_port:43264, +single_handler:!1,handlers:[d=>{if(0===d){for(;this.virtqueue.has_request();)d=this.virtqueue.pop_request(),this.ReceiveRequest(d);this.virtqueue.notify_me_after(0)}}]},isr_status:{initial_port:42752},device_specific:{initial_port:42496,struct:[{bytes:2,name:"mount tag length",read:()=>this.configspace_taglen,write:()=>{}}].concat(k.range(254).map(d=>({bytes:1,name:"mount tag name "+d,read:()=>this.configspace_tagname[d]||0,write:()=>{}})))}});this.virtqueue=this.virtio.queues[0]} +ca.prototype.get_state=function(){var a=[];a[0]=this.configspace_tagname;a[1]=this.configspace_taglen;a[2]=this.virtio;a[3]=this.VERSION;a[4]=this.BLOCKSIZE;a[5]=this.msize;a[6]=this.replybuffer;a[7]=this.replybuffersize;a[8]=this.fids.map(function(b){return[b.inodeid,b.type,b.uid,b.dbg_name]});a[9]=this.fs;return a}; +ca.prototype.set_state=function(a){this.configspace_tagname=a[0];this.configspace_taglen=a[1];this.virtio.set_state(a[2]);this.virtqueue=this.virtio.queues[0];this.VERSION=a[3];this.BLOCKSIZE=a[4];this.msize=a[5];this.replybuffer=a[6];this.replybuffersize=a[7];this.fids=a[8].map(function(b){return{inodeid:b[0],type:b[1],uid:b[2],dbg_name:b[3]}});this.fs.set_state(a[9])};ca.prototype.Createfid=function(a,b,c,d){return{inodeid:a,type:b,uid:c,dbg_name:d}}; +ca.prototype.update_dbg_name=function(a,b){for(const c of this.fids)c.inodeid===a&&(c.dbg_name=b)};ca.prototype.reset=function(){this.fids=[];this.virtio.reset()};ca.prototype.BuildReply=function(a,b,c){t.Marshall(["w","b","h"],[c+7,a+1,b],this.replybuffer,0);c+7>=this.replybuffer.length&&x.Debug("Error in 9p: payloadsize exceeds maximum length");this.replybuffersize=c+7};ca.prototype.SendError=function(a,b,c){b=t.Marshall(["w"],[c],this.replybuffer,7);this.BuildReply(6,a,b)}; +ca.prototype.SendReply=function(a){a.set_next_blob(this.replybuffer.subarray(0,this.replybuffersize));this.virtqueue.push_reply(a);this.virtqueue.flush_replies()}; +ca.prototype.ReceiveRequest=async function(a){var b=new Uint8Array(a.length_readable);a.get_next_blob(b);var c={offset:0},d=t.Unmarshall(["w","b","h"],b,c),e=d[0],g=d[1],f=d[2];switch(g){case 8:e=this.fs.GetTotalSize();b=this.fs.GetSpace();d=[16914839];d[1]=this.BLOCKSIZE;d[2]=Math.floor(b/d[1]);d[3]=d[2]-Math.floor(e/d[1]);d[4]=d[2]-Math.floor(e/d[1]);d[5]=this.fs.CountUsedInodes();d[6]=this.fs.CountFreeInodes();d[7]=0;d[8]=256;e=t.Marshall("wwddddddw".split(""),d,this.replybuffer,7);this.BuildReply(g, +f,e);this.SendReply(a);break;case 112:case 12:d=t.Unmarshall(["w","w"],b,c);var h=d[0];c=d[1];x.Debug("[open] fid="+h+", mode="+c);b=this.fids[h].inodeid;var l=this.fs.GetInode(b);x.Debug("file open "+this.fids[h].dbg_name);e=this.fs.OpenInode(b,c);this.fs.AddEvent(this.fids[h].inodeid,function(){x.Debug("file opened "+this.fids[h].dbg_name+" tag:"+f);var q=[];q[0]=l.qid;q[1]=this.msize-24;t.Marshall(["Q","w"],q,this.replybuffer,7);this.BuildReply(g,f,17);this.SendReply(a)}.bind(this));break;case 70:d= +t.Unmarshall(["w","w","s"],b,c);b=d[0];h=d[1];e=d[2];x.Debug("[link] dfid="+b+", name="+e);e=this.fs.Link(this.fids[b].inodeid,this.fids[h].inodeid,e);if(0>e){this.SendError(f,-1===e?"Operation not permitted":"Unknown error: "+-e,-e);this.SendReply(a);break}this.BuildReply(g,f,0);this.SendReply(a);break;case 16:d=t.Unmarshall(["w","s","s","w"],b,c);h=d[0];e=d[1];b=d[2];d=d[3];x.Debug("[symlink] fid="+h+", name="+e+", symgt="+b+", gid="+d);b=this.fs.CreateSymlink(e,this.fids[h].inodeid,b);l=this.fs.GetInode(b); +l.uid=this.fids[h].uid;l.gid=d;t.Marshall(["Q"],[l.qid],this.replybuffer,7);this.BuildReply(g,f,13);this.SendReply(a);break;case 18:d=t.Unmarshall("wswwww".split(""),b,c);h=d[0];e=d[1];c=d[2];b=d[3];var m=d[4];d=d[5];x.Debug("[mknod] fid="+h+", name="+e+", major="+b+", minor="+m);b=this.fs.CreateNode(e,this.fids[h].inodeid,b,m);l=this.fs.GetInode(b);l.mode=c;l.uid=this.fids[h].uid;l.gid=d;t.Marshall(["Q"],[l.qid],this.replybuffer,7);this.BuildReply(g,f,13);this.SendReply(a);break;case 22:d=t.Unmarshall(["w"], +b,c);h=d[0];l=this.fs.GetInode(this.fids[h].inodeid);x.Debug("[readlink] fid="+h+" name="+this.fids[h].dbg_name+" target="+l.symlink);e=t.Marshall(["s"],[l.symlink],this.replybuffer,7);this.BuildReply(g,f,e);this.SendReply(a);break;case 72:d=t.Unmarshall(["w","s","w","w"],b,c);h=d[0];e=d[1];c=d[2];d=d[3];x.Debug("[mkdir] fid="+h+", name="+e+", mode="+c+", gid="+d);b=this.fs.CreateDirectory(e,this.fids[h].inodeid);l=this.fs.GetInode(b);l.mode=c|fa;l.uid=this.fids[h].uid;l.gid=d;t.Marshall(["Q"],[l.qid], +this.replybuffer,7);this.BuildReply(g,f,13);this.SendReply(a);break;case 14:d=t.Unmarshall(["w","s","w","w","w"],b,c);h=d[0];e=d[1];b=d[2];c=d[3];d=d[4];this.bus.send("9p-create",[e,this.fids[h].inodeid]);x.Debug("[create] fid="+h+", name="+e+", flags="+b+", mode="+c+", gid="+d);b=this.fs.CreateFile(e,this.fids[h].inodeid);this.fids[h].inodeid=b;this.fids[h].type=1;this.fids[h].dbg_name=e;l=this.fs.GetInode(b);l.uid=this.fids[h].uid;l.gid=d;l.mode=c|ia;t.Marshall(["Q","w"],[l.qid,this.msize-24],this.replybuffer, +7);this.BuildReply(g,f,17);this.SendReply(a);break;case 52:d=t.Unmarshall("wbwddws".split(""),b,c);h=d[0];b=d[2];e=0===d[4]?Infinity:d[4];d=this.fs.DescribeLock(d[1],d[3],e,d[5],d[6]);x.Debug("[lock] fid="+h+", type="+ba[d.type]+", start="+d.start+", length="+d.length+", proc_id="+d.proc_id);e=this.fs.Lock(this.fids[h].inodeid,d,b);t.Marshall(["b"],[e],this.replybuffer,7);this.BuildReply(g,f,1);this.SendReply(a);break;case 54:d=t.Unmarshall("wbddws".split(""),b,c);h=d[0];e=0===d[3]?Infinity:d[3]; +d=this.fs.DescribeLock(d[1],d[2],e,d[4],d[5]);x.Debug("[getlock] fid="+h+", type="+ba[d.type]+", start="+d.start+", length="+d.length+", proc_id="+d.proc_id);e=this.fs.GetLock(this.fids[h].inodeid,d);e||(e=d,e.type=2);e=t.Marshall(["b","d","d","w","s"],[e.type,e.start,Infinity===e.length?0:e.length,e.proc_id,e.client_id],this.replybuffer,7);this.BuildReply(g,f,e);this.SendReply(a);break;case 24:d=t.Unmarshall(["w","d"],b,c);h=d[0];l=this.fs.GetInode(this.fids[h].inodeid);x.Debug("[getattr]: fid="+ +h+" name="+this.fids[h].dbg_name+" request mask="+d[1]);if(!l||l.status===ja){x.Debug("getattr: unlinked");this.SendError(f,"No such file or directory",2);this.SendReply(a);break}d[0]=d[1];d[1]=l.qid;d[2]=l.mode;d[3]=l.uid;d[4]=l.gid;d[5]=l.nlinks;d[6]=l.major<<8|l.minor;d[7]=l.size;d[8]=this.BLOCKSIZE;d[9]=Math.floor(l.size/512+1);d[10]=l.atime;d[11]=0;d[12]=l.mtime;d[13]=0;d[14]=l.ctime;d[15]=0;d[16]=0;d[17]=0;d[18]=0;d[19]=0;t.Marshall("dQwwwddddddddddddddd".split(""),d,this.replybuffer,7);this.BuildReply(g, +f,153);this.SendReply(a);break;case 26:d=t.Unmarshall("wwwwwddddd".split(""),b,c);h=d[0];l=this.fs.GetInode(this.fids[h].inodeid);x.Debug("[setattr]: fid="+h+" request mask="+d[1]+" name="+this.fids[h].dbg_name);d[1]&1&&(l.mode=d[2]);d[1]&2&&(l.uid=d[3]);d[1]&4&&(l.gid=d[4]);d[1]&16&&(l.atime=Math.floor((new Date).getTime()/1E3));d[1]&32&&(l.mtime=Math.floor((new Date).getTime()/1E3));d[1]&64&&(l.ctime=Math.floor((new Date).getTime()/1E3));d[1]&128&&(l.atime=d[6]);d[1]&256&&(l.mtime=d[8]);d[1]&8&& +await this.fs.ChangeSize(this.fids[h].inodeid,d[5]);this.BuildReply(g,f,0);this.SendReply(a);break;case 50:d=t.Unmarshall(["w","d"],b,c);h=d[0];this.BuildReply(g,f,0);this.SendReply(a);break;case 40:case 116:d=t.Unmarshall(["w","d","w"],b,c);h=d[0];e=d[1];m=d[2];l=this.fs.GetInode(this.fids[h].inodeid);40===g&&x.Debug("[treaddir]: fid="+h+" offset="+e+" count="+m);116===g&&x.Debug("[read]: fid="+h+" ("+this.fids[h].dbg_name+") offset="+e+" count="+m+" fidtype="+this.fids[h].type);if(!l||l.status=== +ja){x.Debug("read/treaddir: unlinked");this.SendError(f,"No such file or directory",2);this.SendReply(a);break}if(2===this.fids[h].type)for(l.caps.lengthl.size&&(m=0),this.bus.send("9p-read-start",[this.fids[h].dbg_name]),d=await this.fs.Read(d, +e,m),this.bus.send("9p-read-end",[this.fids[h].dbg_name,m]),d&&this.replybuffer.set(d,11);t.Marshall(["w"],[m],this.replybuffer,7);this.BuildReply(g,f,4+m);this.SendReply(a);break;case 118:d=t.Unmarshall(["w","d","w"],b,c);h=d[0];e=d[1];m=d[2];d=this.fids[h].dbg_name;x.Debug("[write]: fid="+h+" ("+d+") offset="+e+" count="+m+" fidtype="+this.fids[h].type);if(2===this.fids[h].type){this.SendError(f,"Setxattr not supported",95);this.SendReply(a);break}else await this.fs.Write(this.fids[h].inodeid,e, +m,b.subarray(c.offset));this.bus.send("9p-write-end",[d,m]);t.Marshall(["w"],[m],this.replybuffer,7);this.BuildReply(g,f,4);this.SendReply(a);break;case 74:d=t.Unmarshall(["w","s","w","s"],b,c);e=d[0];b=d[1];c=d[2];d=d[3];x.Debug("[renameat]: oldname="+b+" newname="+d);e=await this.fs.Rename(this.fids[e].inodeid,b,this.fids[c].inodeid,d);if(0>e){this.SendError(f,-2===e?"No such file or directory":-1===e?"Operation not permitted":-39===e?"Directory not empty":"Unknown error: "+-e,-e);this.SendReply(a); +break}this.BuildReply(g,f,0);this.SendReply(a);break;case 76:d=t.Unmarshall(["w","s","w"],b,c);c=d[0];e=d[1];b=d[2];x.Debug("[unlink]: dirfd="+c+" name="+e+" flags="+b);h=this.fs.Search(this.fids[c].inodeid,e);if(-1===h){this.SendError(f,"No such file or directory",2);this.SendReply(a);break}e=this.fs.Unlink(this.fids[c].inodeid,e);if(0>e){this.SendError(f,-39===e?"Directory not empty":-1===e?"Operation not permitted":"Unknown error: "+-e,-e);this.SendReply(a);break}this.BuildReply(g,f,0);this.SendReply(a); +break;case 100:d=t.Unmarshall(["w","s"],b,c);x.Debug("[version]: msize="+d[0]+" version="+d[1]);this.msize!==d[0]&&(this.msize=d[0],this.replybuffer=new Uint8Array(Math.min(16777216,2*this.msize)));e=t.Marshall(["w","s"],[this.msize,this.VERSION],this.replybuffer,7);this.BuildReply(g,f,e);this.SendReply(a);break;case 104:d=t.Unmarshall(["w","w","s","s","w"],b,c);h=d[0];e=d[4];x.Debug("[attach]: fid="+h+" afid="+B(d[1])+" uname="+d[2]+" aname="+d[3]);this.fids[h]=this.Createfid(0,1,e,"");l=this.fs.GetInode(this.fids[h].inodeid); +t.Marshall(["Q"],[l.qid],this.replybuffer,7);this.BuildReply(g,f,13);this.SendReply(a);this.bus.send("9p-attach");break;case 108:d=t.Unmarshall(["h"],b,c);x.Debug("[flush] "+f);this.BuildReply(g,f,0);this.SendReply(a);break;case 110:d=t.Unmarshall(["w","w","h"],b,c);h=d[0];m=d[1];var n=d[2];x.Debug("[walk]: fid="+d[0]+" nwfid="+d[1]+" nwname="+n);if(0===n){this.fids[m]=this.Createfid(this.fids[h].inodeid,1,this.fids[h].uid,this.fids[h].dbg_name);t.Marshall(["h"],[0],this.replybuffer,7);this.BuildReply(g, +f,2);this.SendReply(a);break}e=[];for(d=0;db;b++)this.ports[b]=this.create_empty_entry();var c=a.memory_size[0];for(b=0;b<<17>>0,8);return 255},function(d,e){B(d>>>0,8);B(e,2)},function(d){B(d>>>0,8);return-1},function(d,e){B(d>>>0,8);B(e>>>0,8)})} +C.prototype.create_empty_entry=function(){return{read8:this.empty_port_read8,read16:this.empty_port_read16,read32:this.empty_port_read32,write8:this.empty_port_write,write16:this.empty_port_write,write32:this.empty_port_write,device:void 0}};C.prototype.empty_port_read8=function(){return 255};C.prototype.empty_port_read16=function(){return 65535};C.prototype.empty_port_read32=function(){return-1};C.prototype.empty_port_write=function(){}; +C.prototype.register_read=function(a,b,c,d,e){c&&(this.ports[a].read8=c);d&&(this.ports[a].read16=d);e&&(this.ports[a].read32=e);this.ports[a].device=b};C.prototype.register_write=function(a,b,c,d,e){c&&(this.ports[a].write8=c);d&&(this.ports[a].write16=d);e&&(this.ports[a].write32=e);this.ports[a].device=b}; +C.prototype.register_read_consecutive=function(a,b,c,d,e,g){function f(){return c.call(this)|d.call(this)<<8}function h(){return e.call(this)|g.call(this)<<8}function l(){return c.call(this)|d.call(this)<<8|e.call(this)<<16|g.call(this)<<24}e&&g?(this.register_read(a,b,c,f,l),this.register_read(a+1,b,d),this.register_read(a+2,b,e,h),this.register_read(a+3,b,g)):(this.register_read(a,b,c,f),this.register_read(a+1,b,d))}; +C.prototype.register_write_consecutive=function(a,b,c,d,e,g){function f(m){c.call(this,m&255);d.call(this,m>>8&255)}function h(m){e.call(this,m&255);g.call(this,m>>8&255)}function l(m){c.call(this,m&255);d.call(this,m>>8&255);e.call(this,m>>16&255);g.call(this,m>>>24)}e&&g?(this.register_write(a,b,c,f,l),this.register_write(a+1,b,d),this.register_write(a+2,b,e,h),this.register_write(a+3,b,g)):(this.register_write(a,b,c,f),this.register_write(a+1,b,d))}; +C.prototype.mmap_read32_shim=function(a){var b=this.cpu.memory_map_read8[a>>>17];return b(a)|b(a+1)<<8|b(a+2)<<16|b(a+3)<<24};C.prototype.mmap_write32_shim=function(a,b){var c=this.cpu.memory_map_write8[a>>>17];c(a,b&255);c(a+1,b>>8&255);c(a+2,b>>16&255);c(a+3,b>>>24)}; +C.prototype.mmap_register=function(a,b,c,d,e,g){B(a>>>0,8);B(b,8);e||(e=this.mmap_read32_shim.bind(this));g||(g=this.mmap_write32_shim.bind(this));for(a>>>=17;0>>0,8),this.get_port_description(a));return c.write32.call(c.device,b)}; +C.prototype.port_read8=function(a){var b=this.ports[a];b.read8===this.empty_port_read8&&(B(a,4),this.get_port_description(a));b=b.read8.call(b.device);B(a);return b};C.prototype.port_read16=function(a){var b=this.ports[a];b.read16===this.empty_port_read16&&(B(a,4),this.get_port_description(a));b=b.read16.call(b.device);B(a);return b};C.prototype.port_read32=function(a){var b=this.ports[a];b.read32===this.empty_port_read32&&(B(a,4),this.get_port_description(a));return b.read32.call(b.device)}; +var ka={4:"PORT_DMA_ADDR_2",5:"PORT_DMA_CNT_2",10:"PORT_DMA1_MASK_REG",11:"PORT_DMA1_MODE_REG",12:"PORT_DMA1_CLEAR_FF_REG",13:"PORT_DMA1_MASTER_CLEAR",32:"PORT_PIC1_CMD",33:"PORT_PIC1_DATA",64:"PORT_PIT_COUNTER0",65:"PORT_PIT_COUNTER1",66:"PORT_PIT_COUNTER2",67:"PORT_PIT_MODE",96:"PORT_PS2_DATA",97:"PORT_PS2_CTRLB",100:"PORT_PS2_STATUS",112:"PORT_CMOS_INDEX",113:"PORT_CMOS_DATA",128:"PORT_DIAG",129:"PORT_DMA_PAGE_2",146:"PORT_A20",160:"PORT_PIC2_CMD",161:"PORT_PIC2_DATA",178:"PORT_SMI_CMD",179:"PORT_SMI_STATUS", +212:"PORT_DMA2_MASK_REG",214:"PORT_DMA2_MODE_REG",218:"PORT_DMA2_MASTER_CLEAR",240:"PORT_MATH_CLEAR",368:"PORT_ATA2_CMD_BASE",496:"PORT_ATA1_CMD_BASE",632:"PORT_LPT2",744:"PORT_SERIAL4",760:"PORT_SERIAL2",884:"PORT_ATA2_CTRL_BASE",888:"PORT_LPT1",1E3:"PORT_SERIAL3",1008:"PORT_FD_BASE",1010:"PORT_FD_DOR",1012:"PORT_FD_STATUS",1013:"PORT_FD_DATA",1014:"PORT_HD_DATA",1015:"PORT_FD_DIR",1016:"PORT_SERIAL1",3320:"PORT_PCI_CMD",3321:"PORT_PCI_REBOOT",3324:"PORT_PCI_DATA",1026:"PORT_BIOS_DEBUG",1296:"PORT_QEMU_CFG_CTL", +1297:"PORT_QEMU_CFG_DATA",45056:"PORT_ACPI_PM_BASE",45312:"PORT_SMB_BASE",35072:"PORT_BIOS_APM"};C.prototype.get_port_description=function(a){return ka[a]?" ("+ka[a]+")":""};function D(a,b){this.stopping=this.running=!1;this.idle=!0;this.tick_counter=0;this.worker=null;this.cpu=new E(a,b,()=>{this.idle&&this.next_tick(0)});this.bus=a;this.register_yield()}D.prototype.run=function(){this.stopping=!1;this.running||(this.running=!0,this.bus.send("emulator-started"));this.next_tick(0)};D.prototype.do_tick=function(){if(this.stopping||!this.running)this.stopping=this.running=!1,this.bus.send("emulator-stopped");else{this.idle=!1;var a=this.cpu.main_loop();this.next_tick(a)}}; +D.prototype.next_tick=function(a){const b=++this.tick_counter;this.idle=!0;this.yield(a,b)};D.prototype.yield_callback=function(a){a===this.tick_counter&&this.do_tick()};D.prototype.stop=function(){this.running&&(this.stopping=!0)};D.prototype.destroy=function(){this.unregister_yield()};D.prototype.restart=function(){this.cpu.reset_cpu();this.cpu.load_bios()};D.prototype.init=function(a){this.cpu.init(a,this.bus);this.bus.send("emulator-ready")}; +if("undefined"!==typeof process)D.prototype.yield=function(a,b){1>a?global.setImmediate(c=>this.yield_callback(c),b):setTimeout(c=>this.yield_callback(c),a,b)},D.prototype.register_yield=function(){},D.prototype.unregister_yield=function(){};else if("undefined"!==typeof Worker){function a(){let b;globalThis.onmessage=function(c){const d=c.data.t;b=b&&clearTimeout(b);1>d?postMessage(c.data.tick):b=setTimeout(()=>postMessage(c.data.tick),d)}}D.prototype.register_yield=function(){const b=URL.createObjectURL(new Blob(["("+ +a.toString()+")()"],{type:"text/javascript"}));this.worker=new Worker(b);this.worker.onmessage=c=>this.yield_callback(c.data);URL.revokeObjectURL(b)};D.prototype.yield=function(b,c){this.worker.postMessage({t:b,tick:c})};D.prototype.unregister_yield=function(){this.worker&&this.worker.terminate();this.worker=null}}else D.prototype.yield=function(a){setTimeout(()=>{this.do_tick()},a)},D.prototype.register_yield=function(){},D.prototype.unregister_yield=function(){};D.prototype.save_state=function(){return this.cpu.save_state()}; +D.prototype.restore_state=function(a){return this.cpu.restore_state(a)};if("object"===typeof performance&&performance.now)D.microtick=performance.now.bind(performance);else if("function"===typeof require){const {performance:a}=require("perf_hooks");D.microtick=a.now.bind(a)}else D.microtick="object"===typeof process&&process.hrtime?function(){var a=process.hrtime();return 1E3*a[0]+a[1]/1E6}:Date.now;var H=H||{};H.exportSymbol=function(a,b){"undefined"!==typeof window?window[a]=b:"undefined"!==typeof module&&"undefined"!==typeof module.exports?module.exports[a]=b:"function"===typeof importScripts&&(self[a]=b)};H.exportProperty=function(){};var k=k||{};k.pads=function(a,b){return(a||0===a?a+"":"").padEnd(b," ")};k.pad0=function(a,b){return(a||0===a?a+"":"").padStart(b,"0")};k.zeros=function(a){return Array(a).fill(0)};k.range=function(a){return Array.from(Array(a).keys())}; +k.view=function(a,b,c,d){return new Proxy({},{get:function(e,g){e=new a(b.buffer,c,d);const f=e[g];if("function"===typeof f)return f.bind(e);/^\d+$/.test(g);return f},set:function(e,g,f){/^\d+$/.test(g);(new a(b.buffer,c,d))[g]=f;return!0}})};function B(a,b){a=a?a.toString(16):"";return"0x"+k.pad0(a.toUpperCase(),b||1)} +if("undefined"!==typeof crypto&&crypto.getRandomValues){const a=new Int32Array(1);k.get_rand_int=function(){crypto.getRandomValues(a);return a[0]}}else if("undefined"!==typeof require){const a=require("crypto");k.get_rand_int=function(){return a.randomBytes(4).readInt32LE(0)}} +(function(){if("function"===typeof Math.clz32)k.int_log2=function(d){return 31-Math.clz32(d)};else{for(var a=new Int8Array(256),b=0,c=-2;256>b;b++)b&b-1||c++,a[b]=c;k.int_log2=function(d){d>>>=0;var e=d>>>16;if(e){var g=e>>>8;return g?24+a[g]:16+a[e]}return(g=d>>>8)?8+a[g]:a[d]}}})();k.round_up_to_next_power_of_2=function(a){return 1>=a?1:1<<1+k.int_log2(a-1)}; +function la(a){var b=new Uint8Array(a),c,d;this.length=0;this.push=function(e){this.length!==a&&this.length++;b[d]=e;d=d+1&a-1};this.shift=function(){if(this.length){var e=b[c];c=c+1&a-1;this.length--;return e}return-1};this.peek=function(){return this.length?b[c]:-1};this.clear=function(){this.length=d=c=0};this.clear()}function oa(a){this.size=a;this.data=new Float32Array(a);this.length=this.end=this.start=0} +oa.prototype.push=function(a){this.length===this.size?this.start=this.start+1&this.size-1:this.length++;this.data[this.end]=a;this.end=this.end+1&this.size-1};oa.prototype.shift=function(){if(this.length){var a=this.data[this.start];this.start=this.start+1&this.size-1;this.length--;return a}}; +oa.prototype.shift_block=function(a){var b=new Float32Array(a);a>this.length&&(a=this.length);var c=this.start+a,d=this.data.subarray(this.start,c);b.set(d);c>=this.size&&(c-=this.size,b.set(this.data.subarray(0,c),d.length));this.start=c;this.length-=a;return b};oa.prototype.peek=function(){if(this.length)return this.data[this.start]};oa.prototype.clear=function(){this.length=this.end=this.start=0}; +k.Bitmap=function(a){"number"===typeof a?this.view=new Uint8Array(a+7>>3):a instanceof ArrayBuffer&&(this.view=new Uint8Array(a))};k.Bitmap.prototype.set=function(a,b){const c=a>>3;a=1<<(a&7);this.view[c]=b?this.view[c]|a:this.view[c]&~a};k.Bitmap.prototype.get=function(a){return this.view[a>>3]>>(a&7)&1};k.Bitmap.prototype.get_buffer=function(){return this.view.buffer};k.load_file=pa; +function qa(a,b,c){function d(){const l=c||0;setTimeout(()=>{qa(a,b,l+1)},1E3*([1,1,2,3,5,8,13,21][l]||34))}var e=new XMLHttpRequest;e.open(b.method||"get",a,!0);e.responseType=b.as_json?"json":"arraybuffer";if(b.headers)for(var g=Object.keys(b.headers),f=0;fe.status&&d();else if(e.response){if(b.range){const l=e.getResponseHeader("Content-Encoding");l&&"identity"!==l&&console.error("Server sent Content-Encoding in response to ranged request",{filename:a,enc:l})}b.done&&b.done(e.response, +e)}};e.onerror=function(l){console.error("Loading the image "+a+" failed",l);d()};b.progress&&(e.onprogress=function(l){b.progress(l)});e.send(null)} +function pa(a,b){const c=require("fs");b.range?c.open(a,"r",(d,e)=>{if(d)throw d;d=b.range.length;var g=Buffer.allocUnsafe(d);c.read(e,g,0,d,b.range.start,f=>{if(f)throw f;b.done&&b.done(new Uint8Array(g));c.close(e,h=>{if(h)throw h;})})}):c.readFile(a,{encoding:b.as_json?"utf-8":null},function(d,e){d?console.log("Could not read file:",a,d):(d=e,d=b.as_json?JSON.parse(d):(new Uint8Array(d)).buffer,b.done(d))})} +k.read_sized_string_from_mem=function(a,b,c){return String.fromCharCode(...(new Uint8Array(a.buffer,b>>>0,c>>>0)))};(function(){function a(f){this.buffer=f;this.byteLength=f.byteLength;this.onprogress=this.onload=void 0}function b(f,h,l){this.filename=f;this.byteLength=h;this.block_cache=new Map;this.block_cache_is_write=new Set;this.fixed_chunk_size=l;this.cache_reads=!!l;this.onprogress=this.onload=void 0}function c(f,h,l,m,n){const p=f.match(/\.[^\.]+(\.zst)?$/);this.extension=p?p[0]:"";this.basename=f.substring(0,f.length-this.extension.length);this.is_zstd=this.extension.endsWith(".zst");this.basename.endsWith("/")|| +(this.basename+="-");this.block_cache=new Map;this.block_cache_is_write=new Set;this.byteLength=h;this.fixed_chunk_size=l;this.partfile_alt_format=!!m;this.zstd_decompress=n;this.cache_reads=!!l;this.onprogress=this.onload=void 0}function d(f){this.file=f;this.byteLength=f.size;1073741824>20)+" MB ...");this.buffer=new ArrayBuffer(f.size);this.onprogress=this.onload=void 0}function e(f){this.file=f;this.byteLength=f.size;this.block_cache= +new Map;this.block_cache_is_write=new Set;this.onprogress=this.onload=void 0}k.SyncBuffer=a;k.AsyncXHRBuffer=b;k.AsyncXHRPartfileBuffer=c;k.AsyncFileBuffer=e;k.SyncFileBuffer=d;k.buffer_from_object=function(f,h){if(f.buffer instanceof ArrayBuffer)return new k.SyncBuffer(f.buffer);if("undefined"!==typeof File&&f.buffer instanceof File)return h=f.async,void 0===h&&(h=268435456<=f.buffer.size),h?new k.AsyncFileBuffer(f.buffer):new k.SyncFileBuffer(f.buffer);if(f.url)return f.use_parts?new k.AsyncXHRPartfileBuffer(f.url, +f.size,f.fixed_chunk_size,!1,h):new k.AsyncXHRBuffer(f.url,f.size,f.fixed_chunk_size)};a.prototype.load=function(){this.onload&&this.onload({buffer:this.buffer})};a.prototype.get=function(f,h,l){l(new Uint8Array(this.buffer,f,h))};a.prototype.set=function(f,h,l){(new Uint8Array(this.buffer,f,h.byteLength)).set(h);l()};a.prototype.get_buffer=function(f){f(this.buffer)};a.prototype.get_state=function(){const f=[];f[0]=this.byteLength;f[1]=new Uint8Array(this.buffer);return f};a.prototype.set_state= +function(f){this.byteLength=f[0];this.buffer=f[1].slice().buffer};b.prototype.load=function(){void 0!==this.byteLength?this.onload&&this.onload(Object.create(null)):g(this.filename,(f,h)=>{if(f)throw Error("Cannot use: "+this.filename+". "+f);this.byteLength=h;this.onload&&this.onload(Object.create(null))})};b.prototype.get_from_cache=function(f,h){var l=h/256;f/=256;for(var m=0;m{l?h(l):h(null,m.size)})}:function(f,h){k.load_file(f,{done:(l,m)=>{l=m.getResponseHeader("Content-Range")||"";(m=l.match(/\/(\d+)\s*$/))?h(null,+m[1]):h("`Range: bytes=...` header not supported (Got `"+l+"`)")},headers:{Range:"bytes=0-0","X-Accept-Encoding":"identity"}})}})();function ra(a,b,c,d,e,g){this.master=new K(this,a,b,d,e,0,g);this.slave=new K(this,a,c,!1,e,1,g);this.current_interface=this.master;this.cpu=a;0===e?(this.ata_port=496,this.irq=14,this.pci_id=240):1===e&&(this.ata_port=368,this.irq=15,this.pci_id=248);this.ata_port_high=this.ata_port|516;this.master_port=46080;this.pci_space=[134,128,16,112,5,0,160,2,0,128,1,1,0,0,0,0,this.ata_port&255|1,this.ata_port>>8,0,0,this.ata_port_high&255|1,this.ata_port_high>>8,0,0,0,0,0,0,0,0,0,0,this.master_port&255|1, +this.master_port>>8,0,0,0,0,0,0,0,0,0,0,67,16,212,130,0,0,0,0,0,0,0,0,0,0,0,0,this.irq,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.pci_bars=[{size:8},{size:4},void 0,void 0,{size:16}];this.name="ide"+e;this.device_control=2;a.io.register_read(this.ata_port|7,this,function(){this.cpu.device_lower_irq(this.irq);return this.read_status()});a.io.register_read(this.ata_port_high| +2,this,this.read_status);a.io.register_write(this.ata_port_high|2,this,this.write_control);a.io.register_read(this.ata_port|0,this,function(){return this.current_interface.read_data(1)},function(){return this.current_interface.read_data(2)},function(){return this.current_interface.read_data(4)});a.io.register_read(this.ata_port|1,this,function(){B(this.current_interface.error&255);return this.current_interface.error&255});a.io.register_read(this.ata_port|2,this,function(){B(this.current_interface.bytecount& +255);return this.current_interface.bytecount&255});a.io.register_read(this.ata_port|3,this,function(){B(this.current_interface.sector&255);return this.current_interface.sector&255});a.io.register_read(this.ata_port|4,this,function(){B(this.current_interface.cylinder_low&255);return this.current_interface.cylinder_low&255});a.io.register_read(this.ata_port|5,this,function(){B(this.current_interface.cylinder_high&255);return this.current_interface.cylinder_high&255});a.io.register_read(this.ata_port| +6,this,function(){return this.current_interface.drive_head&255});a.io.register_write(this.ata_port|0,this,function(f){this.current_interface.write_data_port8(f)},function(f){this.current_interface.write_data_port16(f)},function(f){this.current_interface.write_data_port32(f)});a.io.register_write(this.ata_port|1,this,function(f){B(f);this.master.lba_count=(this.master.lba_count<<8|f)&65535;this.slave.lba_count=(this.slave.lba_count<<8|f)&65535});a.io.register_write(this.ata_port|2,this,function(f){B(f); +this.master.bytecount=(this.master.bytecount<<8|f)&65535;this.slave.bytecount=(this.slave.bytecount<<8|f)&65535});a.io.register_write(this.ata_port|3,this,function(f){B(f);this.master.sector=(this.master.sector<<8|f)&65535;this.slave.sector=(this.slave.sector<<8|f)&65535});a.io.register_write(this.ata_port|4,this,function(f){B(f);this.master.cylinder_low=(this.master.cylinder_low<<8|f)&65535;this.slave.cylinder_low=(this.slave.cylinder_low<<8|f)&65535});a.io.register_write(this.ata_port|5,this,function(f){B(f); +this.master.cylinder_high=(this.master.cylinder_high<<8|f)&65535;this.slave.cylinder_high=(this.slave.cylinder_high<<8|f)&65535});a.io.register_write(this.ata_port|6,this,function(f){var h=f&16;B(f,2);this.current_interface=h?this.slave:this.master;this.master.drive_head=f;this.slave.drive_head=f;this.master.is_lba=this.slave.is_lba=f>>6&1;this.master.head=this.slave.head=f&15});this.dma_command=this.dma_status=this.prdt_addr=0;a.io.register_write(this.ata_port|7,this,function(f){this.cpu.device_lower_irq(this.irq); +this.current_interface.ata_command(f)});a.io.register_read(this.master_port|4,this,void 0,void 0,this.dma_read_addr);a.io.register_write(this.master_port|4,this,void 0,void 0,this.dma_set_addr);a.io.register_read(this.master_port,this,this.dma_read_command8,void 0,this.dma_read_command);a.io.register_write(this.master_port,this,this.dma_write_command8,void 0,this.dma_write_command);a.io.register_read(this.master_port|2,this,this.dma_read_status);a.io.register_write(this.master_port|2,this,this.dma_write_status); +a.io.register_read(this.master_port|8,this,function(){return 0});a.io.register_read(this.master_port|10,this,function(){return 0});a.devices.pci.register_device(this)}ra.prototype.read_status=function(){if(this.current_interface.buffer){var a=this.current_interface.status;B(a,2);return a}return 0};ra.prototype.write_control=function(a){B(a,2);a&4&&(this.cpu.device_lower_irq(this.irq),this.master.device_reset(),this.slave.device_reset());this.device_control=a}; +ra.prototype.dma_read_addr=function(){B(this.prdt_addr,8);return this.prdt_addr};ra.prototype.dma_set_addr=function(a){B(a,8);this.prdt_addr=a};ra.prototype.dma_read_status=function(){B(this.dma_status);return this.dma_status};ra.prototype.dma_write_status=function(a){B(a);this.dma_status&=~(a&6)};ra.prototype.dma_read_command=function(){return this.dma_read_command8()|this.dma_read_status()<<16};ra.prototype.dma_read_command8=function(){B(this.dma_command);return this.dma_command}; +ra.prototype.dma_write_command=function(a){B(a);this.dma_write_command8(a&255);this.dma_write_status(a>>16&255)}; +ra.prototype.dma_write_command8=function(a){B(a);const b=this.dma_command;this.dma_command=a&9;if((b&1)!==(a&1))if(0===(a&1))this.dma_status&=-2;else switch(this.dma_status|=1,this.current_interface.current_command){case 37:case 200:this.current_interface.do_ata_read_sectors_dma();break;case 202:case 53:this.current_interface.do_ata_write_sectors_dma();break;case 160:this.current_interface.do_atapi_dma();break;default:B(this.current_interface.current_command)}}; +ra.prototype.push_irq=function(){0===(this.device_control&2)&&(this.dma_status|=4,this.cpu.device_raise_irq(this.irq))};ra.prototype.get_state=function(){var a=[];a[0]=this.master;a[1]=this.slave;a[2]=this.ata_port;a[3]=this.irq;a[4]=this.pci_id;a[5]=this.ata_port_high;a[6]=this.master_port;a[7]=this.name;a[8]=this.device_control;a[9]=this.prdt_addr;a[10]=this.dma_status;a[11]=this.current_interface===this.master;a[12]=this.dma_command;return a}; +ra.prototype.set_state=function(a){this.master.set_state(a[0]);this.slave.set_state(a[1]);this.ata_port=a[2];this.irq=a[3];this.pci_id=a[4];this.ata_port_high=a[5];this.master_port=a[6];this.name=a[7];this.device_control=a[8];this.prdt_addr=a[9];this.dma_status=a[10];this.current_interface=a[11]?this.master:this.slave;this.dma_command=a[12]}; +function K(a,b,c,d,e,g,f){this.device=a;this.bus=f;this.nr=e;this.cpu=b;this.buffer=c;this.sector_size=d?2048:512;this.is_atapi=d;this.cylinder_count=this.sectors_per_track=this.head_count=this.sector_count=0;this.buffer&&(this.sector_count=this.buffer.byteLength/this.sector_size,this.sector_count!==(this.sector_count|0)&&(this.sector_count=Math.ceil(this.sector_count)),d?(this.head_count=1,this.sectors_per_track=0):(this.head_count=16,this.sectors_per_track=63),this.cylinder_count=this.sector_count/ +this.head_count/this.sectors_per_track,this.cylinder_count!==(this.cylinder_count|0)&&(this.cylinder_count=Math.floor(this.cylinder_count)),a=b.devices.rtc,a.cmos_write(57,a.cmos_read(57)|1<<4*this.nr),a.cmos_write(18,a.cmos_read(18)&15|240),a.cmos_write(27,this.cylinder_count&255),a.cmos_write(28,this.cylinder_count>>8&255),a.cmos_write(29,this.head_count&255),a.cmos_write(30,255),a.cmos_write(31,255),a.cmos_write(32,200),a.cmos_write(33,this.cylinder_count&255),a.cmos_write(34,this.cylinder_count>> +8&255),a.cmos_write(35,this.sectors_per_track&255));this.buffer=c;this.drive_head=this.head=this.cylinder_high=this.cylinder_low=this.lba_count=this.sector=this.bytecount=this.is_lba=0;this.status=80;this.sectors_per_drq=128;this.data_pointer=this.error=0;this.data=new Uint8Array(65536);this.data16=new Uint16Array(this.data.buffer);this.data32=new Int32Array(this.data.buffer);this.data_end=this.data_length=0;this.current_atapi_command=this.current_command=-1;this.last_io_id=this.write_dest=0;this.in_progress_io_ids= +new Set;this.cancelled_io_ids=new Set;Object.seal(this)}K.prototype.device_reset=function(){this.is_atapi?(this.status=0,this.sector=this.error=this.bytecount=1,this.cylinder_low=20,this.cylinder_high=235):(this.status=81,this.sector=this.error=this.bytecount=1,this.cylinder_high=this.cylinder_low=0);this.cancel_io_operations()};K.prototype.push_irq=function(){this.device.push_irq()}; +K.prototype.ata_command=function(a){B(a);if(this.buffer)switch(this.current_command=a,this.error=0,a){case 8:this.data_length=this.data_end=this.data_pointer=0;this.device_reset();this.push_irq();break;case 16:this.status=80;this.cylinder_low=0;this.push_irq();break;case 248:this.status=80;a=this.sector_count-1;this.sector=a&255;this.cylinder_low=a>>8&255;this.cylinder_high=a>>16&255;this.drive_head=this.drive_head&240|a>>24&15;this.push_irq();break;case 39:this.status=80;a=this.sector_count-1;this.sector= +a&255;this.cylinder_low=a>>8&255;this.cylinder_high=a>>16&255;this.sector|=a>>24<<8&65280;this.push_irq();break;case 32:case 36:case 41:case 196:this.ata_read_sectors(a);break;case 48:case 52:case 57:case 197:this.ata_write_sectors(a);break;case 144:this.push_irq();this.error=257;this.status=80;break;case 145:this.status=80;this.push_irq();break;case 160:this.is_atapi&&(this.status=88,this.data_allocate(12),this.data_end=12,this.bytecount=1,this.push_irq());break;case 161:this.is_atapi?(this.create_identify_packet(), +this.status=88,this.cylinder_low=20,this.cylinder_high=235):this.status=65;this.push_irq();break;case 198:B(this.bytecount&255);this.sectors_per_drq=this.bytecount&255;this.status=80;this.push_irq();break;case 37:case 200:this.ata_read_sectors_dma(a);break;case 53:case 202:this.ata_write_sectors_dma(a);break;case 64:this.status=80;this.push_irq();break;case 218:this.status=65;this.error=4;this.push_irq();break;case 224:this.status=80;this.push_irq();break;case 225:this.status=80;this.push_irq();break; +case 231:this.status=80;this.push_irq();break;case 236:if(this.is_atapi){this.status=65;this.error=4;this.push_irq();break}this.create_identify_packet();this.status=88;this.push_irq();break;case 234:this.status=80;this.push_irq();break;case 239:B(this.bytecount&255);this.status=80;this.push_irq();break;case 222:this.status=80;this.push_irq();break;case 245:this.status=80;this.push_irq();break;case 249:this.status=65;this.error=4;break;default:B(a),this.status=65,this.error=4}else this.error=4,this.status= +65,this.push_irq()}; +K.prototype.atapi_handle=function(){B(this.data[0]);this.data_pointer=0;this.current_atapi_command=this.data[0];switch(this.current_atapi_command){case 0:this.data_allocate(0);this.data_end=this.data_length;this.status=80;break;case 3:this.data_allocate(this.data[4]);this.data_end=this.data_length;this.status=88;this.data[0]=240;this.data[2]=5;this.data[7]=8;break;case 18:var a=this.data[4];this.status=88;B(this.data[1],2);this.data.set([5,128,1,49,31,0,0,0,83,79,78,89,32,32,32,32,67,68,45,82,79, +77,32,67,68,85,45,49,48,48,48,32,49,46,49,97]);this.data_end=this.data_length=Math.min(36,a);break;case 26:this.data_allocate(this.data[4]);this.data_end=this.data_length;this.status=88;break;case 30:this.data_allocate(0);this.data_end=this.data_length;this.status=80;break;case 37:a=this.sector_count-1;this.data_set(new Uint8Array([a>>24&255,a>>16&255,a>>8&255,a&255,0,0,this.sector_size>>8&255,this.sector_size&255]));this.data_end=this.data_length;this.status=88;break;case 40:this.lba_count&1?this.atapi_read_dma(this.data): +this.atapi_read(this.data);break;case 66:a=this.data[8];this.data_allocate(Math.min(8,a));this.data_end=this.data_length;this.status=88;break;case 67:a=this.data[8]|this.data[7]<<8;var b=this.data[9]>>6;this.data_allocate(a);this.data_end=this.data_length;B(b,2);B(this.data[6]);0===b?(a=this.sector_count,this.data.set(new Uint8Array([0,18,1,1,0,20,1,0,0,0,0,0,0,22,170,0,a>>24,a>>16&255,a>>8&255,a&255]))):1===b&&this.data.set(new Uint8Array([0,10,1,1,0,0,0,0,0,0,0,0]));this.status=88;break;case 70:a= +this.data[8]|this.data[7]<<8;a=Math.min(a,32);this.data_allocate(a);this.data_end=this.data_length;this.data[0]=a-4>>24&255;this.data[1]=a-4>>16&255;this.data[2]=a-4>>8&255;this.data[3]=a-4&255;this.data[6]=8;this.data[10]=3;this.status=88;break;case 81:this.data_allocate(0);this.data_end=this.data_length;this.status=80;break;case 82:B(this.data[0]);this.status=81;this.data_length=0;this.error=80;break;case 90:a=this.data[8]|this.data[7]<<8;b=this.data[2];B(b);42===b&&this.data_allocate(Math.min(30, +a));this.data_end=this.data_length;this.status=88;break;case 189:this.data_allocate(this.data[9]|this.data[8]<<8);this.data_end=this.data_length;this.data[5]=1;this.status=88;break;case 74:this.status=81;this.data_length=0;this.error=80;B(this.data[0]);break;case 190:B(this.data[0]);this.data_allocate(0);this.data_end=this.data_length;this.status=80;break;default:this.status=81,this.data_length=0,this.error=80,B(this.data[0])}this.bytecount=this.bytecount&-8|2;0===(this.status&128)&&this.push_irq(); +0===(this.status&128)&&0===this.data_length&&(this.bytecount|=1,this.status&=-9)};K.prototype.do_write=function(){this.status=80;var a=this.data.subarray(0,this.data_length);this.ata_advance(this.current_command,this.data_length/512);this.push_irq();this.buffer.set(this.write_dest,a,function(){});this.report_write(this.data_length)}; +K.prototype.atapi_read=function(a){var b=a[2]<<24|a[3]<<16|a[4]<<8|a[5],c=a[7]<<8|a[8];a=a[1];var d=c*this.sector_size,e=b*this.sector_size;ta("CD read lba="+B(b)+" lbacount="+B(c)+" bytecount="+B(d)+" flags="+B(a),32768);this.data_length=0;var g=this.cylinder_high<<8&65280|this.cylinder_low&255;ta(B(this.cylinder_high,2)+" "+B(this.cylinder_low,2),32768);this.cylinder_low=this.cylinder_high=0;65535===g&&g--;g>d&&(g=d);e>=this.buffer.byteLength?(ua(!1,"CD read: Outside of disk end="+B(e+d)+" size="+ +B(this.buffer.byteLength),32768),this.status=255,this.push_irq()):0===d?(this.status=80,this.data_pointer=0):(d=Math.min(d,this.buffer.byteLength-e),this.status=208,this.report_read_start(),this.read_buffer(e,d,f=>{this.data_set(f);this.status=88;this.bytecount=this.bytecount&-8|2;this.push_irq();this.data_end=g&=-4;this.data_end>this.data_length&&(this.data_end=this.data_length);this.cylinder_low=this.data_end&255;this.cylinder_high=this.data_end>>8&255;this.report_read_end(d)}))}; +K.prototype.atapi_read_dma=function(a){var b=a[2]<<24|a[3]<<16|a[4]<<8|a[5],c=a[7]<<8|a[8];a=a[1];var d=c*this.sector_size,e=b*this.sector_size;ta("CD read DMA lba="+B(b)+" lbacount="+B(c)+" bytecount="+B(d)+" flags="+B(a),32768);e>=this.buffer.byteLength?(ua(!1,"CD read: Outside of disk end="+B(e+d)+" size="+B(this.buffer.byteLength),32768),this.status=255,this.push_irq()):(this.status=208,this.report_read_start(),this.read_buffer(e,d,g=>{this.report_read_end(d);this.status=88;this.bytecount=this.bytecount& +-8|2;this.data_set(g);this.do_atapi_dma()}))}; +K.prototype.do_atapi_dma=function(){if(0!==(this.device.dma_status&1)&&0!==(this.status&8)){var a=this.device.prdt_addr,b=0,c=this.data;do{var d=this.cpu.read32s(a),e=this.cpu.read16(a+4),g=this.cpu.read8(a+7)&128;e||(e=65536);B(d);B(e);B(this.data_length);this.cpu.write_blob(c.subarray(b,Math.min(b+e,this.data_length)),d);b+=e;a+=8;if(b>=this.data_length&&!g){B(b);B(this.data_length);B(this.current_command);break}}while(!g);this.status=80;this.device.dma_status&=-2;this.bytecount=this.bytecount& +-8|3;this.push_irq()}};K.prototype.read_data=function(a){if(this.data_pointer>>1]:this.data32[this.data_pointer>>>2];this.data_pointer+=a;0===(this.data_pointer&(0===(this.data_end&4095)?4095:255))&&(B(this.data[this.data_pointer],2),B(this.data_pointer),B(this.data_length));this.data_pointer>=this.data_end&&this.read_end();return b}this.data_pointer+=a;return 0}; +K.prototype.read_end=function(){B(this.current_command);B(this.data_pointer);B(this.data_end);B(this.data_length);if(160===this.current_command)if(this.data_end===this.data_length)this.status=80,this.bytecount=this.bytecount&-8|3,this.push_irq();else{this.status=88;this.bytecount=this.bytecount&-8|2;this.push_irq();var a=this.cylinder_high<<8&65280|this.cylinder_low&255;this.data_end+a>this.data_length?(this.cylinder_low=this.data_length-this.data_end&255,this.cylinder_high=this.data_length-this.data_end>> +8&255,this.data_end=this.data_length):this.data_end+=a;B(this.data_end)}else this.error=0,this.data_pointer>=this.data_length?this.status=80:(a=196===this.current_command||41===this.current_command?Math.min(this.sectors_per_drq,(this.data_length-this.data_end)/512):1,this.ata_advance(this.current_command,a),this.data_end+=512*a,this.status=88,this.push_irq())}; +K.prototype.write_data_port=function(a,b){if(this.data_pointer>=this.data_end)B(a),B(this.data_end),B(this.data_pointer);else{if(0===(this.data_pointer+b&(0===(this.data_end&4095)?4095:255))||20>this.data_end)B(a>>>0),B(this.data_end),B(this.data_pointer);1===b?this.data[this.data_pointer++]=a:2===b?(this.data16[this.data_pointer>>>1]=a,this.data_pointer+=2):(this.data32[this.data_pointer>>>2]=a,this.data_pointer+=4);this.data_pointer===this.data_end&&this.write_end()}}; +K.prototype.write_data_port8=function(a){this.write_data_port(a,1)};K.prototype.write_data_port16=function(a){this.write_data_port(a,2)};K.prototype.write_data_port32=function(a){this.write_data_port(a,4)};K.prototype.write_end=function(){160===this.current_command?this.atapi_handle():(B(this.data_pointer),B(this.data_length),this.data_pointer>=this.data_length?this.do_write():(B(this.current_command),this.status=88,this.data_end+=512,this.push_irq()))}; +K.prototype.ata_advance=function(a,b){this.bytecount-=b;36===a||41===a||52===a||57===a||37===a||53===a?(a=b+this.get_lba48(),this.sector=a&255|a>>16&65280,this.cylinder_low=a>>8&255,this.cylinder_high=a>>16&255):this.is_lba?(a=b+this.get_lba28(),this.sector=a&255,this.cylinder_low=a>>8&255,this.cylinder_high=a>>16&255,this.head=this.head&-16|a&15):(a=b+this.get_chs(),b=a/(this.head_count*this.sectors_per_track)|0,this.cylinder_low=b&255,this.cylinder_high=b>>8&255,this.head=(a/this.sectors_per_track| +0)%this.head_count&15,this.sector=a%this.sectors_per_track+1&255,this.get_chs())}; +K.prototype.ata_read_sectors=function(a){var b=36===a||41===a,c=this.get_count(b);b=this.get_lba(b);var d=32===a||36===a,e=c*this.sector_size,g=b*this.sector_size;ta("ATA read cmd="+B(a)+" mode="+(this.is_lba?"lba":"chs")+" lba="+B(b)+" lbacount="+B(c)+" bytecount="+B(e),32768);g+e>this.buffer.byteLength?(this.status=255,this.push_irq()):(this.status=192,this.report_read_start(),this.read_buffer(g,e,f=>{this.data_set(f);this.status=88;this.data_end=d?512:Math.min(e,512*this.sectors_per_drq);this.ata_advance(a, +d?1:Math.min(c,this.sectors_per_track));this.push_irq();this.report_read_end(e)}))};K.prototype.ata_read_sectors_dma=function(a){var b=37===a;a=this.get_count(b);b=this.get_lba(b);var c=a*this.sector_size,d=b*this.sector_size;B(b);B(a);B(c);d+c>this.buffer.byteLength?(this.status=255,this.push_irq()):(this.status=88,this.device.dma_status|=1)}; +K.prototype.do_ata_read_sectors_dma=function(){var a=37===this.current_command,b=this.get_count(a);a=this.get_lba(a);var c=b*this.sector_size;a*=this.sector_size;this.report_read_start();this.read_buffer(a,c,d=>{var e=this.device.prdt_addr,g=0;do{var f=this.cpu.read32s(e),h=this.cpu.read16(e+4),l=this.cpu.read8(e+7)&128;h||(h=65536);B(f);B(h);this.cpu.write_blob(d.subarray(g,g+h),f);g+=h;e+=8}while(!l);this.ata_advance(this.current_command,b);this.status=80;this.device.dma_status&=-2;this.current_command= +-1;this.push_irq();this.report_read_end(c)})};K.prototype.ata_write_sectors=function(a){var b=52===a||57===a,c=this.get_count(b);b=this.get_lba(b);a=48===a||52===a;var d=c*this.sector_size,e=b*this.sector_size;B(b);B(c);B(d);e+d>this.buffer.byteLength?(this.status=255,this.push_irq()):(this.status=88,this.data_allocate_noclear(d),this.data_end=a?512:Math.min(d,512*this.sectors_per_drq),this.write_dest=e)}; +K.prototype.ata_write_sectors_dma=function(a){var b=53===a;a=this.get_count(b);b=this.get_lba(b);var c=a*this.sector_size,d=b*this.sector_size;B(b);B(a);B(c);d+c>this.buffer.byteLength?(this.status=255,this.push_irq()):(this.status=88,this.device.dma_status|=1)}; +K.prototype.do_ata_write_sectors_dma=function(){var a=53===this.current_command,b=this.get_count(a),c=this.get_lba(a);a=b*this.sector_size;c*=this.sector_size;var d=this.device.prdt_addr,e=0;ta("prdt addr: "+B(d,8),32768);const g=new Uint8Array(a);do{var f=this.cpu.read32s(d),h=this.cpu.read16(d+4),l=this.cpu.read8(d+7)&128;h||(h=65536);ta("dma write transfer dest="+B(f)+" prd_count="+B(h),32768);f=this.cpu.mem8.subarray(f,f+h);g.set(f,e);e+=h;d+=8}while(!l);this.buffer.set(c,g,()=>{this.ata_advance(this.current_command, +b);this.status=80;this.push_irq();this.device.dma_status&=-2;this.current_command=-1});this.report_write(a)};K.prototype.get_chs=function(){return((this.cylinder_low&255|this.cylinder_high<<8&65280)*this.head_count+this.head)*this.sectors_per_track+(this.sector&255)-1};K.prototype.get_lba28=function(){return this.sector&255|this.cylinder_low<<8&65280|this.cylinder_high<<16&16711680|(this.head&15)<<24}; +K.prototype.get_lba48=function(){return(this.sector&255|this.cylinder_low<<8&65280|this.cylinder_high<<16&16711680|this.sector>>8<<24&4278190080)>>>0};K.prototype.get_lba=function(a){return a?this.get_lba48():this.is_lba?this.get_lba28():this.get_chs()};K.prototype.get_count=function(a){a?(a=this.bytecount,0===a&&(a=65536)):(a=this.bytecount&255,0===a&&(a=256));return a}; +K.prototype.create_identify_packet=function(){if(this.drive_head&16)this.data_allocate(0);else{for(var a=0;512>a;a++)this.data[a]=0;a=Math.min(16383,this.cylinder_count);this.data_set([64,this.is_atapi?133:0,a,a>>8,0,0,this.head_count,this.head_count>>8,this.sectors_per_track/512,this.sectors_per_track/512>>8,0,2,this.sectors_per_track,this.sectors_per_track>>8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,4,0,0,0,0,0,0,0,0,0,56,118,32,54,68,72,32,32,32,32,32,32,32,32,32,32,32,32,32, +32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,128,0,1,0,0,2,0,0,0,2,0,2,7,0,a,a>>8,this.head_count,this.head_count>>8,this.sectors_per_track,0,this.sector_count&255,this.sector_count>>8&255,this.sector_count>>16&255,this.sector_count>>24&255,0,0,this.sector_count&255,this.sector_count>>8&255,this.sector_count>>16&255,this.sector_count>>24&255,0,0,160===this.current_command?0:7,160===this.current_command?0:4,0,0,30,0,30,0,30,0,30,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,126,0, +0,0,0,0,0,116,0,64,0,64,0,116,0,64,0,0,0,0,0,0,0,0,0,0,1,96,0,0,0,0,0,0,0,0,0,0,0,0,this.sector_count&255,this.sector_count>>8&255,this.sector_count>>16&255,this.sector_count>>24&255]);this.data_end=this.data_length=512}};K.prototype.data_allocate=function(a){this.data_allocate_noclear(a);for(var b=0;b>2;b++)this.data32[b]=0}; +K.prototype.data_allocate_noclear=function(a){this.data.length{this.cancelled_io_ids.delete(d)?this.in_progress_io_ids.has(d):(this.in_progress_io_ids.delete(d),c(e))})};K.prototype.cancel_io_operations=function(){for(const a of this.in_progress_io_ids)this.cancelled_io_ids.add(a);this.in_progress_io_ids.clear()}; +K.prototype.get_state=function(){var a=[];a[0]=this.bytecount;a[1]=this.cylinder_count;a[2]=this.cylinder_high;a[3]=this.cylinder_low;a[4]=this.data_pointer;a[5]=0;a[6]=0;a[7]=0;a[8]=0;a[9]=this.drive_head;a[10]=this.error;a[11]=this.head;a[12]=this.head_count;a[13]=this.is_atapi;a[14]=this.is_lba;a[15]=this.lba_count;a[16]=this.data;a[17]=this.data_length;a[18]=this.sector;a[19]=this.sector_count;a[20]=this.sector_size;a[21]=this.sectors_per_drq;a[22]=this.sectors_per_track;a[23]=this.status;a[24]= +this.write_dest;a[25]=this.current_command;a[26]=this.data_end;a[27]=this.current_atapi_command;a[28]=this.buffer;return a}; +K.prototype.set_state=function(a){this.bytecount=a[0];this.cylinder_count=a[1];this.cylinder_high=a[2];this.cylinder_low=a[3];this.data_pointer=a[4];this.drive_head=a[9];this.error=a[10];this.head=a[11];this.head_count=a[12];this.is_atapi=a[13];this.is_lba=a[14];this.lba_count=a[15];this.data=a[16];this.data_length=a[17];this.sector=a[18];this.sector_count=a[19];this.sector_size=a[20];this.sectors_per_drq=a[21];this.sectors_per_track=a[22];this.status=a[23];this.write_dest=a[24];this.current_command= +a[25];this.data_end=a[26];this.current_atapi_command=a[27];this.data16=new Uint16Array(this.data.buffer);this.data32=new Int32Array(this.data.buffer);this.buffer&&this.buffer.set_state(a[28])};function va(a){this.pci_addr=new Uint8Array(4);this.pci_value=new Uint8Array(4);this.pci_response=new Uint8Array(4);this.pci_status=new Uint8Array(4);this.pci_addr32=new Int32Array(this.pci_addr.buffer);this.pci_value32=new Int32Array(this.pci_value.buffer);this.pci_response32=new Int32Array(this.pci_response.buffer);this.pci_status32=new Int32Array(this.pci_status.buffer);this.device_spaces=[];this.devices=[];this.cpu=a;for(var b=0;256>b;b++)this.device_spaces[b]=void 0,this.devices[b]=void 0;this.io= +a.io;a.io.register_write(3324,this,function(c){this.pci_write8(this.pci_addr32[0],c)},function(c){this.pci_write16(this.pci_addr32[0],c)},function(c){this.pci_write32(this.pci_addr32[0],c)});a.io.register_write(3325,this,function(c){this.pci_write8(this.pci_addr32[0]+1|0,c)});a.io.register_write(3326,this,function(c){this.pci_write8(this.pci_addr32[0]+2|0,c)},function(c){this.pci_write16(this.pci_addr32[0]+2|0,c)});a.io.register_write(3327,this,function(c){this.pci_write8(this.pci_addr32[0]+3|0,c)}); +a.io.register_read_consecutive(3324,this,function(){return this.pci_response[0]},function(){return this.pci_response[1]},function(){return this.pci_response[2]},function(){return this.pci_response[3]});a.io.register_read_consecutive(3320,this,function(){return this.pci_status[0]},function(){return this.pci_status[1]},function(){return this.pci_status[2]},function(){return this.pci_status[3]});a.io.register_write_consecutive(3320,this,function(c){this.pci_addr[0]=c&252},function(c){2===(this.pci_addr[1]& +6)&&6===(c&6)?a.reboot_internal():this.pci_addr[1]=c},function(c){this.pci_addr[2]=c},function(c){this.pci_addr[3]=c;this.pci_query()});this.register_device({pci_id:0,pci_space:[134,128,55,18,0,0,0,0,2,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0],pci_bars:[],name:"82441FX PMC"});this.isa_bridge={pci_id:8,pci_space:[134,128,0,112,7,0,0,2,0,0,1,6,0,0,128,0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],pci_bars:[],name:"82371SB PIIX3 ISA"};this.isa_bridge_space=this.register_device(this.isa_bridge);this.isa_bridge_space8=new Uint8Array(this.isa_bridge_space.buffer)}va.prototype.get_state=function(){for(var a=[],b=0;256>b;b++)a[b]=this.device_spaces[b];a[256]=this.pci_addr;a[257]=this.pci_value;a[258]=this.pci_response;a[259]=this.pci_status;return a}; +va.prototype.set_state=function(a){for(var b=0;256>b;b++){var c=this.devices[b],d=a[b];if(c&&d){for(var e=0;e>3&31;var d="query enabled="+(this.pci_addr[3]>>7)+(" bdf="+B(a,4));d+=" dev="+B(c,2);d+=" addr="+B(b,2);a=this.device_spaces[a];void 0!==a?(this.pci_status32[0]=-2147483648,this.pci_response32[0]=b>2]:0,d+=" "+B(this.pci_addr32[0]>>>0,8)+" -> "+B(this.pci_response32[0]>>>0,8)):(this.pci_response32[0]=-1,this.pci_status32[0]=0)}; +va.prototype.pci_write8=function(a,b){var c=a>>8&65535;a&=255;var d=new Uint8Array(this.device_spaces[c].buffer);B(a);B(c>>3,2);B(a,4);B(b,2);d[a]=b};va.prototype.pci_write16=function(a,b){var c=a>>8&65535;a&=255;var d=new Uint16Array(this.device_spaces[c].buffer);16<=a&&44>a?B(a):(B(a),B(c>>3,2),B(a,4),B(b,4),d[a>>>1]=b)}; +va.prototype.pci_write32=function(a,b){var c=a>>8&65535;a&=255;var d=this.device_spaces[c],e=this.devices[c];if(d)if(16<=a&&40>a){e=e.pci_bars[a-16>>2];B(b>>>0);B(c>>3,2);if(e){c=a>>2;var g=d[c]&1;-1===(b|3|e.size-1)?(b=~(e.size-1)|g,0===g&&(d[c]=b)):0===g&&(d[c]=e.original_bar);if(1===g){g=d[c]&65534;var f=b&65534;B(g>>>0,8);B(f>>>0,8);this.set_io_bars(e,g,f);d[c]=b|1}}else d[a>>2]=0;B(d[a>>2]>>>0)}else 48===a?(B(c>>3,2),B(b>>>0,8),d[a>>2]=e.pci_rom_size?-1===(b|2047)?-e.pci_rom_size|0:e.pci_rom_address| +0:0):4===a?(B(c>>3,2),B(a,4),B(b>>>0,8)):(B(c>>3,2),B(a,4),B(b>>>0,8),d[a>>>2]=b)};va.prototype.register_device=function(a){var b=a.pci_id;B(b);var c=new Int32Array(64);c.set(new Int32Array((new Uint8Array(a.pci_space)).buffer));this.device_spaces[b]=c;this.devices[b]=a;b=c.slice(4,10);for(var d=0;d>8&255)-1+((a>>3)-1&255)&3)])};va.prototype.lower_irq=function(a){this.cpu.device_lower_irq(this.isa_bridge_space8[96+((this.device_spaces[a][15]>>8&255)+(a>>3&255)-2&3)])};function L(a,b){this.io=a.io;this.cpu=a;this.dma=a.devices.dma;this.bytes_expecting=0;this.receiving_command=new Uint8Array(10);this.receiving_index=0;this.next_command=null;this.response_data=new Uint8Array(10);this.last_head=this.last_cylinder=this.drive=this.status_reg2=this.status_reg1=this.status_reg0=this.response_length=this.response_index=0;this.last_sector=1;this.dir=this.dor=0;this.fdb_image=this.fda_image=null;b?this.set_fda(b):(this.eject_fda(),this.cpu.devices.rtc.cmos_write(16,64)); +this.io.register_read(1008,this,this.port3F0_read);this.io.register_read(1010,this,this.port3F2_read);this.io.register_read(1012,this,this.port3F4_read);this.io.register_read(1013,this,this.port3F5_read);this.io.register_read(1015,this,this.port3F7_read);this.io.register_write(1010,this,this.port3F2_write);this.io.register_write(1012,this,this.port3F4_write);this.io.register_write(1013,this,this.port3F5_write)} +L.prototype.eject_fda=function(){this.fda_image=null;this.number_of_cylinders=this.number_of_heads=this.sectors_per_track=0;this.dir=128}; +L.prototype.set_fda=function(a){var b={[163840]:{type:1,tracks:40,sectors:8,heads:1},[184320]:{type:1,tracks:40,sectors:9,heads:1},[204800]:{type:1,tracks:40,sectors:10,heads:1},[327680]:{type:1,tracks:40,sectors:8,heads:2},[368640]:{type:1,tracks:40,sectors:9,heads:2},[409600]:{type:1,tracks:40,sectors:10,heads:2},[737280]:{type:3,tracks:80,sectors:9,heads:2},[1228800]:{type:2,tracks:80,sectors:15,heads:2},[1474560]:{type:4,tracks:80,sectors:18,heads:2},[1763328]:{type:5,tracks:82,sectors:21,heads:2}, +[2949120]:{type:5,tracks:80,sectors:36,heads:2},512:{type:1,tracks:1,sectors:1,heads:1}};let c=a.byteLength,d=b[c];d||(c=1474560>4);B(a);this.dor=a};L.prototype.check_drive_status=function(){this.status_reg1=this.fda_image?0:5;this.response_index=0;this.response_length=1;this.response_data[0]=0}; +L.prototype.seek=function(a){if(0===(a[0]&3)){var b=a[1];a=a[0]>>2&1;b!==this.last_cylinder&&(this.dir=0);this.status_reg1=this.fda_image?0:5;this.status_reg0=32;this.last_cylinder=b;this.last_head=a}this.raise_irq()};L.prototype.calibrate=function(a){this.seek([a[0],0])};L.prototype.check_interrupt_status=function(){this.response_index=0;this.response_length=2;this.response_data[0]=this.status_reg0;this.response_data[1]=this.last_cylinder}; +L.prototype.do_sector=function(a,b){var c=b[2],d=b[1],e=b[3],g=128<this.sectors_per_track&&(d=1,c++,c>=this.number_of_heads&&(c=0,b++)),b!==this.last_cylinder&&(this.dir=0),this.status_reg0=32,this.last_cylinder=b,this.last_head=c,this.last_sector=d,this.response_index=0,this.response_length=7,this.response_data[0]=c<<2|32,this.response_data[1]=0,this.response_data[2]=0,this.response_data[3]=b,this.response_data[4]=c,this.response_data[5]=d,this.response_data[6]=a[4],this.raise_irq())}; +L.prototype.fix_drive_data=function(a){a.slice(0,this.bytes_expecting)};L.prototype.configure=function(a){a.slice(0,this.bytes_expecting)};L.prototype.read_sector_id=function(){this.response_index=0;this.response_length=7;this.response_data[0]=0;this.response_data[1]=0;this.response_data[2]=0;this.response_data[3]=0;this.response_data[4]=0;this.response_data[5]=0;this.response_data[6]=0;this.raise_irq()};L.prototype.raise_irq=function(){this.dor&8&&this.cpu.device_raise_irq(6)};E.prototype.mmap_read8=function(a){return this.memory_map_read8[a>>>17](a)};E.prototype.mmap_write8=function(a,b){this.memory_map_write8[a>>>17](a,b)};E.prototype.mmap_read16=function(a){var b=this.memory_map_read8[a>>>17];return b(a)|b(a+1|0)<<8};E.prototype.mmap_write16=function(a,b){var c=this.memory_map_write8[a>>>17];c(a,b&255);c(a+1|0,b>>8)};E.prototype.mmap_read32=function(a){return this.memory_map_read32[a>>>17](a)}; +E.prototype.mmap_write32=function(a,b){this.memory_map_write32[a>>>17](a,b)};E.prototype.mmap_write64=function(a,b,c){var d=this.memory_map_write32[a>>>17];d(a,b);d(a+4,c)};E.prototype.mmap_write128=function(a,b,c,d,e){var g=this.memory_map_write32[a>>>17];g(a,b);g(a+4,c);g(a+8,d);g(a+12,e)};E.prototype.write_blob=function(a,b){a.length&&(this.in_mapped_range(b),this.in_mapped_range(b+a.length-1),this.jit_dirty_cache(b,b+a.length),this.mem8.set(a,b))}; +E.prototype.read_blob=function(a,b){b&&(this.in_mapped_range(a),this.in_mapped_range(a+b-1));return this.mem8.subarray(a,a+b)};function M(a){this.cpu=a;this.channel_page=new Uint8Array(8);this.channel_pagehi=new Uint8Array(8);this.channel_addr=new Uint16Array(8);this.channel_addr_init=new Uint16Array(8);this.channel_count=new Uint16Array(8);this.channel_count_init=new Uint16Array(8);this.channel_mask=new Uint8Array(8);this.channel_mode=new Uint8Array(8);this.unmask_listeners=[];this.lsb_msb_flipflop=0;a=a.io;a.register_write(0,this,this.port_addr_write.bind(this,0));a.register_write(2,this,this.port_addr_write.bind(this, 1));a.register_write(4,this,this.port_addr_write.bind(this,2));a.register_write(6,this,this.port_addr_write.bind(this,3));a.register_write(1,this,this.port_count_write.bind(this,0));a.register_write(3,this,this.port_count_write.bind(this,1));a.register_write(5,this,this.port_count_write.bind(this,2));a.register_write(7,this,this.port_count_write.bind(this,3));a.register_read(0,this,this.port_addr_read.bind(this,0));a.register_read(2,this,this.port_addr_read.bind(this,1));a.register_read(4,this,this.port_addr_read.bind(this, 2));a.register_read(6,this,this.port_addr_read.bind(this,3));a.register_read(1,this,this.port_count_read.bind(this,0));a.register_read(3,this,this.port_count_read.bind(this,1));a.register_read(5,this,this.port_count_read.bind(this,2));a.register_read(7,this,this.port_count_read.bind(this,3));a.register_write(192,this,this.port_addr_write.bind(this,4));a.register_write(196,this,this.port_addr_write.bind(this,5));a.register_write(200,this,this.port_addr_write.bind(this,6));a.register_write(204,this, this.port_addr_write.bind(this,7));a.register_write(194,this,this.port_count_write.bind(this,4));a.register_write(198,this,this.port_count_write.bind(this,5));a.register_write(202,this,this.port_count_write.bind(this,6));a.register_write(206,this,this.port_count_write.bind(this,7));a.register_read(192,this,this.port_addr_read.bind(this,4));a.register_read(196,this,this.port_addr_read.bind(this,5));a.register_read(200,this,this.port_addr_read.bind(this,6));a.register_read(204,this,this.port_addr_read.bind(this, @@ -48,696 +172,538 @@ this,this.port_page_write.bind(this,4));a.register_write(139,this,this.port_page 4));a.register_read(139,this,this.port_page_read.bind(this,5));a.register_read(137,this,this.port_page_read.bind(this,6));a.register_read(138,this,this.port_page_read.bind(this,7));a.register_write(1159,this,this.port_pagehi_write.bind(this,0));a.register_write(1155,this,this.port_pagehi_write.bind(this,1));a.register_write(1153,this,this.port_pagehi_write.bind(this,2));a.register_write(1154,this,this.port_pagehi_write.bind(this,3));a.register_write(1163,this,this.port_pagehi_write.bind(this,5)); a.register_write(1161,this,this.port_pagehi_write.bind(this,6));a.register_write(1162,this,this.port_pagehi_write.bind(this,7));a.register_read(1159,this,this.port_pagehi_read.bind(this,0));a.register_read(1155,this,this.port_pagehi_read.bind(this,1));a.register_read(1153,this,this.port_pagehi_read.bind(this,2));a.register_read(1154,this,this.port_pagehi_read.bind(this,3));a.register_read(1163,this,this.port_pagehi_read.bind(this,5));a.register_read(1161,this,this.port_pagehi_read.bind(this,6));a.register_read(1162, this,this.port_pagehi_read.bind(this,7));a.register_write(10,this,this.port_singlemask_write.bind(this,0));a.register_write(212,this,this.port_singlemask_write.bind(this,4));a.register_write(15,this,this.port_multimask_write.bind(this,0));a.register_write(222,this,this.port_multimask_write.bind(this,4));a.register_read(15,this,this.port_multimask_read.bind(this,0));a.register_read(222,this,this.port_multimask_read.bind(this,4));a.register_write(11,this,this.port_mode_write.bind(this,0));a.register_write(214, -this,this.port_mode_write.bind(this,4));a.register_write(12,this,this.portC_write);a.register_write(216,this,this.portC_write)}B.prototype.get_state=function(){return[this.channel_page,this.channel_pagehi,this.channel_addr,this.channel_addr_init,this.channel_count,this.channel_count_init,this.channel_mask,this.channel_mode,this.lsb_msb_flipflop]}; -B.prototype.set_state=function(a){this.channel_page=a[0];this.channel_pagehi=a[1];this.channel_addr=a[2];this.channel_addr_init=a[3];this.channel_count=a[4];this.channel_count_init=a[5];this.channel_mask=a[6];this.channel_mode=a[7];this.lsb_msb_flipflop=a[8]};B.prototype.port_count_write=function(a,b){y(b);this.channel_count[a]=this.flipflop_get(this.channel_count[a],b,!1);this.channel_count_init[a]=this.flipflop_get(this.channel_count_init[a],b,!0)}; -B.prototype.port_count_read=function(a){y(this.channel_count[a]);return this.flipflop_read(this.channel_count[a])};B.prototype.port_addr_write=function(a,b){y(b);this.channel_addr[a]=this.flipflop_get(this.channel_addr[a],b,!1);this.channel_addr_init[a]=this.flipflop_get(this.channel_addr_init[a],b,!0)};B.prototype.port_addr_read=function(a){y(this.channel_addr[a]);return this.flipflop_read(this.channel_addr[a])};B.prototype.port_pagehi_write=function(a,b){y(b);this.channel_pagehi[a]=b}; -B.prototype.port_pagehi_read=function(a){return this.channel_pagehi[a]};B.prototype.port_page_write=function(a,b){y(b);this.channel_page[a]=b};B.prototype.port_page_read=function(a){return this.channel_page[a]};B.prototype.port_singlemask_write=function(a,b){this.update_mask((b&3)+a,b&4?1:0)};B.prototype.port_multimask_write=function(a,b){y(b);for(var c=0;4>c;c++)this.update_mask(a+c,b&1<a.byteLength)e(!0);else{var h=this.cpu;this.channel_addr[d]+=f;a.get(b,f,function(l){h.write_blob(l,g);e(!1)})}}; -B.prototype.do_write=function(a,b,c,d,e){var f=this.channel_count[d]+1&65535,g=5<=d?2:1,h=f*g,l=this.address_get_8bit(d),m=!1,n=!1,p=this.channel_mode[d]&16;ua("to "+y(l)+" len "+y(h),16);ch&&(n=!0);b+h>a.byteLength?e(!0):(this.channel_addr[d]+=f,this.channel_count[d]-=f,!m&&p&&(this.channel_addr[d]=this.channel_addr_init[d],this.channel_count[d]=this.channel_count_init[d]),a.set(b,this.cpu.mem8.subarray(l,l+h),()=>{n&&p?this.do_write(a,b+h,c-h,d,e):e(!1)}))}; -B.prototype.address_get_8bit=function(a){var b=this.channel_addr[a];5<=a&&(b<<=1);b=b&65535|this.channel_page[a]<<16;return b|=this.channel_pagehi[a]<<24};B.prototype.count_get_8bit=function(a){var b=this.channel_count[a]+1;5<=a&&(b*=2);return b};B.prototype.flipflop_get=function(a,b,c){c||(this.lsb_msb_flipflop^=1);return this.lsb_msb_flipflop?a&-256|b:a&-65281|b<<8};B.prototype.flipflop_read=function(a){return(this.lsb_msb_flipflop^=1)?a&255:a>>8&255};function Ca(a){this.ports=[];this.cpu=a;for(var b=0;65536>b;b++)this.ports[b]=this.create_empty_entry();var c=a.memory_size[0];for(b=0;b<<17>>0,8);return 255},function(d,e){y(d>>>0,8);y(e,2)},function(d){y(d>>>0,8);return-1},function(d,e){y(d>>>0,8);y(e>>>0,8)})} -Ca.prototype.create_empty_entry=function(){return{read8:this.empty_port_read8,read16:this.empty_port_read16,read32:this.empty_port_read32,write8:this.empty_port_write,write16:this.empty_port_write,write32:this.empty_port_write,device:void 0}};Ca.prototype.empty_port_read8=function(){return 255};Ca.prototype.empty_port_read16=function(){return 65535};Ca.prototype.empty_port_read32=function(){return-1};Ca.prototype.empty_port_write=function(){}; -Ca.prototype.register_read=function(a,b,c,d,e){c&&(this.ports[a].read8=c);d&&(this.ports[a].read16=d);e&&(this.ports[a].read32=e);this.ports[a].device=b};Ca.prototype.register_write=function(a,b,c,d,e){c&&(this.ports[a].write8=c);d&&(this.ports[a].write16=d);e&&(this.ports[a].write32=e);this.ports[a].device=b}; -Ca.prototype.register_read_consecutive=function(a,b,c,d,e,f){function g(){return c.call(this)|d.call(this)<<8}function h(){return e.call(this)|f.call(this)<<8}function l(){return c.call(this)|d.call(this)<<8|e.call(this)<<16|f.call(this)<<24}e&&f?(this.register_read(a,b,c,g,l),this.register_read(a+1,b,d),this.register_read(a+2,b,e,h),this.register_read(a+3,b,f)):(this.register_read(a,b,c,g),this.register_read(a+1,b,d))}; -Ca.prototype.register_write_consecutive=function(a,b,c,d,e,f){function g(m){c.call(this,m&255);d.call(this,m>>8&255)}function h(m){e.call(this,m&255);f.call(this,m>>8&255)}function l(m){c.call(this,m&255);d.call(this,m>>8&255);e.call(this,m>>16&255);f.call(this,m>>>24)}e&&f?(this.register_write(a,b,c,g,l),this.register_write(a+1,b,d),this.register_write(a+2,b,e,h),this.register_write(a+3,b,f)):(this.register_write(a,b,c,g),this.register_write(a+1,b,d))}; -Ca.prototype.mmap_read32_shim=function(a){var b=this.cpu.memory_map_read8[a>>>17];return b(a)|b(a+1)<<8|b(a+2)<<16|b(a+3)<<24};Ca.prototype.mmap_write32_shim=function(a,b){var c=this.cpu.memory_map_write8[a>>>17];c(a,b&255);c(a+1,b>>8&255);c(a+2,b>>16&255);c(a+3,b>>>24)}; -Ca.prototype.mmap_register=function(a,b,c,d,e,f){y(a>>>0,8);y(b,8);e||(e=this.mmap_read32_shim.bind(this));f||(f=this.mmap_write32_shim.bind(this));for(a>>>=17;0>>0,8),this.get_port_description(a));return c.write32.call(c.device,b)}; -Ca.prototype.port_read8=function(a){var b=this.ports[a];b.read8===this.empty_port_read8&&(y(a,4),this.get_port_description(a));b=b.read8.call(b.device,a);(0>b||256<=b)&&y(a);return b};Ca.prototype.port_read16=function(a){var b=this.ports[a];b.read16===this.empty_port_read16&&(y(a,4),this.get_port_description(a));b=b.read16.call(b.device,a);(0>b||65536<=b)&&y(a);return b}; -Ca.prototype.port_read32=function(a){var b=this.ports[a];b.read32===this.empty_port_read32&&(y(a,4),this.get_port_description(a));return b.read32.call(b.device,a)}; -var Da={4:"PORT_DMA_ADDR_2",5:"PORT_DMA_CNT_2",10:"PORT_DMA1_MASK_REG",11:"PORT_DMA1_MODE_REG",12:"PORT_DMA1_CLEAR_FF_REG",13:"PORT_DMA1_MASTER_CLEAR",32:"PORT_PIC1_CMD",33:"PORT_PIC1_DATA",64:"PORT_PIT_COUNTER0",65:"PORT_PIT_COUNTER1",66:"PORT_PIT_COUNTER2",67:"PORT_PIT_MODE",96:"PORT_PS2_DATA",97:"PORT_PS2_CTRLB",100:"PORT_PS2_STATUS",112:"PORT_CMOS_INDEX",113:"PORT_CMOS_DATA",128:"PORT_DIAG",129:"PORT_DMA_PAGE_2",146:"PORT_A20",160:"PORT_PIC2_CMD",161:"PORT_PIC2_DATA",178:"PORT_SMI_CMD",179:"PORT_SMI_STATUS", -212:"PORT_DMA2_MASK_REG",214:"PORT_DMA2_MODE_REG",218:"PORT_DMA2_MASTER_CLEAR",240:"PORT_MATH_CLEAR",368:"PORT_ATA2_CMD_BASE",496:"PORT_ATA1_CMD_BASE",632:"PORT_LPT2",744:"PORT_SERIAL4",760:"PORT_SERIAL2",884:"PORT_ATA2_CTRL_BASE",888:"PORT_LPT1",1E3:"PORT_SERIAL3",1008:"PORT_FD_BASE",1010:"PORT_FD_DOR",1012:"PORT_FD_STATUS",1013:"PORT_FD_DATA",1014:"PORT_HD_DATA",1015:"PORT_FD_DIR",1016:"PORT_SERIAL1",3320:"PORT_PCI_CMD",3321:"PORT_PCI_REBOOT",3324:"PORT_PCI_DATA",1026:"PORT_BIOS_DEBUG",1296:"PORT_QEMU_CFG_CTL", -1297:"PORT_QEMU_CFG_DATA",45056:"PORT_ACPI_PM_BASE",45312:"PORT_SMB_BASE",35072:"PORT_BIOS_APM"};Ca.prototype.get_port_description=function(a){return Da[a]?" ("+Da[a]+")":""};var Ga={};function Ha(){this.listeners={};this.pair=void 0}Ha.prototype.register=function(a,b,c){var d=this.listeners[a];void 0===d&&(d=this.listeners[a]=[]);d.push({fn:b,this_value:c})};Ha.prototype.unregister=function(a,b){var c=this.listeners[a];void 0!==c&&(this.listeners[a]=c.filter(function(d){return d.fn!==b}))};Ha.prototype.send=function(a,b){if(this.pair&&(a=this.pair.listeners[a],void 0!==a))for(var c=0;c=this.command_size&&this.command_do()};D.prototype.port2xD_write=function(){};D.prototype.port2xE_write=function(){};D.prototype.port2xF_write=function(){}; -D.prototype.port3x0_read=function(){this.mpu_read_buffer.length&&(this.mpu_read_buffer_lastvalue=this.mpu_read_buffer.shift());y(this.mpu_read_buffer_lastvalue);return this.mpu_read_buffer_lastvalue};D.prototype.port3x0_write=function(a){y(a)};D.prototype.port3x1_read=function(){return 0|128*!this.mpu_read_buffer.length};D.prototype.port3x1_write=function(a){y(a);255===a&&(this.mpu_read_buffer.clear(),this.mpu_read_buffer.push(254))}; -D.prototype.command_do=function(){var a=Ja[this.command];a||(a=this.dsp_default_handler);a.call(this);this.command_size=this.command=0;this.write_buffer.clear()};D.prototype.dsp_default_handler=function(){y(this.command)};function E(a,b,c){c||(c=D.prototype.dsp_default_handler);for(var d=0;dc;c++)b.push(a+c);return b}E([14],2,function(){this.asp_registers[this.write_buffer.shift()]=this.write_buffer.shift()}); -E([15],1,function(){this.read_buffer.clear();this.read_buffer.push(this.asp_registers[this.write_buffer.shift()])});E([16],1,function(){var a=this.write_buffer.shift();a=Ra(a/127.5+-1,-1,1);this.dac_buffers[0].push(a);this.dac_buffers[1].push(a);this.bus.send("dac-enable")});E([20,21],2,function(){this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dsp_highspeed=this.dsp_16bit=this.dsp_signed=this.dma_autoinit=!1;this.dma_transfer_size_set();this.dma_transfer_start()});E([22],2);E([23],2); -E([28],0,function(){this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dma_autoinit=!0;this.dsp_highspeed=this.dsp_16bit=this.dsp_signed=!1;this.dma_transfer_start()});E([31],0);E([32],0,function(){this.read_buffer.clear();this.read_buffer.push(127)});E([36],2);E([44],0);E([48],0);E([49],0);E([52],0);E([53],0);E([54],0);E([55],0);E([56],0);E([64],1,function(){this.sampling_rate_change(1E6/(256-this.write_buffer.shift())/this.get_channel_count())}); -E([65,66],2,function(){this.sampling_rate_change(this.write_buffer.shift()<<8|this.write_buffer.shift())});E([72],2,function(){this.dma_transfer_size_set()});E([116],2);E([117],2);E([118],2);E([119],2);E([125],0);E([127],0);E([128],2);E([144],0,function(){this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dma_autoinit=!0;this.dsp_signed=!1;this.dsp_highspeed=!0;this.dsp_16bit=!1;this.dma_transfer_start()});E([145],0);E([152],0);E([153],0);E([160],0);E([168],0); -E(Qa(176),3,function(){if(this.command&8)this.dsp_default_handler();else{var a=this.write_buffer.shift();this.dma_irq=2;this.dma_channel=this.dma_channel_16bit;this.dma_autoinit=!!(this.command&4);this.dsp_signed=!!(a&16);this.dsp_stereo=!!(a&32);this.dsp_16bit=!0;this.dma_transfer_size_set();this.dma_transfer_start()}}); -E(Qa(192),3,function(){if(this.command&8)this.dsp_default_handler();else{var a=this.write_buffer.shift();this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dma_autoinit=!!(this.command&4);this.dsp_signed=!!(a&16);this.dsp_stereo=!!(a&32);this.dsp_16bit=!1;this.dma_transfer_size_set();this.dma_transfer_start()}});E([208],0,function(){this.dma_paused=!0;this.bus.send("dac-disable")});E([209],0,function(){this.dummy_speaker_enabled=!0});E([211],0,function(){this.dummy_speaker_enabled=!1}); -E([212],0,function(){this.dma_paused=!1;this.bus.send("dac-enable")});E([213],0,function(){this.dma_paused=!0;this.bus.send("dac-disable")});E([214],0,function(){this.dma_paused=!1;this.bus.send("dac-enable")});E([216],0,function(){this.read_buffer.clear();this.read_buffer.push(255*this.dummy_speaker_enabled)});E([217,218],0,function(){this.dma_autoinit=!1});E([224],1,function(){this.read_buffer.clear();this.read_buffer.push(~this.write_buffer.shift())}); -E([225],0,function(){this.read_buffer.clear();this.read_buffer.push(4);this.read_buffer.push(5)});E([226],1);E([227],0,function(){this.read_buffer.clear();for(var a=0;44>a;a++)this.read_buffer.push("COPYRIGHT (C) CREATIVE TECHNOLOGY LTD, 1992.".charCodeAt(a));this.read_buffer.push(0)});E([228],1,function(){this.test_register=this.write_buffer.shift()});E([232],0,function(){this.read_buffer.clear();this.read_buffer.push(this.test_register)});E([242,243],0,function(){this.raise_irq()});var Sa=new Uint8Array(256); -Sa[14]=255;Sa[15]=7;Sa[55]=56;E([249],1,function(){var a=this.write_buffer.shift();this.read_buffer.clear();this.read_buffer.push(Sa[a])});D.prototype.mixer_read=function(a){var b=Ka[a];b?b=b.call(this):(b=this.mixer_registers[a],y(a),y(b));return b};D.prototype.mixer_write=function(a,b){var c=Na[a];c?c.call(this,b):(y(a),y(b))};D.prototype.mixer_default_read=function(){y(this.mixer_current_address);return this.mixer_registers[this.mixer_current_address]}; -D.prototype.mixer_default_write=function(a){y(this.mixer_current_address);y(a);this.mixer_registers[this.mixer_current_address]=a}; -D.prototype.mixer_reset=function(){this.mixer_registers[4]=204;this.mixer_registers[34]=204;this.mixer_registers[38]=204;this.mixer_registers[40]=0;this.mixer_registers[46]=0;this.mixer_registers[10]=0;this.mixer_registers[48]=192;this.mixer_registers[49]=192;this.mixer_registers[50]=192;this.mixer_registers[51]=192;this.mixer_registers[52]=192;this.mixer_registers[53]=192;this.mixer_registers[54]=0;this.mixer_registers[55]=0;this.mixer_registers[56]=0;this.mixer_registers[57]=0;this.mixer_registers[59]= -0;this.mixer_registers[60]=31;this.mixer_registers[61]=21;this.mixer_registers[62]=11;this.mixer_registers[63]=0;this.mixer_registers[64]=0;this.mixer_registers[65]=0;this.mixer_registers[66]=0;this.mixer_registers[67]=0;this.mixer_registers[68]=128;this.mixer_registers[69]=128;this.mixer_registers[70]=128;this.mixer_registers[71]=128;this.mixer_full_update()};D.prototype.mixer_full_update=function(){for(var a=1;a>>4};Na[a]=function(d){this.mixer_registers[a]=d;var e=d<<4&240|this.mixer_registers[c]&15;this.mixer_write(b,d&240|this.mixer_registers[b]&15);this.mixer_write(c,e)}} -function Xa(a,b,c){Ka[a]=D.prototype.mixer_default_read;Na[a]=function(d){this.mixer_registers[a]=d;this.bus.send("mixer-volume",[b,c,(d>>>2)-62])}}Ua(0,function(){this.mixer_reset();return 0});Va(0);Wa(4,50,51);Wa(34,48,49);Wa(38,52,53);Wa(40,54,55);Wa(46,56,57);Xa(48,0,0);Xa(49,0,1);Xa(50,2,0);Xa(51,2,1);Ua(59);Va(59,function(a){this.mixer_registers[59]=a;this.bus.send("mixer-volume",[1,2,6*(a>>>6)-18])});Ua(65); -Va(65,function(a){this.mixer_registers[65]=a;this.bus.send("mixer-gain-left",6*(a>>>6))});Ua(66);Va(66,function(a){this.mixer_registers[66]=a;this.bus.send("mixer-gain-right",6*(a>>>6))});Ua(68);Va(68,function(a){this.mixer_registers[68]=a;a>>>=3;this.bus.send("mixer-treble-left",a-(16>a?14:16))});Ua(69);Va(69,function(a){this.mixer_registers[69]=a;a>>>=3;this.bus.send("mixer-treble-right",a-(16>a?14:16))});Ua(70); -Va(70,function(a){this.mixer_registers[70]=a;a>>>=3;this.bus.send("mixer-bass-right",a-(16>a?14:16))});Ua(71);Va(71,function(a){this.mixer_registers[71]=a;a>>>=3;this.bus.send("mixer-bass-right",a-(16>a?14:16))});Ua(128,function(){switch(this.irq){case 2:return 1;case 5:return 2;case 7:return 4;case 10:return 8;default:return 0}});Va(128,function(a){a&1&&(this.irq=2);a&2&&(this.irq=5);a&4&&(this.irq=7);a&8&&(this.irq=10)}); -Ua(129,function(){var a=0;switch(this.dma_channel_8bit){case 0:a|=1;break;case 1:a|=2;break;case 3:a|=8}switch(this.dma_channel_16bit){case 5:a|=32;break;case 6:a|=64;break;case 7:a|=128}return a});Va(129,function(a){a&1&&(this.dma_channel_8bit=0);a&2&&(this.dma_channel_8bit=1);a&8&&(this.dma_channel_8bit=3);a&32&&(this.dma_channel_16bit=5);a&64&&(this.dma_channel_16bit=6);a&128&&(this.dma_channel_16bit=7)});Ua(130,function(){for(var a=32,b=0;16>b;b++)a|=b*this.irq_triggered[b];return a}); -D.prototype.fm_default_write=function(a,b,c){y(c);y(a)};function Ya(a,b){b||(b=D.prototype.fm_default_write);for(var c=0;c>2&-4,32),this.dma_bytes_block);this.dma_waiting_transfer=!0;this.dma.channel_mask[this.dma_channel]||this.dma_on_unmask(this.dma_channel)}; -D.prototype.dma_on_unmask=function(a){a===this.dma_channel&&this.dma_waiting_transfer&&(this.dma_waiting_transfer=!1,this.dma_bytes_left=this.dma_bytes_count,this.dma_paused=!1,this.bus.send("dac-enable"))}; -D.prototype.dma_transfer_next=function(){var a=Math.min(this.dma_bytes_left,this.dma_bytes_block),b=Math.floor(a/this.bytes_per_sample);this.dma.do_write(this.dma_syncbuffer,0,a,this.dma_channel,c=>{c||(this.dma_to_dac(b),this.dma_bytes_left-=a,this.dma_bytes_left||(this.raise_irq(this.dma_irq),this.dma_autoinit&&(this.dma_bytes_left=this.dma_bytes_count)))})}; -D.prototype.dma_to_dac=function(a){var b=this.dsp_16bit?32767.5:127.5,c=this.dsp_signed?0:-1,d=this.dsp_stereo?1:2;var e=this.dsp_16bit?this.dsp_signed?this.dma_buffer_int16:this.dma_buffer_uint16:this.dsp_signed?this.dma_buffer_int8:this.dma_buffer_uint8;for(var f=0,g=0;gc)*c+(b<=a&&a<=c)*a};function ab(a){this.message=a}ab.prototype=Error();const bb={Map,Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array}; -function cb(a,b){if("object"!==typeof a||null===a)return a;if(Array.isArray(a))return a.map(e=>cb(e,b));if(a instanceof Map)return{__state_type__:"Map",args:Array.from(a.entries()).map(([e,f])=>[cb(e,b),cb(f,b)])};a.constructor===Object&&console.log(a);if(a.BYTES_PER_ELEMENT){var c=new Uint8Array(a.buffer,a.byteOffset,a.length*a.BYTES_PER_ELEMENT);return{__state_type__:a.constructor.name.replace("bound ",""),buffer_id:b.push(c)-1}}a=a.get_state();c=[];for(var d=0;dx)throw new ab("Invalid length: "+x);q=new Int32Array(q.buffer,q.byteOffset,4);if(-2039052682!==q[0])throw new ab("Invalid header: "+y(q[0]>>>0));if(6!==q[1])throw new ab("Version mismatch: dump="+q[1]+" we=6");if(r&&q[2]!==x)throw new ab("Length doesn't match header: real="+x+" header="+q[2]);return q[3]}function d(q){q=(new TextDecoder).decode(q);return JSON.parse(q)}b=new Uint8Array(b);if(4247762216===(new Uint32Array(b.buffer,0,1))[0]){var e= -a.zstd_create_ctx(b.length);(new Uint8Array(a.wasm_memory.buffer,a.zstd_get_src_ptr(e)>>>0,b.length)).set(b);var f=a.zstd_read(e,16),g=new Uint8Array(a.wasm_memory.buffer,f>>>0,16),h=c(g,!1);a.zstd_read_free(f,16);f=a.zstd_read(e,h);g=new Uint8Array(a.wasm_memory.buffer,f>>>0,h);g=d(g);a.zstd_read_free(f,h);f=g.state;var l=g.buffer_infos;g=[];h=16+h;for(var m of l){l=(h+3&-4)-h;if(1048576>>0;a.zstd_read_free(n,l);n=new Uint8Array(m.length);g.push(n.buffer);for(var p= -0;p>>0,q),p);a.zstd_read_free(r,q);p+=q}}else n=a.zstd_read(e,l+m.length),p=(n>>>0)+l,g.push(a.wasm_memory.buffer.slice(p,p+m.length)),a.zstd_read_free(n,l+m.length);h+=l+m.length}f=db(f,g);a.set_state(f);a.zstd_free_ctx(e)}else{e=c(b,!0);if(0>e||e+12>=b.length)throw new ab("Invalid info block length: "+e);m=b.subarray(16,16+e);f=d(m);m=f.state;f=f.buffer_infos;let q=16+e;q=q+3&-4;e=f.map(r=> -{const x=q+r.offset;return b.buffer.slice(x,x+r.length)});m=db(m,e);a.set_state(m)}};function fb(a,b,c,d,e){let f="";var g=[],h=b?"compiled":c?"jit exit":d?"unguarded register":e?"wasm size":"executed";for(let n=0;256>n;n++)for(let p=0;8>p;p++)for(const q of[!1,!0]){var l=a.wm.exports.get_opstats_buffer(b,c,d,e,n,!1,q,p);g.push({opcode:n,count:l,is_mem:q,fixed_g:p});l=a.wm.exports.get_opstats_buffer(b,c,d,e,n,!0,q,p);g.push({opcode:3840|n,count:l,is_mem:q,fixed_g:p})}a=0;b=new Set([38,46,54,62,100,101,102,103,240,242,243]);for(const {count:n,opcode:p}of g)b.has(p)||(a+=n);if(0=== -a)return"";c=new Uint32Array(256);b=new Uint32Array(256);for(const {opcode:n,count:p}of g)3840===(n&65280)?b[n&255]+=p:c[n&255]+=p;f=f+"------------------\nTotal: "+(a+"\n");const m=1E7Math.round(n/m)));d=String(d).length;f+=`Instruction counts ${h} (in ${m}):\n`;for(e=0;256>e;e++)f+=e.toString(16).padStart(2,"0")+":"+aa(Math.round(c[e]/m),d),f=15===e%16?f+"\n":f+" ";f=f+"\n"+`Instruction counts ${h} (0f, in ${m}):\n`;for(h=0;256>h;h++)f+=(h&255).toString(16).padStart(2, -"0")+":"+aa(Math.round(b[h]/m),d),f=15===h%16?f+"\n":f+" ";f+="\n";g=g.filter(({count:n})=>n).sort(({count:n},{count:p})=>p-n);for(const {opcode:n,is_mem:p,fixed_g:q,count:r}of g.slice(0,200))g=n.toString(16)+"_"+q+(p?"_m":"_r"),f+=g+":"+(r/a*100).toFixed(2)+" ";return f+"\n"};function gb(a){this.cpu=a;this.cmos_index=0;this.cmos_data=new Uint8Array(128);this.last_update=this.rtc_time=Date.now();this.next_interrupt_alarm=this.next_interrupt=0;this.periodic_interrupt=!1;this.periodic_interrupt_time=.9765625;this.cmos_a=38;this.cmos_b=2;this.nmi_disabled=this.cmos_diag_status=this.cmos_c=0;this.update_interrupt=!1;this.update_interrupt_time=0;a.io.register_write(112,this,function(b){this.cmos_index=b&127;this.nmi_disabled=b>>7});a.io.register_write(113,this,this.cmos_port_write); -a.io.register_read(113,this,this.cmos_port_read)}gb.prototype.get_state=function(){var a=[];a[0]=this.cmos_index;a[1]=this.cmos_data;a[2]=this.rtc_time;a[3]=this.last_update;a[4]=this.next_interrupt;a[5]=this.next_interrupt_alarm;a[6]=this.periodic_interrupt;a[7]=this.periodic_interrupt_time;a[8]=this.cmos_a;a[9]=this.cmos_b;a[10]=this.cmos_c;a[11]=this.nmi_disabled;a[12]=this.update_interrupt;a[13]=this.update_interrupt_time;a[14]=this.cmos_diag_status;return a}; -gb.prototype.set_state=function(a){this.cmos_index=a[0];this.cmos_data=a[1];this.rtc_time=a[2];this.last_update=a[3];this.next_interrupt=a[4];this.next_interrupt_alarm=a[5];this.periodic_interrupt=a[6];this.periodic_interrupt_time=a[7];this.cmos_a=a[8];this.cmos_b=a[9];this.cmos_c=a[10];this.nmi_disabled=a[11];this.update_interrupt=a[12]||!1;this.update_interrupt_time=a[13]||0;this.cmos_diag_status=a[14]||0}; -gb.prototype.timer=function(a){a=Date.now();this.rtc_time+=a-this.last_update;this.last_update=a;this.periodic_interrupt&&this.next_interrupt>4&15)}; -gb.prototype.encode_time=function(a){return this.cmos_b&4?a:this.bcd_pack(a)};gb.prototype.decode_time=function(a){return this.cmos_b&4?a:this.bcd_unpack(a)}; -gb.prototype.cmos_port_read=function(){var a=this.cmos_index;switch(a){case 0:return y(this.encode_time((new Date(this.rtc_time)).getUTCSeconds())),this.encode_time((new Date(this.rtc_time)).getUTCSeconds());case 2:return y(this.encode_time((new Date(this.rtc_time)).getUTCMinutes())),this.encode_time((new Date(this.rtc_time)).getUTCMinutes());case 4:return y(this.encode_time((new Date(this.rtc_time)).getUTCHours())),this.encode_time((new Date(this.rtc_time)).getUTCHours());case 6:return y(this.encode_time((new Date(this.rtc_time)).getUTCDay()+ -1)),this.encode_time((new Date(this.rtc_time)).getUTCDay()+1);case 7:return y(this.encode_time((new Date(this.rtc_time)).getUTCDate())),this.encode_time((new Date(this.rtc_time)).getUTCDate());case 8:return y(this.encode_time((new Date(this.rtc_time)).getUTCMonth()+1)),this.encode_time((new Date(this.rtc_time)).getUTCMonth()+1);case 9:return y(this.encode_time((new Date(this.rtc_time)).getUTCFullYear()%100)),this.encode_time((new Date(this.rtc_time)).getUTCFullYear()%100);case 10:return 999<=F.microtick()% -1E3?this.cmos_a|128:this.cmos_a;case 11:return this.cmos_b;case 12:return this.cpu.device_lower_irq(8),a=this.cmos_c,this.cmos_c&=-241,a;case 13:return 128;case 14:return this.cmos_diag_status;case 50:case 55:return y(this.encode_time((new Date(this.rtc_time)).getUTCFullYear()/100|0)),this.encode_time((new Date(this.rtc_time)).getUTCFullYear()/100|0);default:return y(a),this.cmos_data[this.cmos_index]}}; -gb.prototype.cmos_port_write=function(a){switch(this.cmos_index){case 10:this.cmos_a=a&127;this.periodic_interrupt_time=1E3/(32768>>(this.cmos_a&15)-1);y(this.cmos_a,2);break;case 11:this.cmos_b=a;this.cmos_b&128&&(this.cmos_b&=239);this.cmos_b&64&&(this.next_interrupt=Date.now());if(this.cmos_b&32){a=new Date;const b=this.decode_time(this.cmos_data[1]),c=this.decode_time(this.cmos_data[3]),d=this.decode_time(this.cmos_data[5]);this.next_interrupt_alarm=+new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(), -a.getUTCDate(),d,c,b))}this.cmos_b&16&&(this.update_interrupt_time=Date.now());y(this.cmos_b,2);break;case 14:this.cmos_diag_status=a;break;case 1:case 3:case 5:this.cmos_write(this.cmos_index,a);break;default:y(this.cmos_index),y(a)}this.update_interrupt=16===(this.cmos_b&16)&&0<(this.cmos_a&15);this.periodic_interrupt=64===(this.cmos_b&64)&&0<(this.cmos_a&15)};gb.prototype.cmos_read=function(a){return this.cmos_data[a]};gb.prototype.cmos_write=function(a,b){y(a);y(b);this.cmos_data[a]=b};function hb(a,b){this.cpu=a;this.bus=b;this.counter_start_time=new Float64Array(3);this.counter_start_value=new Uint16Array(3);this.counter_next_low=new Uint8Array(4);this.counter_enabled=new Uint8Array(4);this.counter_mode=new Uint8Array(4);this.counter_read_mode=new Uint8Array(4);this.counter_latch=new Uint8Array(4);this.counter_latch_value=new Uint16Array(3);this.counter_reload=new Uint16Array(3);a.io.register_read(97,this,function(){var c=F.microtick(),d=66.66666666666667*c&1;c=this.did_rollover(2, +this,this.port_mode_write.bind(this,4));a.register_write(12,this,this.portC_write);a.register_write(216,this,this.portC_write)}M.prototype.get_state=function(){return[this.channel_page,this.channel_pagehi,this.channel_addr,this.channel_addr_init,this.channel_count,this.channel_count_init,this.channel_mask,this.channel_mode,this.lsb_msb_flipflop]}; +M.prototype.set_state=function(a){this.channel_page=a[0];this.channel_pagehi=a[1];this.channel_addr=a[2];this.channel_addr_init=a[3];this.channel_count=a[4];this.channel_count_init=a[5];this.channel_mask=a[6];this.channel_mode=a[7];this.lsb_msb_flipflop=a[8]};M.prototype.port_count_write=function(a,b){B(b);this.channel_count[a]=this.flipflop_get(this.channel_count[a],b,!1);this.channel_count_init[a]=this.flipflop_get(this.channel_count_init[a],b,!0)}; +M.prototype.port_count_read=function(a){B(this.channel_count[a]);return this.flipflop_read(this.channel_count[a])};M.prototype.port_addr_write=function(a,b){B(b);this.channel_addr[a]=this.flipflop_get(this.channel_addr[a],b,!1);this.channel_addr_init[a]=this.flipflop_get(this.channel_addr_init[a],b,!0)};M.prototype.port_addr_read=function(a){B(this.channel_addr[a]);return this.flipflop_read(this.channel_addr[a])};M.prototype.port_pagehi_write=function(a,b){B(b);this.channel_pagehi[a]=b}; +M.prototype.port_pagehi_read=function(a){return this.channel_pagehi[a]};M.prototype.port_page_write=function(a,b){B(b);this.channel_page[a]=b};M.prototype.port_page_read=function(a){return this.channel_page[a]};M.prototype.port_singlemask_write=function(a,b){this.update_mask((b&3)+a,b&4?1:0)};M.prototype.port_multimask_write=function(a,b){B(b);for(var c=0;4>c;c++)this.update_mask(a+c,b&1<a.byteLength)e(!0);else{var h=this.cpu;this.channel_addr[d]+=g;a.get(b,g,function(l){h.write_blob(l,f);e(!1)})}}; +M.prototype.do_write=function(a,b,c,d,e){var g=this.channel_count[d]+1&65535,f=5<=d?2:1,h=g*f,l=this.address_get_8bit(d),m=!1,n=!1,p=this.channel_mode[d]&16;ta("to "+B(l)+" len "+B(h),16);ch&&(n=!0);b+h>a.byteLength?e(!0):(this.channel_addr[d]+=g,this.channel_count[d]-=g,!m&&p&&(this.channel_addr[d]=this.channel_addr_init[d],this.channel_count[d]=this.channel_count_init[d]),a.set(b,this.cpu.mem8.subarray(l,l+h),()=>{n&&p?this.do_write(a,b+h,c-h,d,e):e(!1)}))}; +M.prototype.address_get_8bit=function(a){var b=this.channel_addr[a];5<=a&&(b<<=1);b=b&65535|this.channel_page[a]<<16;return b|=this.channel_pagehi[a]<<24};M.prototype.count_get_8bit=function(a){var b=this.channel_count[a]+1;5<=a&&(b*=2);return b};M.prototype.flipflop_get=function(a,b,c){c||(this.lsb_msb_flipflop^=1);return this.lsb_msb_flipflop?a&-256|b:a&-65281|b<<8};M.prototype.flipflop_read=function(a){return(this.lsb_msb_flipflop^=1)?a&255:a>>8&255};function wa(a,b){this.cpu=a;this.bus=b;this.counter_start_time=new Float64Array(3);this.counter_start_value=new Uint16Array(3);this.counter_next_low=new Uint8Array(4);this.counter_enabled=new Uint8Array(4);this.counter_mode=new Uint8Array(4);this.counter_read_mode=new Uint8Array(4);this.counter_latch=new Uint8Array(4);this.counter_latch_value=new Uint16Array(3);this.counter_reload=new Uint16Array(3);a.io.register_read(97,this,function(){var c=D.microtick(),d=66.66666666666667*c&1;c=this.did_rollover(2, c);return d<<4|c<<5});a.io.register_write(97,this,function(c){c&1?this.bus.send("pcspeaker-enable"):this.bus.send("pcspeaker-disable")});a.io.register_read(64,this,function(){return this.counter_read(0)});a.io.register_read(65,this,function(){return this.counter_read(1)});a.io.register_read(66,this,function(){return this.counter_read(2)});a.io.register_write(64,this,function(c){this.counter_write(0,c)});a.io.register_write(65,this,function(c){this.counter_write(1,c)});a.io.register_write(66,this, -function(c){this.counter_write(2,c);this.bus.send("pcspeaker-update",[this.counter_mode[2],this.counter_reload[2]])});a.io.register_write(67,this,this.port43_write)}hb.prototype.get_state=function(){var a=[];a[0]=this.counter_next_low;a[1]=this.counter_enabled;a[2]=this.counter_mode;a[3]=this.counter_read_mode;a[4]=this.counter_latch;a[5]=this.counter_latch_value;a[6]=this.counter_reload;a[7]=this.counter_start_time;a[8]=this.counter_start_value;return a}; -hb.prototype.set_state=function(a){this.counter_next_low=a[0];this.counter_enabled=a[1];this.counter_mode=a[2];this.counter_read_mode=a[3];this.counter_latch=a[4];this.counter_latch_value=a[5];this.counter_reload=a[6];this.counter_start_time=a[7];this.counter_start_value=a[8]}; -hb.prototype.timer=function(a,b){var c=100;b||(this.counter_enabled[0]&&this.did_rollover(0,a)?(this.counter_start_value[0]=this.get_counter_value(0,a),this.counter_start_time[0]=a,this.cpu.device_lower_irq(0),this.cpu.device_raise_irq(0),0===this.counter_mode[0]&&(this.counter_enabled[0]=0)):this.cpu.device_lower_irq(0),this.counter_enabled[0]&&(c=(this.counter_start_value[0]-Math.floor(1193.1816666*(a-this.counter_start_time[0])))/1193.1816666));return c}; -hb.prototype.get_counter_value=function(a,b){if(!this.counter_enabled[a])return 0;b=this.counter_start_value[a]-Math.floor(1193.1816666*(b-this.counter_start_time[a]));a=this.counter_reload[a];b>=a?b%=a:0>b&&(b=b%a+a);return b};hb.prototype.did_rollover=function(a,b){b-=this.counter_start_time[a];return 0>b?!0:this.counter_start_value[a]>8;b=this.counter_next_low[a];3===this.counter_mode[a]&&(this.counter_next_low[a]^=1);a=this.get_counter_value(a,F.microtick());return b?a&255:a>>8}; -hb.prototype.counter_write=function(a,b){this.counter_reload[a]=this.counter_next_low[a]?this.counter_reload[a]&-256|b:this.counter_reload[a]&255|b<<8;3===this.counter_read_mode[a]&&this.counter_next_low[a]||(this.counter_reload[a]||(this.counter_reload[a]=65535),this.counter_start_value[a]=this.counter_reload[a],this.counter_enabled[a]=!0,this.counter_start_time[a]=F.microtick(),y(this.counter_reload[a]));3===this.counter_read_mode[a]&&(this.counter_next_low[a]^=1)}; -hb.prototype.port43_write=function(a){var b=a>>1&7,c=a>>6&3;a=a>>4&3;3!==c&&(0===a?(this.counter_latch[c]=2,b=this.get_counter_value(c,F.microtick()),this.counter_latch_value[c]=b?b-1:0):(6<=b&&(b&=-5),this.counter_next_low[c]=1===a?1:2===a?0:1,0===c&&this.cpu.device_lower_irq(0),0!==b&&3!==b&&2!==b&&y(b),this.counter_mode[c]=b,this.counter_read_mode[c]=a,2===c&&this.bus.send("pcspeaker-update",[this.counter_mode[2],this.counter_reload[2]])))};hb.prototype.dump=function(){};function ib(a){if("undefined"!==typeof window)if(window.AudioContext||window.webkitAudioContext){var b=window.AudioWorklet?jb:kb;this.bus=a;this.audio_context=window.AudioContext?new AudioContext:new webkitAudioContext;this.mixer=new lb(a,this.audio_context);this.pcspeaker=new mb(a,this.audio_context,this.mixer);this.dac=new b(a,this.audio_context,this.mixer);this.pcspeaker.start();a.register("emulator-stopped",function(){this.audio_context.suspend()},this);a.register("emulator-started",function(){this.audio_context.resume()}, -this);a.register("speaker-confirm-initialized",function(){a.send("speaker-has-initialized")},this);a.send("speaker-has-initialized")}else console.warn("Web browser doesn't support Web Audio API")}ib.prototype.destroy=function(){this.audio_context&&this.audio_context.close();this.audio_context=null;this.dac&&this.dac.node_processor&&this.dac.node_processor.port.close();this.dac=null}; -function lb(a,b){function c(d){return function(e){d.gain.setValueAtTime(e,this.audio_context.currentTime)}}this.audio_context=b;this.sources=new Map;this.gain_right=this.gain_left=this.volume_right=this.volume_left=this.volume_both=1;this.node_treble_left=this.audio_context.createBiquadFilter();this.node_treble_right=this.audio_context.createBiquadFilter();this.node_treble_left.type="highshelf";this.node_treble_right.type="highshelf";this.node_treble_left.frequency.setValueAtTime(2E3,this.audio_context.currentTime); -this.node_treble_right.frequency.setValueAtTime(2E3,this.audio_context.currentTime);this.node_bass_left=this.audio_context.createBiquadFilter();this.node_bass_right=this.audio_context.createBiquadFilter();this.node_bass_left.type="lowshelf";this.node_bass_right.type="lowshelf";this.node_bass_left.frequency.setValueAtTime(200,this.audio_context.currentTime);this.node_bass_right.frequency.setValueAtTime(200,this.audio_context.currentTime);this.node_gain_left=this.audio_context.createGain();this.node_gain_right= -this.audio_context.createGain();this.node_merger=this.audio_context.createChannelMerger(2);this.input_left=this.node_treble_left;this.input_right=this.node_treble_right;this.node_treble_left.connect(this.node_bass_left);this.node_bass_left.connect(this.node_gain_left);this.node_gain_left.connect(this.node_merger,0,0);this.node_treble_right.connect(this.node_bass_right);this.node_bass_right.connect(this.node_gain_right);this.node_gain_right.connect(this.node_merger,0,1);this.node_merger.connect(this.audio_context.destination); -a.register("mixer-connect",function(d){this.connect_source(d[0],d[1])},this);a.register("mixer-disconnect",function(d){this.disconnect_source(d[0],d[1])},this);a.register("mixer-volume",function(d){var e=d[0],f=d[1];d=Math.pow(10,d[2]/20);e=0===e?this:this.sources.get(e);void 0===e||e.set_volume(d,f)},this);a.register("mixer-gain-left",function(d){this.gain_left=Math.pow(10,d/20);this.update()},this);a.register("mixer-gain-right",function(d){this.gain_right=Math.pow(10,d/20);this.update()},this); -a.register("mixer-treble-left",c(this.node_treble_left),this);a.register("mixer-treble-right",c(this.node_treble_right),this);a.register("mixer-bass-left",c(this.node_bass_left),this);a.register("mixer-bass-right",c(this.node_bass_right),this)}lb.prototype.add_source=function(a,b){a=new nb(this.audio_context,a,this.input_left,this.input_right);this.sources.has(b);this.sources.set(b,a);return a};lb.prototype.connect_source=function(a,b){a=this.sources.get(a);void 0===a||a.connect(b)}; -lb.prototype.disconnect_source=function(a,b){a=this.sources.get(a);void 0===a||a.disconnect(b)};lb.prototype.set_volume=function(a,b){void 0===b&&(b=2);switch(b){case 0:this.volume_left=a;break;case 1:this.volume_right=a;break;case 2:this.volume_both=a;break;default:return}this.update()}; -lb.prototype.update=function(){var a=this.volume_both*this.volume_right*this.gain_right;this.node_gain_left.gain.setValueAtTime(this.volume_both*this.volume_left*this.gain_left,this.audio_context.currentTime);this.node_gain_right.gain.setValueAtTime(a,this.audio_context.currentTime)}; -function nb(a,b,c,d){this.audio_context=a;this.connected_right=this.connected_left=!0;this.volume_right=this.volume_left=this.volume_both=this.gain_hidden=1;this.node_splitter=a.createChannelSplitter(2);this.node_gain_left=a.createGain();this.node_gain_right=a.createGain();b.connect(this.node_splitter);this.node_splitter.connect(this.node_gain_left,0);this.node_gain_left.connect(c);this.node_splitter.connect(this.node_gain_right,1);this.node_gain_right.connect(d)} -nb.prototype.update=function(){var a=this.connected_right*this.gain_hidden*this.volume_both*this.volume_right;this.node_gain_left.gain.setValueAtTime(this.connected_left*this.gain_hidden*this.volume_both*this.volume_left,this.audio_context.currentTime);this.node_gain_right.gain.setValueAtTime(a,this.audio_context.currentTime)};nb.prototype.connect=function(a){var b=!a||2===a;if(b||0===a)this.connected_left=!0;if(b||1===a)this.connected_right=!0;this.update()}; -nb.prototype.disconnect=function(a){var b=!a||2===a;if(b||0===a)this.connected_left=!1;if(b||1===a)this.connected_right=!1;this.update()};nb.prototype.set_volume=function(a,b){void 0===b&&(b=2);switch(b){case 0:this.volume_left=a;break;case 1:this.volume_right=a;break;case 2:this.volume_both=a;break;default:return}this.update()};nb.prototype.set_gain_hidden=function(a){this.gain_hidden=a}; -function mb(a,b,c){this.node_oscillator=b.createOscillator();this.node_oscillator.type="square";this.node_oscillator.frequency.setValueAtTime(440,b.currentTime);this.mixer_connection=c.add_source(this.node_oscillator,1);this.mixer_connection.disconnect();a.register("pcspeaker-enable",function(){c.connect_source(1)},this);a.register("pcspeaker-disable",function(){c.disconnect_source(1)},this);a.register("pcspeaker-update",function(d){var e=d[1],f=0;3===d[0]&&(f=Math.min(1193181.6665999999/e,this.node_oscillator.frequency.maxValue), -f=Math.max(f,0));this.node_oscillator.frequency.setValueAtTime(f,b.currentTime)},this)}mb.prototype.start=function(){this.node_oscillator.start()}; -function jb(a,b,c){this.bus=a;this.audio_context=b;this.enabled=!1;this.sampling_rate=48E3;b=function(){function g(m){if(0===m)return 1;m*=Math.PI;return Math.sin(m)/m}function h(){var m=Reflect.construct(AudioWorkletProcessor,[],h);m.kernel_size=3;m.queue_data=Array(1024);m.queue_start=0;m.queue_end=0;m.queue_length=0;m.queue_size=m.queue_data.length;m.queued_samples=0;m.source_buffer_previous=l;m.source_buffer_current=l;m.source_samples_per_destination=1;m.source_block_start=0;m.source_time=0;m.source_offset= -0;m.port.onmessage=n=>{switch(n.data.type){case "queue":m.queue_push(n.data.value);break;case "sampling-rate":m.source_samples_per_destination=n.data.value/sampleRate}};return m}var l=[new Float32Array(256),new Float32Array(256)];Reflect.setPrototypeOf(h.prototype,AudioWorkletProcessor.prototype);Reflect.setPrototypeOf(h,AudioWorkletProcessor);h.prototype.process=h.prototype.process=function(m,n){for(m=0;mm?(m+=this.source_buffer_previous[0].length,this.source_buffer_previous[n][m]):this.source_buffer_current[n][m]};h.prototype.ensure_enough_data=function(m){var n=this.source_buffer_current[0].length;n-this.source_block_start -this.queued_samples&&this.queue_length&&this.dbg_log("Not enough samples - should not happen during midway of playback");this.source_buffer_previous=this.source_buffer_current;this.source_buffer_current=this.queue_shift();var m=this.source_buffer_current[0].length;if(256>m){for(var n=this.queue_start,p=0;256>m&&pthis.queued_samples/this.source_samples_per_destination&&this.port.postMessage({type:"pump"})};h.prototype.queue_push=function(m){this.queue_length{URL.revokeObjectURL(f);this.node_processor=new AudioWorkletNode(this.audio_context,"dac-processor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2],parameterData:{},processorOptions:{}});this.node_processor.port.postMessage({type:"sampling-rate",value:this.sampling_rate});this.node_processor.port.onmessage=g=>{switch(g.data.type){case "pump":this.pump()}};this.node_processor.connect(this.node_output)}); -this.mixer_connection=c.add_source(this.node_output,2);this.mixer_connection.set_gain_hidden(3);a.register("dac-send-data",function(g){this.queue(g)},this);a.register("dac-enable",function(){this.enabled=!0},this);a.register("dac-disable",function(){this.enabled=!1},this);a.register("dac-tell-sampling-rate",function(g){this.sampling_rate=g;this.node_processor&&this.node_processor.port.postMessage({type:"sampling-rate",value:g})},this)} -jb.prototype.queue=function(a){this.node_processor&&this.node_processor.port.postMessage({type:"queue",value:a},[a[0].buffer,a[1].buffer])};jb.prototype.pump=function(){this.enabled&&this.bus.send("dac-request-data")}; -function kb(a,b,c){this.bus=a;this.audio_context=b;this.enabled=!1;this.sampling_rate=22050;this.buffered_time=0;this.rate_ratio=1;this.node_lowpass=this.audio_context.createBiquadFilter();this.node_lowpass.type="lowpass";this.node_output=this.node_lowpass;this.mixer_connection=c.add_source(this.node_output,2);this.mixer_connection.set_gain_hidden(3);a.register("dac-send-data",function(d){this.queue(d)},this);a.register("dac-enable",function(){this.enabled=!0;this.pump()},this);a.register("dac-disable", -function(){this.enabled=!1},this);a.register("dac-tell-sampling-rate",function(d){this.sampling_rate=d;this.rate_ratio=Math.ceil(8E3/d);this.node_lowpass.frequency.setValueAtTime(d/2,this.audio_context.currentTime)},this)} -kb.prototype.queue=function(a){var b=a[0].length,c=b/this.sampling_rate;if(1this.pump(),1E3*b);a.start(this.buffered_time);this.buffered_time+=c;setTimeout(()=>this.pump(),0)};kb.prototype.pump=function(){this.enabled&&(.2a)){this.last_connect_attempt=Date.now();try{this.socket=new WebSocket(this.url)}catch(b){console.error(b);return}this.socket.binaryType="arraybuffer";this.socket.onopen=this.handle_open.bind(this);this.socket.onmessage=this.handle_message.bind(this);this.socket.onclose=this.handle_close.bind(this); -this.socket.onerror=this.handle_error.bind(this)}}};ob.prototype.send=function(a){this.socket&&1===this.socket.readyState?this.socket.send(a):(this.send_queue.push(a),this.send_queue.length>2*this.send_queue_limit&&(this.send_queue=this.send_queue.slice(-this.send_queue_limit)),this.connect())};ob.prototype.change_proxy=function(a){this.url=a;this.socket&&(this.socket.onclose=function(){},this.socket.onerror=function(){},this.socket.close(),this.socket=void 0)};const pb=(new Date("1970-01-01T00:00:00Z")).getTime(),qb=(new Date("1900-01-01T00:00:00Z")).getTime(),rb=pb-qb,wb=Math.pow(2,32),xb=[118,56,54];function yb(a){return[0,1,2,3,4,5].map(b=>a[b].toString(16)).map(b=>1===b.length?"0"+b:b).join(":")}function zb(a){return a[0]<<24|a[1]<<16|a[2]<<8|a[3]} -class Ab{constructor(a,b){a=Math.min(a,16);this.maximum_capacity=b?Math.max(b,a):0;this.length=this.head=this.tail=0;this.buffer=new Uint8Array(a)}write(a){const b=a.length;var c=this.length+b;let d=this.buffer.length;if(dthis.maximum_capacity)throw Error("stream capacity overflow in GrowableRingbuffer.write(), package dropped");c=new Uint8Array(d);this.peek(c);this.tail=0;this.head=this.length;this.buffer=c}c=this.buffer;const e=this.head+b;if(e>d){const f= -d-this.head;c.set(a.subarray(0,f),this.head);c.set(a.subarray(f))}else c.set(a,this.head);this.head=e%d;this.length+=b}peek(a){const b=Math.min(this.length,a.length);if(b){const e=this.buffer;var c=e.length,d=this.tail+b;d>c?(d%=c,c-=this.tail,a.set(e.subarray(this.tail)),a.set(e.subarray(0,d),c)):a.set(e.subarray(this.tail,d))}return b}remove(a){a>this.length&&(a=this.length);a&&(this.tail=(this.tail+a)%this.buffer.length,this.length-=a);return a}} -function Bb(a=1500){const b=a-20,c=b-8,d=new Uint8Array(14+a+4),e=d.buffer,f=d.byteOffset;return{eth_frame:d,eth_frame_view:new DataView(e),eth_payload_view:new DataView(e,f+14,a),ipv4_payload_view:new DataView(e,f+34,b),udp_payload_view:new DataView(e,f+42,c),text_encoder:new TextEncoder}}function Cb(a,b,c,d){d.eth_frame.set(b,c.byteOffset+a);return b.length} -function Db(a,b,c,d){const e=c.byteOffset+(a&-2);d=d.eth_frame;for(c=c.byteOffset;c>>16;)b=(b&65535)+(b>>>16);return~b&65535} -function Eb(a,b){a.eth_frame.fill(0);var c=a.eth_frame,d=c.subarray,e=a.eth_frame_view;Cb(0,b.eth.dest,e,a);Cb(6,b.eth.src,e,a);e.setUint16(12,b.eth.ethertype);e=14;if(b.arp){var f=a.eth_payload_view;f.setUint16(0,b.arp.htype);f.setUint16(2,b.arp.ptype);f.setUint8(4,b.arp.sha.length);f.setUint8(5,b.arp.spa.length);f.setUint16(6,b.arp.oper);Cb(8,b.arp.sha,f,a);Cb(14,b.arp.spa,f,a);Cb(18,b.arp.tha,f,a);Cb(24,b.arp.tpa,f,a);e+=28}else if(b.ipv4){f=a.eth_payload_view;var g=20;if(b.icmp){var h=a.ipv4_payload_view; -h.setUint8(0,b.icmp.type);h.setUint8(1,b.icmp.code);h.setUint16(2,0);var l=4+Cb(4,b.icmp.data,h,a);h.setUint16(2,Db(l,0,h,a));g+=l}else if(b.udp){h=a.ipv4_payload_view;var m=8;if(b.dhcp){l=m;var n=a.udp_payload_view;n.setUint8(0,b.dhcp.op);n.setUint8(1,b.dhcp.htype);n.setUint8(2,b.dhcp.hlen);n.setUint8(3,b.dhcp.hops);n.setUint32(4,b.dhcp.xid);n.setUint16(8,b.dhcp.secs);n.setUint16(10,b.dhcp.flags);n.setUint32(12,b.dhcp.ciaddr);n.setUint32(16,b.dhcp.yiaddr);n.setUint32(20,b.dhcp.siaddr);n.setUint32(24, -b.dhcp.giaddr);Cb(28,b.dhcp.chaddr,n,a);n.setUint32(236,1669485411);m=240;for(var p of b.dhcp.options)m+=Cb(m,p,n,a);l+=m}else if(b.dns){p=m;m=a.udp_payload_view;m.setUint16(0,b.dns.id);m.setUint16(2,b.dns.flags);m.setUint16(4,b.dns.questions.length);m.setUint16(6,b.dns.answers.length);let x=12;for(var q=0;q>2<<4),h.setUint8(13,l),h.setUint16(14,n.winsize),h.setUint16(16,0),h.setUint16(18,n.urgent||0),b.tcp_data&&(m+=Cb(20,b.tcp_data,h,a)),h.setUint16(16,Db(m,(b.ipv4.src[0]<<8|b.ipv4.src[1])+(b.ipv4.src[2]<<8|b.ipv4.src[3])+(b.ipv4.dest[0]<<8|b.ipv4.dest[1])+(b.ipv4.dest[2]<<8|b.ipv4.dest[3])+6+m,h,a)),g+=m);f.setUint8(0,69);f.setUint8(1,b.ipv4.tos||0);f.setUint16(2,g);f.setUint16(4,b.ipv4.id|| -0);f.setUint8(6,64);f.setUint8(8,b.ipv4.ttl||32);f.setUint8(9,b.ipv4.proto);f.setUint16(10,0);Cb(12,b.ipv4.src,f,a);Cb(16,b.ipv4.dest,f,a);f.setUint16(10,Db(20,0,f,a));e+=g}return d.call(c,0,e)} -function Fb(a,b){fetch(`https://${b.doh_server||"cloudflare-dns.com"}/dns-query`,{method:"POST",headers:[["content-type","application/dns-message"]],body:a.udp.data}).then(async c=>{c={eth:{ethertype:2048,src:b.router_mac,dest:a.eth.src},ipv4:{proto:17,src:b.router_ip,dest:a.ipv4.src},udp:{sport:53,dport:a.udp.sport,data:new Uint8Array(await c.arrayBuffer())}};b.receive(Eb(b.eth_encoder_buf,c))});return!0} -function Gb(a,b){let c={};c.eth={ethertype:2048,src:b.router_mac,dest:a.eth.src};c.ipv4={proto:17,src:b.router_ip,dest:b.vm_ip};c.udp={sport:67,dport:68};c.dhcp={htype:1,hlen:6,hops:0,xid:a.dhcp.xid,secs:0,flags:0,ciaddr:0,yiaddr:zb(b.vm_ip),siaddr:zb(b.router_ip),giaddr:zb(b.router_ip),chaddr:a.dhcp.chaddr};let d=[],e=a.dhcp.options.find(function(f){return 53===f[0]});e&&3===e[2]&&(a.dhcp.op=3);1===a.dhcp.op&&(c.dhcp.op=2,d.push(new Uint8Array([53,1,2])));3===a.dhcp.op&&(c.dhcp.op=2,d.push(new Uint8Array([53, -1,5])),d.push(new Uint8Array([51,4,8,0,0,0])));a=[b.router_ip[0],b.router_ip[1],b.router_ip[2],b.router_ip[3]];d.push(new Uint8Array([1,4,255,255,255,0]));b.masquerade&&(d.push(new Uint8Array([3,4].concat(a))),d.push(new Uint8Array([6,4].concat(a))));d.push(new Uint8Array([54,4].concat(a)));d.push(new Uint8Array([60,3].concat(xb)));d.push(new Uint8Array([255,0]));c.dhcp.options=d;b.receive(Eb(b.eth_encoder_buf,c))} -function Hb(a,b){let c={};var d=(new DataView(a.buffer,a.byteOffset,a.byteLength)).getUint16(12),e={ethertype:d,dest:a.subarray(0,6),dest_s:yb(a.subarray(0,6)),src:a.subarray(6,12),src_s:yb(a.subarray(6,12))};c.eth=e;a=a.subarray(14,a.length);if(2048===d){var f=new DataView(a.buffer,a.byteOffset,a.byteLength),g=a[0]>>4&15;e=a[0]&15;var h=f.getUint8(1),l=f.getUint16(2);let m=f.getUint8(8);d=f.getUint8(9);f=f.getUint16(10);g={version:g,ihl:e,tos:h,len:l,ttl:m,proto:d,ip_checksum:f,src:a.subarray(12, -16),dest:a.subarray(16,20)};c.ipv4=g;e=a.subarray(4*e,l);if(1===d)a=new DataView(e.buffer,e.byteOffset,e.byteLength),a={type:a.getUint8(0),code:a.getUint8(1),checksum:a.getUint16(2),data:e.subarray(4)},c.icmp=a;else if(6===d)d=new DataView(e.buffer,e.byteOffset,e.byteLength),a={sport:d.getUint16(0),dport:d.getUint16(2),seq:d.getUint32(4),ackn:d.getUint32(8),doff:d.getUint8(12)>>4,winsize:d.getUint16(14),checksum:d.getUint16(16),urgent:d.getUint16(18)},d=d.getUint8(13),a.fin=!!(d&1),a.syn=!!(d&2), -a.rst=!!(d&4),a.psh=!!(d&8),a.ack=!!(d&16),a.urg=!!(d&32),a.ece=!!(d&64),a.cwr=!!(d&128),c.tcp=a,c.tcp_data=e.subarray(4*a.doff);else if(17===d){a=new DataView(e.buffer,e.byteOffset,e.byteLength);a={sport:a.getUint16(0),dport:a.getUint16(2),len:a.getUint16(4),checksum:a.getUint16(6),data:e.subarray(8),data_s:(new TextDecoder).decode(e.subarray(8))};if(67===a.dport||67===a.sport){e=e.subarray(8);d=new DataView(e.buffer,e.byteOffset,e.byteLength);e.subarray(44,236);d={op:d.getUint8(0),htype:d.getUint8(1), -hlen:d.getUint8(2),hops:d.getUint8(3),xid:d.getUint32(4),secs:d.getUint16(8),flags:d.getUint16(10),ciaddr:d.getUint32(12),yiaddr:d.getUint32(16),siaddr:d.getUint32(20),giaddr:d.getUint32(24),chaddr:e.subarray(28,44),magic:d.getUint32(236),options:[]};e=e.subarray(240);for(l=0;l++h&&b.tcp_conn[g]);if(b.tcp_conn[g])throw Error("pool of dynamic TCP port numbers exhausted, connection aborted");c=new Jb(b);c.tuple=g;c.hsrc=b.router_mac;c.psrc=b.router_ip;c.sport=f;c.hdest=b.vm_mac;c.dport=a;c.pdest=b.vm_ip;b.tcp_conn[g]=c;c.connect();return c} -function Ub(a,b){return new Promise(c=>{let d=Tb(a,b);d.state="syn-probe";d.on("probe",c)})}function Jb(a){this.mtu=a.mtu||1500;const b=this.mtu-20-20;this.state="closed";this.net=a;this.send_buffer=new Ab(2048,0);this.send_chunk_buf=new Uint8Array(b);this.delayed_send_fin=this.in_active_close=!1;this.delayed_state=void 0;this.events_handlers={}}Jb.prototype.on=function(a,b){this.events_handlers[a]=b};Jb.prototype.emit=function(a,...b){this.events_handlers[a]&&this.events_handlers[a].apply(this,b)}; -Jb.prototype.ipv4_reply=function(){let a={};a.eth={ethertype:2048,src:this.hsrc,dest:this.hdest};a.ipv4={proto:6,src:this.psrc,dest:this.pdest};a.tcp={sport:this.sport,dport:this.dport,winsize:this.winsize,ackn:this.ack,seq:this.seq,ack:!0};return a};Jb.prototype.packet_reply=function(a,b){a={sport:a.tcp.dport,dport:a.tcp.sport,winsize:a.tcp.winsize,ackn:this.ack,seq:this.seq};if(b)for(const c in b)a[c]=b[c];b=this.ipv4_reply();b.tcp=a;return b}; -Jb.prototype.connect=function(){this.seq=1338;this.ack=1;this.start_seq=0;this.winsize=64240;"syn-probe"!==this.state&&(this.state="syn-sent");let a=this.ipv4_reply();a.ipv4.id=2345;a.tcp={sport:this.sport,dport:this.dport,seq:1337,ackn:0,winsize:0,syn:!0};this.net.receive(Eb(this.net.eth_encoder_buf,a))}; -Jb.prototype.accept=function(a){a=a||this.last;this.net.tcp_conn[this.tuple]=this;this.seq=1338;this.ack=a.tcp.seq+1;this.start_seq=a.tcp.seq;this.winsize=a.tcp.winsize;let b=this.ipv4_reply();b.tcp={sport:this.sport,dport:this.dport,seq:1337,ackn:this.ack,winsize:a.tcp.winsize,syn:!0,ack:!0,options:{mss:this.mtu-20-20}};this.state="established";this.net.receive(Eb(this.net.eth_encoder_buf,b))}; -Jb.prototype.process=function(a){this.last=a;if("closed"===this.state)a=this.packet_reply(a,{rst:!0}),this.net.receive(Eb(this.net.eth_encoder_buf,a));else if(a.tcp.rst){if("syn-probe"===this.state)this.emit("probe",!1);else this.on_close();this.release()}else if(a.tcp.syn)"syn-sent"===this.state&&a.tcp.ack?(this.ack=a.tcp.seq+1,this.start_seq=a.tcp.seq,this.last_received_ackn=a.tcp.ackn,a=this.ipv4_reply(),this.net.receive(Eb(this.net.eth_encoder_buf,a)),this.state="established",this.emit("connect")): -"syn-probe"===this.state&&a.tcp.ack&&(this.emit("probe",!0),a=this.packet_reply(a,{rst:!0}),this.net.receive(Eb(this.net.eth_encoder_buf,a)),this.release());else{if(a.tcp.ack)if("syn-received"===this.state)this.state="established";else if("fin-wait-1"===this.state)a.tcp.fin||(this.state="fin-wait-2");else if("closing"===this.state||"last-ack"===this.state){this.release();return}if(void 0===this.last_received_ackn)this.last_received_ackn=a.tcp.ackn;else{var b=a.tcp.ackn-this.last_received_ackn;if(0< -b){if(this.last_received_ackn=a.tcp.ackn,this.send_buffer.remove(b),this.seq+=b,this.pending=!1,this.delayed_send_fin&&!this.send_buffer.length){this.delayed_send_fin=!1;this.state=this.delayed_state;a=this.ipv4_reply();a.tcp.fin=!0;this.net.receive(Eb(this.net.eth_encoder_buf,a));return}}else if(0>b){a=this.packet_reply(a,{rst:!0});this.net.receive(Eb(this.net.eth_encoder_buf,a));this.on_close();this.release();return}}a.tcp.fin?(++this.ack,b=this.packet_reply(a,{}),"established"===this.state?(b.tcp.ack= -!0,this.state="close-wait",this.on_shutdown()):"fin-wait-1"===this.state?(a.tcp.ack?this.release():this.state="closing",b.tcp.ack=!0):"fin-wait-2"===this.state?(this.release(),b.tcp.ack=!0):(this.release(),this.on_close(),b.tcp.rst=!0),this.net.receive(Eb(this.net.eth_encoder_buf,b))):this.ack!==a.tcp.seq?(a=this.packet_reply(a,{ack:!0}),this.net.receive(Eb(this.net.eth_encoder_buf,a))):a.tcp.ack&&0fetch(...c);this.cors_proxy=b.cors_proxy;this.bus.register("net"+this.id+"-mac",function(c){this.vm_mac=new Uint8Array(c.split(":").map(function(d){return parseInt(d,16)}))},this);this.bus.register("net"+this.id+"-send",function(c){this.send(c)},this);this.bus.register("tcp-connection",c=>{80===c.sport&&(c.on("data",Wb),c.accept())},this)}Vb.prototype.destroy=function(){}; -Vb.prototype.connect=function(a){return Tb(a,this)};Vb.prototype.tcp_probe=function(a){return Ub(a,this)}; -async function Wb(a){this.read=this.read||"";if((this.read+=(new TextDecoder).decode(a))&&-1!==this.read.indexOf("\r\n\r\n")){a=this.read.indexOf("\r\n\r\n");var b=this.read.substring(0,a).split(/\r\n/);a=this.read.substring(a+4);this.read="";let c=b[0].split(" "),d;d=/^https?:/.test(c[1])?new URL(c[1]):new URL("http://host"+c[1]);"undefined"!==typeof window&&"http:"===d.protocol&&"https:"===window.location.protocol&&(d.protocol="https:");let e=new Headers;for(let h=1;hb)d.protocol="http:",d.hostname="localhost",d.port=b.toString(10);else{console.warn('Unknown port for localhost: "%s"',d.href);this.net.respond_text_and_close(this, -400,"Bad Request",`Unknown port for localhost: ${d.href}`);return}this.name=d.href;b={method:c[0],headers:e};-1!==["put","post"].indexOf(b.method.toLowerCase())&&(b.body=a);const f=this.net.cors_proxy?this.net.cors_proxy+encodeURIComponent(d.href):d.href;new TextEncoder;let g=!1;this.net.fetch(f,b).then(h=>{let l=new Headers(h.headers);l.delete("content-encoding");l.delete("keep-alive");l.delete("content-length");l.delete("transfer-encoding");l.set("x-was-fetch-redirected",`${!!h.redirected}`);l.set("x-fetch-resp-url", -h.url);l.set("connection","close");this.write(this.net.form_response_head(h.status,h.statusText,l));g=!0;if(h.body&&h.body.getReader){const m=h.body.getReader(),n=({value:p,done:q})=>{p&&this.write(p);if(q)this.close();else return m.read().then(n)};m.read().then(n)}else h.arrayBuffer().then(m=>{this.write(new Uint8Array(m));this.close()})}).catch(h=>{console.warn("Fetch Failed: "+f+"\n"+h);g||this.net.respond_text_and_close(this,502,"Fetch Error",`Fetch ${f} failed:\n\n${h.stack||h.message}`);this.close()})}} -Vb.prototype.fetch=async function(a,b){this.cors_proxy&&(a=this.cors_proxy+encodeURIComponent(a));try{const c=await fetch(a,b),d=await c.arrayBuffer();return[c,d]}catch(c){return console.warn("Fetch Failed: "+a+"\n"+c),[{status:502,statusText:"Fetch Error",headers:new Headers({"Content-Type":"text/plain"})},(new TextEncoder).encode(`Fetch ${a} failed:\n\n${c.stack}`).buffer]}}; -Vb.prototype.form_response_head=function(a,b,c){a=[`HTTP/1.1 ${a} ${b}`];for(const [d,e]of c.entries())a.push(`${d}: ${e}`);return(new TextEncoder).encode(a.join("\r\n")+"\r\n\r\n")};Vb.prototype.respond_text_and_close=function(a,b,c,d){const e=new Headers({"content-type":"text/plain","content-length":d.length.toString(10),connection:"close"});a.writev([this.form_response_head(b,c,e),(new TextEncoder).encode(d)]);a.close()}; -Vb.prototype.parse_http_header=function(a){var b=a.match(/^([^:]*):(.*)$/);if(b&&(a=b[1],b=b[2].trim(),0!==a.length&&0!==b.length&&/^[\w-]+$/.test(a)&&/^[\x20-\x7E]+$/.test(b)))return{key:a,value:b}};Vb.prototype.send=function(a){Hb(a,this)};Vb.prototype.receive=function(a){this.bus.send("net"+this.id+"-receive",new Uint8Array(a))};function Xb(a,b,c){this.register_ws(a);this.last_stream=1;this.connections={0:{congestion:0}};this.congested_buffer=[];c=c||{};this.bus=b;this.id=c.id||0;this.router_mac=new Uint8Array((c.router_mac||"52:54:0:1:2:3").split(":").map(function(d){return parseInt(d,16)}));this.router_ip=new Uint8Array((c.router_ip||"192.168.86.1").split(".").map(function(d){return parseInt(d,10)}));this.vm_ip=new Uint8Array((c.vm_ip||"192.168.86.100").split(".").map(function(d){return parseInt(d,10)}));this.masquerade= -void 0===c.masquerade||!!c.masquerade;this.vm_mac=new Uint8Array(6);this.dns_method=c.dns_method||"doh";this.doh_server=c.doh_server;this.tcp_conn={};this.mtu=c.mtu;this.eth_encoder_buf=Bb(this.mtu);this.bus.register("net"+this.id+"-mac",function(d){this.vm_mac=new Uint8Array(d.split(":").map(function(e){return parseInt(e,16)}))},this);this.bus.register("net"+this.id+"-send",function(d){this.send(d)},this)} -Xb.prototype.register_ws=function(a){this.wispws=new WebSocket(a.replace("wisp://","ws://").replace("wisps://","wss://"));this.wispws.binaryType="arraybuffer";this.wispws.onmessage=b=>{this.process_incoming_wisp_frame(new Uint8Array(b.data))};this.wispws.onclose=()=>{setTimeout(()=>{this.register_ws(a)},1E4)}}; -Xb.prototype.send_packet=function(a,b,c){this.connections[c]&&(0{0!==c.length&&this.send_wisp_frame({type:"DATA",stream_id:a.stream_id,data:c})});a.on_close=()=>{this.send_wisp_frame({type:"CLOSE",stream_id:a.stream_id,reason:2})};a.on_shutdown=a.on_close;this.send_wisp_frame({type:"CONNECT",stream_id:a.stream_id,hostname:b.ipv4.dest.join("."),port:a.sport,data_callback:c=>{a.write(c)},close_callback:()=>{a.close()}});a.accept();return!0}; -Xb.prototype.send=function(a){Hb(a,this)};Xb.prototype.receive=function(a){this.bus.send("net"+this.id+"-receive",new Uint8Array(a))};const Yb="undefined"!==typeof window&&0<=window.navigator.platform.toString().toLowerCase().search("win"); -function Zb(a){function b(v){return v.shiftKey&&v.ctrlKey&&(73===v.keyCode||74===v.keyCode||75===v.keyCode)||!x.emu_enabled?!1:v.target?v.target.classList.contains("phone_keyboard")||"INPUT"!==v.target.nodeName&&"TEXTAREA"!==v.target.nodeName:!0}function c(v){!v.altKey&&n[56]&&l(56,!1);return g(v,!1)}function d(v){!v.altKey&&n[56]&&l(56,!1);return g(v,!0)}function e(){for(var v=Object.keys(n),L,T=0;T{h(p, -q);p=null},10),!1;h(v,L);return!1}}function h(v,L){a:{if(void 0!==v.code){var T=M[v.code];if(void 0!==T)break a}T=C[v.keyCode]}T?l(T,L,v.repeat):console.log("Missing char in map: keyCode="+(v.keyCode||-1).toString(16)+" code="+v.code)}function l(v,L,T){if(L)n[v]&&!T&&l(v,!1);else if(!n[v])return;(n[v]=L)||(v|=128);255>8),m(v&255)):m(v)}function m(v){x.bus.send("keyboard-code",v)}var n={},p=null,q=!1,r=0,x=this;this.emu_enabled=!0;const C=new Uint16Array([0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0, -42,29,56,0,58,0,0,0,0,0,0,1,0,0,0,0,57,57417,57425,57423,57415,57419,57416,57421,80,0,0,0,0,82,83,0,11,2,3,4,5,6,7,8,9,10,0,39,0,13,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,19,31,20,22,47,17,45,21,44,57435,57436,57437,0,0,82,79,80,81,75,76,77,71,72,73,0,0,0,0,0,0,59,60,61,62,63,64,65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,69,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, -0,0,0,0,0,0,0,26,43,27,40,0,57435,57400,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),t={8:8,10:13,32:32,39:222,44:188,45:189,46:190,47:191,48:48,49:49,50:50,51:51,52:52,53:53,54:54,55:55,56:56,57:57,59:186,61:187,91:219,92:220,93:221,96:192,97:65,98:66,99:67,100:68,101:69,102:70,103:71,104:72,105:73,106:74,107:75,108:76,109:77,110:78,111:79,112:80,113:81,114:82,115:83,116:84,117:85,118:86,119:87,120:88,121:89,122:90},A={33:49,34:222,35:51,36:52,37:53,38:55,40:57,41:48,42:56,43:187,58:186,60:188,62:190,63:191,64:50, -65:65,66:66,67:67,68:68,69:69,70:70,71:71,72:72,73:73,74:74,75:75,76:76,77:77,78:78,79:79,80:80,81:81,82:82,83:83,84:84,85:85,86:86,87:87,88:88,89:89,90:90,94:54,95:189,123:219,124:220,125:221,126:192};var M={Escape:1,Digit1:2,Digit2:3,Digit3:4,Digit4:5,Digit5:6,Digit6:7,Digit7:8,Digit8:9,Digit9:10,Digit0:11,Minus:12,Equal:13,Backspace:14,Tab:15,KeyQ:16,KeyW:17,KeyE:18,KeyR:19,KeyT:20,KeyY:21,KeyU:22,KeyI:23,KeyO:24,KeyP:25,BracketLeft:26,BracketRight:27,Enter:28,ControlLeft:29,KeyA:30,KeyS:31,KeyD:32, -KeyF:33,KeyG:34,KeyH:35,KeyJ:36,KeyK:37,KeyL:38,Semicolon:39,Quote:40,Backquote:41,ShiftLeft:42,Backslash:43,KeyZ:44,KeyX:45,KeyC:46,KeyV:47,KeyB:48,KeyN:49,KeyM:50,Comma:51,Period:52,Slash:53,IntlRo:53,ShiftRight:54,NumpadMultiply:55,AltLeft:56,Space:57,CapsLock:58,F1:59,F2:60,F3:61,F4:62,F5:63,F6:64,F7:65,F8:66,F9:67,F10:68,NumLock:69,ScrollLock:70,Numpad7:71,Numpad8:72,Numpad9:73,NumpadSubtract:74,Numpad4:75,Numpad5:76,Numpad6:77,NumpadAdd:78,Numpad1:79,Numpad2:80,Numpad3:81,Numpad0:82,NumpadDecimal:83, -IntlBackslash:86,F11:87,F12:88,NumpadEnter:57372,ControlRight:57373,NumpadDivide:57397,AltRight:57400,Home:57415,ArrowUp:57416,PageUp:57417,ArrowLeft:57419,ArrowRight:57421,End:57423,ArrowDown:57424,PageDown:57425,Insert:57426,Delete:57427,MetaLeft:57435,OSLeft:57435,MetaRight:57436,OSRight:57436,ContextMenu:57437};this.bus=a;this.destroy=function(){"undefined"!==typeof window&&(window.removeEventListener("keyup",c,!1),window.removeEventListener("keydown",d,!1),window.removeEventListener("blur",e, -!1),window.removeEventListener("input",f,!1))};this.init=function(){"undefined"!==typeof window&&(this.destroy(),window.addEventListener("keyup",c,!1),window.addEventListener("keydown",d,!1),window.addEventListener("blur",e,!1),window.addEventListener("input",f,!1))};this.init();this.simulate_press=function(v){v={keyCode:v};g(v,!0);g(v,!1)};this.simulate_char=function(v){var L=v.charCodeAt(0);L in t?this.simulate_press(t[L]):L in A?(m(42),this.simulate_press(A[L]),m(170)):console.log("ascii -> keyCode not found: ", -L,v)}};function $b(a,b){function c(t){if(!C.enabled||!C.emu_enabled)return!1;var A=b||document.body,M;if(!(M=document.pointerLockElement))a:{for(t=t.target;t.parentNode;){if(t===A){M=!0;break a}t=t.parentNode}M=!1}return M}function d(t){c(t)&&(t=t.changedTouches)&&t.length&&(t=t[t.length-1],r=t.clientX,x=t.clientY)}function e(){if(n||q||p)C.bus.send("mouse-click",[!1,!1,!1]),n=q=p=!1}function f(t){if(C.bus&&c(t)&&C.is_running){var A=0,M=0,v=t.changedTouches;v?v.length&&(v=v[v.length-1],A=v.clientX-r,M=v.clientY- -x,r=v.clientX,x=v.clientY,t.preventDefault()):"number"===typeof t.movementX?(A=t.movementX,M=t.movementY):"number"===typeof t.webkitMovementX?(A=t.webkitMovementX,M=t.webkitMovementY):"number"===typeof t.mozMovementX?(A=t.mozMovementX,M=t.mozMovementY):(A=t.clientX-r,M=t.clientY-x,r=t.clientX,x=t.clientY);C.bus.send("mouse-delta",[1*A,-(1*M)]);b&&C.bus.send("mouse-absolute",[t.pageX-b.offsetLeft,t.pageY-b.offsetTop,b.offsetWidth,b.offsetHeight])}}function g(t){c(t)&&l(t,!0)}function h(t){c(t)&&l(t, -!1)}function l(t,A){C.bus&&(1===t.which?n=A:2===t.which?q=A:3===t.which&&(p=A),C.bus.send("mouse-click",[n,q,p]),t.preventDefault())}function m(t){if(c(t)){var A=t.wheelDelta||-t.detail;0>A?A=-1:0e[g]).join("")};this.set_size_text(80,25)};function bc(a){var b,c=0,d=0,e=sa(a?.encoding);this.put_char=function(f,g,h,l,m,n){f=3*(f*c+g);b[f+0]=h;b[f+1]=m;b[f+2]=n};this.destroy=function(){};this.pause=function(){};this.continue=function(){};this.set_mode=function(){};this.set_font_bitmap=function(){};this.set_font_page=function(){};this.clear_screen=function(){};this.set_size_text=function(f,g){if(f!==c||g!==d)b=new Int32Array(f*g*3),c=f,d=g};this.set_size_graphical=function(){};this.set_scale=function(){};this.update_cursor_scanline=function(){}; -this.update_cursor=function(){};this.update_buffer=function(){};this.get_text_screen=function(){for(var f=[],g=0;g>16};${(p&65280)>>8};${p&255}`}m`,h=p);l!==q&&(r+=`\x1B[38;${`2;${(q&16711680)>>16};${(q&65280)>>8};${q&255}`}m`,l=q);m+=r+n}return m+"\u001b[0m"};this.set_size_text(80,25)} -;function cc(a){function b(g){f.enabled&&(f.send_char(g.which),g.preventDefault())}function c(g){var h=g.which;8===h?(f.send_char(127),g.preventDefault()):9===h&&(f.send_char(9),g.preventDefault())}function d(g){if(f.enabled){for(var h=g.clipboardData.getData("text/plain"),l=0;lh?void 0===this.update_timer&&(this.update_timer=setTimeout(()=>{this.update_timer=void 0;this.last_update=Date.now();this.render()},16-h)):(void 0!==this.update_timer&&(clearTimeout(this.update_timer),this.update_timer=void 0),this.last_update=g,this.render())};this.render=function(){a.value=this.text;this.text_new_line&&(this.text_new_line=!1,a.scrollTop=1E9)};this.send_char=function(){}} -function dc(a,b){var c=Reflect.construct(cc,[a],dc);c.send_char=function(d){b.send("serial0-input",d)};b.register("serial0-output-byte",function(d){d=String.fromCharCode(d);c.show_char&&c.show_char(d)},c);return c}Reflect.setPrototypeOf(dc.prototype,cc.prototype);Reflect.setPrototypeOf(dc,cc); -function ec(a,b){var c=Reflect.construct(cc,[a],ec);c.send_char=function(e){b.send("virtio-console0-input-bytes",new Uint8Array([e]))};const d=new TextDecoder;b.register("virtio-console0-output-bytes",function(e){for(const f of d.decode(e))c.show_char&&c.show_char(f)},c);return c}Reflect.setPrototypeOf(ec.prototype,cc.prototype);Reflect.setPrototypeOf(ec,cc); -function lc(a,b){this.element=a;var c=this.term=new b({logLevel:"off",convertEol:"true"});this.destroy=function(){this.on_data_disposable&&this.on_data_disposable.dispose();c.dispose()}}lc.prototype.show=function(){this.term&&this.term.open(this.element)}; -function mc(a,b,c){if(c){var d=Reflect.construct(lc,[a,c],mc);b.register("serial0-output-byte",function(f){d.term.write(Uint8Array.of(f))},d);var e=new TextEncoder;d.on_data_disposable=d.term.onData(function(f){for(const g of e.encode(f))b.send("serial0-input",g)});return d}}Reflect.setPrototypeOf(mc.prototype,lc.prototype);Reflect.setPrototypeOf(mc,lc); -function nc(a,b,c){if(c){var d=Reflect.construct(lc,[a,c],nc);b.register("virtio-console0-output-bytes",function(f){d.term.write(f)},d);var e=new TextEncoder;d.on_data_disposable=d.term.onData(function(f){b.send("virtio-console0-input-bytes",e.encode(f))});return d}}Reflect.setPrototypeOf(nc.prototype,lc.prototype);Reflect.setPrototypeOf(nc,lc);function oc(a,b){b=b.id||0;this.bus=a;this.bus_send_msgid=`net${b}-send`;this.bus_recv_msgid=`net${b}-receive`;this.channel=new BroadcastChannel(`v86-inbrowser-${b}`);this.is_open=!0;this.nic_to_hub_fn=c=>{this.channel.postMessage(c)};this.bus.register(this.bus_send_msgid,this.nic_to_hub_fn,this);this.hub_to_nic_fn=c=>{this.bus.send(this.bus_recv_msgid,c.data)};this.channel.addEventListener("message",this.hub_to_nic_fn)} -oc.prototype.destroy=function(){this.is_open&&(this.bus.unregister(this.bus_send_msgid,this.nic_to_hub_fn),this.channel.removeEventListener("message",this.hub_to_nic_fn),this.channel.close(),this.is_open=!1)};function pc(){this.filedata=new Map}pc.prototype.read=async function(a,b,c){return(a=this.filedata.get(a))?a.subarray(b,b+c):null};pc.prototype.cache=async function(a,b){this.filedata.set(a,b)};pc.prototype.uncache=function(a){this.filedata.delete(a)};function qc(a,b,c){b.endsWith("/")||(b+="/");this.storage=a;this.baseurl=b;this.zstd_decompress=c} -qc.prototype.load_from_server=function(a,b){return new Promise(c=>{oa(this.baseurl+a,{done:async d=>{d=new Uint8Array(d);a.endsWith(".zst")&&(d=new Uint8Array(this.zstd_decompress(b,d)));await this.cache(a,d);c(d)}})})};qc.prototype.read=async function(a,b,c,d){const e=await this.storage.read(a,b,c,d);return e?e:(await this.load_from_server(a,d)).subarray(b,b+c)};qc.prototype.cache=async function(a,b){return await this.storage.cache(a,b)};qc.prototype.uncache=function(a){this.storage.uncache(a)};const rc=new TextDecoder,sc=new TextEncoder; -function G(a,b,c,d){for(var e,f=0,g=0;g>8&255;c[d++]=e>>16&255;c[d++]=e>>24&255;f+=4;break;case "d":c[d++]=e&255;c[d++]=e>>8&255;c[d++]=e>>16&255;c[d++]=e>>24&255;c[d++]=0;c[d++]=0;c[d++]=0;c[d++]=0;f+=8;break;case "h":c[d++]=e&255;c[d++]=e>>8;f+=2;break;case "b":c[d++]=e;f+=1;break;case "s":var h=d,l=0;c[d++]=0;c[d++]=0;f+=2;e=sc.encode(e);f+=e.byteLength;l+=e.byteLength;c.set(e,d);d+=e.byteLength;c[h+0]=l&255;c[h+1]=l>>8&255;break; -case "Q":G(["b","w","d"],[e.type,e.version,e.path],c,d),d+=13,f+=13}return f} -function I(a,b,c){let d=c.offset;for(var e=[],f=0;f>>0;e.push(g);break;case "d":g=b[d++];g+=b[d++]<<8;g+=b[d++]<<16;g+=b[d++]<<24>>>0;d+=4;e.push(g);break;case "h":g=b[d++];e.push(g+(b[d++]<<8));break;case "b":e.push(b[d++]);break;case "s":g=b[d++];g+=b[d++]<<8;var h=b.slice(d,d+g);d+=g;e.push(rc.decode(h));break;case "Q":c.offset=d,g=I(["b","w","d"],b,c),d=c.offset,e.push({type:g[0],version:g[1],path:g[2]})}c.offset= -d;return e};const tc=new TextEncoder;function J(a,b){this.inodes=[];this.storage=a;this.qidcounter=b||{last_qidnumber:0};this.inodedata={};this.total_size=274877906944;this.used_size=0;this.mounts=[];this.CreateDirectory("",-1)}J.prototype.get_state=function(){let a=[];a[0]=this.inodes;a[1]=this.qidcounter.last_qidnumber;a[2]=[];for(const [b,c]of Object.entries(this.inodedata))0===(this.inodes[b].mode&16384)&&a[2].push([b,c]);a[3]=this.total_size;a[4]=this.used_size;return a=a.concat(this.mounts)}; -J.prototype.set_state=function(a){this.inodes=a[0].map(b=>{const c=new uc(0);c.set_state(b);return c});this.qidcounter.last_qidnumber=a[1];this.inodedata={};for(let [b,c]of a[2])c.buffer.byteLength!==c.byteLength&&(c=c.slice()),this.inodedata[b]=c;this.total_size=a[3];this.used_size=a[4];this.mounts=a.slice(5)}; -J.prototype.load_from_json=function(a){if(3!==a.version)throw"The filesystem JSON format has changed. Please recreate the filesystem JSON.";var b=a.fsroot;this.used_size=a.size;for(a=0;a>8;this.qid.version=a[11];this.qid.path=a[12];this.nlinks=a[13]}; -J.prototype.divert=function(a,b){const c=this.Search(a,b),d=this.inodes[c],e=new uc(-1);this.IsDirectory(c);Object.assign(e,d);const f=this.inodes.length;this.inodes.push(e);e.fid=f;this.is_forwarder(d)&&this.mounts[d.mount_id].backtrack.set(d.foreign_id,f);this.should_be_linked(d)&&(this.unlink_from_dir(a,b),this.link_under_dir(a,f,b));if(this.IsDirectory(c)&&!this.is_forwarder(d))for(const [g,h]of e.direntries)"."!==g&&".."!==g&&this.IsDirectory(h)&&this.inodes[h].direntries.set("..",f);this.inodedata[f]= -this.inodedata[c];delete this.inodedata[c];d.direntries=new Map;d.nlinks=0;return f};J.prototype.copy_inode=function(a,b){Object.assign(b,a,{fid:b.fid,direntries:b.direntries,nlinks:b.nlinks})};J.prototype.CreateInode=function(){const a=Math.round(Date.now()/1E3),b=new uc(++this.qidcounter.last_qidnumber);b.atime=b.ctime=b.mtime=a;return b}; -J.prototype.CreateDirectory=function(a,b){var c=this.inodes[b];if(0<=b&&this.is_forwarder(c))return b=c.foreign_id,a=this.follow_fs(c).CreateDirectory(a,b),this.create_forwarder(c.mount_id,a);c=this.CreateInode();c.mode=16895;0<=b&&(c.uid=this.inodes[b].uid,c.gid=this.inodes[b].gid,c.mode=this.inodes[b].mode&511|16384);c.qid.type=64;this.PushInode(c,b,a);this.NotifyListeners(this.inodes.length-1,"newdir");return this.inodes.length-1}; -J.prototype.CreateFile=function(a,b){var c=this.inodes[b];if(this.is_forwarder(c))return b=c.foreign_id,a=this.follow_fs(c).CreateFile(a,b),this.create_forwarder(c.mount_id,a);c=this.CreateInode();c.uid=this.inodes[b].uid;c.gid=this.inodes[b].gid;c.qid.type=128;c.mode=this.inodes[b].mode&438|32768;this.PushInode(c,b,a);this.NotifyListeners(this.inodes.length-1,"newfile");return this.inodes.length-1}; -J.prototype.CreateNode=function(a,b,c,d){var e=this.inodes[b];if(this.is_forwarder(e))return b=e.foreign_id,a=this.follow_fs(e).CreateNode(a,b,c,d),this.create_forwarder(e.mount_id,a);e=this.CreateInode();e.major=c;e.minor=d;e.uid=this.inodes[b].uid;e.gid=this.inodes[b].gid;e.qid.type=192;e.mode=this.inodes[b].mode&438;this.PushInode(e,b,a);return this.inodes.length-1}; -J.prototype.CreateSymlink=function(a,b,c){var d=this.inodes[b];if(this.is_forwarder(d))return b=d.foreign_id,a=this.follow_fs(d).CreateSymlink(a,b,c),this.create_forwarder(d.mount_id,a);d=this.CreateInode();d.uid=this.inodes[b].uid;d.gid=this.inodes[b].gid;d.qid.type=160;d.symlink=c;d.mode=40960;this.PushInode(d,b,a);return this.inodes.length-1}; -J.prototype.CreateTextFile=async function(a,b,c){var d=this.inodes[b];if(this.is_forwarder(d))return b=d.foreign_id,c=await this.follow_fs(d).CreateTextFile(a,b,c),this.create_forwarder(d.mount_id,c);d=this.CreateFile(a,b);b=this.inodes[d];a=new Uint8Array(c.length);b.size=c.length;for(b=0;bg)return g}var h=this.inodes[e],l=this.inodes[a];g=this.inodes[c];if(this.is_forwarder(l)||this.is_forwarder(g))if(this.is_forwarder(l)&&l.mount_id===g.mount_id){if(a=await this.follow_fs(l).Rename(l.foreign_id,b,g.foreign_id,d),0>a)return a}else{if(this.is_a_root(e)||!this.IsDirectory(e)&&1g)return g;await this.DeleteData(l);a=this.Unlink(a,b);if(0>a)return a}else this.unlink_from_dir(a,b),this.link_under_dir(c,e,d),h.qid.version++;this.NotifyListeners(e,"rename",{oldpath:f});return 0}; -J.prototype.Write=async function(a,b,c,d){this.NotifyListeners(a,"write");var e=this.inodes[a];if(this.is_forwarder(e))a=e.foreign_id,await this.follow_fs(e).Write(a,b,c,d);else{var f=await this.get_buffer(a);!f||f.length>12,d],a,c)}}; -J.prototype.RoundToDirentry=function(a,b){a=this.inodedata[a];if(b>=a.length)return a.length;let c=0;for(;;){const d=I(["Q","d"],a,{offset:c})[1];if(d>b)break;c=d}return c};J.prototype.IsDirectory=function(a){a=this.inodes[a];return this.is_forwarder(a)?this.follow_fs(a).IsDirectory(a.foreign_id):16384===(a.mode&61440)}; -J.prototype.IsEmpty=function(a){a=this.inodes[a];if(this.is_forwarder(a))return this.follow_fs(a).IsDirectory(a.foreign_id);for(const b of a.direntries.keys())if("."!==b&&".."!==b)return!1;return!0};J.prototype.GetChildren=function(a){this.IsDirectory(a);a=this.inodes[a];if(this.is_forwarder(a))return this.follow_fs(a).GetChildren(a.foreign_id);const b=[];for(const c of a.direntries.keys())"."!==c&&".."!==c&&b.push(c);return b}; -J.prototype.GetParent=function(a){this.IsDirectory(a);a=this.inodes[a];if(this.should_be_linked(a))return a.direntries.get("..");const b=this.follow_fs(a).GetParent(a.foreign_id);return this.get_forwarder(a.mount_id,b)}; -J.prototype.PrepareCAPs=function(a){a=this.GetInode(a);if(a.caps)return a.caps.length;a.caps=new Uint8Array(20);a.caps[0]=0;a.caps[1]=0;a.caps[2]=0;a.caps[3]=2;a.caps[4]=255;a.caps[5]=255;a.caps[6]=255;a.caps[7]=255;a.caps[8]=255;a.caps[9]=255;a.caps[10]=255;a.caps[11]=255;a.caps[12]=63;a.caps[13]=0;a.caps[14]=0;a.caps[15]=0;a.caps[16]=63;a.caps[17]=0;a.caps[18]=0;a.caps[19]=0;return a.caps.length};function wc(a){this.fs=a;this.backtrack=new Map} -wc.prototype.get_state=function(){const a=[];a[0]=this.fs;a[1]=[...this.backtrack];return a};wc.prototype.set_state=function(a){this.fs=a[0];this.backtrack=new Map(a[1])};J.prototype.set_forwarder=function(a,b,c){const d=this.inodes[a];this.is_forwarder(d)&&this.mounts[d.mount_id].backtrack.delete(d.foreign_id);d.status=5;d.mount_id=b;d.foreign_id=c;this.mounts[b].backtrack.set(c,a)}; -J.prototype.create_forwarder=function(a,b){const c=this.CreateInode(),d=this.inodes.length;this.inodes.push(c);c.fid=d;this.set_forwarder(d,a,b);return d};J.prototype.is_forwarder=function(a){return 5===a.status};J.prototype.is_a_root=function(a){return 0===this.GetInode(a).fid};J.prototype.get_forwarder=function(a,b){const c=this.mounts[a].backtrack.get(b);return void 0===c?this.create_forwarder(a,b):c};J.prototype.delete_forwarder=function(a){this.is_forwarder(a);a.status=-1;this.mounts[a.mount_id].backtrack.delete(a.foreign_id)}; -J.prototype.follow_fs=function(a){const b=this.mounts[a.mount_id];this.is_forwarder(a);return b.fs};J.prototype.Mount=function(a,b){a=this.SearchPath(a);if(-1===a.parentid)return-2;if(-1!==a.id)return-17;if(a.forward_path){var c=this.inodes[a.parentid];b=this.follow_fs(c).Mount(a.forward_path,b);return 0>b?b:this.get_forwarder(c.mount_id,b)}c=this.mounts.length;this.mounts.push(new wc(b));b=this.create_forwarder(c,0);this.link_under_dir(a.parentid,b,a.name);return b}; -function vc(){this.type=2;this.start=0;this.length=Infinity;this.proc_id=-1;this.client_id=""}vc.prototype.get_state=function(){const a=[];a[0]=this.type;a[1]=this.start;a[2]=Infinity===this.length?0:this.length;a[3]=this.proc_id;a[4]=this.client_id;return a};vc.prototype.set_state=function(a){this.type=a[0];this.start=a[1];this.length=0===a[2]?Infinity:a[2];this.proc_id=a[3];this.client_id=a[4]};vc.prototype.clone=function(){const a=new vc;a.set_state(this.get_state());return a}; -vc.prototype.conflicts_with=function(a){return this.proc_id===a.proc_id&&this.client_id===a.client_id||2===this.type||2===a.type||1!==this.type&&1!==a.type||this.start+this.length<=a.start||a.start+a.length<=this.start?!1:!0};vc.prototype.is_alike=function(a){return a.proc_id===this.proc_id&&a.client_id===this.client_id&&a.type===this.type};vc.prototype.may_merge_after=function(a){return this.is_alike(a)&&a.start+a.length===this.start}; -J.prototype.DescribeLock=function(a,b,c,d,e){const f=new vc;f.type=a;f.start=b;f.length=c;f.proc_id=d;f.client_id=e;return f};J.prototype.GetLock=function(a,b){a=this.inodes[a];if(this.is_forwarder(a)){var c=a.foreign_id;return this.follow_fs(a).GetLock(c,b)}for(c of a.locks)if(b.conflicts_with(c))return c.clone();return null}; -J.prototype.Lock=function(a,b,c){const d=this.inodes[a];if(this.is_forwarder(d))return a=d.foreign_id,this.follow_fs(d).Lock(a,b,c);b=b.clone();if(2!==b.type&&this.GetLock(a,b))return 1;for(c=0;c=f&&0=f&&(d.locks.splice(c,1),c--)}if(2!==b.type){c=b;a=!1;for(e=0;e"."!==b&&".."!==b)};J.prototype.read_file=function(a){a=this.SearchPath(a);if(-1===a.id)return Promise.resolve(null);const b=this.GetInode(a.id);return this.Read(a.id,0,b.size)};function N(a){this.cpu_is_running=!1;this.cpu_exception_hook=function(){};var b=Ga.create();this.bus=b[0];this.emulator_bus=b[1];var c,d;const e=new WebAssembly.Table({element:"anyfunc",initial:1924});b={cpu_exception_hook:g=>this.cpu_exception_hook(g),run_hardware_timers:function(g,h){return c.run_hardware_timers(g,h)},cpu_event_halt:()=>{this.emulator_bus.send("cpu-event-halt")},abort:function(){},microtick:F.microtick,get_rand_int:function(){return ba()},stop_idling:function(){return c.stop_idling()}, -io_port_read8:function(g){return c.io.port_read8(g)},io_port_read16:function(g){return c.io.port_read16(g)},io_port_read32:function(g){return c.io.port_read32(g)},io_port_write8:function(g,h){c.io.port_write8(g,h)},io_port_write16:function(g,h){c.io.port_write16(g,h)},io_port_write32:function(g,h){c.io.port_write32(g,h)},mmap_read8:function(g){return c.mmap_read8(g)},mmap_read32:function(g){return c.mmap_read32(g)},mmap_write8:function(g,h){c.mmap_write8(g,h)},mmap_write16:function(g,h){c.mmap_write16(g, -h)},mmap_write32:function(g,h){c.mmap_write32(g,h)},mmap_write64:function(g,h,l){c.mmap_write64(g,h,l)},mmap_write128:function(g,h,l,m,n){c.mmap_write128(g,h,l,m,n)},log_from_wasm:function(g,h){qa(d,g,h)},console_log_from_wasm:function(g,h){g=qa(d,g,h);console.error(g)},dbg_trace_from_wasm:function(){},codegen_finalize:(g,h,l,m,n)=>{c.codegen_finalize(g,h,l,m,n)},jit_clear_func:g=>c.jit_clear_func(g),jit_clear_all_funcs:()=>c.jit_clear_all_funcs(),__indirect_function_table:e};let f=a.wasm_fn;f||(f= -g=>new Promise(h=>{let l="v86.wasm",m="v86-fallback.wasm";a.wasm_path?(l=a.wasm_path,m=l.replace("v86.wasm","v86-fallback.wasm")):"undefined"===typeof window&&"string"===typeof __dirname?(l=__dirname+"/"+l,m=__dirname+"/"+m):(l="build/"+l,m="build/"+m);oa(l,{done:async n=>{try{const {instance:p}=await WebAssembly.instantiate(n,g);this.wasm_source=n;h(p.exports)}catch(p){oa(m,{done:async q=>{const {instance:r}=await WebAssembly.instantiate(q,g);this.wasm_source=q;h(r.exports)}})}},progress:n=>{this.emulator_bus.send("download-progress", -{file_index:0,file_count:1,file_name:l,lengthComputable:n.lengthComputable,total:n.total,loaded:n.loaded})}})}));f({env:b}).then(g=>{d=g.memory;g.rust_init();g=this.v86=new F(this.emulator_bus,{exports:g,wasm_table:e});c=g.cpu;this.continue_init(g,a)});this.zstd_worker=null;this.zstd_worker_request_id=0} -N.prototype.continue_init=async function(a,b){function c(q,r){switch(q){case "hda":e.hda=r;break;case "hdb":e.hdb=r;break;case "cdrom":e.cdrom=r;break;case "fda":e.fda=r;break;case "fdb":e.fdb=r;break;case "multiboot":e.multiboot=r.buffer;break;case "bzimage":e.bzimage=r.buffer;break;case "initrd":e.initrd=r.buffer;break;case "bios":e.bios=r.buffer;break;case "vga_bios":e.vga_bios=r.buffer;break;case "initial_state":e.initial_state=r.buffer;break;case "fs9p_json":e.fs9p_json=r}}async function d(){if(e.fs9p&& -e.fs9p_json&&!e.initial_state&&(e.fs9p.load_from_json(e.fs9p_json),b.bzimage_initrd_from_filesystem)){const {bzimage_path:q,initrd_path:r}=this.get_bzimage_initrd_from_filesystem(e.fs9p),[x,C]=await Promise.all([e.fs9p.read_file(r),e.fs9p.read_file(q)]);c.call(this,"initrd",new z(x.buffer));c.call(this,"bzimage",new z(C.buffer))}this.serial_adapter&&this.serial_adapter.show&&this.serial_adapter.show();this.virtio_console_adapter&&this.virtio_console_adapter.show&&this.virtio_console_adapter.show(); -this.v86.init(e);e.initial_state&&(a.restore_state(e.initial_state),e.initial_state=void 0);b.autostart&&this.v86.run();this.emulator_bus.send("emulator-loaded")}this.bus.register("emulator-stopped",function(){this.cpu_is_running=!1;this.screen_adapter.pause()},this);this.bus.register("emulator-started",function(){this.cpu_is_running=!0;this.screen_adapter.continue()},this);var e={},f=b.boot_order?b.boot_order:b.fda?801:b.hda?786:291;e.acpi=b.acpi;e.disable_jit=b.disable_jit;e.load_devices=!0;e.memory_size= -b.memory_size||67108864;e.vga_memory_size=b.vga_memory_size||8388608;e.boot_order=f;e.fastboot=b.fastboot||!1;e.fda=void 0;e.fdb=void 0;e.uart1=b.uart1;e.uart2=b.uart2;e.uart3=b.uart3;e.cmdline=b.cmdline;e.preserve_mac_from_state_image=b.preserve_mac_from_state_image;e.mac_address_translation=b.mac_address_translation;e.cpuid_level=b.cpuid_level;e.virtio_balloon=b.virtio_balloon;e.virtio_console=!!b.virtio_console;if(f=b.network_relay_url||b.net_device&&b.net_device.relay_url)"fetch"===f?this.network_adapter= -new Vb(this.bus,b.net_device):"inbrowser"===f?this.network_adapter=new oc(this.bus,b.net_device):f.startsWith("wisp://")||f.startsWith("wisps://")?this.network_adapter=new Xb(f,this.bus,b.net_device):this.network_adapter=new ob(f,this.bus);e.net_device=b.net_device||{type:"ne2k"};f=b.screen||{};b.screen_container&&(f.container=b.screen_container);b.disable_keyboard||(this.keyboard_adapter=new Zb(this.bus));b.disable_mouse||(this.mouse_adapter=new $b(this.bus,f.container));this.screen_adapter=f.container? -new wa(f,()=>this.v86.cpu.devices.vga&&this.v86.cpu.devices.vga.screen_fill_buffer()):f.ansi?new bc(f):new ac(f);e.screen=this.screen_adapter;e.screen_options=f;e.serial_console=b.serial_console||{type:"none"};b.serial_container_xtermjs?(e.serial_console.type="xtermjs",e.serial_console.container=b.serial_container_xtermjs):b.serial_container&&(e.serial_console.type="textarea",e.serial_console.container=b.serial_container);"xtermjs"===e.serial_console?.type?this.serial_adapter=new mc(e.serial_console.container, -this.bus,e.serial_console.xterm_lib||window.Terminal):"textarea"===e.serial_console?.type&&(this.serial_adapter=new dc(e.serial_console.container,this.bus));f=b.virtio_console&&"boolean"===typeof b.virtio_console?{type:"none"}:b.virtio_console;"xtermjs"===f?.type?this.virtio_console_adapter=new nc(f.container,this.bus,f.xterm_lib||window.Terminal):"textarea"===f?.type&&(this.virtio_console_adapter=new ec(f.container,this.bus));b.disable_speaker||(this.speaker_adapter=new ib(this.bus));var g=[];f= -(q,r)=>{if(r)if(r.get&&r.set&&r.load)g.push({name:q,loadable:r});else{if("bios"===q||"vga_bios"===q||"initial_state"===q||"multiboot"===q||"bzimage"===q||"initrd"===q)r.async=!1;if("fda"===q||"fdb"===q)r.async=!1;r.url&&!r.async?g.push({name:q,url:r.url,size:r.size}):g.push({name:q,loadable:Ba(r,this.zstd_decompress_worker.bind(this))})}};b.state&&console.warn("Warning: Unknown option 'state'. Did you mean 'initial_state'?");f("bios",b.bios);f("vga_bios",b.vga_bios);f("cdrom",b.cdrom);f("hda",b.hda); -f("hdb",b.hdb);f("fda",b.fda);f("fdb",b.fdb);f("initial_state",b.initial_state);f("multiboot",b.multiboot);f("bzimage",b.bzimage);f("initrd",b.initrd);if(b.filesystem&&b.filesystem.handle9p)e.handle9p=b.filesystem.handle9p;else if(b.filesystem&&b.filesystem.proxy_url)e.proxy9p=b.filesystem.proxy_url;else if(b.filesystem){f=b.filesystem.basefs;var h=b.filesystem.baseurl;let q=new pc;h&&(q=new qc(q,h,this.zstd_decompress.bind(this)));e.fs9p=this.fs9p=new J(q);if(f){if("object"===typeof f){var l=f.size; -f=f.url}g.push({name:"fs9p_json",url:f,size:l,as_json:!0})}}var m=this,n=g.length,p=function(q){if(q===n)setTimeout(d.bind(this),0);else{var r=g[q];r.loadable?(r.loadable.onload=function(){c.call(this,r.name,r.loadable);p(q+1)}.bind(this),r.loadable.load()):oa(r.url,{done:function(x){r.url.endsWith(".zst")&&"initial_state"!==r.name&&(x=this.zstd_decompress(r.size,new Uint8Array(x)));c.call(this,r.name,r.as_json?x:new z(x));p(q+1)}.bind(this),progress:function(x){200===x.target.status?m.emulator_bus.send("download-progress", -{file_index:q,file_count:n,file_name:r.url,lengthComputable:x.lengthComputable,total:x.total||r.size,loaded:x.loaded}):m.emulator_bus.send("download-error",{file_index:q,file_count:n,file_name:r.url,request:x.target})},as_json:r.as_json})}}.bind(this);p(0)}; -N.prototype.zstd_decompress=function(a,b){const c=this.v86.cpu;this.zstd_context=c.zstd_create_ctx(b.length);(new Uint8Array(c.wasm_memory.buffer)).set(b,c.zstd_get_src_ptr(this.zstd_context));b=c.zstd_read(this.zstd_context,a);const d=c.wasm_memory.buffer.slice(b,b+a);c.zstd_read_free(b,a);c.zstd_free_ctx(this.zstd_context);this.zstd_context=null;return d}; -N.prototype.zstd_decompress_worker=async function(a,b){if(!this.zstd_worker){const c=URL.createObjectURL(new Blob(["("+function(){let d;globalThis.onmessage=function(e){if(d){var {src:f,decompressed_size:g,id:h}=e.data;e=d.exports;var l=e.zstd_create_ctx(f.length);(new Uint8Array(e.memory.buffer)).set(f,e.zstd_get_src_ptr(l));var m=e.zstd_read(l,g),n=e.memory.buffer.slice(m,m+g);e.zstd_read_free(m,g);e.zstd_free_ctx(l);postMessage({result:n,id:h},[n])}else l=Object.fromEntries("cpu_exception_hook run_hardware_timers cpu_event_halt microtick get_rand_int stop_idling io_port_read8 io_port_read16 io_port_read32 io_port_write8 io_port_write16 io_port_write32 mmap_read8 mmap_read32 mmap_write8 mmap_write16 mmap_write32 mmap_write64 mmap_write128 codegen_finalize jit_clear_func jit_clear_all_funcs".split(" ").map(p=> -[p,()=>console.error("zstd worker unexpectedly called "+p)])),l.__indirect_function_table=new WebAssembly.Table({element:"anyfunc",initial:1024}),l.abort=()=>{throw Error("zstd worker aborted");},l.log_from_wasm=l.console_log_from_wasm=(p,q)=>{console.log(qa(d.exports.memory.buffer,p,q))},l.dbg_trace_from_wasm=()=>console.trace(),d=new WebAssembly.Instance(new WebAssembly.Module(e.data),{env:l})}}.toString()+")()"],{type:"text/javascript"}));this.zstd_worker=new Worker(c);URL.revokeObjectURL(c);this.zstd_worker.postMessage(this.wasm_source, -[this.wasm_source])}return new Promise(c=>{const d=this.zstd_worker_request_id++,e=async f=>{f.data.id===d&&(this.zstd_worker.removeEventListener("message",e),c(f.data.result))};this.zstd_worker.addEventListener("message",e);this.zstd_worker.postMessage({src:b,decompressed_size:a,id:d},[b.buffer])})}; -N.prototype.get_bzimage_initrd_from_filesystem=function(a){const b=(a.read_dir("/")||[]).map(e=>"/"+e);a=(a.read_dir("/boot/")||[]).map(e=>"/boot/"+e);let c,d;for(const e of[].concat(b,a)){const f=/old/i.test(e)||/fallback/i.test(e),g=/vmlinuz/i.test(e)||/bzimage/i.test(e),h=/initrd/i.test(e)||/initramfs/i.test(e);!g||d&&f||(d=e);!h||c&&f||(c=e)}c&&d||(console.log("Failed to find bzimage or initrd in filesystem. Files:"),console.log(b.join(" ")),console.log(a.join(" ")));return{initrd_path:c,bzimage_path:d}}; -N.prototype.run=async function(){this.v86.run()};N.prototype.stop=async function(){this.cpu_is_running&&await new Promise(a=>{const b=()=>{this.remove_listener("emulator-stopped",b);a()};this.add_listener("emulator-stopped",b);this.v86.stop()})}; -N.prototype.destroy=async function(){await this.stop();this.v86.destroy();this.keyboard_adapter&&this.keyboard_adapter.destroy();this.network_adapter&&this.network_adapter.destroy();this.mouse_adapter&&this.mouse_adapter.destroy();this.screen_adapter&&this.screen_adapter.destroy();this.serial_adapter&&this.serial_adapter.destroy();this.speaker_adapter&&this.speaker_adapter.destroy();this.virtio_console_adapter&&this.virtio_console_adapter.destroy()};N.prototype.restart=function(){this.v86.restart()}; -N.prototype.add_listener=function(a,b){this.bus.register(a,b,this)};N.prototype.remove_listener=function(a,b){this.bus.unregister(a,b)};N.prototype.restore_state=async function(a){this.v86.restore_state(a)};N.prototype.save_state=async function(){return this.v86.save_state()};N.prototype.get_instruction_counter=function(){return this.v86?this.v86.cpu.instruction_counter[0]>>>0:0};N.prototype.is_running=function(){return this.cpu_is_running}; -N.prototype.set_fda=async function(a){const b=this.v86.cpu.devices.fdc.drives[0];if(a.url&&!a.async)await new Promise(c=>{oa(a.url,{done:d=>{b.insert_disk(new z(d));c()}})});else{const c=Ba(a,this.zstd_decompress_worker.bind(this));c.onload=()=>{b.insert_disk(c)};await c.load()}}; -N.prototype.set_fdb=async function(a){const b=this.v86.cpu.devices.fdc.drives[1];if(a.url&&!a.async)await new Promise(c=>{oa(a.url,{done:d=>{b.insert_disk(new z(d));c()}})});else{const c=Ba(a,this.zstd_decompress_worker.bind(this));c.onload=()=>{b.insert_disk(c)};await c.load()}};N.prototype.eject_fda=function(){this.v86.cpu.devices.fdc.drives[0].eject_disk()};N.prototype.eject_fdb=function(){this.v86.cpu.devices.fdc.drives[1].eject_disk()};N.prototype.get_disk_fda=function(){return this.v86.cpu.devices.fdc.drives[0].get_buffer()}; -N.prototype.get_disk_fdb=function(){return this.v86.cpu.devices.fdc.drives[1].get_buffer()};N.prototype.set_cdrom=async function(a){if(a.url&&!a.async)oa(a.url,{done:b=>{this.v86.cpu.devices.cdrom.set_cdrom(new z(b))}});else{const b=Ba(a,this.zstd_decompress_worker.bind(this));b.onload=()=>{this.v86.cpu.devices.cdrom.set_cdrom(b)};await b.load()}};N.prototype.eject_cdrom=function(){this.v86.cpu.devices.cdrom.eject()}; -N.prototype.keyboard_send_scancodes=async function(a,b){for(var c=0;csetTimeout(d,b))};N.prototype.keyboard_send_keys=async function(a,b){for(var c=0;csetTimeout(d,b))};N.prototype.keyboard_send_text=async function(a,b){for(var c=0;csetTimeout(d,b))}; -N.prototype.screen_make_screenshot=function(){return this.screen_adapter?this.screen_adapter.make_screenshot():null};N.prototype.screen_set_scale=function(a,b){this.screen_adapter&&this.screen_adapter.set_scale(a,b)}; -N.prototype.screen_go_fullscreen=function(){if(this.screen_adapter){var a=document.getElementById("screen_container");if(a){var b=a.requestFullScreen||a.webkitRequestFullscreen||a.mozRequestFullScreen||a.msRequestFullScreen;b&&(b.call(a),(a=document.getElementsByClassName("phone_keyboard")[0])&&a.focus());try{navigator.keyboard.lock()}catch(c){}this.lock_mouse()}}};N.prototype.lock_mouse=async function(){const a=document.body;try{await a.requestPointerLock({unadjustedMovement:!0})}catch(b){await a.requestPointerLock()}}; -N.prototype.mouse_set_enabled=function(a){this.mouse_adapter&&(this.mouse_adapter.emu_enabled=a)};N.prototype.mouse_set_status=N.prototype.mouse_set_enabled;N.prototype.keyboard_set_enabled=function(a){this.keyboard_adapter&&(this.keyboard_adapter.emu_enabled=a)};N.prototype.keyboard_set_status=N.prototype.keyboard_set_enabled;N.prototype.serial0_send=function(a){for(var b=0;b{const d=c[0];if(d){var e=c.slice(1);d.sleep?setTimeout(()=>b(e),1E3*d.sleep):d.vga_text?this.wait_until_vga_screen_contains(d.vga_text).then(()=>b(e)):d.keyboard_send?(Array.isArray(d.keyboard_send)?this.keyboard_send_scancodes(d.keyboard_send):this.keyboard_send_text(d.keyboard_send),b(e)):d.call&&(d.call(),b(e))}};b(a)}; -N.prototype.wait_until_vga_screen_contains=async function(a,b){const c=Array.isArray(a);var d=b?.timeout_msec||0;const e=new Set;b=m=>e.add(m[0]);const f=(m,n)=>n.test?n.test(m):m.startsWith(n),g=[];this.add_listener("screen-put-char",b);for(var h of this.screen_adapter.get_text_screen())if(c)g.push(h.trimRight());else if(f(h,a))return this.remove_listener("screen-put-char",b),!0;h=!1;d=d?performance.now()+d:0;a:for(;!d||performance.now()setTimeout(m,100));for(const m of e)if(l=this.screen_adapter.get_text_row(m),c)g[m]=l.trimRight();else if(f(l,a)){h=!0;break a}e.clear()}this.remove_listener("screen-put-char",b);return h};N.prototype.read_memory=function(a,b){return this.v86.cpu.read_blob(a,b)};N.prototype.write_memory=function(a,b){this.v86.cpu.write_blob(a,b)}; -N.prototype.set_serial_container_xtermjs=function(a,b=window.Terminal){this.serial_adapter&&this.serial_adapter.destroy&&this.serial_adapter.destroy();this.serial_adapter=new mc(a,this.bus,b);this.serial_adapter.show()};N.prototype.set_virtio_console_container_xtermjs=function(a,b=window.Terminal){this.virtio_console_adapter&&this.virtio_console_adapter.destroy&&this.virtio_console_adapter.destroy();this.virtio_console_adapter=new nc(a,this.bus,b);this.virtio_console_adapter.show()}; -N.prototype.get_instruction_stats=function(){var a=this.v86.cpu;var b="";var c="COMPILE COMPILE_SKIPPED_NO_NEW_ENTRY_POINTS COMPILE_WRONG_ADDRESS_SPACE COMPILE_CUT_OFF_AT_END_OF_PAGE COMPILE_WITH_LOOP_SAFETY COMPILE_PAGE COMPILE_PAGE/COMPILE COMPILE_BASIC_BLOCK COMPILE_DUPLICATED_BASIC_BLOCK COMPILE_WASM_BLOCK COMPILE_WASM_LOOP COMPILE_DISPATCHER COMPILE_ENTRY_POINT COMPILE_WASM_TOTAL_BYTES COMPILE_WASM_TOTAL_BYTES/COMPILE_PAGE RUN_INTERPRETED RUN_INTERPRETED_NEW_PAGE RUN_INTERPRETED_PAGE_HAS_CODE RUN_INTERPRETED_PAGE_HAS_ENTRY_AFTER_PAGE_WALK RUN_INTERPRETED_NEAR_END_OF_PAGE RUN_INTERPRETED_DIFFERENT_STATE RUN_INTERPRETED_DIFFERENT_STATE_CPL3 RUN_INTERPRETED_DIFFERENT_STATE_FLAT RUN_INTERPRETED_DIFFERENT_STATE_IS32 RUN_INTERPRETED_DIFFERENT_STATE_SS32 RUN_INTERPRETED_MISSED_COMPILED_ENTRY_RUN_INTERPRETED RUN_INTERPRETED_STEPS RUN_FROM_CACHE RUN_FROM_CACHE_STEPS RUN_FROM_CACHE_STEPS/RUN_FROM_CACHE RUN_FROM_CACHE_STEPS/RUN_INTERPRETED_STEPS DIRECT_EXIT INDIRECT_JUMP INDIRECT_JUMP_NO_ENTRY NORMAL_PAGE_CHANGE NORMAL_FALLTHRU NORMAL_FALLTHRU_WITH_TARGET_BLOCK NORMAL_BRANCH NORMAL_BRANCH_WITH_TARGET_BLOCK CONDITIONAL_JUMP CONDITIONAL_JUMP_PAGE_CHANGE CONDITIONAL_JUMP_EXIT CONDITIONAL_JUMP_FALLTHRU CONDITIONAL_JUMP_FALLTHRU_WITH_TARGET_BLOCK CONDITIONAL_JUMP_BRANCH CONDITIONAL_JUMP_BRANCH_WITH_TARGET_BLOCK DISPATCHER_SMALL DISPATCHER_LARGE LOOP LOOP_SAFETY CONDITION_OPTIMISED CONDITION_UNOPTIMISED CONDITION_UNOPTIMISED_PF CONDITION_UNOPTIMISED_UNHANDLED_L CONDITION_UNOPTIMISED_UNHANDLED_LE FAILED_PAGE_CHANGE SAFE_READ_FAST SAFE_READ_SLOW_PAGE_CROSSED SAFE_READ_SLOW_NOT_VALID SAFE_READ_SLOW_NOT_USER SAFE_READ_SLOW_IN_MAPPED_RANGE SAFE_WRITE_FAST SAFE_WRITE_SLOW_PAGE_CROSSED SAFE_WRITE_SLOW_NOT_VALID SAFE_WRITE_SLOW_NOT_USER SAFE_WRITE_SLOW_IN_MAPPED_RANGE SAFE_WRITE_SLOW_READ_ONLY SAFE_WRITE_SLOW_HAS_CODE SAFE_READ_WRITE_FAST SAFE_READ_WRITE_SLOW_PAGE_CROSSED SAFE_READ_WRITE_SLOW_NOT_VALID SAFE_READ_WRITE_SLOW_NOT_USER SAFE_READ_WRITE_SLOW_IN_MAPPED_RANGE SAFE_READ_WRITE_SLOW_READ_ONLY SAFE_READ_WRITE_SLOW_HAS_CODE PAGE_FAULT TLB_MISS MAIN_LOOP MAIN_LOOP_IDLE DO_MANY_CYCLES CYCLE_INTERNAL INVALIDATE_ALL_MODULES_NO_FREE_WASM_INDICES INVALIDATE_MODULE_WRITTEN_WHILE_COMPILED INVALIDATE_MODULE_UNUSED_AFTER_OVERWRITE INVALIDATE_MODULE_DIRTY_PAGE INVALIDATE_PAGE_HAD_CODE INVALIDATE_PAGE_HAD_ENTRY_POINTS DIRTY_PAGE_DID_NOT_HAVE_CODE RUN_FROM_CACHE_EXIT_SAME_PAGE RUN_FROM_CACHE_EXIT_NEAR_END_OF_PAGE RUN_FROM_CACHE_EXIT_DIFFERENT_PAGE CLEAR_TLB FULL_CLEAR_TLB TLB_FULL TLB_GLOBAL_FULL MODRM_SIMPLE_REG MODRM_SIMPLE_REG_WITH_OFFSET MODRM_SIMPLE_CONST_OFFSET MODRM_COMPLEX SEG_OFFSET_OPTIMISED SEG_OFFSET_NOT_OPTIMISED SEG_OFFSET_NOT_OPTIMISED_ES SEG_OFFSET_NOT_OPTIMISED_FS SEG_OFFSET_NOT_OPTIMISED_GS SEG_OFFSET_NOT_OPTIMISED_NOT_FLAT".split(" "), -d=0;const e={};for(let g=0;g>20)+"m\n";b=b+"Config:\nJIT_DISABLED="+(a.wm.exports.get_jit_config(0)+"\n");b+="MAX_PAGES="+a.wm.exports.get_jit_config(1)+"\n";b+="JIT_USE_LOOP_SAFETY="+!!a.wm.exports.get_jit_config(2)+"\n";b+="MAX_EXTRA_BASIC_BLOCKS="+a.wm.exports.get_jit_config(3)+"\n";a=[fb(a,!1,!1,!1,!1),fb(a,!0,!1,!1,!1),fb(a,!1,!0,!1,!1),fb(a,!1, -!1,!0,!1),fb(a,!1,!1,!1,!0)].join("\n\n");return b+a};function xc(a){this.message=a||"File not found"}xc.prototype=Error.prototype;"undefined"!==typeof module&&"undefined"!==typeof module.exports?module.exports.V86=N:"undefined"!==typeof window?window.V86=N:"function"===typeof importScripts&&(self.V86=N);function F(a,b){this.stopping=this.running=!1;this.idle=!0;this.tick_counter=0;this.worker=null;this.cpu=new O(a,b,()=>{this.idle&&this.next_tick(0)});this.bus=a;this.register_yield()}F.prototype.run=function(){this.stopping=!1;this.running||(this.running=!0,this.bus.send("emulator-started"));this.next_tick(0)};F.prototype.do_tick=function(){if(this.stopping||!this.running)this.stopping=this.running=!1,this.bus.send("emulator-stopped");else{this.idle=!1;var a=this.cpu.main_loop();this.next_tick(a)}}; -F.prototype.next_tick=function(a){const b=++this.tick_counter;this.idle=!0;this.yield(a,b)};F.prototype.yield_callback=function(a){a===this.tick_counter&&this.do_tick()};F.prototype.stop=function(){this.running&&(this.stopping=!0)};F.prototype.destroy=function(){this.unregister_yield()};F.prototype.restart=function(){this.cpu.reset_cpu();this.cpu.load_bios()};F.prototype.init=function(a){this.cpu.init(a,this.bus);this.bus.send("emulator-ready")}; -if("undefined"!==typeof process)F.prototype.yield=function(a,b){1>a?global.setImmediate(c=>this.yield_callback(c),b):setTimeout(c=>this.yield_callback(c),a,b)},F.prototype.register_yield=function(){},F.prototype.unregister_yield=function(){};else if(globalThis.scheduler&&"function"===typeof globalThis.scheduler.postTask&&location.href.includes("use-scheduling-api"))F.prototype.yield=function(a,b){a=Math.max(0,a);globalThis.scheduler.postTask(()=>this.yield_callback(b),{delay:a})},F.prototype.register_yield= -function(){},F.prototype.unregister_yield=function(){};else if("undefined"!==typeof Worker){function a(){let b;globalThis.onmessage=function(c){const d=c.data.t;b=b&&clearTimeout(b);1>d?postMessage(c.data.tick):b=setTimeout(()=>postMessage(c.data.tick),d)}}F.prototype.register_yield=function(){const b=URL.createObjectURL(new Blob(["("+a.toString()+")()"],{type:"text/javascript"}));this.worker=new Worker(b);this.worker.onmessage=c=>this.yield_callback(c.data);URL.revokeObjectURL(b)};F.prototype.yield= -function(b,c){this.worker.postMessage({t:b,tick:c})};F.prototype.unregister_yield=function(){this.worker&&this.worker.terminate();this.worker=null}}else F.prototype.yield=function(a){setTimeout(()=>{this.do_tick()},a)},F.prototype.register_yield=function(){},F.prototype.unregister_yield=function(){}; -F.prototype.save_state=function(){for(var a=[],b=cb(this.cpu,a),c=[],d=0,e=0;ethis.timer_imprecision_offset&&this.timer_imprecision_offset++:this.timer_last_value+this.timer_imprecision_offset<=a&&(this.timer_imprecision_offset=0,this.timer_last_value=a);return this.timer_last_value+this.timer_imprecision_offset};yc.prototype.get_state=function(){var a=[];a[0]=this.status;a[1]=this.pm1_status;a[2]=this.pm1_enable;a[3]=this.gpe;return a}; -yc.prototype.set_state=function(a){this.status=a[0];this.pm1_status=a[1];this.pm1_enable=a[2];this.gpe=a[3]};function zc(a,b,c){this.bus=c;this.cpu=a;this.ints=4;this.line_control=this.baud_rate=0;this.lsr=96;this.ier=this.fifo_control=0;this.iir=1;this.irq=this.scratch_register=this.modem_status=this.modem_control=0;this.input=[];this.current_line="";switch(b){case 1016:this.com=0;this.irq=4;break;case 760:this.com=1;this.irq=3;break;case 1E3:this.com=2;this.irq=4;break;case 744:this.irq=this.com=3;break;default:ua("Invalid serial port: "+y(b),16384),this.com=0,this.irq=4}this.bus.register("serial"+this.com+ -"-input",function(d){this.data_received(d)},this);this.bus.register("serial"+this.com+"-modem-status-input",function(d){this.set_modem_status(d)},this);this.bus.register("serial"+this.com+"-carrier-detect-input",function(d){this.set_modem_status(d?this.modem_status|136:this.modem_status&-137)},this);this.bus.register("serial"+this.com+"-ring-indicator-input",function(d){this.set_modem_status(d?this.modem_status|68:this.modem_status&-69)},this);this.bus.register("serial"+this.com+"-data-set-ready-input", -function(d){this.set_modem_status(d?this.modem_status|34:this.modem_status&-35)},this);this.bus.register("serial"+this.com+"-clear-to-send-input",function(d){this.set_modem_status(d?this.modem_status|17:this.modem_status&-18)},this);a=a.io;a.register_write(b,this,function(d){this.write_data(d)},function(d){this.write_data(d&255);this.write_data(d>>8)});a.register_write(b|1,this,function(d){this.line_control&128?(this.baud_rate=this.baud_rate&255|d<<8,y(this.baud_rate)):(0===(this.ier&2)&&d&2&&this.ThrowInterrupt(2), -this.ier=d&15,y(d),this.CheckInterrupt())});a.register_read(b,this,function(){if(this.line_control&128)return this.baud_rate&255;let d=0;0!==this.input.length&&(d=this.input.shift(),y(d));0===this.input.length&&(this.lsr&=-2,this.ClearInterrupt(12),this.ClearInterrupt(4));return d});a.register_read(b|1,this,function(){return this.line_control&128?this.baud_rate>>8:this.ier&15});a.register_read(b|2,this,function(){var d=this.iir&15;y(this.iir);2===this.iir&&this.ClearInterrupt(2);this.fifo_control& -1&&(d|=192);return d});a.register_write(b|2,this,function(d){y(d);this.fifo_control=d});a.register_read(b|3,this,function(){y(this.line_control);return this.line_control});a.register_write(b|3,this,function(d){y(d);this.line_control=d});a.register_read(b|4,this,function(){return this.modem_control});a.register_write(b|4,this,function(d){y(d);this.modem_control=d});a.register_read(b|5,this,function(){y(this.lsr);return this.lsr});a.register_write(b|5,this,function(){});a.register_read(b|6,this,function(){y(this.modem_status); -return this.modem_status&=240});a.register_write(b|6,this,function(d){y(d);this.set_modem_status(d)});a.register_read(b|7,this,function(){return this.scratch_register});a.register_write(b|7,this,function(d){this.scratch_register=d})}zc.prototype.get_state=function(){var a=[];a[0]=this.ints;a[1]=this.baud_rate;a[2]=this.line_control;a[3]=this.lsr;a[4]=this.fifo_control;a[5]=this.ier;a[6]=this.iir;a[7]=this.modem_control;a[8]=this.modem_status;a[9]=this.scratch_register;a[10]=this.irq;return a}; -zc.prototype.set_state=function(a){this.ints=a[0];this.baud_rate=a[1];this.line_control=a[2];this.lsr=a[3];this.fifo_control=a[4];this.ier=a[5];this.iir=a[6];this.modem_control=a[7];this.modem_status=a[8];this.scratch_register=a[9];this.irq=a[10]}; -zc.prototype.CheckInterrupt=function(){this.ints&4096&&this.ier&1?(this.iir=12,this.cpu.device_raise_irq(this.irq)):this.ints&16&&this.ier&1?(this.iir=4,this.cpu.device_raise_irq(this.irq)):this.ints&4&&this.ier&2?(this.iir=2,this.cpu.device_raise_irq(this.irq)):this.ints&1&&this.ier&8?(this.iir=0,this.cpu.device_raise_irq(this.irq)):(this.iir=1,this.cpu.device_lower_irq(this.irq))};zc.prototype.ThrowInterrupt=function(a){this.ints|=1<>4;this.modem_status=a;this.modem_status=this.modem_status|c|b};function Ac(a){this.pci_addr=new Uint8Array(4);this.pci_value=new Uint8Array(4);this.pci_response=new Uint8Array(4);this.pci_status=new Uint8Array(4);this.pci_addr32=new Int32Array(this.pci_addr.buffer);this.pci_value32=new Int32Array(this.pci_value.buffer);this.pci_response32=new Int32Array(this.pci_response.buffer);this.pci_status32=new Int32Array(this.pci_status.buffer);this.device_spaces=[];this.devices=[];this.cpu=a;for(var b=0;256>b;b++)this.device_spaces[b]=void 0,this.devices[b]=void 0;this.io= -a.io;a.io.register_write(3324,this,function(c){this.pci_write8(this.pci_addr32[0],c)},function(c){this.pci_write16(this.pci_addr32[0],c)},function(c){this.pci_write32(this.pci_addr32[0],c)});a.io.register_write(3325,this,function(c){this.pci_write8(this.pci_addr32[0]+1|0,c)});a.io.register_write(3326,this,function(c){this.pci_write8(this.pci_addr32[0]+2|0,c)},function(c){this.pci_write16(this.pci_addr32[0]+2|0,c)});a.io.register_write(3327,this,function(c){this.pci_write8(this.pci_addr32[0]+3|0,c)}); -a.io.register_read_consecutive(3324,this,function(){return this.pci_response[0]},function(){return this.pci_response[1]},function(){return this.pci_response[2]},function(){return this.pci_response[3]});a.io.register_read_consecutive(3320,this,function(){return this.pci_status[0]},function(){return this.pci_status[1]},function(){return this.pci_status[2]},function(){return this.pci_status[3]});a.io.register_write_consecutive(3320,this,function(c){this.pci_addr[0]=c&252},function(c){2===(this.pci_addr[1]& -6)&&6===(c&6)?a.reboot_internal():this.pci_addr[1]=c},function(c){this.pci_addr[2]=c},function(c){this.pci_addr[3]=c;this.pci_query()});this.register_device({pci_id:0,pci_space:[134,128,55,18,0,0,0,0,2,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0],pci_bars:[],name:"82441FX PMC"});this.isa_bridge={pci_id:8,pci_space:[134,128,0,112,7,0,0,2,0,0,1,6,0,0,128,0,0,0,0,0,0,0,0, -0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],pci_bars:[],name:"82371SB PIIX3 ISA"};this.isa_bridge_space=this.register_device(this.isa_bridge);this.isa_bridge_space8=new Uint8Array(this.isa_bridge_space.buffer)}Ac.prototype.get_state=function(){for(var a=[],b=0;256>b;b++)a[b]=this.device_spaces[b];a[256]=this.pci_addr;a[257]=this.pci_value;a[258]=this.pci_response;a[259]=this.pci_status;return a}; -Ac.prototype.set_state=function(a){for(var b=0;256>b;b++){var c=this.devices[b],d=a[b];if(c&&d){for(var e=0;e>3&31;var d="query enabled="+(this.pci_addr[3]>>7)+(" bdf="+y(a,4));d+=" dev="+y(c,2);d+=" addr="+y(b,2);a=this.device_spaces[a];void 0!==a?(this.pci_status32[0]=-2147483648,this.pci_response32[0]=b>2]:0,d+=" "+y(this.pci_addr32[0]>>>0,8)+" -> "+y(this.pci_response32[0]>>>0,8)):(this.pci_response32[0]=-1,this.pci_status32[0]=0)}; -Ac.prototype.pci_write8=function(a,b){var c=a>>8&65535;a&=255;var d=new Uint8Array(this.device_spaces[c].buffer);y(a);y(c>>3,2);y(a,4);y(b,2);d[a]=b};Ac.prototype.pci_write16=function(a,b){var c=a>>8&65535;a&=255;var d=new Uint16Array(this.device_spaces[c].buffer);16<=a&&44>a?y(a):(y(a),y(c>>3,2),y(a,4),y(b,4),d[a>>>1]=b)}; -Ac.prototype.pci_write32=function(a,b){var c=a>>8&65535;a&=255;var d=this.device_spaces[c],e=this.devices[c];if(d)if(16<=a&&40>a){e=e.pci_bars[a-16>>2];y(d[a>>2]);y(b>>>0);y(c>>3,2);if(e){c=a>>2;var f=d[c]&1;-1===(b|3|e.size-1)?(b=~(e.size-1)|f,0===f&&(d[c]=b)):0===f&&(d[c]=e.original_bar);if(1===f){f=d[c]&65534;var g=b&65534;y(f>>>0,8);y(g>>>0,8);this.set_io_bars(e,f,g);d[c]=b|1}}else d[a>>2]=0;y(d[a>>2]>>>0)}else 48===a?(y(c>>3,2),y(b>>>0,8),d[a>>2]=e.pci_rom_size?-1===(b|2047)?-e.pci_rom_size| -0:e.pci_rom_address|0:0):4===a?(y(c>>3,2),y(a,4),y(b>>>0,8)):(y(c>>3,2),y(a,4),y(b>>>0,8),d[a>>>2]=b)};Ac.prototype.register_device=function(a){var b=a.pci_id;y(b);var c=new Int32Array(64);c.set(new Int32Array((new Uint8Array(a.pci_space)).buffer));this.device_spaces[b]=c;this.devices[b]=a;b=c.slice(4,10);for(var d=0;d>8&255)-1+((a>>3)-1&255)&3)])};Ac.prototype.lower_irq=function(a){this.cpu.device_lower_irq(this.isa_bridge_space8[96+((this.device_spaces[a][15]>>8&255)+(a>>3&255)-2&3)])};function Bc(a,b,c){a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&(a[0]=c[0],a[1]=c[1],a[2]=c[2],a[3]=c[3],a[4]=c[4],a[5]=c[5]);a[6]===b[0]&&a[7]===b[1]&&a[8]===b[2]&&a[9]===b[3]&&a[10]===b[4]&&a[11]===b[5]&&(a[6]=c[0],a[7]=c[1],a[8]=c[2],a[9]=c[3],a[10]=c[4],a[11]=c[5]);var d=a[12]<<8|a[13];if(2048===d){if(a=a.subarray(14),4===a[0]>>4&&17===a[9]){a=a.subarray(20);d=a[0]<<8|a[1];var e=a[2]<<8|a[3];y(a[6]<<8|a[7],4);if(67===d||67===e)if(d=a.subarray(8),e=d[236]<<24|d[237]<< -16|d[238]<<8|d[239],1669485411!==e)y(e,8);else for(d[28]===b[0]&&d[29]===b[1]&&d[30]===b[2]&&d[31]===b[3]&&d[32]===b[4]&&d[33]===b[5]&&(d[28]=c[0],d[29]=c[1],d[30]=c[2],d[31]=c[3],d[32]=c[4],d[33]=c[5],a[6]=a[7]=0),e=240;e>8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,244,26,0,17,0,0,184,254,0,0,0,0,0,0,0,0,0,1,0,0];this.pci_id=(0===this.id?5:7+this.id)<<3;this.pci_bars= -[{size:32}];this.imr=this.isr=0;this.cr=1;this.tpsr=this.tcnt=this.rcnt=this.dcfg=0;this.memory=new Uint8Array(32768);this.txcr=this.rxcr=0;this.tsr=1;this.mac=new Uint8Array([0,34,21,255*Math.random()|0,255*Math.random()|0,255*Math.random()|0]);this.bus.send("net"+this.id+"-mac",Cc(this.mac));this.mar=Uint8Array.of(255,255,255,255,255,255,255,255);this.mac_address_in_state=null;for(b=0;6>b;b++)this.memory[b<<1]=this.memory[b<<1|1]=this.mac[b];this.memory[28]=this.memory[29]=87;this.memory[30]=this.memory[31]= -87;ua("Mac: "+Cc(this.mac),1048576);this.rsar=0;this.pstart=64;this.pstop=128;this.boundary=this.curpg=76;b=a.io;b.register_read(this.port|0,this,function(){return this.cr},function(){return this.cr});b.register_write(this.port|0,this,function(f){this.cr=f;y(f,2);y(this.txcr,2);this.cr&1||(f&24&&0===this.rcnt&&this.do_interrupt(64),f&4&&(f=this.tpsr<<8,f=this.memory.subarray(f,f+this.tcnt),this.mac_address_in_state&&(f=new Uint8Array(f),Bc(f,this.mac_address_in_state,this.mac)),this.bus.send("net"+ -this.id+"-send",f),this.bus.send("eth-transmit-end",[f.length]),this.cr&=-5,this.do_interrupt(2),y(f.byteLength)))});b.register_read(this.port|13,this,function(){return 1===this.get_page()?this.mar[5]:0});b.register_read(this.port|14,this,function(){return 1===this.get_page()?this.mar[6]:0},function(){this.get_page();return 0});b.register_read(this.port|15,this,function(){return 1===this.get_page()?this.mar[7]:0});b.register_read(this.port|31,this,function(){this.get_page();this.do_interrupt(128); -return 0});b.register_write(this.port|31,this,function(f){this.get_page();y(f,2)});b.register_read(this.port|1,this,function(){var f=this.get_page();return 0===f?this.pstart:1===f?this.mac[0]:2===f?this.pstart:0});b.register_write(this.port|1,this,function(f){var g=this.get_page();0===g?(y(f,2),this.pstart=f):1===g?(y(f),this.mac[0]=f):y(f)});b.register_read(this.port|2,this,function(){var f=this.get_page();return 0===f?this.pstop:1===f?this.mac[1]:2===f?this.pstop:0});b.register_write(this.port| -2,this,function(f){var g=this.get_page();0===g?(y(f,2),f>this.memory.length>>8&&(f=this.memory.length>>8,y(f)),this.pstop=f):1===g?(y(f),this.mac[1]=f):y(f)});b.register_read(this.port|7,this,function(){var f=this.get_page();return 0===f?(y(this.isr,2),this.isr):1===f?(y(this.curpg,2),this.curpg):0});b.register_write(this.port|7,this,function(f){var g=this.get_page();0===g?(y(f,2),this.isr&=~f,this.update_irq()):1===g&&(y(f,2),this.curpg=f)});b.register_write(this.port|13,this,function(f){0===this.get_page()&& -(this.txcr=f);y(f,2)});b.register_write(this.port|14,this,function(f){0===this.get_page()?(y(f,2),this.dcfg=f):y(f,2)});b.register_read(this.port|10,this,function(){var f=this.get_page();return 0===f?80:1===f?this.mar[2]:0});b.register_write(this.port|10,this,function(f){0===this.get_page()?(y(f,2),this.rcnt=this.rcnt&65280|f&255):y(f,2)});b.register_read(this.port|11,this,function(){var f=this.get_page();return 0===f?67:1===f?this.mar[3]:0});b.register_write(this.port|11,this,function(f){0===this.get_page()? -(y(f,2),this.rcnt=this.rcnt&255|f<<8&65280):y(f,2)});b.register_read(this.port|8,this,function(){var f=this.get_page();return 0===f?this.rsar&255:1===f?this.mar[0]:0});b.register_write(this.port|8,this,function(f){0===this.get_page()?(y(f,2),this.rsar=this.rsar&65280|f&255):y(f,2)});b.register_read(this.port|9,this,function(){var f=this.get_page();return 0===f?this.rsar>>8&255:1===f?this.mar[1]:0});b.register_write(this.port|9,this,function(f){0===this.get_page()?(y(f,2),this.rsar=this.rsar&255|f<< -8&65280):y(f,2)});b.register_write(this.port|15,this,function(f){0===this.get_page()?(y(f,2),y(this.isr,2),this.imr=f,this.update_irq()):y(f,2)});b.register_read(this.port|3,this,function(){var f=this.get_page();return 0===f?(y(this.boundary,2),this.boundary):1===f?this.mac[2]:0});b.register_write(this.port|3,this,function(f){var g=this.get_page();0===g?(y(f,2),this.boundary=f):1===g?(y(f),this.mac[2]=f):y(f)});b.register_read(this.port|4,this,function(){var f=this.get_page();return 0===f?this.tsr: -1===f?this.mac[3]:0});b.register_write(this.port|4,this,function(f){var g=this.get_page();0===g?(y(f,2),this.tpsr=f):1===g?(y(f),this.mac[3]=f):y(f)});b.register_read(this.port|5,this,function(){var f=this.get_page();return 0===f?0:1===f?this.mac[4]:0});b.register_write(this.port|5,this,function(f){var g=this.get_page();0===g?(y(f,2),this.tcnt=this.tcnt&-256|f):1===g?(y(f),this.mac[4]=f):y(f)});b.register_read(this.port|6,this,function(){var f=this.get_page();return 0===f?0:1===f?this.mac[5]:0}); -b.register_write(this.port|6,this,function(f){var g=this.get_page();0===g?(y(f,2),this.tcnt=this.tcnt&255|f<<8):1===g?(y(f),this.mac[5]=f):y(f)});b.register_read(this.port|12,this,function(){var f=this.get_page();return 0===f?9:1===f?this.mar[4]:0});b.register_write(this.port|12,this,function(f){0===this.get_page()?(y(f,2),this.rxcr=f):y(f)});b.register_read(this.port|16,this,this.data_port_read8,this.data_port_read16,this.data_port_read32);b.register_write(this.port|16,this,this.data_port_write16, -this.data_port_write16,this.data_port_write32);a.devices.pci.register_device(this)}Dc.prototype.get_state=function(){var a=[];a[0]=this.isr;a[1]=this.imr;a[2]=this.cr;a[3]=this.dcfg;a[4]=this.rcnt;a[5]=this.tcnt;a[6]=this.tpsr;a[7]=this.rsar;a[8]=this.pstart;a[9]=this.curpg;a[10]=this.boundary;a[11]=this.pstop;a[12]=this.rxcr;a[13]=this.txcr;a[14]=this.tsr;a[15]=this.mac;a[16]=this.memory;return a}; -Dc.prototype.set_state=function(a){this.isr=a[0];this.imr=a[1];this.cr=a[2];this.dcfg=a[3];this.rcnt=a[4];this.tcnt=a[5];this.tpsr=a[6];this.rsar=a[7];this.pstart=a[8];this.curpg=a[9];this.boundary=a[10];this.pstop=a[11];this.rxcr=a[12];this.txcr=a[13];this.tsr=a[14];this.preserve_mac_from_state_image?(this.mac=a[15],this.memory=a[16]):this.mac_address_translation&&(this.mac_address_in_state=a[15],this.memory=a[16],Cc(this.mac_address_in_state),Cc(this.mac));this.bus.send("net"+this.id+"-mac",Cc(this.mac))}; -Dc.prototype.do_interrupt=function(a){y(a,2);this.isr|=a;this.update_irq()};Dc.prototype.update_irq=function(){this.imr&this.isr?this.pci.raise_irq(this.pci_id):this.pci.lower_irq(this.pci_id)};Dc.prototype.data_port_write=function(a){if(16>=this.rsar||16384<=this.rsar&&32768>this.rsar)this.memory[this.rsar]=a;this.rsar++;this.rcnt--;this.rsar>=this.pstop<<8&&(this.rsar+=this.pstart-this.pstop<<8);0===this.rcnt&&this.do_interrupt(64)}; -Dc.prototype.data_port_write16=function(a){this.data_port_write(a);this.dcfg&1&&this.data_port_write(a>>8)};Dc.prototype.data_port_write32=function(a){this.data_port_write(a);this.data_port_write(a>>8);this.data_port_write(a>>16);this.data_port_write(a>>24)};Dc.prototype.data_port_read=function(){let a=0;32768>this.rsar&&(a=this.memory[this.rsar]);this.rsar++;this.rcnt--;this.rsar>=this.pstop<<8&&(this.rsar+=this.pstart-this.pstop<<8);0===this.rcnt&&this.do_interrupt(64);return a}; -Dc.prototype.data_port_read8=function(){return this.data_port_read16()&255};Dc.prototype.data_port_read16=function(){return this.dcfg&1?this.data_port_read()|this.data_port_read()<<8:this.data_port_read()};Dc.prototype.data_port_read32=function(){return this.data_port_read()|this.data_port_read()<<8|this.data_port_read()<<16|this.data_port_read()<<24}; -Dc.prototype.receive=function(a){if(!(this.cr&1)&&(this.bus.send("eth-receive-end",[a.length]),this.rxcr&16||this.rxcr&4&&255===a[0]&&255===a[1]&&255===a[2]&&255===a[3]&&255===a[4]&&255===a[5]||!(this.rxcr&8&&1===(a[0]&1)||a[0]!==this.mac[0]||a[1]!==this.mac[1]||a[2]!==this.mac[2]||a[3]!==this.mac[3]||a[4]!==this.mac[4]||a[5]!==this.mac[5]))){this.mac_address_in_state&&(a=new Uint8Array(a),Bc(a,this.mac,this.mac_address_in_state));var b=this.curpg<<8,c=Math.max(60,a.length)+4,d=b+4,e=this.curpg+1+ -(c>>8),f=b+c,g=1+(c>>8),h=this.boundary>this.curpg?this.boundary-this.curpg:this.pstop-this.curpg+this.boundary-this.pstart;hthis.pstop<<8?(f=(this.pstop<<8)-d,this.memory.set(a.subarray(0,f),d),this.memory.set(a.subarray(f),this.pstart<<8),y(f)):(this.memory.set(a,d),60>a.length&&this.memory.fill(0,d+a.length,d+60)),e>=this.pstop&&(e+=this.pstart-this.pstop),this.memory[b]=1,this.memory[b+1]=e,this.memory[b+ -2]=c,this.memory[b+3]=c>>8,this.curpg=e,y(b),y(c),y(e),this.do_interrupt(1))}};Dc.prototype.get_page=function(){return this.cr>>6&3};function Ec(a,b){this.bus=b;this.rows=25;this.cols=80;this.ports=4;b=[{size_supported:16,notify_offset:0},{size_supported:16,notify_offset:1},{size_supported:16,notify_offset:2},{size_supported:16,notify_offset:3}];for(let c=1;c{}},notification:{initial_port:47360, -single_handler:!1,handlers:[()=>{},c=>{const d=this.virtio.queues[c],e=3>1:0;for(;d.has_request();){const f=d.pop_request(),g=new Uint8Array(f.length_readable);f.get_next_blob(g);this.bus.send("virtio-console"+e+"-output-bytes",g);this.Ack(c,f)}},()=>{},c=>{if(3===c)for(var d=this.virtio.queues[c];d.has_request();){var e=d.pop_request(),f=new Uint8Array(e.length_readable);e.get_next_blob(f);var g=I(["w","h","h"],f,{offset:0});f=g[0];g=g[1];this.Ack(c,e);switch(g){case 0:for(e=0;ethis.cols,write:()=>{}},{bytes:2,name:"rows",read:()=>this.rows,write:()=>{}},{bytes:4,name:"max_nr_ports",read:()=>this.ports,write:()=>{}},{bytes:4,name:"emerg_wr",read:()=>0,write:()=>{}}]}});for(let c=0;c< -this.ports;++c){const d=0===c?0:2*c+2;this.bus.register("virtio-console"+c+"-input-bytes",function(e){var f=this.virtio.queues[d];f.has_request()&&(f=f.pop_request(),this.Send(d,f,new Uint8Array(e)))},this);this.bus.register("virtio-console"+c+"-resize",function(e){0===c&&(this.cols=e[0],this.rows=e[1]);this.virtio.queues[2].is_configured()&&this.virtio.queues[2].has_request()&&this.SendWindowSize(c,e[0],e[1])},this)}} -Ec.prototype.SendWindowSize=function(a,b,c){c=c||this.rows;b=b||this.cols;const d=this.virtio.queues[2].pop_request(),e=new Uint8Array(12);G(["w","h","h","h","h"],[a,5,0,c,b],e,0);this.Send(2,d,e)};Ec.prototype.SendName=function(a,b){const c=this.virtio.queues[2].pop_request();b=(new TextEncoder).encode(b);const d=new Uint8Array(8+b.length+1);G(["w","h","h"],[a,7,1],d,0);for(a=0;ab)<<5|(0>a)<<4|8|this.mouse_clicks;this.last_mouse_packet=Date.now();this.mouse_buffer.push(c);this.mouse_buffer.push(a);this.mouse_buffer.push(b);4===this.mouse_id?(this.mouse_buffer.push(0|this.wheel_movement&15),this.wheel_movement=0):3===this.mouse_id&&(this.mouse_buffer.push(this.wheel_movement&255),this.wheel_movement=0);this.raise_irq()}; -Gc.prototype.apply_scaling2=function(a){var b=a>>31;switch(Math.abs(a)){case 0:case 1:case 3:return a;case 2:return b;case 4:return 6*b;case 5:return 9*b;default:return a<<1}}; -Gc.prototype.port60_read=function(){this.next_byte_is_ready=!1;if(!this.kbd_buffer.length&&!this.mouse_buffer.length)return this.last_port60_byte;this.next_byte_is_aux?(this.cpu.device_lower_irq(12),this.last_port60_byte=this.mouse_buffer.shift()):(this.cpu.device_lower_irq(1),this.last_port60_byte=this.kbd_buffer.shift());y(this.last_port60_byte);(this.kbd_buffer.length||this.mouse_buffer.length)&&this.raise_irq();return this.last_port60_byte}; -Gc.prototype.port64_read=function(){var a=16;this.next_byte_is_ready&&(a|=1);this.next_byte_is_aux&&(a|=32);y(a);return a}; -Gc.prototype.port60_write=function(a){y(a);if(this.read_command_register)this.command_register=a,this.read_command_register=!1,y(this.command_register);else if(this.read_output_register)this.read_output_register=!1,this.mouse_buffer.clear(),this.mouse_buffer.push(a),this.mouse_irq();else if(this.next_read_sample){this.next_read_sample=!1;this.mouse_buffer.clear();this.mouse_buffer.push(250);this.sample_rate=a;switch(this.mouse_detect_state){case -1:60===a?(this.mouse_reset_workaround=!0,this.mouse_detect_state= -0):(this.mouse_reset_workaround=!1,this.mouse_detect_state=200===a?1:0);break;case 0:200===a&&(this.mouse_detect_state=1);break;case 1:this.mouse_detect_state=100===a?2:200===a?3:0;break;case 2:80===a&&(this.mouse_id=3);this.mouse_detect_state=-1;break;case 3:80===a&&(this.mouse_id=4),this.mouse_detect_state=-1}y(a);y(this.mouse_id);this.sample_rate||(this.sample_rate=100);this.mouse_irq()}else if(this.next_read_resolution)this.next_read_resolution=!1,this.mouse_buffer.clear(),this.mouse_buffer.push(250), -this.resolution=3-1}}(7)},{type:Jc},{machine:Jc},{version1:U},{entry:U},{phoff:U},{shoff:U},{flags:U},{ehsize:Jc},{phentsize:Jc},{phnum:Jc},{shentsize:Jc},{shnum:Jc},{shstrndx:Jc}]);console.assert(52===Lc.reduce((a,b)=>a+b.size,0)); -const Mc=Kc([{type:U},{offset:U},{vaddr:U},{paddr:U},{filesz:U},{memsz:U},{flags:U},{align:U}]);console.assert(32===Mc.reduce((a,b)=>a+b.size,0));const Nc=Kc([{name:U},{type:U},{flags:U},{addr:U},{offset:U},{size:U},{link:U},{info:U},{addralign:U},{entsize:U}]);console.assert(40===Nc.reduce((a,b)=>a+b.size,0));function Kc(a){return a.map(function(b){var c=Object.keys(b);console.assert(1===c.length);c=c[0];b=b[c];console.assert(0e;e++)(e&d.mask)===d.code&&(b[e]=d)}return b}; -V.prototype.raise_irq=function(){this.sra&128||(this.cpu.device_raise_irq(6),this.sra|=128);this.reset_sense_int_count=0};V.prototype.lower_irq=function(){this.status0=0;this.sra&128&&(this.cpu.device_lower_irq(6),this.sra&=-129)};V.prototype.set_curr_drive_no=function(a){this.curr_drive_no=a&1;return this.drives[this.curr_drive_no]};V.prototype.enter_command_phase=function(){this.cmd_phase=1;this.cmd_remaining=this.cmd_cursor=0;this.msr&=-81;this.msr|=128}; -V.prototype.enter_result_phase=function(a){this.cmd_phase=3;this.response_cursor=0;this.response_length=a;this.msr|=208};V.prototype.reset_fdc=function(){this.lower_irq("controller reset");this.sra=0;this.srb=192;this.dor=12;this.msr=128;this.curr_drive_no=0;this.status0|=192;this.response_length=this.response_cursor=0;this.drives[0].seek(0,0,1);this.drives[1].seek(0,0,1);this.enter_command_phase();this.raise_irq("controller reset");this.reset_sense_int_count=4}; -V.prototype.read_reg_sra=function(){y(this.sra);return this.sra};V.prototype.read_reg_srb=function(){y(this.srb);return this.srb};V.prototype.read_reg_dor=function(){const a=this.dor&-4|this.curr_drive_no;y(a);return a};V.prototype.read_reg_tdr=function(){y(this.tdr);return this.tdr};V.prototype.read_reg_msr=function(){y(this.msr);this.dsr&=-65;this.dor|=4;return this.msr}; -V.prototype.read_reg_fifo=function(){this.dsr&=-65;if(!(this.msr&128&&this.msr&64)||3!==this.cmd_phase)return 0;if(this.response_cursor>4);this.curr_drive_no=b&1;this.dor=a};V.prototype.write_reg_tdr=function(a){this.dor&4?(y(a),this.tdr=a&4):y(a)};V.prototype.write_reg_dsr=function(a){this.dor&4?(y(a),a&128&&(this.dor&=-5,this.reset_fdc(),this.dor|=4),a&64&&this.reset_fdc(),this.dsr=a):y(a)}; -V.prototype.write_reg_fifo=function(a){this.dsr&=-65;if(this.dor&4)if(!(this.msr&128)||this.msr&64)y(a);else if(1!==this.cmd_phase)y(a);else{if(0===this.cmd_remaining){var b=this.cmd_table[a];this.cmd_code=a;this.cmd_remaining=b.argc;this.cmd_flags=this.cmd_cursor=0;(6===b.code||5===b.code)&&this.cmd_code&128&&(this.cmd_flags|=1);this.cmd_remaining&&(this.msr|=128);this.msr|=16}else this.cmd_buffer[this.cmd_cursor++]=a,this.cmd_remaining--;0===this.cmd_remaining&&(this.cmd_phase=2,a=this.cmd_table[this.cmd_code], -b=this.cmd_buffer.slice(0,this.cmd_cursor),a.handler.call(this,b))}else y(a)};V.prototype.write_reg_ccr=function(a){this.dor&4?(y(a),this.dsr=this.dsr&-4|a&3):y(a)};V.prototype.exec_unimplemented=function(){y(this.cmd_code);this.status0=128;this.response_data[0]=this.status0;this.enter_result_phase(1)};V.prototype.exec_read=function(a){this.start_read_write(a,!1)};V.prototype.exec_write=function(a){this.start_read_write(a,!0)}; -V.prototype.exec_seek=function(a){const b=this.set_curr_drive_no(a[0]&1);a=a[1];this.enter_command_phase();b.seek(b.curr_head,a,b.curr_sect);this.status0|=32;this.raise_irq("SEEK command")}; -V.prototype.exec_sense_interrupt_status=function(){const a=this.drives[this.curr_drive_no];let b;if(0>2&1;0!==b.max_sect&&(b.curr_sect=b.curr_sect%b.max_sect+1);this.end_read_write(0,0,0)}; -V.prototype.exec_specify=function(a){const b=a[1];this.step_rate_interval=a[0]>>4;this.head_load_time=b>>1;this.dor=b&1?this.dor&-9:this.dor|8;this.enter_command_phase()};V.prototype.exec_sense_drive_status=function(a){a=a[0];const b=this.set_curr_drive_no(a&1);b.curr_head=a>>2&1;this.response_data[0]=(b.read_only?64:0)|(0===b.curr_track?16:0)|b.curr_head<<2|this.curr_drive_no|40;this.enter_result_phase(1)}; -V.prototype.exec_perpendicular_mode=function(a){a=a[0];a&128&&(this.drives[this.curr_drive_no].perpendicular=a&7);this.enter_command_phase()};V.prototype.exec_configure=function(a){this.fdc_config=a[1];this.precomp_trk=a[2];this.enter_command_phase()};V.prototype.exec_lock=function(){this.cmd_code&128?(this.locked=!0,this.response_data[0]=16):(this.locked=!1,this.response_data[0]=0);this.enter_result_phase(1)}; -V.prototype.exec_dump_regs=function(){const a=this.drives[this.curr_drive_no];this.response_data[0]=this.drives[0].curr_track;this.response_data[1]=this.drives[1].curr_track;this.response_data[2]=0;this.response_data[3]=0;this.response_data[4]=this.step_rate_interval;this.response_data[5]=this.head_load_time<<1|(this.dor&8?1:0);this.response_data[6]=a.max_sect;this.response_data[7]=(this.locked?128:0)|a.perpendicular<<2;this.response_data[8]=this.fdc_config;this.response_data[9]=this.precomp_trk; -this.enter_result_phase(10)};V.prototype.exec_version=function(){this.response_data[0]=144;this.enter_result_phase(1)};V.prototype.exec_part_id=function(){this.response_data[0]=65;this.enter_result_phase(1)}; -V.prototype.start_read_write=function(a,b){const c=this.set_curr_drive_no(a[0]&1),d=a[1],e=a[2],f=a[3];var g=a[4];const h=a[5];a=128>a[7]?a[7]:128;switch(c.seek(e,d,f)){case 2:this.end_read_write(64,0,0);this.response_data[3]=d;this.response_data[4]=e;this.response_data[5]=f;return;case 3:this.end_read_write(64,128,0);this.response_data[3]=d;this.response_data[4]=e;this.response_data[5]=f;return;case 1:this.status0|=32}const l=128<<(7=a)){this.end_read_write(64,1,0);this.response_data[3]=d;this.response_data[4]=e;this.response_data[5]=f;return}this.eot=h;b&&c.read_only?(this.end_read_write(96,2,0),this.response_data[3]=d,this.response_data[4]=e,this.response_data[5]=f):this.dor&8&&(this.msr&=-129,(b?this.dma.do_write:this.dma.do_read).call(this.dma,c.buffer,g,a,2,m=>{m?this.end_read_write(64,0,0):(this.seek_next_sect(),this.end_read_write(0,0,0))}))}; -V.prototype.end_read_write=function(a,b,c){const d=this.drives[this.curr_drive_no];this.status0&=-8;this.status0|=this.curr_drive_no;d.curr_head&&(this.status0|=4);this.status0|=a;this.msr|=192;this.msr&=-33;this.response_data[0]=this.status0;this.response_data[1]=b;this.response_data[2]=c;this.response_data[3]=d.curr_track;this.response_data[4]=d.curr_head;this.response_data[5]=d.curr_sect;this.response_data[6]=2;this.enter_result_phase(7);this.raise_irq(this.cmd_table[this.cmd_code].name+" command")}; -V.prototype.seek_next_sect=function(){const a=this.drives[this.curr_drive_no];let b=a.curr_track,c=a.curr_head,d=a.curr_sect,e=1;d>=a.max_sect||d===this.eot?(d=1,this.cmd_flags&1?0===c&&2===a.max_head?c=1:(c=0,b++,this.status0|=32,1===a.max_head&&(e=0)):(this.status0|=32,b++,e=0)):d++;a.seek(c,b,d);return e}; -V.prototype.get_state=function(){const a=[];a[19]=this.sra;a[20]=this.srb;a[21]=this.dor;a[22]=this.tdr;a[23]=this.msr;a[24]=this.dsr;a[25]=this.cmd_phase;a[26]=this.cmd_code;a[27]=this.cmd_flags;a[28]=this.cmd_buffer;a[29]=this.cmd_cursor;a[30]=this.cmd_remaining;a[31]=this.response_data;a[32]=this.response_cursor;a[33]=this.response_length;a[34]=this.status0;a[35]=this.status1;a[36]=this.curr_drive_no;a[37]=this.reset_sense_int_count;a[38]=this.locked;a[39]=this.step_rate_interval;a[40]=this.head_load_time; -a[41]=this.fdc_config;a[42]=this.precomp_trk;a[43]=this.eot;a[44]=this.drives[0].get_state();a[45]=this.drives[1].get_state();return a}; -V.prototype.set_state=function(a){"undefined"!==typeof a[19]&&(this.sra=a[19],this.srb=a[20],this.dor=a[21],this.tdr=a[22],this.msr=a[23],this.dsr=a[24],this.cmd_phase=a[25],this.cmd_code=a[26],this.cmd_flags=a[27],this.cmd_buffer.set(a[28]),this.cmd_cursor=a[29],this.cmd_remaining=a[30],this.response_data.set(a[31]),this.response_cursor=a[32],this.response_length=a[33],this.status0=a[34],this.status1=a[35],this.curr_drive_no=a[36],this.reset_sense_int_count=a[37],this.locked=a[38],this.step_rate_interval= -a[39],this.head_load_time=a[40],this.fdc_config=a[41],this.precomp_trk=a[42],this.eot=a[43],this.drives[0].set_state(a[44]),this.drives[1].set_state(a[45]))}; -const Sc=[{drive_type:4,sectors:18,tracks:80,heads:2},{drive_type:4,sectors:20,tracks:80,heads:2},{drive_type:4,sectors:21,tracks:80,heads:2},{drive_type:4,sectors:21,tracks:82,heads:2},{drive_type:4,sectors:21,tracks:83,heads:2},{drive_type:4,sectors:22,tracks:80,heads:2},{drive_type:4,sectors:23,tracks:80,heads:2},{drive_type:4,sectors:24,tracks:80,heads:2},{drive_type:5,sectors:36,tracks:80,heads:2},{drive_type:5,sectors:39,tracks:80,heads:2},{drive_type:5,sectors:40,tracks:80,heads:2},{drive_type:5, -sectors:44,tracks:80,heads:2},{drive_type:5,sectors:48,tracks:80,heads:2},{drive_type:4,sectors:8,tracks:80,heads:2},{drive_type:4,sectors:9,tracks:80,heads:2},{drive_type:4,sectors:10,tracks:80,heads:2},{drive_type:4,sectors:10,tracks:82,heads:2},{drive_type:4,sectors:10,tracks:83,heads:2},{drive_type:4,sectors:13,tracks:80,heads:2},{drive_type:4,sectors:14,tracks:80,heads:2},{drive_type:2,sectors:15,tracks:80,heads:2},{drive_type:2,sectors:18,tracks:80,heads:2},{drive_type:2,sectors:18,tracks:82, -heads:2},{drive_type:2,sectors:18,tracks:83,heads:2},{drive_type:2,sectors:20,tracks:80,heads:2},{drive_type:2,sectors:9,tracks:80,heads:2},{drive_type:2,sectors:11,tracks:80,heads:2},{drive_type:2,sectors:9,tracks:40,heads:2},{drive_type:2,sectors:9,tracks:40,heads:1},{drive_type:2,sectors:10,tracks:41,heads:2},{drive_type:2,sectors:10,tracks:42,heads:2},{drive_type:2,sectors:8,tracks:40,heads:2},{drive_type:2,sectors:8,tracks:40,heads:1},{drive_type:4,sectors:9,tracks:80,heads:1},{drive_type:1, -sectors:10,tracks:40,heads:1},{drive_type:1,sectors:10,tracks:40,heads:2}];function Rc(a,b,c,d){this.name=a;this.curr_head=this.curr_track=this.max_sect=this.max_head=this.max_track=this.drive_type=0;this.curr_sect=1;this.perpendicular=0;this.read_only=!1;this.media_changed=!0;this.buffer=null;Object.seal(this);a=b?.drive_type;void 0!==a&&0<=a&&5>=a&&(this.drive_type=a);this.insert_disk(c,!!b?.read_only);0===this.drive_type&&void 0===a&&(this.drive_type=d)} -Rc.prototype.insert_disk=function(a,b){if(!a)return!1;a instanceof Uint8Array&&(a=new z(a.buffer));const [c,d]=this.find_disk_format(a,this.drive_type);if(!c)return!1;this.max_track=d.tracks;this.max_head=d.heads;this.max_sect=d.sectors;this.read_only=!!b;this.media_changed=!0;this.buffer=c;0===this.drive_type&&(this.drive_type=d.drive_type);return!0};Rc.prototype.eject_disk=function(){this.max_sect=this.max_head=this.max_track=0;this.media_changed=!0;this.buffer=null}; -Rc.prototype.get_buffer=function(){return this.buffer?new Uint8Array(this.buffer.buffer):null};Rc.prototype.chs2lba=function(a,b,c){return(a*this.max_head+b)*this.max_sect+c-1}; -Rc.prototype.find_disk_format=function(a,b){const c=0===b,d=a.byteLength;let e=-1,f=-1,g=-1,h=-1,l=-1;for(let m=0;mthis.max_track||0!==a&&1===this.max_head)return 2;if(c>this.max_sect)return 3;let d=0;const e=this.chs2lba(this.curr_track,this.curr_head,this.curr_sect),f=this.chs2lba(b,a,c);e!==f&&(this.curr_track!==b&&(this.buffer&&(this.media_changed=!1),d=1),this.curr_head=a,this.curr_track=b,this.curr_sect=c);this.buffer||(d=2);return d}; -Rc.prototype.get_state=function(){const a=[];a[0]=this.drive_type;a[1]=this.max_track;a[2]=this.max_head;a[3]=this.max_sect;a[4]=this.curr_track;a[5]=this.curr_head;a[6]=this.curr_sect;a[7]=this.perpendicular;a[8]=this.read_only;a[9]=this.media_changed;a[10]=this.buffer?this.buffer.get_state():null;return a}; -Rc.prototype.set_state=function(a){this.drive_type=a[0];this.max_track=a[1];this.max_head=a[2];this.max_sect=a[3];this.curr_track=a[4];this.curr_head=a[5];this.curr_sect=a[6];this.perpendicular=a[7];this.read_only=a[8];this.media_changed=a[9];a[10]?(this.buffer||(this.buffer=new z(new ArrayBuffer(0))),this.buffer.set_state(a[10])):this.buffer=null};const Tc={[70]:{name:"GET CONFIGURATION",flags:0},[74]:{name:"GET EVENT STATUS NOTIFICATION",flags:0},[18]:{name:"INQUIRY",flags:0},[189]:{name:"MECHANISM STATUS",flags:0},[26]:{name:"MODE SENSE (6)",flags:0},[90]:{name:"MODE SENSE (10)",flags:0},[69]:{name:"PAUSE",flags:1},[30]:{name:"PREVENT ALLOW MEDIUM REMOVAL",flags:0},[40]:{name:"READ (10)",flags:1},[168]:{name:"READ (12)",flags:1},[37]:{name:"READ CAPACITY",flags:1},[190]:{name:"READ CD",flags:1},[81]:{name:"READ DISK INFORMATION",flags:1}, -[66]:{name:"READ SUBCHANNEL",flags:1},[67]:{name:"READ TOC PMA ATIP",flags:1},[82]:{name:"READ TRACK INFORMATION",flags:1},[3]:{name:"REQUEST SENSE",flags:0},[27]:{name:"START STOP UNIT",flags:0},[0]:{name:"TEST UNIT READY",flags:1}}; -function Uc(a,b,c){this.cpu=a;this.bus=b;this.secondary=this.primary=void 0;b=c&&c[0][0];const d=c&&c[1][0];if(b||d){b&&(this.primary=new Vc(this,0,c[0],496,1014,14));d&&(this.secondary=new Vc(this,1,c[1],368,886,15));c=b?this.primary.command_base:0;const e=b?this.primary.control_base:0,f=d?this.secondary.command_base:0,g=d?this.secondary.control_base:0;this.name="ide";this.pci_id=240;this.pci_space=[134,128,16,112,5,0,160,2,0,128,1,1,0,0,0,0,c&255|1,c>>8,0,0,e&255|1,e>>8,0,0,f&255|1,f>>8,0,0,g&255| -1,g>>8,0,0,1,180,0,0,0,0,0,0,0,0,0,0,67,16,212,130,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.pci_bars=[b?{size:8}:void 0,b?{size:1}:void 0,d?{size:8}:void 0,d?{size:1}:void 0,{size:16}];a.devices.pci.register_device(this)}Object.seal(this)} -Uc.prototype.get_state=function(){const a=[];a[0]=this.primary;a[1]=this.secondary;return a};Uc.prototype.set_state=function(a){this.primary&&this.primary.set_state(a[0]);this.secondary&&this.secondary.set_state(a[1])}; -function Vc(a,b,c,d,e,f){this.controller=a;this.channel_nr=b;this.cpu=a.cpu;this.bus=a.bus;this.command_base=d;this.control_base=e;this.irq=f;this.name="ide"+b;d=c?c[0]:void 0;c=c?c[1]:void 0;this.master=new W(this,0,d?.buffer,d?.is_cdrom);this.slave=new W(this,1,c?.buffer,c?.is_cdrom);this.current_interface=this.master;this.device_control_reg=2;this.dma_command=this.dma_status=this.prdt_addr=0;a=a.cpu;a.io.register_read(this.command_base|0,this,function(){return this.current_interface.read_data(1)}, -function(){return this.current_interface.read_data(2)},function(){return this.current_interface.read_data(4)});a.io.register_read(this.command_base|1,this,function(){return this.current_interface.error_reg&255});a.io.register_read(this.command_base|2,this,function(){return this.current_interface.sector_count_reg&255});a.io.register_read(this.command_base|3,this,function(){return this.current_interface.lba_low_reg&255});a.io.register_read(this.command_base|4,this,function(){return this.current_interface.lba_mid_reg& -255});a.io.register_read(this.command_base|5,this,function(){return this.current_interface.lba_high_reg&255});a.io.register_read(this.command_base|6,this,function(){return this.current_interface.device_reg&255});a.io.register_read(this.command_base|7,this,function(){const g=this.read_status();this.cpu.device_lower_irq(this.irq);return g});a.io.register_write(this.command_base|0,this,function(g){this.current_interface.write_data_port8(g)},function(g){this.current_interface.write_data_port16(g)},function(g){this.current_interface.write_data_port32(g)}); -a.io.register_write(this.command_base|1,this,function(g){this.current_interface.features_reg=(this.current_interface.features_reg<<8|g)&65535});a.io.register_write(this.command_base|2,this,function(g){this.current_interface.sector_count_reg=(this.current_interface.sector_count_reg<<8|g)&65535});a.io.register_write(this.command_base|3,this,function(g){this.current_interface.lba_low_reg=(this.current_interface.lba_low_reg<<8|g)&65535});a.io.register_write(this.command_base|4,this,function(g){this.current_interface.lba_mid_reg= -(this.current_interface.lba_mid_reg<<8|g)&65535});a.io.register_write(this.command_base|5,this,function(g){this.current_interface.lba_high_reg=(this.current_interface.lba_high_reg<<8|g)&65535});a.io.register_write(this.command_base|6,this,function(g){const h=g&16;if(h&&this.current_interface===this.master||!h&&this.current_interface===this.slave)this.current_interface=h?this.slave:this.master;this.current_interface.device_reg=g;this.current_interface.is_lba=g>>6&1;this.current_interface.head=g&15}); -a.io.register_write(this.command_base|7,this,function(g){this.current_interface.status_reg&=-34;this.current_interface.ata_command(g);this.cpu.device_lower_irq(this.irq)});a.io.register_read(this.control_base|0,this,this.read_status);a.io.register_write(this.control_base|0,this,this.write_control);b=46080+8*b;a.io.register_read(b|0,this,this.dma_read_command8,void 0,this.dma_read_command);a.io.register_write(b|0,this,this.dma_write_command8,void 0,this.dma_write_command);a.io.register_read(b|2,this, -this.dma_read_status);a.io.register_write(b|2,this,this.dma_write_status);a.io.register_read(b|4,this,void 0,void 0,this.dma_read_addr);a.io.register_write(b|4,this,void 0,void 0,this.dma_set_addr)}Vc.prototype.read_status=function(){return this.current_interface.drive_connected?this.current_interface.status_reg:0};Vc.prototype.write_control=function(a){a&4&&(this.cpu.device_lower_irq(this.irq),this.master.device_reset(),this.slave.device_reset());this.device_control_reg=a}; -Vc.prototype.dma_read_addr=function(){return this.prdt_addr};Vc.prototype.dma_set_addr=function(a){this.prdt_addr=a};Vc.prototype.dma_read_status=function(){return this.dma_status};Vc.prototype.dma_write_status=function(a){this.dma_status&=~(a&6)};Vc.prototype.dma_read_command=function(){return this.dma_read_command8()|this.dma_read_status()<<16};Vc.prototype.dma_read_command8=function(){return this.dma_command}; -Vc.prototype.dma_write_command=function(a){this.dma_write_command8(a&255);this.dma_write_status(a>>16&255)}; -Vc.prototype.dma_write_command8=function(a){const b=this.dma_command;this.dma_command=a&9;if((b&1)!==(a&1))if(0===(a&1))this.dma_status&=-2;else switch(this.dma_status|=1,this.current_interface.current_command){case 200:case 37:this.current_interface.do_ata_read_sectors_dma();break;case 202:case 53:this.current_interface.do_ata_write_sectors_dma();break;case 160:this.current_interface.do_atapi_dma();break;default:y(this.current_interface.current_command),this.dma_status&=-2,this.dma_status|=2,this.push_irq()}}; -Vc.prototype.push_irq=function(){0===(this.device_control_reg&2)&&(this.dma_status|=4,this.cpu.device_raise_irq(this.irq))};Vc.prototype.get_state=function(){var a=[];a[0]=this.master;a[1]=this.slave;a[2]=this.command_base;a[3]=this.irq;a[5]=this.control_base;a[7]=this.name;a[8]=this.device_control_reg;a[9]=this.prdt_addr;a[10]=this.dma_status;a[11]=this.current_interface===this.master;a[12]=this.dma_command;return a}; -Vc.prototype.set_state=function(a){this.master.set_state(a[0]);this.slave.set_state(a[1]);this.command_base=a[2];this.irq=a[3];this.control_base=a[5];this.name=a[7];this.device_control_reg=a[8];this.prdt_addr=a[9];this.dma_status=a[10];this.current_interface=a[11]?this.master:this.slave;this.dma_command=a[12]}; -function W(a,b,c,d){this.channel=a;this.name=a.name+"."+b;this.bus=a.bus;this.channel_nr=a.channel_nr;this.interface_nr=b;this.cpu=a.cpu;this.buffer=null;this.drive_connected=d||!!c;this.sector_size=d?2048:512;this.is_atapi=d;this.sector_count=0;this.head_count=this.is_atapi?1:0;this.device_reg=this.head=this.lba_high_reg=this.lba_mid_reg=this.features_reg=this.lba_low_reg=this.sector_count_reg=this.is_lba=this.cylinder_count=this.sectors_per_track=0;this.status_reg=80;this.sectors_per_drq=128;this.data_pointer= -this.error_reg=0;this.data=new Uint8Array(65536);this.data16=new Uint16Array(this.data.buffer);this.data32=new Int32Array(this.data.buffer);this.data_end=this.data_length=0;this.current_command=-1;this.last_io_id=this.write_dest=0;this.in_progress_io_ids=new Set;this.cancelled_io_ids=new Set;this.current_atapi_command=-1;this.atapi_add_sense=this.atapi_sense_key=0;this.medium_changed=!1;this.set_disk_buffer(c);Object.seal(this)}W.prototype.has_disk=function(){return!!this.buffer}; -W.prototype.eject=function(){this.is_atapi&&this.buffer&&(this.medium_changed=!0,this.buffer=null,this.status_reg=89,this.error_reg=96,this.push_irq())};W.prototype.set_cdrom=function(a){this.is_atapi&&a&&(this.set_disk_buffer(a),this.medium_changed=!0)}; -W.prototype.set_disk_buffer=function(a){if(a){this.buffer=a;this.is_atapi&&(this.status_reg=89,this.error_reg=96);this.sector_count=this.buffer.byteLength/this.sector_size;this.sector_count!==(this.sector_count|0)&&(this.sector_count=Math.ceil(this.sector_count));this.is_atapi?(this.head_count=1,this.sectors_per_track=2048):(this.head_count=16,this.sectors_per_track=63);this.cylinder_count=this.sector_count/this.head_count/this.sectors_per_track;this.cylinder_count!==(this.cylinder_count|0)&&(this.cylinder_count= -Math.floor(this.cylinder_count));if(0===this.interface_nr){a=this.cpu.devices.rtc;a.cmos_write(57,a.cmos_read(57)|1<<4*this.channel_nr);a.cmos_write(18,a.cmos_read(18)&15|240);const b=0===this.channel_nr?27:36;a.cmos_write(b+0,this.cylinder_count&255);a.cmos_write(b+1,this.cylinder_count>>8&255);a.cmos_write(b+2,this.head_count&255);a.cmos_write(b+3,255);a.cmos_write(b+4,255);a.cmos_write(b+5,200);a.cmos_write(b+6,this.cylinder_count&255);a.cmos_write(b+7,this.cylinder_count>>8&255);a.cmos_write(b+ -8,this.sectors_per_track&255)}this.channel.cpu&&this.push_irq()}};W.prototype.device_reset=function(){this.is_atapi?(this.status_reg=0,this.lba_low_reg=this.error_reg=this.sector_count_reg=1,this.lba_mid_reg=20,this.lba_high_reg=235):(this.status_reg=81,this.lba_low_reg=this.error_reg=this.sector_count_reg=1,this.lba_high_reg=this.lba_mid_reg=0);this.cancel_io_operations()};W.prototype.push_irq=function(){this.channel.push_irq()}; -W.prototype.ata_abort_command=function(){this.error_reg=4;this.status_reg=65;this.push_irq()};W.prototype.capture_regs=function(){return`ST=${y(this.status_reg&255)} ER=${y(this.error_reg&255)} `+`SC=${y(this.sector_count_reg&255)} LL=${y(this.lba_low_reg&255)} `+`LM=${y(this.lba_mid_reg&255)} LH=${y(this.lba_high_reg&255)} `+`FE=${y(this.features_reg&255)}`}; -W.prototype.ata_command=function(a){if(this.drive_connected||144===a)switch(this.current_command=a,this.error_reg=0,a){case 8:this.data_length=this.data_end=this.data_pointer=0;this.device_reset();this.push_irq();break;case 16:this.lba_mid_reg=0;this.status_reg=80;this.push_irq();break;case 248:a=this.sector_count-1;this.lba_low_reg=a&255;this.lba_mid_reg=a>>8&255;this.lba_high_reg=a>>16&255;this.device_reg=this.device_reg&240|a>>24&15;this.status_reg=80;this.push_irq();break;case 39:a=this.sector_count- -1;this.lba_low_reg=a&255;this.lba_mid_reg=a>>8&255;this.lba_high_reg=a>>16&255;this.lba_low_reg|=a>>24<<8&65280;this.status_reg=80;this.push_irq();break;case 32:this.is_atapi?(this.lba_mid_reg=20,this.lba_high_reg=235,this.ata_abort_command()):this.ata_read_sectors(a);break;case 36:case 41:case 196:this.is_atapi?this.ata_abort_command():this.ata_read_sectors(a);break;case 48:case 52:case 57:case 197:this.is_atapi?this.ata_abort_command():this.ata_write_sectors(a);break;case 144:this.channel.master.status_reg= -80;this.channel.master.error_reg=1;this.channel.master.push_irq();this.channel.slave.drive_connected&&(this.channel.slave.status_reg=80,this.channel.slave.error_reg=1,this.channel.slave.push_irq());break;case 145:this.status_reg=80;this.push_irq();break;case 160:this.is_atapi?(this.data_allocate(12),this.data_end=12,this.sector_count_reg=1,this.status_reg=88,this.push_irq()):this.ata_abort_command();break;case 161:this.is_atapi?(this.create_identify_packet(),this.status_reg=88,this.push_irq()):this.ata_abort_command(); -break;case 198:y(this.sector_count_reg&255);this.sectors_per_drq=this.sector_count_reg&255;this.status_reg=80;this.push_irq();break;case 200:case 37:this.ata_read_sectors_dma(a);break;case 202:case 53:this.ata_write_sectors_dma(a);break;case 64:this.status_reg=80;this.push_irq();break;case 218:this.is_atapi&&(this.buffer||(this.error_reg|=2),this.medium_changed&&(this.error_reg|=32,this.medium_changed=!1),this.error_reg|=64);this.status_reg=80;this.push_irq();break;case 224:this.status_reg=80;this.push_irq(); -break;case 225:this.status_reg=80;this.push_irq();break;case 231:this.status_reg=80;this.push_irq();break;case 234:this.status_reg=80;this.push_irq();break;case 236:this.is_atapi?(this.lba_mid_reg=20,this.lba_high_reg=235,this.ata_abort_command()):(this.create_identify_packet(),this.status_reg=88,this.push_irq());break;case 239:this.status_reg=80;this.push_irq();break;case 222:this.status_reg=64;this.push_irq();break;case 245:this.status_reg=80;this.push_irq();break;case 249:this.ata_abort_command(); -break;case 0:this.ata_abort_command();break;case 240:y(a);this.capture_regs();this.ata_abort_command();break;default:y(a),this.capture_regs(),this.ata_abort_command()}else y(a)}; -W.prototype.atapi_handle=function(){var a=this.data[0],b=Tc[a]?Tc[a].flags:0;this.data_pointer=0;this.current_atapi_command=a;3!==a&&(this.atapi_add_sense=this.atapi_sense_key=0);if(!this.buffer&&b&1)this.atapi_check_condition_response(2,58),this.push_irq();else{switch(a){case 0:this.buffer?(this.data_allocate(0),this.data_end=this.data_length,this.status_reg=80):this.atapi_check_condition_response(2,58);break;case 3:this.data_allocate(this.data[4]);this.data_end=this.data_length;this.status_reg= -88;this.data[0]=240;this.data[2]=this.atapi_sense_key;this.data[7]=8;this.data[12]=this.atapi_add_sense;this.atapi_add_sense=this.atapi_sense_key=0;break;case 18:a=this.data[4];this.status_reg=88;y(this.data[1],2);this.data.set([5,128,1,49,31,0,0,0,83,79,78,89,32,32,32,32,67,68,45,82,79,77,32,67,68,85,45,49,48,48,48,32,49,46,49,97]);this.data_end=this.data_length=Math.min(36,a);break;case 26:this.data_allocate(this.data[4]);this.data_end=this.data_length;this.status_reg=88;break;case 30:this.data_allocate(0); -this.data_end=this.data_length;this.status_reg=80;break;case 37:a=this.sector_count-1;this.data_set(new Uint8Array([a>>24&255,a>>16&255,a>>8&255,a&255,0,0,this.sector_size>>8&255,this.sector_size&255]));this.data_end=this.data_length;this.status_reg=88;break;case 40:case 168:this.features_reg&1?this.atapi_read_dma(this.data):this.atapi_read(this.data);break;case 66:a=this.data[8];this.data_allocate(Math.min(8,a));this.data_end=this.data_length;this.status_reg=88;break;case 67:a=this.data[8]|this.data[7]<< -8;b=this.data[9]>>6;y(b,2);y(this.data[6]);this.data_allocate(a);this.data_end=this.data_length;0===b?(a=this.sector_count,this.data.set(new Uint8Array([0,18,1,1,0,20,1,0,0,0,0,0,0,22,170,0,a>>24,a>>16&255,a>>8&255,a&255]))):1===b&&this.data.set(new Uint8Array([0,10,1,1,0,0,0,0,0,0,0,0]));this.status_reg=88;break;case 70:a=Math.min(this.data[8]|this.data[7]<<8,32);this.data_allocate(a);this.data_end=this.data_length;this.data[0]=a-4>>24&255;this.data[1]=a-4>>16&255;this.data[2]=a-4>>8&255;this.data[3]= -a-4&255;this.data[6]=8;this.data[10]=3;this.status_reg=88;break;case 81:this.data_allocate(0);this.data_end=this.data_length;this.status_reg=80;break;case 82:this.atapi_check_condition_response(5,36);break;case 90:a=this.data[8]|this.data[7]<<8;b=this.data[2];y(b);42===b&&this.data_allocate(Math.min(30,a));this.data_end=this.data_length;this.status_reg=88;break;case 189:this.data_allocate(this.data[9]|this.data[8]<<8);this.data_end=this.data_length;this.data[5]=1;this.status_reg=88;break;case 27:a= -this.data[4]&3;y(this.data[1]&1);y(a);this.buffer&&2===a&&(this.medium_changed=!0,this.buffer=null);this.status_reg=80;this.data_allocate(0);this.data_end=this.data_length;break;case 69:case 74:this.atapi_check_condition_response(5,36);break;case 190:this.data_allocate(0);this.data_end=this.data_length;this.status_reg=80;break;default:y(this.data[0]),this.atapi_check_condition_response(5,36)}this.sector_count_reg=this.sector_count_reg&-8|2;0===(this.status_reg&128)&&this.push_irq();0===(this.status_reg& -128)&&0===this.data_length&&(this.sector_count_reg|=1,this.status_reg&=-9)}};W.prototype.atapi_check_condition_response=function(a,b){this.data_allocate(0);this.data_end=this.data_length;this.status_reg=65;this.error_reg=a<<4;this.sector_count_reg=this.sector_count_reg&-8|3;this.atapi_sense_key=a;this.atapi_add_sense=b}; -W.prototype.do_write=function(){this.status_reg=80;var a=this.data.subarray(0,this.data_length);this.ata_advance(this.current_command,this.data_length/512);this.push_irq();this.buffer.set(this.write_dest,a,function(){});this.report_write(this.data_length)}; -W.prototype.atapi_read=function(a){var b=a[2]<<24|a[3]<<16|a[4]<<8|a[5];a=168===a[0]?a[6]<<24|a[7]<<16|a[8]<<8|a[9]:a[7]<<8|a[8];var c=(a>>>0)*this.sector_size;b*=this.sector_size;this.data_length=0;var d=this.lba_high_reg<<8&65280|this.lba_mid_reg&255;this.lba_mid_reg=this.lba_high_reg=0;65535===d&&d--;d>c&&(d=c);this.buffer?b>=this.buffer.byteLength?(va(!1,this.name+": CD read: Outside of disk end="+y(b+c)+" size="+y(this.buffer.byteLength),32768),this.status_reg=255,this.push_irq()):0===c?(this.status_reg= -80,this.data_pointer=0):(c=Math.min(c,this.buffer.byteLength-b),this.status_reg=208,this.report_read_start(),this.read_buffer(b,c,e=>{this.data_set(e);this.status_reg=88;this.sector_count_reg=this.sector_count_reg&-8|2;this.push_irq();this.data_end=d&=-4;this.data_end>this.data_length&&(this.data_end=this.data_length);this.lba_mid_reg=this.data_end&255;this.lba_high_reg=this.data_end>>8&255;this.report_read_end(c)})):(this.status_reg=255,this.error_reg=65,this.push_irq())}; -W.prototype.atapi_read_dma=function(a){var b=a[2]<<24|a[3]<<16|a[4]<<8|a[5],c=168===a[0]?a[6]<<24|a[7]<<16|a[8]<<8|a[9]:a[7]<<8|a[8];c>>>=0;a=a[1];var d=c*this.sector_size,e=b*this.sector_size;ua(this.name+": CD read DMA lba="+y(b)+" lbacount="+y(c)+" bytecount="+y(d)+" flags="+y(a),32768);e>=this.buffer.byteLength?(va(!1,this.name+": CD read: Outside of disk end="+y(e+d)+" size="+y(this.buffer.byteLength),32768),this.status_reg=255,this.push_irq()):(this.status_reg=208,this.report_read_start(), -this.read_buffer(e,d,f=>{this.report_read_end(d);this.status_reg=88;this.sector_count_reg=this.sector_count_reg&-8|2;this.data_set(f);this.do_atapi_dma()}))}; -W.prototype.do_atapi_dma=function(){if(0!==(this.channel.dma_status&1)&&0!==(this.status_reg&8)){var a=this.channel.prdt_addr,b=0,c=this.data;do{var d=this.cpu.read32s(a),e=this.cpu.read16(a+4),f=this.cpu.read8(a+7)&128;e||(e=65536);this.cpu.write_blob(c.subarray(b,Math.min(b+e,this.data_length)),d);b+=e;a+=8;if(b>=this.data_length&&!f)break}while(!f);this.status_reg=80;this.channel.dma_status&=-2;this.sector_count_reg=this.sector_count_reg&-8|3;this.push_irq()}}; -W.prototype.read_data=function(a){if(this.data_pointer>>1]:this.data32[this.data_pointer>>>2];this.data_pointer+=a;this.data_pointer>=this.data_end&&this.read_end();return b}this.data_pointer+=a;return 0}; -W.prototype.read_end=function(){if(160===this.current_command)if(this.data_end===this.data_length)this.status_reg=80,this.sector_count_reg=this.sector_count_reg&-8|3,this.push_irq();else{this.status_reg=88;this.sector_count_reg=this.sector_count_reg&-8|2;this.push_irq();var a=this.lba_high_reg<<8&65280|this.lba_mid_reg&255;this.data_end+a>this.data_length?(this.lba_mid_reg=this.data_length-this.data_end&255,this.lba_high_reg=this.data_length-this.data_end>>8&255,this.data_end=this.data_length):this.data_end+= -a}else this.error_reg=0,this.data_pointer>=this.data_length?this.status_reg=80:(a=41===this.current_command||196===this.current_command?Math.min(this.sectors_per_drq,(this.data_length-this.data_end)/512):1,this.ata_advance(this.current_command,a),this.data_end+=512*a,this.status_reg=88,this.push_irq())}; -W.prototype.write_data_port=function(a,b){this.data_pointer>=this.data_end?(y(a),y(this.data_end),y(this.data_pointer)):(1===b?this.data[this.data_pointer++]=a:2===b?(this.data16[this.data_pointer>>>1]=a,this.data_pointer+=2):(this.data32[this.data_pointer>>>2]=a,this.data_pointer+=4),this.data_pointer===this.data_end&&this.write_end())};W.prototype.write_data_port8=function(a){this.write_data_port(a,1)};W.prototype.write_data_port16=function(a){this.write_data_port(a,2)}; -W.prototype.write_data_port32=function(a){this.write_data_port(a,4)};W.prototype.write_end=function(){160===this.current_command?this.atapi_handle():this.data_pointer>=this.data_length?this.do_write():(y(this.current_command),this.status_reg=88,this.data_end+=512,this.push_irq())}; -W.prototype.ata_advance=function(a,b){this.sector_count_reg-=b;36===a||41===a||37===a||52===a||57===a||53===a?(a=b+this.get_lba48(),this.lba_low_reg=a&255|a>>16&65280,this.lba_mid_reg=a>>8&255,this.lba_high_reg=a>>16&255):this.is_lba?(a=b+this.get_lba28(),this.lba_low_reg=a&255,this.lba_mid_reg=a>>8&255,this.lba_high_reg=a>>16&255,this.head=this.head&-16|a&15):(a=b+this.get_chs(),b=a/(this.head_count*this.sectors_per_track)|0,this.lba_mid_reg=b&255,this.lba_high_reg=b>>8&255,this.head=(a/this.sectors_per_track| -0)%this.head_count&15,this.lba_low_reg=a%this.sectors_per_track+1&255,this.get_chs())}; -W.prototype.ata_read_sectors=function(a){var b=36===a||41===a,c=this.get_count(b);b=this.get_lba(b);var d=32===a||36===a,e=c*this.sector_size;b*=this.sector_size;b+e>this.buffer.byteLength?(this.status_reg=255,this.push_irq()):(this.status_reg=192,this.report_read_start(),this.read_buffer(b,e,f=>{this.data_set(f);this.status_reg=88;this.data_end=d?512:Math.min(e,512*this.sectors_per_drq);this.ata_advance(a,d?1:Math.min(c,this.sectors_per_track));this.push_irq();this.report_read_end(e)}))}; -W.prototype.ata_read_sectors_dma=function(a){a=37===a;var b=this.get_count(a);this.get_lba(a)*this.sector_size+b*this.sector_size>this.buffer.byteLength?(this.status_reg=255,this.push_irq()):(this.status_reg=88,this.channel.dma_status|=1)}; -W.prototype.do_ata_read_sectors_dma=function(){var a=37===this.current_command,b=this.get_count(a);a=this.get_lba(a);var c=b*this.sector_size;a*=this.sector_size;this.report_read_start();this.read_buffer(a,c,d=>{var e=this.channel.prdt_addr,f=0;do{var g=this.cpu.read32s(e),h=this.cpu.read16(e+4),l=this.cpu.read8(e+7)&128;h||(h=65536);this.cpu.write_blob(d.subarray(f,f+h),g);f+=h;e+=8}while(!l);this.ata_advance(this.current_command,b);this.status_reg=80;this.channel.dma_status&=-2;this.current_command= --1;this.report_read_end(c);this.push_irq()})};W.prototype.ata_write_sectors=function(a){var b=52===a||57===a,c=this.get_count(b);b=this.get_lba(b);a=48===a||52===a;c*=this.sector_size;b*=this.sector_size;b+c>this.buffer.byteLength?(this.status_reg=255,this.push_irq()):(this.status_reg=88,this.data_allocate_noclear(c),this.data_end=a?512:Math.min(c,512*this.sectors_per_drq),this.write_dest=b)}; -W.prototype.ata_write_sectors_dma=function(a){a=53===a;var b=this.get_count(a);this.get_lba(a)*this.sector_size+b*this.sector_size>this.buffer.byteLength?(this.status_reg=255,this.push_irq()):(this.status_reg=88,this.channel.dma_status|=1)}; -W.prototype.do_ata_write_sectors_dma=function(){var a=53===this.current_command,b=this.get_count(a),c=this.get_lba(a);a=b*this.sector_size;c*=this.sector_size;var d=this.channel.prdt_addr,e=0;const f=new Uint8Array(a);do{var g=this.cpu.read32s(d),h=this.cpu.read16(d+4),l=this.cpu.read8(d+7)&128;h||(h=65536);g=this.cpu.mem8.subarray(g,g+h);f.set(g,e);e+=h;d+=8}while(!l);this.buffer.set(c,f,()=>{this.ata_advance(this.current_command,b);this.status_reg=80;this.push_irq();this.channel.dma_status&=-2; -this.current_command=-1});this.report_write(a)};W.prototype.get_chs=function(){return((this.lba_mid_reg&255|this.lba_high_reg<<8&65280)*this.head_count+this.head)*this.sectors_per_track+(this.lba_low_reg&255)-1};W.prototype.get_lba28=function(){return this.lba_low_reg&255|this.lba_mid_reg<<8&65280|this.lba_high_reg<<16&16711680|(this.head&15)<<24}; -W.prototype.get_lba48=function(){return(this.lba_low_reg&255|this.lba_mid_reg<<8&65280|this.lba_high_reg<<16&16711680|this.lba_low_reg>>8<<24&4278190080)>>>0};W.prototype.get_lba=function(a){return a?this.get_lba48():this.is_lba?this.get_lba28():this.get_chs()};W.prototype.get_count=function(a){a?(a=this.sector_count_reg,0===a&&(a=65536)):(a=this.sector_count_reg&255,0===a&&(a=256));return a}; -W.prototype.create_identify_packet=function(){const a=Math.min(16383,this.cylinder_count),b=(g,h,l,m)=>{h<<=1;var n=l<<1;l=h+n;g.fill(32,h,n);for(n=0;n>8&255,a&255,a>>8&255,0,0,this.head_count&255,this.head_count>>8&255,this.sectors_per_track/512&255,this.sectors_per_track/ -512>>8&255,0,2,this.sectors_per_track&255,this.sectors_per_track>>8&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128,0,1,0,0,2,0,0,0,2,0,2,7,0,a&255,a>>8&255,this.head_count&255,this.head_count>>8&255,this.sectors_per_track,0,this.sector_count&255,this.sector_count>>8&255,this.sector_count>>16&255,this.sector_count>>24&255,0,0,this.sector_count&255,this.sector_count>>8&255,this.sector_count>> -16&255,this.sector_count>>24&255,0,0,d&255,d>>8&255,0,0,30,0,30,0,30,0,30,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,e&255,e>>8&255,f&255,f>>8&255,0,64,e&255,e>>8&255,f&255,f>>8&255,0,64,0,0,0,0,0,0,0,0,0,0,1,96,0,0,0,0,0,0,0,0,0,0,0,0,this.sector_count&255,this.sector_count>>8&255,this.sector_count>>16&255,this.sector_count>>24&255]);b(this.data,10,10,`8086-86${this.channel_nr}${this.interface_nr}`);b(this.data,23,4,"1.00");b(this.data,27,20,this.is_atapi?"v86 ATAPI CD-ROM":"v86 ATA HD"); -this.data_end=this.data_length=512};W.prototype.data_allocate=function(a){this.data_allocate_noclear(a);this.data32.fill(0,0,a+3>>2)};W.prototype.data_allocate_noclear=function(a){this.data.length{this.cancelled_io_ids.delete(d)?this.in_progress_io_ids.has(d):(this.in_progress_io_ids.delete(d),c(e))})}; -W.prototype.cancel_io_operations=function(){for(const a of this.in_progress_io_ids)this.cancelled_io_ids.add(a);this.in_progress_io_ids.clear()}; -W.prototype.get_state=function(){var a=[];a[0]=this.sector_count_reg;a[1]=this.cylinder_count;a[2]=this.lba_high_reg;a[3]=this.lba_mid_reg;a[4]=this.data_pointer;a[5]=0;a[6]=0;a[7]=0;a[8]=0;a[9]=this.device_reg;a[10]=this.error_reg;a[11]=this.head;a[12]=this.head_count;a[13]=this.is_atapi;a[14]=this.is_lba;a[15]=this.features_reg;a[16]=this.data;a[17]=this.data_length;a[18]=this.lba_low_reg;a[19]=this.sector_count;a[20]=this.sector_size;a[21]=this.sectors_per_drq;a[22]=this.sectors_per_track;a[23]= -this.status_reg;a[24]=this.write_dest;a[25]=this.current_command;a[26]=this.data_end;a[27]=this.current_atapi_command;a[28]=this.buffer;return a}; -W.prototype.set_state=function(a){this.sector_count_reg=a[0];this.cylinder_count=a[1];this.lba_high_reg=a[2];this.lba_mid_reg=a[3];this.data_pointer=a[4];this.device_reg=a[9];this.error_reg=a[10];this.head=a[11];this.head_count=a[12];this.is_atapi=a[13];this.is_lba=a[14];this.features_reg=a[15];this.data=a[16];this.data_length=a[17];this.lba_low_reg=a[18];this.sector_count=a[19];this.sector_size=a[20];this.sectors_per_drq=a[21];this.sectors_per_track=a[22];this.status_reg=a[23];this.write_dest=a[24]; -this.current_command=a[25];this.data_end=a[26];this.current_atapi_command=a[27];this.data16=new Uint16Array(this.data.buffer);this.data32=new Int32Array(this.data.buffer);this.buffer&&this.buffer.set_state(a[28]);this.drive_connected=this.is_atapi||this.buffer;this.medium_changed=!1};function Wc(a,b,c,d=1500){this.bus=b;this.id=a.devices.net?1:0;this.status=this.pairs=1;this.preserve_mac_from_state_image=c;this.mac=new Uint8Array([0,34,21,255*Math.random()|0,255*Math.random()|0,255*Math.random()|0]);this.bus.send("net"+this.id+"-mac",Cc(this.mac));b=[];for(c=0;c{}},notification:{initial_port:51456,single_handler:!1,handlers:[()=>{},e=>{const f=this.virtio.queues[e];for(;f.has_request();){const g=f.pop_request(),h=new Uint8Array(g.length_readable);g.get_next_blob(h);this.bus.send("net"+this.id+"-send",h.subarray(12));this.bus.send("eth-transmit-end",[h.length-12]);this.virtio.queues[e].push_reply(g)}this.virtio.queues[e].flush_replies()},e=>{if(e===2*this.pairs)for(var f=this.virtio.queues[e];f.has_request();){const g= -f.pop_request(),h=new Uint8Array(g.length_readable);g.get_next_blob(h);const l=I(["b","b"],h,{offset:0});switch(l[0]<<8|l[1]){case 1024:I(["h"],h,{offset:2});this.Send(e,g,new Uint8Array([0]));break;case 257:this.mac=h.subarray(2,8);this.Send(e,g,new Uint8Array([0]));this.bus.send("net"+this.id+"-mac",Cc(this.mac));break;default:this.Send(e,g,new Uint8Array([1]));return}}}]},isr_status:{initial_port:50944},device_specific:{initial_port:50688,struct:[0,1,2,3,4,5].map((e,f)=>({bytes:1,name:"mac_"+f, -read:()=>this.mac[f],write:()=>{}})).concat([{bytes:2,name:"status",read:()=>this.status,write:()=>{}},{bytes:2,name:"max_pairs",read:()=>this.pairs,write:()=>{}},{bytes:2,name:"mtu",read:()=>d,write:()=>{}}])}});this.bus.register("net"+this.id+"-receive",e=>{this.bus.send("eth-receive-end",[e.length]);const f=new Uint8Array(12+e.byteLength);(new DataView(f.buffer,f.byteOffset,f.byteLength)).setInt16(10,1);f.set(e,12);e=this.virtio.queues[0];e.has_request()?(e=e.pop_request(),e.set_next_blob(f),this.virtio.queues[0].push_reply(e), -this.virtio.queues[0].flush_replies()):console.log("No buffer to write into!")},this)}Wc.prototype.get_state=function(){const a=[];a[0]=this.virtio;a[1]=this.id;a[2]=this.mac;return a};Wc.prototype.set_state=function(a){this.virtio.set_state(a[0]);this.id=a[1];this.preserve_mac_from_state_image&&(this.mac=a[2],this.bus.send("net"+this.id+"-mac",Cc(this.mac)))};Wc.prototype.reset=function(){this.virtio.reset()}; -Wc.prototype.Send=function(a,b,c){b.set_next_blob(c);this.virtio.queues[a].push_reply(b);this.virtio.queues[a].flush_replies()};Wc.prototype.Ack=function(a,b){this.virtio.queues[a].push_reply(b);this.virtio.queues[a].flush_replies()};const Xc=Uint32Array.from([655360,655360,720896,753664]),Yc=Uint32Array.from([131072,65536,32768,32768]); -function X(a,b,c,d){this.cpu=a;this.bus=b;this.screen=c;this.vga_memory_size=d;this.cursor_address=0;this.cursor_scanline_start=14;this.cursor_scanline_end=15;this.max_cols=80;this.max_rows=25;this.virtual_height=this.virtual_width=this.screen_height=this.screen_width=0;this.layers=[];this.start_address_latched=this.start_address=0;this.crtc=new Uint8Array(25);this.line_compare=this.offset_register=this.preset_row_scan=this.underline_location_register=this.vertical_blank_start=this.vertical_display_enable_end= -this.horizontal_blank_start=this.horizontal_display_enable_end=this.crtc_mode=0;this.graphical_mode=!1;this.vga256_palette=new Int32Array(256);this.latch_dword=0;this.svga_version=45253;this.svga_height=this.svga_width=0;this.svga_enabled=!1;this.svga_bpp=32;this.svga_offset_y=this.svga_offset_x=this.svga_offset=this.svga_bank_offset=0;this.vga_memory_size=void 0===this.vga_memory_size||262144>this.vga_memory_size?262144:268435456=a?b%=a:0>b&&(b=b%a+a);return b};wa.prototype.did_rollover=function(a,b){b-=this.counter_start_time[a];return 0>b?!0:this.counter_start_value[a]>8;b=this.counter_next_low[a];3===this.counter_mode[a]&&(this.counter_next_low[a]^=1);a=this.get_counter_value(a,D.microtick());return b?a&255:a>>8}; +wa.prototype.counter_write=function(a,b){this.counter_reload[a]=this.counter_next_low[a]?this.counter_reload[a]&-256|b:this.counter_reload[a]&255|b<<8;3===this.counter_read_mode[a]&&this.counter_next_low[a]||(this.counter_reload[a]||(this.counter_reload[a]=65535),this.counter_start_value[a]=this.counter_reload[a],this.counter_enabled[a]=!0,this.counter_start_time[a]=D.microtick(),B(this.counter_reload[a]));3===this.counter_read_mode[a]&&(this.counter_next_low[a]^=1)}; +wa.prototype.port43_write=function(a){var b=a>>1&7,c=a>>6&3;a=a>>4&3;3!==c&&(0===a?(this.counter_latch[c]=2,b=this.get_counter_value(c,D.microtick()),this.counter_latch_value[c]=b?b-1:0):(6<=b&&(b&=-5),this.counter_next_low[c]=1===a?0:1,0===c&&this.cpu.device_lower_irq(0),0!==b&&3!==b&&2!==b&&B(b),this.counter_mode[c]=b,this.counter_read_mode[c]=a,2===c&&this.bus.send("pcspeaker-update",[this.counter_mode[2],this.counter_reload[2]])))};wa.prototype.dump=function(){};const xa=Uint32Array.from([655360,655360,720896,753664]),ya=Uint32Array.from([131072,65536,32768,32768]); +function N(a,b,c,d){this.cpu=a;this.bus=b;this.screen=c;this.vga_memory_size=d;this.cursor_address=0;this.cursor_scanline_start=14;this.cursor_scanline_end=15;this.max_cols=80;this.max_rows=25;this.virtual_height=this.virtual_width=this.screen_height=this.screen_width=0;this.layers=[];this.start_address_latched=this.start_address=0;this.crtc=new Uint8Array(25);this.line_compare=this.offset_register=this.preset_row_scan=this.underline_location_register=this.vertical_blank_start=this.vertical_display_enable_end= +this.horizontal_blank_start=this.horizontal_display_enable_end=this.crtc_mode=0;this.graphical_mode=!1;this.vga256_palette=new Int32Array(256);this.latch_dword=0;this.svga_version=45253;this.svga_height=this.svga_width=0;this.svga_enabled=!1;this.svga_bpp=32;this.svga_offset_y=this.svga_offset_x=this.svga_offset=this.svga_bank_offset=0;this.vga_memory_size=void 0===this.vga_memory_size||262144>this.vga_memory_size?262144:268435456>>0;this.svga_memory=k(Uint8Array,a.wasm_memory,c,this.vga_memory_size);this.diff_addr_min=this.vga_memory_size;this.diff_addr_max=0;this.diff_plot_min=this.vga_memory_size;this.diff_plot_max= -0;this.image_data=null;this.vga_memory=new Uint8Array(262144);this.plane0=new Uint8Array(this.vga_memory.buffer,0,65536);this.plane1=new Uint8Array(this.vga_memory.buffer,65536,65536);this.plane2=new Uint8Array(this.vga_memory.buffer,131072,65536);this.plane3=new Uint8Array(this.vga_memory.buffer,196608,65536);this.pixel_buffer=new Uint8Array(524288);b.mmap_register(655360,131072,e=>this.vga_memory_read(e),(e,f)=>this.vga_memory_write(e,f));a.devices.pci.register_device(this)} -X.prototype.get_state=function(){var a=[];a[0]=this.vga_memory_size;a[1]=this.cursor_address;a[2]=this.cursor_scanline_start;a[3]=this.cursor_scanline_end;a[4]=this.max_cols;a[5]=this.max_rows;a[6]=this.vga_memory;a[7]=this.dac_state;a[8]=this.start_address;a[9]=this.graphical_mode;a[10]=this.vga256_palette;a[11]=this.latch_dword;a[12]=this.color_compare;a[13]=this.color_dont_care;a[14]=this.miscellaneous_graphics_register;a[15]=this.svga_width;a[16]=this.svga_height;a[17]=this.crtc_mode;a[18]=this.svga_enabled; +this,this.port3DA_read);b.register_read(954,this,this.port3DA_read);this.dispi_index=-1;this.dispi_enable_value=0;b.register_write(462,this,void 0,this.port1CE_write);b.register_write(463,this,void 0,this.port1CF_write);b.register_read(463,this,void 0,this.port1CF_read);c=a.svga_allocate_memory(this.vga_memory_size)>>>0;this.svga_memory=k.view(Uint8Array,a.wasm_memory,c,this.vga_memory_size);this.diff_addr_min=this.vga_memory_size;this.diff_addr_max=0;this.diff_plot_min=this.vga_memory_size;this.diff_plot_max= +0;this.image_data=null;this.vga_memory=new Uint8Array(262144);this.plane0=new Uint8Array(this.vga_memory.buffer,0,65536);this.plane1=new Uint8Array(this.vga_memory.buffer,65536,65536);this.plane2=new Uint8Array(this.vga_memory.buffer,131072,65536);this.plane3=new Uint8Array(this.vga_memory.buffer,196608,65536);this.pixel_buffer=new Uint8Array(524288);b.mmap_register(655360,131072,e=>this.vga_memory_read(e),(e,g)=>this.vga_memory_write(e,g));a.devices.pci.register_device(this)} +N.prototype.get_state=function(){var a=[];a[0]=this.vga_memory_size;a[1]=this.cursor_address;a[2]=this.cursor_scanline_start;a[3]=this.cursor_scanline_end;a[4]=this.max_cols;a[5]=this.max_rows;a[6]=this.vga_memory;a[7]=this.dac_state;a[8]=this.start_address;a[9]=this.graphical_mode;a[10]=this.vga256_palette;a[11]=this.latch_dword;a[12]=this.color_compare;a[13]=this.color_dont_care;a[14]=this.miscellaneous_graphics_register;a[15]=this.svga_width;a[16]=this.svga_height;a[17]=this.crtc_mode;a[18]=this.svga_enabled; a[19]=this.svga_bpp;a[20]=this.svga_bank_offset;a[21]=this.svga_offset;a[22]=this.index_crtc;a[23]=this.dac_color_index_write;a[24]=this.dac_color_index_read;a[25]=this.dac_map;a[26]=this.sequencer_index;a[27]=this.plane_write_bm;a[28]=this.sequencer_memory_mode;a[29]=this.graphics_index;a[30]=this.plane_read;a[31]=this.planar_mode;a[32]=this.planar_rotate_reg;a[33]=this.planar_bitmap;a[34]=this.max_scan_line;a[35]=this.miscellaneous_output_register;a[36]=this.port_3DA_value;a[37]=this.dispi_index; a[38]=this.dispi_enable_value;a[39]=this.svga_memory;a[41]=this.attribute_controller_index;a[42]=this.offset_register;a[43]=this.planar_setreset;a[44]=this.planar_setreset_enable;a[45]=this.start_address_latched;a[46]=this.crtc;a[47]=this.horizontal_display_enable_end;a[48]=this.horizontal_blank_start;a[49]=this.vertical_display_enable_end;a[50]=this.vertical_blank_start;a[51]=this.underline_location_register;a[52]=this.preset_row_scan;a[53]=this.offset_register;a[54]=this.palette_source;a[55]=this.attribute_mode; a[56]=this.color_plane_enable;a[57]=this.horizontal_panning;a[58]=this.color_select;a[59]=this.clocking_mode;a[60]=this.line_compare;a[61]=this.pixel_buffer;a[62]=this.dac_mask;a[63]=this.character_map_select;a[64]=this.font_page_ab_enabled;return a}; -X.prototype.set_state=function(a){this.vga_memory_size=a[0];this.cursor_address=a[1];this.cursor_scanline_start=a[2];this.cursor_scanline_end=a[3];this.max_cols=a[4];this.max_rows=a[5];a[6]&&this.vga_memory.set(a[6]);this.dac_state=a[7];this.start_address=a[8];this.graphical_mode=a[9];this.vga256_palette=a[10];this.latch_dword=a[11];this.color_compare=a[12];this.color_dont_care=a[13];this.miscellaneous_graphics_register=a[14];this.svga_width=a[15];this.svga_height=a[16];this.crtc_mode=a[17];this.svga_enabled= +N.prototype.set_state=function(a){this.vga_memory_size=a[0];this.cursor_address=a[1];this.cursor_scanline_start=a[2];this.cursor_scanline_end=a[3];this.max_cols=a[4];this.max_rows=a[5];a[6]&&this.vga_memory.set(a[6]);this.dac_state=a[7];this.start_address=a[8];this.graphical_mode=a[9];this.vga256_palette=a[10];this.latch_dword=a[11];this.color_compare=a[12];this.color_dont_care=a[13];this.miscellaneous_graphics_register=a[14];this.svga_width=a[15];this.svga_height=a[16];this.crtc_mode=a[17];this.svga_enabled= a[18];this.svga_bpp=a[19];this.svga_bank_offset=a[20];this.svga_offset=a[21];this.index_crtc=a[22];this.dac_color_index_write=a[23];this.dac_color_index_read=a[24];this.dac_map=a[25];this.sequencer_index=a[26];this.plane_write_bm=a[27];this.sequencer_memory_mode=a[28];this.graphics_index=a[29];this.plane_read=a[30];this.planar_mode=a[31];this.planar_rotate_reg=a[32];this.planar_bitmap=a[33];this.max_scan_line=a[34];this.miscellaneous_output_register=a[35];this.port_3DA_value=a[36];this.dispi_index= a[37];this.dispi_enable_value=a[38];this.svga_memory.set(a[39]);this.attribute_controller_index=a[41];this.offset_register=a[42];this.planar_setreset=a[43];this.planar_setreset_enable=a[44];this.start_address_latched=a[45];this.crtc.set(a[46]);this.horizontal_display_enable_end=a[47];this.horizontal_blank_start=a[48];this.vertical_display_enable_end=a[49];this.vertical_blank_start=a[50];this.underline_location_register=a[51];this.preset_row_scan=a[52];this.offset_register=a[53];this.palette_source= a[54];this.attribute_mode=a[55];this.color_plane_enable=a[56];this.horizontal_panning=a[57];this.color_select=a[58];this.clocking_mode=a[59];this.line_compare=a[60];a[61]&&this.pixel_buffer.set(a[61]);this.dac_mask=void 0===a[62]?255:a[62];this.character_map_select=void 0===a[63]?0:a[63];this.font_page_ab_enabled=void 0===a[64]?0:a[64];this.screen.set_mode(this.graphical_mode);this.graphical_mode?(this.screen_height=this.screen_width=0,this.svga_enabled?(this.set_size_graphical(this.svga_width,this.svga_height, this.svga_width,this.svga_height,this.svga_bpp),this.update_layers()):(this.update_vga_size(),this.update_layers(),this.complete_replot())):(this.set_font_bitmap(!0),this.set_size_text(this.max_cols,this.max_rows),this.set_font_page(),this.update_cursor_scanline(),this.update_cursor());this.complete_redraw()}; -X.prototype.vga_memory_read=function(a){if(this.svga_enabled)return this.cpu.read8((a-655360|this.svga_bank_offset)+3758096384|0);var b=this.miscellaneous_graphics_register>>2&3;a-=Xc[b];if(0>a||a>=Yc[b])return y(a>>>0),0;this.latch_dword=this.plane0[a];this.latch_dword|=this.plane1[a]<<8;this.latch_dword|=this.plane2[a]<<16;this.latch_dword|=this.plane3[a]<<24;if(this.planar_mode&8)return b=255,this.color_dont_care&1&&(b&=this.plane0[a]^~(this.color_compare&1?255:0)),this.color_dont_care&2&&(b&= -this.plane1[a]^~(this.color_compare&2?255:0)),this.color_dont_care&4&&(b&=this.plane2[a]^~(this.color_compare&4?255:0)),this.color_dont_care&8&&(b&=this.plane3[a]^~(this.color_compare&8?255:0)),b;b=this.plane_read;this.graphical_mode?this.sequencer_memory_mode&8?(b=a&3,a&=-4):this.planar_mode&16&&(b=a&1,a&=-2):b&=3;return this.vga_memory[b<<16|a]}; -X.prototype.vga_memory_write=function(a,b){if(this.svga_enabled)this.cpu.write8((a-655360|this.svga_bank_offset)+3758096384|0,b);else{var c=this.miscellaneous_graphics_register>>2&3;a-=Xc[c];0>a||a>=Yc[c]?(y(a>>>0),y(b)):this.graphical_mode?this.vga_memory_write_graphical(a,b):this.plane_write_bm&3?this.vga_memory_write_text_mode(a,b):this.plane_write_bm&4&&(this.plane2[a]=b)}}; -X.prototype.vga_memory_write_graphical=function(a,b){var c=this.planar_mode&3,d=this.apply_feed(this.planar_bitmap),e=this.apply_expand(this.planar_setreset),f=this.apply_expand(this.planar_setreset_enable);switch(c){case 0:b=this.apply_rotate(b);var g=this.apply_feed(b);g=this.apply_setreset(g,f);g=this.apply_logical(g,this.latch_dword);g=this.apply_bitmask(g,d);break;case 1:g=this.latch_dword;break;case 2:g=this.apply_expand(b);g=this.apply_logical(g,this.latch_dword);g=this.apply_bitmask(g,d); -break;case 3:b=this.apply_rotate(b),d&=this.apply_feed(b),g=this.apply_bitmask(e,d)}b=15;switch(this.sequencer_memory_mode&12){case 0:b=5<<(a&1);a&=-2;break;case 8:case 12:b=1<<(a&3),a&=-4}b&=this.plane_write_bm;b&1&&(this.plane0[a]=g>>0&255);b&2&&(this.plane1[a]=g>>8&255);b&4&&(this.plane2[a]=g>>16&255);b&8&&(this.plane3[a]=g>>24&255);a=this.vga_addr_to_pixel(a);this.partial_replot(a,a+7)};X.prototype.apply_feed=function(a){return a|a<<8|a<<16|a<<24}; -X.prototype.apply_expand=function(a){return(a&1?255:0)|(a&2?255:0)<<8|(a&4?255:0)<<16|(a&8?255:0)<<24};X.prototype.apply_rotate=function(a){return(a|a<<8)>>>(this.planar_rotate_reg&7)&255};X.prototype.apply_setreset=function(a,b){var c=this.apply_expand(this.planar_setreset);return(a|b&c)&(~b|c)};X.prototype.apply_logical=function(a,b){switch(this.planar_rotate_reg&24){case 8:return a&b;case 16:return a|b;case 24:return a^b}return a};X.prototype.apply_bitmask=function(a,b){return b&a|~b&this.latch_dword}; -X.prototype.text_mode_redraw=function(){const a=this.scan_line_to_screen_row(this.line_compare),b=Math.max(0,2*(2*this.offset_register-this.max_cols)),c=this.attribute_mode&8,d=this.font_page_ab_enabled?7:15,e=c?7:15,f=this.screen.FLAG_BLINKING,g=this.screen.FLAG_FONT_PAGE_B;let h=this.start_address<<1;for(let l=0;l>2&3;a-=xa[b];if(0>a||a>=ya[b])return B(a),0;this.latch_dword=this.plane0[a];this.latch_dword|=this.plane1[a]<<8;this.latch_dword|=this.plane2[a]<<16;this.latch_dword|=this.plane3[a]<<24;if(this.planar_mode&8)return b=255,this.color_dont_care&1&&(b&=this.plane0[a]^~(this.color_compare&1?255:0)),this.color_dont_care&2&&(b&=this.plane1[a]^ +~(this.color_compare&2?255:0)),this.color_dont_care&4&&(b&=this.plane2[a]^~(this.color_compare&4?255:0)),this.color_dont_care&8&&(b&=this.plane3[a]^~(this.color_compare&8?255:0)),b;b=this.plane_read;this.graphical_mode?this.sequencer_memory_mode&8?(b=a&3,a&=-4):this.planar_mode&16&&(b=a&1,a&=-2):b&=3;return this.vga_memory[b<<16|a]}; +N.prototype.vga_memory_write=function(a,b){if(this.svga_enabled)this.cpu.write8((a-655360|this.svga_bank_offset)+3758096384|0,b);else{var c=this.miscellaneous_graphics_register>>2&3;a-=xa[c];0>a||a>=ya[c]?(B(a),B(b)):this.graphical_mode?this.vga_memory_write_graphical(a,b):this.plane_write_bm&3?this.vga_memory_write_text_mode(a,b):this.plane_write_bm&4&&(this.plane2[a]=b)}}; +N.prototype.vga_memory_write_graphical=function(a,b){var c=this.planar_mode&3,d=this.apply_feed(this.planar_bitmap),e=this.apply_expand(this.planar_setreset),g=this.apply_expand(this.planar_setreset_enable);switch(c){case 0:b=this.apply_rotate(b);var f=this.apply_feed(b);f=this.apply_setreset(f,g);f=this.apply_logical(f,this.latch_dword);f=this.apply_bitmask(f,d);break;case 1:f=this.latch_dword;break;case 2:f=this.apply_expand(b);f=this.apply_logical(f,this.latch_dword);f=this.apply_bitmask(f,d); +break;case 3:b=this.apply_rotate(b),d&=this.apply_feed(b),f=this.apply_bitmask(e,d)}b=15;switch(this.sequencer_memory_mode&12){case 0:b=5<<(a&1);a&=-2;break;case 8:case 12:b=1<<(a&3),a&=-4}b&=this.plane_write_bm;b&1&&(this.plane0[a]=f>>0&255);b&2&&(this.plane1[a]=f>>8&255);b&4&&(this.plane2[a]=f>>16&255);b&8&&(this.plane3[a]=f>>24&255);a=this.vga_addr_to_pixel(a);this.partial_replot(a,a+7)};N.prototype.apply_feed=function(a){return a|a<<8|a<<16|a<<24}; +N.prototype.apply_expand=function(a){return(a&1?255:0)|(a&2?255:0)<<8|(a&4?255:0)<<16|(a&8?255:0)<<24};N.prototype.apply_rotate=function(a){return(a|a<<8)>>>(this.planar_rotate_reg&7)&255};N.prototype.apply_setreset=function(a,b){var c=this.apply_expand(this.planar_setreset);return(a|b&c)&(~b|c)};N.prototype.apply_logical=function(a,b){switch(this.planar_rotate_reg&24){case 8:return a&b;case 16:return a|b;case 24:return a^b}return a};N.prototype.apply_bitmask=function(a,b){return b&a|~b&this.latch_dword}; +N.prototype.text_mode_redraw=function(){const a=this.scan_line_to_screen_row(this.line_compare),b=Math.max(0,2*(2*this.offset_register-this.max_cols)),c=this.attribute_mode&8,d=this.font_page_ab_enabled?7:15,e=c?7:15,g=this.screen.FLAG_BLINKING,f=this.screen.FLAG_FONT_PAGE_B;let h=this.start_address<<1;for(let l=0;l>4&e]],this.vga256_palette[this.dac_mask&this.dac_map[p&d]]);h+=2}h+=b}}; -X.prototype.vga_memory_write_text_mode=function(a,b){this.vga_memory[a]=b;var c=Math.max(this.max_cols,2*this.offset_register);let d;if(a>>1>=this.start_address){var e=(a>>1)-this.start_address;d=e/c|0;c=e%c}else e=a>>1,d=(e/c|0)+this.scan_line_to_screen_row(this.line_compare),c=e%c;if(!(c>=this.max_cols||d>=this.max_rows)){a&1?(e=b,b=this.vga_memory[a&-2]):e=this.vga_memory[a|1];var f=this.attribute_mode&8;a=(f&&e&128?this.screen.FLAG_BLINKING:0)|(!this.font_page_ab_enabled||e&8?0:this.screen.FLAG_FONT_PAGE_B); -var g=this.font_page_ab_enabled?7:15;f=f?7:15;this.bus.send("screen-put-char",[d,c,b]);this.screen.put_char(d,c,b,a,this.vga256_palette[this.dac_mask&this.dac_map[e>>4&f]],this.vga256_palette[this.dac_mask&this.dac_map[e&g]])}}; -X.prototype.update_cursor=function(){var a=Math.max(this.max_cols,2*this.offset_register);let b;this.cursor_address>=this.start_address?(b=(this.cursor_address-this.start_address)/a|0,a=(this.cursor_address-this.start_address)%a):(b=(this.cursor_address/a|0)+this.scan_line_to_screen_row(this.line_compare),a=this.cursor_address%a);this.screen.update_cursor(b,a)}; -X.prototype.complete_redraw=function(){this.graphical_mode?this.svga_enabled?this.cpu.svga_mark_dirty():(this.diff_addr_min=0,this.diff_addr_max=524288):this.text_mode_redraw()};X.prototype.complete_replot=function(){this.graphical_mode&&!this.svga_enabled&&(this.diff_plot_min=0,this.diff_plot_max=524288,this.complete_redraw())};X.prototype.partial_redraw=function(a,b){athis.diff_addr_max&&(this.diff_addr_max=b)}; -X.prototype.partial_replot=function(a,b){athis.diff_plot_max&&(this.diff_plot_max=b);this.partial_redraw(a,b)};X.prototype.reset_diffs=function(){this.diff_addr_min=this.vga_memory_size;this.diff_addr_max=0;this.diff_plot_min=this.vga_memory_size;this.diff_plot_max=0};X.prototype.destroy=function(){};X.prototype.vga_bytes_per_line=function(){var a=this.offset_register<<2;this.underline_location_register&64?a<<=1:this.crtc_mode&64&&(a>>>=1);return a}; -X.prototype.vga_addr_shift_count=function(){var a=128+(~this.underline_location_register&this.crtc_mode&64);a-=this.underline_location_register&64;a-=this.attribute_mode&64;return a>>>6}; -X.prototype.vga_addr_to_pixel=function(a){var b=this.vga_addr_shift_count();if(~this.crtc_mode&3){var c=a-this.start_address;c&=this.crtc_mode<<13|-24577;c<<=b;var d=c/this.virtual_width|0;c%=this.virtual_width;switch(this.crtc_mode&3){case 2:d=d<<1|a>>13&1;break;case 1:d=d<<1|a>>14&1;break;case 0:d=d<<2|a>>13&3}return d*this.virtual_width+c+(this.start_address<>>=1);a=Math.ceil(a/(1+(this.max_scan_line&31)));this.crtc_mode&1||(a<<=1);this.crtc_mode&2||(a<<=1);return a};X.prototype.set_size_text=function(a,b){this.max_cols=a;this.max_rows=b;this.screen.set_size_text(a,b);this.bus.send("screen-set-size",[a,b,0])}; -X.prototype.set_size_graphical=function(a,b,c,d,e){c=Math.max(c,1);d=Math.max(d,1);if(this.screen_width!==a||this.screen_height!==b||this.virtual_width!==c||this.virtual_height!==d){this.screen_width=a;this.screen_height=b;this.virtual_width=c;this.virtual_height=d;if("undefined"!==typeof ImageData){const f=c*d,g=this.cpu.svga_allocate_dest_buffer(f)>>>0;this.dest_buffet_offset=g;this.image_data=new ImageData(new Uint8ClampedArray(this.cpu.wasm_memory.buffer,g,4*f),c,d);this.cpu.svga_mark_dirty()}this.screen.set_size_graphical(a, +N.prototype.vga_memory_write_text_mode=function(a,b){this.vga_memory[a]=b;var c=Math.max(this.max_cols,2*this.offset_register);let d;if(a>>1>=this.start_address){var e=(a>>1)-this.start_address;d=e/c|0;c=e%c}else e=a>>1,d=(e/c|0)+this.scan_line_to_screen_row(this.line_compare),c=e%c;if(!(c>=this.max_cols||d>=this.max_rows)){a&1?(e=b,b=this.vga_memory[a&-2]):e=this.vga_memory[a|1];var g=this.attribute_mode&8;a=(g&&e&128?this.screen.FLAG_BLINKING:0)|(!this.font_page_ab_enabled||e&8?0:this.screen.FLAG_FONT_PAGE_B); +var f=this.font_page_ab_enabled?7:15;g=g?7:15;this.bus.send("screen-put-char",[d,c,b]);this.screen.put_char(d,c,b,a,this.vga256_palette[this.dac_mask&this.dac_map[e>>4&g]],this.vga256_palette[this.dac_mask&this.dac_map[e&f]])}}; +N.prototype.update_cursor=function(){var a=Math.max(this.max_cols,2*this.offset_register);let b;this.cursor_address>=this.start_address?(b=(this.cursor_address-this.start_address)/a|0,a=(this.cursor_address-this.start_address)%a):(b=(this.cursor_address/a|0)+this.scan_line_to_screen_row(this.line_compare),a=this.cursor_address%a);this.screen.update_cursor(b,a)}; +N.prototype.complete_redraw=function(){this.graphical_mode?this.svga_enabled?this.cpu.svga_mark_dirty():(this.diff_addr_min=0,this.diff_addr_max=524288):this.text_mode_redraw()};N.prototype.complete_replot=function(){this.graphical_mode&&!this.svga_enabled&&(this.diff_plot_min=0,this.diff_plot_max=524288,this.complete_redraw())};N.prototype.partial_redraw=function(a,b){athis.diff_addr_max&&(this.diff_addr_max=b)}; +N.prototype.partial_replot=function(a,b){athis.diff_plot_max&&(this.diff_plot_max=b);this.partial_redraw(a,b)};N.prototype.reset_diffs=function(){this.diff_addr_min=this.vga_memory_size;this.diff_addr_max=0;this.diff_plot_min=this.vga_memory_size;this.diff_plot_max=0};N.prototype.destroy=function(){};N.prototype.vga_bytes_per_line=function(){var a=this.offset_register<<2;this.underline_location_register&64?a<<=1:this.crtc_mode&64&&(a>>>=1);return a}; +N.prototype.vga_addr_shift_count=function(){var a=128+(~this.underline_location_register&this.crtc_mode&64);a-=this.underline_location_register&64;a-=this.attribute_mode&64;return a>>>6}; +N.prototype.vga_addr_to_pixel=function(a){var b=this.vga_addr_shift_count();if(~this.crtc_mode&3){var c=a-this.start_address;c&=this.crtc_mode<<13|-24577;c<<=b;var d=c/this.virtual_width|0;c%=this.virtual_width;switch(this.crtc_mode&3){case 2:d=d<<1|a>>13&1;break;case 1:d=d<<1|a>>14&1;break;case 0:d=d<<2|a>>13&3}return d*this.virtual_width+c+(this.start_address<>>=1);a=Math.ceil(a/(1+(this.max_scan_line&31)));this.crtc_mode&1||(a<<=1);this.crtc_mode&2||(a<<=1);return a};N.prototype.set_size_text=function(a,b){this.max_cols=a;this.max_rows=b;this.screen.set_size_text(a,b);this.bus.send("screen-set-size",[a,b,0])}; +N.prototype.set_size_graphical=function(a,b,c,d,e){c=Math.max(c,1);d=Math.max(d,1);if(this.screen_width!==a||this.screen_height!==b||this.virtual_width!==c||this.virtual_height!==d){this.screen_width=a;this.screen_height=b;this.virtual_width=c;this.virtual_height=d;if("undefined"!==typeof ImageData){const g=c*d,f=this.cpu.svga_allocate_dest_buffer(g)>>>0;this.dest_buffet_offset=f;this.image_data=new ImageData(new Uint8ClampedArray(this.cpu.wasm_memory.buffer,f,4*g),c,d);this.cpu.svga_mark_dirty()}this.screen.set_size_graphical(a, b,c,d);this.bus.send("screen-set-size",[a,b,e])}}; -X.prototype.update_vga_size=function(){if(!this.svga_enabled){var a=Math.min(1+this.horizontal_display_enable_end,this.horizontal_blank_start),b=Math.min(1+this.vertical_display_enable_end,this.vertical_blank_start);if(a&&b)if(this.graphical_mode){a<<=3;var c=this.offset_register<<4,d=4;this.attribute_mode&64?(a>>>=1,c>>>=1,d=8):this.attribute_mode&2&&(d=1);b=this.scan_line_to_screen_row(b);var e=Yc[0];const f=this.vga_bytes_per_line();this.set_size_graphical(a,b,c,f?Math.ceil(e/f):b,d);this.update_vertical_retrace(); -this.update_layers()}else this.max_scan_line&128&&(b>>>=1),c=b/(1+(this.max_scan_line&31))|0,a&&c&&this.set_size_text(a,c)}}; -X.prototype.update_layers=function(){this.graphical_mode||this.text_mode_redraw();if(this.svga_enabled)this.layers=[];else if(this.virtual_width&&this.screen_width)if(!this.palette_source||this.clocking_mode&32)this.layers=[],this.screen.clear_screen();else{var a=this.start_address_latched,b=this.horizontal_panning;this.attribute_mode&64&&(b>>>=1);var c=this.preset_row_scan>>5&3,d=this.vga_addr_to_pixel(a+c);a=d/this.virtual_width|0;var e=d%this.virtual_width+b;d=this.scan_line_to_screen_row(1+this.line_compare); -d=Math.min(d,this.screen_height);var f=this.screen_height-d;this.layers=[];e=-e;for(var g=0;ethis.attribute_controller_index)y(this.attribute_controller_index),y(a),this.dac_map[this.attribute_controller_index]=a,this.attribute_mode&64||this.complete_redraw();else switch(this.attribute_controller_index){case 16:y(a);if(this.attribute_mode!==a){var b= -this.attribute_mode;this.attribute_mode=a;const c=0!==(a&1);this.svga_enabled||this.graphical_mode===c||(this.graphical_mode=c,this.screen.set_mode(this.graphical_mode));(b^a)&64&&this.complete_replot();this.update_vga_size();this.complete_redraw();this.set_font_bitmap(!1)}break;case 18:y(a);this.color_plane_enable!==a&&(this.color_plane_enable=a,this.complete_redraw());break;case 19:y(a);this.horizontal_panning!==a&&(this.horizontal_panning=a&15,this.update_layers());break;case 20:y(a);this.color_select!== -a&&(this.color_select=a,this.complete_redraw());break;default:y(this.attribute_controller_index),y(a)}this.attribute_controller_index=-1}};X.prototype.port3C0_read=function(){return(this.attribute_controller_index|this.palette_source)&255};X.prototype.port3C0_read16=function(){return this.port3C0_read()|this.port3C1_read()<<8&65280}; -X.prototype.port3C1_read=function(){if(16>this.attribute_controller_index)return y(this.attribute_controller_index),y(this.dac_map[this.attribute_controller_index]),this.dac_map[this.attribute_controller_index]&255;switch(this.attribute_controller_index){case 16:return y(this.attribute_mode),this.attribute_mode;case 18:return y(this.color_plane_enable),this.color_plane_enable;case 19:return y(this.horizontal_panning),this.horizontal_panning;case 20:return y(this.color_select),this.color_select;default:y(this.attribute_controller_index)}return 255}; -X.prototype.port3C2_write=function(a){y(a);this.miscellaneous_output_register=a};X.prototype.port3C4_write=function(a){this.sequencer_index=a};X.prototype.port3C4_read=function(){return this.sequencer_index}; -X.prototype.port3C5_write=function(a){switch(this.sequencer_index){case 1:y(a);var b=this.clocking_mode;this.clocking_mode=a;(b^a)&32&&this.update_layers();this.set_font_bitmap(!1);break;case 2:y(a);b=this.plane_write_bm;this.plane_write_bm=a;this.graphical_mode||!(b&4)||this.plane_write_bm&4||this.set_font_bitmap(!0);break;case 3:y(a);b=this.character_map_select;this.character_map_select=a;this.graphical_mode||b===a||this.set_font_page();break;case 4:y(a);this.sequencer_memory_mode=a;break;default:y(this.sequencer_index), -y(a)}};X.prototype.port3C5_read=function(){y(this.sequencer_index);switch(this.sequencer_index){case 1:return this.clocking_mode;case 2:return this.plane_write_bm;case 3:return this.character_map_select;case 4:return this.sequencer_memory_mode;case 6:return 18}return 0};X.prototype.port3C6_write=function(a){this.dac_mask!==a&&(this.dac_mask=a,this.complete_redraw())};X.prototype.port3C6_read=function(){return this.dac_mask}; -X.prototype.port3C7_write=function(a){y(a);this.dac_color_index_read=3*a;this.dac_state&=0};X.prototype.port3C7_read=function(){return this.dac_state};X.prototype.port3C8_write=function(a){this.dac_color_index_write=3*a;this.dac_state|=3};X.prototype.port3C8_read=function(){return this.dac_color_index_write/3&255}; -X.prototype.port3C9_write=function(a){var b=this.dac_color_index_write/3|0,c=this.dac_color_index_write%3,d=this.vga256_palette[b];if(0===(this.dispi_enable_value&32)){a&=63;const e=a&1;a=a<<2|e<<1|e}0===c?d=d&-16711681|a<<16:1===c?d=d&-65281|a<<8:(d=d&-256|a,y(b),y(d));this.vga256_palette[b]!==d&&(this.vga256_palette[b]=d,this.complete_redraw());this.dac_color_index_write++}; -X.prototype.port3C9_read=function(){var a=this.vga256_palette[this.dac_color_index_read/3|0]>>8*(2-this.dac_color_index_read%3)&255;this.dac_color_index_read++;return this.dispi_enable_value&32?a:a>>2};X.prototype.port3CC_read=function(){return this.miscellaneous_output_register};X.prototype.port3CE_write=function(a){this.graphics_index=a};X.prototype.port3CE_read=function(){return this.graphics_index}; -X.prototype.port3CF_write=function(a){switch(this.graphics_index){case 0:this.planar_setreset=a;y(a);break;case 1:this.planar_setreset_enable=a;y(a);break;case 2:this.color_compare=a;y(a);break;case 3:this.planar_rotate_reg=a;y(a);break;case 4:this.plane_read=a;y(a);break;case 5:var b=this.planar_mode;this.planar_mode=a;y(a);(b^a)&96&&this.complete_replot();break;case 6:y(a);this.miscellaneous_graphics_register!==a&&(this.miscellaneous_graphics_register=a,this.update_vga_size());break;case 7:this.color_dont_care= -a;y(a);break;case 8:this.planar_bitmap=a;y(a);break;default:y(this.graphics_index),y(a)}};X.prototype.port3CF_read=function(){y(this.graphics_index);switch(this.graphics_index){case 0:return this.planar_setreset;case 1:return this.planar_setreset_enable;case 2:return this.color_compare;case 3:return this.planar_rotate_reg;case 4:return this.plane_read;case 5:return this.planar_mode;case 6:return this.miscellaneous_graphics_register;case 7:return this.color_dont_care;case 8:return this.planar_bitmap}return 0}; -X.prototype.port3D4_write=function(a){this.index_crtc=a};X.prototype.port3D4_write16=function(a){this.port3D4_write(a&255);this.port3D5_write(a>>8&255)};X.prototype.port3D4_read=function(){return this.index_crtc}; -X.prototype.port3D5_write=function(a){switch(this.index_crtc){case 1:y(a);this.horizontal_display_enable_end!==a&&(this.horizontal_display_enable_end=a,this.update_vga_size());break;case 2:this.horizontal_blank_start!==a&&(this.horizontal_blank_start=a,this.update_vga_size());break;case 7:y(a);var b=this.vertical_display_enable_end;this.vertical_display_enable_end&=255;this.vertical_display_enable_end=this.vertical_display_enable_end|a<<3&512|a<<7&256;b!==this.vertical_display_enable_end&&this.update_vga_size(); -this.line_compare=this.line_compare&767|a<<4&256;b=this.vertical_blank_start;this.vertical_blank_start=this.vertical_blank_start&767|a<<5&256;b!==this.vertical_blank_start&&this.update_vga_size();this.update_layers();break;case 8:y(a);this.preset_row_scan=a;this.update_layers();break;case 9:y(a);var c=this.max_scan_line;this.max_scan_line=a;this.line_compare=this.line_compare&511|a<<3&512;b=this.vertical_blank_start;this.vertical_blank_start=this.vertical_blank_start&511|a<<4&512;((c^this.max_scan_line)& -159||b!==this.vertical_blank_start)&&this.update_vga_size();this.update_cursor_scanline();this.update_layers();this.set_font_bitmap(!1);break;case 10:y(a);this.cursor_scanline_start=a;this.update_cursor_scanline();break;case 11:y(a);this.cursor_scanline_end=a;this.update_cursor_scanline();break;case 12:(this.start_address>>8&255)!==a&&(this.start_address=this.start_address&255|a<<8,this.update_layers(),~this.crtc_mode&3&&this.complete_replot());y(a);y(this.start_address,4);break;case 13:(this.start_address& -255)!==a&&(this.start_address=this.start_address&65280|a,this.update_layers(),~this.crtc_mode&3&&this.complete_replot());y(a);y(this.start_address,4);break;case 14:y(a);this.cursor_address=this.cursor_address&255|a<<8;this.update_cursor();break;case 15:y(a);this.cursor_address=this.cursor_address&65280|a;this.update_cursor();break;case 18:y(a);(this.vertical_display_enable_end&255)!==a&&(this.vertical_display_enable_end=this.vertical_display_enable_end&768|a,this.update_vga_size());break;case 19:y(a); -this.offset_register!==a&&(this.offset_register=a,this.update_vga_size(),~this.crtc_mode&3&&this.complete_replot());break;case 20:y(a);this.underline_location_register!==a&&(b=this.underline_location_register,this.underline_location_register=a,this.update_vga_size(),(b^a)&64&&this.complete_replot());break;case 21:y(a);(this.vertical_blank_start&255)!==a&&(this.vertical_blank_start=this.vertical_blank_start&768|a,this.update_vga_size());break;case 23:y(a);this.crtc_mode!==a&&(b=this.crtc_mode,this.crtc_mode= -a,this.update_vga_size(),(b^a)&67&&this.complete_replot());break;case 24:y(a);this.line_compare=this.line_compare&768|a;this.update_layers();break;default:this.index_crtc>7&2|this.vertical_blank_start>>5&8|this.line_compare>>4&16|this.vertical_display_enable_end>>3&64;case 8:return this.preset_row_scan;case 9:return this.max_scan_line;case 10:return this.cursor_scanline_start;case 11:return this.cursor_scanline_end;case 12:return this.start_address&255; -case 13:return this.start_address>>8;case 14:return this.cursor_address>>8;case 15:return this.cursor_address&255;case 18:return this.vertical_display_enable_end&255;case 19:return this.offset_register;case 20:return this.underline_location_register;case 21:return this.vertical_blank_start&255;case 23:return this.crtc_mode;case 24:return this.line_compare&255}return this.index_crtc=a?this.svga_version=a:y(a);break;case 1:this.svga_width=a;2560>>16;case 6:return this.screen_width?this.screen_width:1;case 8:return this.svga_offset_x;case 9:return this.svga_offset_y;case 10:return this.vga_memory_size/65536| -0;default:y(this.dispi_index)}return 255}; -X.prototype.vga_replot=function(){for(var a=this.diff_plot_min&-16,b=Math.min(this.diff_plot_max|15,524287),c=this.vga_addr_shift_count(),d=~this.crtc_mode&3,e=this.planar_mode&96,f=this.attribute_mode&64;a<=b;){var g=a>>>c;if(d){var h=a/this.virtual_width|0,l=a-this.virtual_width*h;switch(d){case 1:g=(h&1)<<13;h>>>=1;break;case 2:g=(h&1)<<14;h>>>=1;break;case 3:g=(h&3)<<13,h>>>=2}g|=(h*this.virtual_width+l>>>c)+this.start_address}h=this.plane0[g];l=this.plane1[g];var m=this.plane2[g],n=this.plane3[g]; -g=new Uint8Array(8);switch(e){case 0:h<<=0;l<<=1;m<<=2;n<<=3;for(var p=7;0<=p;p--)g[7-p]=h>>p&1|l>>p&2|m>>p&4|n>>p&8;break;case 32:g[0]=h>>6&3|m>>4&12;g[1]=h>>4&3|m>>2&12;g[2]=h>>2&3|m>>0&12;g[3]=h>>0&3|m<<2&12;g[4]=l>>6&3|n>>4&12;g[5]=l>>4&3|n>>2&12;g[6]=l>>2&3|n>>0&12;g[7]=l>>0&3|n<<2&12;break;case 64:case 96:g[0]=h>>4&15,g[1]=h>>0&15,g[2]=l>>4&15,g[3]=l>>0&15,g[4]=m>>4&15,g[5]=m>>0&15,g[6]=n>>4&15,g[7]=n>>0&15}if(f)for(h=p=0;4>p;p++,a++,h+=2)this.pixel_buffer[a]=g[h]<<4|g[h+1];else for(p=0;8>p;p++, -a++)this.pixel_buffer[a]=g[p]}}; -X.prototype.vga_redraw=function(){var a=this.diff_addr_min,b=Math.min(this.diff_addr_max,524287);const c=new Int32Array(this.cpu.wasm_memory.buffer,this.dest_buffet_offset,this.virtual_width*this.virtual_height);var d=255,e=0;this.attribute_mode&128&&(d&=207,e|=this.color_select<<4&48);if(this.attribute_mode&64)for(;a<=b;a++){var f=this.pixel_buffer[a]&d|e;f=this.vga256_palette[f];c[a]=f&65280|f<<16|f>>16|4278190080}else for(d&=63,e|=this.color_select<<4&192;a<=b;a++)f=this.dac_map[this.pixel_buffer[a]& -this.color_plane_enable]&d|e,f=this.vga256_palette[f],c[a]=f&65280|f<<16|f>>16|4278190080}; -X.prototype.screen_fill_buffer=function(){if(this.graphical_mode){if(0===this.image_data.data.byteLength){var a=new Uint8ClampedArray(this.cpu.wasm_memory.buffer,this.dest_buffet_offset,4*this.virtual_width*this.virtual_height);this.image_data=new ImageData(a,this.virtual_width,this.virtual_height);this.update_layers()}if(this.svga_enabled){a=0;let d=this.svga_height;if(8===this.svga_bpp){const e=new Int32Array(this.cpu.wasm_memory.buffer,this.dest_buffet_offset,this.screen_width*this.screen_height), -f=new Uint8Array(this.cpu.wasm_memory.buffer,this.svga_memory.byteOffset,this.vga_memory_size);for(var b=0;b>16|4278190080}}else this.cpu.svga_fill_pixel_buffer(this.svga_bpp,this.svga_offset),b=15===this.svga_bpp?2:this.svga_bpp/8,a=((this.cpu.svga_dirty_bitmap_min_offset[0]/b|0)-this.svga_offset)/this.svga_width|0,d=(((this.cpu.svga_dirty_bitmap_max_offset[0]/b|0)-this.svga_offset)/this.svga_width|0)+1;a>>=1,c>>>=1);b=this.scan_line_to_screen_row(b);var d=ya[0];const e=this.vga_bytes_per_line();this.set_size_graphical(a,b,c,e?Math.ceil(d/e):b,8);this.update_vertical_retrace();this.update_layers()}else this.max_scan_line& +128&&(b>>>=1),c=b/(1+(this.max_scan_line&31))|0,a&&c&&this.set_size_text(a,c)}}; +N.prototype.update_layers=function(){this.graphical_mode||this.text_mode_redraw();if(this.svga_enabled)this.layers=[];else if(this.virtual_width&&this.screen_width)if(!this.palette_source||this.clocking_mode&32)this.layers=[],this.screen.clear_screen();else{var a=this.start_address_latched,b=this.horizontal_panning;this.attribute_mode&64&&(b>>>=1);var c=this.preset_row_scan>>5&3,d=this.vga_addr_to_pixel(a+c);a=d/this.virtual_width|0;var e=d%this.virtual_width+b;d=this.scan_line_to_screen_row(1+this.line_compare); +d=Math.min(d,this.screen_height);var g=this.screen_height-d;this.layers=[];e=-e;for(var f=0;ethis.attribute_controller_index)B(this.attribute_controller_index),B(a),this.dac_map[this.attribute_controller_index]=a,this.attribute_mode&64||this.complete_redraw();else switch(this.attribute_controller_index){case 16:B(a);if(this.attribute_mode!==a){var b= +this.attribute_mode;this.attribute_mode=a;const c=0!==(a&1);this.svga_enabled||this.graphical_mode===c||(this.graphical_mode=c,this.screen.set_mode(this.graphical_mode));(b^a)&64&&this.complete_replot();this.update_vga_size();this.complete_redraw();this.set_font_bitmap(!1)}break;case 18:B(a);this.color_plane_enable!==a&&(this.color_plane_enable=a,this.complete_redraw());break;case 19:B(a);this.horizontal_panning!==a&&(this.horizontal_panning=a&15,this.update_layers());break;case 20:B(a);this.color_select!== +a&&(this.color_select=a,this.complete_redraw());break;default:B(this.attribute_controller_index),B(a)}this.attribute_controller_index=-1}};N.prototype.port3C0_read=function(){return(this.attribute_controller_index|this.palette_source)&255};N.prototype.port3C0_read16=function(){return this.port3C0_read()|this.port3C1_read()<<8&65280}; +N.prototype.port3C1_read=function(){if(16>this.attribute_controller_index)return B(this.attribute_controller_index),B(this.dac_map[this.attribute_controller_index]),this.dac_map[this.attribute_controller_index]&255;switch(this.attribute_controller_index){case 16:return B(this.attribute_mode),this.attribute_mode;case 18:return B(this.color_plane_enable),this.color_plane_enable;case 19:return B(this.horizontal_panning),this.horizontal_panning;case 20:return B(this.color_select),this.color_select;default:B(this.attribute_controller_index)}return 255}; +N.prototype.port3C2_write=function(a){B(a);this.miscellaneous_output_register=a};N.prototype.port3C4_write=function(a){this.sequencer_index=a};N.prototype.port3C4_read=function(){return this.sequencer_index}; +N.prototype.port3C5_write=function(a){switch(this.sequencer_index){case 1:B(a);var b=this.clocking_mode;this.clocking_mode=a;(b^a)&32&&this.update_layers();this.set_font_bitmap(!1);break;case 2:B(a);b=this.plane_write_bm;this.plane_write_bm=a;this.graphical_mode||!(b&4)||this.plane_write_bm&4||this.set_font_bitmap(!0);break;case 3:B(a);b=this.character_map_select;this.character_map_select=a;this.graphical_mode||b===a||this.set_font_page();break;case 4:B(a);this.sequencer_memory_mode=a;break;default:B(this.sequencer_index), +B(a)}};N.prototype.port3C5_read=function(){B(this.sequencer_index);switch(this.sequencer_index){case 1:return this.clocking_mode;case 2:return this.plane_write_bm;case 3:return this.character_map_select;case 4:return this.sequencer_memory_mode;case 6:return 18}return 0};N.prototype.port3C6_write=function(a){this.dac_mask!==a&&(this.dac_mask=a,this.complete_redraw())};N.prototype.port3C6_read=function(){return this.dac_mask}; +N.prototype.port3C7_write=function(a){B(a);this.dac_color_index_read=3*a;this.dac_state&=0};N.prototype.port3C7_read=function(){return this.dac_state};N.prototype.port3C8_write=function(a){this.dac_color_index_write=3*a;this.dac_state|=3};N.prototype.port3C8_read=function(){return this.dac_color_index_write/3&255}; +N.prototype.port3C9_write=function(a){var b=this.dac_color_index_write/3|0,c=this.dac_color_index_write%3,d=this.vga256_palette[b];if(0===(this.dispi_enable_value&32)){a&=63;const e=a&1;a=a<<2|e<<1|e}0===c?d=d&-16711681|a<<16:1===c?d=d&-65281|a<<8:(d=d&-256|a,B(b),B(d));this.vga256_palette[b]!==d&&(this.vga256_palette[b]=d,this.complete_redraw());this.dac_color_index_write++}; +N.prototype.port3C9_read=function(){var a=this.vga256_palette[this.dac_color_index_read/3|0]>>8*(2-this.dac_color_index_read%3)&255;this.dac_color_index_read++;return this.dispi_enable_value&32?a:a>>2};N.prototype.port3CC_read=function(){return this.miscellaneous_output_register};N.prototype.port3CE_write=function(a){this.graphics_index=a};N.prototype.port3CE_read=function(){return this.graphics_index}; +N.prototype.port3CF_write=function(a){switch(this.graphics_index){case 0:this.planar_setreset=a;B(a);break;case 1:this.planar_setreset_enable=a;B(a);break;case 2:this.color_compare=a;B(a);break;case 3:this.planar_rotate_reg=a;B(a);break;case 4:this.plane_read=a;B(a);break;case 5:var b=this.planar_mode;this.planar_mode=a;B(a);(b^a)&96&&this.complete_replot();break;case 6:B(a);this.miscellaneous_graphics_register!==a&&(this.miscellaneous_graphics_register=a,this.update_vga_size());break;case 7:this.color_dont_care= +a;B(a);break;case 8:this.planar_bitmap=a;B(a);break;default:B(this.graphics_index),B(a)}};N.prototype.port3CF_read=function(){B(this.graphics_index);switch(this.graphics_index){case 0:return this.planar_setreset;case 1:return this.planar_setreset_enable;case 2:return this.color_compare;case 3:return this.planar_rotate_reg;case 4:return this.plane_read;case 5:return this.planar_mode;case 6:return this.miscellaneous_graphics_register;case 7:return this.color_dont_care;case 8:return this.planar_bitmap}return 0}; +N.prototype.port3D4_write=function(a){this.index_crtc=a};N.prototype.port3D4_write16=function(a){this.port3D4_write(a&255);this.port3D5_write(a>>8&255)};N.prototype.port3D4_read=function(){return this.index_crtc}; +N.prototype.port3D5_write=function(a){switch(this.index_crtc){case 1:B(a);this.horizontal_display_enable_end!==a&&(this.horizontal_display_enable_end=a,this.update_vga_size());break;case 2:this.horizontal_blank_start!==a&&(this.horizontal_blank_start=a,this.update_vga_size());break;case 7:B(a);var b=this.vertical_display_enable_end;this.vertical_display_enable_end&=255;this.vertical_display_enable_end=this.vertical_display_enable_end|a<<3&512|a<<7&256;b!==this.vertical_display_enable_end&&this.update_vga_size(); +this.line_compare=this.line_compare&767|a<<4&256;b=this.vertical_blank_start;this.vertical_blank_start=this.vertical_blank_start&767|a<<5&256;b!==this.vertical_blank_start&&this.update_vga_size();this.update_layers();break;case 8:B(a);this.preset_row_scan=a;this.update_layers();break;case 9:B(a);var c=this.max_scan_line;this.max_scan_line=a;this.line_compare=this.line_compare&511|a<<3&512;b=this.vertical_blank_start;this.vertical_blank_start=this.vertical_blank_start&511|a<<4&512;((c^this.max_scan_line)& +159||b!==this.vertical_blank_start)&&this.update_vga_size();this.update_cursor_scanline();this.update_layers();this.set_font_bitmap(!1);break;case 10:B(a);this.cursor_scanline_start=a;this.update_cursor_scanline();break;case 11:B(a);this.cursor_scanline_end=a;this.update_cursor_scanline();break;case 12:(this.start_address>>8&255)!==a&&(this.start_address=this.start_address&255|a<<8,this.update_layers(),~this.crtc_mode&3&&this.complete_replot());B(a);B(this.start_address,4);break;case 13:(this.start_address& +255)!==a&&(this.start_address=this.start_address&65280|a,this.update_layers(),~this.crtc_mode&3&&this.complete_replot());B(a);B(this.start_address,4);break;case 14:B(a);this.cursor_address=this.cursor_address&255|a<<8;this.update_cursor();break;case 15:B(a);this.cursor_address=this.cursor_address&65280|a;this.update_cursor();break;case 18:B(a);(this.vertical_display_enable_end&255)!==a&&(this.vertical_display_enable_end=this.vertical_display_enable_end&768|a,this.update_vga_size());break;case 19:B(a); +this.offset_register!==a&&(this.offset_register=a,this.update_vga_size(),~this.crtc_mode&3&&this.complete_replot());break;case 20:B(a);this.underline_location_register!==a&&(b=this.underline_location_register,this.underline_location_register=a,this.update_vga_size(),(b^a)&64&&this.complete_replot());break;case 21:B(a);(this.vertical_blank_start&255)!==a&&(this.vertical_blank_start=this.vertical_blank_start&768|a,this.update_vga_size());break;case 23:B(a);this.crtc_mode!==a&&(b=this.crtc_mode,this.crtc_mode= +a,this.update_vga_size(),(b^a)&67&&this.complete_replot());break;case 24:B(a);this.line_compare=this.line_compare&768|a;this.update_layers();break;default:this.index_crtc>7&2|this.vertical_blank_start>>5&8|this.line_compare>>4&16|this.vertical_display_enable_end>>3&64;case 8:return this.preset_row_scan;case 9:return this.max_scan_line;case 10:return this.cursor_scanline_start;case 11:return this.cursor_scanline_end;case 12:return this.start_address&255; +case 13:return this.start_address>>8;case 14:return this.cursor_address>>8;case 15:return this.cursor_address&255;case 18:return this.vertical_display_enable_end&255;case 19:return this.offset_register;case 20:return this.underline_location_register;case 21:return this.vertical_blank_start&255;case 23:return this.crtc_mode;case 24:return this.line_compare&255}return this.index_crtc=a?this.svga_version=a:B(a);break;case 1:this.svga_width=a;2560>>16;case 6:return this.screen_width?this.screen_width:1;case 8:return this.svga_offset_x;case 9:return this.svga_offset_y;case 10:return this.vga_memory_size/65536| +0;default:B(this.dispi_index)}return 255}; +N.prototype.vga_replot=function(){for(var a=this.diff_plot_min&-16,b=Math.min(this.diff_plot_max|15,524287),c=this.vga_addr_shift_count(),d=~this.crtc_mode&3,e=this.planar_mode&96,g=this.attribute_mode&64;a<=b;){var f=a>>>c;if(d){var h=a/this.virtual_width|0,l=a-this.virtual_width*h;switch(d){case 1:f=(h&1)<<13;h>>>=1;break;case 2:f=(h&1)<<14;h>>>=1;break;case 3:f=(h&3)<<13,h>>>=2}f|=(h*this.virtual_width+l>>>c)+this.start_address}h=this.plane0[f];l=this.plane1[f];var m=this.plane2[f],n=this.plane3[f]; +f=new Uint8Array(8);switch(e){case 0:h<<=0;l<<=1;m<<=2;n<<=3;for(var p=7;0<=p;p--)f[7-p]=h>>p&1|l>>p&2|m>>p&4|n>>p&8;break;case 32:f[0]=h>>6&3|m>>4&12;f[1]=h>>4&3|m>>2&12;f[2]=h>>2&3|m>>0&12;f[3]=h>>0&3|m<<2&12;f[4]=l>>6&3|n>>4&12;f[5]=l>>4&3|n>>2&12;f[6]=l>>2&3|n>>0&12;f[7]=l>>0&3|n<<2&12;break;case 64:case 96:f[0]=h>>4&15,f[1]=h>>0&15,f[2]=l>>4&15,f[3]=l>>0&15,f[4]=m>>4&15,f[5]=m>>0&15,f[6]=n>>4&15,f[7]=n>>0&15}if(g)for(h=p=0;4>p;p++,a++,h+=2)this.pixel_buffer[a]=f[h]<<4|f[h+1];else for(p=0;8>p;p++, +a++)this.pixel_buffer[a]=f[p]}}; +N.prototype.vga_redraw=function(){var a=this.diff_addr_min,b=Math.min(this.diff_addr_max,524287);const c=new Int32Array(this.cpu.wasm_memory.buffer,this.dest_buffet_offset,this.virtual_width*this.virtual_height);var d=255,e=0;this.attribute_mode&128&&(d&=207,e|=this.color_select<<4&48);if(this.attribute_mode&64)for(;a<=b;a++){var g=this.pixel_buffer[a]&d|e;g=this.vga256_palette[g];c[a]=g&65280|g<<16|g>>16|4278190080}else for(d&=63,e|=this.color_select<<4&192;a<=b;a++)g=this.dac_map[this.pixel_buffer[a]& +this.color_plane_enable]&d|e,g=this.vga256_palette[g],c[a]=g&65280|g<<16|g>>16|4278190080}; +N.prototype.screen_fill_buffer=function(){if(this.graphical_mode){if(0===this.image_data.data.byteLength){var a=new Uint8ClampedArray(this.cpu.wasm_memory.buffer,this.dest_buffet_offset,4*this.virtual_width*this.virtual_height);this.image_data=new ImageData(a,this.virtual_width,this.virtual_height);this.update_layers()}if(this.svga_enabled){a=0;let d=this.svga_height;if(8===this.svga_bpp){const e=new Int32Array(this.cpu.wasm_memory.buffer,this.dest_buffet_offset,this.screen_width*this.screen_height), +g=new Uint8Array(this.cpu.wasm_memory.buffer,this.svga_memory.byteOffset,this.vga_memory_size);for(var b=0;b>16|4278190080}}else this.cpu.svga_fill_pixel_buffer(this.svga_bpp,this.svga_offset),b=15===this.svga_bpp?2:this.svga_bpp/8,a=((this.cpu.svga_dirty_bitmap_min_offset[0]/b|0)-this.svga_offset)/this.svga_width|0,d=(((this.cpu.svga_dirty_bitmap_max_offset[0]/b|0)-this.svga_offset)/this.svga_width|0)+1;a>2|(this.character_map_select&32)>>3,c=this.character_map_select&3|(this.character_map_select&16)>>2;this.font_page_ab_enabled=b!==c;this.screen.set_font_page(a[b],a[c]);this.complete_redraw()};const Zc="SWAP_IN SWAP_OUT MAJFLT MINFLT MEMFREE MEMTOT AVAIL CACHES HTLB_PGALLOC HTLB_PGFAIL".split(" "); -function $c(a,b){this.bus=b;this.zeroed=this.fp_cmd=this.actual=this.num_pages=0;this.virtio=new Fc(a,{name:"virtio-balloon",pci_id:88,device_id:4165,subsystem_device_id:5,common:{initial_port:55296,queues:[{size_supported:32,notify_offset:0},{size_supported:32,notify_offset:0},{size_supported:2,notify_offset:1},{size_supported:64,notify_offset:2}],features:[1,3,32],on_driver_ok:()=>{}},notification:{initial_port:55552,single_handler:!1,handlers:[c=>{const d=this.virtio.queues[c];for(;d.has_request();){var e= -d.pop_request();const f=new Uint8Array(e.length_readable);e.get_next_blob(f);this.virtio.queues[c].push_reply(e);e=f.byteLength/4;this.actual+=0===c?e:-e}this.virtio.queues[c].flush_replies()},c=>{var d=this.virtio.queues[c];if(d.has_request()){d=d.pop_request();const e=new Uint8Array(d.length_readable);d.get_next_blob(e);let f={};for(let g=0;g{const d= -this.virtio.queues[c];for(;d.has_request();){const f=d.pop_request();if(0this.num_pages,write:()=>{}},{bytes:4,name:"actual",read:()=>this.actual,write:()=>{}},{bytes:4,name:"free_page_hint_cmd_id",read:()=>this.fp_cmd,write:()=>{}}]}})}$c.prototype.Inflate=function(a){this.num_pages+=a;this.virtio.notify_config_changes()};$c.prototype.Deflate=function(a){this.num_pages-=a;this.virtio.notify_config_changes()}; -$c.prototype.Cleanup=function(a){this.fp_cmd=2;this.free_cb=a;this.zeroed=0;this.virtio.notify_config_changes()};$c.prototype.get_state=function(){const a=[];a[0]=this.virtio;a[1]=this.num_pages;a[2]=this.actual;return a};$c.prototype.set_state=function(a){this.virtio.set_state(a[0]);this.num_pages=a[1];this.actual=a[2]};$c.prototype.GetStats=function(a){this.stats_cb=a;for(a=this.virtio.queues[2];a.has_request();){const b=a.pop_request();this.virtio.queues[2].push_reply(b)}this.virtio.queues[2].flush_replies()}; -$c.prototype.Reset=function(){};function ad(a,b,c,d){var e=new Uint8Array(b);const f=new Uint16Array(b);var g=new Uint32Array(b),h=e[497]||4,l=f[255];if(43605!==l)y(l);else if(l=f[257]|f[258]<<16,1400005704!==l)y(l);else{l=f[259];var m=e[529],n=f[283],p=g[139],q=g[140],r=e[565],x=518<=l?g[142]:255,C=g[146],t=g[147],A=g[150],M=g[151],v=g[152];y(l);y(m);y(n);y(g[133]);y(p);y(q);y(r);y(x);y(C);y(t);y(M);y(A);y(v);e[528]=255;e[529]=m&-97|128;f[274]=56832;f[253]=65535;y(56832);d+="\x00";y(581632);g[138]=581632;for(e=0;e>>17](a)};O.prototype.mmap_write8=function(a,b){this.memory_map_write8[a>>>17](a,b)};O.prototype.mmap_write16=function(a,b){var c=this.memory_map_write8[a>>>17];c(a,b&255);c(a+1|0,b>>8)}; -O.prototype.mmap_read32=function(a){return this.memory_map_read32[a>>>17](a)};O.prototype.mmap_write32=function(a,b){this.memory_map_write32[a>>>17](a,b)};O.prototype.mmap_write64=function(a,b,c){var d=this.memory_map_write32[a>>>17];d(a,b);d(a+4,c)};O.prototype.mmap_write128=function(a,b,c,d,e){var f=this.memory_map_write32[a>>>17];f(a,b);f(a+4,c);f(a+8,d);f(a+12,e)}; -O.prototype.write_blob=function(a,b){a.length&&(this.in_mapped_range(b),this.in_mapped_range(b+a.length-1),this.jit_dirty_cache(b,b+a.length),this.mem8.set(a,b))};O.prototype.read_blob=function(a,b){b&&(this.in_mapped_range(a),this.in_mapped_range(a+b-1));return this.mem8.subarray(a,a+b)};O.prototype.clear_opstats=function(){(new Uint8Array(this.wasm_memory.buffer,32768,131072)).fill(0);this.wm.exports.profiler_init()}; -O.prototype.create_jit_imports=function(){const a=Object.create(null);a.m=this.wm.exports.memory;for(const b of Object.keys(this.wm.exports))b.startsWith("_")||b.startsWith("zstd")||b.endsWith("_js")||(a[b]=this.wm.exports[b]);this.jit_imports=a}; -O.prototype.wasm_patch=function(){const a=c=>this.wm.exports[c],b=c=>{const d=a(c);console.assert(d,"Missing import: "+c);return d};this.reset_cpu=b("reset_cpu");this.getiopl=b("getiopl");this.get_eflags=b("get_eflags");this.handle_irqs=b("handle_irqs");this.main_loop=b("main_loop");this.set_jit_config=b("set_jit_config");this.read8=b("read8");this.read16=b("read16");this.read32s=b("read32s");this.write8=b("write8");this.write16=b("write16");this.write32=b("write32");this.in_mapped_range=b("in_mapped_range"); -this.fpu_load_tag_word=b("fpu_load_tag_word");this.fpu_load_status_word=b("fpu_load_status_word");this.fpu_get_sti_f64=b("fpu_get_sti_f64");this.translate_address_system_read=b("translate_address_system_read_js");this.get_seg_cs=b("get_seg_cs");this.get_real_eip=b("get_real_eip");this.clear_tlb=b("clear_tlb");this.full_clear_tlb=b("full_clear_tlb");this.update_state_flags=b("update_state_flags");this.set_tsc=b("set_tsc");this.store_current_tsc=b("store_current_tsc");this.set_cpuid_level=b("set_cpuid_level"); -this.device_raise_irq=b("device_raise_irq");this.device_lower_irq=b("device_lower_irq");this.apic_timer=b("apic_timer");this.jit_clear_cache=b("jit_clear_cache_js");this.jit_dirty_cache=b("jit_dirty_cache");this.codegen_finalize_finished=b("codegen_finalize_finished");this.allocate_memory=b("allocate_memory");this.zero_memory=b("zero_memory");this.is_memory_zeroed=b("is_memory_zeroed");this.svga_allocate_memory=b("svga_allocate_memory");this.svga_allocate_dest_buffer=b("svga_allocate_dest_buffer"); -this.svga_fill_pixel_buffer=b("svga_fill_pixel_buffer");this.svga_mark_dirty=b("svga_mark_dirty");this.get_pic_addr_master=b("get_pic_addr_master");this.get_pic_addr_slave=b("get_pic_addr_slave");this.get_apic_addr=b("get_apic_addr");this.get_ioapic_addr=b("get_ioapic_addr");this.zstd_create_ctx=b("zstd_create_ctx");this.zstd_get_src_ptr=b("zstd_get_src_ptr");this.zstd_free_ctx=b("zstd_free_ctx");this.zstd_read=b("zstd_read");this.zstd_read_free=b("zstd_read_free")}; -O.prototype.jit_force_generate=function(a){this.jit_force_generate_unsafe&&this.jit_force_generate_unsafe(a)};O.prototype.jit_clear_func=function(a){this.wm.wasm_table.set(a+1024,null)};O.prototype.jit_clear_all_funcs=function(){const a=this.wm.wasm_table;for(let b=0;900>b;b++)a.set(1024+b,null)}; -O.prototype.get_state=function(){var a=[];a[0]=this.memory_size[0];a[1]=new Uint8Array([...this.segment_is_null,...this.segment_access_bytes]);a[2]=this.segment_offsets;a[3]=this.segment_limits;a[4]=this.protected_mode[0];a[5]=this.idtr_offset[0];a[6]=this.idtr_size[0];a[7]=this.gdtr_offset[0];a[8]=this.gdtr_size[0];a[9]=this.page_fault[0];a[10]=this.cr;a[11]=this.cpl[0];a[13]=this.is_32[0];a[16]=this.stack_size_32[0];a[17]=this.in_hlt[0];a[18]=this.last_virt_eip[0];a[19]=this.eip_phys[0];a[22]=this.sysenter_cs[0]; -a[23]=this.sysenter_eip[0];a[24]=this.sysenter_esp[0];a[25]=this.prefixes[0];a[26]=this.flags[0];a[27]=this.flags_changed[0];a[28]=this.last_op1[0];a[30]=this.last_op_size[0];a[37]=this.instruction_pointer[0];a[38]=this.previous_ip[0];a[39]=this.reg32;a[40]=this.sreg;a[41]=this.dreg;a[42]=this.reg_pdpte;this.store_current_tsc();a[43]=this.current_tsc;a[45]=this.devices.virtio_9p;a[46]=this.get_state_apic();a[47]=this.devices.rtc;a[48]=this.devices.pci;a[49]=this.devices.dma;a[50]=this.devices.acpi; -a[52]=this.devices.vga;a[53]=this.devices.ps2;a[54]=this.devices.uart0;a[55]=this.devices.fdc;this.devices.ide.secondary?a[85]=this.devices.ide:this.devices.ide.primary?.master.is_atapi?a[56]=this.devices.ide.primary:a[57]=this.devices.ide.primary;a[58]=this.devices.pit;a[59]=this.devices.net;a[60]=this.get_state_pic();a[61]=this.devices.sb16;a[62]=this.fw_value;a[63]=this.get_state_ioapic();a[64]=this.tss_size_32[0];a[66]=this.reg_xmm32s;a[67]=this.fpu_st;a[68]=this.fpu_stack_empty[0];a[69]=this.fpu_stack_ptr[0]; -a[70]=this.fpu_control_word[0];a[71]=this.fpu_ip[0];a[72]=this.fpu_ip_selector[0];a[73]=this.fpu_dp[0];a[74]=this.fpu_dp_selector[0];a[75]=this.fpu_opcode[0];const {packed_memory:b,bitmap:c}=this.pack_memory();a[77]=b;a[78]=new Uint8Array(c.get_buffer());a[79]=this.devices.uart1;a[80]=this.devices.uart2;a[81]=this.devices.uart3;a[82]=this.devices.virtio_console;a[83]=this.devices.virtio_net;a[84]=this.devices.virtio_balloon;a[86]=this.last_result;a[87]=this.fpu_status_word;a[88]=this.mxcsr;return a}; -O.prototype.get_state_pic=function(){const a=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_master(),13),b=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_slave(),13),c=[],d=[];c[0]=a[0];c[1]=a[1];c[2]=a[2];c[3]=a[3];c[4]=a[4];c[5]=d;c[6]=a[6];c[7]=a[7];c[8]=a[8];c[9]=a[9];c[10]=a[10];c[11]=a[11];c[12]=a[12];d[0]=b[0];d[1]=b[1];d[2]=b[2];d[3]=b[3];d[4]=b[4];d[5]=null;d[6]=b[6];d[7]=b[7];d[8]=b[8];d[9]=b[9];d[10]=b[10];d[11]=b[11];d[12]=b[12];return c}; -O.prototype.get_state_apic=function(){return new Uint8Array(this.wasm_memory.buffer,this.get_apic_addr(),184)};O.prototype.get_state_ioapic=function(){return new Uint8Array(this.wasm_memory.buffer,this.get_ioapic_addr(),208)}; -O.prototype.set_state=function(a){this.memory_size[0]=a[0];this.mem8.length!==this.memory_size[0]&&console.warn("Note: Memory size mismatch. we="+this.mem8.length+" state="+this.memory_size[0]);8===a[1].length?(this.segment_is_null.set(a[1]),this.segment_access_bytes.fill(242),this.segment_access_bytes[1]=250):16===a[1].length&&(this.segment_is_null.set(a[1].subarray(0,8)),this.segment_access_bytes.set(a[1].subarray(8,16)));this.segment_offsets.set(a[2]);this.segment_limits.set(a[3]);this.protected_mode[0]= -a[4];this.idtr_offset[0]=a[5];this.idtr_size[0]=a[6];this.gdtr_offset[0]=a[7];this.gdtr_size[0]=a[8];this.page_fault[0]=a[9];this.cr.set(a[10]);this.cpl[0]=a[11];this.is_32[0]=a[13];this.stack_size_32[0]=a[16];this.in_hlt[0]=a[17];this.last_virt_eip[0]=a[18];this.eip_phys[0]=a[19];this.sysenter_cs[0]=a[22];this.sysenter_eip[0]=a[23];this.sysenter_esp[0]=a[24];this.prefixes[0]=a[25];this.flags[0]=a[26];this.flags_changed[0]=a[27];this.last_op1[0]=a[28];this.last_op_size[0]=a[30];this.instruction_pointer[0]= -a[37];this.previous_ip[0]=a[38];this.reg32.set(a[39]);this.sreg.set(a[40]);this.dreg.set(a[41]);a[42]&&this.reg_pdpte.set(a[42]);this.set_tsc(a[43][0],a[43][1]);this.devices.virtio_9p&&this.devices.virtio_9p.set_state(a[45]);a[46]&&this.set_state_apic(a[46]);this.devices.rtc&&this.devices.rtc.set_state(a[47]);this.devices.dma&&this.devices.dma.set_state(a[49]);this.devices.acpi&&this.devices.acpi.set_state(a[50]);this.devices.vga&&this.devices.vga.set_state(a[52]);this.devices.ps2&&this.devices.ps2.set_state(a[53]); -this.devices.uart0&&this.devices.uart0.set_state(a[54]);this.devices.fdc&&this.devices.fdc.set_state(a[55]);if(a[56]||a[57]){var b=[[void 0,void 0],[void 0,void 0]];b[0][0]=a[56]?{is_cdrom:!0,buffer:this.devices.cdrom.buffer}:{is_cdrom:!1,buffer:this.devices.ide.primary.master.buffer};this.devices.ide=new Uc(this,this.devices.ide.bus,b);this.devices.cdrom=a[56]?this.devices.ide.primary.master:void 0;this.devices.ide.primary.set_state(a[56]||a[57])}else a[85]&&this.devices.ide.set_state(a[85]);this.devices.pci&& -this.devices.pci.set_state(a[48]);this.devices.pit&&this.devices.pit.set_state(a[58]);this.devices.net&&this.devices.net.set_state(a[59]);this.set_state_pic(a[60]);this.devices.sb16&&this.devices.sb16.set_state(a[61]);this.devices.uart1&&this.devices.uart1.set_state(a[79]);this.devices.uart2&&this.devices.uart2.set_state(a[80]);this.devices.uart3&&this.devices.uart3.set_state(a[81]);this.devices.virtio_console&&this.devices.virtio_console.set_state(a[82]);this.devices.virtio_net&&this.devices.virtio_net.set_state(a[83]); -this.devices.virtio_balloon&&this.devices.virtio_balloon.set_state(a[84]);this.fw_value=a[62];a[63]&&this.set_state_ioapic(a[63]);this.tss_size_32[0]=a[64];this.reg_xmm32s.set(a[66]);this.fpu_st.set(a[67]);this.fpu_stack_empty[0]=a[68];this.fpu_stack_ptr[0]=a[69];this.fpu_control_word[0]=a[70];this.fpu_ip[0]=a[71];this.fpu_ip_selector[0]=a[72];this.fpu_dp[0]=a[73];this.fpu_dp_selector[0]=a[74];this.fpu_opcode[0]=a[75];void 0!==a[86]&&(this.last_result=a[86]);void 0!==a[87]&&(this.fpu_status_word= -a[87]);void 0!==a[88]&&(this.mxcsr=a[88]);b=new ma(a[78].buffer);this.unpack_memory(b,a[77]);this.update_state_flags();this.full_clear_tlb();this.jit_clear_cache()}; -O.prototype.set_state_pic=function(a){const b=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_master(),13),c=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_slave(),13);b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];const d=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];c[0]=d[0];c[1]=d[1];c[2]=d[2];c[3]=d[3];c[4]=d[4];c[6]=d[6];c[7]=d[7];c[8]=d[8];c[9]=d[9];c[10]=d[10];c[11]=d[11];c[12]=d[12]}; -O.prototype.set_state_apic=function(a){if(a instanceof Array){const b=new Int32Array(this.wasm_memory.buffer,this.get_apic_addr(),46);b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];b[8]=a[6];b[9]=a[7];b[10]=a[8];b[11]=a[9];b[12]=a[10];b[13]=a[11];b[14]=a[12];b[15]=a[13];b.set(a[15],16);b.set(a[15],24);b.set(a[16],32);b[40]=a[17];b[41]=a[18];b[42]=a[19];b[43]=a[20];b[44]=a[21];b[45]=a[22]||65536}else(new Uint8Array(this.wasm_memory.buffer,this.get_apic_addr(),184)).set(a)}; -O.prototype.set_state_ioapic=function(a){if(a instanceof Array){const b=new Int32Array(this.wasm_memory.buffer,this.get_ioapic_addr(),52);b.set(a[0],0);b.set(a[1],24);b[48]=a[2];b[49]=a[3];b[50]=a[4];b[51]=a[5]}else(new Uint8Array(this.wasm_memory.buffer,this.get_ioapic_addr(),208)).set(a)}; -O.prototype.pack_memory=function(){var a=this.mem8.length>>12,b=[];for(var c=0;c>12;let d=0;for(let f=0;f(a|0)&&(a=Math.pow(2,31)-131072);a=(a-1|131071)+1|0;console.assert(0===this.memory_size[0],"Expected uninitialised memory");this.memory_size[0]=a;b=this.allocate_memory(a);this.mem8=k(Uint8Array,this.wasm_memory,b,a);this.mem32s=k(Uint32Array,this.wasm_memory,b,a>>2)}; -O.prototype.init=function(a,b){this.create_memory(a.memory_size||67108864,a.initrd?67108864:1048576);a.disable_jit&&this.set_jit_config(0,1);a.cpuid_level&&this.set_cpuid_level(a.cpuid_level);this.acpi_enabled[0]=+a.acpi;this.reset_cpu();var c=new Ca(this);this.io=c;this.bios.main=a.bios;this.bios.vga=a.vga_bios;this.load_bios();if(a.bzimage){const e=ad(this.mem8,a.bzimage,a.initrd,a.cmdline||"");e&&this.option_roms.push(e)}c.register_read(179,this,function(){return 0});var d=0;c.register_read(146, -this,function(){return d});c.register_write(146,this,function(e){d=e});c.register_read(1297,this,function(){return this.fw_pointer>8|l<<8&65280}function h(l){return l<<24|l<<8&16711680|l>>8&65280|l>>>24}ua("bios config port, index="+y(e));this.fw_pointer=0;if(0===e)this.fw_value=f(1431127377);else if(1===e)this.fw_value= -f(0);else if(3===e)this.fw_value=f(this.memory_size[0]);else if(5===e)this.fw_value=f(1);else if(15===e)this.fw_value=f(1);else if(13===e)this.fw_value=new Uint8Array(16);else if(25===e){e=new Int32Array(4+64*this.option_roms.length);const l=new Uint8Array(e.buffer);e[0]=h(this.option_roms.length);for(let m=0;m>2]=h(p.length);e[q+4>>2]=g(49152+m);for(let r=0;re?this.fw_value=f(0):49152<=e&&e-49152a.byteLength){var d=new Int32Array(2048);(new Uint8Array(d.buffer)).set(new Uint8Array(a))}else d=new Int32Array(a,0,2048);for(var e=0;8192>e;e+=4){if(464367618===d[e>>2]){var f=d[e+4>>2];if(464367618+f+d[e+8>>2]|0)continue}else continue;ua("Multiboot magic found, flags: "+y(f>>>0,8),2);var g=this;this.io.register_read(244,this,function(){return 0},function(){return 0},function(){var n,p=31860;let q=0;if(c){q|=4;g.write32(31760,p);c+="\x00"; -var r=(new TextEncoder).encode(c);g.write_blob(r,p);p+=r.length}if(f&2){q|=64;r=0;g.write32(31788,0);g.write32(31792,p);var x=0;var C=!1;for(n=0;4294967296>n;n+=131072)C&&void 0!==g.memory_map_read8[n>>>17]?(g.write32(p,20),g.write32(p+4,x),g.write32(p+8,0),g.write32(p+12,n-x),g.write32(p+16,0),g.write32(p+20,1),p+=24,r+=24,C=!1):C||void 0!==g.memory_map_read8[n>>>17]||(x=n,C=!0);g.write32(31788,r)}x=r=0;if(f&65536){n=d[e+12>>2];r=d[e+16>>2];var t=d[e+20>>2];x=d[e+24>>2];C=d[e+28>>2];y(n,8);y(r,8); -y(t,8);y(x,8);y(C,8);n=new Uint8Array(a,e-(n-r),0===t?void 0:t-r);g.write_blob(n,r);r=C|0;x=Math.max(t,x)}else if(1179403647===d[0]){C=new DataView(a);const [A,M]=Oc(C,Lc);console.assert(52===M);console.assert(1179403647===A.magic,"Bad magic");console.assert(1===A.class,"Unimplemented: 64 bit elf");console.assert(1===A.data,"Unimplemented: big endian");console.assert(1===A.version0,"Bad version0");console.assert(2===A.type,"Unimplemented type");console.assert(1===A.version1,"Bad version1");console.assert(52=== -A.ehsize,"Bad header size");console.assert(32===A.phentsize,"Bad program header size");console.assert(40===A.shentsize,"Bad section header size");[r]=Pc(new DataView(C.buffer,C.byteOffset+A.phoff,A.phentsize*A.phnum),Mc,A.phnum);Pc(new DataView(C.buffer,C.byteOffset+A.shoff,A.shentsize*A.shnum),Nc,A.shnum);C=A;n=r;r=C.entry;for(t of n)0!==t.type&&(1===t.type?t.paddr+t.memszr&&(r=r-t.vaddr+t.paddr)):y(t.paddr):2===t.type||3===t.type||4===t.type||6===t.type||7===t.type||1685382480===t.type||1685382481===t.type||1685382482===t.type||1685382483===t.type||y(t.type))}b&&(q|=8,g.write32(31764,1),g.write32(31768,p),t=x,0!==(t&4095)&&(t=(t&-4096)+4096),x=t+b.byteLength,g.write32(p,t),g.write32(p+4,x),g.write32(p+8,0),g.write32(p+12,0),g.write_blob(new Uint8Array(b),t));g.write32(31744,q);g.reg32[3]=31744;g.cr[0]=1;g.protected_mode[0]=1;g.flags[0]= -2;g.is_32[0]=1;g.stack_size_32[0]=1;for(p=0;6>p;p++)g.segment_is_null[p]=0,g.segment_offsets[p]=0,g.segment_limits[p]=4294967295,g.sreg[p]=45058;g.instruction_pointer[0]=g.get_seg_cs()+r|0;g.update_state_flags();g.dump_state();g.dump_regs_short();return 732803074});this.io.register_write_consecutive(244,this,function(n){console.log("Test exited with code "+y(n,2));throw"HALT";},function(){},function(){},function(){});for(let n=0;15>=n;n++){function p(q){y(n);y(q,2);q?this.device_raise_irq(n):this.device_lower_irq(n)} -this.io.register_write(8192+n,this,p,p,p)}const l=new Uint8Array(512);(new Uint16Array(l.buffer))[0]=43605;l[2]=1;var h=3;l[h++]=102;l[h++]=229;l[h++]=244;let m=l[h]=0;for(let n=0;n>4&240);a.cmos_write(61,c&255);a.cmos_write(21,128);a.cmos_write(22,2);c=0;1048576<=this.memory_size[0]&&(c=this.memory_size[0]-1048576>>10,c=Math.min(c,65535));a.cmos_write(23,c&255);a.cmos_write(24,c>>8&255);a.cmos_write(48,c&255);a.cmos_write(49,c>>8&255);c=0;16777216<=this.memory_size[0]&&(c=this.memory_size[0]-16777216>>16,c=Math.min(c,65535));a.cmos_write(52,c&255);a.cmos_write(53,c>>8&255);a.cmos_write(91,0);a.cmos_write(92, -0);a.cmos_write(93,0);a.cmos_write(20,47);a.cmos_write(95,0);b.fastboot&&a.cmos_write(63,1)}; -O.prototype.load_bios=function(){var a=this.bios.main,b=this.bios.vga;if(a){var c=new Uint8Array(a);this.write_blob(c,1048576-a.byteLength);if(b){var d=new Uint8Array(b);this.write_blob(d,786432);this.io.mmap_register(4272947200,1048576,function(e){e=e-4272947200|0;return e>>0,e>>>0);WebAssembly.instantiate(f,{e:this.jit_imports}).then(g=>{this.wm.wasm_table.set(a+1024,g.instance.exports.f);this.codegen_finalize_finished(a,b,c);this.test_hook_did_finalize_wasm&&this.test_hook_did_finalize_wasm(f)})};O.prototype.log_uncompiled_code=function(){};O.prototype.dump_function_code=function(){}; -O.prototype.run_hardware_timers=function(a,b){const c=this.devices.pit.timer(b,!1),d=this.devices.rtc.timer(b,!1);let e=100,f=100;a&&(e=this.devices.acpi.timer(b),f=this.apic_timer(b));return Math.min(c,d,e,f)};O.prototype.debug_init=function(){};O.prototype.dump_stack=function(){};O.prototype.debug_get_state=function(){};O.prototype.dump_state=function(){};O.prototype.get_regs_short=function(){};O.prototype.dump_regs_short=function(){};O.prototype.dump_gdt_ldt=function(){};O.prototype.dump_idt=function(){}; -O.prototype.dump_page_structures=function(){if(this.cr[4]&32)for(var a=0;4>a;a++){var b=this.read32s(this.cr[3]+8*a);b&1&&this.dump_page_directory(b&4294963200,!0,a<<30)}else this.dump_page_directory(this.cr[3],!1,0)};O.prototype.dump_page_directory=function(){};O.prototype.get_memory_dump=function(){};O.prototype.memory_hex_dump=function(){};O.prototype.used_memory_dump=function(){};O.prototype.debug_interrupt=function(){};O.prototype.debug_dump_code=function(){};O.prototype.dump_wasm=function(){};function Fc(a,b){this.cpu=a;this.pci=a.devices.pci;this.device_id=b.device_id;this.pci_space=[244,26,b.device_id&255,b.device_id>>8,7,5,16,0,1,0,2,0,0,0,0,0,1,168,0,0,0,16,191,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,244,26,b.subsystem_device_id&255,b.subsystem_device_id>>8,0,0,0,0,64,0,0,0,0,0,0,0,0,1,0,0];this.pci_space=this.pci_space.concat(Array(256-this.pci_space.length).fill(0));this.pci_id=b.pci_id;this.pci_bars=[];this.name=b.name;this.driver_feature_select=this.device_feature_select=0; -this.device_feature=new Uint32Array(4);this.driver_feature=new Uint32Array(4);for(var c of b.common.features)this.device_feature[c>>>5]|=1<<(c&31),this.driver_feature[c>>>5]|=1<<(c&31);b.common.features.includes(32);this.features_ok=!0;this.device_status=0;this.config_has_changed=!1;this.config_generation=0;this.queues=[];for(const d of b.common.queues)this.queues.push(new Y(a,this,d));this.queue_select=0;this.queue_selected=this.queues[0];this.isr_status=0;c=[];c.push(this.create_common_capability(b.common)); -c.push(this.create_notification_capability(b.notification));c.push(this.create_isr_capability(b.isr_status));b.device_specific&&c.push(this.create_device_specific_capability(b.device_specific));this.init_capabilities(c);a.devices.pci.register_device(this);this.reset()} -Fc.prototype.create_common_capability=function(a){return{type:1,bar:0,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array(0),struct:[{bytes:4,name:"device_feature_select",read:()=>this.device_feature_select,write:b=>{this.device_feature_select=b}},{bytes:4,name:"device_feature",read:()=>this.device_feature[this.device_feature_select]||0,write:()=>{}},{bytes:4,name:"driver_feature_select",read:()=>this.driver_feature_select,write:b=>{this.driver_feature_select=b}},{bytes:4,name:"driver_feature", +N.prototype.set_font_bitmap=function(a){const b=this.max_scan_line&31;if(b&&!this.graphical_mode){const c=!!(this.clocking_mode&8);this.screen.set_font_bitmap(b+1,!c&&!(this.clocking_mode&1),c,!!(this.attribute_mode&4),this.plane2,a)}}; +N.prototype.set_font_page=function(){const a=[0,2,4,6,1,3,5,7],b=(this.character_map_select&12)>>2|(this.character_map_select&32)>>3,c=this.character_map_select&3|(this.character_map_select&16)>>2;this.font_page_ab_enabled=b!==c;this.screen.set_font_page(a[b],a[c]);this.complete_redraw()};function za(a,b){this.cpu=a;this.bus=b;this.use_mouse=this.enable_mouse_stream=!1;this.have_mouse=!0;this.mouse_clicks=this.mouse_delta_y=this.mouse_delta_x=0;this.have_keyboard=!0;this.next_read_resolution=this.next_read_rate=this.next_handle_scan_code_set=this.next_read_led=this.next_read_sample=this.next_is_mouse_command=this.enable_keyboard_stream=!1;this.kbd_buffer=new la(1024);this.last_port60_byte=0;this.sample_rate=100;this.mouse_id=this.mouse_detect_state=0;this.mouse_reset_workaround=!1; +this.wheel_movement=0;this.resolution=4;this.scaling2=!1;this.last_mouse_packet=-1;this.mouse_buffer=new la(1024);this.next_byte_is_aux=this.next_byte_is_ready=!1;this.bus.register("keyboard-code",function(c){this.kbd_send_code(c)},this);this.bus.register("mouse-click",function(c){this.mouse_send_click(c[0],c[1],c[2])},this);this.bus.register("mouse-delta",function(c){this.mouse_send_delta(c[0],c[1])},this);this.bus.register("mouse-wheel",function(c){this.wheel_movement-=c[0];this.wheel_movement-= +2*c[1];this.wheel_movement=Math.min(7,Math.max(-8,this.wheel_movement));this.send_mouse_packet(0,0)},this);this.command_register=5;this.controller_output_port=0;this.read_controller_output_port=this.read_command_register=this.read_output_register=!1;a.io.register_read(96,this,this.port60_read);a.io.register_read(100,this,this.port64_read);a.io.register_write(96,this,this.port60_write);a.io.register_write(100,this,this.port64_write)} +za.prototype.get_state=function(){var a=[];a[0]=this.enable_mouse_stream;a[1]=this.use_mouse;a[2]=this.have_mouse;a[3]=this.mouse_delta_x;a[4]=this.mouse_delta_y;a[5]=this.mouse_clicks;a[6]=this.have_keyboard;a[7]=this.enable_keyboard_stream;a[8]=this.next_is_mouse_command;a[9]=this.next_read_sample;a[10]=this.next_read_led;a[11]=this.next_handle_scan_code_set;a[12]=this.next_read_rate;a[13]=this.next_read_resolution;a[15]=this.last_port60_byte;a[16]=this.sample_rate;a[17]=this.resolution;a[18]=this.scaling2; +a[20]=this.command_register;a[21]=this.read_output_register;a[22]=this.read_command_register;a[23]=this.controller_output_port;a[24]=this.read_controller_output_port;a[25]=this.mouse_id;a[26]=this.mouse_detect_state;a[27]=this.mouse_reset_workaround;return a}; +za.prototype.set_state=function(a){this.enable_mouse_stream=a[0];this.use_mouse=a[1];this.have_mouse=a[2];this.mouse_delta_x=a[3];this.mouse_delta_y=a[4];this.mouse_clicks=a[5];this.have_keyboard=a[6];this.enable_keyboard_stream=a[7];this.next_is_mouse_command=a[8];this.next_read_sample=a[9];this.next_read_led=a[10];this.next_handle_scan_code_set=a[11];this.next_read_rate=a[12];this.next_read_resolution=a[13];this.last_port60_byte=a[15];this.sample_rate=a[16];this.resolution=a[17];this.scaling2=a[18]; +this.command_register=a[20];this.read_output_register=a[21];this.read_command_register=a[22];this.controller_output_port=a[23];this.read_controller_output_port=a[24];this.mouse_id=a[25]||0;this.mouse_detect_state=a[26]||0;this.mouse_reset_workaround=a[27]||!1;this.next_byte_is_aux=this.next_byte_is_ready=!1;this.kbd_buffer.clear();this.mouse_buffer.clear();this.bus.send("mouse-enable",this.use_mouse)}; +za.prototype.raise_irq=function(){this.next_byte_is_ready||(this.kbd_buffer.length?this.kbd_irq():this.mouse_buffer.length&&this.mouse_irq())};za.prototype.mouse_irq=function(){this.next_byte_is_aux=this.next_byte_is_ready=!0;this.command_register&2&&(this.cpu.device_lower_irq(12),this.cpu.device_raise_irq(12))};za.prototype.kbd_irq=function(){this.next_byte_is_ready=!0;this.next_byte_is_aux=!1;this.command_register&1&&(this.cpu.device_lower_irq(1),this.cpu.device_raise_irq(1))}; +za.prototype.kbd_send_code=function(a){this.enable_keyboard_stream&&(B(a),this.kbd_buffer.push(a),this.raise_irq())};za.prototype.mouse_send_delta=function(a,b){if(this.have_mouse&&this.use_mouse){var c=this.resolution*this.sample_rate/80;this.mouse_delta_x+=a*c;this.mouse_delta_y+=b*c;this.enable_mouse_stream&&(a=this.mouse_delta_x|0,b=this.mouse_delta_y|0,a||b)&&(Date.now(),this.mouse_delta_x-=a,this.mouse_delta_y-=b,this.send_mouse_packet(a,b))}}; +za.prototype.mouse_send_click=function(a,b,c){this.have_mouse&&this.use_mouse&&(this.mouse_clicks=a|c<<1|b<<2,this.enable_mouse_stream&&this.send_mouse_packet(0,0))}; +za.prototype.send_mouse_packet=function(a,b){var c=(0>b)<<5|(0>a)<<4|8|this.mouse_clicks;this.last_mouse_packet=Date.now();this.mouse_buffer.push(c);this.mouse_buffer.push(a);this.mouse_buffer.push(b);4===this.mouse_id?(this.mouse_buffer.push(0|this.wheel_movement&15),this.wheel_movement=0):3===this.mouse_id&&(this.mouse_buffer.push(this.wheel_movement&255),this.wheel_movement=0);this.raise_irq()}; +za.prototype.apply_scaling2=function(a){var b=a>>31;switch(Math.abs(a)){case 0:case 1:case 3:return a;case 2:return b;case 4:return 6*b;case 5:return 9*b;default:return a<<1}}; +za.prototype.port60_read=function(){this.next_byte_is_ready=!1;if(!this.kbd_buffer.length&&!this.mouse_buffer.length)return this.last_port60_byte;this.next_byte_is_aux?(this.cpu.device_lower_irq(12),this.last_port60_byte=this.mouse_buffer.shift()):(this.cpu.device_lower_irq(1),this.last_port60_byte=this.kbd_buffer.shift());B(this.last_port60_byte);(this.kbd_buffer.length||this.mouse_buffer.length)&&this.raise_irq();return this.last_port60_byte}; +za.prototype.port64_read=function(){var a=16;this.next_byte_is_ready&&(a|=1);this.next_byte_is_aux&&(a|=32);B(a);return a}; +za.prototype.port60_write=function(a){B(a);if(this.read_command_register)this.command_register=a,this.read_command_register=!1,B(this.command_register);else if(this.read_output_register)this.read_output_register=!1,this.mouse_buffer.clear(),this.mouse_buffer.push(a),this.mouse_irq();else if(this.next_read_sample){this.next_read_sample=!1;this.mouse_buffer.clear();this.mouse_buffer.push(250);this.sample_rate=a;switch(this.mouse_detect_state){case -1:60===a?(this.mouse_reset_workaround=!0,this.mouse_detect_state= +0):(this.mouse_reset_workaround=!1,this.mouse_detect_state=200===a?1:0);break;case 0:200===a&&(this.mouse_detect_state=1);break;case 1:this.mouse_detect_state=100===a?2:200===a?3:0;break;case 2:80===a&&(this.mouse_id=3);this.mouse_detect_state=-1;break;case 3:80===a&&(this.mouse_id=4),this.mouse_detect_state=-1}B(a);B(this.mouse_id);this.sample_rate||(this.sample_rate=100);this.mouse_irq()}else if(this.next_read_resolution)this.next_read_resolution=!1,this.mouse_buffer.clear(),this.mouse_buffer.push(250), +this.resolution=3>7});a.io.register_write(113,this,this.cmos_port_write);a.io.register_read(113,this,this.cmos_port_read)} +Ca.prototype.get_state=function(){var a=[];a[0]=this.cmos_index;a[1]=this.cmos_data;a[2]=this.rtc_time;a[3]=this.last_update;a[4]=this.next_interrupt;a[5]=this.next_interrupt_alarm;a[6]=this.periodic_interrupt;a[7]=this.periodic_interrupt_time;a[8]=this.cmos_a;a[9]=this.cmos_b;a[10]=this.cmos_c;a[11]=this.nmi_disabled;return a}; +Ca.prototype.set_state=function(a){this.cmos_index=a[0];this.cmos_data=a[1];this.rtc_time=a[2];this.last_update=a[3];this.next_interrupt=a[4];this.next_interrupt_alarm=a[5];this.periodic_interrupt=a[6];this.periodic_interrupt_time=a[7];this.cmos_a=a[8];this.cmos_b=a[9];this.cmos_c=a[10];this.nmi_disabled=a[11]}; +Ca.prototype.timer=function(a){a=Date.now();this.rtc_time+=a-this.last_update;this.last_update=a;this.periodic_interrupt&&this.next_interrupt>4&15)};Ca.prototype.encode_time=function(a){return this.cmos_b&4?a:this.bcd_pack(a)};Ca.prototype.decode_time=function(a){return this.cmos_b&4?a:this.bcd_unpack(a)}; +Ca.prototype.cmos_port_read=function(){var a=this.cmos_index;switch(a){case 0:return B(this.encode_time((new Date(this.rtc_time)).getUTCSeconds())),this.encode_time((new Date(this.rtc_time)).getUTCSeconds());case 2:return B(this.encode_time((new Date(this.rtc_time)).getUTCMinutes())),this.encode_time((new Date(this.rtc_time)).getUTCMinutes());case 4:return B(this.encode_time((new Date(this.rtc_time)).getUTCHours())),this.encode_time((new Date(this.rtc_time)).getUTCHours());case 6:return B(this.encode_time((new Date(this.rtc_time)).getUTCDay()+ +1)),this.encode_time((new Date(this.rtc_time)).getUTCDay()+1);case 7:return B(this.encode_time((new Date(this.rtc_time)).getUTCDate())),this.encode_time((new Date(this.rtc_time)).getUTCDate());case 8:return B(this.encode_time((new Date(this.rtc_time)).getUTCMonth()+1)),this.encode_time((new Date(this.rtc_time)).getUTCMonth()+1);case 9:return B(this.encode_time((new Date(this.rtc_time)).getUTCFullYear()%100)),this.encode_time((new Date(this.rtc_time)).getUTCFullYear()%100);case 10:return 999<=D.microtick()% +1E3?this.cmos_a|128:this.cmos_a;case 11:return this.cmos_b;case 12:return this.cpu.device_lower_irq(8),a=this.cmos_c,this.cmos_c&=-241,a;case 13:return 0;case 50:case 55:return B(this.encode_time((new Date(this.rtc_time)).getUTCFullYear()/100|0)),this.encode_time((new Date(this.rtc_time)).getUTCFullYear()/100|0);default:return B(a),this.cmos_data[this.cmos_index]}}; +Ca.prototype.cmos_port_write=function(a){switch(this.cmos_index){case 10:this.cmos_a=a&127;this.periodic_interrupt_time=1E3/(32768>>(this.cmos_a&15)-1);B(this.cmos_a,2);break;case 11:this.cmos_b=a;this.cmos_b&64&&(this.next_interrupt=Date.now());if(this.cmos_b&32){a=new Date;const b=this.decode_time(this.cmos_data[1]),c=this.decode_time(this.cmos_data[3]),d=this.decode_time(this.cmos_data[5]);this.next_interrupt_alarm=+new Date(Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),d,c,b))}B(this.cmos_b, +2);break;case 1:case 3:case 5:this.cmos_write(this.cmos_index,a);break;default:B(this.cmos_index),B(a)}this.periodic_interrupt=64===(this.cmos_b&64)&&0<(this.cmos_a&15)};Ca.prototype.cmos_read=function(a){return this.cmos_data[a]};Ca.prototype.cmos_write=function(a,b){B(a);B(b);this.cmos_data[a]=b};function Da(a,b,c){this.bus=c;this.cpu=a;this.ints=4;this.line_control=this.baud_rate=0;this.lsr=96;this.ier=this.fifo_control=0;this.iir=1;this.irq=this.scratch_register=this.modem_status=this.modem_control=0;this.input=[];this.current_line="";switch(b){case 1016:this.com=0;this.irq=4;break;case 760:this.com=1;this.irq=3;break;case 1E3:this.com=2;this.irq=4;break;case 744:this.irq=this.com=3;break;default:ta("Invalid serial port: "+B(b),16384),this.com=0,this.irq=4}this.bus.register("serial"+this.com+ +"-input",function(d){this.data_received(d)},this);this.bus.register("serial"+this.com+"-modem-status-input",function(d){this.set_modem_status(d)},this);this.bus.register("serial"+this.com+"-carrier-detect-input",function(d){this.set_modem_status(d?this.modem_status|136:this.modem_status&-137)},this);this.bus.register("serial"+this.com+"-ring-indicator-input",function(d){this.set_modem_status(d?this.modem_status|68:this.modem_status&-69)},this);this.bus.register("serial"+this.com+"-data-set-ready-input", +function(d){this.set_modem_status(d?this.modem_status|34:this.modem_status&-35)},this);this.bus.register("serial"+this.com+"-clear-to-send-input",function(d){this.set_modem_status(d?this.modem_status|17:this.modem_status&-18)},this);a=a.io;a.register_write(b,this,function(d){this.write_data(d)},function(d){this.write_data(d&255);this.write_data(d>>8)});a.register_write(b|1,this,function(d){this.line_control&128?(this.baud_rate=this.baud_rate&255|d<<8,B(this.baud_rate)):(0===(this.ier&2)&&d&2&&this.ThrowInterrupt(2), +this.ier=d&15,B(d),this.CheckInterrupt())});a.register_read(b,this,function(){if(this.line_control&128)return this.baud_rate&255;let d=0;0!==this.input.length&&(d=this.input.shift(),B(d));0===this.input.length&&(this.lsr&=-2,this.ClearInterrupt(12),this.ClearInterrupt(4));return d});a.register_read(b|1,this,function(){return this.line_control&128?this.baud_rate>>8:this.ier&15});a.register_read(b|2,this,function(){var d=this.iir&15;B(this.iir);2===this.iir&&this.ClearInterrupt(2);this.fifo_control& +1&&(d|=192);return d});a.register_write(b|2,this,function(d){B(d);this.fifo_control=d});a.register_read(b|3,this,function(){B(this.line_control);return this.line_control});a.register_write(b|3,this,function(d){B(d);this.line_control=d});a.register_read(b|4,this,function(){return this.modem_control});a.register_write(b|4,this,function(d){B(d);this.modem_control=d});a.register_read(b|5,this,function(){B(this.lsr);return this.lsr});a.register_write(b|5,this,function(){});a.register_read(b|6,this,function(){B(this.modem_status); +return this.modem_status&=240});a.register_write(b|6,this,function(d){B(d);this.set_modem_status(d)});a.register_read(b|7,this,function(){return this.scratch_register});a.register_write(b|7,this,function(d){this.scratch_register=d})}Da.prototype.get_state=function(){var a=[];a[0]=this.ints;a[1]=this.baud_rate;a[2]=this.line_control;a[3]=this.lsr;a[4]=this.fifo_control;a[5]=this.ier;a[6]=this.iir;a[7]=this.modem_control;a[8]=this.modem_status;a[9]=this.scratch_register;a[10]=this.irq;return a}; +Da.prototype.set_state=function(a){this.ints=a[0];this.baud_rate=a[1];this.line_control=a[2];this.lsr=a[3];this.fifo_control=a[4];this.ier=a[5];this.iir=a[6];this.modem_control=a[7];this.modem_status=a[8];this.scratch_register=a[9];this.irq=a[10]}; +Da.prototype.CheckInterrupt=function(){this.ints&4096&&this.ier&1?(this.iir=12,this.cpu.device_raise_irq(this.irq)):this.ints&16&&this.ier&1?(this.iir=4,this.cpu.device_raise_irq(this.irq)):this.ints&4&&this.ier&2?(this.iir=2,this.cpu.device_raise_irq(this.irq)):this.ints&1&&this.ier&8?(this.iir=0,this.cpu.device_raise_irq(this.irq)):(this.iir=1,this.cpu.device_lower_irq(this.irq))};Da.prototype.ThrowInterrupt=function(a){this.ints|=1<>4;this.modem_status=a;this.modem_status=this.modem_status|c|b};function Ea(a){this.cpu=a;var b=a.io;a.devices.pci.register_device({pci_id:56,pci_space:[134,128,19,113,7,0,128,2,8,0,128,6,0,0,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,1,0,0],pci_bars:[],name:"acpi"});this.timer_imprecision_offset=this.timer_last_value=0;this.status=1;this.pm1_enable=this.pm1_status=0;this.last_timer=this.get_timer(D.microtick());this.gpe=new Uint8Array(4);b.register_read(45056,this,void 0,function(){return this.pm1_status}); +b.register_write(45056,this,void 0,function(c){B(c,4);this.pm1_status&=~c});b.register_read(45058,this,void 0,function(){return this.pm1_enable});b.register_write(45058,this,void 0,function(c){B(c);this.pm1_enable=c});b.register_read(45060,this,void 0,function(){return this.status});b.register_write(45060,this,void 0,function(c){B(c);this.status=c});b.register_read(45064,this,void 0,void 0,function(){return this.get_timer(D.microtick())&16777215});b.register_read(45024,this,function(){return this.gpe[0]}); +b.register_read(45025,this,function(){return this.gpe[1]});b.register_read(45026,this,function(){return this.gpe[2]});b.register_read(45027,this,function(){return this.gpe[3]});b.register_write(45024,this,function(c){B(c);this.gpe[0]=c});b.register_write(45025,this,function(c){B(c);this.gpe[1]=c});b.register_write(45026,this,function(c){B(c);this.gpe[2]=c});b.register_write(45027,this,function(c){B(c);this.gpe[3]=c})} +Ea.prototype.timer=function(a){a=this.get_timer(a);var b=0!==((a^this.last_timer)&8388608);this.pm1_enable&1&&b?(this.pm1_status|=1,this.cpu.device_raise_irq(9)):this.cpu.device_lower_irq(9);this.last_timer=a;return 100}; +Ea.prototype.get_timer=function(a){a=Math.round(3579.545*a);a===this.timer_last_value?3579.545>this.timer_imprecision_offset&&this.timer_imprecision_offset++:this.timer_last_value+this.timer_imprecision_offset<=a&&(this.timer_imprecision_offset=0,this.timer_last_value=a);return this.timer_last_value+this.timer_imprecision_offset};Ea.prototype.get_state=function(){var a=[];a[0]=this.status;a[1]=this.pm1_status;a[2]=this.pm1_enable;a[3]=this.gpe;return a}; +Ea.prototype.set_state=function(a){this.status=a[0];this.pm1_status=a[1];this.pm1_enable=a[2];this.gpe=a[3]};function Fa(a){this.cpu=a;this.timer_divider=this.apic_id=0;this.timer_divider_shift=1;this.timer_current_count=this.timer_initial_count=0;this.next_tick=D.microtick();this.lvt_error=this.lvt_int1=this.lvt_int0=this.lvt_perf_counter=this.lvt_timer=65536;this.icr1=this.icr0=this.tpr=0;this.irr=new Int32Array(8);this.isr=new Int32Array(8);this.tmr=new Int32Array(8);this.spurious_vector=254;this.destination_format=-1;this.read_error=this.error=this.local_destination=0;a.io.mmap_register(4276092928,1048576, +b=>{B(b>>>0);var c=b&3;return this.read32(b&-4)>>8*c&255},(b,c)=>{B(b);B(c)},b=>this.read32(b),(b,c)=>this.write32(b,c))} +Fa.prototype.read32=function(a){a=a-4276092928|0;switch(a){case 32:return this.apic_id;case 48:return 327700;case 128:return this.tpr;case 208:return this.local_destination;case 224:return this.destination_format;case 240:return this.spurious_vector;case 256:case 272:case 288:case 304:case 320:case 336:case 352:case 368:return a=a-256>>4,B(this.isr[a]>>>0,8),this.isr[a];case 384:case 400:case 416:case 432:case 448:case 464:case 480:case 496:return a=a-384>>4,B(this.tmr[a]>>>0,8),this.tmr[a];case 512:case 528:case 544:case 560:case 576:case 592:case 608:case 624:return a= +a-512>>4,B(this.irr[a]>>>0,8),this.irr[a];case 640:return B(this.read_error>>>0,8),this.read_error;case 768:return this.icr0;case 784:return this.icr1;case 800:return this.lvt_timer;case 832:return this.lvt_perf_counter;case 848:return this.lvt_int0;case 864:return this.lvt_int1;case 880:return this.lvt_error;case 992:return this.timer_divider;case 896:return this.timer_initial_count;case 912:return B(this.timer_current_count>>>0,8),this.timer_current_count;default:return B(a),0}}; +Fa.prototype.write32=function(a,b){a=a-4276092928|0;switch(a){case 32:B(b>>>8,8);this.apic_id=b;break;case 48:B(b>>>0,8);break;case 128:this.tpr=b&255;this.check_vector();break;case 176:b=this.highest_isr();-1!==b&&(this.register_clear_bit(this.isr,b),this.register_get_bit(this.tmr,b)&&this.cpu.devices.ioapic.remote_eoi(b),this.check_vector());break;case 208:B(b>>>0,8);this.local_destination=b&4278190080;break;case 224:B(b>>>0,8);this.destination_format=b|16777215;break;case 240:B(b>>>0,8);this.spurious_vector= +b;break;case 640:B(b>>>0,8);this.read_error=this.error;this.error=0;break;case 768:a=b&255;var c=b>>8&7,d=b>>11&1,e=b>>15&1,g=b>>18&3,f=this.icr1>>>24;B(b,8);B(a,2);this.icr0=b&-4097;0===g?this.route(a,c,e,f,d):1===g?this.deliver(a,0,e):2===g&&this.deliver(a,c,e);break;case 784:B(b>>>0,8);this.icr1=b;break;case 800:B(b>>>0,8);this.lvt_timer=b;break;case 832:B(b>>>0,8);this.lvt_perf_counter=b;break;case 848:B(b>>>0,8);this.lvt_int0=b;break;case 864:B(b>>>0,8);this.lvt_int1=b;break;case 880:B(b>>>0, +8);this.lvt_error=b;break;case 992:B(b>>>0,8);this.timer_divider=b;b=b&3|(b&8)>>1;this.timer_divider_shift=7===b?0:b+1;break;case 896:B(b>>>0,8);this.timer_initial_count=b>>>0;this.timer_current_count=b>>>0;this.next_tick=D.microtick();this.timer_active=!0;break;case 912:B(b>>>0,8);break;default:B(a),B(b>>>0,8)}}; +Fa.prototype.timer=function(a){if(0===this.timer_current_count)return 100;const b=1E6/(1<>>0;this.next_tick+=a/b;this.timer_current_count-=a;0>=this.timer_current_count&&(a=this.lvt_timer&393216,131072===a?(this.timer_current_count%=this.timer_initial_count,0>=this.timer_current_count&&(this.timer_current_count+=this.timer_initial_count),0===(this.lvt_timer&65536)&&this.deliver(this.lvt_timer&255,0,!1)):0===a&&(this.timer_current_count=0,0===(this.lvt_timer& +65536)&&this.deliver(this.lvt_timer&255,0,!1)));return Math.max(0,this.timer_current_count/b)};Fa.prototype.route=function(a,b,c){this.deliver(a,b,c)};Fa.prototype.deliver=function(a,b,c){5!==b&&4!==b&&(this.register_get_bit(this.irr,a)?B(a,2):(this.register_set_bit(this.irr,a),c?this.register_set_bit(this.tmr,a):this.register_clear_bit(this.tmr,a),this.check_vector()))};Fa.prototype.highest_irr=function(){return this.register_get_highest_bit(this.irr)};Fa.prototype.highest_isr=function(){return this.register_get_highest_bit(this.isr)}; +Fa.prototype.check_vector=function(){var a=this.highest_irr();-1!==a&&(this.highest_isr()>=a||(a&240)<=(this.tpr&240)||this.cpu.handle_irqs())};Fa.prototype.acknowledge_irq=function(){var a=this.highest_irr();if(-1===a||this.highest_isr()>=a||(a&240)<=(this.tpr&240))return-1;this.register_clear_bit(this.irr,a);this.register_set_bit(this.isr,a);this.check_vector();return a}; +Fa.prototype.get_state=function(){var a=[];a[0]=this.apic_id;a[1]=this.timer_divider;a[2]=this.timer_divider_shift;a[3]=this.timer_initial_count;a[4]=this.timer_current_count;a[5]=this.next_tick;a[6]=this.lvt_timer;a[7]=this.lvt_perf_counter;a[8]=this.lvt_int0;a[9]=this.lvt_int1;a[10]=this.lvt_error;a[11]=this.tpr;a[12]=this.icr0;a[13]=this.icr1;a[14]=this.irr;a[15]=this.isr;a[16]=this.tmr;a[17]=this.spurious_vector;a[18]=this.destination_format;a[19]=this.local_destination;a[20]=this.error;a[21]= +this.read_error;return a}; +Fa.prototype.set_state=function(a){this.apic_id=a[0];this.timer_divider=a[1];this.timer_divider_shift=a[2];this.timer_initial_count=a[3];this.timer_current_count=a[4];this.next_tick=a[5];this.lvt_timer=a[6];this.lvt_perf_counter=a[7];this.lvt_int0=a[8];this.lvt_int1=a[9];this.lvt_error=a[10];this.tpr=a[11];this.icr0=a[12];this.icr1=a[13];this.irr=a[14];this.isr=a[15];this.tmr=a[16];this.spurious_vector=a[17];this.destination_format=a[18];this.local_destination=a[19];this.error=a[20];this.read_error= +a[21]};Fa.prototype.register_get_bit=function(a,b){return a[b>>5]>>(b&31)&1};Fa.prototype.register_set_bit=function(a,b){a[b>>5]|=1<<(b&31)};Fa.prototype.register_clear_bit=function(a,b){a[b>>5]&=~(1<<(b&31))};Fa.prototype.register_get_highest_bit=function(a){for(var b=7;0<=b;b--){var c=a[b];if(c)return k.int_log2(c>>>0)|b<<5}return-1};function Ga(a){this.cpu=a;this.ioredtbl_config=new Int32Array(24);this.ioredtbl_destination=new Int32Array(24);for(var b=0;b{c=c-4273995776|0;if(16<=c&&20>c)return c-=16,B(this.ioregsel),this.read(this.ioregsel)>>8*c&255;B(c>>>0);return 0},c=>{B(c>>>0)},c=>{c=c-4273995776|0;if(0===c)return this.ioregsel;if(16===c)return this.read(this.ioregsel); +B(c>>>0);return 0},(c,d)=>{c=c-4273995776|0;0===c?this.ioregsel=d:16===c?this.write(this.ioregsel,d):(B(c>>>0),B(d>>>0,8))})}Ga.prototype.remote_eoi=function(a){for(var b=0;24>b;b++){var c=this.ioredtbl_config[b];(c&255)===a&&c&16384&&(B(b),this.ioredtbl_config[b]&=-16385,this.check_irq(b))}}; +Ga.prototype.check_irq=function(a){var b=1<>8&7,e=this.ioredtbl_destination[a]>>>24;if(0===(c&32768))this.irr&=~b;else if(this.ioredtbl_config[a]|=16384,c&16384)return;0!==d&&1!==d||this.cpu.devices.apic.route(c&255,d,32768===(c&32768),e,c>>11&1);this.ioredtbl_config[a]&=-4097}}}; +Ga.prototype.set_irq=function(a){if(!(24<=a)){var b=1<a){var b=a-16>>1;a=a&1?this.ioredtbl_destination[b]:this.ioredtbl_config[b];B(b);B(a,8);return a}B(a);return 0}; +Ga.prototype.write=function(a,b){if(0===a)this.ioapic_id=b>>>24&15;else if(1!==a&&2!==a)if(16<=a&&64>a){var c=a-16>>1;a&1?(this.ioredtbl_destination[c]=b&4278190080,B(b>>>0,8),B(c),B(b>>>24,2)):(this.ioredtbl_config[c]=b&110591|this.ioredtbl_config[c]&-110592,a=b&255,B(b>>>0,8),B(c),B(a,2),this.check_irq(c))}else B(a),B(b>>>0,8)}; +Ga.prototype.get_state=function(){var a=[];a[0]=this.ioredtbl_config;a[1]=this.ioredtbl_destination;a[2]=this.ioregsel;a[3]=this.ioapic_id;a[4]=this.irr;a[5]=this.irq_value;return a};Ga.prototype.set_state=function(a){this.ioredtbl_config=a[0];this.ioredtbl_destination=a[1];this.ioregsel=a[2];this.ioapic_id=a[3];this.irr=a[4];this.irq_value=a[5]};function Ha(a){this.message=a}Ha.prototype=Error();const Ka={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array}; +function La(a,b){if("object"!==typeof a||null===a)return a;if(Array.isArray(a))return a.map(e=>La(e,b));a.constructor===Object&&console.log(a);if(a.BYTES_PER_ELEMENT){var c=new Uint8Array(a.buffer,a.byteOffset,a.length*a.BYTES_PER_ELEMENT);return{__state_type__:a.constructor.name.replace("bound ",""),buffer_id:b.push(c)-1}}a=a.get_state();c=[];for(var d=0;dr)throw new Ha("Invalid length: "+r);p=new Int32Array(p.buffer,p.byteOffset,4);if(-2039052682!==p[0])throw new Ha("Invalid header: "+B(p[0]>>>0));if(6!==p[1])throw new Ha("Version mismatch: dump="+p[1]+" we=6");if(q&&p[2]!==r)throw new Ha("Length doesn't match header: real="+r+" header="+p[2]);return p[3]}function c(p){p=(new TextDecoder).decode(p);return JSON.parse(p)}a=new Uint8Array(a);if(4247762216===(new Uint32Array(a.buffer, +0,1))[0]){var d=this.zstd_create_ctx(a.length);(new Uint8Array(this.wasm_memory.buffer,this.zstd_get_src_ptr(d),a.length)).set(a);var e=this.zstd_read(d,16),g=new Uint8Array(this.wasm_memory.buffer,e,16),f=b(g,!1);this.zstd_read_free(e,16);e=this.zstd_read(d,f);g=new Uint8Array(this.wasm_memory.buffer,e,f);g=c(g);this.zstd_read_free(e,f);e=g.state;var h=g.buffer_infos;g=[];f=16+f;for(var l of h){h=(f+3&-4)-f;if(1048576d||d+12>=a.length)throw new Ha("Invalid info block length: "+d);l=a.subarray(16,16+d);e=c(l);l=e.state;e= +e.buffer_infos;let p=16+d;p=p+3&-4;d=e.map(q=>{const r=p+q.offset;return a.buffer.slice(r,r+q.length)});l=Ma(l,d);this.set_state(l)}};function Na(a,b,c){a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]&&(a[0]=c[0],a[1]=c[1],a[2]=c[2],a[3]=c[3],a[4]=c[4],a[5]=c[5]);a[6]===b[0]&&a[7]===b[1]&&a[8]===b[2]&&a[9]===b[3]&&a[10]===b[4]&&a[11]===b[5]&&(a[6]=c[0],a[7]=c[1],a[8]=c[2],a[9]=c[3],a[10]=c[4],a[11]=c[5]);var d=a[12]<<8|a[13];if(2048===d){if(a=a.subarray(14),4===a[0]>>4&&17===a[9]){a=a.subarray(20);d=a[0]<<8|a[1];var e=a[2]<<8|a[3];B(a[6]<<8|a[7],4);if(67===d||67===e)if(d=a.subarray(8),e=d[236]<<24|d[237]<< +16|d[238]<<8|d[239],1669485411!==e)B(e,8);else for(d[28]===b[0]&&d[29]===b[1]&&d[30]===b[2]&&d[31]===b[3]&&d[32]===b[4]&&d[33]===b[5]&&(d[28]=c[0],d[29]=c[1],d[30]=c[2],d[31]=c[3],d[32]=c[4],d[33]=c[5],a[6]=a[7]=0),e=240;e>8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,244,26,0,17,0,0,184,254,0,0,0,0,0,0,0,0,0,1,0,0];this.pci_id=(0===this.id?5:7+this.id)<<3;this.pci_bars= +[{size:32}];this.imr=this.isr=0;this.cr=1;this.tpsr=this.tcnt=this.rcnt=this.dcfg=0;this.memory=new Uint8Array(32768);this.txcr=this.rxcr=0;this.tsr=1;this.mac=new Uint8Array([0,34,21,255*Math.random()|0,255*Math.random()|0,255*Math.random()|0]);this.bus.send("net"+this.id+"-mac",Pa(this.mac));this.mar=Uint8Array.of(255,255,255,255,255,255,255,255);this.mac_address_in_state=null;for(b=0;6>b;b++)this.memory[b<<1]=this.memory[b<<1|1]=this.mac[b];this.memory[28]=this.memory[29]=87;this.memory[30]=this.memory[31]= +87;ta("Mac: "+Pa(this.mac),1048576);this.rsar=0;this.pstart=64;this.pstop=128;this.boundary=this.curpg=76;b=a.io;b.register_read(this.port|0,this,function(){return this.cr});b.register_write(this.port|0,this,function(g){this.cr=g;B(g,2);B(this.txcr,2);this.cr&1||(g&24&&0===this.rcnt&&this.do_interrupt(64),g&4&&(g=this.tpsr<<8,g=this.memory.subarray(g,g+this.tcnt),this.mac_address_in_state&&(g=new Uint8Array(g),Na(g,this.mac_address_in_state,this.mac)),this.bus.send("net"+this.id+"-send",g),this.bus.send("eth-transmit-end", +[g.length]),this.cr&=-5,this.do_interrupt(2),B(g.byteLength)))});b.register_read(this.port|13,this,function(){return 1===this.get_page()?this.mar[5]:0});b.register_read(this.port|14,this,function(){return 1===this.get_page()?this.mar[6]:0},function(){this.get_page();return 0});b.register_read(this.port|15,this,function(){return 1===this.get_page()?this.mar[7]:0});b.register_read(this.port|31,this,function(){this.get_page();this.do_interrupt(128);return 0});b.register_write(this.port|31,this,function(g){this.get_page(); +B(g,2)});b.register_read(this.port|1,this,function(){var g=this.get_page();return 0===g?this.pstart:1===g?this.mac[0]:2===g?this.pstart:0});b.register_write(this.port|1,this,function(g){var f=this.get_page();0===f?(B(g,2),this.pstart=g):1===f?(B(g),this.mac[0]=g):B(g)});b.register_read(this.port|2,this,function(){var g=this.get_page();return 0===g?this.pstop:1===g?this.mac[1]:2===g?this.pstop:0});b.register_write(this.port|2,this,function(g){var f=this.get_page();0===f?(B(g,2),g>this.memory.length>> +8&&(g=this.memory.length>>8,B(g)),this.pstop=g):1===f?(B(g),this.mac[1]=g):B(g)});b.register_read(this.port|7,this,function(){var g=this.get_page();return 0===g?(B(this.isr,2),this.isr):1===g?(B(this.curpg,2),this.curpg):0});b.register_write(this.port|7,this,function(g){var f=this.get_page();0===f?(B(g,2),this.isr&=~g,this.update_irq()):1===f&&(B(g,2),this.curpg=g)});b.register_write(this.port|13,this,function(g){0===this.get_page()&&(this.txcr=g);B(g,2)});b.register_write(this.port|14,this,function(g){0=== +this.get_page()?(B(g,2),this.dcfg=g):B(g,2)});b.register_read(this.port|10,this,function(){var g=this.get_page();return 0===g?80:1===g?this.mar[2]:0});b.register_write(this.port|10,this,function(g){0===this.get_page()?(B(g,2),this.rcnt=this.rcnt&65280|g&255):B(g,2)});b.register_read(this.port|11,this,function(){var g=this.get_page();return 0===g?67:1===g?this.mar[3]:0});b.register_write(this.port|11,this,function(g){0===this.get_page()?(B(g,2),this.rcnt=this.rcnt&255|g<<8&65280):B(g,2)});b.register_read(this.port| +8,this,function(){var g=this.get_page();return 0===g?this.rsar&255:1===g?this.mar[0]:0});b.register_write(this.port|8,this,function(g){0===this.get_page()?(B(g,2),this.rsar=this.rsar&65280|g&255):B(g,2)});b.register_read(this.port|9,this,function(){var g=this.get_page();return 0===g?this.rsar>>8&255:1===g?this.mar[1]:0});b.register_write(this.port|9,this,function(g){0===this.get_page()?(B(g,2),this.rsar=this.rsar&255|g<<8&65280):B(g,2)});b.register_write(this.port|15,this,function(g){0===this.get_page()? +(B(g,2),B(this.isr,2),this.imr=g,this.update_irq()):B(g,2)});b.register_read(this.port|3,this,function(){var g=this.get_page();return 0===g?(B(this.boundary,2),this.boundary):1===g?this.mac[2]:0});b.register_write(this.port|3,this,function(g){var f=this.get_page();0===f?(B(g,2),this.boundary=g):1===f?(B(g),this.mac[2]=g):B(g)});b.register_read(this.port|4,this,function(){var g=this.get_page();return 0===g?this.tsr:1===g?this.mac[3]:0});b.register_write(this.port|4,this,function(g){var f=this.get_page(); +0===f?(B(g,2),this.tpsr=g):1===f?(B(g),this.mac[3]=g):B(g)});b.register_read(this.port|5,this,function(){var g=this.get_page();return 0===g?0:1===g?this.mac[4]:0});b.register_write(this.port|5,this,function(g){var f=this.get_page();0===f?(B(g,2),this.tcnt=this.tcnt&-256|g):1===f?(B(g),this.mac[4]=g):B(g)});b.register_read(this.port|6,this,function(){var g=this.get_page();return 0===g?0:1===g?this.mac[5]:0});b.register_write(this.port|6,this,function(g){var f=this.get_page();0===f?(B(g,2),this.tcnt= +this.tcnt&255|g<<8):1===f?(B(g),this.mac[5]=g):B(g)});b.register_read(this.port|12,this,function(){var g=this.get_page();return 0===g?9:1===g?this.mar[4]:0});b.register_write(this.port|12,this,function(g){0===this.get_page()?(B(g,2),this.rxcr=g):B(g)});b.register_read(this.port|16,this,this.data_port_read8,this.data_port_read16,this.data_port_read32);b.register_write(this.port|16,this,this.data_port_write16,this.data_port_write16,this.data_port_write32);a.devices.pci.register_device(this)} +Qa.prototype.get_state=function(){var a=[];a[0]=this.isr;a[1]=this.imr;a[2]=this.cr;a[3]=this.dcfg;a[4]=this.rcnt;a[5]=this.tcnt;a[6]=this.tpsr;a[7]=this.rsar;a[8]=this.pstart;a[9]=this.curpg;a[10]=this.boundary;a[11]=this.pstop;a[12]=this.rxcr;a[13]=this.txcr;a[14]=this.tsr;a[15]=this.mac;a[16]=this.memory;return a}; +Qa.prototype.set_state=function(a){this.isr=a[0];this.imr=a[1];this.cr=a[2];this.dcfg=a[3];this.rcnt=a[4];this.tcnt=a[5];this.tpsr=a[6];this.rsar=a[7];this.pstart=a[8];this.curpg=a[9];this.boundary=a[10];this.pstop=a[11];this.rxcr=a[12];this.txcr=a[13];this.tsr=a[14];this.preserve_mac_from_state_image?(this.mac=a[15],this.memory=a[16]):this.mac_address_translation&&(this.mac_address_in_state=a[15],this.memory=a[16],Pa(this.mac_address_in_state),Pa(this.mac));this.bus.send("net"+this.id+"-mac",Pa(this.mac))}; +Qa.prototype.do_interrupt=function(a){B(a,2);this.isr|=a;this.update_irq()};Qa.prototype.update_irq=function(){this.imr&this.isr?this.pci.raise_irq(this.pci_id):this.pci.lower_irq(this.pci_id)};Qa.prototype.data_port_write=function(a){if(16>=this.rsar||16384<=this.rsar&&32768>this.rsar)this.memory[this.rsar]=a;this.rsar++;this.rcnt--;this.rsar>=this.pstop<<8&&(this.rsar+=this.pstart-this.pstop<<8);0===this.rcnt&&this.do_interrupt(64)}; +Qa.prototype.data_port_write16=function(a){this.data_port_write(a);this.dcfg&1&&this.data_port_write(a>>8)};Qa.prototype.data_port_write32=function(a){this.data_port_write(a);this.data_port_write(a>>8);this.data_port_write(a>>16);this.data_port_write(a>>24)};Qa.prototype.data_port_read=function(){let a=0;32768>this.rsar&&(a=this.memory[this.rsar]);this.rsar++;this.rcnt--;this.rsar>=this.pstop<<8&&(this.rsar+=this.pstart-this.pstop<<8);0===this.rcnt&&this.do_interrupt(64);return a}; +Qa.prototype.data_port_read8=function(){return this.data_port_read16()&255};Qa.prototype.data_port_read16=function(){return this.dcfg&1?this.data_port_read()|this.data_port_read()<<8:this.data_port_read()};Qa.prototype.data_port_read32=function(){return this.data_port_read()|this.data_port_read()<<8|this.data_port_read()<<16|this.data_port_read()<<24}; +Qa.prototype.receive=function(a){if(!(this.cr&1)&&(this.bus.send("eth-receive-end",[a.length]),this.rxcr&16||this.rxcr&4&&255===a[0]&&255===a[1]&&255===a[2]&&255===a[3]&&255===a[4]&&255===a[5]||!(this.rxcr&8&&1===(a[0]&1)||a[0]!==this.mac[0]||a[1]!==this.mac[1]||a[2]!==this.mac[2]||a[3]!==this.mac[3]||a[4]!==this.mac[4]||a[5]!==this.mac[5]))){this.mac_address_in_state&&(a=new Uint8Array(a),Na(a,this.mac,this.mac_address_in_state));var b=this.curpg<<8,c=Math.max(60,a.length)+4,d=b+4,e=this.curpg+1+ +(c>>8),g=b+c,f=1+(c>>8),h=this.boundary>this.curpg?this.boundary-this.curpg:this.pstop-this.curpg+this.boundary-this.pstart;hthis.pstop<<8?(g=(this.pstop<<8)-d,this.memory.set(a.subarray(0,g),d),this.memory.set(a.subarray(g),this.pstart<<8),B(g)):(this.memory.set(a,d),60>a.length&&this.memory.fill(0,d+a.length,d+60)),e>=this.pstop&&(e+=this.pstart-this.pstop),this.memory[b]=1,this.memory[b+1]=e,this.memory[b+ +2]=c,this.memory[b+3]=c>>8,this.curpg=e,B(b),B(c),B(e),this.do_interrupt(1))}};Qa.prototype.get_page=function(){return this.cr>>6&3};var Ra=new Uint8Array(256),Sa=[],Ta=[],Ua=[],Va=new Uint8Array(256),Wa=[]; +function O(a,b){this.cpu=a;this.bus=b;this.write_buffer=new la(64);this.read_buffer=new la(64);this.mixer_current_address=this.command_size=this.command=this.read_buffer_lastvalue=0;this.mixer_registers=new Uint8Array(256);this.mixer_reset();this.dummy_speaker_enabled=!1;this.test_register=0;this.dsp_signed=this.dsp_16bit=this.dsp_stereo=this.dsp_highspeed=!1;this.dac_buffers=[new oa(65536),new oa(65536)];this.dma=a.devices.dma;this.dma_channel=this.dma_irq=this.dma_bytes_block=this.dma_bytes_left= +this.dma_bytes_count=this.dma_sample_count=0;this.dma_channel_8bit=1;this.dma_channel_16bit=5;this.dma_autoinit=!1;this.dma_buffer=new ArrayBuffer(65536);this.dma_buffer_int8=new Int8Array(this.dma_buffer);this.dma_buffer_uint8=new Uint8Array(this.dma_buffer);this.dma_buffer_int16=new Int16Array(this.dma_buffer);this.dma_buffer_uint16=new Uint16Array(this.dma_buffer);this.dma_syncbuffer=new k.SyncBuffer(this.dma_buffer);this.dma_paused=this.dma_waiting_transfer=!1;this.sampling_rate=22050;b.send("dac-tell-sampling-rate", +this.sampling_rate);this.bytes_per_sample=1;this.e2_value=170;this.e2_count=0;this.asp_registers=new Uint8Array(256);this.mpu_read_buffer=new la(64);this.fm_current_address1=this.fm_current_address0=this.mpu_read_buffer_lastvalue=0;this.fm_waveform_select_enable=!1;this.irq=5;this.irq_triggered=new Uint8Array(16);a.io.register_read_consecutive(544,this,this.port2x0_read,this.port2x1_read,this.port2x2_read,this.port2x3_read);a.io.register_read_consecutive(904,this,this.port2x0_read,this.port2x1_read); +a.io.register_read_consecutive(548,this,this.port2x4_read,this.port2x5_read);a.io.register_read(550,this,this.port2x6_read);a.io.register_read(551,this,this.port2x7_read);a.io.register_read(552,this,this.port2x8_read);a.io.register_read(553,this,this.port2x9_read);a.io.register_read(554,this,this.port2xA_read);a.io.register_read(555,this,this.port2xB_read);a.io.register_read(556,this,this.port2xC_read);a.io.register_read(557,this,this.port2xD_read);a.io.register_read_consecutive(558,this,this.port2xE_read, +this.port2xF_read);a.io.register_write_consecutive(544,this,this.port2x0_write,this.port2x1_write,this.port2x2_write,this.port2x3_write);a.io.register_write_consecutive(904,this,this.port2x0_write,this.port2x1_write);a.io.register_write_consecutive(548,this,this.port2x4_write,this.port2x5_write);a.io.register_write(550,this,this.port2x6_write);a.io.register_write(551,this,this.port2x7_write);a.io.register_write_consecutive(552,this,this.port2x8_write,this.port2x9_write);a.io.register_write(554,this, +this.port2xA_write);a.io.register_write(555,this,this.port2xB_write);a.io.register_write(556,this,this.port2xC_write);a.io.register_write(557,this,this.port2xD_write);a.io.register_write(558,this,this.port2xE_write);a.io.register_write(559,this,this.port2xF_write);a.io.register_read_consecutive(816,this,this.port3x0_read,this.port3x1_read);a.io.register_write_consecutive(816,this,this.port3x0_write,this.port3x1_write);this.dma.on_unmask(this.dma_on_unmask,this);b.register("dac-request-data",function(){this.dac_handle_request()}, +this);b.register("speaker-has-initialized",function(){this.mixer_reset()},this);b.send("speaker-confirm-initialized");this.dsp_reset()} +O.prototype.dsp_reset=function(){this.write_buffer.clear();this.read_buffer.clear();this.command_size=this.command=0;this.dummy_speaker_enabled=!1;this.test_register=0;this.dsp_signed=this.dsp_16bit=this.dsp_stereo=this.dsp_highspeed=!1;this.dac_buffers[0].clear();this.dac_buffers[1].clear();this.dma_channel=this.dma_irq=this.dma_bytes_block=this.dma_bytes_left=this.dma_bytes_count=this.dma_sample_count=0;this.dma_autoinit=!1;this.dma_buffer_uint8.fill(0);this.dma_paused=this.dma_waiting_transfer= +!1;this.e2_value=170;this.e2_count=0;this.sampling_rate=22050;this.bytes_per_sample=1;this.lower_irq(1);this.irq_triggered.fill(0);this.asp_registers.fill(0);this.asp_registers[5]=1;this.asp_registers[9]=248}; +O.prototype.get_state=function(){var a=[];a[2]=this.read_buffer_lastvalue;a[3]=this.command;a[4]=this.command_size;a[5]=this.mixer_current_address;a[6]=this.mixer_registers;a[7]=this.dummy_speaker_enabled;a[8]=this.test_register;a[9]=this.dsp_highspeed;a[10]=this.dsp_stereo;a[11]=this.dsp_16bit;a[12]=this.dsp_signed;a[15]=this.dma_sample_count;a[16]=this.dma_bytes_count;a[17]=this.dma_bytes_left;a[18]=this.dma_bytes_block;a[19]=this.dma_irq;a[20]=this.dma_channel;a[21]=this.dma_channel_8bit;a[22]= +this.dma_channel_16bit;a[23]=this.dma_autoinit;a[24]=this.dma_buffer_uint8;a[25]=this.dma_waiting_transfer;a[26]=this.dma_paused;a[27]=this.sampling_rate;a[28]=this.bytes_per_sample;a[29]=this.e2_value;a[30]=this.e2_count;a[31]=this.asp_registers;a[33]=this.mpu_read_buffer_last_value;a[34]=this.irq;a[35]=this.irq_triggered;return a}; +O.prototype.set_state=function(a){this.read_buffer_lastvalue=a[2];this.command=a[3];this.command_size=a[4];this.mixer_current_address=a[5];this.mixer_registers=a[6];this.mixer_full_update();this.dummy_speaker_enabled=a[7];this.test_register=a[8];this.dsp_highspeed=a[9];this.dsp_stereo=a[10];this.dsp_16bit=a[11];this.dsp_signed=a[12];this.dma_sample_count=a[15];this.dma_bytes_count=a[16];this.dma_bytes_left=a[17];this.dma_bytes_block=a[18];this.dma_irq=a[19];this.dma_channel=a[20];this.dma_channel_8bit= +a[21];this.dma_channel_16bit=a[22];this.dma_autoinit=a[23];this.dma_buffer_uint8=a[24];this.dma_waiting_transfer=a[25];this.dma_paused=a[26];this.sampling_rate=a[27];this.bytes_per_sample=a[28];this.e2_value=a[29];this.e2_count=a[30];this.asp_registers=a[31];this.mpu_read_buffer_last_value=a[33];this.irq=a[34];this.irq_triggered=a[35];this.dma_buffer=this.dma_buffer_uint8.buffer;this.dma_buffer_int8=new Int8Array(this.dma_buffer);this.dma_buffer_int16=new Int16Array(this.dma_buffer);this.dma_buffer_uint16= +new Uint16Array(this.dma_buffer);this.dma_syncbuffer=new k.SyncBuffer(this.dma_buffer);this.dma_paused?this.bus.send("dac-disable"):this.bus.send("dac-enable")};O.prototype.port2x0_read=function(){return 255};O.prototype.port2x1_read=function(){return 255};O.prototype.port2x2_read=function(){return 255};O.prototype.port2x3_read=function(){return 255};O.prototype.port2x4_read=function(){return this.mixer_current_address};O.prototype.port2x5_read=function(){return this.mixer_read(this.mixer_current_address)}; +O.prototype.port2x6_read=function(){return 255};O.prototype.port2x7_read=function(){return 255};O.prototype.port2x8_read=function(){return 255};O.prototype.port2x9_read=function(){return 255};O.prototype.port2xA_read=function(){this.read_buffer.length&&(this.read_buffer_lastvalue=this.read_buffer.shift());B(this.read_buffer_lastvalue);String.fromCharCode(this.read_buffer_lastvalue);return this.read_buffer_lastvalue};O.prototype.port2xB_read=function(){return 255};O.prototype.port2xC_read=function(){return 127}; +O.prototype.port2xD_read=function(){return 255};O.prototype.port2xE_read=function(){this.irq_triggered[1]&&this.lower_irq(1);return(this.read_buffer.length&&!this.dsp_highspeed)<<7|127};O.prototype.port2xF_read=function(){this.lower_irq(2);return 0};O.prototype.port2x0_write=function(a){B(a);this.fm_current_address0=0};O.prototype.port2x1_write=function(a){B(a);var b=Wa[this.fm_current_address0];b||(b=this.fm_default_write);b.call(this,a,0,this.fm_current_address0)}; +O.prototype.port2x2_write=function(a){B(a);this.fm_current_address1=0};O.prototype.port2x3_write=function(a){B(a);var b=Wa[this.fm_current_address1];b||(b=this.fm_default_write);b.call(this,a,1,this.fm_current_address1)};O.prototype.port2x4_write=function(a){B(a);this.mixer_current_address=a};O.prototype.port2x5_write=function(a){B(a);this.mixer_write(this.mixer_current_address,a)}; +O.prototype.port2x6_write=function(a){B(a);this.dsp_highspeed?this.dsp_highspeed=!1:a&&this.dsp_reset();this.read_buffer.clear();this.read_buffer.push(170)};O.prototype.port2x7_write=function(){};O.prototype.port2x8_write=function(){};O.prototype.port2x9_write=function(){};O.prototype.port2xA_write=function(){};O.prototype.port2xB_write=function(){}; +O.prototype.port2xC_write=function(a){0===this.command?(B(a),this.command=a,this.write_buffer.clear(),this.command_size=Ra[a]):(B(a),this.write_buffer.push(a));this.write_buffer.length>=this.command_size&&this.command_do()};O.prototype.port2xD_write=function(){};O.prototype.port2xE_write=function(){};O.prototype.port2xF_write=function(){}; +O.prototype.port3x0_read=function(){this.mpu_read_buffer.length&&(this.mpu_read_buffer_lastvalue=this.mpu_read_buffer.shift());B(this.mpu_read_buffer_lastvalue);return this.mpu_read_buffer_lastvalue};O.prototype.port3x0_write=function(a){B(a)};O.prototype.port3x1_read=function(){return 0|128*!this.mpu_read_buffer.length};O.prototype.port3x1_write=function(a){B(a);255===a&&(this.mpu_read_buffer.clear(),this.mpu_read_buffer.push(254))}; +O.prototype.command_do=function(){var a=Sa[this.command];a||(a=this.dsp_default_handler);a.call(this);this.command_size=this.command=0;this.write_buffer.clear()};O.prototype.dsp_default_handler=function(){B(this.command)};function U(a,b,c){c||(c=O.prototype.dsp_default_handler);for(var d=0;dc;c++)b.push(a+c);return b}U([14],2,function(){this.asp_registers[this.write_buffer.shift()]=this.write_buffer.shift()}); +U([15],1,function(){this.read_buffer.clear();this.read_buffer.push(this.asp_registers[this.write_buffer.shift()])});U([16],1,function(){var a=this.write_buffer.shift();a=Ya(a/127.5+-1,-1,1);this.dac_buffers[0].push(a);this.dac_buffers[1].push(a);this.bus.send("dac-enable")});U([20,21],2,function(){this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dsp_highspeed=this.dsp_16bit=this.dsp_signed=this.dma_autoinit=!1;this.dma_transfer_size_set();this.dma_transfer_start()});U([22],2);U([23],2); +U([28],0,function(){this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dma_autoinit=!0;this.dsp_highspeed=this.dsp_16bit=this.dsp_signed=!1;this.dma_transfer_start()});U([31],0);U([32],0,function(){this.read_buffer.clear();this.read_buffer.push(127)});U([36],2);U([44],0);U([48],0);U([49],0);U([52],0);U([53],0);U([54],0);U([55],0);U([56],0);U([64],1,function(){this.sampling_rate_change(1E6/(256-this.write_buffer.shift())/this.get_channel_count())}); +U([65,66],2,function(){this.sampling_rate_change(this.write_buffer.shift()<<8|this.write_buffer.shift())});U([72],2,function(){this.dma_transfer_size_set()});U([116],2);U([117],2);U([118],2);U([119],2);U([125],0);U([127],0);U([128],2);U([144],0,function(){this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dma_autoinit=!0;this.dsp_signed=!1;this.dsp_highspeed=!0;this.dsp_16bit=!1;this.dma_transfer_start()});U([145],0);U([152],0);U([153],0);U([160],0);U([168],0); +U(Xa(176),3,function(){if(this.command&8)this.dsp_default_handler();else{var a=this.write_buffer.shift();this.dma_irq=2;this.dma_channel=this.dma_channel_16bit;this.dma_autoinit=!!(this.command&4);this.dsp_signed=!!(a&16);this.dsp_stereo=!!(a&32);this.dsp_16bit=!0;this.dma_transfer_size_set();this.dma_transfer_start()}}); +U(Xa(192),3,function(){if(this.command&8)this.dsp_default_handler();else{var a=this.write_buffer.shift();this.dma_irq=1;this.dma_channel=this.dma_channel_8bit;this.dma_autoinit=!!(this.command&4);this.dsp_signed=!!(a&16);this.dsp_stereo=!!(a&32);this.dsp_16bit=!1;this.dma_transfer_size_set();this.dma_transfer_start()}});U([208],0,function(){this.dma_paused=!0;this.bus.send("dac-disable")});U([209],0,function(){this.dummy_speaker_enabled=!0});U([211],0,function(){this.dummy_speaker_enabled=!1}); +U([212],0,function(){this.dma_paused=!1;this.bus.send("dac-enable")});U([213],0,function(){this.dma_paused=!0;this.bus.send("dac-disable")});U([214],0,function(){this.dma_paused=!1;this.bus.send("dac-enable")});U([216],0,function(){this.read_buffer.clear();this.read_buffer.push(255*this.dummy_speaker_enabled)});U([217,218],0,function(){this.dma_autoinit=!1});U([224],1,function(){this.read_buffer.clear();this.read_buffer.push(~this.write_buffer.shift())}); +U([225],0,function(){this.read_buffer.clear();this.read_buffer.push(4);this.read_buffer.push(5)});U([226],1);U([227],0,function(){this.read_buffer.clear();for(var a=0;44>a;a++)this.read_buffer.push("COPYRIGHT (C) CREATIVE TECHNOLOGY LTD, 1992.".charCodeAt(a));this.read_buffer.push(0)});U([228],1,function(){this.test_register=this.write_buffer.shift()});U([232],0,function(){this.read_buffer.clear();this.read_buffer.push(this.test_register)});U([242,243],0,function(){this.raise_irq()});var Za=new Uint8Array(256); +Za[14]=255;Za[15]=7;Za[55]=56;U([249],1,function(){var a=this.write_buffer.shift();this.read_buffer.clear();this.read_buffer.push(Za[a])});O.prototype.mixer_read=function(a){var b=Ta[a];b?b=b.call(this):(b=this.mixer_registers[a],B(a),B(b));return b};O.prototype.mixer_write=function(a,b){var c=Ua[a];c?c.call(this,b):(B(a),B(b))};O.prototype.mixer_default_read=function(){B(this.mixer_current_address);return this.mixer_registers[this.mixer_current_address]}; +O.prototype.mixer_default_write=function(a){B(this.mixer_current_address);B(a);this.mixer_registers[this.mixer_current_address]=a}; +O.prototype.mixer_reset=function(){this.mixer_registers[4]=204;this.mixer_registers[34]=204;this.mixer_registers[38]=204;this.mixer_registers[40]=0;this.mixer_registers[46]=0;this.mixer_registers[10]=0;this.mixer_registers[48]=192;this.mixer_registers[49]=192;this.mixer_registers[50]=192;this.mixer_registers[51]=192;this.mixer_registers[52]=192;this.mixer_registers[53]=192;this.mixer_registers[54]=0;this.mixer_registers[55]=0;this.mixer_registers[56]=0;this.mixer_registers[57]=0;this.mixer_registers[59]= +0;this.mixer_registers[60]=31;this.mixer_registers[61]=21;this.mixer_registers[62]=11;this.mixer_registers[63]=0;this.mixer_registers[64]=0;this.mixer_registers[65]=0;this.mixer_registers[66]=0;this.mixer_registers[67]=0;this.mixer_registers[68]=128;this.mixer_registers[69]=128;this.mixer_registers[70]=128;this.mixer_registers[71]=128;this.mixer_full_update()};O.prototype.mixer_full_update=function(){for(var a=1;a>>4};Ua[a]=function(d){this.mixer_registers[a]=d;var e=d<<4&240|this.mixer_registers[c]&15;this.mixer_write(b,d&240|this.mixer_registers[b]&15);this.mixer_write(c,e)}} +function cb(a,b,c){Ta[a]=O.prototype.mixer_default_read;Ua[a]=function(d){this.mixer_registers[a]=d;this.bus.send("mixer-volume",[b,c,(d>>>2)-62])}}$a(0,function(){this.mixer_reset();return 0});ab(0);bb(4,50,51);bb(34,48,49);bb(38,52,53);bb(40,54,55);bb(46,56,57);cb(48,0,0);cb(49,0,1);cb(50,2,0);cb(51,2,1);$a(59);ab(59,function(a){this.mixer_registers[59]=a;this.bus.send("mixer-volume",[1,2,6*(a>>>6)-18])});$a(65); +ab(65,function(a){this.mixer_registers[65]=a;this.bus.send("mixer-gain-left",6*(a>>>6))});$a(66);ab(66,function(a){this.mixer_registers[66]=a;this.bus.send("mixer-gain-right",6*(a>>>6))});$a(68);ab(68,function(a){this.mixer_registers[68]=a;a>>>=3;this.bus.send("mixer-treble-left",a-(16>a?14:16))});$a(69);ab(69,function(a){this.mixer_registers[69]=a;a>>>=3;this.bus.send("mixer-treble-right",a-(16>a?14:16))});$a(70); +ab(70,function(a){this.mixer_registers[70]=a;a>>>=3;this.bus.send("mixer-bass-right",a-(16>a?14:16))});$a(71);ab(71,function(a){this.mixer_registers[71]=a;a>>>=3;this.bus.send("mixer-bass-right",a-(16>a?14:16))});$a(128,function(){switch(this.irq){case 2:return 1;case 5:return 2;case 7:return 4;case 10:return 8;default:return 0}});ab(128,function(a){a&1&&(this.irq=2);a&2&&(this.irq=5);a&4&&(this.irq=7);a&8&&(this.irq=10)}); +$a(129,function(){var a=0;switch(this.dma_channel_8bit){case 0:a|=1;break;case 1:a|=2;break;case 3:a|=8}switch(this.dma_channel_16bit){case 5:a|=32;break;case 6:a|=64;break;case 7:a|=128}return a});ab(129,function(a){a&1&&(this.dma_channel_8bit=0);a&2&&(this.dma_channel_8bit=1);a&8&&(this.dma_channel_8bit=3);a&32&&(this.dma_channel_16bit=5);a&64&&(this.dma_channel_16bit=6);a&128&&(this.dma_channel_16bit=7)});$a(130,function(){for(var a=32,b=0;16>b;b++)a|=b*this.irq_triggered[b];return a}); +O.prototype.fm_default_write=function(a,b,c){B(c);B(a)};function db(a,b){b||(b=O.prototype.fm_default_write);for(var c=0;c>2&-4,32),this.dma_bytes_block);this.dma_waiting_transfer=!0;this.dma.channel_mask[this.dma_channel]||this.dma_on_unmask(this.dma_channel)}; +O.prototype.dma_on_unmask=function(a){a===this.dma_channel&&this.dma_waiting_transfer&&(this.dma_waiting_transfer=!1,this.dma_bytes_left=this.dma_bytes_count,this.dma_paused=!1,this.bus.send("dac-enable"))}; +O.prototype.dma_transfer_next=function(){var a=Math.min(this.dma_bytes_left,this.dma_bytes_block),b=Math.floor(a/this.bytes_per_sample);this.dma.do_write(this.dma_syncbuffer,0,a,this.dma_channel,c=>{c||(this.dma_to_dac(b),this.dma_bytes_left-=a,this.dma_bytes_left||(this.raise_irq(this.dma_irq),this.dma_autoinit&&(this.dma_bytes_left=this.dma_bytes_count)))})}; +O.prototype.dma_to_dac=function(a){var b=this.dsp_16bit?32767.5:127.5,c=this.dsp_signed?0:-1,d=this.dsp_stereo?1:2;var e=this.dsp_16bit?this.dsp_signed?this.dma_buffer_int16:this.dma_buffer_uint16:this.dsp_signed?this.dma_buffer_int8:this.dma_buffer_uint8;for(var g=0,f=0;fc)*c+(b<=a&&a<=c)*a};function da(a,b){this.cpu=a;this.pci=a.devices.pci;this.device_id=b.device_id;this.pci_space=[244,26,b.device_id&255,b.device_id>>8,7,5,16,0,1,0,2,0,0,0,0,0,1,168,0,0,0,16,191,254,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,244,26,b.subsystem_device_id&255,b.subsystem_device_id>>8,0,0,0,0,64,0,0,0,0,0,0,0,0,1,0,0];this.pci_space=this.pci_space.concat(k.zeros(256-this.pci_space.length));this.pci_id=b.pci_id;this.pci_bars=[];this.name=b.name;this.driver_feature_select=this.device_feature_select=0;this.device_feature= +new Uint32Array(4);this.driver_feature=new Uint32Array(4);for(var c of b.common.features)this.device_feature[c>>>5]|=1<<(c&31),this.driver_feature[c>>>5]|=1<<(c&31);b.common.features.includes(32);this.features_ok=!0;this.device_status=0;this.config_has_changed=!1;this.config_generation=0;this.queues=[];for(const d of b.common.queues)this.queues.push(new V(a,this,d));this.queue_select=0;this.queue_selected=this.queues[0];this.isr_status=0;c=[];c.push(this.create_common_capability(b.common));c.push(this.create_notification_capability(b.notification)); +c.push(this.create_isr_capability(b.isr_status));b.device_specific&&c.push(this.create_device_specific_capability(b.device_specific));this.init_capabilities(c);a.devices.pci.register_device(this);this.reset()} +da.prototype.create_common_capability=function(a){return{type:1,bar:0,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array(0),struct:[{bytes:4,name:"device_feature_select",read:()=>this.device_feature_select,write:b=>{this.device_feature_select=b}},{bytes:4,name:"device_feature",read:()=>this.device_feature[this.device_feature_select]||0,write:()=>{}},{bytes:4,name:"driver_feature_select",read:()=>this.driver_feature_select,write:b=>{this.driver_feature_select=b}},{bytes:4,name:"driver_feature", read:()=>this.driver_feature[this.driver_feature_select]||0,write:b=>{const c=this.device_feature[this.driver_feature_select];this.driver_feature_select65535,write:()=>{}},{bytes:2,name:"num_queues",read:()=>this.queues.length,write:()=>{}},{bytes:1,name:"device_status",read:()=>this.device_status,write:b=>{0===b&&this.reset();b&~this.device_status& 4&&this.device_status&64&&this.notify_config_changes();this.features_ok||(b&=-9);this.device_status=b;if(b&~this.device_status&4)a.on_driver_ok()}},{bytes:1,name:"config_generation",read:()=>this.config_generation,write:()=>{}},{bytes:2,name:"queue_select",read:()=>this.queue_select,write:b=>{this.queue_select=b;this.queue_selected=this.queue_selectthis.queue_selected?this.queue_selected.size:0,write:b=> -{this.queue_selected&&(b&b-1&&(b=1<this.queue_selected.size_supported&&(b=this.queue_selected.size_supported),this.queue_selected.set_size(b))}},{bytes:2,name:"queue_msix_vector",read:()=>65535,write:()=>{}},{bytes:2,name:"queue_enable",read:()=>this.queue_selected?this.queue_selected.enabled|0:0,write:b=>{this.queue_selected&&1===b&&this.queue_selected.is_configured()&&this.queue_selected.enable()}},{bytes:2,name:"queue_notify_off",read:()=>this.queue_selected?this.queue_selected.notify_offset: +{this.queue_selected&&(b&b-1&&(b=1<this.queue_selected.size_supported&&(b=this.queue_selected.size_supported),this.queue_selected.set_size(b))}},{bytes:2,name:"queue_msix_vector",read:()=>65535,write:()=>{}},{bytes:2,name:"queue_enable",read:()=>this.queue_selected?this.queue_selected.enabled|0:0,write:b=>{this.queue_selected&&1===b&&this.queue_selected.is_configured()&&this.queue_selected.enable()}},{bytes:2,name:"queue_notify_off",read:()=>this.queue_selected?this.queue_selected.notify_offset: 0,write:()=>{}},{bytes:4,name:"queue_desc (low dword)",read:()=>this.queue_selected?this.queue_selected.desc_addr:0,write:b=>{this.queue_selected&&(this.queue_selected.desc_addr=b)}},{bytes:4,name:"queue_desc (high dword)",read:()=>0,write:()=>{}},{bytes:4,name:"queue_avail (low dword)",read:()=>this.queue_selected?this.queue_selected.avail_addr:0,write:b=>{this.queue_selected&&(this.queue_selected.avail_addr=b)}},{bytes:4,name:"queue_avail (high dword)",read:()=>0,write:()=>{}},{bytes:4,name:"queue_used (low dword)", read:()=>this.queue_selected?this.queue_selected.used_addr:0,write:b=>{this.queue_selected&&(this.queue_selected.used_addr=b)}},{bytes:4,name:"queue_used (high dword)",read:()=>0,write:()=>{}}]}}; -Fc.prototype.create_notification_capability=function(a){const b=[];let c;c=a.single_handler?0:2;for(const [d,e]of a.handlers.entries())b.push({bytes:2,name:"notify"+d,read:()=>65535,write:e||(()=>{})});return{type:2,bar:1,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array([c&255,c>>8&255,c>>16&255,c>>24]),struct:b}}; -Fc.prototype.create_isr_capability=function(a){return{type:3,bar:2,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array(0),struct:[{bytes:1,name:"isr_status",read:()=>{const b=this.isr_status;this.lower_irq();return b},write:()=>{}}]}};Fc.prototype.create_device_specific_capability=function(a){return{type:4,bar:3,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array(0),struct:a.struct}}; -Fc.prototype.init_capabilities=function(a){let b=this.pci_space[52]=64;var c=b;for(const e of a){a=16+e.extra.length;c=b;b=c+a;var d=e.struct.reduce((f,g)=>f+g.bytes,0);d+=e.offset;d=16>d?16:1<>>8&255;this.pci_space[c+ -10]=e.offset>>>16&255;this.pci_space[c+11]=e.offset>>>24;this.pci_space[c+12]=d&255;this.pci_space[c+13]=d>>>8&255;this.pci_space[c+14]=d>>>16&255;this.pci_space[c+15]=d>>>24;for(const [f,g]of e.extra.entries())this.pci_space[c+16+f]=g;c=16+4*e.bar;this.pci_space[c]=e.port&254|!e.use_mmio;this.pci_space[c+1]=e.port>>>8&255;this.pci_space[c+2]=e.port>>>16&255;this.pci_space[c+3]=e.port>>>24&255;c=e.port+e.offset;for(const f of e.struct){let g=f.read;a=f.write;if(!e.use_mmio){d=function(m){return g(m& --2)>>((m&1)<<3)&255};const h=function(m){return g(m&-4)>>((m&3)<<3)&255},l=function(m){return g(m)};switch(f.bytes){case 4:this.cpu.io.register_read(c,this,h,void 0,g);this.cpu.io.register_read(c+1,this,h);this.cpu.io.register_read(c+2,this,h);this.cpu.io.register_read(c+3,this,h);this.cpu.io.register_write(c,this,void 0,void 0,a);break;case 2:this.cpu.io.register_read(c,this,d,g,l);this.cpu.io.register_read(c+1,this,d);this.cpu.io.register_write(c,this,void 0,a);break;case 1:this.cpu.io.register_read(c, -this,g),this.cpu.io.register_write(c,this,a)}}c+=f.bytes}}this.pci_space[b]=9;this.pci_space[b+1]=0;this.pci_space[b+2]=20;this.pci_space[b+3]=5;this.pci_space[b+4]=0;this.pci_space[b+5]=0;this.pci_space[b+6]=0;this.pci_space[b+7]=0;this.pci_space[b+8]=0;this.pci_space[b+9]=0;this.pci_space[b+10]=0;this.pci_space[b+11]=0;this.pci_space[b+12]=0;this.pci_space[b+13]=0;this.pci_space[b+14]=0;this.pci_space[b+15]=0;this.pci_space[b+16]=0;this.pci_space[b+17]=0;this.pci_space[b+18]=0;this.pci_space[b+ -19]=0};Fc.prototype.get_state=function(){let a=[];a[0]=this.device_feature_select;a[1]=this.driver_feature_select;a[2]=this.device_feature;a[3]=this.driver_feature;a[4]=this.features_ok;a[5]=this.device_status;a[6]=this.config_has_changed;a[7]=this.config_generation;a[8]=this.isr_status;a[9]=this.queue_select;return a=a.concat(this.queues)}; -Fc.prototype.set_state=function(a){this.device_feature_select=a[0];this.driver_feature_select=a[1];this.device_feature=a[2];this.driver_feature=a[3];this.features_ok=a[4];this.device_status=a[5];this.config_has_changed=a[6];this.config_generation=a[7];this.isr_status=a[8];this.queue_select=a[9];let b=0;for(const c of a.slice(10))this.queues[b].set_state(c),b++;this.queue_selected=this.queues[this.queue_select]||null}; -Fc.prototype.reset=function(){this.driver_feature_select=this.device_feature_select=0;this.driver_feature.set(this.device_feature);this.features_ok=!0;this.queue_select=this.device_status=0;this.queue_selected=this.queues[0];for(const a of this.queues)a.reset();this.config_has_changed=!1;this.config_generation=0;this.lower_irq()};Fc.prototype.notify_config_changes=function(){this.config_has_changed=!0;this.device_status&4&&this.raise_irq(2)}; -Fc.prototype.update_config_generation=function(){this.config_has_changed&&(this.config_generation++,this.config_generation&=255,this.config_has_changed=!1)};Fc.prototype.is_feature_negotiated=function(a){return 0<(this.driver_feature[a>>>5]&1<<(a&31))};Fc.prototype.needs_reset=function(){this.device_status|=64;this.device_status&4&&this.notify_config_changes()};Fc.prototype.raise_irq=function(a){y(a);this.isr_status|=a;this.pci.raise_irq(this.pci_id)}; -Fc.prototype.lower_irq=function(){this.isr_status=0;this.pci.lower_irq(this.pci_id)};function Y(a,b,c){this.cpu=a;this.virtio=b;this.size_supported=this.size=c.size_supported;this.mask=this.size-1;this.enabled=!1;this.notify_offset=c.notify_offset;this.num_staged_replies=this.used_addr=this.avail_last_idx=this.avail_addr=this.desc_addr=0;this.reset()} -Y.prototype.get_state=function(){const a=[];a[0]=this.size;a[1]=this.size_supported;a[2]=this.enabled;a[3]=this.notify_offset;a[4]=this.desc_addr;a[5]=this.avail_addr;a[6]=this.avail_last_idx;a[7]=this.used_addr;a[8]=this.num_staged_replies;a[9]=1;return a}; -Y.prototype.set_state=function(a){this.size=a[0];this.size_supported=a[1];this.enabled=a[2];this.notify_offset=a[3];this.desc_addr=a[4];this.avail_addr=a[5];this.avail_last_idx=a[6];this.used_addr=a[7];this.num_staged_replies=a[8];this.mask=this.size-1;this.fix_wrapping=1!==a[9]};Y.prototype.reset=function(){this.enabled=!1;this.num_staged_replies=this.used_addr=this.avail_last_idx=this.avail_addr=this.desc_addr=0;this.set_size(this.size_supported)}; -Y.prototype.is_configured=function(){return this.desc_addr&&this.avail_addr&&this.used_addr};Y.prototype.enable=function(){this.is_configured();this.enabled=!0};Y.prototype.set_size=function(a){this.size=a;this.mask=a-1};Y.prototype.count_requests=function(){this.fix_wrapping&&(this.fix_wrapping=!1,this.avail_last_idx=(this.avail_get_idx()&~this.mask)+(this.avail_last_idx&this.mask));return this.avail_get_idx()-this.avail_last_idx&65535};Y.prototype.has_request=function(){return 0!==this.count_requests()}; -Y.prototype.pop_request=function(){this.has_request();var a=this.avail_get_entry(this.avail_last_idx);a=new ed(this,a);this.avail_last_idx=this.avail_last_idx+1&65535;return a};Y.prototype.push_reply=function(a){const b=this.used_get_idx()+this.num_staged_replies&this.mask;this.used_set_entry(b,a.head_idx,a.length_written);this.num_staged_replies++}; -Y.prototype.flush_replies=function(){if(0!==this.num_staged_replies){var a=this.used_get_idx()+this.num_staged_replies&65535;this.used_set_idx(a);this.num_staged_replies=0;this.virtio.is_feature_negotiated(29)?(this.avail_get_used_event(),this.virtio.raise_irq(1)):~this.avail_get_flags()&1&&this.virtio.raise_irq(1)}};Y.prototype.notify_me_after=function(a){a=this.avail_get_idx()+a&65535;this.used_set_avail_event(a)}; -Y.prototype.get_descriptor=function(a,b){return{addr_low:this.cpu.read32s(a+16*b),addr_high:this.cpu.read32s(a+16*b+4),len:this.cpu.read32s(a+16*b+8),flags:this.cpu.read16(a+16*b+12),next:this.cpu.read16(a+16*b+14)}};Y.prototype.avail_get_flags=function(){return this.cpu.read16(this.avail_addr)};Y.prototype.avail_get_idx=function(){return this.cpu.read16(this.avail_addr+2)};Y.prototype.avail_get_entry=function(a){return this.cpu.read16(this.avail_addr+4+2*(a&this.mask))}; -Y.prototype.avail_get_used_event=function(){return this.cpu.read16(this.avail_addr+4+2*this.size)};Y.prototype.used_get_flags=function(){return this.cpu.read16(this.used_addr)};Y.prototype.used_set_flags=function(a){this.cpu.write16(this.used_addr,a)};Y.prototype.used_get_idx=function(){return this.cpu.read16(this.used_addr+2)};Y.prototype.used_set_idx=function(a){this.cpu.write16(this.used_addr+2,a)}; -Y.prototype.used_set_entry=function(a,b,c){this.cpu.write32(this.used_addr+4+8*a,b);this.cpu.write32(this.used_addr+8+8*a,c)};Y.prototype.used_set_avail_event=function(a){this.cpu.write16(this.used_addr+4+8*this.size,a)}; -function ed(a,b){this.cpu=a.cpu;this.virtio=a.virtio;this.head_idx=b;this.read_buffers=[];this.length_readable=this.read_buffer_offset=this.read_buffer_idx=0;this.write_buffers=[];this.length_writable=this.length_written=this.write_buffer_offset=this.write_buffer_idx=0;let c=a.desc_addr,d=0,e=a.size,f=!1;const g=this.virtio.is_feature_negotiated(28);do{const h=a.get_descriptor(c,b);y(h.addr_high,8);y(h.addr_low,8);y(h.len,8);y(h.flags,4);y(h.next,4);if(g&&h.flags&4)c=h.addr_low,d=b=0,e=h.len/16;else{if(h.flags& -2)f=!0,this.write_buffers.push(h),this.length_writable+=h.len;else{if(f)break;this.read_buffers.push(h);this.length_readable+=h.len}d++;if(d>e)break;if(h.flags&1)b=h.next;else break}}while(1)} -ed.prototype.get_next_blob=function(a){let b=0,c=a.length;for(;c&&this.read_buffer_idx!==this.read_buffers.length;){var d=this.read_buffers[this.read_buffer_idx];const e=d.addr_low+this.read_buffer_offset;d=d.len-this.read_buffer_offset;d>c?(d=c,this.read_buffer_offset+=c):(this.read_buffer_idx++,this.read_buffer_offset=0);a.set(this.cpu.read_blob(e,d),b);b+=d;c-=d}return b}; -ed.prototype.set_next_blob=function(a){let b=0,c=a.length;for(;c&&this.write_buffer_idx!==this.write_buffers.length;){var d=this.write_buffers[this.write_buffer_idx];const e=d.addr_low+this.write_buffer_offset;d=d.len-this.write_buffer_offset;d>c?(d=c,this.write_buffer_offset+=c):(this.write_buffer_idx++,this.write_buffer_offset=0);this.cpu.write_blob(a.subarray(b,b+d),e);b+=d;c-=d}this.length_written+=b;return b};function fd(a,b,c,d){const e=new Fc(a,{name:"virtio-9p",pci_id:48,device_id:4169,subsystem_device_id:9,common:{initial_port:43008,queues:[{size_supported:32,notify_offset:0}],features:[0,32,29,28],on_driver_ok:()=>{}},notification:{initial_port:43264,single_handler:!1,handlers:[f=>{if(0===f){for(f=e.queues[0];f.has_request();){const g=f.pop_request();d(g)}f.notify_me_after(0)}}]},isr_status:{initial_port:42752},device_specific:{initial_port:42496,struct:[{bytes:2,name:"mount tag length",read:()=> -b,write:()=>{}}].concat(Array.from(Array(254).keys()).map(f=>({bytes:1,name:"mount tag name "+f,read:()=>c[f]||0,write:()=>{}})))}});return e} -function bd(a,b,c){this.fs=a;this.bus=c;this.configspace_tagname=[104,111,115,116,57,112];this.configspace_taglen=this.configspace_tagname.length;this.virtio=fd(b,this.configspace_taglen,this.configspace_tagname,this.ReceiveRequest.bind(this));this.virtqueue=this.virtio.queues[0];this.VERSION="9P2000.L";this.msize=this.BLOCKSIZE=8192;this.replybuffer=new Uint8Array(2*this.msize);this.replybuffersize=0;this.fids=[]} -bd.prototype.get_state=function(){var a=[];a[0]=this.configspace_tagname;a[1]=this.configspace_taglen;a[2]=this.virtio;a[3]=this.VERSION;a[4]=this.BLOCKSIZE;a[5]=this.msize;a[6]=this.replybuffer;a[7]=this.replybuffersize;a[8]=this.fids.map(function(b){return[b.inodeid,b.type,b.uid,b.dbg_name]});a[9]=this.fs;return a}; -bd.prototype.set_state=function(a){this.configspace_tagname=a[0];this.configspace_taglen=a[1];this.virtio.set_state(a[2]);this.virtqueue=this.virtio.queues[0];this.VERSION=a[3];this.BLOCKSIZE=a[4];this.msize=a[5];this.replybuffer=a[6];this.replybuffersize=a[7];this.fids=a[8].map(function(b){return{inodeid:b[0],type:b[1],uid:b[2],dbg_name:b[3]}});this.fs.set_state(a[9])};bd.prototype.Createfid=function(a,b,c,d){return{inodeid:a,type:b,uid:c,dbg_name:d}}; -bd.prototype.update_dbg_name=function(a,b){for(const c of this.fids)c.inodeid===a&&(c.dbg_name=b)};bd.prototype.reset=function(){this.fids=[];this.virtio.reset()};bd.prototype.BuildReply=function(a,b,c){G(["w","b","h"],[c+7,a+1,b],this.replybuffer,0);this.replybuffersize=c+7};bd.prototype.SendError=function(a,b,c){b=G(["w"],[c],this.replybuffer,7);this.BuildReply(6,a,b)}; -bd.prototype.SendReply=function(a){a.set_next_blob(this.replybuffer.subarray(0,this.replybuffersize));this.virtqueue.push_reply(a);this.virtqueue.flush_replies()}; -bd.prototype.ReceiveRequest=async function(a){var b=new Uint8Array(a.length_readable);a.get_next_blob(b);var c={offset:0},d=I(["w","b","h"],b,c),e=d[1];d=d[2];switch(e){case 8:var f=this.fs.GetTotalSize();var g=this.fs.GetSpace(),h=[16914839];h[1]=this.BLOCKSIZE;h[2]=Math.floor(g/h[1]);h[3]=h[2]-Math.floor(f/h[1]);h[4]=h[2]-Math.floor(f/h[1]);h[5]=this.fs.CountUsedInodes();h[6]=this.fs.CountFreeInodes();h[7]=0;h[8]=256;f=G("wwddddddw".split(""),h,this.replybuffer,7);this.BuildReply(e,d,f);this.SendReply(a); -break;case 112:case 12:h=I(["w","w"],b,c);f=h[0];var l=h[1];b=this.fids[f].inodeid;c=this.fs.GetInode(b);await this.fs.OpenInode(b,l);h=[];h[0]=c.qid;h[1]=this.msize-24;G(["Q","w"],h,this.replybuffer,7);this.BuildReply(e,d,17);this.SendReply(a);break;case 70:h=I(["w","w","s"],b,c);b=h[0];f=h[1];g=h[2];f=this.fs.Link(this.fids[b].inodeid,this.fids[f].inodeid,g);if(0>f){this.SendError(d,-1===f?"Operation not permitted":"Unknown error: "+-f,-f);this.SendReply(a);break}this.BuildReply(e,d,0);this.SendReply(a); -break;case 16:h=I(["w","s","s","w"],b,c);f=h[0];g=h[1];var m=h[3];b=this.fs.CreateSymlink(g,this.fids[f].inodeid,h[2]);c=this.fs.GetInode(b);c.uid=this.fids[f].uid;c.gid=m;G(["Q"],[c.qid],this.replybuffer,7);this.BuildReply(e,d,13);this.SendReply(a);break;case 18:h=I("wswwww".split(""),b,c);f=h[0];g=h[1];l=h[2];b=h[3];c=h[4];m=h[5];b=this.fs.CreateNode(g,this.fids[f].inodeid,b,c);c=this.fs.GetInode(b);c.mode=l;c.uid=this.fids[f].uid;c.gid=m;G(["Q"],[c.qid],this.replybuffer,7);this.BuildReply(e,d, -13);this.SendReply(a);break;case 22:h=I(["w"],b,c);f=h[0];c=this.fs.GetInode(this.fids[f].inodeid);f=G(["s"],[c.symlink],this.replybuffer,7);this.BuildReply(e,d,f);this.SendReply(a);break;case 72:h=I(["w","s","w","w"],b,c);f=h[0];g=h[1];l=h[2];m=h[3];b=this.fs.CreateDirectory(g,this.fids[f].inodeid);c=this.fs.GetInode(b);c.mode=l|16384;c.uid=this.fids[f].uid;c.gid=m;G(["Q"],[c.qid],this.replybuffer,7);this.BuildReply(e,d,13);this.SendReply(a);break;case 14:h=I(["w","s","w","w","w"],b,c);f=h[0];g= -h[1];l=h[3];m=h[4];this.bus.send("9p-create",[g,this.fids[f].inodeid]);b=this.fs.CreateFile(g,this.fids[f].inodeid);this.fids[f].inodeid=b;this.fids[f].type=1;this.fids[f].dbg_name=g;c=this.fs.GetInode(b);c.uid=this.fids[f].uid;c.gid=m;c.mode=l|32768;G(["Q","w"],[c.qid,this.msize-24],this.replybuffer,7);this.BuildReply(e,d,17);this.SendReply(a);break;case 52:h=I("wbwddws".split(""),b,c);f=h[0];g=h[2];b=0===h[4]?Infinity:h[4];h=this.fs.DescribeLock(h[1],h[3],b,h[5],h[6]);f=this.fs.Lock(this.fids[f].inodeid, -h,g);G(["b"],[f],this.replybuffer,7);this.BuildReply(e,d,1);this.SendReply(a);break;case 54:h=I("wbddws".split(""),b,c);f=h[0];b=0===h[3]?Infinity:h[3];h=this.fs.DescribeLock(h[1],h[2],b,h[4],h[5]);f=this.fs.GetLock(this.fids[f].inodeid,h);f||(f=h,f.type=2);f=G(["b","d","d","w","s"],[f.type,f.start,Infinity===f.length?0:f.length,f.proc_id,f.client_id],this.replybuffer,7);this.BuildReply(e,d,f);this.SendReply(a);break;case 24:h=I(["w","d"],b,c);f=h[0];c=this.fs.GetInode(this.fids[f].inodeid);if(!c|| -4===c.status){this.SendError(d,"No such file or directory",2);this.SendReply(a);break}h[0]=h[1];h[1]=c.qid;h[2]=c.mode;h[3]=c.uid;h[4]=c.gid;h[5]=c.nlinks;h[6]=c.major<<8|c.minor;h[7]=c.size;h[8]=this.BLOCKSIZE;h[9]=Math.floor(c.size/512+1);h[10]=c.atime;h[11]=0;h[12]=c.mtime;h[13]=0;h[14]=c.ctime;h[15]=0;h[16]=0;h[17]=0;h[18]=0;h[19]=0;G("dQwwwddddddddddddddd".split(""),h,this.replybuffer,7);this.BuildReply(e,d,153);this.SendReply(a);break;case 26:h=I("wwwwwddddd".split(""),b,c);f=h[0];c=this.fs.GetInode(this.fids[f].inodeid); -h[1]&1&&(c.mode=h[2]);h[1]&2&&(c.uid=h[3]);h[1]&4&&(c.gid=h[4]);h[1]&16&&(c.atime=Math.floor((new Date).getTime()/1E3));h[1]&32&&(c.mtime=Math.floor((new Date).getTime()/1E3));h[1]&64&&(c.ctime=Math.floor((new Date).getTime()/1E3));h[1]&128&&(c.atime=h[6]);h[1]&256&&(c.mtime=h[8]);h[1]&8&&await this.fs.ChangeSize(this.fids[f].inodeid,h[5]);this.BuildReply(e,d,0);this.SendReply(a);break;case 50:I(["w","d"],b,c);this.BuildReply(e,d,0);this.SendReply(a);break;case 40:case 116:h=I(["w","d","w"],b,c); -f=h[0];g=h[1];l=h[2];c=this.fs.GetInode(this.fids[f].inodeid);if(!c||4===c.status){this.SendError(d,"No such file or directory",2);this.SendReply(a);break}if(2===this.fids[f].type)for(c.caps.lengthc.size&&(l=0),this.bus.send("9p-read-start", -[this.fids[f].dbg_name]),h=await this.fs.Read(h,g,l),this.bus.send("9p-read-end",[this.fids[f].dbg_name,l]),h&&this.replybuffer.set(h,11);G(["w"],[l],this.replybuffer,7);this.BuildReply(e,d,4+l);this.SendReply(a);break;case 118:h=I(["w","d","w"],b,c);f=h[0];g=h[1];l=h[2];h=this.fids[f].dbg_name;if(2===this.fids[f].type){this.SendError(d,"Setxattr not supported",95);this.SendReply(a);break}else await this.fs.Write(this.fids[f].inodeid,g,l,b.subarray(c.offset));this.bus.send("9p-write-end",[h,l]);G(["w"], -[l],this.replybuffer,7);this.BuildReply(e,d,4);this.SendReply(a);break;case 74:h=I(["w","s","w","s"],b,c);f=await this.fs.Rename(this.fids[h[0]].inodeid,h[1],this.fids[h[2]].inodeid,h[3]);if(0>f){this.SendError(d,-2===f?"No such file or directory":-1===f?"Operation not permitted":-39===f?"Directory not empty":"Unknown error: "+-f,-f);this.SendReply(a);break}this.BuildReply(e,d,0);this.SendReply(a);break;case 76:h=I(["w","s","w"],b,c);b=h[0];g=h[1];f=this.fs.Search(this.fids[b].inodeid,g);if(-1=== -f){this.SendError(d,"No such file or directory",2);this.SendReply(a);break}f=this.fs.Unlink(this.fids[b].inodeid,g);if(0>f){this.SendError(d,-39===f?"Directory not empty":-1===f?"Operation not permitted":"Unknown error: "+-f,-f);this.SendReply(a);break}this.BuildReply(e,d,0);this.SendReply(a);break;case 100:f=I(["w","s"],b,c);this.msize!==f[0]&&(this.msize=f[0],this.replybuffer=new Uint8Array(Math.min(16777216,2*this.msize)));f=G(["w","s"],[this.msize,this.VERSION],this.replybuffer,7);this.BuildReply(e, -d,f);this.SendReply(a);break;case 104:h=I(["w","w","s","s","w"],b,c);f=h[0];g=h[4];y(h[1]);this.fids[f]=this.Createfid(0,1,g,"");c=this.fs.GetInode(this.fids[f].inodeid);G(["Q"],[c.qid],this.replybuffer,7);this.BuildReply(e,d,13);this.SendReply(a);this.bus.send("9p-attach");break;case 108:I(["h"],b,c);this.BuildReply(e,d,0);this.SendReply(a);break;case 110:h=I(["w","w","h"],b,c);f=h[0];l=h[1];m=h[2];if(0===m){this.fids[l]=this.Createfid(this.fids[f].inodeid,1,this.fids[f].uid,this.fids[f].dbg_name); -G(["h"],[0],this.replybuffer,7);this.BuildReply(e,d,2);this.SendReply(a);break}g=[];for(h=0;h{const d=new Uint8Array(c.length_readable);c.get_next_blob(d);var e=I(["w","b","h"],d,{offset:0})[2];this.tag_bufchain.set(e,c);this.handle_fn(d,f=>{var g=I(["w","b","h"],f,{offset:0})[2];const h=this.tag_bufchain.get(g);h?(h.set_next_blob(f),this.virtqueue.push_reply(h), -this.virtqueue.flush_replies(),this.tag_bufchain.delete(g)):console.error("No bufchain found for tag: "+g)})});this.virtqueue=this.virtio.queues[0]}cd.prototype.get_state=function(){var a=[];a[0]=this.configspace_tagname;a[1]=this.configspace_taglen;a[2]=this.virtio;a[3]=this.tag_bufchain;return a};cd.prototype.set_state=function(a){this.configspace_tagname=a[0];this.configspace_taglen=a[1];this.virtio.set_state(a[2]);this.virtqueue=this.virtio.queues[0];this.tag_bufchain=a[3]}; -cd.prototype.reset=function(){this.virtio.reset()}; -function dd(a,b){this.socket=void 0;this.cpu=b;this.send_queue=[];this.url=a;this.reconnect_interval=1E4;this.last_connect_attempt=Date.now()-this.reconnect_interval;this.send_queue_limit=64;this.destroyed=!1;this.tag_bufchain=new Map;this.configspace_tagname=[104,111,115,116,57,112];this.configspace_taglen=this.configspace_tagname.length;this.virtio=fd(b,this.configspace_taglen,this.configspace_tagname,async c=>{const d=new Uint8Array(c.length_readable);c.get_next_blob(d);const e=I(["w","b","h"], -d,{offset:0})[2];this.tag_bufchain.set(e,c);this.send(d)});this.virtqueue=this.virtio.queues[0]}dd.prototype.get_state=function(){var a=[];a[0]=this.configspace_tagname;a[1]=this.configspace_taglen;a[2]=this.virtio;a[3]=this.tag_bufchain;return a};dd.prototype.set_state=function(a){this.configspace_tagname=a[0];this.configspace_taglen=a[1];this.virtio.set_state(a[2]);this.virtqueue=this.virtio.queues[0];this.tag_bufchain=a[3]};dd.prototype.reset=function(){this.virtio.reset()}; -dd.prototype.handle_message=function(a){a=new Uint8Array(a.data);const b=I(["w","b","h"],a,{offset:0})[2],c=this.tag_bufchain.get(b);c?(c.set_next_blob(a),this.virtqueue.push_reply(c),this.virtqueue.flush_replies(),this.tag_bufchain.delete(b)):console.error("Virtio9pProxy: No bufchain found for tag: "+b)};dd.prototype.handle_close=function(){this.destroyed||(this.connect(),setTimeout(this.connect.bind(this),this.reconnect_interval))}; -dd.prototype.handle_open=function(){for(var a=0;aa)){this.last_connect_attempt=Date.now();try{this.socket=new WebSocket(this.url)}catch(b){console.error(b);return}this.socket.binaryType="arraybuffer";this.socket.onopen=this.handle_open.bind(this);this.socket.onmessage=this.handle_message.bind(this);this.socket.onclose=this.handle_close.bind(this); -this.socket.onerror=this.handle_error.bind(this)}}};dd.prototype.send=function(a){this.socket&&1===this.socket.readyState?this.socket.send(a):(this.send_queue.push(a),this.send_queue.length>2*this.send_queue_limit&&(this.send_queue=this.send_queue.slice(-this.send_queue_limit)),this.connect())};dd.prototype.change_proxy=function(a){this.url=a;this.socket&&(this.socket.onclose=function(){},this.socket.onerror=function(){},this.socket.close(),this.socket=void 0)};}).call(this); +da.prototype.create_notification_capability=function(a){const b=[];let c;c=a.single_handler?0:2;for(const [d,e]of a.handlers.entries())b.push({bytes:2,name:"notify"+d,read:()=>65535,write:e||(()=>{})});return{type:2,bar:1,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array([c&255,c>>8&255,c>>16&255,c>>24]),struct:b}}; +da.prototype.create_isr_capability=function(a){return{type:3,bar:2,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array(0),struct:[{bytes:1,name:"isr_status",read:()=>{const b=this.isr_status;this.lower_irq();return b},write:()=>{}}]}};da.prototype.create_device_specific_capability=function(a){return{type:4,bar:3,port:a.initial_port,use_mmio:!1,offset:0,extra:new Uint8Array(0),struct:a.struct}}; +da.prototype.init_capabilities=function(a){let b=this.pci_space[52]=64;var c=b;for(const e of a){a=16+e.extra.length;c=b;b=c+a;var d=e.struct.reduce((g,f)=>g+f.bytes,0);d+=e.offset;d=16>d?16:1<>>8&255;this.pci_space[c+ +10]=e.offset>>>16&255;this.pci_space[c+11]=e.offset>>>24;this.pci_space[c+12]=d&255;this.pci_space[c+13]=d>>>8&255;this.pci_space[c+14]=d>>>16&255;this.pci_space[c+15]=d>>>24;for(const [g,f]of e.extra.entries())this.pci_space[c+16+g]=f;c=16+4*e.bar;this.pci_space[c]=e.port&254|!e.use_mmio;this.pci_space[c+1]=e.port>>>8&255;this.pci_space[c+2]=e.port>>>16&255;this.pci_space[c+3]=e.port>>>24&255;c=e.port+e.offset;for(const g of e.struct){let f=g.read;a=g.write;if(!e.use_mmio){d=function(l){return f(l& +-2)>>((l&1)<<3)&255};const h=function(l){return f(l&-4)>>((l&3)<<3)&255};switch(g.bytes){case 4:this.cpu.io.register_read(c,this,h,void 0,f);this.cpu.io.register_write(c,this,void 0,void 0,a);break;case 2:this.cpu.io.register_read(c,this,d,f);this.cpu.io.register_write(c,this,void 0,a);break;case 1:this.cpu.io.register_read(c,this,f),this.cpu.io.register_write(c,this,a)}}c+=g.bytes}}this.pci_space[b]=9;this.pci_space[b+1]=0;this.pci_space[b+2]=20;this.pci_space[b+3]=5;this.pci_space[b+4]=0;this.pci_space[b+ +5]=0;this.pci_space[b+6]=0;this.pci_space[b+7]=0;this.pci_space[b+8]=0;this.pci_space[b+9]=0;this.pci_space[b+10]=0;this.pci_space[b+11]=0;this.pci_space[b+12]=0;this.pci_space[b+13]=0;this.pci_space[b+14]=0;this.pci_space[b+15]=0;this.pci_space[b+16]=0;this.pci_space[b+17]=0;this.pci_space[b+18]=0;this.pci_space[b+19]=0}; +da.prototype.get_state=function(){let a=[];a[0]=this.device_feature_select;a[1]=this.driver_feature_select;a[2]=this.device_feature;a[3]=this.driver_feature;a[4]=this.features_ok;a[5]=this.device_status;a[6]=this.config_has_changed;a[7]=this.config_generation;a[8]=this.isr_status;a[9]=this.queue_select;return a=a.concat(this.queues)}; +da.prototype.set_state=function(a){this.device_feature_select=a[0];this.driver_feature_select=a[1];this.device_feature=a[2];this.driver_feature=a[3];this.features_ok=a[4];this.device_status=a[5];this.config_has_changed=a[6];this.config_generation=a[7];this.isr_status=a[8];this.queue_select=a[9];let b=0;for(const c of a.slice(10))this.queues[b].set_state(c),b++;this.queue_selected=this.queues[this.queue_select]||null}; +da.prototype.reset=function(){this.driver_feature_select=this.device_feature_select=0;this.driver_feature.set(this.device_feature);this.features_ok=!0;this.queue_select=this.device_status=0;this.queue_selected=this.queues[0];for(const a of this.queues)a.reset();this.config_has_changed=!1;this.config_generation=0;this.lower_irq()};da.prototype.notify_config_changes=function(){this.config_has_changed=!0;this.device_status&4&&this.raise_irq(2)}; +da.prototype.update_config_generation=function(){this.config_has_changed&&(this.config_generation++,this.config_generation&=255,this.config_has_changed=!1)};da.prototype.is_feature_negotiated=function(a){return 0<(this.driver_feature[a>>>5]&1<<(a&31))};da.prototype.needs_reset=function(){this.device_status|=64;this.device_status&4&&this.notify_config_changes()};da.prototype.raise_irq=function(a){B(a);this.isr_status|=a;this.pci.raise_irq(this.pci_id)}; +da.prototype.lower_irq=function(){this.isr_status=0;this.pci.lower_irq(this.pci_id)};function V(a,b,c){this.cpu=a;this.virtio=b;this.size_supported=this.size=c.size_supported;this.mask=this.size-1;this.enabled=!1;this.notify_offset=c.notify_offset;this.num_staged_replies=this.used_addr=this.avail_last_idx=this.avail_addr=this.desc_addr=0;this.reset()} +V.prototype.get_state=function(){const a=[];a[0]=this.size;a[1]=this.size_supported;a[2]=this.enabled;a[3]=this.notify_offset;a[4]=this.desc_addr;a[5]=this.avail_addr;a[6]=this.avail_last_idx;a[7]=this.used_addr;a[8]=this.num_staged_replies;return a}; +V.prototype.set_state=function(a){this.size=a[0];this.size_supported=a[1];this.enabled=a[2];this.notify_offset=a[3];this.desc_addr=a[4];this.avail_addr=a[5];this.avail_last_idx=a[6];this.used_addr=a[7];this.num_staged_replies=a[8];this.mask=this.size-1};V.prototype.reset=function(){this.enabled=!1;this.num_staged_replies=this.used_addr=this.avail_last_idx=this.avail_addr=this.desc_addr=0;this.set_size(this.size_supported)}; +V.prototype.is_configured=function(){return this.desc_addr&&this.avail_addr&&this.used_addr};V.prototype.enable=function(){this.is_configured();this.enabled=!0};V.prototype.set_size=function(a){this.size=a;this.mask=a-1};V.prototype.count_requests=function(){return this.avail_get_idx()-this.avail_last_idx&this.mask};V.prototype.has_request=function(){return(this.avail_get_idx()&this.mask)!==this.avail_last_idx}; +V.prototype.pop_request=function(){this.has_request();var a=this.avail_get_entry(this.avail_last_idx);a=new lb(this,a);this.avail_last_idx=this.avail_last_idx+1&this.mask;return a};V.prototype.push_reply=function(a){const b=this.used_get_idx()+this.num_staged_replies&this.mask;this.used_set_entry(b,a.head_idx,a.length_written);this.num_staged_replies++}; +V.prototype.flush_replies=function(){if(0!==this.num_staged_replies){var a=this.used_get_idx()+this.num_staged_replies&65535;this.used_set_idx(a);this.num_staged_replies=0;this.virtio.is_feature_negotiated(29)?(this.avail_get_used_event(),this.virtio.raise_irq(1)):~this.avail_get_flags()&1&&this.virtio.raise_irq(1)}};V.prototype.notify_me_after=function(a){a=this.avail_get_idx()+a&65535;this.used_set_avail_event(a)}; +V.prototype.get_descriptor=function(a,b){return{addr_low:this.cpu.read32s(a+16*b),addr_high:this.cpu.read32s(a+16*b+4),len:this.cpu.read32s(a+16*b+8),flags:this.cpu.read16(a+16*b+12),next:this.cpu.read16(a+16*b+14)}};V.prototype.avail_get_flags=function(){return this.cpu.read16(this.avail_addr)};V.prototype.avail_get_idx=function(){return this.cpu.read16(this.avail_addr+2)};V.prototype.avail_get_entry=function(a){return this.cpu.read16(this.avail_addr+4+2*a)}; +V.prototype.avail_get_used_event=function(){return this.cpu.read16(this.avail_addr+4+2*this.size)};V.prototype.used_get_flags=function(){return this.cpu.read16(this.used_addr)};V.prototype.used_set_flags=function(a){this.cpu.write16(this.used_addr,a)};V.prototype.used_get_idx=function(){return this.cpu.read16(this.used_addr+2)};V.prototype.used_set_idx=function(a){this.cpu.write16(this.used_addr+2,a)}; +V.prototype.used_set_entry=function(a,b,c){this.cpu.write32(this.used_addr+4+8*a,b);this.cpu.write32(this.used_addr+8+8*a,c)};V.prototype.used_set_avail_event=function(a){this.cpu.write16(this.used_addr+4+8*this.size,a)}; +function lb(a,b){this.cpu=a.cpu;this.virtio=a.virtio;this.head_idx=b;this.read_buffers=[];this.length_readable=this.read_buffer_offset=this.read_buffer_idx=0;this.write_buffers=[];this.length_writable=this.length_written=this.write_buffer_offset=this.write_buffer_idx=0;let c=a.desc_addr,d=0,e=a.size,g=!1;const f=this.virtio.is_feature_negotiated(28);do{const h=a.get_descriptor(c,b);B(h.addr_high,8);B(h.addr_low,8);B(h.len,8);B(h.flags,4);B(h.next,4);if(f&&h.flags&4)c=h.addr_low,d=b=0,e=h.len/16;else{if(h.flags& +2)g=!0,this.write_buffers.push(h),this.length_writable+=h.len;else{if(g)break;this.read_buffers.push(h);this.length_readable+=h.len}d++;if(d>e)break;if(h.flags&1)b=h.next;else break}}while(1)} +lb.prototype.get_next_blob=function(a){let b=0,c=a.length;for(;c&&this.read_buffer_idx!==this.read_buffers.length;){var d=this.read_buffers[this.read_buffer_idx];const e=d.addr_low+this.read_buffer_offset;d=d.len-this.read_buffer_offset;d>c?(d=c,this.read_buffer_offset+=c):(this.read_buffer_idx++,this.read_buffer_offset=0);a.set(this.cpu.read_blob(e,d),b);b+=d;c-=d}return b}; +lb.prototype.set_next_blob=function(a){let b=0,c=a.length;for(;c&&this.write_buffer_idx!==this.write_buffers.length;){var d=this.write_buffers[this.write_buffer_idx];const e=d.addr_low+this.write_buffer_offset;d=d.len-this.write_buffer_offset;d>c?(d=c,this.write_buffer_offset+=c):(this.write_buffer_idx++,this.write_buffer_offset=0);this.cpu.write_blob(a.subarray(b,b+d),e);b+=d;c-=d}this.length_written+=b;return b};function mb(a,b){this.bus=b;this.rows=25;this.cols=80;this.ports=4;b=[{size_supported:16,notify_offset:0},{size_supported:16,notify_offset:1},{size_supported:16,notify_offset:2},{size_supported:16,notify_offset:3}];for(let c=1;c{}},notification:{initial_port:47360, +single_handler:!1,handlers:[c=>{for(c=this.virtio.queues[c];c.count_requests()>c.size-2;)c.pop_request()},c=>{const d=this.virtio.queues[c],e=3>1:0;for(;d.has_request();){const g=d.pop_request(),f=new Uint8Array(g.length_readable);g.get_next_blob(f);this.bus.send("virtio-console"+e+"-output-bytes",f);this.Ack(c,g)}},c=>{if(2===c)for(c=this.virtio.queues[c];c.count_requests()>c.size-2;)c.pop_request()},c=>{if(3===c)for(var d=this.virtio.queues[c];d.has_request();){var e=d.pop_request(),g=new Uint8Array(e.length_readable); +e.get_next_blob(g);var f=t.Unmarshall(["w","h","h"],g,{offset:0});g=f[0];f=f[1];this.Ack(c,e);switch(f){case 0:for(e=0;ethis.cols,write:()=>{}},{bytes:2,name:"rows",read:()=> +this.rows,write:()=>{}},{bytes:4,name:"max_nr_ports",read:()=>this.ports,write:()=>{}},{bytes:4,name:"emerg_wr",read:()=>0,write:()=>{}}]}});for(let c=0;c{}},notification:{initial_port:51456,single_handler:!1,handlers:[d=>{d=this.virtio.queues[d];var e=d.avail_get_entry(d.avail_last_idx);e=new lb(d,e);d.avail_last_idx=d.avail_last_idx+1&d.mask;this.virtio.queues[0].push_reply(e);this.virtio.queues[0].flush_replies()},d=>{const e=this.virtio.queues[d];for(;e.has_request();){const g=e.pop_request(),f=new Uint8Array(g.length_readable);g.get_next_blob(f);this.bus.send("net"+ +this.id+"-send",f.subarray(12));this.bus.send("eth-transmit-end",[f.length-12]);this.virtio.queues[d].push_reply(g)}this.virtio.queues[d].flush_replies()},d=>{if(d===2*this.pairs)for(var e=this.virtio.queues[d];e.has_request();){const g=e.pop_request(),f=new Uint8Array(g.length_readable);g.get_next_blob(f);const h=t.Unmarshall(["b","b"],f,{offset:0});switch(h[0]<<8|h[1]){case 1024:t.Unmarshall(["h"],f,{offset:2});this.Send(d,g,new Uint8Array([0]));break;case 257:this.mac=f.subarray(2,8);this.Send(d, +g,new Uint8Array([0]));this.bus.send("net"+this.id+"-mac",Pa(this.mac));break;default:this.Send(d,g,new Uint8Array([1]));return}}}]},isr_status:{initial_port:50944},device_specific:{initial_port:50688,struct:[0,1,2,3,4,5].map((d,e)=>({bytes:1,name:"mac_"+e,read:()=>this.mac[e],write:()=>{}})).concat([{bytes:2,name:"status",read:()=>this.status,write:()=>{}},{bytes:2,name:"max_pairs",read:()=>this.pairs,write:()=>{}},{bytes:2,name:"mtu",read:()=>1500,write:()=>{}}])}});this.bus.register("net"+this.id+ +"-receive",d=>{this.bus.send("eth-receive-end",[d.length]);const e=new Uint8Array(12+d.byteLength);(new DataView(e.buffer,e.byteOffset,e.byteLength)).setInt16(10,1);e.set(d,12);d=this.virtio.queues[0];d.has_request()?(d=d.pop_request(),d.set_next_blob(e),this.virtio.queues[0].push_reply(d),this.virtio.queues[0].flush_replies()):console.log("No buffer to write into!")},this)}nb.prototype.get_state=function(){const a=[];a[0]=this.virtio;a[1]=this.id;a[2]=this.mac;return a}; +nb.prototype.set_state=function(a){this.virtio.set_state(a[0]);this.id=a[1];this.preserve_mac_from_state_image&&(this.mac=a[2],this.bus.send("net"+this.id+"-mac",Pa(this.mac)))};nb.prototype.reset=function(){this.virtio.reset()};nb.prototype.Send=function(a,b,c){b.set_next_blob(c);this.virtio.queues[a].push_reply(b);this.virtio.queues[a].flush_replies()};nb.prototype.Ack=function(a,b){this.virtio.queues[a].push_reply(b);this.virtio.queues[a].flush_replies()};const ob="SWAP_IN SWAP_OUT MAJFLT MINFLT MEMFREE MEMTOT AVAIL CACHES HTLB_PGALLOC HTLB_PGFAIL".split(" "); +function pb(a,b){this.bus=b;this.zeroed=this.fp_cmd=this.actual=this.num_pages=0;this.virtio=new da(a,{name:"virtio-balloon",pci_id:88,device_id:4165,subsystem_device_id:5,common:{initial_port:55296,queues:[{size_supported:32,notify_offset:0},{size_supported:32,notify_offset:0},{size_supported:2,notify_offset:1},{size_supported:64,notify_offset:2}],features:[1,3,32],on_driver_ok:()=>{}},notification:{initial_port:55552,single_handler:!1,handlers:[c=>{const d=this.virtio.queues[c];for(;d.has_request();){var e= +d.pop_request();const g=new Uint8Array(e.length_readable);e.get_next_blob(g);this.virtio.queues[c].push_reply(e);e=g.byteLength/4;this.actual+=0===c?e:-e}this.virtio.queues[c].flush_replies()},c=>{var d=this.virtio.queues[c];if(d.has_request()){d=d.pop_request();const e=new Uint8Array(d.length_readable);d.get_next_blob(e);let g={};for(let f=0;f +{const d=this.virtio.queues[c];for(;d.has_request();){const g=d.pop_request();if(0this.num_pages,write:()=>{}},{bytes:4,name:"actual",read:()=>this.actual,write:()=>{}},{bytes:4,name:"free_page_hint_cmd_id",read:()=>this.fp_cmd,write:()=>{}}]}})}pb.prototype.Inflate=function(a){this.num_pages+=a;this.virtio.notify_config_changes()};pb.prototype.Deflate=function(a){this.num_pages-=a;this.virtio.notify_config_changes()}; +pb.prototype.Cleanup=function(a){this.fp_cmd=2;this.free_cb=a;this.zeroed=0;this.virtio.notify_config_changes()};pb.prototype.get_state=function(){const a=[];a[0]=this.virtio;a[1]=this.num_pages;a[2]=this.actual;return a};pb.prototype.set_state=function(a){this.virtio.set_state(a[0]);this.num_pages=a[1];this.actual=a[2]};pb.prototype.GetStats=function(a){this.stats_cb=a;for(a=this.virtio.queues[2];a.has_request();){const b=a.pop_request();this.virtio.queues[2].push_reply(b)}this.virtio.queues[2].flush_replies()}; +pb.prototype.Reset=function(){};var qb={};function rb(){this.listeners={};this.pair=void 0}rb.prototype.register=function(a,b,c){var d=this.listeners[a];void 0===d&&(d=this.listeners[a]=[]);d.push({fn:b,this_value:c})};rb.prototype.unregister=function(a,b){var c=this.listeners[a];void 0!==c&&(this.listeners[a]=c.filter(function(d){return d.fn!==b}))};rb.prototype.send=function(a,b){if(this.pair&&(a=this.pair.listeners[a],void 0!==a))for(var c=0;cthis.wm.exports[c],b=c=>{const d=a(c);console.assert(d,"Missing import: "+c);return d};this.reset_cpu=b("reset_cpu");this.getiopl=b("getiopl");this.get_eflags=b("get_eflags");this.handle_irqs=b("handle_irqs");this.main_loop=b("main_loop");this.set_jit_config=b("set_jit_config");this.read8=b("read8");this.read16=b("read16");this.read32s=b("read32s");this.write8=b("write8");this.write16=b("write16");this.write32=b("write32");this.in_mapped_range=b("in_mapped_range"); +this.fpu_load_tag_word=b("fpu_load_tag_word");this.fpu_load_status_word=b("fpu_load_status_word");this.fpu_get_sti_f64=b("fpu_get_sti_f64");this.translate_address_system_read=b("translate_address_system_read_js");this.get_seg_cs=b("get_seg_cs");this.get_real_eip=b("get_real_eip");this.clear_tlb=b("clear_tlb");this.full_clear_tlb=b("full_clear_tlb");this.update_state_flags=b("update_state_flags");this.set_tsc=b("set_tsc");this.store_current_tsc=b("store_current_tsc");this.set_cpuid_level=b("set_cpuid_level"); +this.pic_set_irq=b("pic_set_irq");this.pic_clear_irq=b("pic_clear_irq");this.jit_clear_cache=b("jit_clear_cache_js");this.jit_dirty_cache=b("jit_dirty_cache");this.codegen_finalize_finished=b("codegen_finalize_finished");this.allocate_memory=b("allocate_memory");this.zero_memory=b("zero_memory");this.is_memory_zeroed=b("is_memory_zeroed");this.svga_allocate_memory=b("svga_allocate_memory");this.svga_allocate_dest_buffer=b("svga_allocate_dest_buffer");this.svga_fill_pixel_buffer=b("svga_fill_pixel_buffer"); +this.svga_mark_dirty=b("svga_mark_dirty");this.get_pic_addr_master=b("get_pic_addr_master");this.get_pic_addr_slave=b("get_pic_addr_slave");this.zstd_create_ctx=b("zstd_create_ctx");this.zstd_get_src_ptr=b("zstd_get_src_ptr");this.zstd_free_ctx=b("zstd_free_ctx");this.zstd_read=b("zstd_read");this.zstd_read_free=b("zstd_read_free");this.port20_read=b("port20_read");this.port21_read=b("port21_read");this.portA0_read=b("portA0_read");this.portA1_read=b("portA1_read");this.port20_write=b("port20_write"); +this.port21_write=b("port21_write");this.portA0_write=b("portA0_write");this.portA1_write=b("portA1_write");this.port4D0_read=b("port4D0_read");this.port4D1_read=b("port4D1_read");this.port4D0_write=b("port4D0_write");this.port4D1_write=b("port4D1_write")};E.prototype.jit_force_generate=function(a){this.jit_force_generate_unsafe&&this.jit_force_generate_unsafe(a)};E.prototype.jit_clear_func=function(a){this.wm.wasm_table.set(a+1024,null)}; +E.prototype.jit_clear_all_funcs=function(){const a=this.wm.wasm_table;for(let b=0;900>b;b++)a.set(1024+b,null)}; +E.prototype.get_state=function(){var a=[];a[0]=this.memory_size[0];a[1]=new Uint8Array([...this.segment_is_null,...this.segment_access_bytes]);a[2]=this.segment_offsets;a[3]=this.segment_limits;a[4]=this.protected_mode[0];a[5]=this.idtr_offset[0];a[6]=this.idtr_size[0];a[7]=this.gdtr_offset[0];a[8]=this.gdtr_size[0];a[9]=this.page_fault[0];a[10]=this.cr;a[11]=this.cpl[0];a[13]=this.is_32[0];a[16]=this.stack_size_32[0];a[17]=this.in_hlt[0];a[18]=this.last_virt_eip[0];a[19]=this.eip_phys[0];a[22]=this.sysenter_cs[0]; +a[23]=this.sysenter_eip[0];a[24]=this.sysenter_esp[0];a[25]=this.prefixes[0];a[26]=this.flags[0];a[27]=this.flags_changed[0];a[28]=this.last_op1[0];a[30]=this.last_op_size[0];a[37]=this.instruction_pointer[0];a[38]=this.previous_ip[0];a[39]=this.reg32;a[40]=this.sreg;a[41]=this.dreg;a[42]=this.reg_pdpte;this.store_current_tsc();a[43]=this.current_tsc;a[45]=this.devices.virtio_9p;a[46]=this.devices.apic;a[47]=this.devices.rtc;a[48]=this.devices.pci;a[49]=this.devices.dma;a[50]=this.devices.acpi;a[52]= +this.devices.vga;a[53]=this.devices.ps2;a[54]=this.devices.uart0;a[55]=this.devices.fdc;a[56]=this.devices.cdrom;a[57]=this.devices.hda;a[58]=this.devices.pit;a[59]=this.devices.net;a[60]=this.get_state_pic();a[61]=this.devices.sb16;a[62]=this.fw_value;a[63]=this.devices.ioapic;a[64]=this.tss_size_32[0];a[66]=this.reg_xmm32s;a[67]=this.fpu_st;a[68]=this.fpu_stack_empty[0];a[69]=this.fpu_stack_ptr[0];a[70]=this.fpu_control_word[0];a[71]=this.fpu_ip[0];a[72]=this.fpu_ip_selector[0];a[73]=this.fpu_dp[0]; +a[74]=this.fpu_dp_selector[0];a[75]=this.fpu_opcode[0];const {packed_memory:b,bitmap:c}=this.pack_memory();a[77]=b;a[78]=new Uint8Array(c.get_buffer());a[79]=this.devices.uart1;a[80]=this.devices.uart2;a[81]=this.devices.uart3;a[82]=this.devices.virtio_console;a[83]=this.devices.virtio_net;a[84]=this.devices.virtio_balloon;return a}; +E.prototype.get_state_pic=function(){const a=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_master(),13),b=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_slave(),13),c=[],d=[];c[0]=a[0];c[1]=a[1];c[2]=a[2];c[3]=a[3];c[4]=a[4];c[5]=d;c[6]=a[6];c[7]=a[7];c[8]=a[8];c[9]=a[9];c[10]=a[10];c[11]=a[11];c[12]=a[12];d[0]=b[0];d[1]=b[1];d[2]=b[2];d[3]=b[3];d[4]=b[4];d[5]=null;d[6]=b[6];d[7]=b[7];d[8]=b[8];d[9]=b[9];d[10]=b[10];d[11]=b[11];d[12]=b[12];return c}; +E.prototype.set_state=function(a){this.memory_size[0]=a[0];this.mem8.length!==this.memory_size[0]&&console.warn("Note: Memory size mismatch. we="+this.mem8.length+" state="+this.memory_size[0]);8===a[1].length?(this.segment_is_null.set(a[1]),this.segment_access_bytes.fill(242),this.segment_access_bytes[1]=250):16===a[1].length&&(this.segment_is_null.set(a[1].subarray(0,8)),this.segment_access_bytes.set(a[1].subarray(8,16)));this.segment_offsets.set(a[2]);this.segment_limits.set(a[3]);this.protected_mode[0]= +a[4];this.idtr_offset[0]=a[5];this.idtr_size[0]=a[6];this.gdtr_offset[0]=a[7];this.gdtr_size[0]=a[8];this.page_fault[0]=a[9];this.cr.set(a[10]);this.cpl[0]=a[11];this.is_32[0]=a[13];this.stack_size_32[0]=a[16];this.in_hlt[0]=a[17];this.last_virt_eip[0]=a[18];this.eip_phys[0]=a[19];this.sysenter_cs[0]=a[22];this.sysenter_eip[0]=a[23];this.sysenter_esp[0]=a[24];this.prefixes[0]=a[25];this.flags[0]=a[26];this.flags_changed[0]=a[27];this.last_op1[0]=a[28];this.last_op_size[0]=a[30];this.instruction_pointer[0]= +a[37];this.previous_ip[0]=a[38];this.reg32.set(a[39]);this.sreg.set(a[40]);this.dreg.set(a[41]);a[42]&&this.reg_pdpte.set(a[42]);this.set_tsc(a[43][0],a[43][1]);this.devices.virtio_9p&&this.devices.virtio_9p.set_state(a[45]);this.devices.apic&&this.devices.apic.set_state(a[46]);this.devices.rtc&&this.devices.rtc.set_state(a[47]);this.devices.pci&&this.devices.pci.set_state(a[48]);this.devices.dma&&this.devices.dma.set_state(a[49]);this.devices.acpi&&this.devices.acpi.set_state(a[50]);this.devices.vga&& +this.devices.vga.set_state(a[52]);this.devices.ps2&&this.devices.ps2.set_state(a[53]);this.devices.uart0&&this.devices.uart0.set_state(a[54]);this.devices.fdc&&this.devices.fdc.set_state(a[55]);this.devices.cdrom&&this.devices.cdrom.set_state(a[56]);this.devices.hda&&this.devices.hda.set_state(a[57]);this.devices.pit&&this.devices.pit.set_state(a[58]);this.devices.net&&this.devices.net.set_state(a[59]);this.set_state_pic(a[60]);this.devices.sb16&&this.devices.sb16.set_state(a[61]);this.devices.uart1&& +this.devices.uart1.set_state(a[79]);this.devices.uart2&&this.devices.uart2.set_state(a[80]);this.devices.uart3&&this.devices.uart3.set_state(a[81]);this.devices.virtio_console&&this.devices.virtio_console.set_state(a[82]);this.devices.virtio_net&&this.devices.virtio_net.set_state(a[83]);this.devices.virtio_balloon&&this.devices.virtio_balloon.set_state(a[84]);this.fw_value=a[62];this.devices.ioapic&&this.devices.ioapic.set_state(a[63]);this.tss_size_32[0]=a[64];this.reg_xmm32s.set(a[66]);this.fpu_st.set(a[67]); +this.fpu_stack_empty[0]=a[68];this.fpu_stack_ptr[0]=a[69];this.fpu_control_word[0]=a[70];this.fpu_ip[0]=a[71];this.fpu_ip_selector[0]=a[72];this.fpu_dp[0]=a[73];this.fpu_dp_selector[0]=a[74];this.fpu_opcode[0]=a[75];const b=new k.Bitmap(a[78].buffer);this.unpack_memory(b,a[77]);this.update_state_flags();this.full_clear_tlb();this.jit_clear_cache()}; +E.prototype.set_state_pic=function(a){const b=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_master(),13),c=new Uint8Array(this.wasm_memory.buffer,this.get_pic_addr_slave(),13);b[0]=a[0];b[1]=a[1];b[2]=a[2];b[3]=a[3];b[4]=a[4];const d=a[5];b[6]=a[6];b[7]=a[7];b[8]=a[8];b[9]=a[9];b[10]=a[10];b[11]=a[11];b[12]=a[12];c[0]=d[0];c[1]=d[1];c[2]=d[2];c[3]=d[3];c[4]=d[4];c[6]=d[6];c[7]=d[7];c[8]=d[8];c[9]=d[9];c[10]=d[10];c[11]=d[11];c[12]=d[12]}; +E.prototype.pack_memory=function(){var a=this.mem8.length>>12,b=[];for(var c=0;c>12;let d=0;for(let g=0;g(a|0)&&(a=Math.pow(2,31)-131072);a=(a-1|131071)+1|0;console.assert(0===this.memory_size[0],"Expected uninitialised memory");this.memory_size[0]=a;b=this.allocate_memory(a);this.mem8=k.view(Uint8Array,this.wasm_memory,b,a);this.mem32s=k.view(Uint32Array,this.wasm_memory,b,a>>2)}; +E.prototype.init=function(a,b){this.create_memory(a.memory_size||67108864,a.initrd?67108864:1048576);a.disable_jit&&this.set_jit_config(0,1);a.cpuid_level&&this.set_cpuid_level(a.cpuid_level);this.acpi_enabled[0]=+a.acpi;this.reset_cpu();var c=new C(this);this.io=c;this.bios.main=a.bios;this.bios.vga=a.vga_bios;this.load_bios();if(a.bzimage){const e=Bb(this.mem8,a.bzimage,a.initrd,a.cmdline||"");e&&this.option_roms.push(e)}c.register_read(179,this,function(){return 0});var d=0;c.register_read(146, +this,function(){return d});c.register_write(146,this,function(e){d=e});c.register_read(1297,this,function(){return this.fw_pointer>8|l<<8&65280}function h(l){return l<<24|l<<8&16711680|l>>8&65280|l>>>24}ta("bios config port, index="+B(e));this.fw_pointer=0;if(0===e)this.fw_value=g(1431127377);else if(1===e)this.fw_value= +g(0);else if(3===e)this.fw_value=g(this.memory_size[0]);else if(5===e)this.fw_value=g(1);else if(15===e)this.fw_value=g(1);else if(13===e)this.fw_value=new Uint8Array(16);else if(25===e){e=new Int32Array(4+64*this.option_roms.length);const l=new Uint8Array(e.buffer);e[0]=h(this.option_roms.length);for(let m=0;m>2]=h(p.length);e[q+4>>2]=f(49152+m);for(let r=0;re?this.fw_value=g(0):49152<=e&&e-49152a.byteLength){var d=new Int32Array(2048);(new Uint8Array(d.buffer)).set(new Uint8Array(a))}else d=new Int32Array(a,0,2048);for(var e=0;8192>e;e+=4){if(464367618===d[e>>2]){var g=d[e+4>>2];if(464367618+g+d[e+8>>2]|0)continue}else continue;ta("Multiboot magic found, flags: "+B(g>>>0,8),2);var f=this;this.io.register_read(244,this,function(){return 0},function(){return 0},function(){var n=31860,p=0;if(c){p|=4;f.write32(31760,n);c+="\x00"; +var q=(new TextEncoder).encode(c);f.write_blob(q,n);n+=q.length}if(g&2){p|=64;q=0;f.write32(31788,0);f.write32(31792,n);var r=0;var A=!1;for(let u=0;4294967296>u;u+=131072)A&&void 0!==f.memory_map_read8[u>>>17]?(f.write32(n,20),f.write32(n+4,r),f.write32(n+8,0),f.write32(n+12,u-r),f.write32(n+16,0),f.write32(n+20,1),n+=24,q+=24,A=!1):A||void 0!==f.memory_map_read8[u>>>17]||(r=u,A=!0);f.write32(31788,q)}f.write32(31744,p);q=p=0;if(g&65536){A=d[e+12>>2];p=d[e+16>>2];var w=d[e+20>>2];q=d[e+24>>2];r= +d[e+28>>2];B(A,8);B(p,8);B(w,8);B(q,8);B(r,8);A=new Uint8Array(a,e-(A-p),0===w?void 0:w-p);f.write_blob(A,p);p=r|0;q=Math.max(w,q)}else if(1179403647===d[0]){r=new DataView(a);const [u,G]=Cb(r,Db);console.assert(52===G);console.assert(1179403647===u.magic,"Bad magic");console.assert(1===u.class,"Unimplemented: 64 bit elf");console.assert(1===u.data,"Unimplemented: big endian");console.assert(1===u.version0,"Bad version0");console.assert(2===u.type,"Unimplemented type");console.assert(1===u.version1, +"Bad version1");console.assert(52===u.ehsize,"Bad header size");console.assert(32===u.phentsize,"Bad program header size");console.assert(40===u.shentsize,"Bad section header size");[p]=Eb(new DataView(r.buffer,r.byteOffset+u.phoff,u.phentsize*u.phnum),Fb,u.phnum);Eb(new DataView(r.buffer,r.byteOffset+u.shoff,u.shentsize*u.shnum),Gb,u.shnum);r=u;A=p;p=r.entry;for(w of A)0!==w.type&&(1===w.type?w.paddr+w.memszp&&(p=p-w.vaddr+w.paddr)):B(w.paddr):2===w.type||3===w.type||4===w.type||6===w.type||7===w.type||1685382480===w.type||1685382481===w.type||1685382482===w.type||1685382483===w.type||B(w.type))}b&&(f.write32(31764,1),f.write32(31768,n),w=q,0!==(w&4095)&&(w=(w&-4096)+4096),q=w+b.byteLength,f.write32(n,w),f.write32(n+4,q),f.write32(n+8,0),f.write32(n+12,0),f.write_blob(new Uint8Array(b),w));f.reg32[3]=31744;f.cr[0]=1;f.protected_mode[0]= +1;f.flags[0]=2;f.is_32[0]=1;f.stack_size_32[0]=1;for(n=0;6>n;n++)f.segment_is_null[n]=0,f.segment_offsets[n]=0,f.segment_limits[n]=4294967295,f.sreg[n]=45058;f.instruction_pointer[0]=f.get_seg_cs()+p|0;f.update_state_flags();f.debug.dump_state();f.debug.dump_regs();return 732803074});this.io.register_write_consecutive(244,this,function(n){console.log("Test exited with code "+B(n,2));throw"HALT";},function(){},function(){},function(){});for(let n=0;15>=n;n++){function p(q){B(n);B(q,2);q?this.device_raise_irq(n): +this.device_lower_irq(n)}this.io.register_write(8192+n,this,p,p,p)}const l=new Uint8Array(512);(new Uint16Array(l.buffer))[0]=43605;l[2]=1;var h=3;l[h++]=102;l[h++]=229;l[h++]=244;let m=l[h]=0;for(let n=0;n>4&240);a.cmos_write(61,c&255);a.cmos_write(21,128);a.cmos_write(22,2);c=0;1048576<=this.memory_size[0]&&(c=this.memory_size[0]-1048576>>10,c=Math.min(c,65535));a.cmos_write(23,c&255);a.cmos_write(24,c>>8&255);a.cmos_write(48,c&255);a.cmos_write(49,c>>8&255);c=0;16777216<=this.memory_size[0]&&(c=this.memory_size[0]-16777216>>16,c=Math.min(c,65535));a.cmos_write(52,c&255);a.cmos_write(53,c>>8&255);a.cmos_write(91,0);a.cmos_write(92, +0);a.cmos_write(93,0);a.cmos_write(20,47);a.cmos_write(95,0);b.fastboot&&a.cmos_write(63,1)}; +E.prototype.load_bios=function(){var a=this.bios.main,b=this.bios.vga;if(a){var c=new Uint8Array(a);this.write_blob(c,1048576-a.byteLength);if(b){var d=new Uint8Array(b);this.write_blob(d,786432);this.io.mmap_register(4272947200,1048576,function(e){e=e-4272947200|0;return e>>0,e>>>0);WebAssembly.instantiate(g,{e:this.jit_imports}).then(f=>{this.wm.wasm_table.set(a+1024,f.instance.exports.f);this.codegen_finalize_finished(a,b,c);this.test_hook_did_finalize_wasm&&this.test_hook_did_finalize_wasm(g)})};E.prototype.log_uncompiled_code=function(){};E.prototype.dump_function_code=function(){}; +E.prototype.run_hardware_timers=function(a,b){const c=this.devices.pit.timer(b,!1),d=this.devices.rtc.timer(b,!1);let e=100,g=100;a&&(e=this.devices.acpi.timer(b),g=this.devices.apic.timer(b));return Math.min(c,d,e,g)};E.prototype.device_raise_irq=function(a){this.pic_set_irq(a);this.devices.ioapic&&this.devices.ioapic.set_irq(a)};E.prototype.device_lower_irq=function(a){this.pic_clear_irq(a);this.devices.ioapic&&this.devices.ioapic.clear_irq(a)};E.prototype.debug_init=function(){var a=this,b={};this.debug=b;b.init=function(){};b.get_regs_short=function(){};b.dump_regs=function(){};b.get_state=function(){};b.dump_state=function(){};b.dump_stack=function(){};b.dump_page_structures=function(){if(a.cr[4]&32)for(var g=0;4>g;g++)a.read32s(a.cr[3]+8*g)};b.dump_gdt_ldt=function(){};b.dump_idt=function(){};b.get_memory_dump=function(){};b.memory_hex_dump=function(){};b.used_memory_dump=function(){};b.debug_interrupt=function(){};let c,d;b.dump_code= +function(g,f,h){if(!d){if(void 0===c&&(c="function"===typeof require?require("./capstone-x86.min.js"):window.cs,void 0===c))return;d=[new c.Capstone(c.ARCH_X86,c.MODE_16),new c.Capstone(c.ARCH_X86,c.MODE_32)]}try{d[g].disasm(f,h).forEach(function(l){ta(B(l.address>>>0)+": "+k.pads(l.bytes.map(m=>B(m,2).slice(-2)).join(" "),20)+" "+l.mnemonic+" "+l.op_str)})}catch(l){ta("Could not disassemble: "+Array.from(f).map(m=>B(m,2)).join(" "))}};let e;b.dump_wasm=function(g){if(void 0===e&&(e="function"=== +typeof require?require("./libwabt.js"):new window.WabtModule,void 0===e))return;g=g.slice();try{var f=e.readWasm(g,{readDebugNames:!1});f.generateNames();f.applyNames();f.toText({foldExprs:!0,inlineExport:!0})}catch(m){var h=new Blob([g]),l=document.createElement("a");l.download="failed.wasm";l.href=window.URL.createObjectURL(h);l.dataset.downloadurl=["application/octet-stream",l.download,l.href].join(":");l.click();window.URL.revokeObjectURL(l.src);console.log(m.toString())}finally{f&&f.destroy()}}};const Hb=DataView.prototype,Ib={size:1,get:Hb.getUint8,set:Hb.setUint8},Jb={size:2,get:Hb.getUint16,set:Hb.setUint16},W={size:4,get:Hb.getUint32,set:Hb.setUint32},Db=Kb([{magic:W},{class:Ib},{data:Ib},{version0:Ib},{osabi:Ib},{abiversion:Ib},{pad0:function(a){return{size:a,get:()=>-1}}(7)},{type:Jb},{machine:Jb},{version1:W},{entry:W},{phoff:W},{shoff:W},{flags:W},{ehsize:Jb},{phentsize:Jb},{phnum:Jb},{shentsize:Jb},{shnum:Jb},{shstrndx:Jb}]);console.assert(52===Db.reduce((a,b)=>a+b.size,0)); +const Fb=Kb([{type:W},{offset:W},{vaddr:W},{paddr:W},{filesz:W},{memsz:W},{flags:W},{align:W}]);console.assert(32===Fb.reduce((a,b)=>a+b.size,0));const Gb=Kb([{name:W},{type:W},{flags:W},{addr:W},{offset:W},{size:W},{link:W},{info:W},{addralign:W},{entsize:W}]);console.assert(40===Gb.reduce((a,b)=>a+b.size,0));function Kb(a){return a.map(function(b){var c=Object.keys(b);console.assert(1===c.length);c=c[0];b=b[c];console.assert(0{f(n,p);n=null},10),!1;f(z,I);return!1}}function f(z,I){a:{if(void 0!==z.code){var R=G[z.code];if(void 0!==R)break a}R=A[z.keyCode]}R?h(R,I,z.repeat):console.log("Missing char in map: keyCode="+(z.keyCode||-1).toString(16)+" code="+z.code)}function h(z,I,R){if(I)m[z]&&!R&&h(z,!1);else if(!m[z])return; +(m[z]=I)||(z|=128);255>8),l(z&255)):l(z)}function l(z){r.bus.send("keyboard-code",z)}var m={},n=null,p=!1,q=0,r=this;this.emu_enabled=!0;var A=new Uint16Array([0,0,0,0,0,0,0,0,14,15,0,0,0,28,0,0,42,29,56,0,58,0,0,0,0,0,0,1,0,0,0,0,57,57417,57425,57423,57415,57419,57416,57421,80,0,0,0,0,82,83,0,11,2,3,4,5,6,7,8,9,10,0,39,0,13,0,0,0,30,48,46,32,18,33,34,35,23,36,37,38,50,49,24,25,16,19,31,20,22,47,17,45,21,44,57435,57436,57437,0,0,82,79,80,81,75,76,77,71,72,73,0,0,0,0,0,0,59,60,61,62,63,64, +65,66,67,68,87,88,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,69,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,39,13,51,12,52,53,41,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,43,27,40,0,57435,57400,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),w={8:8,10:13,32:32,39:222,44:188,45:189,46:190,47:191,48:48,49:49,50:50,51:51,52:52,53:53,54:54,55:55,56:56,57:57,59:186,61:187,91:219,92:220,93:221,96:192,97:65,98:66,99:67,100:68,101:69,102:70,103:71,104:72,105:73,106:74,107:75, +108:76,109:77,110:78,111:79,112:80,113:81,114:82,115:83,116:84,117:85,118:86,119:87,120:88,121:89,122:90},u={33:49,34:222,35:51,36:52,37:53,38:55,40:57,41:48,42:56,43:187,58:186,60:188,62:190,63:191,64:50,65:65,66:66,67:67,68:68,69:69,70:70,71:71,72:72,73:73,74:74,75:75,76:76,77:77,78:78,79:79,80:80,81:81,82:82,83:83,84:84,85:85,86:86,87:87,88:88,89:89,90:90,94:54,95:189,123:219,124:220,125:221,126:192},G={Escape:1,Digit1:2,Digit2:3,Digit3:4,Digit4:5,Digit5:6,Digit6:7,Digit7:8,Digit8:9,Digit9:10, +Digit0:11,Minus:12,Equal:13,Backspace:14,Tab:15,KeyQ:16,KeyW:17,KeyE:18,KeyR:19,KeyT:20,KeyY:21,KeyU:22,KeyI:23,KeyO:24,KeyP:25,BracketLeft:26,BracketRight:27,Enter:28,ControlLeft:29,KeyA:30,KeyS:31,KeyD:32,KeyF:33,KeyG:34,KeyH:35,KeyJ:36,KeyK:37,KeyL:38,Semicolon:39,Quote:40,Backquote:41,ShiftLeft:42,Backslash:43,KeyZ:44,KeyX:45,KeyC:46,KeyV:47,KeyB:48,KeyN:49,KeyM:50,Comma:51,Period:52,Slash:53,IntlRo:53,ShiftRight:54,NumpadMultiply:55,AltLeft:56,Space:57,CapsLock:58,F1:59,F2:60,F3:61,F4:62,F5:63, +F6:64,F7:65,F8:66,F9:67,F10:68,NumLock:69,ScrollLock:70,Numpad7:71,Numpad8:72,Numpad9:73,NumpadSubtract:74,Numpad4:75,Numpad5:76,Numpad6:77,NumpadAdd:78,Numpad1:79,Numpad2:80,Numpad3:81,Numpad0:82,NumpadDecimal:83,IntlBackslash:86,F11:87,F12:88,NumpadEnter:57372,ControlRight:57373,NumpadDivide:57397,AltRight:57400,Home:57415,ArrowUp:57416,PageUp:57417,ArrowLeft:57419,ArrowRight:57421,End:57423,ArrowDown:57424,PageDown:57425,Insert:57426,Delete:57427,OSLeft:57435,OSRight:57436,ContextMenu:57437};this.bus= +a;this.destroy=function(){"undefined"!==typeof window&&(window.removeEventListener("keyup",c,!1),window.removeEventListener("keydown",d,!1),window.removeEventListener("blur",e,!1))};this.init=function(){"undefined"!==typeof window&&(this.destroy(),window.addEventListener("keyup",c,!1),window.addEventListener("keydown",d,!1),window.addEventListener("blur",e,!1))};this.init();this.simulate_press=function(z){z={keyCode:z};g(z,!0);g(z,!1)};this.simulate_char=function(z){var I=z.charCodeAt(0);I in w?this.simulate_press(w[I]): +I in u?(l(42),this.simulate_press(u[I]),l(170)):console.log("ascii -> keyCode not found: ",I,z)}};function Tb(a,b){function c(u){if(!w.enabled||!w.emu_enabled)return!1;var G=b||document.body,z;if(!(z=document.pointerLockElement))a:{for(u=u.target;u.parentNode;){if(u===G){z=!0;break a}u=u.parentNode}z=!1}return z}function d(u){c(u)&&(u=u.changedTouches)&&u.length&&(u=u[u.length-1],r=u.clientX,A=u.clientY)}function e(){if(n||q||p)w.bus.send("mouse-click",[!1,!1,!1]),n=q=p=!1}function g(u){if(w.bus&&c(u)&&w.is_running){var G=0,z=0,I=u.changedTouches;I?I.length&&(I=I[I.length-1],G=I.clientX-r,z=I.clientY- +A,r=I.clientX,A=I.clientY,u.preventDefault()):"number"===typeof u.movementX?(G=u.movementX,z=u.movementY):"number"===typeof u.webkitMovementX?(G=u.webkitMovementX,z=u.webkitMovementY):"number"===typeof u.mozMovementX?(G=u.mozMovementX,z=u.mozMovementY):(G=u.clientX-r,z=u.clientY-A,r=u.clientX,A=u.clientY);w.bus.send("mouse-delta",[.15*G,-(.15*z)]);b&&w.bus.send("mouse-absolute",[u.pageX-b.offsetLeft,u.pageY-b.offsetTop,b.offsetWidth,b.offsetHeight])}}function f(u){c(u)&&l(u,!0)}function h(u){c(u)&& +l(u,!1)}function l(u,G){w.bus&&(1===u.which?n=G:2===u.which?q=G:3===u.which&&(p=G),w.bus.send("mouse-click",[n,q,p]),u.preventDefault())}function m(u){if(c(u)){var G=u.wheelDelta||-u.detail;0>G?G=-1:0{switch(n.data.type){case "queue":m.queue_push(n.data.value);break;case "sampling-rate":m.source_samples_per_destination=n.data.value/sampleRate}};return m}var l=[new Float32Array(256),new Float32Array(256)];Reflect.setPrototypeOf(h.prototype,AudioWorkletProcessor.prototype);Reflect.setPrototypeOf(h,AudioWorkletProcessor);h.prototype.process=h.prototype.process=function(m,n){for(m=0;mm?(m+=this.source_buffer_previous[0].length,this.source_buffer_previous[n][m]):this.source_buffer_current[n][m]};h.prototype.ensure_enough_data=function(m){var n=this.source_buffer_current[0].length;n-this.source_block_start +this.queued_samples&&this.queue_length&&this.dbg_log("Not enough samples - should not happen during midway of playback");this.source_buffer_previous=this.source_buffer_current;this.source_buffer_current=this.queue_shift();var m=this.source_buffer_current[0].length;if(256>m){for(var n=this.queue_start,p=0;256>m&&pthis.queued_samples/this.source_samples_per_destination&&this.port.postMessage({type:"pump"})};h.prototype.queue_push=function(m){this.queue_length{URL.revokeObjectURL(g);this.node_processor=new AudioWorkletNode(this.audio_context,"dac-processor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[2],parameterData:{},processorOptions:{}});this.node_processor.port.postMessage({type:"sampling-rate",value:this.sampling_rate});this.node_processor.port.onmessage=f=>{switch(f.data.type){case "pump":this.pump()}};this.node_processor.connect(this.node_output)}); +this.mixer_connection=c.add_source(this.node_output,2);this.mixer_connection.set_gain_hidden(3);a.register("dac-send-data",function(f){this.queue(f)},this);a.register("dac-enable",function(){this.enabled=!0},this);a.register("dac-disable",function(){this.enabled=!1},this);a.register("dac-tell-sampling-rate",function(f){this.sampling_rate=f;this.node_processor&&this.node_processor.port.postMessage({type:"sampling-rate",value:f})},this)} +Vb.prototype.queue=function(a){this.node_processor&&this.node_processor.port.postMessage({type:"queue",value:a},[a[0].buffer,a[1].buffer])};Vb.prototype.pump=function(){this.enabled&&this.bus.send("dac-request-data")}; +function Wb(a,b,c){this.bus=a;this.audio_context=b;this.enabled=!1;this.sampling_rate=22050;this.buffered_time=0;this.rate_ratio=1;this.node_lowpass=this.audio_context.createBiquadFilter();this.node_lowpass.type="lowpass";this.node_output=this.node_lowpass;this.mixer_connection=c.add_source(this.node_output,2);this.mixer_connection.set_gain_hidden(3);a.register("dac-send-data",function(d){this.queue(d)},this);a.register("dac-enable",function(){this.enabled=!0;this.pump()},this);a.register("dac-disable", +function(){this.enabled=!1},this);a.register("dac-tell-sampling-rate",function(d){this.sampling_rate=d;this.rate_ratio=Math.ceil(8E3/d);this.node_lowpass.frequency.setValueAtTime(d/2,this.audio_context.currentTime)},this)} +Wb.prototype.queue=function(a){var b=a[0].length,c=b/this.sampling_rate;if(1this.pump(),1E3*b);a.start(this.buffered_time);this.buffered_time+=c;setTimeout(()=>this.pump(),0)};Wb.prototype.pump=function(){this.enabled&&(.2l?void 0===this.update_timer&&(this.update_timer=setTimeout(()=>{this.update_timer=void 0;this.last_update=Date.now();this.render()},16-l)):(void 0!==this.update_timer&&(clearTimeout(this.update_timer),this.update_timer=void 0),this.last_update=h,this.render())};this.render=function(){a.value=this.text;this.text_new_line&&(this.text_new_line= +!1,a.scrollTop=1E9)};this.send_char=function(h){f.bus&&f.bus.send("serial0-input",h)}} +function ac(a,b){this.element=a;if(window.Terminal){var c=this.term=new window.Terminal({logLevel:"off"});c.write("This is the serial console. Whatever you type or paste here will be sent to COM1");var d=c.onData(function(e){for(let g=0;ga)){this.last_connect_attempt=Date.now();try{this.socket=new WebSocket(this.url)}catch(b){console.error(b);return}this.socket.binaryType="arraybuffer";this.socket.onopen=this.handle_open.bind(this);this.socket.onmessage=this.handle_message.bind(this);this.socket.onclose=this.handle_close.bind(this); +this.socket.onerror=this.handle_error.bind(this)}}};bc.prototype.send=function(a){this.socket&&1===this.socket.readyState?this.socket.send(a):(this.send_queue.push(a),this.send_queue.length>2*this.send_queue_limit&&(this.send_queue=this.send_queue.slice(-this.send_queue_limit)),this.connect())};bc.prototype.change_proxy=function(a){this.url=a;this.socket&&(this.socket.onclose=function(){},this.socket.onerror=function(){},this.socket.close(),this.socket=void 0)};function X(a){this.cpu_is_running=!1;this.cpu_exception_hook=function(){};var b=qb.create();this.bus=b[0];this.emulator_bus=b[1];var c,d;const e=new WebAssembly.Table({element:"anyfunc",initial:1924});b={cpu_exception_hook:f=>this.cpu_exception_hook(f),run_hardware_timers:function(f,h){return c.run_hardware_timers(f,h)},cpu_event_halt:()=>{this.emulator_bus.send("cpu-event-halt")},abort:function(){},microtick:D.microtick,get_rand_int:function(){return k.get_rand_int()},apic_acknowledge_irq:function(){return c.devices.apic.acknowledge_irq()}, +stop_idling:function(){return c.stop_idling()},io_port_read8:function(f){return c.io.port_read8(f)},io_port_read16:function(f){return c.io.port_read16(f)},io_port_read32:function(f){return c.io.port_read32(f)},io_port_write8:function(f,h){c.io.port_write8(f,h)},io_port_write16:function(f,h){c.io.port_write16(f,h)},io_port_write32:function(f,h){c.io.port_write32(f,h)},mmap_read8:function(f){return c.mmap_read8(f)},mmap_read16:function(f){return c.mmap_read16(f)},mmap_read32:function(f){return c.mmap_read32(f)}, +mmap_write8:function(f,h){c.mmap_write8(f,h)},mmap_write16:function(f,h){c.mmap_write16(f,h)},mmap_write32:function(f,h){c.mmap_write32(f,h)},mmap_write64:function(f,h,l){c.mmap_write64(f,h,l)},mmap_write128:function(f,h,l,m,n){c.mmap_write128(f,h,l,m,n)},log_from_wasm:function(f,h){k.read_sized_string_from_mem(d,f,h)},console_log_from_wasm:function(f,h){f=k.read_sized_string_from_mem(d,f,h);console.error(f)},dbg_trace_from_wasm:function(){},codegen_finalize:(f,h,l,m,n)=>{c.codegen_finalize(f,h,l, +m,n)},jit_clear_func:f=>c.jit_clear_func(f),jit_clear_all_funcs:()=>c.jit_clear_all_funcs(),__indirect_function_table:e};let g=a.wasm_fn;g||(g=f=>new Promise(h=>{let l="v86.wasm",m="v86-fallback.wasm";if(a.wasm_path){l=a.wasm_path;const n=l.lastIndexOf("/");m=(-1===n?"":l.substr(0,n))+"/"+m}else"undefined"===typeof window&&"string"===typeof __dirname?(l=__dirname+"/"+l,m=__dirname+"/"+m):(l="build/"+l,m="build/"+m);k.load_file(l,{done:async n=>{try{const {instance:p}=await WebAssembly.instantiate(n, +f);this.wasm_source=n;h(p.exports)}catch(p){k.load_file(m,{done:async q=>{const {instance:r}=await WebAssembly.instantiate(q,f);this.wasm_source=q;h(r.exports)}})}},progress:n=>{this.emulator_bus.send("download-progress",{file_index:0,file_count:1,file_name:l,lengthComputable:n.lengthComputable,total:n.total,loaded:n.loaded})}})}));g({env:b}).then(f=>{d=f.memory;f.rust_init();f=this.v86=new D(this.emulator_bus,{exports:f,wasm_table:e});c=f.cpu;this.continue_init(f,a)});this.zstd_worker=null;this.zstd_worker_request_id= +0}H.exportSymbol("V86",X); +X.prototype.continue_init=async function(a,b){function c(q,r){switch(q){case "hda":e.hda=this.disk_images.hda=r;break;case "hdb":e.hdb=this.disk_images.hdb=r;break;case "cdrom":e.cdrom=this.disk_images.cdrom=r;break;case "fda":e.fda=this.disk_images.fda=r;break;case "fdb":e.fdb=this.disk_images.fdb=r;break;case "multiboot":e.multiboot=this.disk_images.multiboot=r.buffer;break;case "bzimage":e.bzimage=this.disk_images.bzimage=r.buffer;break;case "initrd":e.initrd=this.disk_images.initrd=r.buffer;break; +case "bios":e.bios=r.buffer;break;case "vga_bios":e.vga_bios=r.buffer;break;case "initial_state":e.initial_state=r.buffer;break;case "fs9p_json":e.fs9p_json=r}}async function d(){if(e.fs9p&&e.fs9p_json&&!e.initial_state&&(e.fs9p.load_from_json(e.fs9p_json),b.bzimage_initrd_from_filesystem)){const {bzimage_path:q,initrd_path:r}=this.get_bzimage_initrd_from_filesystem(e.fs9p),[A,w]=await Promise.all([e.fs9p.read_file(r),e.fs9p.read_file(q)]);c.call(this,"initrd",new k.SyncBuffer(A.buffer));c.call(this, +"bzimage",new k.SyncBuffer(w.buffer))}this.serial_adapter&&this.serial_adapter.show&&this.serial_adapter.show();this.v86.init(e);e.initial_state&&(a.restore_state(e.initial_state),e.initial_state=void 0);b.autostart&&this.v86.run();this.emulator_bus.send("emulator-loaded")}this.bus.register("emulator-stopped",function(){this.cpu_is_running=!1;this.screen_adapter.pause()},this);this.bus.register("emulator-started",function(){this.cpu_is_running=!0;this.screen_adapter.continue()},this);var e={};this.disk_images= +{fda:void 0,fdb:void 0,hda:void 0,hdb:void 0,cdrom:void 0};var g=b.boot_order?b.boot_order:b.fda?801:b.hda?786:291;e.acpi=b.acpi;e.disable_jit=b.disable_jit;e.load_devices=!0;e.memory_size=b.memory_size||67108864;e.vga_memory_size=b.vga_memory_size||8388608;e.boot_order=g;e.fastboot=b.fastboot||!1;e.fda=void 0;e.fdb=void 0;e.uart1=b.uart1;e.uart2=b.uart2;e.uart3=b.uart3;e.cmdline=b.cmdline;e.preserve_mac_from_state_image=b.preserve_mac_from_state_image;e.mac_address_translation=b.mac_address_translation; +e.cpuid_level=b.cpuid_level;e.virtio_balloon=b.virtio_balloon;e.virtio_console=b.virtio_console;e.virtio_net=b.virtio_net;e.screen_options=b.screen_options;if(g=b.network_relay_url||b.net_device&&b.net_device.relay_url)"fetch"===g?this.network_adapter=new cc(this.bus,b.net_device):"inbrowser"===g?this.network_adapter=new dc(this.bus,b.net_device):g.startsWith("wisp://")||g.startsWith("wisps://")?this.network_adapter=new ec(g,this.bus,b.net_device):this.network_adapter=new bc(g,this.bus);e.net_device= +b.net_device||{type:"ne2k"};g=b.screen||{};b.screen_container&&(g.container=b.screen_container);b.disable_keyboard||(this.keyboard_adapter=new Sb(this.bus));b.disable_mouse||(this.mouse_adapter=new Tb(this.bus,g.container));this.screen_adapter=g.container?new aa(g,()=>this.v86.cpu.devices.vga&&this.v86.cpu.devices.vga.screen_fill_buffer()):new fc;e.screen=this.screen_adapter;e.screen_options=g;b.serial_container&&(this.serial_adapter=new $b(b.serial_container,this.bus));b.serial_container_xtermjs&& +(this.serial_adapter=new ac(b.serial_container_xtermjs,this.bus));b.disable_speaker||(this.speaker_adapter=new Ub(this.bus));var f=[];g=(q,r)=>{if(r)if(r.get&&r.set&&r.load)f.push({name:q,loadable:r});else{if("bios"===q||"vga_bios"===q||"initial_state"===q||"multiboot"===q||"bzimage"===q||"initrd"===q)r.async=!1;if("fda"===q||"fdb"===q)r.async=!1;r.url&&!r.async?f.push({name:q,url:r.url,size:r.size}):f.push({name:q,loadable:k.buffer_from_object(r,this.zstd_decompress_worker.bind(this))})}};b.state&& +console.warn("Warning: Unknown option 'state'. Did you mean 'initial_state'?");g("bios",b.bios);g("vga_bios",b.vga_bios);g("cdrom",b.cdrom);g("hda",b.hda);g("hdb",b.hdb);g("fda",b.fda);g("fdb",b.fdb);g("initial_state",b.initial_state);g("multiboot",b.multiboot);g("bzimage",b.bzimage);g("initrd",b.initrd);if(b.filesystem){g=b.filesystem.basefs;var h=b.filesystem.baseurl;let q=new gc;h&&(q=new hc(q,h));e.fs9p=this.fs9p=new Z(q);if(g){if("object"===typeof g){var l=g.size;g=g.url}f.push({name:"fs9p_json", +url:g,size:l,as_json:!0})}}var m=this,n=f.length,p=function(q){if(q===n)setTimeout(d.bind(this),0);else{var r=f[q];r.loadable?(r.loadable.onload=function(){c.call(this,r.name,r.loadable);p(q+1)}.bind(this),r.loadable.load()):k.load_file(r.url,{done:function(A){r.url.endsWith(".zst")&&"initial_state"!==r.name&&(A=this.zstd_decompress(r.size,new Uint8Array(A)));c.call(this,r.name,r.as_json?A:new k.SyncBuffer(A));p(q+1)}.bind(this),progress:function(A){200===A.target.status?m.emulator_bus.send("download-progress", +{file_index:q,file_count:n,file_name:r.url,lengthComputable:A.lengthComputable,total:A.total||r.size,loaded:A.loaded}):m.emulator_bus.send("download-error",{file_index:q,file_count:n,file_name:r.url,request:A.target})},as_json:r.as_json})}}.bind(this);p(0)}; +X.prototype.zstd_decompress=function(a,b){const c=this.v86.cpu;this.zstd_context=c.zstd_create_ctx(b.length);(new Uint8Array(c.wasm_memory.buffer)).set(b,c.zstd_get_src_ptr(this.zstd_context));b=c.zstd_read(this.zstd_context,a);const d=c.wasm_memory.buffer.slice(b,b+a);c.zstd_read_free(b,a);c.zstd_free_ctx(this.zstd_context);this.zstd_context=null;return d}; +X.prototype.zstd_decompress_worker=async function(a,b){if(!this.zstd_worker){const c=URL.createObjectURL(new Blob(["("+function(){let d;globalThis.onmessage=function(e){if(d){var {src:g,decompressed_size:f,id:h}=e.data;e=d.exports;var l=e.zstd_create_ctx(g.length);(new Uint8Array(e.memory.buffer)).set(g,e.zstd_get_src_ptr(l));var m=e.zstd_read(l,f),n=e.memory.buffer.slice(m,m+f);e.zstd_read_free(m,f);e.zstd_free_ctx(l);postMessage({result:n,id:h},[n])}else l=Object.fromEntries("cpu_exception_hook run_hardware_timers cpu_event_halt microtick get_rand_int apic_acknowledge_irq stop_idling io_port_read8 io_port_read16 io_port_read32 io_port_write8 io_port_write16 io_port_write32 mmap_read8 mmap_read16 mmap_read32 mmap_write8 mmap_write16 mmap_write32 mmap_write64 mmap_write128 codegen_finalize jit_clear_func jit_clear_all_funcs".split(" ").map(p=> +[p,()=>console.error("zstd worker unexpectedly called "+p)])),l.__indirect_function_table=new WebAssembly.Table({element:"anyfunc",initial:1024}),l.abort=()=>{throw Error("zstd worker aborted");},l.log_from_wasm=l.console_log_from_wasm=(p,q)=>{console.log(String.fromCharCode(...(new Uint8Array(d.exports.memory.buffer,p,q))))},l.dbg_trace_from_wasm=()=>console.trace(),d=new WebAssembly.Instance(new WebAssembly.Module(e.data),{env:l})}}.toString()+")()"],{type:"text/javascript"}));this.zstd_worker= +new Worker(c);URL.revokeObjectURL(c);this.zstd_worker.postMessage(this.wasm_source,[this.wasm_source])}return new Promise(c=>{const d=this.zstd_worker_request_id++,e=async g=>{g.data.id===d&&(this.zstd_worker.removeEventListener("message",e),c(g.data.result))};this.zstd_worker.addEventListener("message",e);this.zstd_worker.postMessage({src:b,decompressed_size:a,id:d},[b.buffer])})}; +X.prototype.get_bzimage_initrd_from_filesystem=function(a){const b=(a.read_dir("/")||[]).map(e=>"/"+e);a=(a.read_dir("/boot/")||[]).map(e=>"/boot/"+e);let c,d;for(const e of[].concat(b,a)){const g=/old/i.test(e)||/fallback/i.test(e),f=/vmlinuz/i.test(e)||/bzimage/i.test(e),h=/initrd/i.test(e)||/initramfs/i.test(e);!f||d&&g||(d=e);!h||c&&g||(c=e)}c&&d||(console.log("Failed to find bzimage or initrd in filesystem. Files:"),console.log(b.join(" ")),console.log(a.join(" ")));return{initrd_path:c,bzimage_path:d}}; +X.prototype.run=async function(){this.v86.run()};H.exportProperty(X.prototype,"run",X.prototype.run);X.prototype.stop=async function(){this.cpu_is_running&&await new Promise(a=>{const b=()=>{this.remove_listener("emulator-stopped",b);a()};this.add_listener("emulator-stopped",b);this.v86.stop()})};H.exportProperty(X.prototype,"stop",X.prototype.stop); +X.prototype.destroy=async function(){await this.stop();this.v86.destroy();this.keyboard_adapter&&this.keyboard_adapter.destroy();this.network_adapter&&this.network_adapter.destroy();this.mouse_adapter&&this.mouse_adapter.destroy();this.screen_adapter&&this.screen_adapter.destroy();this.serial_adapter&&this.serial_adapter.destroy();this.speaker_adapter&&this.speaker_adapter.destroy()};H.exportProperty(X.prototype,"destroy",X.prototype.destroy);X.prototype.restart=function(){this.v86.restart()}; +H.exportProperty(X.prototype,"restart",X.prototype.restart);X.prototype.add_listener=function(a,b){this.bus.register(a,b,this)};H.exportProperty(X.prototype,"add_listener",X.prototype.add_listener);X.prototype.remove_listener=function(a,b){this.bus.unregister(a,b)};H.exportProperty(X.prototype,"remove_listener",X.prototype.remove_listener);X.prototype.restore_state=async function(a){this.v86.restore_state(a)};H.exportProperty(X.prototype,"restore_state",X.prototype.restore_state); +X.prototype.save_state=async function(){return this.v86.save_state()};H.exportProperty(X.prototype,"save_state",X.prototype.save_state);X.prototype.get_instruction_counter=function(){return this.v86?this.v86.cpu.instruction_counter[0]>>>0:0};H.exportProperty(X.prototype,"get_instruction_counter",X.prototype.get_instruction_counter);X.prototype.is_running=function(){return this.cpu_is_running};H.exportProperty(X.prototype,"is_running",X.prototype.is_running); +X.prototype.set_fda=async function(a){if(a.url&&!a.async)k.load_file(a.url,{done:b=>{this.v86.cpu.devices.fdc.set_fda(new k.SyncBuffer(b))}});else{const b=k.buffer_from_object(a,this.zstd_decompress_worker.bind(this));b.onload=()=>{this.v86.cpu.devices.fdc.set_fda(b)};await b.load()}};H.exportProperty(X.prototype,"set_fda",X.prototype.set_fda);X.prototype.eject_fda=function(){this.v86.cpu.devices.fdc.eject_fda()};H.exportProperty(X.prototype,"eject_fda",X.prototype.eject_fda); +X.prototype.keyboard_send_scancodes=function(a){for(var b=0;ba)throw Error("Failed to mount. Error number: "+-a);};H.exportProperty(X.prototype,"mount_fs",X.prototype.mount_fs);X.prototype.create_file=async function(a,b){var c=this.fs9p;if(c){var d=a.split("/");d=d[d.length-1];a=c.SearchPath(a).parentid;if(""!==d&&-1!==a)await c.CreateBinaryFile(d,a,b);else return Promise.reject(new ic)}}; +H.exportProperty(X.prototype,"create_file",X.prototype.create_file);X.prototype.read_file=async function(a){var b=this.fs9p;if(b)return(a=await b.read_file(a))?a:Promise.reject(new ic)};H.exportProperty(X.prototype,"read_file",X.prototype.read_file); +X.prototype.automatically=function(a){const b=c=>{const d=c[0];if(d){var e=c.slice(1);d.sleep?setTimeout(()=>b(e),1E3*d.sleep):d.vga_text?this.wait_until_vga_screen_contains(d.vga_text).then(()=>b(e)):d.keyboard_send?(Array.isArray(d.keyboard_send)?this.keyboard_send_scancodes(d.keyboard_send):this.keyboard_send_text(d.keyboard_send),b(e)):d.call&&(d.call(),b(e))}};b(a)}; +X.prototype.wait_until_vga_screen_contains=function(a){return new Promise(b=>{function c(f){return"string"===typeof a?f.includes(a):a.test(f)}function d(f){[f]=f;e.add(f)}for(const f of this.screen_adapter.get_text_screen())if(c(f)){b(!0);return}const e=new Set,g=()=>{for(const f of e){const h=this.screen_adapter.get_text_row(f);if(c(h)){this.remove_listener("screen-put-char",d);b();return}}e.clear();setTimeout(g,100)};g();this.add_listener("screen-put-char",d)})}; +X.prototype.read_memory=function(a,b){return this.v86.cpu.read_blob(a,b)};X.prototype.write_memory=function(a,b){this.v86.cpu.write_blob(a,b)};X.prototype.set_serial_container_xtermjs=function(a){this.serial_adapter&&this.serial_adapter.destroy&&this.serial_adapter.destroy();this.serial_adapter=new ac(a,this.bus);this.serial_adapter.show()};function jc(a){this.message=a||"File already exists"}jc.prototype=Error.prototype;function ic(a){this.message=a||"File not found"}ic.prototype=Error.prototype;var kc={Connector:function(a){this.listeners={};this.pair=a;a.addEventListener("message",function(b){b=b.data;for(var c=this.listeners[b[0]],d=0;d{this.channel.postMessage(c)};this.bus.register(this.bus_send_msgid,this.nic_to_hub_fn,this);this.hub_to_nic_fn=c=>{this.bus.send(this.bus_recv_msgid,c.data)};this.channel.addEventListener("message",this.hub_to_nic_fn)} +dc.prototype.destroy=function(){this.is_open&&(this.bus.unregister(this.bus_send_msgid,this.nic_to_hub_fn),this.channel.removeEventListener("message",this.hub_to_nic_fn),this.channel.close(),this.is_open=!1)};const lc=(new Date("1970-01-01T00:00:00Z")).getTime(),mc=(new Date("1900-01-01T00:00:00Z")).getTime(),nc=lc-mc,oc=Math.pow(2,32),pc=[118,56,54];function qc(a){return[0,1,2,3,4,5].map(b=>a[b].toString(16)).map(b=>1===b.length?"0"+b:b).join(":")}function rc(a){return a[0]<<24|a[1]<<16|a[2]<<8|a[3]} +class sc{constructor(a,b){a=Math.min(a,16);this.maximum_capacity=b?Math.max(b,a):0;this.length=this.head=this.tail=0;this.buffer=new Uint8Array(a)}write(a){const b=a.length;var c=this.length+b;let d=this.buffer.length;if(dthis.maximum_capacity)throw Error("stream capacity overflow in GrowableRingbuffer.write(), package dropped");c=new Uint8Array(d);this.peek(c);this.tail=0;this.head=this.length;this.buffer=c}c=this.buffer;const e=this.head+b;if(e>d){const g= +d-this.head;c.set(a.subarray(0,g),this.head);c.set(a.subarray(g))}else c.set(a,this.head);this.head=e%d;this.length+=b}peek(a){const b=Math.min(this.length,a.length);if(b){const e=this.buffer;var c=e.length,d=this.tail+b;d>c?(d%=c,c-=this.tail,a.set(e.subarray(this.tail)),a.set(e.subarray(0,d),c)):a.set(e.subarray(this.tail,d))}return b}remove(a){a>this.length&&(a=this.length);a&&(this.tail=(this.tail+a)%this.buffer.length,this.length-=a);return a}} +function tc(){const a=new Uint8Array(1518),b=a.buffer,c=a.byteOffset;return{eth_frame:a,eth_frame_view:new DataView(b),eth_payload_view:new DataView(b,c+14,1500),ipv4_payload_view:new DataView(b,c+34,1480),udp_payload_view:new DataView(b,c+42,1472),text_encoder:new TextEncoder}}function uc(a,b,c,d){d.eth_frame.set(b,c.byteOffset+a);return b.length} +function vc(a,b,c,d){const e=c.byteOffset+(a&-2);d=d.eth_frame;for(c=c.byteOffset;c>16;)b=(b&65535)+(b>>16);return~b&65535} +function wc(a,b){a.eth_frame.fill(0);var c=a.eth_frame,d=c.subarray,e=a.eth_frame_view;uc(0,b.eth.dest,e,a);uc(6,b.eth.src,e,a);e.setUint16(12,b.eth.ethertype);e=14;if(b.arp){var g=a.eth_payload_view;g.setUint16(0,b.arp.htype);g.setUint16(2,b.arp.ptype);g.setUint8(4,b.arp.sha.length);g.setUint8(5,b.arp.spa.length);g.setUint16(6,b.arp.oper);uc(8,b.arp.sha,g,a);uc(14,b.arp.spa,g,a);uc(18,b.arp.tha,g,a);uc(24,b.arp.tpa,g,a);e+=28}else if(b.ipv4){g=a.eth_payload_view;var f=20;if(b.icmp){var h=a.ipv4_payload_view; +h.setUint8(0,b.icmp.type);h.setUint8(1,b.icmp.code);h.setUint16(2,0);var l=4+uc(4,b.icmp.data,h,a);h.setUint16(2,vc(l,0,h,a));f+=l}else if(b.udp){h=a.ipv4_payload_view;var m=8;if(b.dhcp){l=m;var n=a.udp_payload_view;n.setUint8(0,b.dhcp.op);n.setUint8(1,b.dhcp.htype);n.setUint8(2,b.dhcp.hlen);n.setUint8(3,b.dhcp.hops);n.setUint32(4,b.dhcp.xid);n.setUint16(8,b.dhcp.secs);n.setUint16(10,b.dhcp.flags);n.setUint32(12,b.dhcp.ciaddr);n.setUint32(16,b.dhcp.yiaddr);n.setUint32(20,b.dhcp.siaddr);n.setUint32(24, +b.dhcp.giaddr);uc(28,b.dhcp.chaddr,n,a);n.setUint32(236,1669485411);m=240;for(var p of b.dhcp.options)m+=uc(m,p,n,a);l+=m}else if(b.dns){p=m;m=a.udp_payload_view;m.setUint16(0,b.dns.id);m.setUint16(2,b.dns.flags);m.setUint16(4,b.dns.questions.length);m.setUint16(6,b.dns.answers.length);let A=12;for(var q=0;q{c={eth:{ethertype:2048,src:b.router_mac,dest:a.eth.src},ipv4:{proto:17,src:b.router_ip,dest:a.ipv4.src},udp:{sport:53,dport:a.udp.sport,data:new Uint8Array(await c.arrayBuffer())}};b.receive(wc(b.eth_encoder_buf,c))});return!0} +function yc(a,b){let c={};c.eth={ethertype:2048,src:b.router_mac,dest:a.eth.src};c.ipv4={proto:17,src:b.router_ip,dest:b.vm_ip};c.udp={sport:67,dport:68};c.dhcp={htype:1,hlen:6,hops:0,xid:a.dhcp.xid,secs:0,flags:0,ciaddr:0,yiaddr:rc(b.vm_ip),siaddr:rc(b.router_ip),giaddr:rc(b.router_ip),chaddr:a.dhcp.chaddr};let d=[],e=a.dhcp.options.find(function(g){return 53===g[0]});e&&3===e[2]&&(a.dhcp.op=3);1===a.dhcp.op&&(c.dhcp.op=2,d.push(new Uint8Array([53,1,2])));3===a.dhcp.op&&(c.dhcp.op=2,d.push(new Uint8Array([53, +1,5])),d.push(new Uint8Array([51,4,8,0,0,0])));a=[b.router_ip[0],b.router_ip[1],b.router_ip[2],b.router_ip[3]];d.push(new Uint8Array([1,4,255,255,255,0]));b.masquerade&&(d.push(new Uint8Array([3,4].concat(a))),d.push(new Uint8Array([6,4].concat(a))));d.push(new Uint8Array([54,4].concat(a)));d.push(new Uint8Array([60,3].concat(pc)));d.push(new Uint8Array([255,0]));c.dhcp.options=d;b.receive(wc(b.eth_encoder_buf,c))} +function zc(a,b){let c={};var d=(new DataView(a.buffer,a.byteOffset,a.byteLength)).getUint16(12),e={ethertype:d,dest:a.subarray(0,6),dest_s:qc(a.subarray(0,6)),src:a.subarray(6,12),src_s:qc(a.subarray(6,12))};c.eth=e;a=a.subarray(14,a.length);if(2048===d){var g=new DataView(a.buffer,a.byteOffset,a.byteLength),f=a[0]>>4&15;e=a[0]&15;var h=g.getUint8(1),l=g.getUint16(2);let m=g.getUint8(8);d=g.getUint8(9);g=g.getUint16(10);f={version:f,ihl:e,tos:h,len:l,ttl:m,proto:d,ip_checksum:g,src:a.subarray(12, +16),dest:a.subarray(16,20)};c.ipv4=f;e=a.subarray(4*e,l);if(1===d)a=new DataView(e.buffer,e.byteOffset,e.byteLength),a={type:a.getUint8(0),code:a.getUint8(1),checksum:a.getUint16(2),data:e.subarray(4)},c.icmp=a;else if(6===d)d=new DataView(e.buffer,e.byteOffset,e.byteLength),a={sport:d.getUint16(0),dport:d.getUint16(2),seq:d.getUint32(4),ackn:d.getUint32(8),doff:d.getUint8(12)>>4,winsize:d.getUint16(14),checksum:d.getUint16(16),urgent:d.getUint16(18)},d=d.getUint8(13),a.fin=!!(d&1),a.syn=!!(d&2), +a.rst=!!(d&4),a.psh=!!(d&8),a.ack=!!(d&16),a.urg=!!(d&32),a.ece=!!(d&64),a.cwr=!!(d&128),c.tcp=a,c.tcp_data=e.subarray(4*a.doff);else if(17===d){a=new DataView(e.buffer,e.byteOffset,e.byteLength);a={sport:a.getUint16(0),dport:a.getUint16(2),len:a.getUint16(4),checksum:a.getUint16(6),data:e.subarray(8),data_s:(new TextDecoder).decode(e.subarray(8))};if(67===a.dport||67===a.sport){e=e.subarray(8);d=new DataView(e.buffer,e.byteOffset,e.byteLength);e.subarray(44,236);d={op:d.getUint8(0),htype:d.getUint8(1), +hlen:d.getUint8(2),hops:d.getUint8(3),xid:d.getUint32(4),secs:d.getUint16(8),flags:d.getUint16(10),ciaddr:d.getUint32(12),yiaddr:d.getUint32(16),siaddr:d.getUint32(20),giaddr:d.getUint32(24),chaddr:e.subarray(28,44),magic:d.getUint32(236),options:[]};e=e.subarray(240);for(l=0;l++h&&b.tcp_conn[f]);if(b.tcp_conn[f])throw Error("pool of dynamic TCP port numbers exhausted, connection aborted");let l,m,n,p,q=new Cc;q.net=b;q.on_data=function(A){l&&l.call(r,A)};q.on_connect=function(){m&&m.call(r)};q.on_close=function(){n&&n.call(r)};q.on_shutdown=function(){p&&p.call(r)};q.tuple=f;q.hsrc=b.router_mac;q.psrc=b.router_ip; +q.sport=g;q.hdest=b.vm_mac;q.dport=a;q.pdest=b.vm_ip;b.tcp_conn[f]=q;q.connect();let r={write:function(A){q.write(A)},on:function(A,w){"data"===A&&(l=w);"connect"===A&&(m=w);"close"===A&&(n=w);"shutdown"===A&&(p=w)},close:function(){q.close()}};return r}function Cc(){this.state="closed";this.net=null;this.send_buffer=new sc(2048,0);this.send_chunk_buf=new Uint8Array(1460);this.delayed_send_fin=this.in_active_close=!1;this.delayed_state=void 0} +Cc.prototype.ipv4_reply=function(){let a={};a.eth={ethertype:2048,src:this.hsrc,dest:this.hdest};a.ipv4={proto:6,src:this.psrc,dest:this.pdest};a.tcp={sport:this.sport,dport:this.dport,winsize:this.winsize,ackn:this.ack,seq:this.seq,ack:!0};return a};Cc.prototype.packet_reply=function(a,b){a={sport:a.tcp.dport,dport:a.tcp.sport,winsize:a.tcp.winsize,ackn:this.ack,seq:this.seq};if(b)for(const c in b)a[c]=b[c];b=this.ipv4_reply();b.tcp=a;return b}; +Cc.prototype.connect=function(){this.seq=1338;this.ack=1;this.start_seq=0;this.winsize=64240;this.state="syn-sent";let a=this.ipv4_reply();a.ipv4.id=2345;a.tcp={sport:this.sport,dport:this.dport,seq:1337,ackn:0,winsize:0,syn:!0};this.net.receive(wc(this.net.eth_encoder_buf,a))}; +Cc.prototype.accept=function(a){this.seq=1338;this.ack=a.tcp.seq+1;this.start_seq=a.tcp.seq;this.hsrc=this.net.router_mac;this.psrc=a.ipv4.dest;this.sport=a.tcp.dport;this.hdest=a.eth.src;this.dport=a.tcp.sport;this.pdest=a.ipv4.src;this.winsize=a.tcp.winsize;let b=this.ipv4_reply();b.tcp={sport:this.sport,dport:this.dport,seq:1337,ackn:this.ack,winsize:a.tcp.winsize,syn:!0,ack:!0};this.state="established";this.net.receive(wc(this.net.eth_encoder_buf,b))}; +Cc.prototype.process=function(a){if("closed"===this.state)a=this.packet_reply(a,{rst:!0}),this.net.receive(wc(this.net.eth_encoder_buf,a));else if(a.tcp.rst)this.on_close(),this.release();else if(a.tcp.syn)"syn-sent"===this.state&&a.tcp.ack&&(this.ack=a.tcp.seq+1,this.start_seq=a.tcp.seq,this.last_received_ackn=a.tcp.ackn,a=this.ipv4_reply(),this.net.receive(wc(this.net.eth_encoder_buf,a)),this.state="established",this.on_connect&&this.on_connect.call(this));else{if(a.tcp.ack)if("syn-received"=== +this.state)this.state="established";else if("fin-wait-1"===this.state)a.tcp.fin||(this.state="fin-wait-2");else if("closing"===this.state||"last-ack"===this.state){this.release();return}if(void 0===this.last_received_ackn)this.last_received_ackn=a.tcp.ackn;else{var b=a.tcp.ackn-this.last_received_ackn;if(0b){a=this.packet_reply(a,{rst:!0});this.net.receive(wc(this.net.eth_encoder_buf,a));this.on_close();this.release();return}}a.tcp.fin?(++this.ack,b=this.packet_reply(a,{}),"established"===this.state?(b.tcp.ack=!0,this.state="close-wait",this.on_shutdown()):"fin-wait-1"===this.state?(a.tcp.ack?this.release():this.state="closing",b.tcp.ack=!0):"fin-wait-2"===this.state?(this.release(),b.tcp.ack=!0):(this.release(), +this.on_close(),b.tcp.rst=!0),this.net.receive(wc(this.net.eth_encoder_buf,b))):this.ack!==a.tcp.seq?(a=this.packet_reply(a,{ack:!0}),this.net.receive(wc(this.net.eth_encoder_buf,a))):a.tcp.ack&&0{this.process_incoming_wisp_frame(new Uint8Array(b.data))};this.wispws.onclose=()=>{setTimeout(()=>{this.register_ws(a)},1E4)}}; +ec.prototype.send_packet=function(a,b,c){this.connections[c]&&(0{0!==d.length&&this.send_wisp_frame({type:"DATA",stream_id:c.stream_id,data:d})};c.on_close=()=>{this.send_wisp_frame({type:"CLOSE",stream_id:c.stream_id,reason:2})};c.on_shutdown=c.on_close;this.send_wisp_frame({type:"CONNECT",stream_id:c.stream_id,hostname:a.ipv4.dest.join("."),port:a.tcp.dport,data_callback:d=>{c.write(d)},close_callback:()=> +{c.close()}});c.accept(a);return!0};ec.prototype.send=function(a){zc(a,this)};ec.prototype.receive=function(a){this.bus.send("net"+this.id+"-receive",new Uint8Array(a))};function cc(a,b){b=b||{};this.bus=a;this.id=b.id||0;this.router_mac=new Uint8Array((b.router_mac||"52:54:0:1:2:3").split(":").map(function(c){return parseInt(c,16)}));this.router_ip=new Uint8Array((b.router_ip||"192.168.86.1").split(".").map(function(c){return parseInt(c,10)}));this.vm_ip=new Uint8Array((b.vm_ip||"192.168.86.100").split(".").map(function(c){return parseInt(c,10)}));this.masquerade=void 0===b.masquerade||!!b.masquerade;this.vm_mac=new Uint8Array(6);this.dns_method=b.dns_method||"static"; +this.doh_server=b.doh_server;this.tcp_conn={};this.eth_encoder_buf=tc();this.fetch=(...args)=>fetch(...args);this.cors_proxy=b.cors_proxy;this.bus.register("net"+this.id+"-mac",function(c){this.vm_mac=new Uint8Array(c.split(":").map(function(d){return parseInt(d,16)}))},this);this.bus.register("net"+this.id+"-send",function(c){this.send(c)},this)}H.exportSymbol("FetchNetworkAdapter",cc);cc.prototype.destroy=function(){}; +cc.prototype.on_tcp_connection=function(a,b){if(80===a.tcp.dport){let c=new Cc;c.state="syn-received";c.net=this;c.on_data=Dc;c.tuple=b;c.accept(a);this.tcp_conn[b]=c;return!0}return!1};cc.prototype.connect=function(a){return Bc(a,this)}; +async function Dc(a){this.read=this.read||"";if((this.read+=(new TextDecoder).decode(a))&&-1!==this.read.indexOf("\r\n\r\n")){var b=this.read.indexOf("\r\n\r\n");a=this.read.substring(0,b).split(/\r\n/);b=this.read.substring(b+4);this.read="";let c=a[0].split(" "),d;d=/^https?:/.test(c[1])?new URL(c[1]):new URL("http://host"+c[1]);"undefined"!==typeof window&&"http:"===d.protocol&&"https:"===window.location.protocol&&(d.protocol="https:");let e=new Headers;for(let l=1;l{const m=[`HTTP/1.1 ${l.status} ${l.statusText}`, +`x-was-fetch-redirected: ${!!l.redirected}`,`x-fetch-resp-url: ${l.url}`,"Connection: closed"];for(const [n,p]of l.headers.entries())["content-encoding","connection","content-length","transfer-encoding"].includes(n.toLowerCase())||m.push(`${n}: ${p}`);this.write(f.encode(m.join("\r\n")+"\r\n\r\n"));h=!0;if(l.body&&l.body.getReader){const n=l.body.getReader(),p=({value:q,done:r})=>{q&&this.write(q);if(r)this.close();else return n.read().then(p)};n.read().then(p)}else l.arrayBuffer().then(n=>{this.write(new Uint8Array(n)); +this.close()})}).catch(l=>{console.warn("Fetch Failed: "+g+"\n"+l);h||(l=f.encode(`Fetch ${g} failed:\n\n${l.stack||l.message}`),this.writev([f.encode(["HTTP/1.1 502 Fetch Error","Content-Type: text/plain",`Content-Length: ${l.length}`,"Connection: closed"].join("\r\n")+"\r\n\r\n"),l]));this.close()})}} +cc.prototype.fetch=async function(a,b){this.cors_proxy&&(a=this.cors_proxy+encodeURIComponent(a));try{const c=await fetch(a,b),d=await c.arrayBuffer();return[c,d]}catch(c){return console.warn("Fetch Failed: "+a+"\n"+c),b=new Headers,b.set("Content-Type","text/plain"),[{status:502,statusText:"Fetch Error",headers:b},(new TextEncoder).encode(`Fetch ${a} failed:\n\n${c.stack}`).buffer]}}; +cc.prototype.parse_http_header=function(a){var b=a.match(/^([^:]*):(.*)$/);if(b&&(a=b[1],b=b[2].trim(),0!==a.length&&0!==b.length&&/^[\w-]+$/.test(a)&&/^[\x20-\x7E]+$/.test(b)))return{key:a,value:b}};cc.prototype.send=function(a){zc(a,this)};cc.prototype.receive=function(a){this.bus.send("net"+this.id+"-receive",new Uint8Array(a))};const Ec={stats_to_string:function(a){return Ec.print_misc_stats(a)+Ec.print_instruction_counts(a)},print_misc_stats:function(a){let b="";var c="COMPILE COMPILE_SKIPPED_NO_NEW_ENTRY_POINTS COMPILE_WRONG_ADDRESS_SPACE COMPILE_CUT_OFF_AT_END_OF_PAGE COMPILE_WITH_LOOP_SAFETY COMPILE_PAGE COMPILE_PAGE/COMPILE COMPILE_BASIC_BLOCK COMPILE_DUPLICATED_BASIC_BLOCK COMPILE_WASM_BLOCK COMPILE_WASM_LOOP COMPILE_DISPATCHER COMPILE_ENTRY_POINT COMPILE_WASM_TOTAL_BYTES COMPILE_WASM_TOTAL_BYTES/COMPILE_PAGE RUN_INTERPRETED RUN_INTERPRETED_NEW_PAGE RUN_INTERPRETED_PAGE_HAS_CODE RUN_INTERPRETED_PAGE_HAS_ENTRY_AFTER_PAGE_WALK RUN_INTERPRETED_NEAR_END_OF_PAGE RUN_INTERPRETED_DIFFERENT_STATE RUN_INTERPRETED_DIFFERENT_STATE_CPL3 RUN_INTERPRETED_DIFFERENT_STATE_FLAT RUN_INTERPRETED_DIFFERENT_STATE_IS32 RUN_INTERPRETED_DIFFERENT_STATE_SS32 RUN_INTERPRETED_MISSED_COMPILED_ENTRY_RUN_INTERPRETED RUN_INTERPRETED_STEPS RUN_FROM_CACHE RUN_FROM_CACHE_STEPS RUN_FROM_CACHE_STEPS/RUN_FROM_CACHE RUN_FROM_CACHE_STEPS/RUN_INTERPRETED_STEPS DIRECT_EXIT INDIRECT_JUMP INDIRECT_JUMP_NO_ENTRY NORMAL_PAGE_CHANGE NORMAL_FALLTHRU NORMAL_FALLTHRU_WITH_TARGET_BLOCK NORMAL_BRANCH NORMAL_BRANCH_WITH_TARGET_BLOCK CONDITIONAL_JUMP CONDITIONAL_JUMP_PAGE_CHANGE CONDITIONAL_JUMP_EXIT CONDITIONAL_JUMP_FALLTHRU CONDITIONAL_JUMP_FALLTHRU_WITH_TARGET_BLOCK CONDITIONAL_JUMP_BRANCH CONDITIONAL_JUMP_BRANCH_WITH_TARGET_BLOCK DISPATCHER_SMALL DISPATCHER_LARGE LOOP LOOP_SAFETY CONDITION_OPTIMISED CONDITION_UNOPTIMISED CONDITION_UNOPTIMISED_PF CONDITION_UNOPTIMISED_UNHANDLED_L CONDITION_UNOPTIMISED_UNHANDLED_LE FAILED_PAGE_CHANGE SAFE_READ_FAST SAFE_READ_SLOW_PAGE_CROSSED SAFE_READ_SLOW_NOT_VALID SAFE_READ_SLOW_NOT_USER SAFE_READ_SLOW_IN_MAPPED_RANGE SAFE_WRITE_FAST SAFE_WRITE_SLOW_PAGE_CROSSED SAFE_WRITE_SLOW_NOT_VALID SAFE_WRITE_SLOW_NOT_USER SAFE_WRITE_SLOW_IN_MAPPED_RANGE SAFE_WRITE_SLOW_READ_ONLY SAFE_WRITE_SLOW_HAS_CODE SAFE_READ_WRITE_FAST SAFE_READ_WRITE_SLOW_PAGE_CROSSED SAFE_READ_WRITE_SLOW_NOT_VALID SAFE_READ_WRITE_SLOW_NOT_USER SAFE_READ_WRITE_SLOW_IN_MAPPED_RANGE SAFE_READ_WRITE_SLOW_READ_ONLY SAFE_READ_WRITE_SLOW_HAS_CODE PAGE_FAULT TLB_MISS MAIN_LOOP MAIN_LOOP_IDLE DO_MANY_CYCLES CYCLE_INTERNAL INVALIDATE_ALL_MODULES_NO_FREE_WASM_INDICES INVALIDATE_MODULE_WRITTEN_WHILE_COMPILED INVALIDATE_MODULE_UNUSED_AFTER_OVERWRITE INVALIDATE_MODULE_DIRTY_PAGE INVALIDATE_PAGE_HAD_CODE INVALIDATE_PAGE_HAD_ENTRY_POINTS DIRTY_PAGE_DID_NOT_HAVE_CODE RUN_FROM_CACHE_EXIT_SAME_PAGE RUN_FROM_CACHE_EXIT_NEAR_END_OF_PAGE RUN_FROM_CACHE_EXIT_DIFFERENT_PAGE CLEAR_TLB FULL_CLEAR_TLB TLB_FULL TLB_GLOBAL_FULL MODRM_SIMPLE_REG MODRM_SIMPLE_REG_WITH_OFFSET MODRM_SIMPLE_CONST_OFFSET MODRM_COMPLEX SEG_OFFSET_OPTIMISED SEG_OFFSET_NOT_OPTIMISED SEG_OFFSET_NOT_OPTIMISED_ES SEG_OFFSET_NOT_OPTIMISED_FS SEG_OFFSET_NOT_OPTIMISED_GS SEG_OFFSET_NOT_OPTIMISED_NOT_FLAT".split(" "), +d=0;const e={};for(let f=0;f>20)+"m\n";b=b+"Config:\nJIT_DISABLED="+(a.wm.exports.get_jit_config(0)+"\n");b+="MAX_PAGES="+a.wm.exports.get_jit_config(1)+"\n";b+="JIT_USE_LOOP_SAFETY="+!!a.wm.exports.get_jit_config(2)+"\n";return b+="MAX_EXTRA_BASIC_BLOCKS="+a.wm.exports.get_jit_config(3)+"\n"},print_instruction_counts:function(a){return[Ec.print_instruction_counts_offset(a, +!1,!1,!1,!1),Ec.print_instruction_counts_offset(a,!0,!1,!1,!1),Ec.print_instruction_counts_offset(a,!1,!0,!1,!1),Ec.print_instruction_counts_offset(a,!1,!1,!0,!1),Ec.print_instruction_counts_offset(a,!1,!1,!1,!0)].join("\n\n")},print_instruction_counts_offset:function(a,b,c,d,e){let g="";var f=[],h=b?"compiled":c?"jit exit":d?"unguarded register":e?"wasm size":"executed";for(let n=0;256>n;n++)for(let p=0;8>p;p++)for(const q of[!1,!0]){var l=a.wm.exports.get_opstats_buffer(b,c,d,e,n,!1,q,p);f.push({opcode:n, +count:l,is_mem:q,fixed_g:p});l=a.wm.exports.get_opstats_buffer(b,c,d,e,n,!0,q,p);f.push({opcode:3840|n,count:l,is_mem:q,fixed_g:p})}a=0;b=new Set([38,46,54,62,100,101,102,103,240,242,243]);for(const {count:n,opcode:p}of f)b.has(p)||(a+=n);if(0===a)return"";c=new Uint32Array(256);b=new Uint32Array(256);for(const {opcode:n,count:p}of f)3840===(n&65280)?b[n&255]+=p:c[n&255]+=p;g=g+"------------------\nTotal: "+(a+"\n");const m=1E7Math.round(n/m)));d= +String(d).length;g+=`Instruction counts ${h} (in ${m}):\n`;for(e=0;256>e;e++)g+=e.toString(16).padStart(2,"0")+":"+k.pads(Math.round(c[e]/m),d),g=15===e%16?g+"\n":g+" ";g=g+"\n"+`Instruction counts ${h} (0f, in ${m}):\n`;for(h=0;256>h;h++)g+=(h&255).toString(16).padStart(2,"0")+":"+k.pads(Math.round(b[h]/m),d),g=15===h%16?g+"\n":g+" ";g+="\n";f=f.filter(({count:n})=>n).sort(({count:n},{count:p})=>p-n);for(const {opcode:n,is_mem:p,fixed_g:q,count:r}of f.slice(0,200))f=n.toString(16)+"_"+q+(p?"_m": +"_r"),g+=f+":"+(r/a*100).toFixed(2)+" ";return g+"\n"}};H.exportSymbol("print_stats",Ec);function gc(){this.filedata=new Map}gc.prototype.read=async function(a,b,c){return(a=this.filedata.get(a))?a.subarray(b,b+c):null};gc.prototype.cache=async function(a,b){this.filedata.set(a,b)};gc.prototype.uncache=function(a){this.filedata.delete(a)};function hc(a,b){b.endsWith("/")||(b+="/");this.storage=a;this.baseurl=b}hc.prototype.load_from_server=function(a){return new Promise(b=>{k.load_file(this.baseurl+a,{done:async c=>{c=new Uint8Array(c);await this.cache(a,c);b(c)}})})}; +hc.prototype.read=async function(a,b,c){const d=await this.storage.read(a,b,c);return d?d:(await this.load_from_server(a)).subarray(b,b+c)};hc.prototype.cache=async function(a,b){return await this.storage.cache(a,b)};hc.prototype.uncache=function(a){this.storage.uncache(a)};var ia=32768,fa=16384,ja=4;function Z(a,b){this.inodes=[];this.events=[];this.storage=a;this.qidcounter=b||{last_qidnumber:0};this.inodedata={};this.total_size=274877906944;this.used_size=0;this.mounts=[];this.CreateDirectory("",-1)}Z.prototype.get_state=function(){let a=[];a[0]=this.inodes;a[1]=this.qidcounter.last_qidnumber;a[2]=[];for(const [b,c]of Object.entries(this.inodedata))0===(this.inodes[b].mode&fa)&&a[2].push([b,c]);a[3]=this.total_size;a[4]=this.used_size;return a=a.concat(this.mounts)}; +Z.prototype.set_state=function(a){this.inodes=a[0].map(b=>{const c=new Fc(0);c.set_state(b);return c});this.qidcounter.last_qidnumber=a[1];this.inodedata={};for(let [b,c]of a[2])c.buffer.byteLength!==c.byteLength&&(c=c.slice()),this.inodedata[b]=c;this.total_size=a[3];this.used_size=a[4];this.mounts=a.slice(5)};Z.prototype.AddEvent=function(a,b){var c=this.inodes[a];0===c.status||2===c.status?b():this.is_forwarder(c)?this.follow_fs(c).AddEvent(c.foreign_id,b):this.events.push({id:a,OnEvent:b})}; +Z.prototype.HandleEvent=function(a){var b=this.inodes[a];this.is_forwarder(b)&&this.follow_fs(b).HandleEvent(b.foreign_id);b=[];for(var c=0;c>8;this.qid.version=a[11];this.qid.path=a[12];this.nlinks=a[13]}; +Z.prototype.divert=function(a,b){const c=this.Search(a,b),d=this.inodes[c],e=new Fc(-1);this.IsDirectory(c);Object.assign(e,d);const g=this.inodes.length;this.inodes.push(e);e.fid=g;this.is_forwarder(d)&&this.mounts[d.mount_id].backtrack.set(d.foreign_id,g);this.should_be_linked(d)&&(this.unlink_from_dir(a,b),this.link_under_dir(a,g,b));if(this.IsDirectory(c)&&!this.is_forwarder(d))for(const [f,h]of e.direntries)"."!==f&&".."!==f&&this.IsDirectory(h)&&this.inodes[h].direntries.set("..",g);this.inodedata[g]= +this.inodedata[c];delete this.inodedata[c];d.direntries=new Map;d.nlinks=0;return g};Z.prototype.copy_inode=function(a,b){Object.assign(b,a,{fid:b.fid,direntries:b.direntries,nlinks:b.nlinks})};Z.prototype.CreateInode=function(){const a=Math.round(Date.now()/1E3),b=new Fc(++this.qidcounter.last_qidnumber);b.atime=b.ctime=b.mtime=a;return b}; +Z.prototype.CreateDirectory=function(a,b){var c=this.inodes[b];if(0<=b&&this.is_forwarder(c))return b=c.foreign_id,a=this.follow_fs(c).CreateDirectory(a,b),this.create_forwarder(c.mount_id,a);c=this.CreateInode();c.mode=511|fa;0<=b&&(c.uid=this.inodes[b].uid,c.gid=this.inodes[b].gid,c.mode=this.inodes[b].mode&511|fa);c.qid.type=fa>>8;this.PushInode(c,b,a);this.NotifyListeners(this.inodes.length-1,"newdir");return this.inodes.length-1}; +Z.prototype.CreateFile=function(a,b){var c=this.inodes[b];if(this.is_forwarder(c))return b=c.foreign_id,a=this.follow_fs(c).CreateFile(a,b),this.create_forwarder(c.mount_id,a);c=this.CreateInode();c.uid=this.inodes[b].uid;c.gid=this.inodes[b].gid;c.qid.type=ia>>8;c.mode=this.inodes[b].mode&438|ia;this.PushInode(c,b,a);this.NotifyListeners(this.inodes.length-1,"newfile");return this.inodes.length-1}; +Z.prototype.CreateNode=function(a,b,c,d){var e=this.inodes[b];if(this.is_forwarder(e))return b=e.foreign_id,a=this.follow_fs(e).CreateNode(a,b,c,d),this.create_forwarder(e.mount_id,a);e=this.CreateInode();e.major=c;e.minor=d;e.uid=this.inodes[b].uid;e.gid=this.inodes[b].gid;e.qid.type=192;e.mode=this.inodes[b].mode&438;this.PushInode(e,b,a);return this.inodes.length-1}; +Z.prototype.CreateSymlink=function(a,b,c){var d=this.inodes[b];if(this.is_forwarder(d))return b=d.foreign_id,a=this.follow_fs(d).CreateSymlink(a,b,c),this.create_forwarder(d.mount_id,a);d=this.CreateInode();d.uid=this.inodes[b].uid;d.gid=this.inodes[b].gid;d.qid.type=160;d.symlink=c;d.mode=40960;this.PushInode(d,b,a);return this.inodes.length-1}; +Z.prototype.CreateTextFile=async function(a,b,c){var d=this.inodes[b];if(this.is_forwarder(d))return b=d.foreign_id,c=await this.follow_fs(d).CreateTextFile(a,b,c),this.create_forwarder(d.mount_id,c);d=this.CreateFile(a,b);b=this.inodes[d];a=new Uint8Array(c.length);b.size=c.length;for(b=0;bf)return f}var h=this.inodes[e],l=this.inodes[a];f=this.inodes[c];if(this.is_forwarder(l)||this.is_forwarder(f))if(this.is_forwarder(l)&&l.mount_id===f.mount_id){if(a=await this.follow_fs(l).Rename(l.foreign_id,b,f.foreign_id,d),0>a)return a}else{if(this.is_a_root(e)||!this.IsDirectory(e)&&1f)return f;await this.DeleteData(l);a=this.Unlink(a,b);if(0>a)return a}else this.unlink_from_dir(a,b),this.link_under_dir(c,e,d),h.qid.version++;this.NotifyListeners(e,"rename",{oldpath:g});return 0}; +Z.prototype.Write=async function(a,b,c,d){this.NotifyListeners(a,"write");var e=this.inodes[a];if(this.is_forwarder(e))a=e.foreign_id,await this.follow_fs(e).Write(a,b,c,d);else{var g=await this.get_buffer(a);!g||g.lengthb.nlinks&&x.Debug("Error in filesystem: negative nlinks="+b.nlinks+" at id ="+a);if(this.IsDirectory(a)){b=this.GetInode(a);this.IsDirectory(a)&&0>this.GetParent(a)&&x.Debug("Error in filesystem: negative parent id "+a);for(const [c,d]of b.direntries){0===c.length&&x.Debug("Error in filesystem: inode with no name and id "+d);for(const e of c)32>e&&x.Debug("Error in filesystem: Unallowed char in filename")}}}}; +Z.prototype.FillDirectory=function(a){var b=this.inodes[a];if(this.is_forwarder(b))this.follow_fs(b).FillDirectory(b.foreign_id);else{var c=0;for(const d of b.direntries.keys())c+=24+Hc.encode(d).length;a=this.inodedata[a]=new Uint8Array(c);b.size=c;c=0;for(const [d,e]of b.direntries)b=this.GetInode(e),c+=t.Marshall(["Q","d","b","s"],[b.qid,c+13+8+1+2+Hc.encode(d).length,b.mode>>12,d],a,c)}}; +Z.prototype.RoundToDirentry=function(a,b){a=this.inodedata[a];if(b>=a.length)return a.length;let c=0;for(;;){const d=t.Unmarshall(["Q","d"],a,{offset:c})[1];if(d>b)break;c=d}return c};Z.prototype.IsDirectory=function(a){a=this.inodes[a];return this.is_forwarder(a)?this.follow_fs(a).IsDirectory(a.foreign_id):(a.mode&61440)===fa}; +Z.prototype.IsEmpty=function(a){a=this.inodes[a];if(this.is_forwarder(a))return this.follow_fs(a).IsDirectory(a.foreign_id);for(const b of a.direntries.keys())if("."!==b&&".."!==b)return!1;return!0};Z.prototype.GetChildren=function(a){this.IsDirectory(a);a=this.inodes[a];if(this.is_forwarder(a))return this.follow_fs(a).GetChildren(a.foreign_id);const b=[];for(const c of a.direntries.keys())"."!==c&&".."!==c&&b.push(c);return b}; +Z.prototype.GetParent=function(a){this.IsDirectory(a);a=this.inodes[a];if(this.should_be_linked(a))return a.direntries.get("..");const b=this.follow_fs(a).GetParent(a.foreign_id);return this.get_forwarder(a.mount_id,b)}; +Z.prototype.PrepareCAPs=function(a){a=this.GetInode(a);if(a.caps)return a.caps.length;a.caps=new Uint8Array(20);a.caps[0]=0;a.caps[1]=0;a.caps[2]=0;a.caps[3]=2;a.caps[4]=255;a.caps[5]=255;a.caps[6]=255;a.caps[7]=255;a.caps[8]=255;a.caps[9]=255;a.caps[10]=255;a.caps[11]=255;a.caps[12]=63;a.caps[13]=0;a.caps[14]=0;a.caps[15]=0;a.caps[16]=63;a.caps[17]=0;a.caps[18]=0;a.caps[19]=0;return a.caps.length};function Ic(a){this.fs=a;this.backtrack=new Map} +Ic.prototype.get_state=function(){const a=[];a[0]=this.fs;a[1]=[...this.backtrack];return a};Ic.prototype.set_state=function(a){this.fs=a[0];this.backtrack=new Map(a[1])};Z.prototype.set_forwarder=function(a,b,c){const d=this.inodes[a];this.is_forwarder(d)&&this.mounts[d.mount_id].backtrack.delete(d.foreign_id);d.status=5;d.mount_id=b;d.foreign_id=c;this.mounts[b].backtrack.set(c,a)}; +Z.prototype.create_forwarder=function(a,b){const c=this.CreateInode(),d=this.inodes.length;this.inodes.push(c);c.fid=d;this.set_forwarder(d,a,b);return d};Z.prototype.is_forwarder=function(a){return 5===a.status};Z.prototype.is_a_root=function(a){return 0===this.GetInode(a).fid};Z.prototype.get_forwarder=function(a,b){const c=this.mounts[a].backtrack.get(b);return void 0===c?this.create_forwarder(a,b):c};Z.prototype.delete_forwarder=function(a){this.is_forwarder(a);a.status=-1;this.mounts[a.mount_id].backtrack.delete(a.foreign_id)}; +Z.prototype.follow_fs=function(a){const b=this.mounts[a.mount_id];this.is_forwarder(a);return b.fs};Z.prototype.Mount=function(a,b){a=this.SearchPath(a);if(-1===a.parentid)return-2;if(-1!==a.id)return-17;if(a.forward_path){var c=this.inodes[a.parentid];b=this.follow_fs(c).Mount(a.forward_path,b);return 0>b?b:this.get_forwarder(c.mount_id,b)}c=this.mounts.length;this.mounts.push(new Ic(b));b=this.create_forwarder(c,0);this.link_under_dir(a.parentid,b,a.name);return b}; +function Gc(){this.type=2;this.start=0;this.length=Infinity;this.proc_id=-1;this.client_id=""}Gc.prototype.get_state=function(){const a=[];a[0]=this.type;a[1]=this.start;a[2]=Infinity===this.length?0:this.length;a[3]=this.proc_id;a[4]=this.client_id;return a};Gc.prototype.set_state=function(a){this.type=a[0];this.start=a[1];this.length=0===a[2]?Infinity:a[2];this.proc_id=a[3];this.client_id=a[4]};Gc.prototype.clone=function(){const a=new Gc;a.set_state(this.get_state());return a}; +Gc.prototype.conflicts_with=function(a){return this.proc_id===a.proc_id&&this.client_id===a.client_id||2===this.type||2===a.type||1!==this.type&&1!==a.type||this.start+this.length<=a.start||a.start+a.length<=this.start?!1:!0};Gc.prototype.is_alike=function(a){return a.proc_id===this.proc_id&&a.client_id===this.client_id&&a.type===this.type};Gc.prototype.may_merge_after=function(a){return this.is_alike(a)&&a.start+a.length===this.start}; +Z.prototype.DescribeLock=function(a,b,c,d,e){const g=new Gc;g.type=a;g.start=b;g.length=c;g.proc_id=d;g.client_id=e;return g};Z.prototype.GetLock=function(a,b){a=this.inodes[a];if(this.is_forwarder(a)){var c=a.foreign_id;return this.follow_fs(a).GetLock(c,b)}for(c of a.locks)if(b.conflicts_with(c))return c.clone();return null}; +Z.prototype.Lock=function(a,b,c){const d=this.inodes[a];if(this.is_forwarder(d))return a=d.foreign_id,this.follow_fs(d).Lock(a,b,c);b=b.clone();if(2!==b.type&&this.GetLock(a,b))return 1;for(c=0;c=g&&0=g&&(d.locks.splice(c,1),c--)}if(2!==b.type){c=b;a=!1;for(e=0;e"."!==b&&".."!==b)};Z.prototype.read_file=function(a){a=this.SearchPath(a);if(-1===a.id)return Promise.resolve(null);const b=this.GetInode(a.id);return this.Read(a.id,0,b.size)};var x={Debug:function(a){[].slice.apply(arguments).join(" ")},Abort:function(){}};var t={};const Jc=new TextDecoder,Hc=new TextEncoder; +t.Marshall=function(a,b,c,d){for(var e,g=0,f=0;f>8&255;c[d++]=e>>16&255;c[d++]=e>>24&255;g+=4;break;case "d":c[d++]=e&255;c[d++]=e>>8&255;c[d++]=e>>16&255;c[d++]=e>>24&255;c[d++]=0;c[d++]=0;c[d++]=0;c[d++]=0;g+=8;break;case "h":c[d++]=e&255;c[d++]=e>>8;g+=2;break;case "b":c[d++]=e;g+=1;break;case "s":var h=d,l=0;c[d++]=0;c[d++]=0;g+=2;e=Hc.encode(e);g+=e.byteLength;l+=e.byteLength;c.set(e,d);d+=e.byteLength;c[h+0]=l&255;c[h+1]=l>>8& +255;break;case "Q":t.Marshall(["b","w","d"],[e.type,e.version,e.path],c,d);d+=13;g+=13;break;default:x.Debug("Marshall: Unknown type="+a[f])}return g}; +t.Unmarshall=function(a,b,c){let d=c.offset;for(var e=[],g=0;g>>0;e.push(f);break;case "d":f=b[d++];f+=b[d++]<<8;f+=b[d++]<<16;f+=b[d++]<<24>>>0;d+=4;e.push(f);break;case "h":f=b[d++];e.push(f+(b[d++]<<8));break;case "b":e.push(b[d++]);break;case "s":f=b[d++];f+=b[d++]<<8;var h=b.slice(d,d+f);d+=f;e.push(Jc.decode(h));break;case "Q":c.offset=d;f=t.Unmarshall(["b","w","d"],b,c);d=c.offset;e.push({type:f[0],version:f[1], +path:f[2]});break;default:x.Debug("Error in Unmarshall: Unknown type="+a[g])}c.offset=d;return e};}).call(this); diff --git a/src/renderer/smb/README.md b/src/renderer/smb/README.md new file mode 100644 index 0000000..ff9b229 --- /dev/null +++ b/src/renderer/smb/README.md @@ -0,0 +1,91 @@ +# SMB1 server for Windows 95 + +Zero-dependency SMB1/CIFS server that lets Windows 95 (running inside v86) mount +a host folder as a network drive. Read-only. ~1500 lines. + +## Stack + +| Layer | File | What it does | +|---|---|---| +| Ethernet/IP/UDP | `nbns.ts` | Taps `bus.register("net0-send")` for raw frames, parses UDP 137, builds reply frames manually | +| NetBIOS Name Service | `nbns.ts` | Answers Node Status (0x21) and Name Query (0x20) — Win95 won't try TCP until this resolves | +| TCP 139 hook | `index.ts` | Monkeypatches `adapter.on_tcp_connection` (old v86) or registers `tcp-connection` bus event (new v86) | +| NetBIOS Session | `netbios.ts` | RFC 1002 framing — 4-byte header, reassembles fragmented TCP | +| SMB1 wire | `wire.ts`, `smb.ts` | Little-endian Reader/Writer, header parse/build | +| Commands | `server.ts` | NEGOTIATE, SESSION_SETUP, TREE_CONNECT, TRANSACTION (RAP), TRANSACTION2, SEARCH, OPEN, READ, CLOSE, etc. | + +## Protocol gotchas (learned the hard way) + +### NEGOTIATE: don't pick NT LM 0.12 unless you implement the NT response +Win95 offers `["PC NETWORK PROGRAM 1.0", "MICROSOFT NETWORKS 3.0", "DOS LM1.2X002", +"DOS LANMAN2.1", "Windows for Workgroups 3.1a", "NT LM 0.12"]`. We send the +13-word LANMAN-style negotiate response. If you pick `NT LM 0.12` and send 13 +words, Win95 silently drops the connection — it expects the 17-word NT response +with capability flags. Pick `DOS LANMAN2.1` instead. + +### SEARCH (0x81): single-file probes vs wildcard listings +`SEARCH "\FOO.TXT"` is a stat probe — Win95 wants exactly one entry back. If you +prepend `.` and `..` like you would for `\*`, Win95 reads the first entry (`.`, +attr=DIRECTORY) and treats `FOO.TXT` as a folder. Only prepend dots when the +pattern contains `*` or `?`. + +### SEARCH filename: null-terminate before padding +The 13-byte name field must be `name\0\0\0...`, not `name \0`. Space-padding +before the null means Win95 sees `FOO.BAT ` (with trailing spaces) and can't +match the `.BAT` file association. + +### 8.3 mapping needs `~N` suffixes, not just truncation +84 files in a real Downloads folder → most have long names → naive truncation +gives 30 copies of `15_UNDER.PDF`. Use Windows-style `~N` and keep a per-dir +SFN→real-name map so OPEN can find the actual file. `resolve()` walks each path +component through the map. + +### RAP (TRANSACTION 0x25): Win95 loops until ServerGetInfo answers +After `TREE_CONNECT \\HOST\IPC$`, Win95 sends RAP NetShareEnum (func=0, `WrLeh`/ +`B13BWz`) then NetWkstaGetInfo (func=63, `WrLh`/`zzzBBzz`) then NetServerGetInfo +(func=13, `WrLh`/`B16BBDz`). The data descriptor tells you the layout: +`B16` = 16-byte inline name, `z` = string pointer (4 bytes into a heap that +follows the struct), `B` = byte, `D` = dword. We synthesize the struct from the +descriptor so any info-level Win95 asks for gets a plausible reply. + +### Virtual files need to be visible to QUERY_INFORMATION too +The injected `_MAPZ.BAT` showed in listings but Win95 stats before opening, +got ERR_BADFILE, said "cannot find". Hook `getVirtual()` into QUERY_INFO and +CHECK_DIRECTORY, not just OPEN. + +## v86 integration (the hard part) + +### Old v86 (Feb 2025 — what currently boots): connection theft +The `tcp-connection` bus event was added later. The old API is +`adapter.on_tcp_connection(packet, tuple)` — you must construct `TCPConnection` +yourself, but it's closure-scoped in Closure-compiled `libv86.js`. Worse, +`.on()`/`.emit()`/`events_handlers` were dead-code-eliminated; the data callback +is a flat `.on_data` property. + +The trick: shadow `adapter.receive` with a no-op (own-prop on a prototype method +— **must** restore via `delete`, not reassignment), call the original handler +with a fake port-80 SYN, take the `TCPConnection` it builds, re-aim it at port +139. `accept(packet)` overwrites all routing fields (sport/dport/hsrc/psrc/seq/ +ack), `.on_data = handler` replaces the HTTP callback. + +### New v86: just `bus.register("tcp-connection")` +Clean API. The new code keeps both paths; the bus event is a no-op on old builds. + +### Exception in a bus listener kills the emulator +`bus.send` doesn't catch listener exceptions. They bubble through ne2k → +`port_write8` → wasm. Win95 freezes. The corrupted state then gets saved by +`onbeforeunload`. Wrap everything that runs in a callback. + +## Security +- Read-only. +- Path traversal blocked lexically (`../`) AND through symlinks: `realpathSync` + the deepest existing ancestor, re-append the unresolved tail, confirm under + root. Symlinks pointing inside the share still work; symlinks pointing out + return ERR_BADFILE. +- Share path validated in main-process IPC (`realpathSync` + `isDirectory()`). + +## Tests +`test-standalone.ts` — 35 protocol tests, full round-trips with real file I/O. +Run: `npx tsc --ignoreConfig --module commonjs --target es2020 --esModuleInterop +--moduleResolution bundler --outDir /tmp/smb-test --skipLibCheck +src/renderer/smb/*.ts && node /tmp/smb-test/test-standalone.js` diff --git a/src/renderer/smb/index.ts b/src/renderer/smb/index.ts new file mode 100644 index 0000000..a4ff22a --- /dev/null +++ b/src/renderer/smb/index.ts @@ -0,0 +1,193 @@ +// Glue: hook v86's TCP-connection bus event for port 139 and bridge it to +// our SMB server. Windows 95 connects via NetBIOS-over-TCP — ethernet frame +// → ne2k → fake_network's userspace TCP/IP → tcp-connection event with a +// stream-like TCPConnection object. +// +// To use: in emulator.tsx after `new V86()`, call +// setupSmbShare(window.emulator, "/Users/you/share") +// Then inside Win95: Start → Run → \\192.168.86.1\host + +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; +import { NetBIOSFramer, nbPositiveResponse, nbWrap } from "./netbios"; +import { setupNbns } from "./nbns"; +import { SmbSession } from "./server"; + +// SPIKE diagnostics: tee everything to a file so we can debug without DevTools +const LOG_FILE = path.join(os.tmpdir(), "windows95-smb.log"); +try { fs.writeFileSync(LOG_FILE, `--- ${new Date().toISOString()} ---\n`); } catch {} +const origLog = console.log; +console.log = (...args: unknown[]) => { + origLog(...args); + const tag = String(args[0] ?? ""); + if (tag === "[smb]" || tag === "[nbns]") { + try { + fs.appendFileSync(LOG_FILE, args.map(a => + typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\n"); + } catch {} + } +}; + +interface TCPConnection { + sport: number; + tuple: string; + state: string; + net: unknown; + on(event: "data", handler: (data: Uint8Array) => void): void; + write(data: Uint8Array): void; + accept(packet?: unknown): void; + close(): void; +} + +interface NetworkAdapter { + tcp_conn: Record; + on_tcp_connection?: (packet: any, tuple: string) => boolean; + router_mac: Uint8Array; + router_ip: Uint8Array; +} + +interface V86 { + bus: { + register(name: string, fn: (arg: unknown) => void, ctx?: unknown): void; + }; + network_adapter?: NetworkAdapter; +} + +const log = (...a: unknown[]) => console.log("[smb]", ...a); + +export function setupSmbShare(emulator: V86, hostPath: string) { + log(`serving ${hostPath} on \\\\HOST\\host (port 139)`); + + // SPIKE diagnostic: count every ethernet frame so we know if the NIC is + // emitting anything at all (DHCP, ARP, anything). Logged on a timer so + // we don't flood — and so the absence of a tick proves the bus is dead. + let frameStats = { total: 0, arp: 0, ip: 0, udp: 0, tcp: 0, other: 0 }; + emulator.bus.register("net0-send", (raw: unknown) => { + const f = raw as Uint8Array; + frameStats.total++; + if (f.length < 14) { frameStats.other++; return; } + const et = (f[12] << 8) | f[13]; + if (et === 0x0806) frameStats.arp++; + else if (et === 0x0800) { + frameStats.ip++; + const proto = f[14 + 9]; + if (proto === 6) frameStats.tcp++; + else if (proto === 17) frameStats.udp++; + } else frameStats.other++; + }); + setInterval(() => { + if (frameStats.total > 0) { + log("frames:", JSON.stringify(frameStats)); + frameStats = { total: 0, arp: 0, ip: 0, udp: 0, tcp: 0, other: 0 }; + } + }, 5000); + + // Win95 won't even try TCP 139 until UDP 137 answers a Node Status query + setupNbns(emulator as Parameters[0]); + + // ─── TCP 139 hook ─────────────────────────────────────────────────────── + // v86 has two APIs depending on age: + // new (2025+): bus event "tcp-connection" with a pre-built conn + // old (≤Feb 2025): adapter.on_tcp_connection(packet, tuple) callback + // where we must construct TCPConnection ourselves + // We can't `new TCPConnection()` directly (closure-scoped), so for the + // old API we steal the constructor from the prototype of any existing + // connection — which means we need a probe HTTP connection to fire first + // (or we wait for one). The fetch adapter itself uses the constructor for + // port 80, so as soon as anything in Win95 hits HTTP, we can steal it. + + const wireConn = (conn: TCPConnection) => { + log(`← TCP SYN ${conn.tuple}`); + const framer = new NetBIOSFramer(); + const session = new SmbSession(hostPath); + + const handler = (data: Uint8Array) => { + for (const msg of framer.push(data)) { + if (msg.type === 0x81) { + log("← NB session request → +response"); + conn.write(nbPositiveResponse()); + } else if (msg.type === 0x00) { + const reply = session.handle(msg.payload); + if (reply) conn.write(nbWrap(reply)); + } + } + }; + + // New v86 has .on(); old v86 had .on/.emit dead-code-eliminated by + // Closure into a flat .on_data callback property. Check for the method + // first, fall back to direct assignment. + if (typeof (conn as any).on === "function") { + conn.on("data", handler); + } else { + (conn as any).on_data = handler; + } + }; + + // New API: bus event (no-op on old v86 — event never fires) + emulator.bus.register("tcp-connection", (c: unknown) => { + const conn = c as TCPConnection; + if (conn.sport !== 139) return; + wireConn(conn); + conn.accept(); + }); + + // Old API: monkey-patch adapter.on_tcp_connection. The adapter is created + // inside V86's async init, so poll for it. + // + // Instead of stealing the TCPConnection constructor (closure-scoped, brittle + // with new-on-stolen-ctor), we make the original handler build one for us + // by handing it a port-80 SYN — then RECONFIGURE that connection for 139. + // accept(packet) overwrites every routing field (sport/dport/hsrc/etc), and + // .on("data") overwrites the HTTP handler. The probe's fake SYN-ACK is eaten + // by shadowing adapter.receive (prototype method — `delete` to restore). + const tryHook = () => { + const adapter = emulator.network_adapter; + if (!adapter || typeof adapter.on_tcp_connection !== "function") return false; + + const orig = adapter.on_tcp_connection.bind(adapter); + adapter.on_tcp_connection = function (packet: any, tuple: string): boolean { + if (packet.tcp.dport !== 139) return orig(packet, tuple); + + const adapterAny = adapter as any; + adapterAny.receive = () => {}; + let conn: TCPConnection | undefined; + try { + const fakeTuple = "__nbt__"; + orig({ ...packet, tcp: { ...packet.tcp, dport: 80 } }, fakeTuple); + conn = adapter.tcp_conn[fakeTuple]; + delete adapter.tcp_conn[fakeTuple]; + } finally { + delete adapterAny.receive; + } + + if (!conn) { + log("⚠ probe didn't yield a connection; RST"); + return false; + } + + // Re-aim it at port 139. accept() overwrites sport/dport/hsrc/psrc/seq/ack + // from the packet; .on("data") replaces the HTTP handler (assignment, not + // push). Only state needs explicit reset — the probe accept set it to + // "established" and we want a fresh handshake. + conn.tuple = tuple; + conn.state = "syn-received"; + wireConn(conn); + try { + conn.accept(packet); + } catch (e) { + log("accept threw:", e instanceof Error ? e.message : String(e)); + return false; + } + adapter.tcp_conn[tuple] = conn; + return true; + }; + log("hooked adapter.on_tcp_connection (old API, conn-recycling)"); + return true; + }; + + if (!tryHook()) { + const poll = setInterval(() => { if (tryHook()) clearInterval(poll); }, 100); + setTimeout(() => clearInterval(poll), 10000); + } +} diff --git a/src/renderer/smb/nbns.ts b/src/renderer/smb/nbns.ts new file mode 100644 index 0000000..fd75fd9 --- /dev/null +++ b/src/renderer/smb/nbns.ts @@ -0,0 +1,258 @@ +// NetBIOS Name Service (RFC 1002, UDP 137). Win95 won't connect to +// \\192.168.86.1 until this answers — even with an IP address it sends a +// Node Status Request to learn our NetBIOS name for the session-layer +// "called name" field. +// +// fake_network.js handles DNS/DHCP/NTP/echo and silently drops everything +// else. We tap net0-send to see raw ethernet frames, parse UDP 137 ourselves, +// and inject replies via net0-receive. + +const ETHERTYPE_IPV4 = 0x0800; +const IPPROTO_UDP = 17; +const NBNS_PORT = 137; + +const NB_NAME = "HOST"; // what shows up in Network Neighborhood +const NB_WORKGROUP = "WORKGROUP"; + +const log = (...a: unknown[]) => console.log("[nbns]", ...a); + +interface V86 { + bus: { + register(name: string, fn: (data: Uint8Array) => void): void; + send(name: string, data: Uint8Array): void; + }; + network_adapter?: { + router_mac: Uint8Array; + router_ip: Uint8Array; + vm_mac: Uint8Array; + vm_ip: Uint8Array; + }; +} + +export function setupNbns(emulator: V86) { + emulator.bus.register("net0-send", (frame: Uint8Array) => { + const r = parseUdp(frame); + if (!r || r.dport !== NBNS_PORT) return; + + const reply = handleNbns(r.payload, emulator); + if (reply) { + const eth = buildUdpFrame(emulator, r, NBNS_PORT, r.sport, reply); + emulator.bus.send("net0-receive", eth); + } + }); + log(`listening on UDP 137 — answering as "${NB_NAME}"`); +} + +// ─── Packet parsing ────────────────────────────────────────────────────────── + +interface UdpPacket { + srcMac: Uint8Array; dstMac: Uint8Array; + srcIp: Uint8Array; dstIp: Uint8Array; + sport: number; dport: number; + payload: Uint8Array; +} + +function parseUdp(frame: Uint8Array): UdpPacket | null { + if (frame.length < 42) return null; + const ethertype = (frame[12] << 8) | frame[13]; + if (ethertype !== ETHERTYPE_IPV4) return null; + + const ip = 14; + const ihl = (frame[ip] & 0x0f) * 4; + if (frame[ip + 9] !== IPPROTO_UDP) return null; + + const udp = ip + ihl; + const sport = (frame[udp] << 8) | frame[udp + 1]; + const dport = (frame[udp + 2] << 8) | frame[udp + 3]; + const len = (frame[udp + 4] << 8) | frame[udp + 5]; + + return { + srcMac: frame.slice(6, 12), + dstMac: frame.slice(0, 6), + srcIp: frame.slice(ip + 12, ip + 16), + dstIp: frame.slice(ip + 16, ip + 20), + sport, dport, + payload: frame.slice(udp + 8, udp + len), + }; +} + +// ─── NBNS protocol ─────────────────────────────────────────────────────────── +// Format is DNS-like. Names are encoded by splitting each byte into two +// nibbles, adding 'A' (0x41) to each — so "HOST " becomes 32 chars. + +const TYPE_NB = 0x0020; // name query → IP +const TYPE_NBSTAT = 0x0021; // node status → name list +const CLASS_IN = 0x0001; + +function handleNbns(data: Uint8Array, emulator: V86): Uint8Array | null { + if (data.length < 12) return null; + const txid = (data[0] << 8) | data[1]; + const flags = (data[2] << 8) | data[3]; + const opcode = (flags >> 11) & 0x0f; + const qdcount = (data[4] << 8) | data[5]; + + if (opcode !== 0 || qdcount < 1) return null; // not a query + + // Parse first question. Name is L1-encoded: length byte (always 32), then + // 32 chars, then 0x00, then type(2) + class(2). + let p = 12; + const nameLen = data[p++]; + if (nameLen !== 32) return null; + const encoded = data.slice(p, p + 32); + p += 32; + if (data[p++] !== 0) return null; // scope terminator + const qtype = (data[p] << 8) | data[p + 1]; p += 2; + /* qclass */ p += 2; + + const name = decodeNbName(encoded); + const adapter = emulator.network_adapter; + if (!adapter) { log("no adapter yet"); return null; } + + log(`← query type=0x${qtype.toString(16)} name="${name}" txid=${txid}`); + + if (qtype === TYPE_NBSTAT) { + // Node Status: "what names are registered on this node?" + // RDATA = num_names(1) + (name(15) + suffix(1) + flags(2)) * N + stats(46) + const names = [ + { name: NB_NAME, suffix: 0x00, flags: 0x0400 }, // workstation, unique, active + { name: NB_NAME, suffix: 0x20, flags: 0x0400 }, // file server, unique, active + { name: NB_WORKGROUP, suffix: 0x00, flags: 0x8400 }, // workgroup, group, active + ]; + const rdata: number[] = [names.length]; + for (const n of names) { + const padded = n.name.padEnd(15, " "); + for (let i = 0; i < 15; i++) rdata.push(padded.charCodeAt(i)); + rdata.push(n.suffix); + rdata.push((n.flags >> 8) & 0xff, n.flags & 0xff); + } + // 46-byte statistics block: 6-byte MAC + 40 bytes of zeros + for (const b of adapter.router_mac) rdata.push(b); + for (let i = 0; i < 40; i++) rdata.push(0); + + return buildNbnsAnswer(txid, encoded, TYPE_NBSTAT, new Uint8Array(rdata)); + } + + if (qtype === TYPE_NB) { + // Name Query: "what IP has this name?" — answer if it's us or wildcard + const trimmed = name.trim().toUpperCase(); + if (trimmed !== NB_NAME && trimmed !== "*") { + return null; // not us — drop, let it time out + } + // RDATA = flags(2) + ip(4) + const rdata = new Uint8Array([ + 0x00, 0x00, // unique, B-node + ...adapter.router_ip, + ]); + return buildNbnsAnswer(txid, encoded, TYPE_NB, rdata); + } + + return null; +} + +function buildNbnsAnswer(txid: number, encodedName: Uint8Array, type: number, + rdata: Uint8Array): Uint8Array { + const out: number[] = []; + const u16 = (v: number) => out.push((v >> 8) & 0xff, v & 0xff); + const u32 = (v: number) => { u16((v >>> 16) & 0xffff); u16(v & 0xffff); }; + + u16(txid); + u16(0x8400); // response + authoritative, opcode=0, rcode=0 + u16(0); // qdcount + u16(1); // ancount + u16(0); u16(0); // ns/ar + + // answer RR: name(L1-encoded) + type + class + ttl + rdlen + rdata + out.push(32); for (const b of encodedName) out.push(b); out.push(0); + u16(type); + u16(CLASS_IN); + u32(300); // TTL 5min + u16(rdata.length); + for (const b of rdata) out.push(b); + + return new Uint8Array(out); +} + +function decodeNbName(enc: Uint8Array): string { + // Each pair of bytes encodes one byte: ((b1-'A')<<4) | (b2-'A') + let s = ""; + for (let i = 0; i < 30; i += 2) { + const hi = enc[i] - 0x41; + const lo = enc[i + 1] - 0x41; + s += String.fromCharCode((hi << 4) | lo); + } + return s; // 15 chars, space-padded; 16th byte (suffix) ignored here +} + +// ─── Ethernet frame building ───────────────────────────────────────────────── + +function buildUdpFrame(emulator: V86, req: UdpPacket, sport: number, + dport: number, payload: Uint8Array): Uint8Array { + const a = emulator.network_adapter!; + // For broadcast queries, reply unicast from router_ip → vm_ip; for + // unicast, just swap. Either way the dest MAC/IP come from the request. + const srcMac = a.router_mac; + const dstMac = req.srcMac; + const srcIp = a.router_ip; + const dstIp = req.srcIp; + + const udpLen = 8 + payload.length; + const ipLen = 20 + udpLen; + const total = 14 + ipLen; + const f = new Uint8Array(total); + + // Ethernet + f.set(dstMac, 0); + f.set(srcMac, 6); + f[12] = ETHERTYPE_IPV4 >> 8; f[13] = ETHERTYPE_IPV4 & 0xff; + + // IPv4 (offset 14) + const ip = 14; + f[ip] = 0x45; // v4, IHL=5 + f[ip + 1] = 0; // DSCP/ECN + f[ip + 2] = ipLen >> 8; f[ip + 3] = ipLen & 0xff; + f[ip + 4] = 0; f[ip + 5] = 0; // ID + f[ip + 6] = 0x40; f[ip + 7] = 0; // DF, no fragment + f[ip + 8] = 64; // TTL + f[ip + 9] = IPPROTO_UDP; + f[ip + 10] = 0; f[ip + 11] = 0; // checksum placeholder + f.set(srcIp, ip + 12); + f.set(dstIp, ip + 16); + const ipck = ipChecksum(f.subarray(ip, ip + 20)); + f[ip + 10] = ipck >> 8; f[ip + 11] = ipck & 0xff; + + // UDP (offset 34) + const udp = ip + 20; + f[udp] = sport >> 8; f[udp + 1] = sport & 0xff; + f[udp + 2] = dport >> 8; f[udp + 3] = dport & 0xff; + f[udp + 4] = udpLen >> 8; f[udp + 5] = udpLen & 0xff; + f[udp + 6] = 0; f[udp + 7] = 0; // checksum placeholder + f.set(payload, udp + 8); + const uck = udpChecksum(srcIp, dstIp, f.subarray(udp, udp + udpLen)); + f[udp + 6] = uck >> 8; f[udp + 7] = uck & 0xff; + + return f; +} + +function ipChecksum(hdr: Uint8Array): number { + let sum = 0; + for (let i = 0; i < hdr.length; i += 2) { + sum += (hdr[i] << 8) | hdr[i + 1]; + } + while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); + return (~sum) & 0xffff; +} + +function udpChecksum(srcIp: Uint8Array, dstIp: Uint8Array, udp: Uint8Array): number { + // pseudo-header: src(4) + dst(4) + zero(1) + proto(1) + udplen(2) + let sum = 0; + const add = (hi: number, lo: number) => { sum += (hi << 8) | lo; }; + add(srcIp[0], srcIp[1]); add(srcIp[2], srcIp[3]); + add(dstIp[0], dstIp[1]); add(dstIp[2], dstIp[3]); + add(0, IPPROTO_UDP); + add(udp.length >> 8, udp.length & 0xff); + for (let i = 0; i < udp.length - 1; i += 2) add(udp[i], udp[i + 1]); + if (udp.length & 1) add(udp[udp.length - 1], 0); + while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); + const ck = (~sum) & 0xffff; + return ck === 0 ? 0xffff : ck; // UDP: zero means "no checksum", so flip +} diff --git a/src/renderer/smb/netbios.ts b/src/renderer/smb/netbios.ts new file mode 100644 index 0000000..5edf04d --- /dev/null +++ b/src/renderer/smb/netbios.ts @@ -0,0 +1,65 @@ +// NetBIOS Session Service (RFC 1002, port 139). All SMB1 traffic from +// Windows 95 is wrapped in these 4-byte-header frames. + +const NB_SESSION_MESSAGE = 0x00; +const NB_SESSION_REQUEST = 0x81; +const NB_POSITIVE_RESPONSE = 0x82; +const NB_SESSION_KEEPALIVE = 0x85; + +export type NBMessage = + | { type: typeof NB_SESSION_MESSAGE; payload: Uint8Array } + | { type: typeof NB_SESSION_REQUEST } + | { type: typeof NB_SESSION_KEEPALIVE }; + +/** + * Reassembles NetBIOS frames from a TCP stream. TCP delivers in + * arbitrary chunks so we buffer until we have a complete frame. + */ +export class NetBIOSFramer { + private buf = new Uint8Array(0); + + push(chunk: Uint8Array): NBMessage[] { + // append + const merged = new Uint8Array(this.buf.length + chunk.length); + merged.set(this.buf); + merged.set(chunk, this.buf.length); + this.buf = merged; + + const out: NBMessage[] = []; + while (this.buf.length >= 4) { + const type = this.buf[0]; + // length is 17-bit: high bit of byte 1, then bytes 2-3 big-endian + const len = ((this.buf[1] & 0x01) << 16) | (this.buf[2] << 8) | this.buf[3]; + const total = 4 + len; + if (this.buf.length < total) break; + + const frame = this.buf.subarray(0, total); + this.buf = this.buf.slice(total); + + if (type === NB_SESSION_REQUEST) { + out.push({ type: NB_SESSION_REQUEST }); + } else if (type === NB_SESSION_MESSAGE) { + out.push({ type: NB_SESSION_MESSAGE, payload: frame.slice(4) }); + } else if (type === NB_SESSION_KEEPALIVE) { + out.push({ type: NB_SESSION_KEEPALIVE }); + } + // anything else: drop + } + return out; + } +} + +export function nbPositiveResponse(): Uint8Array { + return new Uint8Array([NB_POSITIVE_RESPONSE, 0, 0, 0]); +} + +export function nbWrap(payload: Uint8Array): Uint8Array { + const len = payload.length; + const out = new Uint8Array(4 + len); + out[0] = NB_SESSION_MESSAGE; + out[1] = (len >> 16) & 0x01; + out[2] = (len >> 8) & 0xff; + out[3] = len & 0xff; + out.set(payload, 4); + return out; +} diff --git a/src/renderer/smb/server.ts b/src/renderer/smb/server.ts new file mode 100644 index 0000000..c2d0519 --- /dev/null +++ b/src/renderer/smb/server.ts @@ -0,0 +1,1120 @@ +// SMB1 server core. One instance per TCP connection. State is per-session +// (UID/TID/FID tables). Everything is read-only for the spike. + +import * as fs from "fs"; +import * as path from "path"; +import { Reader, Writer } from "./wire"; +import { + parseSmb, buildSmb, dosError, andxNone, cmdName, SmbHeader, + CMD_NEGOTIATE, CMD_SESSION_SETUP_ANDX, CMD_TREE_CONNECT_ANDX, + CMD_TREE_DISCONNECT, CMD_LOGOFF_ANDX, CMD_NT_CREATE_ANDX, CMD_OPEN_ANDX, + CMD_READ_ANDX, CMD_CLOSE, CMD_TRANSACTION, CMD_TRANSACTION2, CMD_ECHO, + CMD_QUERY_INFORMATION, CMD_FIND_CLOSE2, CMD_CHECK_DIRECTORY, CMD_SEARCH, + TRANS2_FIND_FIRST2, TRANS2_FIND_NEXT2, TRANS2_QUERY_PATH_INFO, + ERRDOS, ERRSRV, ERR_BADFILE, ERR_BADPATH, ERR_BADFID, ERR_NOFILES, ERR_BADFUNC, +} from "./smb"; + +const log = (...a: unknown[]) => console.log("[smb]", ...a); +const hex = (b: Uint8Array, n = 64) => + Array.from(b.slice(0, n)).map(x => x.toString(16).padStart(2, "0")).join(" ") + + (b.length > n ? ` …(+${b.length - n})` : ""); + +interface OpenFile { + hostPath: string; + fd: number; + size: number; + isDir: boolean; + virtual?: Uint8Array; +} + +interface DirEntry { + name: string; // real filename (long) + sfn: string; // 8.3 name shown to the client + stat: { isDirectory(): boolean; size: number; mtime: Date }; +} + +interface SearchState { + entries: DirEntry[]; + idx: number; +} + +const ATTR_DIRECTORY = 0x10; +const ATTR_ARCHIVE = 0x20; + +const DIALECTS = [ + // Our negotiate response uses the 13-word LANMAN format, so we MUST NOT + // pick "NT LM 0.12" — Win95 expects the 17-word NT response for that + // dialect and will silently drop a malformed reply. Win95's actual + // dialect strings have a "DOS " prefix (vs the bare names NT/2000 send). + "DOS LANMAN2.1", + "LANMAN2.1", + "Windows for Workgroups 3.1a", + "DOS LM1.2X002", + "LM1.2X002", +]; + +export class SmbSession { + private uid = 0; + private tid = 0; + private nextFid = 1; + private nextSid = 1; + private fids = new Map(); + private sids = new Map(); + // 8.3 → real name, per host directory. SEARCH builds this; OPEN/QUERY + // consult it so clicking "15UNDE~2.PDF" finds the right long-named file. + private sfnMaps = new Map>(); + private readonly realRoot: string; + public capture = true; + + // Synthetic files served at the share root. They show up in directory + // listings and OPEN/READ work, but they don't exist on the host fs — + // just in-memory bytes. _MAPZ.BAT maps the share to Z: when the user + // double-clicks it; copying it to C:\WINDOWS\Start Menu\Programs\StartUp + // makes the mapping survive reboots. + private readonly virtuals = new Map([ + ["_MAPZ.BAT", new TextEncoder().encode( + "@ECHO OFF\r\n" + + "NET USE Z: \\\\HOST\\HOST\r\n" + + "ECHO Share mapped to Z:\r\n" + + "ECHO Copy this file to C:\\WINDOWS\\STARTM~1\\PROGRAMS\\STARTUP\r\n" + + "ECHO to reconnect automatically on every boot.\r\n" + + "PAUSE\r\n" + )], + ]); + + constructor(rootPath: string) { + this.realRoot = fs.realpathSync(rootPath); + } + + private getVirtual(smbPath: string): Uint8Array | undefined { + const p = smbPath.replace(/^[\\\/]+/, "").replace(/\\/g, "/"); + if (p.includes("/")) return undefined; // root-only + return this.virtuals.get(p.toUpperCase()); + } + + /** + * Read a host directory once, generate stable 8.3 names, cache the mapping. + * The cache lives for the session — directory contents changing underneath + * is OK (entries vanish or appear), but the SFN→real mapping for existing + * files stays put so a follow-up OPEN finds the same file SEARCH listed. + */ + private listDir(hostDir: string): DirEntry[] { + const realNames = fs.readdirSync(hostDir); + const sfnMap = buildSfnMap(realNames); + this.sfnMaps.set(hostDir, sfnMap); + + const entries: DirEntry[] = []; + for (const [sfn, real] of sfnMap) { + try { + entries.push({ name: real, sfn, stat: fs.statSync(path.join(hostDir, real)) }); + } catch { /* raced — skip */ } + } + + // Virtuals only at root. They're already 8.3. + if (hostDir === this.realRoot) { + const now = new Date(); + for (const [name, bytes] of this.virtuals) { + entries.unshift({ + name, sfn: name, + stat: { isDirectory: () => false, size: bytes.length, mtime: now }, + }); + } + } + return entries; + } + + /** Main entry: one SMB request → zero or one SMB reply */ + handle(buf: Uint8Array): Uint8Array | null { + const req = parseSmb(buf); + if (!req) { + log("bad SMB magic", hex(buf, 8)); + return null; + } + + if (this.capture) { + log(`← ${cmdName[req.cmd] ?? "0x" + req.cmd.toString(16)} ` + + `tid=${req.tid} uid=${req.uid} mid=${req.mid} ` + + `wc=${req.wordCount} bc=${req.byteCount}`); + if (req.wordCount) log(" words:", hex(req.words)); + if (req.byteCount) log(" bytes:", hex(req.bytes)); + } + + try { + switch (req.cmd) { + case CMD_NEGOTIATE: return this.negotiate(req); + case CMD_SESSION_SETUP_ANDX: return this.sessionSetup(req); + case CMD_TREE_CONNECT_ANDX: return this.treeConnect(req); + case CMD_TREE_DISCONNECT: return this.treeDisconnect(req); + case CMD_LOGOFF_ANDX: return this.logoff(req); + case CMD_NT_CREATE_ANDX: return this.ntCreate(req); + case CMD_OPEN_ANDX: return this.openAndx(req); + case CMD_READ_ANDX: return this.read(req); + case CMD_CLOSE: return this.close(req); + case CMD_TRANSACTION: return this.transRap(req); + case CMD_TRANSACTION2: return this.trans2(req); + case CMD_ECHO: return this.echo(req); + case CMD_QUERY_INFORMATION: return this.queryInfo(req); + case CMD_CHECK_DIRECTORY: return this.checkDirectory(req); + case CMD_FIND_CLOSE2: return this.findClose(req); + case CMD_SEARCH: return this.search(req); + default: + log(`⚠ unhandled cmd 0x${req.cmd.toString(16)}`); + return buildSmb(req, req.cmd, dosError(ERRSRV, ERR_BADFUNC), + new Uint8Array(0), new Uint8Array(0)); + } + } catch (e) { + log("handler threw:", e); + return buildSmb(req, req.cmd, dosError(ERRSRV, 0x02 /* ERRerror */), + new Uint8Array(0), new Uint8Array(0)); + } + } + + // ─────────────────────────────────────────────────────────────────────────── + // NEGOTIATE: client sends a list of dialect strings; we pick one by index. + // ─────────────────────────────────────────────────────────────────────────── + private negotiate(req: SmbHeader): Uint8Array { + // bytes block is: 0x02 \0 0x02 \0 ... + const offered: string[] = []; + let i = 0; + while (i < req.bytes.length) { + if (req.bytes[i] !== 0x02) break; + i++; + let end = i; + while (end < req.bytes.length && req.bytes[end] !== 0) end++; + offered.push(String.fromCharCode(...req.bytes.slice(i, end))); + i = end + 1; + } + log("dialects offered:", offered); + + let pick = -1; + for (const d of DIALECTS) { + const idx = offered.indexOf(d); + if (idx >= 0) { pick = idx; break; } + } + if (pick < 0) { + // refuse — but Win95 always offers at least LANMAN + const w = new Writer().u16(0xffff).build(); + return buildSmb(req, CMD_NEGOTIATE, 0, w, new Uint8Array(0)); + } + + // LM 2.1 / NT-compatible response (13 words). We claim share-level + // security (no challenge), no encryption, modest buffer. + const words = new Writer() + .u16(pick) // DialectIndex + .u16(0x0000) // SecurityMode: share-level, no challenge + .u16(16384) // MaxBufferSize + .u16(1) // MaxMpxCount + .u16(1) // MaxNumberVcs + .u16(0) // RawMode (none) + .u32(0) // SessionKey + .u16(0) // ServerTime (we cheat — Win95 doesn't care) + .u16(0) // ServerDate + .u16(0) // ServerTimeZone + .u16(0) // ChallengeLength = 0 (no challenge → null session) + .u16(0) // reserved + .build(); + + // bytes: empty challenge + domain name (OEM) + const bytes = new Writer().cstr("WORKGROUP").build(); + + return buildSmb(req, CMD_NEGOTIATE, 0, words, bytes); + } + + // ─────────────────────────────────────────────────────────────────────────── + // SESSION_SETUP_ANDX: auth. We accept anything as guest. + // ─────────────────────────────────────────────────────────────────────────── + private sessionSetup(req: SmbHeader): Uint8Array { + this.uid = 1; + const words = new Writer() + .bytes(andxNone()) + .u16(0x0001) // Action: logged in as GUEST + .build(); + const bytes = new Writer() + .cstr("Unix") // NativeOS + .cstr("v86") // NativeLanMan + .cstr("WORKGROUP") + .build(); + return buildSmb(req, CMD_SESSION_SETUP_ANDX, 0, words, bytes, { uid: this.uid }); + } + + // ─────────────────────────────────────────────────────────────────────────── + // TREE_CONNECT_ANDX: connect to a share. We expose one share: HOST → rootPath + // ─────────────────────────────────────────────────────────────────────────── + private treeConnect(req: SmbHeader): Uint8Array { + // words: AndX(4) + Flags(2) + PasswordLength(2) + const wr = new Reader(req.words); + wr.skip(4); wr.skip(2); + const pwLen = wr.u16(); + // bytes: Password(pwLen) + Path\0 + Service\0 + const br = new Reader(req.bytes); + br.skip(pwLen); + const reqPath = (req.flags2 & 0x8000) ? br.ucs2() : br.cstr(); + const service = br.cstr(); + log(`tree connect: path="${reqPath}" service="${service}"`); + + // Accept anything for now — share name extraction is a refinement. + // IPC$ is special (named pipes); we pretend to support it so the + // redirector doesn't bail, but file ops on tid 0xfffe will error out. + const isIpc = /\\IPC\$$/i.test(reqPath); + this.tid = isIpc ? 0xfffe : 1; + + const words = new Writer() + .bytes(andxNone()) + .u16(0x0000) // OptionalSupport + .build(); + // bytes: Service\0 + NativeFileSystem\0 (both OEM) + const bytes = new Writer() + .cstr(isIpc ? "IPC" : "A:") + .cstr(isIpc ? "" : "FAT") + .build(); + return buildSmb(req, CMD_TREE_CONNECT_ANDX, 0, words, bytes, { tid: this.tid }); + } + + private treeDisconnect(req: SmbHeader): Uint8Array { + return buildSmb(req, CMD_TREE_DISCONNECT, 0, new Uint8Array(0), new Uint8Array(0)); + } + + private logoff(req: SmbHeader): Uint8Array { + const words = new Writer().bytes(andxNone()).build(); + return buildSmb(req, CMD_LOGOFF_ANDX, 0, words, new Uint8Array(0)); + } + + private echo(req: SmbHeader): Uint8Array { + const words = new Writer().u16(0).build(); // SequenceNumber + return buildSmb(req, CMD_ECHO, 0, words, req.bytes); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Path resolution: SMB paths are \-separated, leading \, possibly with + // wildcards. The client sends 8.3 names (that's all SEARCH gives it), so + // each component is mapped through the SFN table. Refuses traversal, + // including via symlinks. + // ─────────────────────────────────────────────────────────────────────────── + private resolve(smbPath: string): string | null { + let p = smbPath.replace(/\\/g, "/"); + if (p.startsWith("/")) p = p.slice(1); + + // Walk component-by-component, translating each 8.3 name to its real name. + // Unmapped components pass through verbatim — they might be already-real + // names (if the client somehow learned them) or they'll fail existence + // checks below. + const parts = p ? p.split("/") : []; + let cur = this.realRoot; + for (const part of parts) { + if (!part || part === ".") continue; + const map = this.sfnMaps.get(cur); + const real = map?.get(part.toUpperCase()) ?? part; + cur = path.join(cur, real); + } + const candidate = cur; + + // Lexical check first — fast reject for ../../ without touching disk + const lex = path.relative(this.realRoot, candidate); + if (lex.startsWith("..") || path.isAbsolute(lex)) return null; + + // Symlink check: realpath the deepest existing ancestor, then re-append + // the unresolved tail. This catches a symlink at any level pointing + // outside the share, without requiring the leaf to exist. + let probe = candidate; + let tail = ""; + for (;;) { + try { + probe = fs.realpathSync(probe); + break; + } catch { + const parent = path.dirname(probe); + if (parent === probe) return null; + tail = path.join(path.basename(probe), tail); + probe = parent; + } + } + const real = tail ? path.join(probe, tail) : probe; + + if (real !== this.realRoot && !real.startsWith(this.realRoot + path.sep)) { + return null; + } + return real; + } + + private smbPathFromBytes(req: SmbHeader, offset = 0): string { + const br = new Reader(req.bytes, offset); + // Some commands prefix path with a 0x04 buffer-format byte + if (req.bytes[offset] === 0x04) br.u8(); + return (req.flags2 & 0x8000) ? br.ucs2() : br.cstr(); + } + + // ─────────────────────────────────────────────────────────────────────────── + // QUERY_INFORMATION (0x08): legacy stat-by-path + // ─────────────────────────────────────────────────────────────────────────── + private queryInfo(req: SmbHeader): Uint8Array { + const smbPath = this.smbPathFromBytes(req); + + const v = this.getVirtual(smbPath); + if (v) { + const words = new Writer() + .u16(ATTR_ARCHIVE) + .u32(unixToSmbTime(new Date())) + .u32(v.length) + .zero(10) + .build(); + return buildSmb(req, CMD_QUERY_INFORMATION, 0, words, new Uint8Array(0)); + } + + const hostPath = this.resolve(smbPath); + if (!hostPath || !fs.existsSync(hostPath)) { + return buildSmb(req, CMD_QUERY_INFORMATION, dosError(ERRDOS, ERR_BADFILE), + new Uint8Array(0), new Uint8Array(0)); + } + const st = fs.statSync(hostPath); + const attrs = st.isDirectory() ? ATTR_DIRECTORY : ATTR_ARCHIVE; + const words = new Writer() + .u16(attrs) + .u32(unixToSmbTime(st.mtime)) + .u32(Math.min(st.size, 0xffffffff)) + .zero(10) // reserved + .build(); + return buildSmb(req, CMD_QUERY_INFORMATION, 0, words, new Uint8Array(0)); + } + + private checkDirectory(req: SmbHeader): Uint8Array { + const smbPath = this.smbPathFromBytes(req); + // Virtuals are files — explicitly NOT directories + if (this.getVirtual(smbPath)) { + return buildSmb(req, CMD_CHECK_DIRECTORY, dosError(ERRDOS, ERR_BADPATH), + new Uint8Array(0), new Uint8Array(0)); + } + const hostPath = this.resolve(smbPath); + if (!hostPath || !fs.existsSync(hostPath) || !fs.statSync(hostPath).isDirectory()) { + return buildSmb(req, CMD_CHECK_DIRECTORY, dosError(ERRDOS, ERR_BADPATH), + new Uint8Array(0), new Uint8Array(0)); + } + return buildSmb(req, CMD_CHECK_DIRECTORY, 0, new Uint8Array(0), new Uint8Array(0)); + } + + // ─────────────────────────────────────────────────────────────────────────── + // OPEN_ANDX (0x2d): the older open. Win95 uses this if NT_CREATE fails. + // ─────────────────────────────────────────────────────────────────────────── + private openAndx(req: SmbHeader): Uint8Array { + // words: AndX(4) Flags(2) Access(2) SearchAttrs(2) FileAttrs(2) + // CreateTime(4) OpenFunc(2) AllocSize(4) Timeout(4) Reserved(4) + const smbPath = this.smbPathFromBytes(req); + return this.doOpen(req, CMD_OPEN_ANDX, smbPath); + } + + // ─────────────────────────────────────────────────────────────────────────── + // NT_CREATE_ANDX (0xa2) + // ─────────────────────────────────────────────────────────────────────────── + private ntCreate(req: SmbHeader): Uint8Array { + // words layout: AndX(4) Reserved(1) NameLength(2) Flags(4) RootFID(4) + // DesiredAccess(4) AllocSize(8) ExtAttrs(4) ShareAccess(4) + // CreateDisp(4) CreateOpts(4) Impersonation(4) SecurityFlags(1) + const wr = new Reader(req.words); + wr.skip(4); wr.skip(1); + const nameLen = wr.u16(); + // bytes: filename. NT_CREATE puts a leading pad byte if unicode-aligned; + // since we never claim FLAGS2_UNICODE in our replies, Win95 sticks to OEM. + let off = 0; + // NT_CREATE doesn't use the 0x04 prefix; name is at start (sometimes + // with a single null pad we strip) + if (req.bytes[0] === 0) off = 1; + const nameBytes = req.bytes.slice(off, off + nameLen); + const smbPath = String.fromCharCode(...nameBytes).replace(/\0+$/, ""); + return this.doOpen(req, CMD_NT_CREATE_ANDX, smbPath); + } + + private doOpen(req: SmbHeader, cmd: number, smbPath: string): Uint8Array { + // Virtual root files first — they shadow anything on disk with the same name + const vbytes = this.getVirtual(smbPath); + if (vbytes) { + const fid = this.nextFid++; + this.fids.set(fid, { hostPath: `${smbPath}`, fd: -1, size: vbytes.length, isDir: false, virtual: vbytes }); + log(`open "${smbPath}" → virtual (${vbytes.length} bytes)`); + return this.buildOpenReply(req, cmd, fid, false, vbytes.length, new Date()); + } + + const hostPath = this.resolve(smbPath); + log(`open "${smbPath}" → ${hostPath}`); + if (!hostPath || !fs.existsSync(hostPath)) { + return buildSmb(req, cmd, dosError(ERRDOS, ERR_BADFILE), + new Uint8Array(0), new Uint8Array(0)); + } + const st = fs.statSync(hostPath); + const fid = this.nextFid++; + const isDir = st.isDirectory(); + const fd = isDir ? -1 : fs.openSync(hostPath, "r"); + this.fids.set(fid, { hostPath, fd, size: st.size, isDir }); + return this.buildOpenReply(req, cmd, fid, isDir, st.size, st.mtime); + } + + private buildOpenReply(req: SmbHeader, cmd: number, fid: number, isDir: boolean, size: number, mtime: Date): Uint8Array { + + const sz = Math.min(size, 0xffffffff); + if (cmd === CMD_OPEN_ANDX) { + const words = new Writer() + .bytes(andxNone()) + .u16(fid) + .u16(isDir ? ATTR_DIRECTORY : ATTR_ARCHIVE) + .u32(unixToSmbTime(mtime)) + .u32(sz) + .u16(0) // GrantedAccess: read + .u16(0) // FileType: disk + .u16(0) // DeviceState + .u16(1) // Action: file existed and was opened + .u32(0) // ServerFid + .u16(0) // Reserved + .build(); + return buildSmb(req, cmd, 0, words, new Uint8Array(0)); + } + + // NT_CREATE_ANDX response: 34 words + const words = new Writer() + .bytes(andxNone()) + .u8(0) // OplockLevel + .u16(fid) + .u32(1) // CreateAction: FILE_OPENED + .u64(0) // CreationTime + .u64(0) // LastAccessTime + .u64(0) // LastWriteTime + .u64(0) // ChangeTime + .u32(isDir ? ATTR_DIRECTORY : ATTR_ARCHIVE) // ExtFileAttributes + .u64(sz) // AllocationSize + .u64(sz) // EndOfFile + .u16(0) // FileType: disk + .u16(0) // DeviceState + .u8(isDir ? 1 : 0) // IsDirectory + .build(); + return buildSmb(req, cmd, 0, words, new Uint8Array(0)); + } + + // ─────────────────────────────────────────────────────────────────────────── + // READ_ANDX (0x2e) + // ─────────────────────────────────────────────────────────────────────────── + private read(req: SmbHeader): Uint8Array { + const wr = new Reader(req.words); + wr.skip(4); // AndX + const fid = wr.u16(); + const offset = wr.u32(); + const maxCount = wr.u16(); + // (MinCount, Timeout/MaxCountHigh, Remaining, OffsetHigh — we ignore) + + const file = this.fids.get(fid); + if (!file || file.isDir) { + return buildSmb(req, CMD_READ_ANDX, dosError(ERRDOS, ERR_BADFID), + new Uint8Array(0), new Uint8Array(0)); + } + + const want = Math.min(maxCount, 16384, Math.max(0, file.size - offset)); + let data: Uint8Array; + let nread = 0; + if (file.virtual) { + data = file.virtual.slice(offset, offset + want); + nread = data.length; + } else { + const buf = Buffer.alloc(want); + if (want > 0) nread = fs.readSync(file.fd, buf, 0, want, offset); + data = buf; + } + + // Response data block has a 1-byte pad before the file bytes so DataOffset + // can be aligned. DataOffset is relative to the start of the SMB header. + // header(32) + wc(1) + words(24) + bcc(2) + pad(1) = 60 + const words = new Writer() + .bytes(andxNone()) + .u16(0xffff) // Remaining (legacy, -1 = unknown) + .u16(0) // DataCompactionMode + .u16(0) // Reserved + .u16(nread) // DataLength + .u16(60) // DataOffset + .zero(10) // Reserved + .build(); + const bytes = new Uint8Array(1 + nread); + bytes.set(data.subarray(0, nread), 1); + return buildSmb(req, CMD_READ_ANDX, 0, words, bytes); + } + + private close(req: SmbHeader): Uint8Array { + const wr = new Reader(req.words); + const fid = wr.u16(); + const file = this.fids.get(fid); + if (file) { + if (file.fd >= 0) try { fs.closeSync(file.fd); } catch {} + this.fids.delete(fid); + } + return buildSmb(req, CMD_CLOSE, 0, new Uint8Array(0), new Uint8Array(0)); + } + + // ─────────────────────────────────────────────────────────────────────────── + // SEARCH (0x81): the original DOS-era directory listing. We use this when + // the client picks LANMAN — TRANS2/FIND_FIRST2 came later. 43-byte + // fixed-size entries, 8.3 names only. Win95 calls this for the initial + // listing then drills into folders the same way. + // + // The 21-byte resume key is opaque to the client — we stuff our search + // position into it. + // ─────────────────────────────────────────────────────────────────────────── + private search(req: SmbHeader): Uint8Array { + const wr = new Reader(req.words); + const maxCount = wr.u16(); + wr.u16(); // searchAttrs + + // bytes: 0x04 + path\0 + 0x05 + resumeLen(2) + resumeKey + const br = new Reader(req.bytes); + if (br.u8() !== 0x04) { + return buildSmb(req, CMD_SEARCH, dosError(ERRDOS, ERR_BADFUNC), + new Uint8Array(0), new Uint8Array(0)); + } + const pattern = br.cstr(); + if (br.u8() !== 0x05) { + return buildSmb(req, CMD_SEARCH, dosError(ERRDOS, ERR_BADFUNC), + new Uint8Array(0), new Uint8Array(0)); + } + const resumeLen = br.u16(); + const resume = br.bytes(resumeLen); + + let sid: number, idx: number; + if (resumeLen === 0) { + // First call: parse pattern, do the readdir, stash a search context + const lastSep = Math.max(pattern.lastIndexOf("\\"), pattern.lastIndexOf("/")); + const dirPart = lastSep >= 0 ? pattern.slice(0, lastSep) : ""; + const namePart = lastSep >= 0 ? pattern.slice(lastSep + 1) : pattern; + const hostDir = this.resolve(dirPart || "\\"); + log(`SEARCH "${pattern}" → ${hostDir}`); + if (!hostDir || !fs.existsSync(hostDir)) { + return buildSmb(req, CMD_SEARCH, dosError(ERRDOS, ERR_BADPATH), + new Uint8Array(0), new Uint8Array(0)); + } + const matcher = wildcardMatcher(namePart); + const all = this.listDir(hostDir); + // Match against the SFN — that's what the client sees and asks for + const entries = all.filter(e => matcher(e.sfn)); + // . and .. only for wildcard listings — a single-name SEARCH is a stat + // probe and must return exactly the matching file or nothing. + if (/[*?]/.test(namePart)) { + const dotStat = fs.statSync(hostDir); + entries.unshift( + { name: "..", sfn: "..", stat: dotStat }, + { name: ".", sfn: ".", stat: dotStat }, + ); + } + sid = this.nextSid++; + this.sids.set(sid, { entries, idx: 0 }); + idx = 0; + } else { + // Continuation: pull sid+idx from our resume key (bytes 0-3) + sid = resume[0] | (resume[1] << 8); + idx = resume[2] | (resume[3] << 8); + } + + const ctx = this.sids.get(sid); + if (!ctx || idx >= ctx.entries.length) { + this.sids.delete(sid); + return buildSmb(req, CMD_SEARCH, dosError(ERRDOS, ERR_NOFILES), + new Uint8Array(0), new Uint8Array(0)); + } + + // Each entry is exactly 43 bytes: + // ResumeKey(21) + Attrs(1) + Time(2) + Date(2) + Size(4) + Name(13) + const out = new Writer(); + let count = 0; + while (idx < ctx.entries.length && count < maxCount) { + const e = ctx.entries[idx]; + const nextIdx = idx + 1; + // ResumeKey: first 4 bytes carry our sid+idx; rest is mandated to + // start with reserved(1) + filename(11) — Win95 doesn't actually + // parse it but Samba does it this way so we're consistent. + out.u8(sid & 0xff).u8(sid >> 8).u8(nextIdx & 0xff).u8(nextIdx >> 8); + out.zero(21 - 4); + // Attrs + out.u8(e.stat.isDirectory() ? ATTR_DIRECTORY : ATTR_ARCHIVE); + // Time/Date + const dt = unixToDosDateTime(e.stat.mtime); + out.u16(dt.time).u16(dt.date); + // Size + out.u32(Math.min(e.stat.size, 0xffffffff)); + // Name: 13 bytes total. Null-terminate immediately after the SFN so + // extension parsing stops there. + for (let k = 0; k < e.sfn.length && k < 12; k++) out.u8(e.sfn.charCodeAt(k)); + out.zero(13 - Math.min(e.sfn.length, 12)); + count++; + idx++; + } + ctx.idx = idx; + if (idx >= ctx.entries.length) this.sids.delete(sid); + + // Response: words = Count(2); bytes = 0x05 + DataLength(2) + entries + const words = new Writer().u16(count).build(); + const data = out.build(); + const bytes = new Writer().u8(0x05).u16(data.length).bytes(data).build(); + return buildSmb(req, CMD_SEARCH, 0, words, bytes); + } + + private findClose(req: SmbHeader): Uint8Array { + const wr = new Reader(req.words); + const sid = wr.u16(); + this.sids.delete(sid); + return buildSmb(req, CMD_FIND_CLOSE2, 0, new Uint8Array(0), new Uint8Array(0)); + } + + // ─────────────────────────────────────────────────────────────────────────── + // TRANSACTION2: multiplexed sub-protocol. The setup word holds the + // subcommand; parameters and data are at offsets given in the word block. + // ─────────────────────────────────────────────────────────────────────────── + private trans2(req: SmbHeader): Uint8Array { + // words: TotalParamCount(2) TotalDataCount(2) MaxParamCount(2) + // MaxDataCount(2) MaxSetupCount(1) Reserved(1) Flags(2) Timeout(4) + // Reserved(2) ParamCount(2) ParamOffset(2) DataCount(2) DataOffset(2) + // SetupCount(1) Reserved(1) Setup[SetupCount] + const wr = new Reader(req.words); + wr.skip(2 + 2 + 2 + 2 + 1 + 1 + 2 + 4 + 2); + const paramCount = wr.u16(); + const paramOffset = wr.u16(); + wr.u16(); // dataCount + wr.u16(); // dataOffset + const setupCount = wr.u8(); + wr.u8(); // reserved + const subCmd = setupCount > 0 ? wr.u16() : 0xffff; + + // ParamOffset is from SMB header start; bytes block starts at + // 32 + 1 + wc*2 + 2 = 35 + wc*2 + const bytesStart = 32 + 1 + req.wordCount * 2 + 2; + const paramRel = paramOffset - bytesStart; + const params = req.bytes.slice(paramRel, paramRel + paramCount); + + log(`TRANS2 sub=0x${subCmd.toString(16)} pc=${paramCount}`); + + switch (subCmd) { + case TRANS2_FIND_FIRST2: return this.findFirst(req, params); + case TRANS2_FIND_NEXT2: return this.findNext(req, params); + case TRANS2_QUERY_PATH_INFO: return this.queryPathInfo(req, params); + default: + return buildSmb(req, CMD_TRANSACTION2, dosError(ERRSRV, ERR_BADFUNC), + new Uint8Array(0), new Uint8Array(0)); + } + } + + private findFirst(req: SmbHeader, params: Uint8Array): Uint8Array { + // params: SearchAttrs(2) SearchCount(2) Flags(2) InfoLevel(2) + // SearchStorageType(4) FileName(string) + const pr = new Reader(params); + pr.u16(); // searchAttrs + pr.u16(); // searchCount + pr.u16(); // flags + const infoLevel = pr.u16(); + pr.u32(); // storageType + const pattern = (req.flags2 & 0x8000) ? pr.ucs2() : pr.cstr(); + log(`FIND_FIRST2 level=0x${infoLevel.toString(16)} pattern="${pattern}"`); + + // pattern is like "\dir\*" or "\*" or "\file.txt" + const lastSep = Math.max(pattern.lastIndexOf("\\"), pattern.lastIndexOf("/")); + const dirPart = lastSep >= 0 ? pattern.slice(0, lastSep) : ""; + const namePart = lastSep >= 0 ? pattern.slice(lastSep + 1) : pattern; + const hostDir = this.resolve(dirPart || "\\"); + if (!hostDir || !fs.existsSync(hostDir)) { + return buildSmb(req, CMD_TRANSACTION2, dosError(ERRDOS, ERR_BADPATH), + new Uint8Array(0), new Uint8Array(0)); + } + + const matcher = wildcardMatcher(namePart); + const all = this.listDir(hostDir); + const entries = all.filter(e => matcher(e.sfn) || matcher(e.name)); + if (/[*?]/.test(namePart)) { + const dotStat = fs.statSync(hostDir); + entries.unshift( + { name: "..", sfn: "..", stat: dotStat }, + { name: ".", sfn: ".", stat: dotStat }, + ); + } + + const sid = this.nextSid++; + this.sids.set(sid, { entries, idx: 0 }); + return this.findReply(req, sid, infoLevel, true); + } + + private findNext(req: SmbHeader, params: Uint8Array): Uint8Array { + const pr = new Reader(params); + const sid = pr.u16(); + pr.u16(); // searchCount + const infoLevel = pr.u16(); + // ResumeKey(4) Flags(2) FileName — we just continue from where we left off + return this.findReply(req, sid, infoLevel, false); + } + + private findReply(req: SmbHeader, sid: number, _infoLevel: number, isFirst: boolean): Uint8Array { + const search = this.sids.get(sid); + if (!search || search.idx >= search.entries.length) { + this.sids.delete(sid); + return buildSmb(req, CMD_TRANSACTION2, dosError(ERRDOS, ERR_NOFILES), + new Uint8Array(0), new Uint8Array(0)); + } + + // We return SMB_INFO_STANDARD (level 1) regardless of what was asked — + // Win95 accepts this. Each entry: ResumeKey(4) CreationDate(2) CreationTime(2) + // LastAccessDate(2) LastAccessTime(2) LastWriteDate(2) LastWriteTime(2) + // DataSize(4) AllocationSize(4) Attributes(2) FileNameLength(1) FileName + // Max ~500 bytes per entry batch to keep under our buffer cap. + const data = new Writer(); + let count = 0; + let lastNameOffset = 0; + while (search.idx < search.entries.length && data.length < 8000) { + const e = search.entries[search.idx++]; + const dosDate = unixToDosDateTime(e.stat.mtime); + const sz = Math.min(e.stat.size, 0xffffffff); + const entryStart = data.length; + data.u32(search.idx); // ResumeKey + data.u16(dosDate.date).u16(dosDate.time); // create + data.u16(dosDate.date).u16(dosDate.time); // access + data.u16(dosDate.date).u16(dosDate.time); // write + data.u32(sz); + data.u32(sz); + data.u16(e.stat.isDirectory() ? ATTR_DIRECTORY : ATTR_ARCHIVE); + data.u8(e.name.length); + lastNameOffset = data.length - entryStart; + data.cstr(e.name); + count++; + } + const eos = search.idx >= search.entries.length; + if (eos) this.sids.delete(sid); + + // params reply differs: FIND_FIRST has SID(2), FIND_NEXT doesn't + const pw = new Writer(); + if (isFirst) pw.u16(sid); + pw.u16(count); // SearchCount + pw.u16(eos ? 1 : 0); // EndOfSearch + pw.u16(0); // EaErrorOffset + pw.u16(lastNameOffset); // LastNameOffset + return this.trans2Reply(req, pw.build(), data.build()); + } + + private queryPathInfo(req: SmbHeader, params: Uint8Array): Uint8Array { + // params: InfoLevel(2) Reserved(4) FileName + const pr = new Reader(params); + const level = pr.u16(); + pr.u32(); + const smbPath = (req.flags2 & 0x8000) ? pr.ucs2() : pr.cstr(); + const hostPath = this.resolve(smbPath); + log(`QUERY_PATH_INFO level=0x${level.toString(16)} "${smbPath}"`); + if (!hostPath || !fs.existsSync(hostPath)) { + return buildSmb(req, CMD_TRANSACTION2, dosError(ERRDOS, ERR_BADFILE), + new Uint8Array(0), new Uint8Array(0)); + } + const st = fs.statSync(hostPath); + const dosDate = unixToDosDateTime(st.mtime); + const sz = Math.min(st.size, 0xffffffff); + // SMB_INFO_STANDARD response data: same shape as a find entry minus name + const data = new Writer() + .u16(dosDate.date).u16(dosDate.time) + .u16(dosDate.date).u16(dosDate.time) + .u16(dosDate.date).u16(dosDate.time) + .u32(sz).u32(sz) + .u16(st.isDirectory() ? ATTR_DIRECTORY : ATTR_ARCHIVE) + .build(); + const replyParams = new Writer().u16(0).build(); // EaErrorOffset + return this.trans2Reply(req, replyParams, data); + } + + // ─────────────────────────────────────────────────────────────────────────── + // TRANSACTION (0x25) — RAP over \PIPE\LANMAN. Win95 uses this to enumerate + // shares (NetShareEnum, func=0, descriptor "WrLeh"/"B13BWz") before showing + // the share list under \\HOST. We return our one disk share. + // ─────────────────────────────────────────────────────────────────────────── + private transRap(req: SmbHeader): Uint8Array { + // Same envelope as TRANS2; the name is in the bytes block before params. + const wr = new Reader(req.words); + wr.skip(2 + 2 + 2 + 2 + 1 + 1 + 2 + 4 + 2); + const paramCount = wr.u16(); + const paramOffset = wr.u16(); + wr.u16(); wr.u16(); // dataCount/Offset + const setupCount = wr.u8(); + wr.u8(); + if (setupCount) wr.skip(setupCount * 2); + + const bytesStart = 32 + 1 + req.wordCount * 2 + 2; + + // bytes: TransactionName\0 [pad] params [pad] data + // Win95 sends "\PIPE\LANMAN\0" — we don't bother parsing it. + const params = req.bytes.slice(paramOffset - bytesStart, paramOffset - bytesStart + paramCount); + + // RAP params: func(2) + paramDesc\0 + dataDesc\0 + actual params + const pr = new Reader(params); + const func = pr.u16(); + const paramDesc = pr.cstr(); + const dataDesc = pr.cstr(); + log(`RAP func=${func} pDesc="${paramDesc}" dDesc="${dataDesc}"`); + + // NetWkstaGetInfo (63) / NetServerGetInfo (13) — Win95 calls these before + // rendering the share window. The DATA DESCRIPTOR tells us the layout, + // not the function code: B16=16-byte inline name, z=string pointer, + // B=byte, D=dword. We synthesize the struct from the descriptor so any + // info-level Win95 asks for gets a plausible answer. + if ((func === 13 || func === 63) && paramDesc.startsWith("WrL")) { + const data = buildRapStruct(dataDesc, { + name16: "HOST", + verMajor: 4, verMinor: 0, + // SV_TYPE_WORKSTATION | SV_TYPE_SERVER + dword: 0x00000003, + }); + const replyParams = new Writer() + .u16(0) // NERR_Success + .u16(0) // converter + .u16(data.length) + .build(); + return this.transReply(req, CMD_TRANSACTION, replyParams, data); + } + + if (func === 0 && paramDesc === "WrLeh") { + // NetShareEnum. Data structure per "B13BWz": + // B13 = 13-byte share name (null-padded) + // B = 1-byte pad + // W = 2-byte type (0=disk, 3=IPC) + // z = 4-byte string pointer (we send 0 = no remark) + const shares = [ + { name: "HOST", type: 0 }, + { name: "IPC$", type: 3 }, + ]; + const data = new Writer(); + for (const s of shares) { + const padded = s.name.padEnd(13, "\0"); + for (let i = 0; i < 13; i++) data.u8(padded.charCodeAt(i)); + data.u8(0); // pad + data.u16(s.type); + data.u32(0); // remark pointer: null + } + + // Reply params: status(2) converter(2) entriesRead(2) totalEntries(2) + const replyParams = new Writer() + .u16(0) // NERR_Success + .u16(0) // converter (no string offsets to fix up) + .u16(shares.length) + .u16(shares.length) + .build(); + + return this.transReply(req, CMD_TRANSACTION, replyParams, data.build()); + } + + // Anything else: "not supported" — Win95 falls back gracefully + const replyParams = new Writer() + .u16(50) // ERROR_NOT_SUPPORTED + .u16(0).u16(0).u16(0) + .build(); + return this.transReply(req, CMD_TRANSACTION, replyParams, new Uint8Array(0)); + } + + /** TRANSACTION/TRANS2 share the same reply envelope. */ + private transReply(req: SmbHeader, cmd: number, params: Uint8Array, data: Uint8Array): Uint8Array { + // 10 words + 0 setup, then bytes = pad + params + pad + data + const wc = 10; + const wordBlockSize = 1 + wc * 2 + 2; + const paramOffset = 32 + wordBlockSize; + const dataOffset = paramOffset + params.length; + + const words = new Writer() + .u16(params.length).u16(data.length) + .u16(0) // Reserved + .u16(params.length).u16(paramOffset).u16(0) + .u16(data.length).u16(dataOffset).u16(0) + .u8(0).u8(0) // SetupCount=0, Reserved + .build(); + + const bytes = new Uint8Array(params.length + data.length); + bytes.set(params, 0); + bytes.set(data, params.length); + + return buildSmb(req, cmd, 0, words, bytes); + } + + /** Build the TRANS2 response envelope. Tedious but mechanical. */ + private trans2Reply(req: SmbHeader, params: Uint8Array, data: Uint8Array): Uint8Array { + // 10 words + 1 setup word, then bytes = pad + params + pad + data + // Offsets are from SMB header start (32 bytes before word_count byte). + const wc = 10 + 1; // SetupCount=1 → 1 setup word + const wordBlockSize = 1 + wc * 2 + 2; // wc byte + words + bcc + + // bytes block: pad to align params (we don't bother), params, pad, data + const paramOffset = 32 + wordBlockSize; + const dataOffset = paramOffset + params.length; + + const words = new Writer() + .u16(params.length) // TotalParamCount + .u16(data.length) // TotalDataCount + .u16(0) // Reserved + .u16(params.length) // ParamCount + .u16(paramOffset) // ParamOffset + .u16(0) // ParamDisplacement + .u16(data.length) // DataCount + .u16(dataOffset) // DataOffset + .u16(0) // DataDisplacement + .u8(1) // SetupCount + .u8(0) // Reserved + .u16(0) // Setup[0] + .build(); + + const bytes = new Uint8Array(params.length + data.length); + bytes.set(params, 0); + bytes.set(data, params.length); + + return buildSmb(req, CMD_TRANSACTION2, 0, words, bytes); + } + + destroy() { + for (const f of this.fids.values()) { + if (f.fd >= 0) try { fs.closeSync(f.fd); } catch {} + } + this.fids.clear(); + this.sids.clear(); + } +} + +// ─── helpers ───────────────────────────────────────────────────────────────── + +function wildcardMatcher(pattern: string): (name: string) => boolean { + // SMB wildcards: * = any, ? = one char, also ">"/"<"/"\"" exist but + // Win95 mostly sends *.* or * — collapse *.* → * + const p = pattern.replace(/\*\.\*/, "*"); + if (p === "*" || p === "") return () => true; + if (!/[*?]/.test(p)) return (name) => name.toLowerCase() === p.toLowerCase(); + const re = new RegExp("^" + p.replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "i"); + return (name) => re.test(name); +} + +/** + * Generate a RAP data block from its descriptor string. Each character is a + * field type: B=byte (or B=n bytes inline), W=word, D=dword, z=string + * pointer (4 bytes, points into the heap that follows the struct). We fill + * the first inline-name field with the server name, the first byte pair with + * version, the first dword with flags, and null everything else — Win95 only + * looks at the name and type bits. + */ +function buildRapStruct(desc: string, vals: { + name16: string; verMajor: number; verMinor: number; dword: number; +}): Uint8Array { + const w = new Writer(); + let nameDone = false, bytesUsed = 0, dwordDone = false; + let heapStart = 0; + // First pass: compute struct size so we know where heap (z-strings) starts + let i = 0; + while (i < desc.length) { + const c = desc[i++]; + if (c === "B") { + let n = 1; + const m = desc.slice(i).match(/^\d+/); + if (m) { n = parseInt(m[0]); i += m[0].length; } + heapStart += n; + } else if (c === "W") heapStart += 2; + else if (c === "D") heapStart += 4; + else if (c === "z") heapStart += 4; + } + // Second pass: emit + const heapStrings: string[] = []; + let heapOff = heapStart; + i = 0; + while (i < desc.length) { + const c = desc[i++]; + if (c === "B") { + let n = 1; + const m = desc.slice(i).match(/^\d+/); + if (m) { n = parseInt(m[0]); i += m[0].length; } + if (n >= 13 && !nameDone) { + // Inline name field — null-padded + const padded = vals.name16.padEnd(n, "\0"); + for (let k = 0; k < n; k++) w.u8(padded.charCodeAt(k)); + nameDone = true; + } else if (n === 1) { + // Single bytes — the first two are version major/minor + w.u8(bytesUsed === 0 ? vals.verMajor : bytesUsed === 1 ? vals.verMinor : 0); + bytesUsed++; + } else { + w.zero(n); + } + } else if (c === "W") { + w.u16(0); + } else if (c === "D") { + w.u32(dwordDone ? 0 : vals.dword); + dwordDone = true; + } else if (c === "z") { + // First z gets the name; rest are null + if (!nameDone) { + w.u32(heapOff); + heapStrings.push(vals.name16); + heapOff += vals.name16.length + 1; + nameDone = true; + } else { + w.u32(0); + } + } + } + // Append heap + for (const s of heapStrings) w.cstr(s); + return w.build(); +} + +function unixToSmbTime(d: Date): number { + return Math.floor(d.getTime() / 1000); +} + +function clean83(s: string): string { + return s.replace(/[^A-Za-z0-9_$~!#%&'()@^`{}-]/g, "").toUpperCase(); +} + +/** True if the name already fits 8.3 with no lossy transformation. */ +function fits83(name: string): boolean { + if (name === "." || name === "..") return true; + const dot = name.lastIndexOf("."); + const base = dot > 0 ? name.slice(0, dot) : name; + const ext = dot > 0 ? name.slice(dot + 1) : ""; + return base.length > 0 && base.length <= 8 && ext.length <= 3 && + clean83(base).length === base.length && + clean83(ext).length === ext.length; +} + +/** + * Generate unique 8.3 names (Windows-style ~N suffixes) and build the + * reverse map. Names that already fit 8.3 keep their original form so + * OPEN can resolve them without the map. Everything else gets BASE~N.EXT. + */ +function buildSfnMap(names: string[]): Map { + const sfnToReal = new Map(); + const used = new Set(); + + // First pass: claim natural 8.3 names so they don't collide with mangled ones + for (const real of names) { + if (fits83(real)) { + const sfn = real.toUpperCase(); + sfnToReal.set(sfn, real); + used.add(sfn); + } + } + + // Second pass: mangle the rest with ~N until unique + for (const real of names) { + if (fits83(real)) continue; + const dot = real.lastIndexOf("."); + const baseRaw = dot > 0 ? real.slice(0, dot) : real; + const extRaw = dot > 0 ? real.slice(dot + 1) : ""; + const ext = clean83(extRaw).slice(0, 3); + let base = clean83(baseRaw); + if (base.length === 0) base = "_"; + + // Windows uses 6 chars + ~N for N<10, then 5+~NN, etc. Good enough. + for (let n = 1; ; n++) { + const suffix = `~${n}`; + const stem = base.slice(0, Math.max(1, 8 - suffix.length)) + suffix; + const sfn = ext ? `${stem}.${ext}` : stem; + if (!used.has(sfn)) { + used.add(sfn); + sfnToReal.set(sfn, real); + break; + } + } + } + return sfnToReal; +} + +function unixToDosDateTime(d: Date): { date: number; time: number } { + // DOS date: bits 15-9 year-1980, 8-5 month, 4-0 day + // DOS time: bits 15-11 hour, 10-5 min, 4-0 sec/2 + const y = Math.max(0, d.getFullYear() - 1980); + const date = (y << 9) | ((d.getMonth() + 1) << 5) | d.getDate(); + const time = (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1); + return { date, time }; +} diff --git a/src/renderer/smb/smb.ts b/src/renderer/smb/smb.ts new file mode 100644 index 0000000..81f46c9 --- /dev/null +++ b/src/renderer/smb/smb.ts @@ -0,0 +1,154 @@ +// Minimal SMB1/CIFS implementation — just enough for Windows 95 to map a +// drive and read files. Spec: [MS-CIFS] / [MS-SMB]. +// +// SMB1 message = 32-byte header + word block + byte block. +// Header is at a fixed offset; word/byte blocks vary by command. + +import { Reader, Writer } from "./wire"; + +export const SMB_MAGIC = [0xff, 0x53, 0x4d, 0x42]; // \xFF SMB + +// Commands we handle +export const CMD_NEGOTIATE = 0x72; +export const CMD_SESSION_SETUP_ANDX = 0x73; +export const CMD_TREE_CONNECT_ANDX = 0x75; +export const CMD_TREE_DISCONNECT = 0x71; +export const CMD_LOGOFF_ANDX = 0x74; +export const CMD_NT_CREATE_ANDX = 0xa2; +export const CMD_OPEN_ANDX = 0x2d; +export const CMD_READ_ANDX = 0x2e; +export const CMD_CLOSE = 0x04; +export const CMD_TRANSACTION = 0x25; +export const CMD_TRANSACTION2 = 0x32; +export const CMD_ECHO = 0x2b; +export const CMD_QUERY_INFORMATION = 0x08; +export const CMD_QUERY_INFORMATION2 = 0x23; +export const CMD_FIND_CLOSE2 = 0x34; +export const CMD_CHECK_DIRECTORY = 0x10; +export const CMD_SEARCH = 0x81; + +// TRANS2 subcommands +export const TRANS2_FIND_FIRST2 = 0x01; +export const TRANS2_FIND_NEXT2 = 0x02; +export const TRANS2_QUERY_PATH_INFO = 0x05; +export const TRANS2_QUERY_FILE_INFO = 0x07; + +// Status codes (DOS-style, not NT) +export const STATUS_OK = 0x00000000; +export const ERRDOS = 0x01; +export const ERRSRV = 0x02; +export const ERR_BADFILE = 0x0002; // file not found +export const ERR_BADPATH = 0x0003; // path not found +export const ERR_NOACCESS = 0x0005; +export const ERR_BADFID = 0x0006; +export const ERR_NOFILES = 0x0012; // no more files +export const ERR_BADFUNC = 0x0001; // unsupported + +// Flags +const FLAGS_REPLY = 0x80; +const FLAGS_CASELESS = 0x08; +const FLAGS_CANONICAL = 0x10; + +// Flags2 (we only echo LONG_NAMES; never claim NT_STATUS or UNICODE) +const FLAGS2_LONG_NAMES = 0x0001; + +export interface SmbHeader { + cmd: number; + status: number; + flags: number; + flags2: number; + tid: number; + pid: number; + uid: number; + mid: number; + wordCount: number; + words: Uint8Array; // raw parameter words (wordCount*2 bytes) + byteCount: number; + bytes: Uint8Array; // raw data bytes +} + +export function parseSmb(buf: Uint8Array): SmbHeader | null { + if (buf.length < 33) return null; + if (buf[0] !== 0xff || buf[1] !== 0x53 || buf[2] !== 0x4d || buf[3] !== 0x42) { + return null; + } + const r = new Reader(buf, 4); + const cmd = r.u8(); + const status = r.u32(); + const flags = r.u8(); + const flags2 = r.u16(); + r.skip(12); // PIDHigh(2) + SecurityFeatures(8) + Reserved(2) + const tid = r.u16(); + const pid = r.u16(); + const uid = r.u16(); + const mid = r.u16(); + const wordCount = r.u8(); + const words = r.bytes(wordCount * 2); + const byteCount = r.u16(); + const bytes = r.bytes(byteCount); + return { cmd, status, flags, flags2, tid, pid, uid, mid, wordCount, words, byteCount, bytes }; +} + +/** + * Build an SMB1 reply. The reply echoes tid/pid/uid/mid from the request and + * sets the reply flag. Status uses DOS error class/code in the low bytes + * (we don't set FLAGS2_NT_STATUS). + */ +export function buildSmb( + req: SmbHeader, + cmd: number, + status: number, + words: Uint8Array, + bytes: Uint8Array, + overrides?: { tid?: number; uid?: number; flags2?: number } +): Uint8Array { + const w = new Writer(); + w.bytes(SMB_MAGIC); + w.u8(cmd); + w.u32(status); + w.u8(FLAGS_REPLY | FLAGS_CASELESS | FLAGS_CANONICAL); + // mirror long-name capability so the client keeps sending long names; never + // claim NT status or unicode (we reply in ASCII) + w.u16((overrides?.flags2 ?? req.flags2) & FLAGS2_LONG_NAMES); + w.zero(12); + w.u16(overrides?.tid ?? req.tid); + w.u16(req.pid); + w.u16(overrides?.uid ?? req.uid); + w.u16(req.mid); + if (words.length % 2 !== 0) throw new Error("word block must be even"); + w.u8(words.length / 2); + w.bytes(words); + w.u16(bytes.length); + w.bytes(bytes); + return w.build(); +} + +export function dosError(errClass: number, errCode: number): number { + // DOS-style: byte 0 = class, byte 1 = reserved, bytes 2-3 = code (LE) + return errClass | (errCode << 16); +} + +/** AndX: most replies have a 4-byte AndX header at the start of words */ +export function andxNone(): number[] { + return [0xff, 0x00, 0x00, 0x00]; // AndXCommand=0xFF (none), reserved, offset=0 +} + +export const cmdName: Record = { + [CMD_NEGOTIATE]: "NEGOTIATE", + [CMD_SESSION_SETUP_ANDX]: "SESSION_SETUP", + [CMD_TREE_CONNECT_ANDX]: "TREE_CONNECT", + [CMD_TREE_DISCONNECT]: "TREE_DISCONNECT", + [CMD_LOGOFF_ANDX]: "LOGOFF", + [CMD_NT_CREATE_ANDX]: "NT_CREATE", + [CMD_OPEN_ANDX]: "OPEN", + [CMD_READ_ANDX]: "READ", + [CMD_CLOSE]: "CLOSE", + [CMD_TRANSACTION]: "TRANS(RAP)", + [CMD_TRANSACTION2]: "TRANS2", + [CMD_ECHO]: "ECHO", + [CMD_QUERY_INFORMATION]: "QUERY_INFO", + [CMD_QUERY_INFORMATION2]: "QUERY_INFO2", + [CMD_FIND_CLOSE2]: "FIND_CLOSE2", + [CMD_CHECK_DIRECTORY]: "CHECK_DIR", + [CMD_SEARCH]: "SEARCH", +}; diff --git a/src/renderer/smb/test-standalone.ts b/src/renderer/smb/test-standalone.ts new file mode 100644 index 0000000..7d972bc --- /dev/null +++ b/src/renderer/smb/test-standalone.ts @@ -0,0 +1,308 @@ +// Standalone test of the SMB stack — no v86, no Electron. Feeds canned +// requests through NetBIOSFramer + SmbSession and inspects responses. +// Run: npx ts-node src/renderer/smb/test-standalone.ts + +import * as fs from "fs"; +import * as path from "path"; +import * as os from "os"; +import { NetBIOSFramer, nbWrap } from "./netbios"; +import { SmbSession } from "./server"; +import { parseSmb, CMD_NEGOTIATE, CMD_SESSION_SETUP_ANDX, + CMD_TREE_CONNECT_ANDX, CMD_TRANSACTION2, CMD_OPEN_ANDX, + CMD_READ_ANDX, CMD_CLOSE } from "./smb"; + +let pass = 0, fail = 0; +const ok = (cond: boolean, msg: string) => { + if (cond) { pass++; console.log(" ✓", msg); } + else { fail++; console.log(" ✗", msg); } +}; + +// @ts-ignore — kept for debugging when tests fail +const hex = (b: Uint8Array, n = 32) => + Array.from(b.slice(0, n)).map(x => x.toString(16).padStart(2, "0")).join(" "); +void hex; + +// ─── Build a minimal SMB request from scratch ──────────────────────────────── +function smbReq(cmd: number, words: number[], bytes: number[], + tid = 0, uid = 0, mid = 1): Uint8Array { + const out: number[] = []; + out.push(0xff, 0x53, 0x4d, 0x42); // magic + out.push(cmd); // cmd + out.push(0, 0, 0, 0); // status + out.push(0x18); // flags (caseless+canonical) + out.push(0x01, 0x00); // flags2: long names, no unicode + for (let i = 0; i < 12; i++) out.push(0); // reserved + out.push(tid & 0xff, tid >> 8); + out.push(0, 0); // pid + out.push(uid & 0xff, uid >> 8); + out.push(mid & 0xff, mid >> 8); + if (words.length % 2) throw new Error("words must be even"); + out.push(words.length / 2); + out.push(...words); + out.push(bytes.length & 0xff, bytes.length >> 8); + out.push(...bytes); + return new Uint8Array(out); +} + +const u16 = (v: number) => [v & 0xff, (v >> 8) & 0xff]; +const u32 = (v: number) => [...u16(v & 0xffff), ...u16((v >>> 16) & 0xffff)]; +const cstr = (s: string) => [...Buffer.from(s, "ascii"), 0]; + +// ─── Setup test fixture ────────────────────────────────────────────────────── +const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "smbtest-")); +fs.writeFileSync(path.join(tmpRoot, "hello.txt"), "Hello from the host!\n"); +fs.mkdirSync(path.join(tmpRoot, "subdir")); +fs.writeFileSync(path.join(tmpRoot, "subdir", "nested.dat"), Buffer.alloc(100, 0xAB)); +console.log("fixture:", tmpRoot); + +const session = new SmbSession(tmpRoot); +session.capture = false; + +// ─── Test 1: NetBIOS framing ───────────────────────────────────────────────── +console.log("\n[1] NetBIOS framer"); +{ + const framer = new NetBIOSFramer(); + // Session request: type 0x81, len 68 (called name 34 + calling name 34) + const sessReq = new Uint8Array([0x81, 0, 0, 68, ...new Array(68).fill(0x20)]); + const msgs1 = framer.push(sessReq); + ok(msgs1.length === 1 && msgs1[0].type === 0x81, "parses session request"); + + // Fragmented session message + const payload = new Uint8Array([0xff, 0x53, 0x4d, 0x42, 0x72, 0, 0, 0, 0, 0]); + const wrapped = nbWrap(payload); + const msgs2 = framer.push(wrapped.slice(0, 5)); + ok(msgs2.length === 0, "incomplete frame buffers"); + const msgs3 = framer.push(wrapped.slice(5)); + ok(msgs3.length === 1 && msgs3[0].type === 0x00, "completes on second chunk"); + ok(msgs3[0].type === 0x00 && msgs3[0].payload[0] === 0xff && msgs3[0].payload[1] === 0x53, + "payload extracted"); +} + +// ─── Test 2: NEGOTIATE ─────────────────────────────────────────────────────── +console.log("\n[2] NEGOTIATE"); +{ + // Real Win95 dialect list (abbreviated). Each entry is 0x02 + cstr. + const dialects = ["PC NETWORK PROGRAM 1.0", "LANMAN1.0", "LM1.2X002", + "LANMAN2.1", "NT LM 0.12"]; + const bytes: number[] = []; + for (const d of dialects) { bytes.push(0x02); bytes.push(...cstr(d)); } + + const req = smbReq(CMD_NEGOTIATE, [], bytes); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.cmd === CMD_NEGOTIATE, "cmd echoed"); + ok((parsed.flags & 0x80) !== 0, "reply flag set"); + ok(parsed.status === 0, "status OK"); + ok(parsed.wordCount === 13, "13-word LM response"); + // word[0] = dialect index — we pick LANMAN2.1 (idx 3) since our 13-word + // response is the LANMAN format; picking NT LM 0.12 would require the + // 17-word NT response which we don't implement + const pickedIdx = parsed.words[0] | (parsed.words[1] << 8); + ok(pickedIdx === 3, `picked LANMAN2.1 (idx ${pickedIdx})`); +} + +// ─── Test 3: SESSION_SETUP ─────────────────────────────────────────────────── +console.log("\n[3] SESSION_SETUP_ANDX"); +{ + // Minimal setup: AndX(4) MaxBuf(2) MaxMpx(2) VcNum(2) SessKey(4) + // PwLen(2) Reserved(4) — bytes: password + account + domain + os + lanman + const words = [0xff, 0, 0, 0, ...u16(4096), ...u16(1), ...u16(0), + ...u32(0), ...u16(0), ...u32(0)]; + const bytes = [...cstr(""), ...cstr("GUEST"), ...cstr("WORKGROUP"), + ...cstr("Windows 4.0"), ...cstr("Windows 4.0")]; + const req = smbReq(CMD_SESSION_SETUP_ANDX, words, bytes); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "status OK"); + ok(parsed.uid === 1, `assigned uid=${parsed.uid}`); + // Action word at offset 4 (after AndX) = guest bit + const action = parsed.words[4] | (parsed.words[5] << 8); + ok((action & 1) === 1, "guest bit set"); +} + +// ─── Test 4: TREE_CONNECT ──────────────────────────────────────────────────── +console.log("\n[4] TREE_CONNECT_ANDX"); +{ + const words = [0xff, 0, 0, 0, ...u16(0), ...u16(1)]; // pwLen=1 + const bytes = [0, ...cstr("\\\\192.168.86.1\\HOST"), ...cstr("?????")]; + const req = smbReq(CMD_TREE_CONNECT_ANDX, words, bytes, 0, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "status OK"); + ok(parsed.tid === 1, `assigned tid=${parsed.tid}`); + // bytes should start with "A:\0" + const svc = String.fromCharCode(parsed.bytes[0], parsed.bytes[1]); + ok(svc === "A:", `service="${svc}"`); +} + +// ─── Test 5: TRANS2 FIND_FIRST2 (directory listing) ────────────────────────── +console.log("\n[5] TRANS2 FIND_FIRST2"); +{ + // TRANS2 setup is gnarly. Build from spec: + // params: SearchAttrs(2) SearchCount(2) Flags(2) InfoLevel(2) Storage(4) "\*"\0 + const t2params = [...u16(0x16), ...u16(100), ...u16(0), ...u16(1), + ...u32(0), ...cstr("\\*")]; + // setup word = TRANS2_FIND_FIRST2 (1) + // word block: TotPrm(2) TotData(2) MaxPrm(2) MaxData(2) MaxSetup(1) Rsvd(1) + // Flags(2) Timeout(4) Rsvd(2) PrmCnt(2) PrmOff(2) DataCnt(2) DataOff(2) + // SetupCnt(1) Rsvd(1) Setup[0](2) + const wc = 14 + 1; // 14 fixed + 1 setup + const bytesStart = 32 + 1 + wc * 2 + 2; + const paramOff = bytesStart + 3; // 3 bytes pad ("\0\0\0") before params + const words = [ + ...u16(t2params.length), ...u16(0), ...u16(100), ...u16(8000), + 1, 0, ...u16(0), ...u32(0), ...u16(0), + ...u16(t2params.length), ...u16(paramOff), + ...u16(0), ...u16(0), + 1, 0, ...u16(1) // SetupCount=1, Setup[0]=FIND_FIRST2 + ]; + const bytes = [0, 0, 0, ...t2params]; // 3-byte name padding + params + const req = smbReq(CMD_TRANSACTION2, words, bytes, 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "status OK"); + // Reply params: SID(2) Count(2) EOS(2) EaErr(2) LastName(2) + // Reply words tell us where params live + const rw = parsed.words; + const replyParamOffset = rw[8] | (rw[9] << 8); + const replyParamCount = rw[6] | (rw[7] << 8); + const replyBytesStart = 32 + 1 + parsed.wordCount * 2 + 2; + const pStart = replyParamOffset - replyBytesStart; + const replyParams = parsed.bytes.slice(pStart, pStart + replyParamCount); + const searchCount = replyParams[2] | (replyParams[3] << 8); + // Should find: . .. _MAPZ.BAT(virtual) hello.txt subdir = 5 + ok(searchCount === 5, `found ${searchCount} entries (expect 5)`); + // Data block has the entries — just verify they're in there somewhere + const dataStr = String.fromCharCode(...parsed.bytes); + ok(dataStr.includes("_MAPZ.BAT"), "virtual _MAPZ.BAT in listing"); + ok(dataStr.includes("hello.txt"), "hello.txt in listing"); + ok(dataStr.includes("subdir"), "subdir in listing"); +} + +// ─── Test 6: OPEN + READ + CLOSE ───────────────────────────────────────────── +console.log("\n[6] OPEN_ANDX + READ_ANDX + CLOSE"); +let openedFid = 0; +{ + // OPEN_ANDX words: AndX(4) Flags(2) Access(2) SrchAttr(2) FileAttr(2) + // CreateTime(4) OpenFunc(2) AllocSize(4) Timeout(4) Rsvd(4) + const words = [0xff, 0, 0, 0, ...u16(0), ...u16(0), ...u16(0), ...u16(0), + ...u32(0), ...u16(1), ...u32(0), ...u32(0), ...u32(0)]; + const bytes = [...cstr("\\hello.txt")]; + const req = smbReq(CMD_OPEN_ANDX, words, bytes, 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "open status OK"); + openedFid = parsed.words[4] | (parsed.words[5] << 8); // FID after AndX + ok(openedFid > 0, `fid=${openedFid}`); + // OPEN_ANDX response: AndX(4) FID(2) Attrs(2) LastWrite(4) DataSize(4) ... + const fileSize = parsed.words[12] | (parsed.words[13] << 8) | + (parsed.words[14] << 16) | (parsed.words[15] << 24); + ok(fileSize === 21, `size=${fileSize} (expect 21)`); +} +{ + // READ_ANDX: AndX(4) FID(2) Offset(4) MaxCount(2) MinCount(2) + // Timeout(4) Remaining(2) [OffsetHigh(4)] + const words = [0xff, 0, 0, 0, ...u16(openedFid), ...u32(0), ...u16(100), + ...u16(0), ...u32(0), ...u16(0)]; + const req = smbReq(CMD_READ_ANDX, words, [], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "read status OK"); + const dataLen = parsed.words[10] | (parsed.words[11] << 8); + ok(dataLen === 21, `read ${dataLen} bytes`); + // bytes = pad(1) + data + const text = String.fromCharCode(...parsed.bytes.slice(1, 1 + dataLen)); + ok(text === "Hello from the host!\n", `content: ${JSON.stringify(text)}`); +} +{ + const words = [...u16(openedFid), ...u32(0)]; + const req = smbReq(CMD_CLOSE, words, [], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "close status OK"); +} + +// ─── Test 7: error paths ───────────────────────────────────────────────────── +console.log("\n[7] Error handling"); +{ + const words = [0xff, 0, 0, 0, ...u16(0), ...u16(0), ...u16(0), ...u16(0), + ...u32(0), ...u16(1), ...u32(0), ...u32(0), ...u32(0)]; + const req = smbReq(CMD_OPEN_ANDX, words, [...cstr("\\nope.txt")], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status !== 0, `nonexistent file → status=0x${parsed.status.toString(16)}`); + // DOS error: class=1 (ERRDOS), code=2 (badfile) + ok((parsed.status & 0xff) === 1 && (parsed.status >> 16) === 2, "ERRDOS/ERR_badfile"); +} +{ + const req = smbReq(CMD_OPEN_ANDX, + [0xff,0,0,0,...u16(0),...u16(0),...u16(0),...u16(0),...u32(0),...u16(1),...u32(0),...u32(0),...u32(0)], + [...cstr("\\..\\..\\etc\\passwd")], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status !== 0, "lexical traversal (../) blocked"); +} +{ + // Virtual file: open and read _MAPZ.BAT + const oReq = smbReq(CMD_OPEN_ANDX, + [0xff,0,0,0,...u16(0),...u16(0),...u16(0),...u16(0),...u32(0),...u16(1),...u32(0),...u32(0),...u32(0)], + [...cstr("\\_MAPZ.BAT")], 1, 1); + const oReply = session.handle(oReq)!; + const oParsed = parseSmb(oReply)!; + ok(oParsed.status === 0, "open virtual _MAPZ.BAT"); + const vfid = oParsed.words[4] | (oParsed.words[5] << 8); + const rReq = smbReq(CMD_READ_ANDX, + [0xff,0,0,0,...u16(vfid),...u32(0),...u16(500),...u16(0),...u32(0),...u16(0)], [], 1, 1); + const rReply = session.handle(rReq)!; + const rParsed = parseSmb(rReply)!; + const len = rParsed.words[10] | (rParsed.words[11] << 8); + const text = String.fromCharCode(...rParsed.bytes.slice(1, 1 + len)); + ok(text.includes("NET USE Z:"), `virtual read: ${JSON.stringify(text.slice(0, 40))}`); +} +{ + // symlink escape: link inside share → file outside share + const outside = path.join(os.tmpdir(), "smbtest-secret.txt"); + fs.writeFileSync(outside, "leaked"); + fs.symlinkSync(outside, path.join(tmpRoot, "evil")); + + const req = smbReq(CMD_OPEN_ANDX, + [0xff,0,0,0,...u16(0),...u16(0),...u16(0),...u16(0),...u32(0),...u16(1),...u32(0),...u32(0),...u32(0)], + [...cstr("\\evil")], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status !== 0, "symlink escape blocked"); + + fs.unlinkSync(outside); +} +{ + // symlink directory escape: link inside share → dir outside, then walk into it + const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), "smbtest-out-")); + fs.writeFileSync(path.join(outsideDir, "secret.txt"), "leaked"); + fs.symlinkSync(outsideDir, path.join(tmpRoot, "evildir")); + + const req = smbReq(CMD_OPEN_ANDX, + [0xff,0,0,0,...u16(0),...u16(0),...u16(0),...u16(0),...u32(0),...u16(1),...u32(0),...u32(0),...u32(0)], + [...cstr("\\evildir\\secret.txt")], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status !== 0, "symlink dir escape blocked"); + + fs.rmSync(outsideDir, { recursive: true }); +} +{ + // symlink that stays INSIDE the share should still work + fs.symlinkSync(path.join(tmpRoot, "hello.txt"), path.join(tmpRoot, "alias")); + const req = smbReq(CMD_OPEN_ANDX, + [0xff,0,0,0,...u16(0),...u16(0),...u16(0),...u16(0),...u32(0),...u16(1),...u32(0),...u32(0),...u32(0)], + [...cstr("\\alias")], 1, 1); + const reply = session.handle(req)!; + const parsed = parseSmb(reply)!; + ok(parsed.status === 0, "internal symlink allowed"); +} + +// ─── Cleanup ───────────────────────────────────────────────────────────────── +session.destroy(); +fs.rmSync(tmpRoot, { recursive: true }); + +console.log(`\n${pass} passed, ${fail} failed`); +process.exit(fail > 0 ? 1 : 0); diff --git a/src/renderer/smb/wire.ts b/src/renderer/smb/wire.ts new file mode 100644 index 0000000..8db39dc --- /dev/null +++ b/src/renderer/smb/wire.ts @@ -0,0 +1,50 @@ +// SMB1 wire format helpers. Everything is little-endian except the +// 0xFF 'SMB' magic. + +export class Reader { + pos = 0; + constructor(private buf: Uint8Array, start = 0) { + this.pos = start; + } + u8() { return this.buf[this.pos++]; } + u16() { const v = this.buf[this.pos] | (this.buf[this.pos+1] << 8); this.pos += 2; return v; } + u32() { const v = this.u16() | (this.u16() << 16); return v >>> 0; } + skip(n: number) { this.pos += n; } + bytes(n: number) { const v = this.buf.slice(this.pos, this.pos + n); this.pos += n; return v; } + rest() { return this.buf.slice(this.pos); } + /** OEM string, null-terminated */ + cstr(): string { + let end = this.pos; + while (end < this.buf.length && this.buf[end] !== 0) end++; + const s = String.fromCharCode(...this.buf.slice(this.pos, end)); + this.pos = end + 1; + return s; + } + /** UCS-2LE string, null-terminated */ + ucs2(): string { + let end = this.pos; + while (end + 1 < this.buf.length && (this.buf[end] | this.buf[end+1]) !== 0) end += 2; + const s = Buffer.from(this.buf.slice(this.pos, end)).toString('ucs2'); + this.pos = end + 2; + return s; + } +} + +export class Writer { + private chunks: number[] = []; + u8(v: number) { this.chunks.push(v & 0xff); return this; } + u16(v: number) { this.chunks.push(v & 0xff, (v >> 8) & 0xff); return this; } + u32(v: number) { return this.u16(v & 0xffff).u16((v >>> 16) & 0xffff); } + u64(lo: number, hi = 0) { return this.u32(lo).u32(hi); } + bytes(b: Uint8Array | number[]) { for (const x of b) this.chunks.push(x & 0xff); return this; } + zero(n: number) { for (let i = 0; i < n; i++) this.chunks.push(0); return this; } + cstr(s: string) { for (let i = 0; i < s.length; i++) this.chunks.push(s.charCodeAt(i) & 0xff); this.chunks.push(0); return this; } + ucs2(s: string) { + const b = Buffer.from(s, 'ucs2'); + for (const x of b) this.chunks.push(x); + this.chunks.push(0, 0); + return this; + } + get length() { return this.chunks.length; } + build() { return new Uint8Array(this.chunks); } +} diff --git a/tools/bisect-v86.sh b/tools/bisect-v86.sh new file mode 100755 index 0000000..0c840ce --- /dev/null +++ b/tools/bisect-v86.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# Bisect harness: checkout v86 to a commit, rebuild wasm, probe boot. +# Logs to /tmp/win95-bisect.log +# +# Usage: +# tools/bisect-v86.sh # test one commit +# tools/bisect-v86.sh '{"acpi":false}' # with options + +set -e +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +V86="${V86_DIR:-$ROOT/../v86}" +LOG=/tmp/win95-bisect.log + +COMMIT="$1" +OPTS="${2:-{}}" + +[ -z "$COMMIT" ] && { echo "usage: $0 [opts-json]"; exit 1; } + +cd "$V86" +SAVED_HEAD=$(git rev-parse HEAD) +trap "cd '$V86' && git checkout -q '$SAVED_HEAD' 2>/dev/null" EXIT + +echo "─── checkout $COMMIT ───" +git checkout -q "$COMMIT" 2>&1 | head -3 +HASH=$(git rev-parse --short HEAD) +SUBJ=$(git log -1 --format='%s' | head -c 60) +DATE=$(git log -1 --format='%ci' | cut -d' ' -f1) + +export PATH="/opt/homebrew/opt/openjdk/bin:$PATH" + +echo "─── build wasm + libv86.js @ $HASH ($DATE) ───" +rm -f build/v86.wasm build/libv86.js +make build/v86.wasm 2>&1 | tail -3 +[ -f build/v86.wasm ] || { echo "WASM BUILD FAILED"; exit 1; } +make build/libv86.js 2>&1 | tail -3 +[ -f build/libv86.js ] || { echo "LIBV86 BUILD FAILED"; exit 1; } + +WASM_SIZE=$(stat -f%z build/v86.wasm) +JS_SIZE=$(stat -f%z build/libv86.js) + +cp build/v86.wasm "$ROOT/src/renderer/lib/build/v86.wasm" +cp build/libv86.js "$ROOT/src/renderer/lib/libv86.js" + +# Re-apply phantom-slave patch (it's a v86 bug from May 2025 onwards; +# harmless before that since the pattern won't match) +node -e ' +const fs=require("fs"); +let s=fs.readFileSync(process.argv[1],"utf8"); +const re=/(\w+)\[0\]\[1\]=\{buffer:(\w+)\.hdb\}/g; +const n=[...s.matchAll(re)].length; +if(n===1){s=s.replace(re,"$2.hdb&&($1[0][1]={buffer:$2.hdb})");fs.writeFileSync(process.argv[1],s);console.log("phantom-slave: patched")} +else console.log("phantom-slave: skip ("+n+" matches)"); +' "$ROOT/src/renderer/lib/libv86.js" + +# Win95 has sporadic bluescreens on all v86 versions — a single FAIL doesn't +# mean the commit is bad. Probe up to 3 times; one SUCCESS = good commit. +echo "─── probe (up to 3 attempts) ───" +cd "$ROOT" +VERDICT="UNKNOWN" +for ATTEMPT in 1 2 3; do + echo " attempt $ATTEMPT/3" + set +e + tools/probe-boot.sh "$OPTS" 2>&1 | tee /tmp/win95-probe-out.log | tail -10 + set -e + V=$(cat /tmp/win95-probe.done 2>/dev/null || echo "UNKNOWN") + if [ "$V" = "SUCCESS" ]; then + VERDICT="SUCCESS" + break + fi + VERDICT="$V" # keep the last failure mode + [ "$ATTEMPT" -lt 3 ] && sleep 3 +done +GFX=$(python3 -c "import json;s=json.load(open('/tmp/win95-probe.json'));print(f\"{s.get('gfxW',0)}x{s.get('gfxH',0)} {s.get('dominantColor','')}\")" 2>/dev/null || echo "?") + +LINE="$HASH $DATE | wasm=${WASM_SIZE} opts=$OPTS | $VERDICT $GFX | $SUBJ" +echo "$LINE" >> "$LOG" +echo "" +echo "═══ $LINE ═══" + +exit $RESULT diff --git a/tools/parcel-build.js b/tools/parcel-build.js index 689608f..bfbddc9 100644 --- a/tools/parcel-build.js +++ b/tools/parcel-build.js @@ -10,11 +10,16 @@ const fs = require('fs') const LIBV86_SHIM = ` ` -// v86's node-path file loader uses `await import("node:fs/promises")`, but -// dynamic import of node: URLs doesn't work in an Electron renderer — only -// require() does. The string literal is stable across Closure builds. -const V86_FS_IMPORT = 'await import("node:fs/promises")' -const V86_FS_REQUIRE = 'require("fs").promises' +// v86's node-path file loader used `await import("node:...")` until d4c5fa86 +// switched it to require(). Dynamic import of node: URLs doesn't work in an +// Electron renderer — only require() does. The literals are stable across +// Closure builds; if they're absent the build is post-d4c5fa86 and already +// uses require, so a no-op is correct. +const V86_NODE_IMPORTS = [ + ['await import("node:fs/promises")', 'require("fs").promises'], + ['await import("node:"+"fs/promises")', 'require("fs").promises'], + ['await import("node:crypto")', 'require("crypto")'], +]; async function copyLib() { const target = path.join(__dirname, '../dist/static') @@ -24,12 +29,16 @@ async function copyLib() { await fs.promises.cp(lib, target, { recursive: true }); const libv86path = path.join(target, 'libv86.js') - const libv86 = fs.readFileSync(libv86path, 'utf-8') - const patched = libv86.split(V86_FS_IMPORT).join(V86_FS_REQUIRE) - if (patched === libv86) { - throw new Error(`libv86.js patch failed: \`${V86_FS_IMPORT}\` not found. Check src/lib.js in copy/v86.`) + let libv86 = fs.readFileSync(libv86path, 'utf-8') + let patchCount = 0; + for (const [from, to] of V86_NODE_IMPORTS) { + const next = libv86.split(from).join(to); + if (next !== libv86) { patchCount++; libv86 = next; } + } + if (patchCount > 0) { + fs.writeFileSync(libv86path, libv86) + console.log(`libv86: ${patchCount} dynamic-import → require`) } - fs.writeFileSync(libv86path, patched) const indexContents = fs.readFileSync(index, 'utf-8'); const replacedContents = indexContents.replace('', LIBV86_SHIM) diff --git a/tools/probe-boot.sh b/tools/probe-boot.sh new file mode 100755 index 0000000..27994e8 --- /dev/null +++ b/tools/probe-boot.sh @@ -0,0 +1,76 @@ +#!/bin/bash +# Single boot probe: build → launch → wait for verdict → kill → report. +# Usage: tools/probe-boot.sh [json-options] +# tools/probe-boot.sh '{"acpi":false}' +# tools/probe-boot.sh '{"disable_jit":true}' + +set -e +cd "$(dirname "$0")/.." + +OPTS="${1:-{}}" +STATUS=/tmp/win95-probe.json +DONE=/tmp/win95-probe.done +SCREEN=/tmp/win95-screen.png +TIMEOUT=200 + +echo "═══ probe: opts=$OPTS ═══" + +# clean slate +rm -f "$STATUS" "$DONE" "$SCREEN" +pkill -f "windows95/node_modules/electron" 2>/dev/null || true +sleep 1 + +# build (parcel only — forge's generateAssets does this too but we want +# direct control without the forge startup overhead) +rm -rf dist .cache +node tools/parcel-build.js > /tmp/win95-build.log 2>&1 +if [ $? -ne 0 ]; then + echo "BUILD FAILED" + tail -20 /tmp/win95-build.log + exit 1 +fi + +# launch electron directly (skip forge to avoid double-build) +WIN95_PROBE=1 WIN95_PROBE_OPTS="$OPTS" \ + ./node_modules/.bin/electron . > /tmp/win95-electron.log 2>&1 & +PID=$! +echo "electron pid=$PID, waiting for verdict (timeout ${TIMEOUT}s)..." + +# poll +for i in $(seq 1 $TIMEOUT); do + if [ -f "$DONE" ]; then + VERDICT=$(cat "$DONE") + echo "verdict at ${i}s: $VERDICT" + break + fi + if ! kill -0 $PID 2>/dev/null; then + echo "electron died at ${i}s" + tail -30 /tmp/win95-electron.log + VERDICT="CRASHED" + break + fi + sleep 1 +done + +if [ -z "$VERDICT" ]; then + echo "TIMEOUT at ${TIMEOUT}s" + VERDICT="TIMEOUT" +fi + +# capture final state +echo "─── final status ───" +[ -f "$STATUS" ] && python3 -c " +import json +s=json.load(open('$STATUS')) +print(f\"phase={s['phase']} cpu={s['cpuRunning']} instr_delta={s['instructionDelta']:,}\") +print(f\"uptime={s['uptimeSec']}s\") +t=s['textScreen'].strip() +if t: print('text:'); print(' ' + t.replace(chr(10), chr(10)+' ')[:500]) +" || echo "(no status file)" + +# kill +kill $PID 2>/dev/null || true +wait $PID 2>/dev/null || true + +echo "═══ $VERDICT ═══" +[ "$VERDICT" = "SUCCESS" ] && exit 0 || exit 1 diff --git a/tools/update-v86.js b/tools/update-v86.js index 44dca7b..4e90f93 100644 --- a/tools/update-v86.js +++ b/tools/update-v86.js @@ -1,35 +1,151 @@ #!/usr/bin/env node +/** + * Updates v86 by building the wasm from a local checkout. The libv86.js + + * v86.wasm pair MUST be ABI-matched — copy.sh historically rebuilds the JS + * without rebuilding the wasm, and a mismatch silently breaks fresh boot + * (state restore still works because the CPU snapshot is opaque, so you + * won't notice until Win95 BSODs at the splash screen with "Invalid VxD + * dynamic link call"). + * + * Usage: + * node tools/update-v86.js [path/to/v86] # builds wasm from source + * node tools/update-v86.js --js-only # just download libv86.js + * + * The wasm build needs `rustup target add wasm32-unknown-unknown` and clang. + * libv86.js needs Java + Closure; if you don't have those, --js-only fetches + * from copy.sh and warns if its Last-Modified is far from your wasm build. + */ + const fs = require('fs'); const path = require('path'); const https = require('https'); +const { execSync } = require('child_process'); const LIB_DIR = path.join(__dirname, '../src/renderer/lib'); -const FILES = [ - { url: 'https://copy.sh/v86/build/libv86.js', dest: path.join(LIB_DIR, 'libv86.js') }, - { url: 'https://copy.sh/v86/build/v86.wasm', dest: path.join(LIB_DIR, 'build/v86.wasm') }, -]; +const V86_DIR = process.argv.find(a => a !== process.argv[0] && a !== process.argv[1] && !a.startsWith('--')) + || path.resolve(__dirname, '../../v86'); +const JS_ONLY = process.argv.includes('--js-only'); +const SKEW_DAYS = 14; + +function head(url) { + return new Promise((resolve, reject) => { + https.request(url, { method: 'HEAD' }, (res) => { + resolve({ status: res.statusCode, lastModified: res.headers['last-modified'] }); + }).on('error', reject).end(); + }); +} function download(url, dest) { return new Promise((resolve, reject) => { https.get(url, (res) => { - if (res.statusCode !== 200) { - return reject(new Error(`${url} → HTTP ${res.statusCode}`)); - } + if (res.statusCode !== 200) return reject(new Error(`${url} → HTTP ${res.statusCode}`)); const chunks = []; res.on('data', (c) => chunks.push(c)); res.on('end', () => { const buf = Buffer.concat(chunks); fs.writeFileSync(dest, buf); - console.log(`✓ ${path.relative(process.cwd(), dest)} (${(buf.length / 1024).toFixed(0)} KB)`); - resolve(); + console.log(` ${path.basename(dest)}: ${(buf.length / 1024).toFixed(0)} KB`); + resolve(res.headers['last-modified']); }); - res.on('error', reject); }).on('error', reject); }); } -(async () => { - for (const { url, dest } of FILES) { - await download(url, dest); +async function main() { + const jsDest = path.join(LIB_DIR, 'libv86.js'); + const wasmDest = path.join(LIB_DIR, 'build/v86.wasm'); + + // ─── wasm ──────────────────────────────────────────────────────────────── + let wasmDate; + if (JS_ONLY) { + if (!fs.existsSync(wasmDest)) { + throw new Error(`--js-only requires an existing wasm at ${wasmDest}`); + } + wasmDate = fs.statSync(wasmDest).mtime; + console.log(`Keeping existing wasm (${wasmDate.toISOString().slice(0, 10)})`); + } else { + if (!fs.existsSync(path.join(V86_DIR, 'Makefile'))) { + throw new Error(`No v86 checkout at ${V86_DIR}. Clone copy/v86 there or pass a path.`); + } + const head = execSync('git log -1 --format="%h %ci"', { cwd: V86_DIR }).toString().trim(); + console.log(`Building wasm from ${V86_DIR} @ ${head}`); + execSync('make build/v86.wasm', { cwd: V86_DIR, stdio: 'inherit' }); + fs.copyFileSync(path.join(V86_DIR, 'build/v86.wasm'), wasmDest); + wasmDate = new Date(); + console.log(` v86.wasm: ${(fs.statSync(wasmDest).size / 1024).toFixed(0)} KB`); } -})(); + + // ─── libv86.js ─────────────────────────────────────────────────────────── + // Build from source if Closure is available; otherwise fetch and check skew. + const hasClosure = !JS_ONLY && fs.existsSync(path.join(V86_DIR, 'closure-compiler/compiler.jar')); + if (hasClosure) { + console.log('Building libv86.js (Closure)…'); + execSync('make build/libv86.js', { cwd: V86_DIR, stdio: 'inherit' }); + fs.copyFileSync(path.join(V86_DIR, 'build/libv86.js'), jsDest); + console.log(` libv86.js: ${(fs.statSync(jsDest).size / 1024).toFixed(0)} KB`); + } else { + console.log('No Closure jar — fetching libv86.js from copy.sh'); + const lm = await download('https://copy.sh/v86/build/libv86.js', jsDest); + const jsDate = new Date(lm); + const skew = Math.abs(jsDate - wasmDate) / 86400000; + console.log(` JS: ${jsDate.toISOString().slice(0, 10)}`); + console.log(` wasm: ${wasmDate.toISOString().slice(0, 10)}`); + if (skew > SKEW_DAYS) { + throw new Error( + `JS and wasm are ${skew.toFixed(0)} days apart. ` + + `Either install Closure (java + v86/closure-compiler/compiler.jar) ` + + `to build libv86.js from the same commit, or git-checkout v86 to a ` + + `commit near ${jsDate.toISOString().slice(0, 10)} and rebuild the wasm.` + ); + } + } + + // ─── BIOS ──────────────────────────────────────────────────────────────── + // SeaBIOS sets up the interrupt controller for whatever the emulated + // hardware presents. New v86 + old BIOS = APIC never armed = IDE IRQs + // never fire = boot hangs at the splash screen with no disk activity. + if (!JS_ONLY) { + const biosDir = path.join(__dirname, '../bios'); + for (const f of ['seabios.bin', 'vgabios.bin']) { + fs.copyFileSync(path.join(V86_DIR, 'bios', f), path.join(biosDir, f)); + console.log(` ${f}: ${(fs.statSync(path.join(biosDir, f)).size / 1024).toFixed(0)} KB`); + } + } + + // ─── patch: phantom slave drive ────────────────────────────────────────── + // v86 bug since 1b90d2e7 (May 2025 IDE refactor): cpu.js does + // ide_config[0][1] = { buffer: settings.hdb } + // unconditionally inside the `if(settings.hda)` block. When hdb is + // undefined this creates a phantom 0-size HD on primary slave; Win95's + // ESDI_506.PDR detects it, sends IDENTIFY, and spins forever waiting for + // DRQ from a drive that has no sectors. State restore skips driver init, + // so it only bites on fresh boot. + // + // The pattern is structurally stable: `buffer` and `hdb` are option keys + // (externed, not mangled), `[0][1]=` is literal. + let js = fs.readFileSync(jsDest, 'utf-8'); + const phantom = /(\w+)\[0\]\[1\]=\{buffer:(\w+)\.hdb\}/g; + const matches = [...js.matchAll(phantom)]; + if (matches.length !== 1) { + throw new Error( + `phantom-slave patch: expected exactly 1 match, found ${matches.length}. ` + + `Either v86 fixed this upstream (good — remove this patch) or the ` + + `pattern changed. Check src/cpu.js around ide_config[0][1].` + ); + } + js = js.replace(phantom, '$2.hdb&&($1[0][1]={buffer:$2.hdb})'); + fs.writeFileSync(jsDest, js); + console.log(' patched: phantom slave drive guard (1 site)'); + + // ─── sanity ────────────────────────────────────────────────────────────── + if (!js.includes('process.versions.node')) + throw new Error('libv86 lost the process.versions.node check (file loader regression)'); + if (!/this\.fetch=\([^)]*\)=>fetch\(/.test(js)) + throw new Error('libv86 lost the fetch arrow wrapper'); + if (!js.includes('window.V86=') && !js.includes('module.exports.V86=')) + throw new Error('libv86 export pattern changed — check the runtime shim'); + + console.log('✓ installed (sanity checks pass)'); +} + +main().catch((e) => { console.error('✗', e.message); process.exit(1); });