starter.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. "use strict";
  2. /**
  3. * Constructor for emulator instances.
  4. *
  5. * Usage: `var emulator = new V86Starter(options);`
  6. *
  7. * Options can have the following properties (all optional, default in parenthesis):
  8. *
  9. * - `memory_size number` (16 * 1024 * 1024) - The memory size in bytes, should
  10. * be a power of 2.
  11. * - `vga_memory_size number` (8 * 1024 * 1024) - VGA memory size in bytes.
  12. *
  13. * - `autostart boolean` (false) - If emulation should be started when emulator
  14. * is ready.
  15. *
  16. * - `disable_keyboard boolean` (false) - If the keyboard should be disabled.
  17. * - `disable_mouse boolean` (false) - If the mouse should be disabled.
  18. *
  19. * - `network_relay_url string` (No network card) - The url of a server running
  20. * websockproxy. See [networking.md](networking.md). Setting this will
  21. * enable an emulated network card.
  22. *
  23. * - `bios Object` (No bios) - Either a url pointing to a bios or an
  24. * ArrayBuffer, see below.
  25. * - `vga_bios Object` (No VGA bios) - VGA bios, see below.
  26. * - `hda Object` (No hard drive) - First hard disk, see below.
  27. * - `fda Object` (No floppy disk) - First floppy disk, see below.
  28. * - `cdrom Object` (No CD) - See below.
  29. *
  30. * - `bzimage Object` - A Linux kernel image to boot (only bzimage format), see below.
  31. * - `initrd Object` - A Linux ramdisk image, see below.
  32. * - `bzimage_initrd_from_filesystem boolean` - Automatically fetch bzimage and
  33. * initrd from the specified `filesystem`.
  34. *
  35. * - `initial_state Object` (Normal boot) - An initial state to load, see
  36. * [`restore_state`](#restore_statearraybuffer-state) and below.
  37. *
  38. * - `filesystem Object` (No 9p filesystem) - A 9p filesystem, see
  39. * [filesystem.md](filesystem.md).
  40. *
  41. * - `serial_container HTMLTextAreaElement` (No serial terminal) - A textarea
  42. * that will receive and send data to the emulated serial terminal.
  43. * Alternatively the serial terminal can also be accessed programatically,
  44. * see [serial.html](../examples/serial.html).
  45. *
  46. * - `screen_container HTMLElement` (No screen) - An HTMLElement. This should
  47. * have a certain structure, see [basic.html](../examples/basic.html).
  48. *
  49. * ***
  50. *
  51. * There are two ways to load images (`bios`, `vga_bios`, `cdrom`, `hda`, ...):
  52. *
  53. * - Pass an object that has a url. Optionally, `async: true` and `size:
  54. * size_in_bytes` can be added to the object, so that sectors of the image
  55. * are loaded on demand instead of being loaded before boot (slower, but
  56. * strongly recommended for big files). In that case, the `Range: bytes=...`
  57. * header must be supported on the server.
  58. *
  59. * ```javascript
  60. * // download file before boot
  61. * bios: {
  62. * url: "bios/seabios.bin"
  63. * }
  64. * // download file sectors as requested, size is required
  65. * hda: {
  66. * url: "disk/linux.iso",
  67. * async: true,
  68. * size: 16 * 1024 * 1024
  69. * }
  70. * ```
  71. *
  72. * - Pass an `ArrayBuffer` or `File` object as `buffer` property.
  73. *
  74. * ```javascript
  75. * // use <input type=file>
  76. * bios: {
  77. * buffer: document.all.hd_image.files[0]
  78. * }
  79. * // start with empty hard drive
  80. * hda: {
  81. * buffer: new ArrayBuffer(16 * 1024 * 1024)
  82. * }
  83. * ```
  84. *
  85. * ***
  86. *
  87. * @param {Object} options Options to initialize the emulator with.
  88. * @constructor
  89. */
  90. function V86Starter(options)
  91. {
  92. //var worker = new Worker("src/browser/worker.js");
  93. //var adapter_bus = this.bus = WorkerBus.init(worker);
  94. this.cpu_is_running = false;
  95. const bus = Bus.create();
  96. const adapter_bus = this.bus = bus[0];
  97. this.emulator_bus = bus[1];
  98. var cpu;
  99. var wasm_memory;
  100. const wasm_table = new WebAssembly.Table({ element: "anyfunc", "initial": WASM_TABLE_SIZE + WASM_TABLE_OFFSET });
  101. const wasm_shared_funcs = {
  102. "cpu_exception_hook": (n) => {
  103. return this["cpu_exception_hook"] && this["cpu_exception_hook"](n);
  104. },
  105. "hlt_op": function() { return cpu.hlt_op(); },
  106. "abort": function() { dbg_assert(false); },
  107. "microtick": v86.microtick,
  108. "get_rand_int": function() { return v86util.get_rand_int(); },
  109. "pic_acknowledge": function() { cpu.pic_acknowledge(); },
  110. "io_port_read8": function(addr) { return cpu.io.port_read8(addr); },
  111. "io_port_read16": function(addr) { return cpu.io.port_read16(addr); },
  112. "io_port_read32": function(addr) { return cpu.io.port_read32(addr); },
  113. "io_port_write8": function(addr, value) { cpu.io.port_write8(addr, value); },
  114. "io_port_write16": function(addr, value) { cpu.io.port_write16(addr, value); },
  115. "io_port_write32": function(addr, value) { cpu.io.port_write32(addr, value); },
  116. "mmap_read8": function(addr) { return cpu.mmap_read8(addr); },
  117. "mmap_read16": function(addr) { return cpu.mmap_read16(addr); },
  118. "mmap_read32": function(addr) { return cpu.mmap_read32(addr); },
  119. "mmap_write8": function(addr, value) { cpu.mmap_write8(addr, value); },
  120. "mmap_write16": function(addr, value) { cpu.mmap_write16(addr, value); },
  121. "mmap_write32": function(addr, value) { cpu.mmap_write32(addr, value); },
  122. "mmap_write64": function(addr, value0, value1) { cpu.mmap_write64(addr, value0, value1); },
  123. "mmap_write128": function(addr, value0, value1, value2, value3) {
  124. cpu.mmap_write128(addr, value0, value1, value2, value3);
  125. },
  126. "log_from_wasm": function(offset, len) {
  127. const str = v86util.read_sized_string_from_mem(wasm_memory, offset, len);
  128. dbg_log(str, LOG_CPU);
  129. },
  130. "console_log_from_wasm": function(offset, len) {
  131. const str = v86util.read_sized_string_from_mem(wasm_memory, offset, len);
  132. console.error(str);
  133. },
  134. "dbg_trace_from_wasm": function() {
  135. dbg_trace();
  136. },
  137. "codegen_finalize": (wasm_table_index, start, state_flags, ptr, len) => {
  138. cpu.codegen_finalize(wasm_table_index, start, state_flags, ptr, len);
  139. },
  140. "jit_clear_func": (wasm_table_index) => cpu.jit_clear_func(wasm_table_index),
  141. "jit_clear_all_funcs": () => cpu.jit_clear_all_funcs(),
  142. "__indirect_function_table": wasm_table,
  143. };
  144. let wasm_fn = options["wasm_fn"];
  145. if(!wasm_fn)
  146. {
  147. wasm_fn = env =>
  148. {
  149. return new Promise(resolve => {
  150. let v86_bin = DEBUG ? "v86-debug.wasm" : "v86.wasm";
  151. let v86_bin_fallback = "v86-fallback.wasm";
  152. if(options["wasm_path"])
  153. {
  154. v86_bin = options["wasm_path"];
  155. const slash = v86_bin.lastIndexOf("/");
  156. const dir = slash === -1 ? "" : v86_bin.substr(0, slash);
  157. v86_bin_fallback = dir + "/" + v86_bin_fallback;
  158. }
  159. else if(typeof window === "undefined" && typeof __dirname === "string")
  160. {
  161. v86_bin = __dirname + "/" + v86_bin;
  162. v86_bin_fallback = __dirname + "/" + v86_bin_fallback;
  163. }
  164. else
  165. {
  166. v86_bin = "build/" + v86_bin;
  167. v86_bin_fallback = "build/" + v86_bin_fallback;
  168. }
  169. v86util.load_file(v86_bin, {
  170. done: async bytes =>
  171. {
  172. try
  173. {
  174. const { instance } = await WebAssembly.instantiate(bytes, env);
  175. resolve(instance.exports);
  176. }
  177. catch(err)
  178. {
  179. v86util.load_file(v86_bin_fallback, {
  180. done: async bytes => {
  181. const { instance } = await WebAssembly.instantiate(bytes, env);
  182. resolve(instance.exports);
  183. },
  184. });
  185. }
  186. },
  187. progress: e =>
  188. {
  189. this.emulator_bus.send("download-progress", {
  190. file_index: 0,
  191. file_count: 1,
  192. file_name: v86_bin,
  193. lengthComputable: e.lengthComputable,
  194. total: e.total,
  195. loaded: e.loaded,
  196. });
  197. }
  198. });
  199. });
  200. };
  201. }
  202. wasm_fn({ "env": wasm_shared_funcs })
  203. .then((exports) => {
  204. wasm_memory = exports.memory;
  205. exports["rust_init"]();
  206. const emulator = this.v86 = new v86(this.emulator_bus, { exports, wasm_table });
  207. cpu = emulator.cpu;
  208. this.continue_init(emulator, options);
  209. });
  210. }
  211. V86Starter.prototype.continue_init = async function(emulator, options)
  212. {
  213. this.bus.register("emulator-stopped", function()
  214. {
  215. this.cpu_is_running = false;
  216. }, this);
  217. this.bus.register("emulator-started", function()
  218. {
  219. this.cpu_is_running = true;
  220. }, this);
  221. var settings = {};
  222. this.disk_images = {
  223. "fda": undefined,
  224. "fdb": undefined,
  225. "hda": undefined,
  226. "hdb": undefined,
  227. "cdrom": undefined,
  228. };
  229. settings.acpi = options["acpi"];
  230. settings.load_devices = true;
  231. settings.log_level = options["log_level"];
  232. settings.memory_size = options["memory_size"] || 64 * 1024 * 1024;
  233. settings.vga_memory_size = options["vga_memory_size"] || 8 * 1024 * 1024;
  234. settings.boot_order = options["boot_order"] || 0x213;
  235. settings.fastboot = options["fastboot"] || false;
  236. settings.fda = undefined;
  237. settings.fdb = undefined;
  238. settings.uart1 = options["uart1"];
  239. settings.uart2 = options["uart2"];
  240. settings.uart3 = options["uart3"];
  241. settings.cmdline = options["cmdline"];
  242. settings.preserve_mac_from_state_image = options["preserve_mac_from_state_image"];
  243. settings.mac_address_translation = options["mac_address_translation"];
  244. if(options["network_adapter"])
  245. {
  246. this.network_adapter = options["network_adapter"](this.bus);
  247. }
  248. else if(options["network_relay_url"])
  249. {
  250. this.network_adapter = new NetworkAdapter(options["network_relay_url"], this.bus);
  251. }
  252. // Enable unconditionally, so that state images don't miss hardware
  253. // TODO: Should be properly fixed in restore_state
  254. settings.enable_ne2k = true;
  255. if(!options["disable_keyboard"])
  256. {
  257. this.keyboard_adapter = new KeyboardAdapter(this.bus);
  258. }
  259. if(!options["disable_mouse"])
  260. {
  261. this.mouse_adapter = new MouseAdapter(this.bus, options["screen_container"]);
  262. }
  263. if(options["screen_container"])
  264. {
  265. this.screen_adapter = new ScreenAdapter(options["screen_container"], this.bus);
  266. }
  267. else if(options["screen_dummy"])
  268. {
  269. this.screen_adapter = new DummyScreenAdapter(this.bus);
  270. }
  271. if(options["serial_container"])
  272. {
  273. this.serial_adapter = new SerialAdapter(options["serial_container"], this.bus);
  274. //this.recording_adapter = new SerialRecordingAdapter(this.bus);
  275. }
  276. if(options["serial_container_xtermjs"])
  277. {
  278. this.serial_adapter = new SerialAdapterXtermJS(options["serial_container_xtermjs"], this.bus);
  279. }
  280. if(!options["disable_speaker"])
  281. {
  282. this.speaker_adapter = new SpeakerAdapter(this.bus);
  283. }
  284. // ugly, but required for closure compiler compilation
  285. function put_on_settings(name, buffer)
  286. {
  287. switch(name)
  288. {
  289. case "hda":
  290. settings.hda = this.disk_images["hda"] = buffer;
  291. break;
  292. case "hdb":
  293. settings.hdb = this.disk_images["hdb"] = buffer;
  294. break;
  295. case "cdrom":
  296. settings.cdrom = this.disk_images["cdrom"] = buffer;
  297. break;
  298. case "fda":
  299. settings.fda = this.disk_images["fda"] = buffer;
  300. break;
  301. case "fdb":
  302. settings.fdb = this.disk_images["fdb"] = buffer;
  303. break;
  304. case "multiboot":
  305. settings.multiboot = this.disk_images["multiboot"] = buffer.buffer;
  306. break;
  307. case "bzimage":
  308. settings.bzimage = this.disk_images["bzimage"] = buffer.buffer;
  309. break;
  310. case "initrd":
  311. settings.initrd = this.disk_images["initrd"] = buffer.buffer;
  312. break;
  313. case "bios":
  314. settings.bios = buffer.buffer;
  315. break;
  316. case "vga_bios":
  317. settings.vga_bios = buffer.buffer;
  318. break;
  319. case "initial_state":
  320. settings.initial_state = buffer.buffer;
  321. break;
  322. case "fs9p_json":
  323. settings.fs9p_json = buffer;
  324. break;
  325. default:
  326. dbg_assert(false, name);
  327. }
  328. }
  329. var files_to_load = [];
  330. function add_file(name, file)
  331. {
  332. if(!file)
  333. {
  334. return;
  335. }
  336. if(file["get"] && file["set"] && file["load"])
  337. {
  338. files_to_load.push({
  339. name: name,
  340. loadable: file,
  341. });
  342. return;
  343. }
  344. // Anything coming from the outside world needs to be quoted for
  345. // Closure Compiler compilation
  346. file = {
  347. buffer: file["buffer"],
  348. async: file["async"],
  349. url: file["url"],
  350. size: file["size"],
  351. fixed_chunk_size: file["fixed_chunk_size"],
  352. use_parts: file.use_parts,
  353. };
  354. if(name === "bios" || name === "vga_bios" ||
  355. name === "initial_state" || name === "multiboot" ||
  356. name === "bzimage" || name === "initrd")
  357. {
  358. // Ignore async for these because they must be available before boot.
  359. // This should make result.buffer available after the object is loaded
  360. file.async = false;
  361. }
  362. if(file.buffer instanceof ArrayBuffer)
  363. {
  364. var buffer = new SyncBuffer(file.buffer);
  365. files_to_load.push({
  366. name: name,
  367. loadable: buffer,
  368. });
  369. }
  370. else if(typeof File !== "undefined" && file.buffer instanceof File)
  371. {
  372. // SyncFileBuffer:
  373. // - loads the whole disk image into memory, impossible for large files (more than 1GB)
  374. // - can later serve get/set operations fast and synchronously
  375. // - takes some time for first load, neglectable for small files (up to 100Mb)
  376. //
  377. // AsyncFileBuffer:
  378. // - loads slices of the file asynchronously as requested
  379. // - slower get/set
  380. // Heuristics: If file is larger than or equal to 256M, use AsyncFileBuffer
  381. if(file.async === undefined)
  382. {
  383. file.async = file.buffer.size >= 256 * 1024 * 1024;
  384. }
  385. if(file.async)
  386. {
  387. var buffer = new v86util.AsyncFileBuffer(file.buffer);
  388. }
  389. else
  390. {
  391. var buffer = new v86util.SyncFileBuffer(file.buffer);
  392. }
  393. files_to_load.push({
  394. name: name,
  395. loadable: buffer,
  396. });
  397. }
  398. else if(file.url)
  399. {
  400. if(file.async)
  401. {
  402. let buffer;
  403. if(file.use_parts)
  404. {
  405. buffer = new v86util.AsyncXHRPartfileBuffer(file.url, file.size, file.fixed_chunk_size);
  406. }
  407. else
  408. {
  409. buffer = new v86util.AsyncXHRBuffer(file.url, file.size);
  410. }
  411. files_to_load.push({
  412. name: name,
  413. loadable: buffer,
  414. });
  415. }
  416. else
  417. {
  418. files_to_load.push({
  419. name: name,
  420. url: file.url,
  421. size: file.size,
  422. });
  423. }
  424. }
  425. else
  426. {
  427. dbg_log("Ignored file: url=" + file.url + " buffer=" + file.buffer);
  428. }
  429. }
  430. if(options["state"])
  431. {
  432. console.warn("Warning: Unknown option 'state'. Did you mean 'initial_state'?");
  433. }
  434. var image_names = [
  435. "bios", "vga_bios",
  436. "cdrom", "hda", "hdb", "fda", "fdb",
  437. "initial_state", "multiboot",
  438. "bzimage", "initrd",
  439. ];
  440. for(var i = 0; i < image_names.length; i++)
  441. {
  442. add_file(image_names[i], options[image_names[i]]);
  443. }
  444. if(options["filesystem"])
  445. {
  446. var fs_url = options["filesystem"]["basefs"];
  447. var base_url = options["filesystem"]["baseurl"];
  448. let file_storage = new MemoryFileStorage();
  449. if(base_url)
  450. {
  451. file_storage = new ServerFileStorageWrapper(file_storage, base_url);
  452. }
  453. settings.fs9p = this.fs9p = new FS(file_storage);
  454. if(fs_url)
  455. {
  456. console.assert(base_url, "Filesystem: baseurl must be specified");
  457. var size;
  458. if(typeof fs_url === "object")
  459. {
  460. size = fs_url["size"];
  461. fs_url = fs_url["url"];
  462. }
  463. dbg_assert(typeof fs_url === "string");
  464. files_to_load.push({
  465. name: "fs9p_json",
  466. url: fs_url,
  467. size: size,
  468. as_json: true,
  469. });
  470. }
  471. }
  472. var starter = this;
  473. var total = files_to_load.length;
  474. var cont = function(index)
  475. {
  476. if(index === total)
  477. {
  478. setTimeout(done.bind(this), 0);
  479. return;
  480. }
  481. var f = files_to_load[index];
  482. if(f.loadable)
  483. {
  484. f.loadable.onload = function(e)
  485. {
  486. put_on_settings.call(this, f.name, f.loadable);
  487. cont(index + 1);
  488. }.bind(this);
  489. f.loadable.load();
  490. }
  491. else
  492. {
  493. v86util.load_file(f.url, {
  494. done: function(result)
  495. {
  496. put_on_settings.call(this, f.name, f.as_json ? result : new SyncBuffer(result));
  497. cont(index + 1);
  498. }.bind(this),
  499. progress: function progress(e)
  500. {
  501. if(e.target.status === 200)
  502. {
  503. starter.emulator_bus.send("download-progress", {
  504. file_index: index,
  505. file_count: total,
  506. file_name: f.url,
  507. lengthComputable: e.lengthComputable,
  508. total: e.total || f.size,
  509. loaded: e.loaded,
  510. });
  511. }
  512. else
  513. {
  514. starter.emulator_bus.send("download-error", {
  515. file_index: index,
  516. file_count: total,
  517. file_name: f.url,
  518. request: e.target,
  519. });
  520. }
  521. },
  522. as_json: f.as_json,
  523. });
  524. }
  525. }.bind(this);
  526. cont(0);
  527. async function done()
  528. {
  529. //if(settings.initial_state)
  530. //{
  531. // // avoid large allocation now, memory will be restored later anyway
  532. // settings.memory_size = 0;
  533. //}
  534. if(settings.fs9p && settings.fs9p_json)
  535. {
  536. if(!settings.initial_state)
  537. {
  538. settings.fs9p.load_from_json(settings.fs9p_json);
  539. }
  540. else
  541. {
  542. dbg_log("Filesystem basefs ignored: Overridden by state image");
  543. }
  544. if(options["bzimage_initrd_from_filesystem"])
  545. {
  546. const { bzimage_path, initrd_path } = this.get_bzimage_initrd_from_filesystem(settings.fs9p);
  547. dbg_log("Found bzimage: " + bzimage_path + " and initrd: " + initrd_path);
  548. const [initrd, bzimage] = await Promise.all([
  549. settings.fs9p.read_file(initrd_path),
  550. settings.fs9p.read_file(bzimage_path),
  551. ]);
  552. put_on_settings.call(this, "initrd", new SyncBuffer(initrd.buffer));
  553. put_on_settings.call(this, "bzimage", new SyncBuffer(bzimage.buffer));
  554. finish.call(this);
  555. }
  556. else
  557. {
  558. finish.call(this);
  559. }
  560. }
  561. else
  562. {
  563. console.assert(
  564. !options["bzimage_initrd_from_filesystem"],
  565. "bzimage_initrd_from_filesystem: Requires a filesystem");
  566. finish.call(this);
  567. }
  568. function finish()
  569. {
  570. this.serial_adapter && this.serial_adapter.show && this.serial_adapter.show();
  571. this.bus.send("cpu-init", settings);
  572. if(settings.initial_state)
  573. {
  574. emulator.restore_state(settings.initial_state);
  575. // The GC can't free settings, since it is referenced from
  576. // several closures. This isn't needed anymore, so we delete it
  577. // here
  578. settings.initial_state = undefined;
  579. }
  580. if(options["autostart"])
  581. {
  582. this.bus.send("cpu-run");
  583. }
  584. this.emulator_bus.send("emulator-loaded");
  585. }
  586. }
  587. };
  588. V86Starter.prototype.get_bzimage_initrd_from_filesystem = function(filesystem)
  589. {
  590. const root = (filesystem.read_dir("/") || []).map(x => "/" + x);
  591. const boot = (filesystem.read_dir("/boot/") || []).map(x => "/boot/" + x);
  592. let initrd_path;
  593. let bzimage_path;
  594. for(let f of [].concat(root, boot))
  595. {
  596. const old = /old/i.test(f) || /fallback/i.test(f);
  597. const is_bzimage = /vmlinuz/i.test(f) || /bzimage/i.test(f);
  598. const is_initrd = /initrd/i.test(f) || /initramfs/i.test(f);
  599. if(is_bzimage && (!bzimage_path || !old))
  600. {
  601. bzimage_path = f;
  602. }
  603. if(is_initrd && (!initrd_path || !old))
  604. {
  605. initrd_path = f;
  606. }
  607. }
  608. if(!initrd_path || !bzimage_path)
  609. {
  610. console.log("Failed to find bzimage or initrd in filesystem. Files:");
  611. console.log(root.join(" "));
  612. console.log(boot.join(" "));
  613. }
  614. return { initrd_path, bzimage_path };
  615. };
  616. /**
  617. * Start emulation. Do nothing if emulator is running already. Can be
  618. * asynchronous.
  619. * @export
  620. */
  621. V86Starter.prototype.run = async function()
  622. {
  623. this.bus.send("cpu-run");
  624. };
  625. /**
  626. * Stop emulation. Do nothing if emulator is not running. Can be asynchronous.
  627. * @export
  628. */
  629. V86Starter.prototype.stop = async function()
  630. {
  631. this.bus.send("cpu-stop");
  632. };
  633. /**
  634. * @ignore
  635. * @export
  636. */
  637. V86Starter.prototype.destroy = function()
  638. {
  639. this.stop();
  640. this.v86.destroy();
  641. this.keyboard_adapter && this.keyboard_adapter.destroy();
  642. this.network_adapter && this.network_adapter.destroy();
  643. this.mouse_adapter && this.mouse_adapter.destroy();
  644. this.screen_adapter && this.screen_adapter.destroy();
  645. this.serial_adapter && this.serial_adapter.destroy();
  646. };
  647. /**
  648. * Restart (force a reboot).
  649. * @export
  650. */
  651. V86Starter.prototype.restart = function()
  652. {
  653. this.bus.send("cpu-restart");
  654. };
  655. /**
  656. * Add an event listener (the emulator is an event emitter). A list of events
  657. * can be found at [events.md](events.md).
  658. *
  659. * The callback function gets a single argument which depends on the event.
  660. *
  661. * @param {string} event Name of the event.
  662. * @param {function(*)} listener The callback function.
  663. * @export
  664. */
  665. V86Starter.prototype.add_listener = function(event, listener)
  666. {
  667. this.bus.register(event, listener, this);
  668. };
  669. /**
  670. * Remove an event listener.
  671. *
  672. * @param {string} event
  673. * @param {function(*)} listener
  674. * @export
  675. */
  676. V86Starter.prototype.remove_listener = function(event, listener)
  677. {
  678. this.bus.unregister(event, listener);
  679. };
  680. /**
  681. * Restore the emulator state from the given state, which must be an
  682. * ArrayBuffer returned by
  683. * [`save_state`](#save_statefunctionobject-arraybuffer-callback).
  684. *
  685. * Note that the state can only be restored correctly if this constructor has
  686. * been created with the same options as the original instance (e.g., same disk
  687. * images, memory size, etc.).
  688. *
  689. * Different versions of the emulator might use a different format for the
  690. * state buffer.
  691. *
  692. * @param {ArrayBuffer} state
  693. * @export
  694. */
  695. V86Starter.prototype.restore_state = async function(state)
  696. {
  697. console.assert(arguments.length === 1);
  698. this.v86.restore_state(state);
  699. };
  700. /**
  701. * Asynchronously save the current state of the emulator.
  702. *
  703. * @return {Promise<ArrayBuffer>}
  704. * @export
  705. */
  706. V86Starter.prototype.save_state = async function()
  707. {
  708. console.assert(arguments.length === 0);
  709. return this.v86.save_state();
  710. };
  711. /**
  712. * Return an object with several statistics. Return value looks similar to
  713. * (but can be subject to change in future versions or different
  714. * configurations, so use defensively):
  715. *
  716. * ```javascript
  717. * {
  718. * "cpu": {
  719. * "instruction_counter": 2821610069
  720. * },
  721. * "hda": {
  722. * "sectors_read": 95240,
  723. * "sectors_written": 952,
  724. * "bytes_read": 48762880,
  725. * "bytes_written": 487424,
  726. * "loading": false
  727. * },
  728. * "cdrom": {
  729. * "sectors_read": 0,
  730. * "sectors_written": 0,
  731. * "bytes_read": 0,
  732. * "bytes_written": 0,
  733. * "loading": false
  734. * },
  735. * "mouse": {
  736. * "enabled": true
  737. * },
  738. * "vga": {
  739. * "is_graphical": true,
  740. * "res_x": 800,
  741. * "res_y": 600,
  742. * "bpp": 32
  743. * }
  744. * }
  745. * ```
  746. *
  747. * @deprecated
  748. * @return {Object}
  749. * @export
  750. */
  751. V86Starter.prototype.get_statistics = function()
  752. {
  753. console.warn("V86Starter.prototype.get_statistics is deprecated. Use events instead.");
  754. var stats = {
  755. cpu: {
  756. instruction_counter: this.get_instruction_counter(),
  757. },
  758. };
  759. if(!this.v86)
  760. {
  761. return stats;
  762. }
  763. var devices = this.v86.cpu.devices;
  764. if(devices.hda)
  765. {
  766. stats.hda = devices.hda.stats;
  767. }
  768. if(devices.cdrom)
  769. {
  770. stats.cdrom = devices.cdrom.stats;
  771. }
  772. if(devices.ps2)
  773. {
  774. stats["mouse"] = {
  775. "enabled": devices.ps2.use_mouse,
  776. };
  777. }
  778. if(devices.vga)
  779. {
  780. stats["vga"] = {
  781. "is_graphical": devices.vga.stats.is_graphical,
  782. };
  783. }
  784. return stats;
  785. };
  786. /**
  787. * @return {number}
  788. * @ignore
  789. * @export
  790. */
  791. V86Starter.prototype.get_instruction_counter = function()
  792. {
  793. if(this.v86)
  794. {
  795. return this.v86.cpu.instruction_counter[0] >>> 0;
  796. }
  797. else
  798. {
  799. // TODO: Should be handled using events
  800. return 0;
  801. }
  802. };
  803. /**
  804. * @return {boolean}
  805. * @export
  806. */
  807. V86Starter.prototype.is_running = function()
  808. {
  809. return this.cpu_is_running;
  810. };
  811. /**
  812. * Send a sequence of scan codes to the emulated PS2 controller. A list of
  813. * codes can be found at http://stanislavs.org/helppc/make_codes.html.
  814. * Do nothing if there is no keyboard controller.
  815. *
  816. * @param {Array.<number>} codes
  817. * @export
  818. */
  819. V86Starter.prototype.keyboard_send_scancodes = function(codes)
  820. {
  821. for(var i = 0; i < codes.length; i++)
  822. {
  823. this.bus.send("keyboard-code", codes[i]);
  824. }
  825. };
  826. /**
  827. * Send translated keys
  828. * @ignore
  829. * @export
  830. */
  831. V86Starter.prototype.keyboard_send_keys = function(codes)
  832. {
  833. for(var i = 0; i < codes.length; i++)
  834. {
  835. this.keyboard_adapter.simulate_press(codes[i]);
  836. }
  837. };
  838. /**
  839. * Send text
  840. * @ignore
  841. * @export
  842. */
  843. V86Starter.prototype.keyboard_send_text = function(string)
  844. {
  845. for(var i = 0; i < string.length; i++)
  846. {
  847. this.keyboard_adapter.simulate_char(string[i]);
  848. }
  849. };
  850. /**
  851. * Download a screenshot.
  852. *
  853. * @ignore
  854. * @export
  855. */
  856. V86Starter.prototype.screen_make_screenshot = function()
  857. {
  858. if(this.screen_adapter)
  859. {
  860. this.screen_adapter.make_screenshot();
  861. }
  862. };
  863. /**
  864. * Set the scaling level of the emulated screen.
  865. *
  866. * @param {number} sx
  867. * @param {number} sy
  868. *
  869. * @ignore
  870. * @export
  871. */
  872. V86Starter.prototype.screen_set_scale = function(sx, sy)
  873. {
  874. if(this.screen_adapter)
  875. {
  876. this.screen_adapter.set_scale(sx, sy);
  877. }
  878. };
  879. /**
  880. * Go fullscreen.
  881. *
  882. * @ignore
  883. * @export
  884. */
  885. V86Starter.prototype.screen_go_fullscreen = function()
  886. {
  887. if(!this.screen_adapter)
  888. {
  889. return;
  890. }
  891. var elem = document.getElementById("screen_container");
  892. if(!elem)
  893. {
  894. return;
  895. }
  896. // bracket notation because otherwise they get renamed by closure compiler
  897. var fn = elem["requestFullScreen"] ||
  898. elem["webkitRequestFullscreen"] ||
  899. elem["mozRequestFullScreen"] ||
  900. elem["msRequestFullScreen"];
  901. if(fn)
  902. {
  903. fn.call(elem);
  904. // This is necessary, because otherwise chromium keyboard doesn't work anymore.
  905. // Might (but doesn't seem to) break something else
  906. var focus_element = document.getElementsByClassName("phone_keyboard")[0];
  907. focus_element && focus_element.focus();
  908. }
  909. try {
  910. navigator.keyboard.lock();
  911. } catch(e) {}
  912. this.lock_mouse();
  913. };
  914. /**
  915. * Lock the mouse cursor: It becomes invisble and is not moved out of the
  916. * browser window.
  917. *
  918. * @ignore
  919. * @export
  920. */
  921. V86Starter.prototype.lock_mouse = function()
  922. {
  923. var elem = document.body;
  924. var fn = elem["requestPointerLock"] ||
  925. elem["mozRequestPointerLock"] ||
  926. elem["webkitRequestPointerLock"];
  927. if(fn)
  928. {
  929. fn.call(elem);
  930. }
  931. };
  932. /**
  933. * Enable or disable sending mouse events to the emulated PS2 controller.
  934. *
  935. * @param {boolean} enabled
  936. */
  937. V86Starter.prototype.mouse_set_status = function(enabled)
  938. {
  939. if(this.mouse_adapter)
  940. {
  941. this.mouse_adapter.emu_enabled = enabled;
  942. }
  943. };
  944. /**
  945. * Enable or disable sending keyboard events to the emulated PS2 controller.
  946. *
  947. * @param {boolean} enabled
  948. * @export
  949. */
  950. V86Starter.prototype.keyboard_set_status = function(enabled)
  951. {
  952. if(this.keyboard_adapter)
  953. {
  954. this.keyboard_adapter.emu_enabled = enabled;
  955. }
  956. };
  957. /**
  958. * Send a string to the first emulated serial terminal.
  959. *
  960. * @param {string} data
  961. * @export
  962. */
  963. V86Starter.prototype.serial0_send = function(data)
  964. {
  965. for(var i = 0; i < data.length; i++)
  966. {
  967. this.bus.send("serial0-input", data.charCodeAt(i));
  968. }
  969. };
  970. /**
  971. * Send bytes to a serial port (to be received by the emulated PC).
  972. *
  973. * @param {Uint8Array} data
  974. * @export
  975. */
  976. V86Starter.prototype.serial_send_bytes = function(serial, data)
  977. {
  978. for(var i = 0; i < data.length; i++)
  979. {
  980. this.bus.send("serial" + serial + "-input", data[i]);
  981. }
  982. };
  983. /**
  984. * Mount another filesystem to the current filesystem.
  985. * @param {string} path Path for the mount point
  986. * @param {string|undefined} baseurl
  987. * @param {string|undefined} basefs As a JSON string
  988. * @param {function(Object)=} callback
  989. * @export
  990. */
  991. V86Starter.prototype.mount_fs = async function(path, baseurl, basefs, callback)
  992. {
  993. let file_storage = new MemoryFileStorage();
  994. if(baseurl)
  995. {
  996. file_storage = new ServerFileStorageWrapper(file_storage, baseurl);
  997. }
  998. const newfs = new FS(file_storage, this.fs9p.qidcounter);
  999. const mount = () =>
  1000. {
  1001. const idx = this.fs9p.Mount(path, newfs);
  1002. if(!callback)
  1003. {
  1004. return;
  1005. }
  1006. if(idx === -ENOENT)
  1007. {
  1008. callback(new FileNotFoundError());
  1009. }
  1010. else if(idx === -EEXIST)
  1011. {
  1012. callback(new FileExistsError());
  1013. }
  1014. else if(idx < 0)
  1015. {
  1016. dbg_assert(false, "Unexpected error code: " + (-idx));
  1017. callback(new Error("Failed to mount. Error number: " + (-idx)));
  1018. }
  1019. else
  1020. {
  1021. callback(null);
  1022. }
  1023. };
  1024. if(baseurl)
  1025. {
  1026. dbg_assert(typeof basefs === "object", "Filesystem: basefs must be a JSON object");
  1027. newfs.load_from_json(basefs, () => mount());
  1028. }
  1029. else
  1030. {
  1031. mount();
  1032. }
  1033. };
  1034. /**
  1035. * Write to a file in the 9p filesystem. Nothing happens if no filesystem has
  1036. * been initialized.
  1037. *
  1038. * @param {string} file
  1039. * @param {Uint8Array} data
  1040. * @export
  1041. */
  1042. V86Starter.prototype.create_file = async function(file, data)
  1043. {
  1044. console.assert(arguments.length === 2);
  1045. var fs = this.fs9p;
  1046. if(!fs)
  1047. {
  1048. return;
  1049. }
  1050. var parts = file.split("/");
  1051. var filename = parts[parts.length - 1];
  1052. var path_infos = fs.SearchPath(file);
  1053. var parent_id = path_infos.parentid;
  1054. var not_found = filename === "" || parent_id === -1;
  1055. if(!not_found)
  1056. {
  1057. await fs.CreateBinaryFile(filename, parent_id, data);
  1058. }
  1059. else
  1060. {
  1061. return Promise.reject(new FileNotFoundError());
  1062. }
  1063. };
  1064. /**
  1065. * Read a file in the 9p filesystem. Nothing happens if no filesystem has been
  1066. * initialized.
  1067. *
  1068. * @param {string} file
  1069. * @export
  1070. */
  1071. V86Starter.prototype.read_file = async function(file)
  1072. {
  1073. console.assert(arguments.length === 1);
  1074. var fs = this.fs9p;
  1075. if(!fs)
  1076. {
  1077. return;
  1078. }
  1079. const result = await fs.read_file(file);
  1080. if(result)
  1081. {
  1082. return result;
  1083. }
  1084. else
  1085. {
  1086. return Promise.reject(new FileNotFoundError());
  1087. }
  1088. };
  1089. V86Starter.prototype.automatically = function(steps)
  1090. {
  1091. const run = (steps) =>
  1092. {
  1093. const step = steps[0];
  1094. if(!step)
  1095. {
  1096. return;
  1097. }
  1098. const remaining_steps = steps.slice(1);
  1099. if(step.sleep)
  1100. {
  1101. setTimeout(() => run(remaining_steps), step.sleep * 1000);
  1102. return;
  1103. }
  1104. if(step.vga_text)
  1105. {
  1106. const screen = this.screen_adapter.get_text_screen();
  1107. for(let line of screen)
  1108. {
  1109. if(line.includes(step.vga_text))
  1110. {
  1111. run(remaining_steps);
  1112. return;
  1113. }
  1114. }
  1115. setTimeout(() => run(steps), 1000);
  1116. return;
  1117. }
  1118. if(step.keyboard_send)
  1119. {
  1120. if(step.keyboard_send instanceof Array)
  1121. {
  1122. this.keyboard_send_scancodes(step.keyboard_send);
  1123. }
  1124. else
  1125. {
  1126. dbg_assert(typeof step.keyboard_send === "string");
  1127. this.keyboard_send_text(step.keyboard_send);
  1128. }
  1129. run(remaining_steps);
  1130. return;
  1131. }
  1132. if(step.call)
  1133. {
  1134. step.call();
  1135. run(remaining_steps);
  1136. return;
  1137. }
  1138. console.assert(false, step);
  1139. };
  1140. run(steps);
  1141. };
  1142. /**
  1143. * Reads data from memory at specified offset.
  1144. *
  1145. * @param {number} offset
  1146. * @param {number} length
  1147. * @returns
  1148. */
  1149. V86Starter.prototype.read_memory = function(offset, length)
  1150. {
  1151. return this.v86.cpu.read_blob(offset, length);
  1152. };
  1153. /**
  1154. * Writes data to memory at specified offset.
  1155. *
  1156. * @param {Array.<number>|Uint8Array} blob
  1157. * @param {number} offset
  1158. */
  1159. V86Starter.prototype.write_memory = function(blob, offset)
  1160. {
  1161. this.v86.cpu.write_blob(blob, offset);
  1162. };
  1163. /**
  1164. * @ignore
  1165. * @constructor
  1166. *
  1167. * @param {string=} message
  1168. */
  1169. function FileExistsError(message)
  1170. {
  1171. this.message = message || "File already exists";
  1172. }
  1173. FileExistsError.prototype = Error.prototype;
  1174. /**
  1175. * @ignore
  1176. * @constructor
  1177. *
  1178. * @param {string=} message
  1179. */
  1180. function FileNotFoundError(message)
  1181. {
  1182. this.message = message || "File not found";
  1183. }
  1184. FileNotFoundError.prototype = Error.prototype;
  1185. // Closure Compiler's way of exporting
  1186. if(typeof window !== "undefined")
  1187. {
  1188. window["V86Starter"] = V86Starter;
  1189. window["V86"] = V86Starter;
  1190. }
  1191. else if(typeof module !== "undefined" && typeof module.exports !== "undefined")
  1192. {
  1193. module.exports["V86Starter"] = V86Starter;
  1194. module.exports["V86"] = V86Starter;
  1195. }
  1196. else if(typeof importScripts === "function")
  1197. {
  1198. // web worker
  1199. self["V86Starter"] = V86Starter;
  1200. self["V86"] = V86Starter;
  1201. }