-
Notifications
You must be signed in to change notification settings - Fork 0
/
starter.js
1480 lines (1310 loc) · 41.1 KB
/
starter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/**
* Constructor for emulator instances.
*
* Usage: `new V86(options);`
*
* Options can have the following properties (all optional, default in parenthesis):
*
* - `memory_size number` (64 * 1024 * 1024) - The memory size in bytes, should
* be a power of 2.
* - `vga_memory_size number` (8 * 1024 * 1024) - VGA memory size in bytes.
*
* - `autostart boolean` (false) - If emulation should be started when emulator
* is ready.
*
* - `disable_keyboard boolean` (false) - If the keyboard should be disabled.
* - `disable_mouse boolean` (false) - If the mouse should be disabled.
*
* - `network_relay_url string` (No network card) - The url of a server running
* websockproxy. See [networking.md](networking.md). Setting this will
* enable an emulated ne2k network card. Only provided for backwards
* compatibility, use `net_device` instead.
*
* - `net_device Object` (null) - An object with the following properties:
* - `relay_url: string` - See above
* - `type: "ne2k" | "virtio"` - the type of the emulated cards
*
* - `net_devices Array<Object>` - Like `net_device`, but allows specifying
* more than one network card (up to 4). (currently not implemented)
*
* - `bios Object` (No bios) - Either a url pointing to a bios or an
* ArrayBuffer, see below.
* - `vga_bios Object` (No VGA bios) - VGA bios, see below.
* - `hda Object` (No hard disk) - First hard disk, see below.
* - `fda Object` (No floppy disk) - First floppy disk, see below.
* - `cdrom Object` (No CD) - See below.
*
* - `bzimage Object` - A Linux kernel image to boot (only bzimage format), see below.
* - `initrd Object` - A Linux ramdisk image, see below.
* - `bzimage_initrd_from_filesystem boolean` - Automatically fetch bzimage and
* initrd from the specified `filesystem`.
*
* - `initial_state Object` (Normal boot) - An initial state to load, see
* [`restore_state`](#restore_statearraybuffer-state) and below.
*
* - `filesystem Object` (No 9p filesystem) - A 9p filesystem, see
* [filesystem.md](filesystem.md).
*
* - `serial_container HTMLTextAreaElement` (No serial terminal) - A textarea
* that will receive and send data to the emulated serial terminal.
* Alternatively the serial terminal can also be accessed programatically,
* see [serial.html](../examples/serial.html).
*
* - `screen_container HTMLElement` (No screen) - An HTMLElement. This should
* have a certain structure, see [basic.html](../examples/basic.html). Only
* provided for backwards compatibility, use `screen` instead.
*
* - `screen Object` (No screen) - An object with the following properties:
* - `container HTMLElement` - An HTMLElement, see above.
* - `scale` (1) - Set initial scale_x and scale_y, if 0 disable automatic upscaling and dpi-adaption
*
* ***
*
* There are two ways to load images (`bios`, `vga_bios`, `cdrom`, `hda`, ...):
*
* - Pass an object that has a url. Optionally, `async: true` and `size:
* size_in_bytes` can be added to the object, so that sectors of the image
* are loaded on demand instead of being loaded before boot (slower, but
* strongly recommended for big files). In that case, the `Range: bytes=...`
* header must be supported on the server.
*
* ```javascript
* // download file before boot
* bios: {
* url: "bios/seabios.bin"
* }
* // download file sectors as requested, size is required
* hda: {
* url: "disk/linux.iso",
* async: true,
* size: 16 * 1024 * 1024
* }
* ```
*
* - Pass an `ArrayBuffer` or `File` object as `buffer` property.
*
* ```javascript
* // use <input type=file>
* bios: {
* buffer: document.all.hd_image.files[0]
* }
* // start with empty hard disk
* hda: {
* buffer: new ArrayBuffer(16 * 1024 * 1024)
* }
* ```
*
* @param {{
disable_mouse: (boolean|undefined),
disable_keyboard: (boolean|undefined),
wasm_fn: (Function|undefined),
screen: ({
scale: (number|undefined),
} | undefined),
}} options
* @constructor
*/
function V86(options)
{
if(typeof options.log_level === "number")
{
// XXX: Shared between all emulator instances
LOG_LEVEL = options.log_level;
}
//var worker = new Worker("src/browser/worker.js");
//var adapter_bus = this.bus = WorkerBus.init(worker);
this.cpu_is_running = false;
this.cpu_exception_hook = function(n) {};
const bus = Bus.create();
const adapter_bus = this.bus = bus[0];
this.emulator_bus = bus[1];
var cpu;
var wasm_memory;
const wasm_table = new WebAssembly.Table({ element: "anyfunc", initial: WASM_TABLE_SIZE + WASM_TABLE_OFFSET });
const wasm_shared_funcs = {
"cpu_exception_hook": n => this.cpu_exception_hook(n),
"run_hardware_timers": function(a, t) { return cpu.run_hardware_timers(a, t); },
"cpu_event_halt": () => { this.emulator_bus.send("cpu-event-halt"); },
"abort": function() { dbg_assert(false); },
"microtick": v86.microtick,
"get_rand_int": function() { return v86util.get_rand_int(); },
"apic_acknowledge_irq": function() { return cpu.devices.apic.acknowledge_irq(); },
"stop_idling": function() { return cpu.stop_idling(); },
"io_port_read8": function(addr) { return cpu.io.port_read8(addr); },
"io_port_read16": function(addr) { return cpu.io.port_read16(addr); },
"io_port_read32": function(addr) { return cpu.io.port_read32(addr); },
"io_port_write8": function(addr, value) { cpu.io.port_write8(addr, value); },
"io_port_write16": function(addr, value) { cpu.io.port_write16(addr, value); },
"io_port_write32": function(addr, value) { cpu.io.port_write32(addr, value); },
"mmap_read8": function(addr) { return cpu.mmap_read8(addr); },
"mmap_read16": function(addr) { return cpu.mmap_read16(addr); },
"mmap_read32": function(addr) { return cpu.mmap_read32(addr); },
"mmap_write8": function(addr, value) { cpu.mmap_write8(addr, value); },
"mmap_write16": function(addr, value) { cpu.mmap_write16(addr, value); },
"mmap_write32": function(addr, value) { cpu.mmap_write32(addr, value); },
"mmap_write64": function(addr, value0, value1) { cpu.mmap_write64(addr, value0, value1); },
"mmap_write128": function(addr, value0, value1, value2, value3) {
cpu.mmap_write128(addr, value0, value1, value2, value3);
},
"log_from_wasm": function(offset, len) {
const str = v86util.read_sized_string_from_mem(wasm_memory, offset, len);
dbg_log(str, LOG_CPU);
},
"console_log_from_wasm": function(offset, len) {
const str = v86util.read_sized_string_from_mem(wasm_memory, offset, len);
console.error(str);
},
"dbg_trace_from_wasm": function() {
dbg_trace(LOG_CPU);
},
"codegen_finalize": (wasm_table_index, start, state_flags, ptr, len) => {
cpu.codegen_finalize(wasm_table_index, start, state_flags, ptr, len);
},
"jit_clear_func": (wasm_table_index) => cpu.jit_clear_func(wasm_table_index),
"jit_clear_all_funcs": () => cpu.jit_clear_all_funcs(),
"__indirect_function_table": wasm_table,
};
let wasm_fn = options.wasm_fn;
if(!wasm_fn)
{
wasm_fn = env =>
{
return new Promise(resolve => {
let v86_bin = DEBUG ? "v86-debug.wasm" : "v86.wasm";
let v86_bin_fallback = "v86-fallback.wasm";
if(options.wasm_path)
{
v86_bin = options.wasm_path;
const slash = v86_bin.lastIndexOf("/");
const dir = slash === -1 ? "" : v86_bin.substr(0, slash);
v86_bin_fallback = dir + "/" + v86_bin_fallback;
}
else if(typeof window === "undefined" && typeof __dirname === "string")
{
v86_bin = __dirname + "/" + v86_bin;
v86_bin_fallback = __dirname + "/" + v86_bin_fallback;
}
else
{
v86_bin = "build/" + v86_bin;
v86_bin_fallback = "build/" + v86_bin_fallback;
}
v86util.load_file(v86_bin, {
done: async bytes =>
{
try
{
const { instance } = await WebAssembly.instantiate(bytes, env);
this.wasm_source = bytes;
resolve(instance.exports);
}
catch(err)
{
v86util.load_file(v86_bin_fallback, {
done: async bytes => {
const { instance } = await WebAssembly.instantiate(bytes, env);
this.wasm_source = bytes;
resolve(instance.exports);
},
});
}
},
progress: e =>
{
this.emulator_bus.send("download-progress", {
file_index: 0,
file_count: 1,
file_name: v86_bin,
lengthComputable: e.lengthComputable,
total: e.total,
loaded: e.loaded,
});
}
});
});
};
}
wasm_fn({ "env": wasm_shared_funcs })
.then((exports) => {
wasm_memory = exports.memory;
exports["rust_init"]();
const emulator = this.v86 = new v86(this.emulator_bus, { exports, wasm_table });
cpu = emulator.cpu;
this.continue_init(emulator, options);
});
this.zstd_worker = null;
this.zstd_worker_request_id = 0;
}
V86.prototype.continue_init = async function(emulator, options)
{
this.bus.register("emulator-stopped", function()
{
this.cpu_is_running = false;
this.screen_adapter.pause();
}, this);
this.bus.register("emulator-started", function()
{
this.cpu_is_running = true;
this.screen_adapter.continue();
}, this);
var settings = {};
this.disk_images = {
fda: undefined,
fdb: undefined,
hda: undefined,
hdb: undefined,
cdrom: undefined,
};
const boot_order =
options.boot_order ? options.boot_order :
options.fda ? BOOT_ORDER_FD_FIRST :
options.hda ? BOOT_ORDER_HD_FIRST : BOOT_ORDER_CD_FIRST;
settings.acpi = options.acpi;
settings.disable_jit = options.disable_jit;
settings.load_devices = true;
settings.memory_size = options.memory_size || 64 * 1024 * 1024;
settings.vga_memory_size = options.vga_memory_size || 8 * 1024 * 1024;
settings.boot_order = boot_order;
settings.fastboot = options.fastboot || false;
settings.fda = undefined;
settings.fdb = undefined;
settings.uart1 = options.uart1;
settings.uart2 = options.uart2;
settings.uart3 = options.uart3;
settings.cmdline = options.cmdline;
settings.preserve_mac_from_state_image = options.preserve_mac_from_state_image;
settings.mac_address_translation = options.mac_address_translation;
settings.cpuid_level = options.cpuid_level;
settings.virtio_console = options.virtio_console;
settings.virtio_net = options.virtio_net;
settings.screen_options = options.screen_options;
const relay_url = options.network_relay_url || options.net_device && options.net_device.relay_url;
if(relay_url)
{
// TODO: remove bus, use direct calls instead
if(relay_url === "fetch")
{
this.network_adapter = new FetchNetworkAdapter(this.bus);
}
else if(relay_url.startsWith("wisp://") || relay_url.startsWith("wisps://"))
{
this.network_adapter = new WispNetworkAdapter(relay_url, this.bus, options);
}
else
{
this.network_adapter = new NetworkAdapter(relay_url, this.bus);
}
}
// Enable unconditionally, so that state images don't miss hardware
// TODO: Should be properly fixed in restore_state
settings.net_device = options.net_device || { type: "ne2k" };
const screen_options = options.screen || {};
if(options.screen_container)
{
screen_options.container = options.screen_container;
}
if(!options.disable_keyboard)
{
this.keyboard_adapter = new KeyboardAdapter(this.bus);
}
if(!options.disable_mouse)
{
this.mouse_adapter = new MouseAdapter(this.bus, screen_options.container);
}
if(screen_options.container)
{
this.screen_adapter = new ScreenAdapter(screen_options, () => this.v86.cpu.devices.vga && this.v86.cpu.devices.vga.screen_fill_buffer());
}
else
{
this.screen_adapter = new DummyScreenAdapter();
}
settings.screen = this.screen_adapter;
settings.screen_options = screen_options;
if(options.serial_container)
{
this.serial_adapter = new SerialAdapter(options.serial_container, this.bus);
//this.recording_adapter = new SerialRecordingAdapter(this.bus);
}
if(options.serial_container_xtermjs)
{
this.serial_adapter = new SerialAdapterXtermJS(options.serial_container_xtermjs, this.bus);
}
if(!options.disable_speaker)
{
this.speaker_adapter = new SpeakerAdapter(this.bus);
}
// ugly, but required for closure compiler compilation
function put_on_settings(name, buffer)
{
switch(name)
{
case "hda":
settings.hda = this.disk_images.hda = buffer;
break;
case "hdb":
settings.hdb = this.disk_images.hdb = buffer;
break;
case "cdrom":
settings.cdrom = this.disk_images.cdrom = buffer;
break;
case "fda":
settings.fda = this.disk_images.fda = buffer;
break;
case "fdb":
settings.fdb = this.disk_images.fdb = buffer;
break;
case "multiboot":
settings.multiboot = this.disk_images.multiboot = buffer.buffer;
break;
case "bzimage":
settings.bzimage = this.disk_images.bzimage = buffer.buffer;
break;
case "initrd":
settings.initrd = this.disk_images.initrd = buffer.buffer;
break;
case "bios":
settings.bios = buffer.buffer;
break;
case "vga_bios":
settings.vga_bios = buffer.buffer;
break;
case "initial_state":
settings.initial_state = buffer.buffer;
break;
case "fs9p_json":
settings.fs9p_json = buffer;
break;
default:
dbg_assert(false, name);
}
}
var files_to_load = [];
const add_file = (name, file) =>
{
if(!file)
{
return;
}
if(file.get && file.set && file.load)
{
files_to_load.push({
name: name,
loadable: file,
});
return;
}
if(name === "bios" || name === "vga_bios" ||
name === "initial_state" || name === "multiboot" ||
name === "bzimage" || name === "initrd")
{
// Ignore async for these because they must be available before boot.
// This should make result.buffer available after the object is loaded
file.async = false;
}
if(name === "fda" || name === "fdb")
{
// small, doesn't make sense loading asynchronously
file.async = false;
}
if(file.url && !file.async)
{
files_to_load.push({
name: name,
url: file.url,
size: file.size,
});
}
else
{
files_to_load.push({
name,
loadable: v86util.buffer_from_object(file, this.zstd_decompress_worker.bind(this)),
});
}
};
if(options.state)
{
console.warn("Warning: Unknown option 'state'. Did you mean 'initial_state'?");
}
add_file("bios", options.bios);
add_file("vga_bios", options.vga_bios);
add_file("cdrom", options.cdrom);
add_file("hda", options.hda);
add_file("hdb", options.hdb);
add_file("fda", options.fda);
add_file("fdb", options.fdb);
add_file("initial_state", options.initial_state);
add_file("multiboot", options.multiboot);
add_file("bzimage", options.bzimage);
add_file("initrd", options.initrd);
if(options.filesystem)
{
var fs_url = options.filesystem.basefs;
var base_url = options.filesystem.baseurl;
let file_storage = new MemoryFileStorage();
if(base_url)
{
file_storage = new ServerFileStorageWrapper(file_storage, base_url);
}
settings.fs9p = this.fs9p = new FS(file_storage);
if(fs_url)
{
dbg_assert(base_url, "Filesystem: baseurl must be specified");
var size;
if(typeof fs_url === "object")
{
size = fs_url.size;
fs_url = fs_url.url;
}
dbg_assert(typeof fs_url === "string");
files_to_load.push({
name: "fs9p_json",
url: fs_url,
size: size,
as_json: true,
});
}
}
var starter = this;
var total = files_to_load.length;
var cont = function(index)
{
if(index === total)
{
setTimeout(done.bind(this), 0);
return;
}
var f = files_to_load[index];
if(f.loadable)
{
f.loadable.onload = function(e)
{
put_on_settings.call(this, f.name, f.loadable);
cont(index + 1);
}.bind(this);
f.loadable.load();
}
else
{
v86util.load_file(f.url, {
done: function(result)
{
if(f.url.endsWith(".zst") && f.name !== "initial_state")
{
dbg_assert(f.size, "A size must be provided for compressed images");
result = this.zstd_decompress(f.size, new Uint8Array(result));
}
put_on_settings.call(this, f.name, f.as_json ? result : new v86util.SyncBuffer(result));
cont(index + 1);
}.bind(this),
progress: function progress(e)
{
if(e.target.status === 200)
{
starter.emulator_bus.send("download-progress", {
file_index: index,
file_count: total,
file_name: f.url,
lengthComputable: e.lengthComputable,
total: e.total || f.size,
loaded: e.loaded,
});
}
else
{
starter.emulator_bus.send("download-error", {
file_index: index,
file_count: total,
file_name: f.url,
request: e.target,
});
}
},
as_json: f.as_json,
});
}
}.bind(this);
cont(0);
async function done()
{
//if(settings.initial_state)
//{
// // avoid large allocation now, memory will be restored later anyway
// settings.memory_size = 0;
//}
if(settings.fs9p && settings.fs9p_json)
{
if(!settings.initial_state)
{
settings.fs9p.load_from_json(settings.fs9p_json);
if(options.bzimage_initrd_from_filesystem)
{
const { bzimage_path, initrd_path } = this.get_bzimage_initrd_from_filesystem(settings.fs9p);
dbg_log("Found bzimage: " + bzimage_path + " and initrd: " + initrd_path);
const [initrd, bzimage] = await Promise.all([
settings.fs9p.read_file(initrd_path),
settings.fs9p.read_file(bzimage_path),
]);
put_on_settings.call(this, "initrd", new v86util.SyncBuffer(initrd.buffer));
put_on_settings.call(this, "bzimage", new v86util.SyncBuffer(bzimage.buffer));
}
}
else
{
dbg_log("Filesystem basefs ignored: Overridden by state image");
}
}
else
{
dbg_assert(
!options.bzimage_initrd_from_filesystem || settings.initial_state,
"bzimage_initrd_from_filesystem: Requires a filesystem");
}
this.serial_adapter && this.serial_adapter.show && this.serial_adapter.show();
this.v86.init(settings);
if(settings.initial_state)
{
emulator.restore_state(settings.initial_state);
// The GC can't free settings, since it is referenced from
// several closures. This isn't needed anymore, so we delete it
// here
settings.initial_state = undefined;
}
if(options.autostart)
{
this.v86.run();
}
this.emulator_bus.send("emulator-loaded");
}
};
/**
* @param {number} decompressed_size
* @param {Uint8Array} src
* @return {ArrayBuffer}
*/
V86.prototype.zstd_decompress = function(decompressed_size, src)
{
const cpu = this.v86.cpu;
dbg_assert(!this.zstd_context);
this.zstd_context = cpu.zstd_create_ctx(src.length);
new Uint8Array(cpu.wasm_memory.buffer).set(src, cpu.zstd_get_src_ptr(this.zstd_context));
const ptr = cpu.zstd_read(this.zstd_context, decompressed_size);
const result = cpu.wasm_memory.buffer.slice(ptr, ptr + decompressed_size);
cpu.zstd_read_free(ptr, decompressed_size);
cpu.zstd_free_ctx(this.zstd_context);
this.zstd_context = null;
return result;
};
/**
* @param {number} decompressed_size
* @param {Uint8Array} src
* @return {Promise<ArrayBuffer>}
*/
V86.prototype.zstd_decompress_worker = async function(decompressed_size, src)
{
if(!this.zstd_worker)
{
function the_worker()
{
let wasm;
globalThis.onmessage = function(e)
{
if(!wasm)
{
const env = 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",
].map(f => [f, () => console.error("zstd worker unexpectedly called " + f)]));
env["__indirect_function_table"] = new WebAssembly.Table({ element: "anyfunc", initial: 1024 });
env["abort"] = () => { throw new Error("zstd worker aborted"); };
env["log_from_wasm"] = env["console_log_from_wasm"] = (off, len) => {
console.log(String.fromCharCode(...new Uint8Array(wasm.exports.memory.buffer, off, len)));
};
env["dbg_trace_from_wasm"] = () => console.trace();
wasm = new WebAssembly.Instance(new WebAssembly.Module(e.data), { "env": env });
return;
}
const { src, decompressed_size, id } = e.data;
const exports = wasm.exports;
const zstd_context = exports["zstd_create_ctx"](src.length);
new Uint8Array(exports.memory.buffer).set(src, exports["zstd_get_src_ptr"](zstd_context));
const ptr = exports["zstd_read"](zstd_context, decompressed_size);
const result = exports.memory.buffer.slice(ptr, ptr + decompressed_size);
exports["zstd_read_free"](ptr, decompressed_size);
exports["zstd_free_ctx"](zstd_context);
postMessage({ result, id }, [result]);
};
}
const url = URL.createObjectURL(new Blob(["(" + the_worker.toString() + ")()"], { type: "text/javascript" }));
this.zstd_worker = new Worker(url);
URL.revokeObjectURL(url);
this.zstd_worker.postMessage(this.wasm_source, [this.wasm_source]);
}
return new Promise(resolve => {
const id = this.zstd_worker_request_id++;
const done = async e =>
{
if(e.data.id === id)
{
this.zstd_worker.removeEventListener("message", done);
dbg_assert(decompressed_size === e.data.result.byteLength);
resolve(e.data.result);
}
};
this.zstd_worker.addEventListener("message", done);
this.zstd_worker.postMessage({ src, decompressed_size, id }, [src.buffer]);
});
};
V86.prototype.get_bzimage_initrd_from_filesystem = function(filesystem)
{
const root = (filesystem.read_dir("/") || []).map(x => "/" + x);
const boot = (filesystem.read_dir("/boot/") || []).map(x => "/boot/" + x);
let initrd_path;
let bzimage_path;
for(const f of [].concat(root, boot))
{
const old = /old/i.test(f) || /fallback/i.test(f);
const is_bzimage = /vmlinuz/i.test(f) || /bzimage/i.test(f);
const is_initrd = /initrd/i.test(f) || /initramfs/i.test(f);
if(is_bzimage && (!bzimage_path || !old))
{
bzimage_path = f;
}
if(is_initrd && (!initrd_path || !old))
{
initrd_path = f;
}
}
if(!initrd_path || !bzimage_path)
{
console.log("Failed to find bzimage or initrd in filesystem. Files:");
console.log(root.join(" "));
console.log(boot.join(" "));
}
return { initrd_path, bzimage_path };
};
/**
* Start emulation. Do nothing if emulator is running already. Can be
* asynchronous.
* @export
*/
V86.prototype.run = async function()
{
this.v86.run();
};
/**
* Stop emulation. Do nothing if emulator is not running. Can be asynchronous.
* @export
*/
V86.prototype.stop = async function()
{
if(!this.cpu_is_running)
{
return;
}
await new Promise(resolve => {
const listener = () => {
this.remove_listener("emulator-stopped", listener);
resolve();
};
this.add_listener("emulator-stopped", listener);
this.v86.stop();
});
};
/**
* @ignore
* @export
*/
V86.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();
};
/**
* Restart (force a reboot).
* @export
*/
V86.prototype.restart = function()
{
this.v86.restart();
};
/**
* Add an event listener (the emulator is an event emitter). A list of events
* can be found at [events.md](events.md).
*
* The callback function gets a single argument which depends on the event.
*
* @param {string} event Name of the event.
* @param {function(?)} listener The callback function.
* @export
*/
V86.prototype.add_listener = function(event, listener)
{
this.bus.register(event, listener, this);
};
/**
* Remove an event listener.
*
* @param {string} event
* @param {function(*)} listener
* @export
*/
V86.prototype.remove_listener = function(event, listener)
{
this.bus.unregister(event, listener);
};
/**
* Restore the emulator state from the given state, which must be an
* ArrayBuffer returned by
* [`save_state`](#save_statefunctionobject-arraybuffer-callback).
*
* Note that the state can only be restored correctly if this constructor has
* been created with the same options as the original instance (e.g., same disk
* images, memory size, etc.).
*
* Different versions of the emulator might use a different format for the
* state buffer.
*
* @param {ArrayBuffer} state
* @export
*/
V86.prototype.restore_state = async function(state)
{
dbg_assert(arguments.length === 1);
this.v86.restore_state(state);
};
/**
* Asynchronously save the current state of the emulator.
*
* @return {Promise<ArrayBuffer>}
* @export
*/
V86.prototype.save_state = async function()
{
dbg_assert(arguments.length === 0);
return this.v86.save_state();
};
/**
* @return {number}
* @ignore
* @export
*/
V86.prototype.get_instruction_counter = function()
{
if(this.v86)
{
return this.v86.cpu.instruction_counter[0] >>> 0;
}
else
{
// TODO: Should be handled using events
return 0;
}
};
/**
* @return {boolean}
* @export
*/
V86.prototype.is_running = function()
{
return this.cpu_is_running;
};
/**
* Set the image inserted in the floppy drive. Can be changed at runtime, as
* when physically changing the floppy disk.
* @export
*/
V86.prototype.set_fda = async function(file)
{
if(file.url && !file.async)
{
v86util.load_file(file.url, {
done: result =>
{
this.v86.cpu.devices.fdc.set_fda(new v86util.SyncBuffer(result));
},
});
}
else
{
const image = v86util.buffer_from_object(file, this.zstd_decompress_worker.bind(this));
image.onload = () =>
{
this.v86.cpu.devices.fdc.set_fda(image);
};
await image.load();
}
};
/**
* Eject the floppy drive.
* @export
*/
V86.prototype.eject_fda = function()
{
this.v86.cpu.devices.fdc.eject_fda();
};
/**
* Send a sequence of scan codes to the emulated PS2 controller. A list of
* codes can be found at http://stanislavs.org/helppc/make_codes.html.
* Do nothing if there is no keyboard controller.
*
* @param {Array.<number>} codes
* @export
*/
V86.prototype.keyboard_send_scancodes = function(codes)
{
for(var i = 0; i < codes.length; i++)
{
this.bus.send("keyboard-code", codes[i]);
}
};
/**
* Send translated keys
* @ignore
* @export
*/
V86.prototype.keyboard_send_keys = function(codes)
{
for(var i = 0; i < codes.length; i++)
{
this.keyboard_adapter.simulate_press(codes[i]);
}
};
/**
* Send text