cpu.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  1. "use strict";
  2. // Resources:
  3. // https://pdos.csail.mit.edu/6.828/2006/readings/i386/toc.htm
  4. // https://www-ssl.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html
  5. // http://ref.x86asm.net/geek32.html
  6. /** @constructor */
  7. function CPU(bus, wm, next_tick_immediately)
  8. {
  9. this.next_tick_immediately = next_tick_immediately;
  10. this.wm = wm;
  11. this.wasm_patch();
  12. this.create_jit_imports();
  13. const memory = this.wm.exports.memory;
  14. this.wasm_memory = memory;
  15. this.memory_size = v86util.view(Uint32Array, memory, 812, 1);
  16. this.mem8 = new Uint8Array(0);
  17. this.mem32s = new Int32Array(this.mem8.buffer);
  18. this.segment_is_null = v86util.view(Uint8Array, memory, 724, 8);
  19. this.segment_offsets = v86util.view(Int32Array, memory, 736, 8);
  20. this.segment_limits = v86util.view(Uint32Array, memory, 768, 8);
  21. this.segment_access_bytes = v86util.view(Uint8Array, memory, 512, 8);
  22. /**
  23. * Wheter or not in protected mode
  24. */
  25. this.protected_mode = v86util.view(Int32Array, memory, 800, 1);
  26. this.idtr_size = v86util.view(Int32Array, memory, 564, 1);
  27. this.idtr_offset = v86util.view(Int32Array, memory, 568, 1);
  28. /**
  29. * global descriptor table register
  30. */
  31. this.gdtr_size = v86util.view(Int32Array, memory, 572, 1);
  32. this.gdtr_offset = v86util.view(Int32Array, memory, 576, 1);
  33. this.tss_size_32 = v86util.view(Int32Array, memory, 1128, 1);
  34. /*
  35. * whether or not a page fault occured
  36. */
  37. this.page_fault = v86util.view(Uint32Array, memory, 540, 8);
  38. this.cr = v86util.view(Int32Array, memory, 580, 8);
  39. // current privilege level
  40. this.cpl = v86util.view(Uint8Array, memory, 612, 1);
  41. // current operand/address size
  42. this.is_32 = v86util.view(Int32Array, memory, 804, 1);
  43. this.stack_size_32 = v86util.view(Int32Array, memory, 808, 1);
  44. /**
  45. * Was the last instruction a hlt?
  46. */
  47. this.in_hlt = v86util.view(Uint8Array, memory, 616, 1);
  48. this.last_virt_eip = v86util.view(Int32Array, memory, 620, 1);
  49. this.eip_phys = v86util.view(Int32Array, memory, 624, 1);
  50. this.sysenter_cs = v86util.view(Int32Array, memory, 636, 1);
  51. this.sysenter_esp = v86util.view(Int32Array, memory, 640, 1);
  52. this.sysenter_eip = v86util.view(Int32Array, memory, 644, 1);
  53. this.prefixes = v86util.view(Int32Array, memory, 648, 1);
  54. this.flags = v86util.view(Int32Array, memory, 120, 1);
  55. /**
  56. * bitmap of flags which are not updated in the flags variable
  57. * changed by arithmetic instructions, so only relevant to arithmetic flags
  58. */
  59. this.flags_changed = v86util.view(Int32Array, memory, 100, 1);
  60. /**
  61. * enough infos about the last arithmetic operation to compute eflags
  62. */
  63. this.last_op_size = v86util.view(Int32Array, memory, 96, 1);
  64. this.last_op1 = v86util.view(Int32Array, memory, 104, 1);
  65. this.last_result = v86util.view(Int32Array, memory, 112, 1);
  66. this.current_tsc = v86util.view(Uint32Array, memory, 960, 2); // 64 bit
  67. /** @type {!Object} */
  68. this.devices = {};
  69. this.instruction_pointer = v86util.view(Int32Array, memory, 556, 1);
  70. this.previous_ip = v86util.view(Int32Array, memory, 560, 1);
  71. // configured by guest
  72. this.apic_enabled = v86util.view(Uint8Array, memory, 548, 1);
  73. // configured when the emulator starts (changes bios initialisation)
  74. this.acpi_enabled = v86util.view(Uint8Array, memory, 552, 1);
  75. // managed in io.js
  76. /** @const */ this.memory_map_read8 = [];
  77. /** @const */ this.memory_map_write8 = [];
  78. /** @const */ this.memory_map_read32 = [];
  79. /** @const */ this.memory_map_write32 = [];
  80. /**
  81. * @const
  82. * @type {{main: ArrayBuffer, vga: ArrayBuffer}}
  83. */
  84. this.bios = {
  85. main: null,
  86. vga: null,
  87. };
  88. this.instruction_counter = v86util.view(Uint32Array, memory, 664, 1);
  89. // registers
  90. this.reg32 = v86util.view(Int32Array, memory, 64, 8);
  91. this.fpu_st = v86util.view(Int32Array, memory, 1152, 4 * 8);
  92. this.fpu_stack_empty = v86util.view(Uint8Array, memory, 816, 1);
  93. this.fpu_stack_empty[0] = 0xFF;
  94. this.fpu_stack_ptr = v86util.view(Uint8Array, memory, 1032, 1);
  95. this.fpu_stack_ptr[0] = 0;
  96. this.fpu_control_word = v86util.view(Uint16Array, memory, 1036, 1);
  97. this.fpu_control_word[0] = 0x37F;
  98. this.fpu_status_word = v86util.view(Uint16Array, memory, 1040, 1);
  99. this.fpu_status_word[0] = 0;
  100. this.fpu_ip = v86util.view(Int32Array, memory, 1048, 1);
  101. this.fpu_ip[0] = 0;
  102. this.fpu_ip_selector = v86util.view(Int32Array, memory, 1052, 1);
  103. this.fpu_ip_selector[0] = 0;
  104. this.fpu_opcode = v86util.view(Int32Array, memory, 1044, 1);
  105. this.fpu_opcode[0] = 0;
  106. this.fpu_dp = v86util.view(Int32Array, memory, 1056, 1);
  107. this.fpu_dp[0] = 0;
  108. this.fpu_dp_selector = v86util.view(Int32Array, memory, 1060, 1);
  109. this.fpu_dp_selector[0] = 0;
  110. this.reg_xmm32s = v86util.view(Int32Array, memory, 832, 8 * 4);
  111. this.mxcsr = v86util.view(Int32Array, memory, 824, 1);
  112. // segment registers, tr and ldtr
  113. this.sreg = v86util.view(Uint16Array, memory, 668, 8);
  114. // debug registers
  115. this.dreg = v86util.view(Int32Array, memory, 684, 8);
  116. this.reg_pdpte = v86util.view(Int32Array, memory, 968, 8);
  117. this.svga_dirty_bitmap_min_offset = v86util.view(Uint32Array, memory, 716, 1);
  118. this.svga_dirty_bitmap_max_offset = v86util.view(Uint32Array, memory, 720, 1);
  119. this.fw_value = [];
  120. this.fw_pointer = 0;
  121. this.option_roms = [];
  122. this.io = undefined;
  123. this.bus = bus;
  124. this.set_tsc(0, 0);
  125. this.debug_init();
  126. if(DEBUG)
  127. {
  128. this.seen_code = {};
  129. this.seen_code_uncompiled = {};
  130. }
  131. //Object.seal(this);
  132. }
  133. CPU.prototype.clear_opstats = function()
  134. {
  135. new Uint8Array(this.wasm_memory.buffer, 0x8000, 0x20000).fill(0);
  136. this.wm.exports["profiler_init"]();
  137. };
  138. CPU.prototype.create_jit_imports = function()
  139. {
  140. // Set this.jit_imports as generated WASM modules will expect
  141. const jit_imports = Object.create(null);
  142. jit_imports["m"] = this.wm.exports["memory"];
  143. for(let name of Object.keys(this.wm.exports))
  144. {
  145. if(name.startsWith("_") || name.startsWith("zstd") || name.endsWith("_js"))
  146. {
  147. continue;
  148. }
  149. jit_imports[name] = this.wm.exports[name];
  150. }
  151. this.jit_imports = jit_imports;
  152. };
  153. CPU.prototype.wasm_patch = function()
  154. {
  155. const get_optional_import = name => this.wm.exports[name];
  156. const get_import = name =>
  157. {
  158. const f = get_optional_import(name);
  159. console.assert(f, "Missing import: " + name);
  160. return f;
  161. };
  162. this.reset_cpu = get_import("reset_cpu");
  163. this.getiopl = get_import("getiopl");
  164. this.get_eflags = get_import("get_eflags");
  165. this.handle_irqs = get_import("handle_irqs");
  166. this.main_loop = get_import("main_loop");
  167. this.set_jit_config = get_import("set_jit_config");
  168. this.read8 = get_import("read8");
  169. this.read16 = get_import("read16");
  170. this.read32s = get_import("read32s");
  171. this.write8 = get_import("write8");
  172. this.write16 = get_import("write16");
  173. this.write32 = get_import("write32");
  174. this.in_mapped_range = get_import("in_mapped_range");
  175. // used by nasmtests
  176. this.fpu_load_tag_word = get_import("fpu_load_tag_word");
  177. this.fpu_load_status_word = get_import("fpu_load_status_word");
  178. this.fpu_get_sti_f64 = get_import("fpu_get_sti_f64");
  179. this.translate_address_system_read = get_import("translate_address_system_read_js");
  180. this.get_seg_cs = get_import("get_seg_cs");
  181. this.get_real_eip = get_import("get_real_eip");
  182. this.clear_tlb = get_import("clear_tlb");
  183. this.full_clear_tlb = get_import("full_clear_tlb");
  184. this.update_state_flags = get_import("update_state_flags");
  185. this.set_tsc = get_import("set_tsc");
  186. this.store_current_tsc = get_import("store_current_tsc");
  187. this.set_cpuid_level = get_import("set_cpuid_level");
  188. this.pic_set_irq = get_import("pic_set_irq");
  189. this.pic_clear_irq = get_import("pic_clear_irq");
  190. if(DEBUG)
  191. {
  192. this.jit_force_generate_unsafe = get_optional_import("jit_force_generate_unsafe");
  193. }
  194. this.jit_clear_cache = get_import("jit_clear_cache_js");
  195. this.jit_dirty_cache = get_import("jit_dirty_cache");
  196. this.codegen_finalize_finished = get_import("codegen_finalize_finished");
  197. this.allocate_memory = get_import("allocate_memory");
  198. this.zero_memory = get_import("zero_memory");
  199. this.svga_allocate_memory = get_import("svga_allocate_memory");
  200. this.svga_allocate_dest_buffer = get_import("svga_allocate_dest_buffer");
  201. this.svga_fill_pixel_buffer = get_import("svga_fill_pixel_buffer");
  202. this.svga_mark_dirty = get_import("svga_mark_dirty");
  203. this.get_pic_addr_master = get_import("get_pic_addr_master");
  204. this.get_pic_addr_slave = get_import("get_pic_addr_slave");
  205. this.zstd_create_ctx = get_import("zstd_create_ctx");
  206. this.zstd_get_src_ptr = get_import("zstd_get_src_ptr");
  207. this.zstd_free_ctx = get_import("zstd_free_ctx");
  208. this.zstd_read = get_import("zstd_read");
  209. this.zstd_read_free = get_import("zstd_read_free");
  210. this.port20_read = get_import("port20_read");
  211. this.port21_read = get_import("port21_read");
  212. this.portA0_read = get_import("portA0_read");
  213. this.portA1_read = get_import("portA1_read");
  214. this.port20_write = get_import("port20_write");
  215. this.port21_write = get_import("port21_write");
  216. this.portA0_write = get_import("portA0_write");
  217. this.portA1_write = get_import("portA1_write");
  218. this.port4D0_read = get_import("port4D0_read");
  219. this.port4D1_read = get_import("port4D1_read");
  220. this.port4D0_write = get_import("port4D0_write");
  221. this.port4D1_write = get_import("port4D1_write");
  222. };
  223. CPU.prototype.jit_force_generate = function(addr)
  224. {
  225. if(!this.jit_force_generate_unsafe)
  226. {
  227. dbg_assert(false, "Not supported in this wasm build: jit_force_generate_unsafe");
  228. return;
  229. }
  230. this.jit_force_generate_unsafe(addr);
  231. };
  232. CPU.prototype.jit_clear_func = function(index)
  233. {
  234. dbg_assert(index >= 0 && index < WASM_TABLE_SIZE);
  235. this.wm.wasm_table.set(index + WASM_TABLE_OFFSET, null);
  236. };
  237. CPU.prototype.jit_clear_all_funcs = function()
  238. {
  239. const table = this.wm.wasm_table;
  240. for(let i = 0; i < WASM_TABLE_SIZE; i++)
  241. {
  242. table.set(WASM_TABLE_OFFSET + i, null);
  243. }
  244. };
  245. CPU.prototype.get_state = function()
  246. {
  247. var state = [];
  248. state[0] = this.memory_size[0];
  249. state[1] = new Uint8Array([...this.segment_is_null, ...this.segment_access_bytes]);
  250. state[2] = this.segment_offsets;
  251. state[3] = this.segment_limits;
  252. state[4] = this.protected_mode[0];
  253. state[5] = this.idtr_offset[0];
  254. state[6] = this.idtr_size[0];
  255. state[7] = this.gdtr_offset[0];
  256. state[8] = this.gdtr_size[0];
  257. state[9] = this.page_fault[0];
  258. state[10] = this.cr;
  259. state[11] = this.cpl[0];
  260. state[13] = this.is_32[0];
  261. state[16] = this.stack_size_32[0];
  262. state[17] = this.in_hlt[0];
  263. state[18] = this.last_virt_eip[0];
  264. state[19] = this.eip_phys[0];
  265. state[22] = this.sysenter_cs[0];
  266. state[23] = this.sysenter_eip[0];
  267. state[24] = this.sysenter_esp[0];
  268. state[25] = this.prefixes[0];
  269. state[26] = this.flags[0];
  270. state[27] = this.flags_changed[0];
  271. state[28] = this.last_op1[0];
  272. state[30] = this.last_op_size[0];
  273. state[37] = this.instruction_pointer[0];
  274. state[38] = this.previous_ip[0];
  275. state[39] = this.reg32;
  276. state[40] = this.sreg;
  277. state[41] = this.dreg;
  278. state[42] = this.reg_pdpte;
  279. this.store_current_tsc();
  280. state[43] = this.current_tsc;
  281. state[45] = this.devices.virtio_9p;
  282. state[46] = this.devices.apic;
  283. state[47] = this.devices.rtc;
  284. state[48] = this.devices.pci;
  285. state[49] = this.devices.dma;
  286. state[50] = this.devices.acpi;
  287. // 51 (formerly hpet)
  288. state[52] = this.devices.vga;
  289. state[53] = this.devices.ps2;
  290. state[54] = this.devices.uart0;
  291. state[55] = this.devices.fdc;
  292. state[56] = this.devices.cdrom;
  293. state[57] = this.devices.hda;
  294. state[58] = this.devices.pit;
  295. state[59] = this.devices.net;
  296. state[60] = this.get_state_pic();
  297. state[61] = this.devices.sb16;
  298. state[62] = this.fw_value;
  299. state[63] = this.devices.ioapic;
  300. state[64] = this.tss_size_32[0];
  301. state[66] = this.reg_xmm32s;
  302. state[67] = this.fpu_st;
  303. state[68] = this.fpu_stack_empty[0];
  304. state[69] = this.fpu_stack_ptr[0];
  305. state[70] = this.fpu_control_word[0];
  306. state[71] = this.fpu_ip[0];
  307. state[72] = this.fpu_ip_selector[0];
  308. state[73] = this.fpu_dp[0];
  309. state[74] = this.fpu_dp_selector[0];
  310. state[75] = this.fpu_opcode[0];
  311. const { packed_memory, bitmap } = this.pack_memory();
  312. state[77] = packed_memory;
  313. state[78] = new Uint8Array(bitmap.get_buffer());
  314. state[79] = this.devices.uart1;
  315. state[80] = this.devices.uart2;
  316. state[81] = this.devices.uart3;
  317. state[82] = this.devices.virtio_console;
  318. return state;
  319. };
  320. CPU.prototype.get_state_pic = function()
  321. {
  322. const pic_size = 13;
  323. const pic = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_master(), pic_size);
  324. const pic_slave = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_slave(), pic_size);
  325. const state = [];
  326. const state_slave = [];
  327. state[0] = pic[0]; // irq_mask
  328. state[1] = pic[1]; // irq_map
  329. state[2] = pic[2]; // isr
  330. state[3] = pic[3]; // irr
  331. state[4] = pic[4]; // is_master
  332. state[5] = state_slave;
  333. state[6] = pic[6]; // expect_icw4
  334. state[7] = pic[7]; // state
  335. state[8] = pic[8]; // read_isr
  336. state[9] = pic[9]; // auto_eoi
  337. state[10] = pic[10]; // elcr
  338. state[11] = pic[11]; // irq_value
  339. state[12] = pic[12]; // special_mask_mode
  340. state_slave[0] = pic_slave[0]; // irq_mask
  341. state_slave[1] = pic_slave[1]; // irq_map
  342. state_slave[2] = pic_slave[2]; // isr
  343. state_slave[3] = pic_slave[3]; // irr
  344. state_slave[4] = pic_slave[4]; // is_master
  345. state_slave[5] = null;
  346. state_slave[6] = pic_slave[6]; // expect_icw4
  347. state_slave[7] = pic_slave[7]; // state
  348. state_slave[8] = pic_slave[8]; // read_isr
  349. state_slave[9] = pic_slave[9]; // auto_eoi
  350. state_slave[10] = pic_slave[10]; // elcr
  351. state_slave[11] = pic_slave[11]; // irq_value
  352. state_slave[12] = pic_slave[12]; // special_mask_mode
  353. return state;
  354. };
  355. CPU.prototype.set_state = function(state)
  356. {
  357. this.memory_size[0] = state[0];
  358. if(this.mem8.length !== this.memory_size[0])
  359. {
  360. console.warn("Note: Memory size mismatch. we=" + this.mem8.length + " state=" + this.memory_size[0]);
  361. }
  362. if(state[1].length === 8)
  363. {
  364. // NOTE: support for old state images; delete this when bumping STATE_VERSION
  365. this.segment_is_null.set(state[1]);
  366. this.segment_access_bytes.fill(0x80 | (3 << 5) | 0x10 | 0x02);
  367. this.segment_access_bytes[REG_CS] = 0x80 | (3 << 5) | 0x10 | 0x08 | 0x02;
  368. }
  369. else if(state[1].length === 16)
  370. {
  371. this.segment_is_null.set(state[1].subarray(0, 8));
  372. this.segment_access_bytes.set(state[1].subarray(8, 16));
  373. }
  374. else
  375. {
  376. dbg_assert("Unexpected cpu segment state length:" + state[1].length);
  377. }
  378. this.segment_offsets.set(state[2]);
  379. this.segment_limits.set(state[3]);
  380. this.protected_mode[0] = state[4];
  381. this.idtr_offset[0] = state[5];
  382. this.idtr_size[0] = state[6];
  383. this.gdtr_offset[0] = state[7];
  384. this.gdtr_size[0] = state[8];
  385. this.page_fault[0] = state[9];
  386. this.cr.set(state[10]);
  387. this.cpl[0] = state[11];
  388. this.is_32[0] = state[13];
  389. this.stack_size_32[0] = state[16];
  390. this.in_hlt[0] = state[17];
  391. this.last_virt_eip[0] = state[18];
  392. this.eip_phys[0] = state[19];
  393. this.sysenter_cs[0] = state[22];
  394. this.sysenter_eip[0] = state[23];
  395. this.sysenter_esp[0] = state[24];
  396. this.prefixes[0] = state[25];
  397. this.flags[0] = state[26];
  398. this.flags_changed[0] = state[27];
  399. this.last_op1[0] = state[28];
  400. this.last_op_size[0] = state[30];
  401. this.instruction_pointer[0] = state[37];
  402. this.previous_ip[0] = state[38];
  403. this.reg32.set(state[39]);
  404. this.sreg.set(state[40]);
  405. this.dreg.set(state[41]);
  406. state[42] && this.reg_pdpte.set(state[42]);
  407. this.set_tsc(state[43][0], state[43][1]);
  408. this.devices.virtio_9p && this.devices.virtio_9p.set_state(state[45]);
  409. this.devices.apic && this.devices.apic.set_state(state[46]);
  410. this.devices.rtc && this.devices.rtc.set_state(state[47]);
  411. this.devices.pci && this.devices.pci.set_state(state[48]);
  412. this.devices.dma && this.devices.dma.set_state(state[49]);
  413. this.devices.acpi && this.devices.acpi.set_state(state[50]);
  414. // 51 (formerly hpet)
  415. this.devices.vga && this.devices.vga.set_state(state[52]);
  416. this.devices.ps2 && this.devices.ps2.set_state(state[53]);
  417. this.devices.uart0 && this.devices.uart0.set_state(state[54]);
  418. this.devices.fdc && this.devices.fdc.set_state(state[55]);
  419. this.devices.cdrom && this.devices.cdrom.set_state(state[56]);
  420. this.devices.hda && this.devices.hda.set_state(state[57]);
  421. this.devices.pit && this.devices.pit.set_state(state[58]);
  422. this.devices.net && this.devices.net.set_state(state[59]);
  423. this.set_state_pic(state[60]);
  424. this.devices.sb16 && this.devices.sb16.set_state(state[61]);
  425. this.devices.uart1 && this.devices.uart1.set_state(state[79]);
  426. this.devices.uart2 && this.devices.uart2.set_state(state[80]);
  427. this.devices.uart3 && this.devices.uart3.set_state(state[81]);
  428. this.devices.virtio_console && this.devices.virtio_console.set_state(state[82]);
  429. this.fw_value = state[62];
  430. this.devices.ioapic && this.devices.ioapic.set_state(state[63]);
  431. this.tss_size_32[0] = state[64];
  432. this.reg_xmm32s.set(state[66]);
  433. this.fpu_st.set(state[67]);
  434. this.fpu_stack_empty[0] = state[68];
  435. this.fpu_stack_ptr[0] = state[69];
  436. this.fpu_control_word[0] = state[70];
  437. this.fpu_ip[0] = state[71];
  438. this.fpu_ip_selector[0] = state[72];
  439. this.fpu_dp[0] = state[73];
  440. this.fpu_dp_selector[0] = state[74];
  441. this.fpu_opcode[0] = state[75];
  442. const bitmap = new v86util.Bitmap(state[78].buffer);
  443. const packed_memory = state[77];
  444. this.unpack_memory(bitmap, packed_memory);
  445. this.update_state_flags();
  446. this.full_clear_tlb();
  447. this.jit_clear_cache();
  448. };
  449. CPU.prototype.set_state_pic = function(state)
  450. {
  451. // Note: This could exists for compatibility with old state images
  452. // It should be deleted when the state version changes
  453. const pic_size = 13;
  454. const pic = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_master(), pic_size);
  455. const pic_slave = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_slave(), pic_size);
  456. pic[0] = state[0]; // irq_mask
  457. pic[1] = state[1]; // irq_map
  458. pic[2] = state[2]; // isr
  459. pic[3] = state[3]; // irr
  460. pic[4] = state[4]; // is_master
  461. const state_slave = state[5];
  462. pic[6] = state[6]; // expect_icw4
  463. pic[7] = state[7]; // state
  464. pic[8] = state[8]; // read_isr
  465. pic[9] = state[9]; // auto_eoi
  466. pic[10] = state[10]; // elcr
  467. pic[11] = state[11]; // irq_value (undefined in old state images)
  468. pic[12] = state[12]; // special_mask_mode (undefined in old state images)
  469. pic_slave[0] = state_slave[0]; // irq_mask
  470. pic_slave[1] = state_slave[1]; // irq_map
  471. pic_slave[2] = state_slave[2]; // isr
  472. pic_slave[3] = state_slave[3]; // irr
  473. pic_slave[4] = state_slave[4]; // is_master
  474. // dummy
  475. pic_slave[6] = state_slave[6]; // expect_icw4
  476. pic_slave[7] = state_slave[7]; // state
  477. pic_slave[8] = state_slave[8]; // read_isr
  478. pic_slave[9] = state_slave[9]; // auto_eoi
  479. pic_slave[10] = state_slave[10]; // elcr
  480. pic_slave[11] = state_slave[11]; // irq_value (undefined in old state images)
  481. pic_slave[12] = state_slave[12]; // special_mask_mode (undefined in old state images)
  482. };
  483. CPU.prototype.pack_memory = function()
  484. {
  485. dbg_assert((this.mem8.length & 0xFFF) === 0);
  486. const page_count = this.mem8.length >> 12;
  487. const nonzero_pages = [];
  488. for(let page = 0; page < page_count; page++)
  489. {
  490. const offset = page << 12;
  491. const view = this.mem32s.subarray(offset >> 2, offset + 0x1000 >> 2);
  492. let is_zero = true;
  493. for(let i = 0; i < view.length; i++)
  494. {
  495. if(view[i] !== 0)
  496. {
  497. is_zero = false;
  498. break;
  499. }
  500. }
  501. if(!is_zero)
  502. {
  503. nonzero_pages.push(page);
  504. }
  505. }
  506. const bitmap = new v86util.Bitmap(page_count);
  507. const packed_memory = new Uint8Array(nonzero_pages.length << 12);
  508. for(let [i, page] of nonzero_pages.entries())
  509. {
  510. bitmap.set(page, 1);
  511. const offset = page << 12;
  512. const page_contents = this.mem8.subarray(offset, offset + 0x1000);
  513. packed_memory.set(page_contents, i << 12);
  514. }
  515. return { bitmap, packed_memory };
  516. };
  517. CPU.prototype.unpack_memory = function(bitmap, packed_memory)
  518. {
  519. this.zero_memory(this.memory_size[0]);
  520. const page_count = this.memory_size[0] >> 12;
  521. let packed_page = 0;
  522. for(let page = 0; page < page_count; page++)
  523. {
  524. if(bitmap.get(page))
  525. {
  526. let offset = packed_page << 12;
  527. let view = packed_memory.subarray(offset, offset + 0x1000);
  528. this.mem8.set(view, page << 12);
  529. packed_page++;
  530. }
  531. }
  532. };
  533. CPU.prototype.reboot_internal = function()
  534. {
  535. this.reset_cpu();
  536. this.fw_value = [];
  537. if(this.devices.virtio_9p)
  538. {
  539. this.devices.virtio_9p.reset();
  540. }
  541. if(this.devices.virtio_console)
  542. {
  543. this.devices.virtio_console.reset();
  544. }
  545. this.load_bios();
  546. };
  547. CPU.prototype.reset_memory = function()
  548. {
  549. this.mem8.fill(0);
  550. };
  551. /** @export */
  552. CPU.prototype.create_memory = function(size)
  553. {
  554. if(size < 1024 * 1024)
  555. {
  556. size = 1024 * 1024;
  557. }
  558. else if((size | 0) < 0)
  559. {
  560. size = Math.pow(2, 31) - MMAP_BLOCK_SIZE;
  561. }
  562. size = ((size - 1) | (MMAP_BLOCK_SIZE - 1)) + 1 | 0;
  563. dbg_assert((size | 0) > 0);
  564. dbg_assert((size & MMAP_BLOCK_SIZE - 1) === 0);
  565. console.assert(this.memory_size[0] === 0, "Expected uninitialised memory");
  566. this.memory_size[0] = size;
  567. const memory_offset = this.allocate_memory(size);
  568. this.mem8 = v86util.view(Uint8Array, this.wasm_memory, memory_offset, size);
  569. this.mem32s = v86util.view(Uint32Array, this.wasm_memory, memory_offset, size >> 2);
  570. };
  571. CPU.prototype.init = function(settings, device_bus)
  572. {
  573. if(typeof settings.log_level === "number")
  574. {
  575. // XXX: Shared between all emulator instances
  576. LOG_LEVEL = settings.log_level;
  577. }
  578. this.create_memory(typeof settings.memory_size === "number" ?
  579. settings.memory_size : 1024 * 1024 * 64);
  580. if(settings.disable_jit)
  581. {
  582. this.set_jit_config(0, 1);
  583. }
  584. settings.cpuid_level && this.set_cpuid_level(settings.cpuid_level);
  585. this.acpi_enabled[0] = +settings.acpi;
  586. this.reset_cpu();
  587. var io = new IO(this);
  588. this.io = io;
  589. this.bios.main = settings.bios;
  590. this.bios.vga = settings.vga_bios;
  591. this.load_bios();
  592. if(settings.bzimage)
  593. {
  594. const option_rom = load_kernel(this.mem8, settings.bzimage, settings.initrd, settings.cmdline || "");
  595. if(option_rom)
  596. {
  597. this.option_roms.push(option_rom);
  598. }
  599. }
  600. io.register_read(0xB3, this, function()
  601. {
  602. // seabios smm_relocate_and_restore
  603. dbg_log("port 0xB3 read");
  604. return 0;
  605. });
  606. var a20_byte = 0;
  607. io.register_read(0x92, this, function()
  608. {
  609. return a20_byte;
  610. });
  611. io.register_write(0x92, this, function(out_byte)
  612. {
  613. a20_byte = out_byte;
  614. });
  615. io.register_read(0x511, this, function()
  616. {
  617. // bios config port (used by seabios and kvm-unit-test)
  618. if(this.fw_pointer < this.fw_value.length)
  619. {
  620. return this.fw_value[this.fw_pointer++];
  621. }
  622. else
  623. {
  624. dbg_assert(false, "config port: Read past value");
  625. return 0;
  626. }
  627. });
  628. io.register_write(0x510, this, undefined, function(value)
  629. {
  630. // https://wiki.osdev.org/QEMU_fw_cfg
  631. // https://github.com/qemu/qemu/blob/master/docs/specs/fw_cfg.txt
  632. dbg_log("bios config port, index=" + h(value));
  633. function i32(x)
  634. {
  635. return new Uint8Array(Int32Array.of(x).buffer);
  636. }
  637. function to_be16(x)
  638. {
  639. return x >> 8 | x << 8 & 0xFF00;
  640. }
  641. function to_be32(x)
  642. {
  643. return x << 24 | x << 8 & 0xFF0000 | x >> 8 & 0xFF00 | x >>> 24;
  644. }
  645. this.fw_pointer = 0;
  646. if(value === FW_CFG_SIGNATURE)
  647. {
  648. // Pretend to be qemu (for seabios)
  649. this.fw_value = i32(FW_CFG_SIGNATURE_QEMU);
  650. }
  651. else if(value === FW_CFG_ID)
  652. {
  653. this.fw_value = i32(0);
  654. }
  655. else if(value === FW_CFG_RAM_SIZE)
  656. {
  657. this.fw_value = i32(this.memory_size[0]);
  658. }
  659. else if(value === FW_CFG_NB_CPUS)
  660. {
  661. this.fw_value = i32(1);
  662. }
  663. else if(value === FW_CFG_MAX_CPUS)
  664. {
  665. this.fw_value = i32(1);
  666. }
  667. else if(value === FW_CFG_NUMA)
  668. {
  669. this.fw_value = new Uint8Array(16);
  670. }
  671. else if(value === FW_CFG_FILE_DIR)
  672. {
  673. const buffer_size = 4 + 64 * this.option_roms.length;
  674. const buffer32 = new Int32Array(buffer_size);
  675. const buffer8 = new Uint8Array(buffer32.buffer);
  676. buffer32[0] = to_be32(this.option_roms.length);
  677. for(let i = 0; i < this.option_roms.length; i++)
  678. {
  679. const { name, data } = this.option_roms[i];
  680. const file_struct_ptr = 4 + 64 * i;
  681. dbg_assert(FW_CFG_FILE_START + i < 0x10000);
  682. buffer32[file_struct_ptr + 0 >> 2] = to_be32(data.length);
  683. buffer32[file_struct_ptr + 4 >> 2] = to_be16(FW_CFG_FILE_START + i);
  684. dbg_assert(name.length < 64 - 8);
  685. for(let j = 0; j < name.length; j++)
  686. {
  687. buffer8[file_struct_ptr + 8 + j] = name.charCodeAt(j);
  688. }
  689. }
  690. this.fw_value = buffer8;
  691. }
  692. else if(value >= FW_CFG_CUSTOM_START && value < FW_CFG_FILE_START)
  693. {
  694. this.fw_value = i32(0);
  695. }
  696. else if(value >= FW_CFG_FILE_START && value - FW_CFG_FILE_START < this.option_roms.length)
  697. {
  698. const i = value - FW_CFG_FILE_START;
  699. this.fw_value = this.option_roms[i].data;
  700. }
  701. else
  702. {
  703. dbg_log("Warning: Unimplemented fw index: " + h(value));
  704. this.fw_value = i32(0);
  705. }
  706. });
  707. if(DEBUG)
  708. {
  709. // Avoid logging noisey ports
  710. io.register_write(0x80, this, function(out_byte) {});
  711. io.register_read(0x80, this, function() { return 0xFF; });
  712. io.register_write(0xE9, this, function(out_byte) {});
  713. }
  714. io.register_read(0x20, this, this.port20_read);
  715. io.register_read(0x21, this, this.port21_read);
  716. io.register_read(0xA0, this, this.portA0_read);
  717. io.register_read(0xA1, this, this.portA1_read);
  718. io.register_write(0x20, this, this.port20_write);
  719. io.register_write(0x21, this, this.port21_write);
  720. io.register_write(0xA0, this, this.portA0_write);
  721. io.register_write(0xA1, this, this.portA1_write);
  722. io.register_read(0x4D0, this, this.port4D0_read);
  723. io.register_read(0x4D1, this, this.port4D1_read);
  724. io.register_write(0x4D0, this, this.port4D0_write);
  725. io.register_write(0x4D1, this, this.port4D1_write);
  726. this.devices = {};
  727. // TODO: Make this more configurable
  728. if(settings.load_devices)
  729. {
  730. this.devices.pci = new PCI(this);
  731. if(this.acpi_enabled[0])
  732. {
  733. this.devices.ioapic = new IOAPIC(this);
  734. this.devices.apic = new APIC(this);
  735. this.devices.acpi = new ACPI(this);
  736. }
  737. this.devices.rtc = new RTC(this);
  738. this.fill_cmos(this.devices.rtc, settings);
  739. this.devices.dma = new DMA(this);
  740. this.devices.vga = new VGAScreen(this, device_bus,
  741. settings.vga_memory_size || 8 * 1024 * 1024);
  742. this.devices.ps2 = new PS2(this, device_bus);
  743. this.devices.uart0 = new UART(this, 0x3F8, device_bus);
  744. if(settings.uart1)
  745. {
  746. this.devices.uart1 = new UART(this, 0x2F8, device_bus);
  747. }
  748. if(settings.uart2)
  749. {
  750. this.devices.uart2 = new UART(this, 0x3E8, device_bus);
  751. }
  752. if(settings.uart3)
  753. {
  754. this.devices.uart3 = new UART(this, 0x2E8, device_bus);
  755. }
  756. this.devices.fdc = new FloppyController(this, settings.fda, settings.fdb);
  757. var ide_device_count = 0;
  758. if(settings.hda)
  759. {
  760. this.devices.hda = new IDEDevice(this, settings.hda, settings.hdb, false, ide_device_count++, device_bus);
  761. }
  762. if(settings.cdrom)
  763. {
  764. this.devices.cdrom = new IDEDevice(this, settings.cdrom, undefined, true, ide_device_count++, device_bus);
  765. }
  766. this.devices.pit = new PIT(this, device_bus);
  767. if(settings.enable_ne2k)
  768. {
  769. this.devices.net = new Ne2k(this, device_bus, settings.preserve_mac_from_state_image, settings.mac_address_translation);
  770. }
  771. if(settings.fs9p)
  772. {
  773. this.devices.virtio_9p = new Virtio9p(settings.fs9p, this, device_bus);
  774. }
  775. if(settings.virtio_console)
  776. {
  777. this.devices.virtio_console = new VirtioConsole(this, device_bus);
  778. }
  779. if(true)
  780. {
  781. this.devices.sb16 = new SB16(this, device_bus);
  782. }
  783. }
  784. if(settings.multiboot)
  785. {
  786. dbg_log("loading multiboot", LOG_CPU);
  787. const option_rom = this.load_multiboot_option_rom(settings.multiboot, settings.initrd, settings.cmdline);
  788. if(option_rom)
  789. {
  790. if(this.bios.main)
  791. {
  792. dbg_log("adding option rom for multiboot", LOG_CPU);
  793. this.option_roms.push(option_rom);
  794. }
  795. else
  796. {
  797. dbg_log("loaded multiboot without bios", LOG_CPU);
  798. this.reg32[REG_EAX] = this.io.port_read32(0xF4);
  799. }
  800. }
  801. }
  802. if(DEBUG)
  803. {
  804. this.debug.init();
  805. }
  806. };
  807. CPU.prototype.load_multiboot = function (buffer)
  808. {
  809. if(this.bios.main)
  810. {
  811. dbg_assert(false, "load_multiboot not supported with BIOS");
  812. }
  813. const option_rom = this.load_multiboot_option_rom(buffer, undefined, "");
  814. if(option_rom)
  815. {
  816. dbg_log("loaded multiboot", LOG_CPU);
  817. this.reg32[REG_EAX] = this.io.port_read32(0xF4);
  818. }
  819. };
  820. CPU.prototype.load_multiboot_option_rom = function(buffer, initrd, cmdline)
  821. {
  822. // https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
  823. dbg_log("Trying multiboot from buffer of size " + buffer.byteLength, LOG_CPU);
  824. const ELF_MAGIC = 0x464C457F;
  825. const MULTIBOOT_HEADER_MAGIC = 0x1BADB002;
  826. const MULTIBOOT_HEADER_MEMORY_INFO = 0x2;
  827. const MULTIBOOT_HEADER_ADDRESS = 0x10000;
  828. const MULTIBOOT_BOOTLOADER_MAGIC = 0x2BADB002;
  829. const MULTIBOOT_SEARCH_BYTES = 8192;
  830. const MULTIBOOT_INFO_STRUCT_LEN = 116;
  831. const MULTIBOOT_INFO_CMDLINE = 0x4;
  832. const MULTIBOOT_INFO_MEM_MAP = 0x40;
  833. if(buffer.byteLength < MULTIBOOT_SEARCH_BYTES)
  834. {
  835. var buf32 = new Int32Array(MULTIBOOT_SEARCH_BYTES / 4);
  836. new Uint8Array(buf32.buffer).set(new Uint8Array(buffer));
  837. }
  838. else
  839. {
  840. var buf32 = new Int32Array(buffer, 0, MULTIBOOT_SEARCH_BYTES / 4);
  841. }
  842. for(var offset = 0; offset < MULTIBOOT_SEARCH_BYTES; offset += 4)
  843. {
  844. if(buf32[offset >> 2] === MULTIBOOT_HEADER_MAGIC)
  845. {
  846. var flags = buf32[offset + 4 >> 2];
  847. var checksum = buf32[offset + 8 >> 2];
  848. var total = MULTIBOOT_HEADER_MAGIC + flags + checksum | 0;
  849. if(total)
  850. {
  851. dbg_log("Multiboot checksum check failed", LOG_CPU);
  852. continue;
  853. }
  854. }
  855. else
  856. {
  857. continue;
  858. }
  859. dbg_log("Multiboot magic found, flags: " + h(flags >>> 0, 8), LOG_CPU);
  860. // bit 0 : load modules on page boundaries (may as well, if we load modules)
  861. // bit 1 : provide a memory map (which we always will)
  862. dbg_assert((flags & ~MULTIBOOT_HEADER_ADDRESS & ~3) === 0, "TODO");
  863. // do this in a io register hook, so it can happen after BIOS does its work
  864. var cpu = this;
  865. this.io.register_read(0xF4, this, function () {return 0;} , function () { return 0;}, function () {
  866. // actually do the load and return the multiboot magic
  867. let multiboot_info_addr = 0x7C00;
  868. let multiboot_data = multiboot_info_addr + MULTIBOOT_INFO_STRUCT_LEN;
  869. let info = 0;
  870. // command line
  871. if(cmdline)
  872. {
  873. info |= MULTIBOOT_INFO_CMDLINE;
  874. cpu.write32(multiboot_info_addr + 16, multiboot_data);
  875. cmdline += "\x00";
  876. const encoder = new TextEncoder();
  877. const cmdline_utf8 = encoder.encode(cmdline);
  878. cpu.write_blob(cmdline_utf8, multiboot_data);
  879. multiboot_data += cmdline_utf8.length;
  880. }
  881. // memory map
  882. if(flags & MULTIBOOT_HEADER_MEMORY_INFO)
  883. {
  884. info |= MULTIBOOT_INFO_MEM_MAP;
  885. let multiboot_mmap_count = 0;
  886. cpu.write32(multiboot_info_addr + 44, 0);
  887. cpu.write32(multiboot_info_addr + 48, multiboot_data);
  888. // Create a memory map for the multiboot kernel
  889. // does not exclude traditional bios exclusions
  890. let start = 0;
  891. let was_memory = false;
  892. for(let addr = 0; addr < MMAP_MAX; addr += MMAP_BLOCK_SIZE)
  893. {
  894. if(was_memory && cpu.memory_map_read8[addr >>> MMAP_BLOCK_BITS] !== undefined)
  895. {
  896. cpu.write32(multiboot_data, 20); // size
  897. cpu.write32(multiboot_data + 4, start); //addr (64-bit)
  898. cpu.write32(multiboot_data + 8, 0);
  899. cpu.write32(multiboot_data + 12, addr - start); // len (64-bit)
  900. cpu.write32(multiboot_data + 16, 0);
  901. cpu.write32(multiboot_data + 20, 1); // type (MULTIBOOT_MEMORY_AVAILABLE)
  902. multiboot_data += 24;
  903. multiboot_mmap_count += 24;
  904. was_memory = false;
  905. }
  906. else if(!was_memory && cpu.memory_map_read8[addr >>> MMAP_BLOCK_BITS] === undefined)
  907. {
  908. start = addr;
  909. was_memory = true;
  910. }
  911. }
  912. dbg_assert (!was_memory, "top of 4GB shouldn't have memory");
  913. cpu.write32(multiboot_info_addr + 44, multiboot_mmap_count);
  914. }
  915. cpu.write32(multiboot_info_addr, info);
  916. let entrypoint = 0;
  917. let top_of_load = 0;
  918. if(flags & MULTIBOOT_HEADER_ADDRESS)
  919. {
  920. dbg_log("Multiboot specifies its own address table", LOG_CPU);
  921. var header_addr = buf32[offset + 12 >> 2];
  922. var load_addr = buf32[offset + 16 >> 2];
  923. var load_end_addr = buf32[offset + 20 >> 2];
  924. var bss_end_addr = buf32[offset + 24 >> 2];
  925. var entry_addr = buf32[offset + 28 >> 2];
  926. dbg_log("header=" + h(header_addr, 8) +
  927. " load=" + h(load_addr, 8) +
  928. " load_end=" + h(load_end_addr, 8) +
  929. " bss_end=" + h(bss_end_addr, 8) +
  930. " entry=" + h(entry_addr, 8));
  931. dbg_assert(load_addr <= header_addr);
  932. var file_start = offset - (header_addr - load_addr);
  933. if(load_end_addr === 0)
  934. {
  935. var length = undefined;
  936. }
  937. else
  938. {
  939. dbg_assert(load_end_addr >= load_addr);
  940. var length = load_end_addr - load_addr;
  941. }
  942. let blob = new Uint8Array(buffer, file_start, length);
  943. cpu.write_blob(blob, load_addr);
  944. entrypoint = entry_addr | 0;
  945. top_of_load = Math.max(load_end_addr, bss_end_addr);
  946. }
  947. else if(buf32[0] === ELF_MAGIC)
  948. {
  949. dbg_log("Multiboot image is in elf format", LOG_CPU);
  950. let elf = read_elf(buffer);
  951. entrypoint = elf.header.entry;
  952. for(let program of elf.program_headers)
  953. {
  954. if(program.type === 0)
  955. {
  956. // null
  957. }
  958. else if(program.type === 1)
  959. {
  960. // load
  961. dbg_assert(program.filesz <= program.memsz);
  962. if(program.paddr + program.memsz < cpu.memory_size[0])
  963. {
  964. if(program.filesz) // offset might be outside of buffer if filesz is 0
  965. {
  966. let blob = new Uint8Array(buffer, program.offset, program.filesz);
  967. cpu.write_blob(blob, program.paddr);
  968. }
  969. top_of_load = Math.max(top_of_load, program.paddr + program.memsz);
  970. dbg_log("prg load " + program.paddr + " to " + (program.paddr + program.memsz), LOG_CPU);
  971. // Since multiboot specifies that paging is disabled, we load to the physical address;
  972. // but the entry point is specified in virtual addresses so adjust the entrypoint if needed
  973. if(entrypoint === elf.header.entry && program.vaddr <= entrypoint && (program.vaddr + program.memsz) > entrypoint)
  974. {
  975. entrypoint = (entrypoint - program.vaddr) + program.paddr;
  976. }
  977. }
  978. else
  979. {
  980. dbg_log("Warning: Skipped loading section, paddr=" + h(program.paddr) + " memsz=" + program.memsz, LOG_CPU);
  981. }
  982. }
  983. else if(
  984. program.type === 2 || // dynamic
  985. program.type === 3 || // interp
  986. program.type === 4 || // note
  987. program.type === 6 || // phdr
  988. program.type === 7 || // tls
  989. program.type === 0x6474e550 || // gnu_eh_frame
  990. program.type === 0x6474e551 || // gnu_stack
  991. program.type === 0x6474e552 || // gnu_relro
  992. program.type === 0x6474e553) // gnu_property
  993. {
  994. dbg_log("skip load type " + program.type + " " + program.paddr + " to " + (program.paddr + program.memsz), LOG_CPU);
  995. // ignore for now
  996. }
  997. else
  998. {
  999. dbg_assert(false, "unimplemented elf section type: " + h(program.type));
  1000. }
  1001. }
  1002. }
  1003. else
  1004. {
  1005. dbg_assert(false, "Not a bootable multiboot format");
  1006. }
  1007. if(initrd)
  1008. {
  1009. cpu.write32(multiboot_info_addr + 20, 1); // mods_count
  1010. cpu.write32(multiboot_info_addr + 24, multiboot_data); // mods_addr;
  1011. var ramdisk_address = top_of_load;
  1012. if((ramdisk_address & 4095) !== 0)
  1013. {
  1014. ramdisk_address = (ramdisk_address & ~4095) + 4096;
  1015. }
  1016. dbg_log("ramdisk address " + ramdisk_address);
  1017. var ramdisk_top = ramdisk_address + initrd.byteLength;
  1018. cpu.write32(multiboot_data, ramdisk_address); // mod_start
  1019. cpu.write32(multiboot_data + 4, ramdisk_top); // mod_end
  1020. cpu.write32(multiboot_data + 8, 0); // string
  1021. cpu.write32(multiboot_data + 12, 0); // reserved
  1022. multiboot_data += 16;
  1023. dbg_assert(ramdisk_top < cpu.memory_size[0]);
  1024. cpu.write_blob(new Uint8Array(initrd), ramdisk_address);
  1025. }
  1026. // set state for multiboot
  1027. cpu.reg32[REG_EBX] = multiboot_info_addr;
  1028. cpu.cr[0] = 1;
  1029. cpu.protected_mode[0] = +true;
  1030. cpu.flags[0] = FLAGS_DEFAULT;
  1031. cpu.is_32[0] = +true;
  1032. cpu.stack_size_32[0] = +true;
  1033. for(var i = 0; i < 6; i++)
  1034. {
  1035. cpu.segment_is_null[i] = 0;
  1036. cpu.segment_offsets[i] = 0;
  1037. cpu.segment_limits[i] = 0xFFFFFFFF;
  1038. // cpu.segment_access_bytes[i]
  1039. // Value doesn't matter, OS isn't allowed to reload without setting
  1040. // up a proper GDT
  1041. cpu.sreg[i] = 0xB002;
  1042. }
  1043. cpu.instruction_pointer[0] = cpu.get_seg_cs() + entrypoint | 0;
  1044. cpu.update_state_flags();
  1045. dbg_log("Starting multiboot kernel at:", LOG_CPU);
  1046. cpu.debug.dump_state();
  1047. cpu.debug.dump_regs();
  1048. return MULTIBOOT_BOOTLOADER_MAGIC;
  1049. });
  1050. // only for kvm-unit-test
  1051. this.io.register_write_consecutive(0xF4, this,
  1052. function(value)
  1053. {
  1054. console.log("Test exited with code " + h(value, 2));
  1055. throw "HALT";
  1056. },
  1057. function() {},
  1058. function() {},
  1059. function() {});
  1060. // only for kvm-unit-test
  1061. for(let i = 0; i <= 0xF; i++)
  1062. {
  1063. function handle_write(value)
  1064. {
  1065. dbg_log("kvm-unit-test: Set irq " + h(i) + " to " + h(value, 2));
  1066. if(value)
  1067. {
  1068. this.device_raise_irq(i);
  1069. }
  1070. else
  1071. {
  1072. this.device_lower_irq(i);
  1073. }
  1074. }
  1075. this.io.register_write(0x2000 + i, this, handle_write, handle_write, handle_write);
  1076. }
  1077. // This rom will be executed by seabios after its initialisation
  1078. // It sets up the multiboot environment.
  1079. const SIZE = 0x200;
  1080. const data8 = new Uint8Array(SIZE);
  1081. const data16 = new Uint16Array(data8.buffer);
  1082. data16[0] = 0xAA55;
  1083. data8[2] = SIZE / 0x200;
  1084. let i = 3;
  1085. // trigger load
  1086. data8[i++] = 0x66; // in 0xF4
  1087. data8[i++] = 0xE5;
  1088. data8[i++] = 0xF4;
  1089. dbg_assert(i < SIZE);
  1090. const checksum_index = i;
  1091. data8[checksum_index] = 0;
  1092. let rom_checksum = 0;
  1093. for(let i = 0; i < data8.length; i++)
  1094. {
  1095. rom_checksum += data8[i];
  1096. }
  1097. data8[checksum_index] = -rom_checksum;
  1098. return {
  1099. name: "genroms/multiboot.bin",
  1100. data: data8
  1101. };
  1102. }
  1103. dbg_log("Multiboot header not found", LOG_CPU);
  1104. };
  1105. CPU.prototype.fill_cmos = function(rtc, settings)
  1106. {
  1107. var boot_order = settings.boot_order || BOOT_ORDER_CD_FIRST;
  1108. // Used by seabios to determine the boot order
  1109. // Nibble
  1110. // 1: FloppyPrio
  1111. // 2: HDPrio
  1112. // 3: CDPrio
  1113. // 4: BEVPrio
  1114. // bootflag 1, high nibble, lowest priority
  1115. // Low nibble: Disable floppy signature check (1)
  1116. rtc.cmos_write(CMOS_BIOS_BOOTFLAG1 , 1 | boot_order >> 4 & 0xF0);
  1117. // bootflag 2, both nibbles, high and middle priority
  1118. rtc.cmos_write(CMOS_BIOS_BOOTFLAG2, boot_order & 0xFF);
  1119. // 640k or less if less memory is used
  1120. rtc.cmos_write(CMOS_MEM_BASE_LOW, 640 & 0xFF);
  1121. rtc.cmos_write(CMOS_MEM_BASE_HIGH, 640 >> 8);
  1122. var memory_above_1m = 0; // in k
  1123. if(this.memory_size[0] >= 1024 * 1024)
  1124. {
  1125. memory_above_1m = (this.memory_size[0] - 1024 * 1024) >> 10;
  1126. memory_above_1m = Math.min(memory_above_1m, 0xFFFF);
  1127. }
  1128. rtc.cmos_write(CMOS_MEM_OLD_EXT_LOW, memory_above_1m & 0xFF);
  1129. rtc.cmos_write(CMOS_MEM_OLD_EXT_HIGH, memory_above_1m >> 8 & 0xFF);
  1130. rtc.cmos_write(CMOS_MEM_EXTMEM_LOW, memory_above_1m & 0xFF);
  1131. rtc.cmos_write(CMOS_MEM_EXTMEM_HIGH, memory_above_1m >> 8 & 0xFF);
  1132. var memory_above_16m = 0; // in 64k blocks
  1133. if(this.memory_size[0] >= 16 * 1024 * 1024)
  1134. {
  1135. memory_above_16m = (this.memory_size[0] - 16 * 1024 * 1024) >> 16;
  1136. memory_above_16m = Math.min(memory_above_16m, 0xFFFF);
  1137. }
  1138. rtc.cmos_write(CMOS_MEM_EXTMEM2_LOW, memory_above_16m & 0xFF);
  1139. rtc.cmos_write(CMOS_MEM_EXTMEM2_HIGH, memory_above_16m >> 8 & 0xFF);
  1140. // memory above 4G (not supported by this emulator)
  1141. rtc.cmos_write(CMOS_MEM_HIGHMEM_LOW, 0);
  1142. rtc.cmos_write(CMOS_MEM_HIGHMEM_MID, 0);
  1143. rtc.cmos_write(CMOS_MEM_HIGHMEM_HIGH, 0);
  1144. rtc.cmos_write(CMOS_EQUIPMENT_INFO, 0x2F);
  1145. rtc.cmos_write(CMOS_BIOS_SMP_COUNT, 0);
  1146. // Used by bochs BIOS to skip the boot menu delay.
  1147. if (settings.fastboot) rtc.cmos_write(0x3f, 0x01);
  1148. };
  1149. CPU.prototype.load_bios = function()
  1150. {
  1151. var bios = this.bios.main;
  1152. var vga_bios = this.bios.vga;
  1153. if(!bios)
  1154. {
  1155. dbg_log("Warning: No BIOS");
  1156. return;
  1157. }
  1158. // load bios
  1159. var data = new Uint8Array(bios),
  1160. start = 0x100000 - bios.byteLength;
  1161. this.write_blob(data, start);
  1162. if(vga_bios)
  1163. {
  1164. // load vga bios
  1165. var vga_bios8 = new Uint8Array(vga_bios);
  1166. // older versions of seabios
  1167. this.write_blob(vga_bios8, 0xC0000);
  1168. // newer versions of seabios (needs to match pci rom address, see vga.js)
  1169. this.io.mmap_register(0xFEB00000, 0x100000,
  1170. function(addr)
  1171. {
  1172. addr = (addr - 0xFEB00000) | 0;
  1173. if(addr < vga_bios8.length)
  1174. {
  1175. return vga_bios8[addr];
  1176. }
  1177. else
  1178. {
  1179. return 0;
  1180. }
  1181. },
  1182. function(addr, value)
  1183. {
  1184. dbg_assert(false, "Unexpected write to VGA rom");
  1185. });
  1186. }
  1187. else
  1188. {
  1189. dbg_log("Warning: No VGA BIOS");
  1190. }
  1191. // seabios expects the bios to be mapped to 0xFFF00000 also
  1192. this.io.mmap_register(0xFFF00000, 0x100000,
  1193. function(addr)
  1194. {
  1195. addr &= 0xFFFFF;
  1196. return this.mem8[addr];
  1197. }.bind(this),
  1198. function(addr, value)
  1199. {
  1200. addr &= 0xFFFFF;
  1201. this.mem8[addr] = value;
  1202. }.bind(this));
  1203. };
  1204. CPU.prototype.codegen_finalize = function(wasm_table_index, start, state_flags, ptr, len)
  1205. {
  1206. ptr >>>= 0;
  1207. len >>>= 0;
  1208. dbg_assert(wasm_table_index >= 0 && wasm_table_index < WASM_TABLE_SIZE);
  1209. const code = new Uint8Array(this.wasm_memory.buffer, ptr, len);
  1210. if(DEBUG)
  1211. {
  1212. if(DUMP_GENERATED_WASM && !this.seen_code[start])
  1213. {
  1214. this.debug.dump_wasm(code);
  1215. const DUMP_ASSEMBLY = false;
  1216. if(DUMP_ASSEMBLY)
  1217. {
  1218. let end = 0;
  1219. if((start ^ end) & ~0xFFF)
  1220. {
  1221. dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0));
  1222. end = (start | 0xFFF) + 1; // until the end of the page
  1223. }
  1224. dbg_assert(end >= start);
  1225. const buffer = new Uint8Array(end - start);
  1226. for(let i = start; i < end; i++)
  1227. {
  1228. buffer[i - start] = this.read8(i);
  1229. }
  1230. this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start);
  1231. }
  1232. }
  1233. this.seen_code[start] = (this.seen_code[start] || 0) + 1;
  1234. if(this.test_hook_did_generate_wasm)
  1235. {
  1236. this.test_hook_did_generate_wasm(code);
  1237. }
  1238. }
  1239. const SYNC_COMPILATION = false;
  1240. if(SYNC_COMPILATION)
  1241. {
  1242. const module = new WebAssembly.Module(code);
  1243. const result = new WebAssembly.Instance(module, { "e": this.jit_imports });
  1244. const f = result.exports["f"];
  1245. this.wm.wasm_table.set(wasm_table_index + WASM_TABLE_OFFSET, f);
  1246. this.codegen_finalize_finished(wasm_table_index, start, state_flags);
  1247. if(this.test_hook_did_finalize_wasm)
  1248. {
  1249. this.test_hook_did_finalize_wasm(code);
  1250. }
  1251. return;
  1252. }
  1253. const result = WebAssembly.instantiate(code, { "e": this.jit_imports }).then(result => {
  1254. const f = result.instance.exports["f"];
  1255. this.wm.wasm_table.set(wasm_table_index + WASM_TABLE_OFFSET, f);
  1256. this.codegen_finalize_finished(wasm_table_index, start, state_flags);
  1257. if(this.test_hook_did_finalize_wasm)
  1258. {
  1259. this.test_hook_did_finalize_wasm(code);
  1260. }
  1261. });
  1262. if(DEBUG)
  1263. {
  1264. result.catch(e => {
  1265. console.log(e);
  1266. debugger;
  1267. throw e;
  1268. });
  1269. }
  1270. };
  1271. CPU.prototype.log_uncompiled_code = function(start, end)
  1272. {
  1273. if(!DEBUG || !DUMP_UNCOMPILED_ASSEMBLY)
  1274. {
  1275. return;
  1276. }
  1277. if((this.seen_code_uncompiled[start] || 0) < 100)
  1278. {
  1279. this.seen_code_uncompiled[start] = (this.seen_code_uncompiled[start] || 0) + 1;
  1280. end += 8; // final jump is not included
  1281. if((start ^ end) & ~0xFFF)
  1282. {
  1283. dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0));
  1284. end = (start | 0xFFF) + 1; // until the end of the page
  1285. }
  1286. if(end < start) end = start;
  1287. dbg_assert(end >= start);
  1288. const buffer = new Uint8Array(end - start);
  1289. for(let i = start; i < end; i++)
  1290. {
  1291. buffer[i - start] = this.read8(i);
  1292. }
  1293. dbg_log("Uncompiled code:");
  1294. this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start);
  1295. }
  1296. };
  1297. CPU.prototype.dump_function_code = function(block_ptr, count)
  1298. {
  1299. if(!DEBUG || !DUMP_GENERATED_WASM)
  1300. {
  1301. return;
  1302. }
  1303. const SIZEOF_BASIC_BLOCK_IN_DWORDS = 7;
  1304. const mem32 = new Int32Array(this.wasm_memory.buffer);
  1305. dbg_assert((block_ptr & 3) === 0);
  1306. const is_32 = this.is_32[0];
  1307. for(let i = 0; i < count; i++)
  1308. {
  1309. const struct_start = (block_ptr >> 2) + i * SIZEOF_BASIC_BLOCK_IN_DWORDS;
  1310. const start = mem32[struct_start + 0];
  1311. const end = mem32[struct_start + 1];
  1312. const is_entry_block = mem32[struct_start + 6] & 0xFF00;
  1313. const buffer = new Uint8Array(end - start);
  1314. for(let i = start; i < end; i++)
  1315. {
  1316. buffer[i - start] = this.read8(this.translate_address_system_read(i));
  1317. }
  1318. dbg_log("---" + (is_entry_block ? " entry" : ""));
  1319. this.debug.dump_code(is_32 ? 1 : 0, buffer, start);
  1320. }
  1321. };
  1322. CPU.prototype.run_hardware_timers = function(acpi_enabled, now)
  1323. {
  1324. const pit_time = this.devices.pit.timer(now, false);
  1325. const rtc_time = this.devices.rtc.timer(now, false);
  1326. let acpi_time = 100;
  1327. let apic_time = 100;
  1328. if(acpi_enabled)
  1329. {
  1330. acpi_time = this.devices.acpi.timer(now);
  1331. apic_time = this.devices.apic.timer(now);
  1332. }
  1333. return Math.min(pit_time, rtc_time, acpi_time, apic_time);
  1334. };
  1335. CPU.prototype.device_raise_irq = function(i)
  1336. {
  1337. dbg_assert(arguments.length === 1);
  1338. this.pic_set_irq(i);
  1339. if(this.devices.ioapic)
  1340. {
  1341. this.devices.ioapic.set_irq(i);
  1342. }
  1343. };
  1344. CPU.prototype.device_lower_irq = function(i)
  1345. {
  1346. this.pic_clear_irq(i);
  1347. if(this.devices.ioapic)
  1348. {
  1349. this.devices.ioapic.clear_irq(i);
  1350. }
  1351. };
  1352. // Closure Compiler's way of exporting
  1353. if(typeof window !== "undefined")
  1354. {
  1355. window["CPU"] = CPU;
  1356. }
  1357. else if(typeof module !== "undefined" && typeof module.exports !== "undefined")
  1358. {
  1359. module.exports["CPU"] = CPU;
  1360. }
  1361. else if(typeof importScripts === "function")
  1362. {
  1363. self["CPU"] = CPU;
  1364. }