cpu.js 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143
  1. "use strict";
  2. /** @const */
  3. var CPU_LOG_VERBOSE = false;
  4. // Resources:
  5. // https://pdos.csail.mit.edu/6.828/2006/readings/i386/toc.htm
  6. // https://www-ssl.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html
  7. // http://ref.x86asm.net/geek32.html
  8. /** @constructor */
  9. function CPU(bus, wm, v86oxide)
  10. {
  11. this.wm = wm;
  12. this.v86oxide = v86oxide;
  13. this.wasm_patch(wm);
  14. this.create_jit_imports();
  15. const memory = v86oxide.instance.exports.memory;
  16. this.wasm_memory = memory;
  17. this.memory_size = v86util.view(Uint32Array, memory, 812, 1);
  18. // Note: Currently unused (degrades performance and not required by any OS
  19. // that we support)
  20. this.a20_enabled = v86util.view(Int32Array, memory, 552, 1);
  21. this.a20_enabled[0] = +true;
  22. this.mem8 = new Uint8Array(0);
  23. this.mem16 = new Uint16Array(this.mem8.buffer);
  24. this.mem32s = new Int32Array(this.mem8.buffer);
  25. this.segment_is_null = v86util.view(Uint8Array, memory, 724, 8);
  26. this.segment_offsets = v86util.view(Int32Array, memory, 736, 8);
  27. this.segment_limits = v86util.view(Uint32Array, memory, 768, 8);
  28. /**
  29. * Wheter or not in protected mode
  30. */
  31. this.protected_mode = v86util.view(Int32Array, memory, 800, 1);
  32. this.idtr_size = v86util.view(Int32Array, memory, 564, 1);
  33. this.idtr_offset = v86util.view(Int32Array, memory, 568, 1);
  34. /**
  35. * global descriptor table register
  36. */
  37. this.gdtr_size = v86util.view(Int32Array, memory, 572, 1);
  38. this.gdtr_offset = v86util.view(Int32Array, memory, 576, 1);
  39. this.tss_size_32 = v86util.view(Int32Array, memory, 1128, 1);
  40. /*
  41. * whether or not a page fault occured
  42. */
  43. this.page_fault = v86util.view(Uint32Array, memory, 540, 8);
  44. this.cr = v86util.view(Int32Array, memory, 580, 8);
  45. /** @type {number} */
  46. this.cr[0] = 0;
  47. /** @type {number} */
  48. this.cr[2] = 0;
  49. /** @type {number} */
  50. this.cr[3] = 0;
  51. /** @type {number} */
  52. this.cr[4] = 0;
  53. // current privilege level
  54. this.cpl = v86util.view(Int32Array, memory, 612, 1);
  55. // current operand/address size
  56. this.is_32 = v86util.view(Int32Array, memory, 804, 1);
  57. this.stack_size_32 = v86util.view(Int32Array, memory, 808, 1);
  58. /**
  59. * Was the last instruction a hlt?
  60. */
  61. this.in_hlt = v86util.view(Uint8Array, memory, 616, 1);
  62. this.last_virt_eip = v86util.view(Int32Array, memory, 620, 1);
  63. this.eip_phys = v86util.view(Int32Array, memory, 624, 1);
  64. this.last_virt_esp = v86util.view(Int32Array, memory, 628, 1);
  65. this.esp_phys = v86util.view(Int32Array, memory, 632, 1);
  66. this.sysenter_cs = v86util.view(Int32Array, memory, 636, 1);
  67. this.sysenter_esp = v86util.view(Int32Array, memory, 640, 1);
  68. this.sysenter_eip = v86util.view(Int32Array, memory, 644, 1);
  69. this.prefixes = v86util.view(Int32Array, memory, 648, 1);
  70. this.flags = v86util.view(Int32Array, memory, 120, 1);
  71. /**
  72. * bitmap of flags which are not updated in the flags variable
  73. * changed by arithmetic instructions, so only relevant to arithmetic flags
  74. */
  75. this.flags_changed = v86util.view(Int32Array, memory, 116, 1);
  76. /**
  77. * the last 2 operators and the result and size of the last arithmetic operation
  78. */
  79. this.last_op1 = v86util.view(Int32Array, memory, 96, 1);
  80. this.last_op2 = v86util.view(Int32Array, memory, 100, 1);
  81. this.last_op_size = v86util.view(Int32Array, memory, 104, 1);
  82. this.last_add_result = v86util.view(Int32Array, memory, 108, 1);
  83. this.last_result = v86util.view(Int32Array, memory, 112, 1);
  84. this.current_tsc = v86util.view(Uint32Array, memory, 960, 2); // 64 bit
  85. /** @type {!Object} */
  86. this.devices = {};
  87. this.instruction_pointer = v86util.view(Int32Array, memory, 556, 1);
  88. this.previous_ip = v86util.view(Int32Array, memory, 560, 1);
  89. this.apic_enabled = true;
  90. // managed in io.js
  91. /** @const */ this.memory_map_read8 = [];
  92. /** @const */ this.memory_map_write8 = [];
  93. /** @const */ this.memory_map_read32 = [];
  94. /** @const */ this.memory_map_write32 = [];
  95. /**
  96. * @const
  97. * @type {{main: ArrayBuffer, vga: ArrayBuffer}}
  98. */
  99. this.bios = {
  100. main: null,
  101. vga: null,
  102. };
  103. this.timestamp_counter = v86util.view(Uint32Array, memory, 664, 1);
  104. // registers
  105. this.reg32s = v86util.view(Int32Array, memory, 64, 8);
  106. this.reg32 = v86util.view(Uint32Array, memory, 64, 8);
  107. this.reg16s = v86util.view(Int16Array, memory, 64, 16);
  108. this.reg16 = v86util.view(Uint16Array, memory, 64, 16);
  109. this.reg8s = v86util.view(Int8Array, memory, 64, 32);
  110. this.reg8 = v86util.view(Uint8Array, memory, 64, 32);
  111. // Why no Float80Array :-(
  112. this.fpu_st = v86util.view(Float64Array, memory, 968, 8);
  113. this.fpu_stack_empty = v86util.view(Int32Array, memory, 816, 1);
  114. this.fpu_stack_empty[0] = 0xFF;
  115. this.fpu_stack_ptr = v86util.view(Uint32Array, memory, 1032, 1);
  116. this.fpu_stack_ptr[0] = 0;
  117. this.fpu_control_word = v86util.view(Int32Array, memory, 1036, 1);
  118. this.fpu_control_word[0] = 0x37F;
  119. this.fpu_status_word = v86util.view(Int32Array, memory, 1040, 1);
  120. this.fpu_status_word[0] = 0;
  121. this.fpu_ip = v86util.view(Int32Array, memory, 1048, 1);
  122. this.fpu_ip[0] = 0;
  123. this.fpu_ip_selector = v86util.view(Int32Array, memory, 1052, 1);
  124. this.fpu_ip_selector[0] = 0;
  125. this.fpu_opcode = v86util.view(Int32Array, memory, 1044, 1);
  126. this.fpu_opcode[0] = 0;
  127. this.fpu_dp = v86util.view(Int32Array, memory, 1056, 1);
  128. this.fpu_dp[0] = 0;
  129. this.fpu_dp_selector = v86util.view(Int32Array, memory, 1060, 1);
  130. this.fpu_dp_selector[0] = 0;
  131. // mm0-mm7 split up into 32 bit pairs
  132. this.reg_mmxs = v86util.view(Int32Array, memory, 1064, 16);
  133. this.reg_mmx = v86util.view(Uint32Array, this.reg_mmxs.buffer, 1064, 16);
  134. this.reg_mmx8s = v86util.view(Int8Array, this.reg_mmxs.buffer, 1064, 64);
  135. this.reg_mmx8 = v86util.view(Uint8Array, this.reg_mmxs.buffer, 1064, 64);
  136. this.fxsave_store_fpu_mask = v86util.view(Uint8Array, memory, 1132, 1);
  137. this.reg_xmm32s = v86util.view(Int32Array, memory, 832, 8 * 4);
  138. this.mxcsr = v86util.view(Int32Array, memory, 824, 1);
  139. // segment registers, tr and ldtr
  140. this.sreg = v86util.view(Uint16Array, memory, 668, 8);
  141. // debug registers
  142. this.dreg = v86util.view(Int32Array, memory, 684, 8);
  143. this.fw_value = [];
  144. this.fw_pointer = 0;
  145. this.option_roms = [];
  146. this.io = undefined;
  147. this.bus = bus;
  148. this.update_operand_size();
  149. this.set_tsc(0, 0);
  150. this.debug_init();
  151. //Object.seal(this);
  152. }
  153. CPU.prototype.clear_opstats = function()
  154. {
  155. new Uint8Array(this.wasm_memory.buffer, 0x8000, 0x20000).fill(0);
  156. };
  157. CPU.prototype.wasmgen_get_module_code = function()
  158. {
  159. const ptr = this.jit_get_op_ptr();
  160. const len = this.jit_get_op_len();
  161. const output_buffer_view = new Uint8Array(this.v86oxide.instance.exports.memory.buffer, ptr, len);
  162. return output_buffer_view;
  163. };
  164. CPU.prototype.create_jit_imports = function()
  165. {
  166. // Set this.jit_imports as generated WASM modules will expect
  167. /** @constructor */
  168. function JITImports()
  169. {
  170. // put all imports that change here
  171. }
  172. // put all imports that don't change on the prototype
  173. JITImports.prototype["m"] = this.v86oxide.memory;
  174. const exports = this.v86oxide.instance.exports;
  175. JITImports.prototype["m"] = exports["memory"];
  176. for(let name of Object.keys(exports))
  177. {
  178. //if(name[0] !== "_")
  179. //{
  180. // continue;
  181. //}
  182. //JITImports.prototype[name.slice(1)] = exports[name];
  183. JITImports.prototype[name] = exports[name];
  184. }
  185. this.jit_imports = new JITImports();
  186. };
  187. CPU.prototype.wasm_patch = function(wm)
  188. {
  189. const get_optional_import = (name) => {
  190. return this.v86oxide.exports[name];
  191. };
  192. const get_import = (name) =>
  193. {
  194. const f = get_optional_import(name);
  195. console.assert(f, "Missing import: " + name);
  196. return f;
  197. };
  198. this.getiopl = get_import("getiopl");
  199. this.vm86_mode = get_import("vm86_mode");
  200. this.get_eflags = get_import("get_eflags");
  201. this.get_eflags_no_arith = get_import("get_eflags_no_arith");
  202. this.update_eflags = get_import("update_eflags");
  203. this.trigger_gp = get_import("trigger_gp");
  204. this.trigger_ud = get_import("trigger_ud");
  205. this.trigger_np = get_import("trigger_np");
  206. this.trigger_ss = get_import("trigger_ss");
  207. this.switch_cs_real_mode = get_import("switch_cs_real_mode");
  208. this.pic_call_irq = get_import("pic_call_irq");
  209. this.get_tss_stack_addr = get_import("get_tss_stack_addr_js");
  210. this.do_many_cycles_native = get_import("do_many_cycles_native");
  211. this.cycle_internal = get_import("cycle_internal");
  212. this.read8 = get_import("read8");
  213. this.read16 = get_import("read16");
  214. this.read32s = get_import("read32s");
  215. this.write8 = get_import("write8");
  216. this.write16 = get_import("write16");
  217. this.write32 = get_import("write32");
  218. this.in_mapped_range = get_import("in_mapped_range");
  219. this.push16 = get_import("push16_js");
  220. this.push32 = get_import("push32_js");
  221. this.set_stack_reg = get_import("set_stack_reg");
  222. this.fpu_load_tag_word = get_import("fpu_load_tag_word");
  223. this.fpu_load_status_word = get_import("fpu_load_status_word");
  224. this.translate_address_read = get_import("translate_address_read_js");
  225. this.translate_address_system_read = get_import("translate_address_system_read_js");
  226. this.translate_address_system_write = get_import("translate_address_system_write_js");
  227. this.get_seg = get_import("get_seg");
  228. this.adjust_stack_reg = get_import("adjust_stack_reg");
  229. this.get_real_eip = get_import("get_real_eip");
  230. this.get_stack_pointer = get_import("get_stack_pointer");
  231. this.writable_or_pagefault = get_import("writable_or_pagefault_js");
  232. this.safe_write32 = get_import("safe_write32_js");
  233. this.safe_read32s = get_import("safe_read32s_js");
  234. this.safe_write16 = get_import("safe_write16_js");
  235. this.safe_read16 = get_import("safe_read16_js");
  236. this.clear_tlb = get_import("clear_tlb");
  237. this.full_clear_tlb = get_import("full_clear_tlb");
  238. this.set_tsc = get_import("set_tsc");
  239. this.store_current_tsc = get_import("store_current_tsc");
  240. this.pack_current_state_flags = get_import("pack_current_state_flags");
  241. if(DEBUG)
  242. {
  243. this.jit_force_generate_unsafe = get_optional_import("jit_force_generate_unsafe");
  244. }
  245. this.jit_empty_cache = get_import("jit_empty_cache");
  246. this.jit_dirty_cache = get_import("jit_dirty_cache");
  247. this.codegen_finalize_finished = get_import("codegen_finalize_finished");
  248. this.jit_get_op_ptr = get_import("jit_get_op_ptr");
  249. this.jit_get_op_len = get_import("jit_get_op_len");
  250. this.allocate_memory = get_import("allocate_memory");
  251. };
  252. CPU.prototype.jit_force_generate = function(addr)
  253. {
  254. if(!this.jit_force_generate_unsafe)
  255. {
  256. dbg_assert(false, "Not supported in this wasm build: jit_force_generate_unsafe");
  257. return;
  258. }
  259. const cs_offset = this.get_seg(reg_cs);
  260. const state_flags = this.pack_current_state_flags();
  261. this.jit_force_generate_unsafe(addr, cs_offset, state_flags);
  262. };
  263. CPU.prototype.jit_clear_func = function(index)
  264. {
  265. dbg_assert(index >= 0 && index < WASM_TABLE_SIZE);
  266. this.wm.imports["env"][WASM_EXPORT_TABLE_NAME].set(index + WASM_TABLE_OFFSET, null);
  267. };
  268. CPU.prototype.get_state = function()
  269. {
  270. var state = [];
  271. state[0] = this.memory_size[0];
  272. state[1] = this.segment_is_null;
  273. state[2] = this.segment_offsets;
  274. state[3] = this.segment_limits;
  275. state[4] = this.protected_mode[0];
  276. state[5] = this.idtr_offset[0];
  277. state[6] = this.idtr_size[0];
  278. state[7] = this.gdtr_offset[0];
  279. state[8] = this.gdtr_size[0];
  280. state[9] = this.page_fault[0];
  281. state[10] = this.cr;
  282. state[11] = this.cpl[0];
  283. state[13] = this.is_32[0];
  284. state[16] = this.stack_size_32[0];
  285. state[17] = this.in_hlt[0];
  286. state[18] = this.last_virt_eip[0];
  287. state[19] = this.eip_phys[0];
  288. state[20] = this.last_virt_esp[0];
  289. state[21] = this.esp_phys[0];
  290. state[22] = this.sysenter_cs[0];
  291. state[23] = this.sysenter_eip[0];
  292. state[24] = this.sysenter_esp[0];
  293. state[25] = this.prefixes[0];
  294. state[26] = this.flags[0];
  295. state[27] = this.flags_changed[0];
  296. state[28] = this.last_op1[0];
  297. state[29] = this.last_op2[0];
  298. state[30] = this.last_op_size[0];
  299. state[31] = this.last_add_result[0];
  300. state[37] = this.instruction_pointer[0];
  301. state[38] = this.previous_ip[0];
  302. state[39] = this.reg32s;
  303. state[40] = this.sreg;
  304. state[41] = this.dreg;
  305. this.store_current_tsc();
  306. state[43] = this.current_tsc;
  307. state[45] = this.devices.virtio_9p;
  308. state[46] = this.devices.apic;
  309. state[47] = this.devices.rtc;
  310. state[48] = this.devices.pci;
  311. state[49] = this.devices.dma;
  312. state[50] = this.devices.acpi;
  313. state[51] = this.devices.hpet;
  314. state[52] = this.devices.vga;
  315. state[53] = this.devices.ps2;
  316. state[54] = this.devices.uart;
  317. state[55] = this.devices.fdc;
  318. state[56] = this.devices.cdrom;
  319. state[57] = this.devices.hda;
  320. state[58] = this.devices.pit;
  321. state[59] = this.devices.net;
  322. state[60] = this.devices.pic;
  323. state[61] = this.a20_enabled[0];
  324. state[62] = this.fw_value;
  325. state[63] = this.devices.ioapic;
  326. state[64] = this.tss_size_32[0];
  327. state[65] = this.reg_mmxs;
  328. state[66] = this.reg_xmm32s;
  329. state[67] = this.fpu_st;
  330. state[68] = this.fpu_stack_empty[0];
  331. state[69] = this.fpu_stack_ptr[0];
  332. state[70] = this.fpu_control_word[0];
  333. state[71] = this.fpu_ip[0];
  334. state[72] = this.fpu_ip_selector[0];
  335. state[73] = this.fpu_dp[0];
  336. state[74] = this.fpu_dp_selector[0];
  337. state[75] = this.fpu_opcode[0];
  338. state[76] = this.fxsave_store_fpu_mask;
  339. const { packed_memory, bitmap } = this.pack_memory();
  340. state[77] = packed_memory;
  341. state[78] = new Uint8Array(bitmap.get_buffer());
  342. return state;
  343. };
  344. CPU.prototype.set_state = function(state)
  345. {
  346. this.memory_size[0] = state[0];
  347. if(this.mem8.length !== this.memory_size[0])
  348. {
  349. console.warn("Note: Memory size mismatch. we=" + this.mem8.length + " state=" + this.memory_size[0]);
  350. }
  351. this.segment_is_null.set(state[1]);
  352. this.segment_offsets.set(state[2]);
  353. this.segment_limits.set(state[3]);
  354. this.protected_mode[0] = state[4];
  355. this.idtr_offset[0] = state[5];
  356. this.idtr_size[0] = state[6];
  357. this.gdtr_offset[0] = state[7];
  358. this.gdtr_size[0] = state[8];
  359. this.page_fault[0] = state[9];
  360. this.cr.set(state[10]);
  361. this.cpl[0] = state[11];
  362. this.is_32[0] = state[13];
  363. this.stack_size_32[0] = state[16];
  364. this.in_hlt[0] = state[17];
  365. this.last_virt_eip[0] = state[18];
  366. this.eip_phys[0] = state[19];
  367. this.last_virt_esp[0] = state[20];
  368. this.esp_phys[0] = state[21];
  369. this.sysenter_cs[0] = state[22];
  370. this.sysenter_eip[0] = state[23];
  371. this.sysenter_esp[0] = state[24];
  372. this.prefixes[0] = state[25];
  373. this.flags[0] = state[26];
  374. this.flags_changed[0] = state[27];
  375. this.last_op1[0] = state[28];
  376. this.last_op2[0] = state[29];
  377. this.last_op_size[0] = state[30];
  378. this.last_add_result[0] = state[31];
  379. this.instruction_pointer[0] = state[37];
  380. this.previous_ip[0] = state[38];
  381. this.reg32s.set(state[39]);
  382. this.sreg.set(state[40]);
  383. this.dreg.set(state[41]);
  384. this.set_tsc(state[43][0], state[43][1]);
  385. this.devices.virtio_9p = state[45];
  386. this.devices.apic = state[46];
  387. this.devices.rtc = state[47];
  388. this.devices.pci = state[48];
  389. this.devices.dma = state[49];
  390. this.devices.acpi = state[50];
  391. this.devices.hpet = state[51];
  392. this.devices.vga = state[52];
  393. this.devices.ps2 = state[53];
  394. this.devices.uart = state[54];
  395. this.devices.fdc = state[55];
  396. this.devices.cdrom = state[56];
  397. this.devices.hda = state[57];
  398. this.devices.pit = state[58];
  399. this.devices.net = state[59];
  400. this.devices.pic = state[60];
  401. this.a20_enabled[0] = state[61];
  402. this.fw_value = state[62];
  403. this.devices.ioapic = state[63];
  404. this.tss_size_32[0] = state[64];
  405. this.reg_mmxs.set(state[65]);
  406. this.reg_xmm32s.set(state[66]);
  407. this.fpu_st.set(state[67]);
  408. this.fpu_stack_empty[0] = state[68];
  409. this.fpu_stack_ptr[0] = state[69];
  410. this.fpu_control_word[0] = state[70];
  411. this.fpu_ip[0] = state[71];
  412. this.fpu_ip_selector[0] = state[72];
  413. this.fpu_dp[0] = state[73];
  414. this.fpu_dp_selector[0] = state[74];
  415. this.fpu_opcode[0] = state[75];
  416. this.fxsave_store_fpu_mask = state[76];
  417. const bitmap = new v86util.Bitmap(state[78].buffer);
  418. const packed_memory = state[77];
  419. this.unpack_memory(bitmap, packed_memory);
  420. this.full_clear_tlb();
  421. this.update_operand_size();
  422. };
  423. CPU.prototype.pack_memory = function()
  424. {
  425. dbg_assert((this.mem8.length & 0xFFF) === 0);
  426. const page_count = this.mem8.length >> 12;
  427. const nonzero_pages = [];
  428. for(let page = 0; page < page_count; page++)
  429. {
  430. const offset = page << 12;
  431. const view = this.mem32s.subarray(offset >> 2, offset + 0x1000 >> 2);
  432. let is_zero = true;
  433. for(let i = 0; i < view.length; i++)
  434. {
  435. if(view[i] !== 0)
  436. {
  437. is_zero = false;
  438. break;
  439. }
  440. }
  441. if(!is_zero)
  442. {
  443. nonzero_pages.push(page);
  444. }
  445. }
  446. const bitmap = new v86util.Bitmap(page_count);
  447. const packed_memory = new Uint8Array(nonzero_pages.length << 12);
  448. for(let [i, page] of nonzero_pages.entries())
  449. {
  450. bitmap.set(page, 1);
  451. const offset = page << 12;
  452. const page_contents = this.mem8.subarray(offset, offset + 0x1000);
  453. packed_memory.set(page_contents, i << 12);
  454. }
  455. return { bitmap, packed_memory };
  456. };
  457. CPU.prototype.unpack_memory = function(bitmap, packed_memory)
  458. {
  459. // TODO: Skip zeroing memory if the memory has just been allocated
  460. this.mem8.fill(0);
  461. const page_count = this.memory_size[0] >> 12;
  462. let packed_page = 0;
  463. for(let page = 0; page < page_count; page++)
  464. {
  465. if(bitmap.get(page))
  466. {
  467. let offset = packed_page << 12;
  468. let view = packed_memory.subarray(offset, offset + 0x1000);
  469. this.mem8.set(view, page << 12);
  470. packed_page++;
  471. }
  472. }
  473. };
  474. /**
  475. * @return {number} time in ms until this method should becalled again
  476. */
  477. CPU.prototype.main_run = function()
  478. {
  479. if(this.in_hlt[0])
  480. {
  481. //if(false)
  482. //{
  483. // var _t = this.hlt_loop();
  484. // var t = 0;
  485. //}
  486. //else
  487. //{
  488. var t = this.hlt_loop();
  489. //}
  490. if(this.in_hlt[0])
  491. {
  492. return t;
  493. }
  494. }
  495. this.do_run();
  496. return 0;
  497. };
  498. CPU.prototype.reboot_internal = function()
  499. {
  500. this.reset();
  501. this.load_bios();
  502. };
  503. CPU.prototype.reset = function()
  504. {
  505. this.a20_enabled[0] = +true;
  506. this.segment_is_null.fill(0);
  507. this.segment_limits.fill(0);
  508. //this.segment_infos = new Uint32Array(8);
  509. this.segment_offsets.fill(0);
  510. this.reg32s.fill(0);
  511. this.sreg.fill(0);
  512. this.dreg.fill(0);
  513. this.fpu_st.fill(0);
  514. this.fpu_stack_empty[0] = 0xFF;
  515. this.fpu_stack_ptr[0] = 0;
  516. this.fpu_control_word[0] = 0x37F;
  517. this.fpu_status_word[0] = 0;
  518. this.fpu_ip[0] = 0;
  519. this.fpu_ip_selector[0] = 0;
  520. this.fpu_opcode[0] = 0;
  521. this.fpu_dp[0] = 0;
  522. this.fpu_dp_selector[0] = 0;
  523. this.reg_mmxs.fill(0);
  524. this.reg_xmm32s.fill(0);
  525. this.mxcsr[0] = 0x1F80;
  526. this.full_clear_tlb();
  527. this.protected_mode[0] = +false;
  528. // http://www.sandpile.org/x86/initial.htm
  529. this.idtr_size[0] = 0;
  530. this.idtr_offset[0] = 0;
  531. this.gdtr_size[0] = 0;
  532. this.gdtr_offset[0] = 0;
  533. this.page_fault[0] = 0;
  534. this.cr[0] = 1 << 30 | 1 << 29 | 1 << 4;
  535. this.cr[2] = 0;
  536. this.cr[3] = 0;
  537. this.cr[4] = 0;
  538. this.dreg[6] = 0xFFFF0FF0|0;
  539. this.dreg[7] = 0x400;
  540. this.cpl[0] = 0;
  541. this.is_32[0] = +false;
  542. this.stack_size_32[0] = +false;
  543. this.prefixes[0] = 0;
  544. this.last_virt_eip[0] = -1;
  545. this.last_virt_esp[0] = -1;
  546. this.update_operand_size();
  547. this.timestamp_counter[0] = 0;
  548. this.previous_ip[0] = 0;
  549. this.in_hlt[0] = +false;
  550. this.sysenter_cs[0] = 0;
  551. this.sysenter_esp[0] = 0;
  552. this.sysenter_eip[0] = 0;
  553. this.flags[0] = flags_default;
  554. this.flags_changed.fill(0);
  555. this.last_result.fill(0);
  556. this.last_add_result.fill(0);
  557. this.last_op1.fill(0);
  558. this.last_op2.fill(0);
  559. this.last_op_size.fill(0);
  560. this.set_tsc(0, 0);
  561. this.instruction_pointer[0] = 0xFFFF0;
  562. this.switch_cs_real_mode(0xF000);
  563. if(!this.switch_seg(reg_ss, 0x30)) dbg_assert(false);
  564. this.reg16[reg_sp] = 0x100;
  565. if(this.devices.virtio)
  566. {
  567. this.devices.virtio.reset();
  568. }
  569. this.fw_value = [];
  570. this.jit_clear_cache();
  571. };
  572. CPU.prototype.reset_memory = function()
  573. {
  574. this.mem8.fill(0);
  575. };
  576. /** @export */
  577. CPU.prototype.create_memory = function(size)
  578. {
  579. if(size < 1024 * 1024)
  580. {
  581. size = 1024 * 1024;
  582. }
  583. else if((size | 0) < 0)
  584. {
  585. size = Math.pow(2, 31) - MMAP_BLOCK_SIZE;
  586. }
  587. size = ((size - 1) | (MMAP_BLOCK_SIZE - 1)) + 1 | 0;
  588. dbg_assert((size | 0) > 0);
  589. dbg_assert((size & MMAP_BLOCK_SIZE - 1) === 0);
  590. console.assert(this.memory_size[0] === 0);
  591. this.memory_size[0] = size;
  592. const memory_offset = this.allocate_memory(size);
  593. this.mem8 = v86util.view(Uint8Array, this.v86oxide.instance.exports.memory, memory_offset, size);
  594. this.mem16 = v86util.view(Uint16Array, this.v86oxide.instance.exports.memory, memory_offset, size >> 1);
  595. this.mem32s = v86util.view(Uint32Array, this.v86oxide.instance.exports.memory, memory_offset, size >> 2);
  596. };
  597. CPU.prototype.init = function(settings, device_bus)
  598. {
  599. if(typeof settings.log_level === "number")
  600. {
  601. // XXX: Shared between all emulator instances
  602. LOG_LEVEL = settings.log_level;
  603. }
  604. this.create_memory(typeof settings.memory_size === "number" ?
  605. settings.memory_size : 1024 * 1024 * 64);
  606. this.reset();
  607. var io = new IO(this);
  608. this.io = io;
  609. this.bios.main = settings.bios;
  610. this.bios.vga = settings.vga_bios;
  611. this.load_bios();
  612. if(settings.bzimage)
  613. {
  614. dbg_assert(settings.cmdline);
  615. const { option_rom } = load_kernel(this.mem8, settings.bzimage, settings.initrd, settings.cmdline);
  616. if(option_rom)
  617. {
  618. this.option_roms.push(option_rom);
  619. }
  620. }
  621. var a20_byte = 0;
  622. io.register_read(0xB3, this, function()
  623. {
  624. // seabios smm_relocate_and_restore
  625. dbg_log("port 0xB3 read");
  626. return 0;
  627. });
  628. io.register_read(0x92, this, function()
  629. {
  630. return a20_byte;
  631. });
  632. io.register_write(0x92, this, function(out_byte)
  633. {
  634. a20_byte = out_byte;
  635. });
  636. io.register_read(0x511, this, function()
  637. {
  638. // bios config port (used by seabios and kvm-unit-test)
  639. if(this.fw_pointer < this.fw_value.length)
  640. {
  641. return this.fw_value[this.fw_pointer++];
  642. }
  643. else
  644. {
  645. dbg_assert(false, "config port: Read past value");
  646. return 0;
  647. }
  648. });
  649. io.register_write(0x510, this, undefined, function(value)
  650. {
  651. // https://wiki.osdev.org/QEMU_fw_cfg
  652. // https://github.com/qemu/qemu/blob/master/docs/specs/fw_cfg.txt
  653. dbg_log("bios config port, index=" + h(value));
  654. function i32(x)
  655. {
  656. return new Uint8Array(new Int32Array([x]).buffer);
  657. }
  658. function i64(x0, x1)
  659. {
  660. return new Uint8Array(new Int32Array([x0, x1]).buffer);
  661. }
  662. function to_be16(x)
  663. {
  664. return x >> 8 | x << 8 & 0xFF00;
  665. }
  666. function to_be32(x)
  667. {
  668. return x << 24 | x << 8 & 0xFF0000 | x >> 8 & 0xFF00 | x >>> 24;
  669. }
  670. this.fw_pointer = 0;
  671. if(value === FW_CFG_SIGNATURE)
  672. {
  673. // Pretend to be qemu (for seabios)
  674. this.fw_value = i32(FW_CFG_SIGNATURE_QEMU);
  675. }
  676. else if(value === FW_CFG_ID)
  677. {
  678. this.fw_value = i32(0);
  679. }
  680. else if(value === FW_CFG_RAM_SIZE)
  681. {
  682. this.fw_value = i32(this.memory_size[0]);
  683. }
  684. else if(value === FW_CFG_NB_CPUS)
  685. {
  686. this.fw_value = i32(1);
  687. }
  688. else if(value === FW_CFG_MAX_CPUS)
  689. {
  690. this.fw_value = i32(1);
  691. }
  692. else if(value === FW_CFG_NUMA)
  693. {
  694. this.fw_value = i64(0, 0);
  695. }
  696. else if(value === FW_CFG_FILE_DIR)
  697. {
  698. const buffer_size = 4 + 64 * this.option_roms.length;
  699. const buffer32 = new Int32Array(buffer_size);
  700. const buffer8 = new Uint8Array(buffer32.buffer);
  701. buffer32[0] = to_be32(this.option_roms.length);
  702. for(let i = 0; i < this.option_roms.length; i++)
  703. {
  704. const { name, data } = this.option_roms[i];
  705. const file_struct_ptr = 4 + 64 * i;
  706. dbg_assert(FW_CFG_FILE_START + i < 0x10000);
  707. buffer32[file_struct_ptr + 0 >> 2] = to_be32(data.length);
  708. buffer32[file_struct_ptr + 4 >> 2] = to_be16(FW_CFG_FILE_START + i);
  709. dbg_assert(name.length < 64 - 8);
  710. for(let j = 0; j < name.length; j++)
  711. {
  712. buffer8[file_struct_ptr + 8 + j] = name.charCodeAt(j);
  713. }
  714. }
  715. this.fw_value = buffer8;
  716. }
  717. else if(value >= FW_CFG_CUSTOM_START && value < FW_CFG_FILE_START)
  718. {
  719. this.fw_value = i32(0);
  720. }
  721. else if(value >= FW_CFG_FILE_START && value - FW_CFG_FILE_START < this.option_roms.length)
  722. {
  723. const i = value - FW_CFG_FILE_START;
  724. this.fw_value = this.option_roms[i].data;
  725. }
  726. else
  727. {
  728. dbg_assert(false, "Unimplemented fw index: " + h(value));
  729. this.fw_value = i32(0);
  730. }
  731. });
  732. if(DEBUG)
  733. {
  734. // Use by linux for port-IO delay
  735. // Avoid generating tons of debug messages
  736. io.register_write(0x80, this, function(out_byte)
  737. {
  738. });
  739. }
  740. this.devices = {};
  741. // TODO: Make this more configurable
  742. if(settings.load_devices)
  743. {
  744. this.devices.pic = new PIC(this);
  745. this.devices.pci = new PCI(this);
  746. if(ENABLE_ACPI)
  747. {
  748. this.devices.ioapic = new IOAPIC(this);
  749. this.devices.apic = new APIC(this);
  750. this.devices.acpi = new ACPI(this);
  751. }
  752. this.devices.rtc = new RTC(this);
  753. this.fill_cmos(this.devices.rtc, settings);
  754. this.devices.dma = new DMA(this);
  755. if(ENABLE_HPET)
  756. {
  757. this.devices.hpet = new HPET(this);
  758. }
  759. this.devices.vga = new VGAScreen(this, device_bus,
  760. settings.vga_memory_size || 8 * 1024 * 1024);
  761. this.devices.ps2 = new PS2(this, device_bus);
  762. this.devices.uart = new UART(this, 0x3F8, device_bus);
  763. this.devices.fdc = new FloppyController(this, settings.fda, settings.fdb);
  764. var ide_device_count = 0;
  765. if(settings.hda)
  766. {
  767. this.devices.hda = new IDEDevice(this, settings.hda, false, ide_device_count++, device_bus);
  768. }
  769. if(settings.cdrom)
  770. {
  771. this.devices.cdrom = new IDEDevice(this, settings.cdrom, true, ide_device_count++, device_bus);
  772. }
  773. if(settings.hdb)
  774. {
  775. this.devices.hdb = new IDEDevice(this, settings.hdb, false, ide_device_count++, device_bus);
  776. }
  777. this.devices.pit = new PIT(this);
  778. if(settings.enable_ne2k)
  779. {
  780. this.devices.net = new Ne2k(this, device_bus);
  781. }
  782. if(settings.fs9p)
  783. {
  784. this.devices.virtio_9p = new Virtio9p(settings.fs9p, this, device_bus);
  785. }
  786. }
  787. if(settings.multiboot)
  788. {
  789. this.load_multiboot(settings.multiboot);
  790. }
  791. if(DEBUG)
  792. {
  793. this.debug.init();
  794. }
  795. //this.wm.exports["_profiler_init"]();
  796. };
  797. CPU.prototype.load_multiboot = function(buffer)
  798. {
  799. // https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
  800. dbg_log("Trying multiboot from buffer of size " + buffer.byteLength, LOG_CPU);
  801. const MAGIC = 0x1BADB002;
  802. const ELF_MAGIC = 0x464C457F;
  803. const MULTIBOOT_HEADER_ADDRESS = 0x10000;
  804. const MULTIBOOT_SEARCH_BYTES = 8192;
  805. if(buffer.byteLength < MULTIBOOT_SEARCH_BYTES)
  806. {
  807. var buf32 = new Int32Array(MULTIBOOT_SEARCH_BYTES / 4);
  808. new Uint8Array(buf32.buffer).set(new Uint8Array(buffer));
  809. }
  810. else
  811. {
  812. var buf32 = new Int32Array(buffer, 0, MULTIBOOT_SEARCH_BYTES / 4);
  813. }
  814. for(var offset = 0; offset < MULTIBOOT_SEARCH_BYTES; offset += 4)
  815. {
  816. if(buf32[offset >> 2] === MAGIC)
  817. {
  818. var flags = buf32[offset + 4 >> 2];
  819. var checksum = buf32[offset + 8 >> 2];
  820. var total = MAGIC + flags + checksum | 0;
  821. if(total)
  822. {
  823. dbg_log("Multiboot checksum check failed", LOG_CPU);
  824. continue;
  825. }
  826. }
  827. else
  828. {
  829. continue;
  830. }
  831. dbg_log("Multiboot magic found, flags: " + h(flags >>> 0, 8), LOG_CPU);
  832. dbg_assert((flags & ~MULTIBOOT_HEADER_ADDRESS) === 0, "TODO");
  833. this.reg32s[reg_eax] = 0x2BADB002;
  834. let multiboot_info_addr = 0x7C00;
  835. this.reg32s[reg_ebx] = multiboot_info_addr;
  836. this.write32(multiboot_info_addr, 0);
  837. this.cr[0] = 1;
  838. this.protected_mode[0] = +true;
  839. this.flags[0] = flags_default;
  840. this.update_cs_size(true);
  841. this.stack_size_32[0] = +true;
  842. for(var i = 0; i < 6; i++)
  843. {
  844. this.segment_is_null[i] = 0;
  845. this.segment_offsets[i] = 0;
  846. this.segment_limits[i] = 0xFFFFFFFF;
  847. // Value doesn't matter, OS isn't allowed to reload without setting
  848. // up a proper GDT
  849. this.sreg[i] = 0xB002;
  850. }
  851. if(flags & MULTIBOOT_HEADER_ADDRESS)
  852. {
  853. dbg_log("Multiboot specifies its own address table", LOG_CPU);
  854. var header_addr = buf32[offset + 12 >> 2];
  855. var load_addr = buf32[offset + 16 >> 2];
  856. var load_end_addr = buf32[offset + 20 >> 2];
  857. var bss_end_addr = buf32[offset + 24 >> 2];
  858. var entry_addr = buf32[offset + 28 >> 2];
  859. dbg_log("header=" + h(header_addr, 8) +
  860. " load=" + h(load_addr, 8) +
  861. " load_end=" + h(load_end_addr, 8) +
  862. " bss_end=" + h(bss_end_addr, 8) +
  863. " entry=" + h(entry_addr, 8));
  864. dbg_assert(load_addr <= header_addr);
  865. var file_start = offset - (header_addr - load_addr);
  866. if(load_end_addr === 0)
  867. {
  868. var length = undefined;
  869. }
  870. else
  871. {
  872. dbg_assert(load_end_addr >= load_addr);
  873. var length = load_end_addr - load_addr;
  874. }
  875. let blob = new Uint8Array(buffer, file_start, length);
  876. this.write_blob(blob, load_addr);
  877. this.instruction_pointer[0] = this.get_seg(reg_cs) + entry_addr | 0;
  878. }
  879. else if(buf32[0] === ELF_MAGIC)
  880. {
  881. dbg_log("Multiboot image is in elf format", LOG_CPU);
  882. let elf = read_elf(buffer);
  883. this.instruction_pointer[0] = this.get_seg(reg_cs) + elf.header.entry | 0;
  884. for(let program of elf.program_headers)
  885. {
  886. if(program.type === 0)
  887. {
  888. // null
  889. }
  890. else if(program.type === 1)
  891. {
  892. // load
  893. // Since multiboot specifies that paging is disabled,
  894. // virtual and physical address must be equal
  895. dbg_assert(program.paddr === program.vaddr);
  896. dbg_assert(program.filesz <= program.memsz);
  897. if(program.paddr + program.memsz < this.memory_size[0])
  898. {
  899. if(program.filesz) // offset might be outside of buffer if filesz is 0
  900. {
  901. let blob = new Uint8Array(buffer, program.offset, program.filesz);
  902. this.write_blob(blob, program.paddr);
  903. }
  904. }
  905. else
  906. {
  907. dbg_log("Warning: Skipped loading section, paddr=" + h(program.paddr) + " memsz=" + program.memsz, LOG_CPU);
  908. }
  909. }
  910. else if(
  911. program.type === 2 ||
  912. program.type === 3 ||
  913. program.type === 4 ||
  914. program.type === 6 ||
  915. program.type === 0x6474e550 ||
  916. program.type === 0x6474e551)
  917. {
  918. // ignore for now
  919. }
  920. else
  921. {
  922. dbg_assert(false, "unimplemented elf section type");
  923. }
  924. }
  925. }
  926. else
  927. {
  928. dbg_assert(false, "Not a bootable multiboot format");
  929. }
  930. // only for kvm-unit-test
  931. this.io.register_write_consecutive(0xF4, this,
  932. function(value)
  933. {
  934. console.log("Test exited with code " + h(value, 2));
  935. throw "HALT";
  936. },
  937. function() {},
  938. function() {},
  939. function() {});
  940. // only for kvm-unit-test
  941. for(let i = 0xE; i <= 0xF; i++)
  942. {
  943. this.io.register_write(0x2000 + i, this,
  944. function(value)
  945. {
  946. dbg_log("kvm-unit-test: Set irq " + h(i) + " to " + h(value, 2));
  947. if(value)
  948. {
  949. this.device_raise_irq(i);
  950. }
  951. else
  952. {
  953. this.device_lower_irq(i);
  954. }
  955. });
  956. }
  957. dbg_log("Starting multiboot kernel at:", LOG_CPU);
  958. this.debug.dump_state();
  959. this.debug.dump_regs();
  960. break;
  961. }
  962. };
  963. CPU.prototype.fill_cmos = function(rtc, settings)
  964. {
  965. var boot_order = settings.boot_order || 0x213;
  966. // Used by seabios to determine the boot order
  967. // Nibble
  968. // 1: FloppyPrio
  969. // 2: HDPrio
  970. // 3: CDPrio
  971. // 4: BEVPrio
  972. // bootflag 1, high nibble, lowest priority
  973. // Low nibble: Disable floppy signature check (1)
  974. rtc.cmos_write(CMOS_BIOS_BOOTFLAG1 , 1 | boot_order >> 4 & 0xF0);
  975. // bootflag 2, both nibbles, high and middle priority
  976. rtc.cmos_write(CMOS_BIOS_BOOTFLAG2, boot_order & 0xFF);
  977. // 640k or less if less memory is used
  978. rtc.cmos_write(CMOS_MEM_BASE_LOW, 640 & 0xFF);
  979. rtc.cmos_write(CMOS_MEM_BASE_HIGH, 640 >> 8);
  980. var memory_above_1m = 0; // in k
  981. if(this.memory_size[0] >= 1024 * 1024)
  982. {
  983. memory_above_1m = (this.memory_size[0] - 1024 * 1024) >> 10;
  984. memory_above_1m = Math.min(memory_above_1m, 0xFFFF);
  985. }
  986. rtc.cmos_write(CMOS_MEM_OLD_EXT_LOW, memory_above_1m & 0xFF);
  987. rtc.cmos_write(CMOS_MEM_OLD_EXT_HIGH, memory_above_1m >> 8 & 0xFF);
  988. rtc.cmos_write(CMOS_MEM_EXTMEM_LOW, memory_above_1m & 0xFF);
  989. rtc.cmos_write(CMOS_MEM_EXTMEM_HIGH, memory_above_1m >> 8 & 0xFF);
  990. var memory_above_16m = 0; // in 64k blocks
  991. if(this.memory_size[0] >= 16 * 1024 * 1024)
  992. {
  993. memory_above_16m = (this.memory_size[0] - 16 * 1024 * 1024) >> 16;
  994. memory_above_16m = Math.min(memory_above_16m, 0xFFFF);
  995. }
  996. rtc.cmos_write(CMOS_MEM_EXTMEM2_LOW, memory_above_16m & 0xFF);
  997. rtc.cmos_write(CMOS_MEM_EXTMEM2_HIGH, memory_above_16m >> 8 & 0xFF);
  998. // memory above 4G (not supported by this emulator)
  999. rtc.cmos_write(CMOS_MEM_HIGHMEM_LOW, 0);
  1000. rtc.cmos_write(CMOS_MEM_HIGHMEM_MID, 0);
  1001. rtc.cmos_write(CMOS_MEM_HIGHMEM_HIGH, 0);
  1002. rtc.cmos_write(CMOS_EQUIPMENT_INFO, 0x2F);
  1003. rtc.cmos_write(CMOS_BIOS_SMP_COUNT, 0);
  1004. };
  1005. CPU.prototype.load_bios = function()
  1006. {
  1007. var bios = this.bios.main;
  1008. var vga_bios = this.bios.vga;
  1009. if(!bios)
  1010. {
  1011. dbg_log("Warning: No BIOS");
  1012. return;
  1013. }
  1014. // load bios
  1015. var data = new Uint8Array(bios),
  1016. start = 0x100000 - bios.byteLength;
  1017. this.write_blob(data, start);
  1018. if(vga_bios)
  1019. {
  1020. // load vga bios
  1021. var vga_bios8 = new Uint8Array(vga_bios);
  1022. // older versions of seabios
  1023. this.write_blob(vga_bios8, 0xC0000);
  1024. // newer versions of seabios (needs to match pci rom address, see vga.js)
  1025. this.io.mmap_register(0xFEB00000, 0x100000,
  1026. function(addr)
  1027. {
  1028. addr = (addr - 0xFEB00000) | 0;
  1029. if(addr < vga_bios8.length)
  1030. {
  1031. return vga_bios8[addr];
  1032. }
  1033. else
  1034. {
  1035. return 0;
  1036. }
  1037. },
  1038. function(addr, value)
  1039. {
  1040. dbg_assert(false, "Unexpected write to VGA rom");
  1041. });
  1042. }
  1043. else
  1044. {
  1045. dbg_log("Warning: No VGA BIOS");
  1046. }
  1047. // seabios expects the bios to be mapped to 0xFFF00000 also
  1048. this.io.mmap_register(0xFFF00000, 0x100000,
  1049. function(addr)
  1050. {
  1051. addr &= 0xFFFFF;
  1052. return this.mem8[addr];
  1053. }.bind(this),
  1054. function(addr, value)
  1055. {
  1056. addr &= 0xFFFFF;
  1057. this.mem8[addr] = value;
  1058. }.bind(this));
  1059. };
  1060. CPU.prototype.do_run = function()
  1061. {
  1062. //this.wm.exports["_profiler_stat_increment_do_run"]();
  1063. /** @type {number} */
  1064. var start = v86.microtick();
  1065. /** @type {number} */
  1066. var now = start;
  1067. // outer loop:
  1068. // runs cycles + timers
  1069. for(; now - start < TIME_PER_FRAME;)
  1070. {
  1071. this.run_hardware_timers(now);
  1072. this.handle_irqs();
  1073. this.do_many_cycles();
  1074. if(this.in_hlt[0])
  1075. {
  1076. return;
  1077. }
  1078. now = v86.microtick();
  1079. }
  1080. };
  1081. let do_many_cycles_count = 0;
  1082. let do_many_cycles_total = 0;
  1083. CPU.prototype.do_many_cycles = function()
  1084. {
  1085. if(ENABLE_PROFILER)
  1086. {
  1087. var start_time = v86.microtick();
  1088. }
  1089. this.do_many_cycles_native();
  1090. if(ENABLE_PROFILER)
  1091. {
  1092. do_many_cycles_total += v86.microtick() - start_time;
  1093. do_many_cycles_count++;
  1094. }
  1095. };
  1096. /** @export */
  1097. CPU.prototype.cycle = function()
  1098. {
  1099. // XXX: May do several cycles
  1100. this.cycle_internal();
  1101. };
  1102. var seen_code = {};
  1103. var seen_code_uncompiled = {};
  1104. CPU.prototype.codegen_finalize = function(wasm_table_index, start, end, first_opcode, state_flags)
  1105. {
  1106. dbg_assert(wasm_table_index >= 0 && wasm_table_index < WASM_TABLE_SIZE);
  1107. const code = this.wasmgen_get_module_code();
  1108. if(DEBUG)
  1109. {
  1110. if(DUMP_GENERATED_WASM && !seen_code[start])
  1111. {
  1112. this.debug.dump_wasm(code);
  1113. const DUMP_ASSEMBLY = false;
  1114. if(DUMP_ASSEMBLY)
  1115. {
  1116. if((start ^ end) & ~0xFFF)
  1117. {
  1118. dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0));
  1119. end = (start | 0xFFF) + 1; // until the end of the page
  1120. }
  1121. dbg_assert(end >= start);
  1122. const buffer = new Uint8Array(end - start);
  1123. for(let i = start; i < end; i++)
  1124. {
  1125. buffer[i - start] = this.read8(i);
  1126. }
  1127. this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start);
  1128. }
  1129. }
  1130. seen_code[start] = (seen_code[start] || 0) + 1;
  1131. if(this.test_hook_did_generate_wasm)
  1132. {
  1133. this.test_hook_did_generate_wasm(code);
  1134. }
  1135. }
  1136. // Make a copy of jit_imports, since some imports change and
  1137. // WebAssembly.instantiate looks them up asynchronously
  1138. const jit_imports = new this.jit_imports.constructor();
  1139. const result = WebAssembly.instantiate(code, { "e": jit_imports }).then(result => {
  1140. const f = result.instance.exports["f"];
  1141. this.codegen_finalize_finished(
  1142. wasm_table_index, start, end,
  1143. first_opcode, state_flags);
  1144. // The following will throw if f isn't an exported function
  1145. this.wm.imports["env"][WASM_EXPORT_TABLE_NAME].set(wasm_table_index + WASM_TABLE_OFFSET, f);
  1146. if(this.test_hook_did_finalize_wasm)
  1147. {
  1148. this.test_hook_did_finalize_wasm(code);
  1149. }
  1150. });
  1151. if(DEBUG)
  1152. {
  1153. result.catch(e => {
  1154. console.log(e);
  1155. debugger;
  1156. throw e;
  1157. });
  1158. }
  1159. };
  1160. CPU.prototype.log_uncompiled_code = function(start, end)
  1161. {
  1162. if(!DEBUG || !DUMP_UNCOMPILED_ASSEMBLY)
  1163. {
  1164. return;
  1165. }
  1166. if((seen_code_uncompiled[start] || 0) < 100)
  1167. {
  1168. seen_code_uncompiled[start] = (seen_code_uncompiled[start] || 0) + 1;
  1169. end += 8; // final jump is not included
  1170. if((start ^ end) & ~0xFFF)
  1171. {
  1172. dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0));
  1173. end = (start | 0xFFF) + 1; // until the end of the page
  1174. }
  1175. if(end < start) end = start;
  1176. dbg_assert(end >= start);
  1177. const buffer = new Uint8Array(end - start);
  1178. for(let i = start; i < end; i++)
  1179. {
  1180. buffer[i - start] = this.read8(i);
  1181. }
  1182. dbg_log("Uncompiled code:");
  1183. this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start);
  1184. }
  1185. };
  1186. CPU.prototype.dump_function_code = function(block_ptr, count)
  1187. {
  1188. if(!DEBUG || !DUMP_GENERATED_WASM)
  1189. {
  1190. return;
  1191. }
  1192. const SIZEOF_BASIC_BLOCK_IN_DWORDS = 7;
  1193. const mem32 = new Int32Array(this.v86oxide.instance.exports.memory.buffer);
  1194. dbg_assert((block_ptr & 3) === 0);
  1195. const is_32 = this.is_32[0];
  1196. for(let i = 0; i < count; i++)
  1197. {
  1198. const struct_start = (block_ptr >> 2) + i * SIZEOF_BASIC_BLOCK_IN_DWORDS;
  1199. const start = mem32[struct_start + 0];
  1200. const end = mem32[struct_start + 1];
  1201. const is_entry_block = mem32[struct_start + 6] & 0xFF00;
  1202. const buffer = new Uint8Array(end - start);
  1203. for(let i = start; i < end; i++)
  1204. {
  1205. buffer[i - start] = this.read8(this.translate_address_read(i));
  1206. }
  1207. dbg_log("---" + (is_entry_block ? " entry" : ""));
  1208. this.debug.dump_code(is_32 ? 1 : 0, buffer, start);
  1209. }
  1210. };
  1211. CPU.prototype.dbg_log = function()
  1212. {
  1213. dbg_log("from wasm: " + [].join.call(arguments));
  1214. };
  1215. CPU.prototype.dbg_assert = function(x)
  1216. {
  1217. dbg_assert(x);
  1218. };
  1219. CPU.prototype.hlt_loop = function()
  1220. {
  1221. if(this.get_eflags_no_arith() & flag_interrupt)
  1222. {
  1223. //dbg_log("In HLT loop", LOG_CPU);
  1224. this.run_hardware_timers(v86.microtick());
  1225. this.handle_irqs();
  1226. return 0;
  1227. }
  1228. else
  1229. {
  1230. return 100;
  1231. }
  1232. };
  1233. CPU.prototype.run_hardware_timers = function(now)
  1234. {
  1235. if(ENABLE_HPET)
  1236. {
  1237. var pit_time = this.devices.pit.timer(now, this.devices.hpet.legacy_mode);
  1238. var rtc_time = this.devices.rtc.timer(now, this.devices.hpet.legacy_mode);
  1239. this.devices.hpet.timer(now);
  1240. }
  1241. else
  1242. {
  1243. var pit_time = this.devices.pit.timer(now, false);
  1244. var rtc_time = this.devices.rtc.timer(now, false);
  1245. }
  1246. if(ENABLE_ACPI)
  1247. {
  1248. this.devices.acpi.timer(now);
  1249. this.devices.apic.timer(now);
  1250. }
  1251. };
  1252. CPU.prototype.cpl_changed = function()
  1253. {
  1254. this.last_virt_eip[0] = -1;
  1255. this.last_virt_esp[0] = -1;
  1256. };
  1257. CPU.prototype.jit_clear_cache = function()
  1258. {
  1259. this.jit_empty_cache();
  1260. const table = this.wm.exports[WASM_EXPORT_TABLE_NAME] || this.wm.imports["env"][WASM_EXPORT_TABLE_NAME];
  1261. for(let i = 0; i < WASM_TABLE_SIZE; i++)
  1262. {
  1263. table.set(WASM_TABLE_OFFSET + i, null);
  1264. }
  1265. };
  1266. CPU.prototype.far_return = function(eip, selector, stack_adjust)
  1267. {
  1268. dbg_assert(typeof selector === "number" && selector < 0x10000 && selector >= 0);
  1269. //dbg_log("far return eip=" + h(eip >>> 0, 8) + " cs=" + h(selector, 4) + " stack_adjust=" + h(stack_adjust), LOG_CPU);
  1270. CPU_LOG_VERBOSE && this.debug.dump_state("far ret start");
  1271. if(!this.protected_mode[0])
  1272. {
  1273. dbg_assert(!this.is_32[0]);
  1274. //dbg_assert(!this.stack_size_32[0]);
  1275. }
  1276. if(!this.protected_mode[0] || this.vm86_mode())
  1277. {
  1278. this.switch_cs_real_mode(selector);
  1279. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1280. this.adjust_stack_reg(2 * (this.is_osize_32() ? 4 : 2) + stack_adjust);
  1281. return;
  1282. }
  1283. var info = this.lookup_segment_selector(selector);
  1284. if(info.is_null)
  1285. {
  1286. dbg_log("null cs", LOG_CPU);
  1287. this.trigger_gp(0);
  1288. return;
  1289. }
  1290. if(!info.is_valid)
  1291. {
  1292. dbg_log("invalid cs: " + h(selector), LOG_CPU);
  1293. this.trigger_gp(selector & ~3);
  1294. return;
  1295. }
  1296. if(info.is_system)
  1297. {
  1298. dbg_assert(false, "is system in far return");
  1299. this.trigger_gp(selector & ~3);
  1300. return;
  1301. }
  1302. if(!info.is_executable)
  1303. {
  1304. dbg_log("non-executable cs: " + h(selector), LOG_CPU);
  1305. this.trigger_gp(selector & ~3);
  1306. return;
  1307. }
  1308. if(info.rpl < this.cpl[0])
  1309. {
  1310. dbg_log("cs rpl < cpl: " + h(selector), LOG_CPU);
  1311. this.trigger_gp(selector & ~3);
  1312. return;
  1313. }
  1314. if(info.dc_bit && info.dpl > info.rpl)
  1315. {
  1316. dbg_log("cs conforming and dpl > rpl: " + h(selector), LOG_CPU);
  1317. this.trigger_gp(selector & ~3);
  1318. return;
  1319. }
  1320. if(!info.dc_bit && info.dpl !== info.rpl)
  1321. {
  1322. dbg_log("cs non-conforming and dpl != rpl: " + h(selector), LOG_CPU);
  1323. this.trigger_gp(selector & ~3);
  1324. return;
  1325. }
  1326. if(!info.is_present)
  1327. {
  1328. dbg_log("#NP for loading not-present in cs sel=" + h(selector, 4), LOG_CPU);
  1329. dbg_trace(LOG_CPU);
  1330. this.trigger_np(selector & ~3);
  1331. return;
  1332. }
  1333. if(info.rpl > this.cpl[0])
  1334. {
  1335. dbg_log("far return privilege change cs: " + h(selector) + " from=" + this.cpl[0] + " to=" + info.rpl + " is_16=" + this.is_osize_32(), LOG_CPU);
  1336. if(this.is_osize_32())
  1337. {
  1338. //dbg_log("esp read from " + h(this.translate_address_system_read(this.get_stack_pointer(stack_adjust + 8))))
  1339. var temp_esp = this.safe_read32s(this.get_stack_pointer(stack_adjust + 8));
  1340. //dbg_log("esp=" + h(temp_esp));
  1341. var temp_ss = this.safe_read16(this.get_stack_pointer(stack_adjust + 12));
  1342. }
  1343. else
  1344. {
  1345. //dbg_log("esp read from " + h(this.translate_address_system_read(this.get_stack_pointer(stack_adjust + 4))));
  1346. var temp_esp = this.safe_read16(this.get_stack_pointer(stack_adjust + 4));
  1347. //dbg_log("esp=" + h(temp_esp));
  1348. var temp_ss = this.safe_read16(this.get_stack_pointer(stack_adjust + 6));
  1349. }
  1350. this.cpl[0] = info.rpl;
  1351. this.cpl_changed();
  1352. // XXX: This failure should be checked before side effects
  1353. if(!this.switch_seg(reg_ss, temp_ss)) dbg_assert(false);
  1354. this.set_stack_reg(temp_esp + stack_adjust);
  1355. //if(this.is_osize_32())
  1356. //{
  1357. // this.adjust_stack_reg(2 * 4);
  1358. //}
  1359. //else
  1360. //{
  1361. // this.adjust_stack_reg(2 * 2);
  1362. //}
  1363. //throw this.debug.unimpl("privilege change");
  1364. //this.adjust_stack_reg(stack_adjust);
  1365. }
  1366. else
  1367. {
  1368. if(this.is_osize_32())
  1369. {
  1370. this.adjust_stack_reg(2 * 4 + stack_adjust);
  1371. }
  1372. else
  1373. {
  1374. this.adjust_stack_reg(2 * 2 + stack_adjust);
  1375. }
  1376. }
  1377. //dbg_assert(this.cpl[0] === info.dpl);
  1378. this.update_cs_size(info.size);
  1379. this.segment_is_null[reg_cs] = 0;
  1380. this.segment_limits[reg_cs] = info.effective_limit;
  1381. //this.segment_infos[reg_cs] = 0; // TODO
  1382. this.segment_offsets[reg_cs] = info.base;
  1383. this.sreg[reg_cs] = selector;
  1384. dbg_assert((selector & 3) === this.cpl[0]);
  1385. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1386. //dbg_log("far return to:", LOG_CPU)
  1387. CPU_LOG_VERBOSE && this.debug.dump_state("far ret end");
  1388. };
  1389. CPU.prototype.far_jump = function(eip, selector, is_call)
  1390. {
  1391. is_call = !!is_call;
  1392. dbg_assert(typeof selector === "number" && selector < 0x10000 && selector >= 0);
  1393. //dbg_log("far " + ["jump", "call"][+is_call] + " eip=" + h(eip >>> 0, 8) + " cs=" + h(selector, 4), LOG_CPU);
  1394. CPU_LOG_VERBOSE && this.debug.dump_state("far " + ["jump", "call"][+is_call]);
  1395. if(!this.protected_mode[0] || this.vm86_mode())
  1396. {
  1397. if(is_call)
  1398. {
  1399. if(this.is_osize_32())
  1400. {
  1401. if(!this.writable_or_pagefault(this.get_stack_pointer(-8), 8))
  1402. {
  1403. return;
  1404. }
  1405. this.push32(this.sreg[reg_cs]);
  1406. this.push32(this.get_real_eip());
  1407. }
  1408. else
  1409. {
  1410. if(!this.writable_or_pagefault(this.get_stack_pointer(-4), 4))
  1411. {
  1412. return;
  1413. }
  1414. this.push16(this.sreg[reg_cs]);
  1415. this.push16(this.get_real_eip());
  1416. }
  1417. }
  1418. this.switch_cs_real_mode(selector);
  1419. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1420. return;
  1421. }
  1422. var info = this.lookup_segment_selector(selector);
  1423. if(info.is_null)
  1424. {
  1425. dbg_log("#gp null cs", LOG_CPU);
  1426. this.trigger_gp(0);
  1427. return;
  1428. }
  1429. if(!info.is_valid)
  1430. {
  1431. dbg_log("#gp invalid cs: " + h(selector), LOG_CPU);
  1432. this.trigger_gp(selector & ~3);
  1433. return;
  1434. }
  1435. if(info.is_system)
  1436. {
  1437. dbg_assert(is_call, "TODO: Jump");
  1438. dbg_log("system type cs: " + h(selector), LOG_CPU);
  1439. if(info.type === 0xC || info.type === 4)
  1440. {
  1441. // call gate
  1442. var is_16 = info.type === 4;
  1443. if(info.dpl < this.cpl[0] || info.dpl < info.rpl)
  1444. {
  1445. dbg_log("#gp cs gate dpl < cpl or dpl < rpl: " + h(selector), LOG_CPU);
  1446. this.trigger_gp(selector & ~3);
  1447. return;
  1448. }
  1449. if(!info.is_present)
  1450. {
  1451. dbg_log("#NP for loading not-present in gate cs sel=" + h(selector, 4), LOG_CPU);
  1452. this.trigger_np(selector & ~3);
  1453. return;
  1454. }
  1455. var cs_selector = info.raw0 >>> 16;
  1456. var cs_info = this.lookup_segment_selector(cs_selector);
  1457. if(cs_info.is_null)
  1458. {
  1459. dbg_log("#gp null cs", LOG_CPU);
  1460. this.trigger_gp(0);
  1461. return;
  1462. }
  1463. if(!cs_info.is_valid)
  1464. {
  1465. dbg_log("#gp invalid cs: " + h(cs_selector), LOG_CPU);
  1466. this.trigger_gp(cs_selector & ~3);
  1467. return;
  1468. }
  1469. if(!cs_info.is_executable)
  1470. {
  1471. dbg_log("#gp non-executable cs: " + h(cs_selector), LOG_CPU);
  1472. this.trigger_gp(cs_selector & ~3);
  1473. return;
  1474. }
  1475. if(cs_info.dpl > this.cpl[0])
  1476. {
  1477. dbg_log("#gp dpl > cpl: " + h(cs_selector), LOG_CPU);
  1478. this.trigger_gp(cs_selector & ~3);
  1479. return;
  1480. }
  1481. if(!cs_info.is_present)
  1482. {
  1483. dbg_log("#NP for loading not-present in cs sel=" + h(cs_selector, 4), LOG_CPU);
  1484. this.trigger_np(cs_selector & ~3);
  1485. return;
  1486. }
  1487. if(!cs_info.dc_bit && cs_info.dpl < this.cpl[0])
  1488. {
  1489. dbg_log("more privilege call gate is_16=" + is_16 + " from=" + this.cpl[0] + " to=" + cs_info.dpl);
  1490. var tss_stack_addr = this.get_tss_stack_addr(cs_info.dpl);
  1491. if(this.tss_size_32[0])
  1492. {
  1493. var new_esp = this.read32s(tss_stack_addr);
  1494. var new_ss = this.read16(tss_stack_addr + 4 | 0);
  1495. }
  1496. else
  1497. {
  1498. var new_esp = this.read16(tss_stack_addr);
  1499. var new_ss = this.read16(tss_stack_addr + 2 | 0);
  1500. }
  1501. var ss_info = this.lookup_segment_selector(new_ss);
  1502. // Disabled: Incorrect handling of direction bit
  1503. // See http://css.csail.mit.edu/6.858/2014/readings/i386/s06_03.htm
  1504. //if(!((new_esp >>> 0) <= ss_info.effective_limit))
  1505. // debugger;
  1506. //dbg_assert((new_esp >>> 0) <= ss_info.effective_limit);
  1507. dbg_assert(ss_info.is_valid && !ss_info.is_system && ss_info.is_writable);
  1508. if(ss_info.is_null)
  1509. {
  1510. throw this.debug.unimpl("#TS handler");
  1511. }
  1512. if(ss_info.rpl !== cs_info.dpl) // xxx: 0 in v86 mode
  1513. {
  1514. throw this.debug.unimpl("#TS handler");
  1515. }
  1516. if(ss_info.dpl !== cs_info.dpl || !ss_info.rw_bit)
  1517. {
  1518. throw this.debug.unimpl("#TS handler");
  1519. }
  1520. if(!ss_info.is_present)
  1521. {
  1522. throw this.debug.unimpl("#SS handler");
  1523. }
  1524. var parameter_count = info.raw1 & 0x1F;
  1525. var stack_space = is_16 ? 4 : 8;
  1526. if(is_call)
  1527. {
  1528. stack_space += is_16 ? 4 + 2 * parameter_count : 8 + 4 * parameter_count;
  1529. }
  1530. if(ss_info.size)
  1531. {
  1532. if(!this.writable_or_pagefault(ss_info.base + new_esp - stack_space | 0, stack_space)) // , cs_info.dpl
  1533. {
  1534. return;
  1535. }
  1536. }
  1537. else
  1538. {
  1539. if(!this.writable_or_pagefault(ss_info.base + (new_esp - stack_space & 0xFFFF) | 0, stack_space)) // , cs_info.dpl
  1540. {
  1541. return;
  1542. }
  1543. }
  1544. var old_esp = this.reg32s[reg_esp];
  1545. var old_ss = this.sreg[reg_ss];
  1546. var old_stack_pointer = this.get_stack_pointer(0);
  1547. //dbg_log("old_esp=" + h(old_esp));
  1548. this.cpl[0] = cs_info.dpl;
  1549. this.cpl_changed();
  1550. this.update_cs_size(cs_info.size);
  1551. // XXX: Should be checked before side effects
  1552. if(!this.switch_seg(reg_ss, new_ss)) dbg_assert(false);
  1553. this.set_stack_reg(new_esp);
  1554. //dbg_log("parameter_count=" + parameter_count);
  1555. //dbg_assert(parameter_count === 0, "TODO");
  1556. if(is_16)
  1557. {
  1558. this.push16(old_ss);
  1559. this.push16(old_esp);
  1560. //dbg_log("old esp written to " + h(this.translate_address_system_read(this.get_stack_pointer(0))));
  1561. }
  1562. else
  1563. {
  1564. this.push32(old_ss);
  1565. this.push32(old_esp);
  1566. //dbg_log("old esp written to " + h(this.translate_address_system_read(this.get_stack_pointer(0))));
  1567. }
  1568. if(is_call)
  1569. {
  1570. if(is_16)
  1571. {
  1572. for(var i = parameter_count - 1; i >= 0; i--)
  1573. {
  1574. var parameter = this.safe_read16(old_stack_pointer + 2 * i);
  1575. this.push16(parameter);
  1576. }
  1577. //this.writable_or_pagefault(this.get_stack_pointer(-4), 4);
  1578. this.push16(this.sreg[reg_cs]);
  1579. this.push16(this.get_real_eip());
  1580. }
  1581. else
  1582. {
  1583. for(var i = parameter_count - 1; i >= 0; i--)
  1584. {
  1585. var parameter = this.safe_read32s(old_stack_pointer + 4 * i);
  1586. this.push32(parameter);
  1587. }
  1588. //this.writable_or_pagefault(this.get_stack_pointer(-8), 8);
  1589. this.push32(this.sreg[reg_cs]);
  1590. this.push32(this.get_real_eip());
  1591. }
  1592. }
  1593. }
  1594. else
  1595. {
  1596. dbg_log("same privilege call gate is_16=" + is_16 + " from=" + this.cpl[0] + " to=" + cs_info.dpl + " conforming=" + cs_info.dc_bit);
  1597. // ok
  1598. if(is_call)
  1599. {
  1600. if(is_16)
  1601. {
  1602. if(!this.writable_or_pagefault(this.get_stack_pointer(-4), 4))
  1603. {
  1604. return;
  1605. }
  1606. this.push16(this.sreg[reg_cs]);
  1607. this.push16(this.get_real_eip());
  1608. }
  1609. else
  1610. {
  1611. if(!this.writable_or_pagefault(this.get_stack_pointer(-8), 8))
  1612. {
  1613. return;
  1614. }
  1615. this.push32(this.sreg[reg_cs]);
  1616. this.push32(this.get_real_eip());
  1617. }
  1618. }
  1619. }
  1620. // Note: eip from call is ignored
  1621. var new_eip = info.raw0 & 0xFFFF;
  1622. if(!is_16)
  1623. {
  1624. new_eip |= info.raw1 & 0xFFFF0000;
  1625. }
  1626. dbg_log("call gate eip=" + h(new_eip >>> 0) + " cs=" + h(cs_selector) + " conforming=" + cs_info.dc_bit);
  1627. dbg_assert((new_eip >>> 0) <= cs_info.effective_limit, "todo: #gp");
  1628. this.update_cs_size(cs_info.size);
  1629. this.segment_is_null[reg_cs] = 0;
  1630. this.segment_limits[reg_cs] = cs_info.effective_limit;
  1631. //this.segment_infos[reg_cs] = 0; // TODO
  1632. this.segment_offsets[reg_cs] = cs_info.base;
  1633. this.sreg[reg_cs] = cs_selector & ~3 | this.cpl[0];
  1634. dbg_assert((this.sreg[reg_cs] & 3) === this.cpl[0]);
  1635. this.instruction_pointer[0] = this.get_seg(reg_cs) + new_eip | 0;
  1636. }
  1637. else
  1638. {
  1639. var types = { 9: "Available 386 TSS", 0xb: "Busy 386 TSS", 4: "286 Call Gate", 0xc: "386 Call Gate" };
  1640. throw this.debug.unimpl("load system segment descriptor, type = " + (info.access & 15) + " (" + types[info.access & 15] + ")");
  1641. }
  1642. }
  1643. else
  1644. {
  1645. if(!info.is_executable)
  1646. {
  1647. dbg_log("#gp non-executable cs: " + h(selector), LOG_CPU);
  1648. this.trigger_gp(selector & ~3);
  1649. return;
  1650. }
  1651. if(info.dc_bit)
  1652. {
  1653. // conforming code segment
  1654. if(info.dpl > this.cpl[0])
  1655. {
  1656. dbg_log("#gp cs dpl > cpl: " + h(selector), LOG_CPU);
  1657. this.trigger_gp(selector & ~3);
  1658. return;
  1659. }
  1660. }
  1661. else
  1662. {
  1663. // non-conforming code segment
  1664. if(info.rpl > this.cpl[0] || info.dpl !== this.cpl[0])
  1665. {
  1666. dbg_log("#gp cs rpl > cpl or dpl != cpl: " + h(selector), LOG_CPU);
  1667. this.trigger_gp(selector & ~3);
  1668. return;
  1669. }
  1670. }
  1671. if(!info.is_present)
  1672. {
  1673. dbg_log("#NP for loading not-present in cs sel=" + h(selector, 4), LOG_CPU);
  1674. dbg_trace(LOG_CPU);
  1675. this.trigger_np(selector & ~3);
  1676. return;
  1677. }
  1678. if(is_call)
  1679. {
  1680. if(this.is_osize_32())
  1681. {
  1682. if(!this.writable_or_pagefault(this.get_stack_pointer(-8), 8))
  1683. {
  1684. return;
  1685. }
  1686. this.push32(this.sreg[reg_cs]);
  1687. this.push32(this.get_real_eip());
  1688. }
  1689. else
  1690. {
  1691. if(!this.writable_or_pagefault(this.get_stack_pointer(-4), 4))
  1692. {
  1693. return;
  1694. }
  1695. this.push16(this.sreg[reg_cs]);
  1696. this.push16(this.get_real_eip());
  1697. }
  1698. }
  1699. dbg_assert((eip >>> 0) <= info.effective_limit, "todo: #gp");
  1700. this.update_cs_size(info.size);
  1701. this.segment_is_null[reg_cs] = 0;
  1702. this.segment_limits[reg_cs] = info.effective_limit;
  1703. //this.segment_infos[reg_cs] = 0; // TODO
  1704. this.segment_offsets[reg_cs] = info.base;
  1705. this.sreg[reg_cs] = selector & ~3 | this.cpl[0];
  1706. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1707. }
  1708. //dbg_log("far " + ["jump", "call"][+is_call] + " to:", LOG_CPU)
  1709. CPU_LOG_VERBOSE && this.debug.dump_state("far " + ["jump", "call"][+is_call] + " end");
  1710. };
  1711. CPU.prototype.do_task_switch = function(selector, has_error_code, error_code)
  1712. {
  1713. dbg_assert(this.tss_size_32[0], "TODO");
  1714. dbg_log("do_task_switch sel=" + h(selector), LOG_CPU);
  1715. var descriptor = this.lookup_segment_selector(selector);
  1716. dbg_assert((descriptor.type | 2) === 3 || (descriptor.type | 2) === 0xb);
  1717. var tss_is_16 = descriptor.type <= 3;
  1718. var tss_is_busy = (descriptor.type & 2) === 2;
  1719. if(!descriptor.is_valid || descriptor.is_null || !descriptor.from_gdt)
  1720. {
  1721. throw this.debug.unimpl("#GP handler");
  1722. }
  1723. if((descriptor.access & 31) === 0xB)
  1724. {
  1725. // is busy
  1726. throw this.debug.unimpl("#GP handler");
  1727. }
  1728. if(!descriptor.is_present)
  1729. {
  1730. throw this.debug.unimpl("#NP handler");
  1731. }
  1732. if(descriptor.effective_limit < 103)
  1733. {
  1734. throw this.debug.unimpl("#NP handler");
  1735. }
  1736. var tsr_size = this.segment_limits[reg_tr];
  1737. var tsr_offset = this.segment_offsets[reg_tr];
  1738. var old_eflags = this.get_eflags();
  1739. if(tss_is_busy)
  1740. {
  1741. old_eflags &= ~flag_nt;
  1742. }
  1743. if(!this.writable_or_pagefault(tsr_offset, 0x66))
  1744. {
  1745. return;
  1746. }
  1747. //this.safe_write32(tsr_offset + TSR_CR3, this.cr[3]);
  1748. // TODO: Write 16 bit values if old tss is 16 bit
  1749. this.safe_write32(tsr_offset + TSR_EIP, this.get_real_eip());
  1750. this.safe_write32(tsr_offset + TSR_EFLAGS, old_eflags);
  1751. this.safe_write32(tsr_offset + TSR_EAX, this.reg32s[reg_eax]);
  1752. this.safe_write32(tsr_offset + TSR_ECX, this.reg32s[reg_ecx]);
  1753. this.safe_write32(tsr_offset + TSR_EDX, this.reg32s[reg_edx]);
  1754. this.safe_write32(tsr_offset + TSR_EBX, this.reg32s[reg_ebx]);
  1755. this.safe_write32(tsr_offset + TSR_ESP, this.reg32s[reg_esp]);
  1756. this.safe_write32(tsr_offset + TSR_EBP, this.reg32s[reg_ebp]);
  1757. this.safe_write32(tsr_offset + TSR_ESI, this.reg32s[reg_esi]);
  1758. this.safe_write32(tsr_offset + TSR_EDI, this.reg32s[reg_edi]);
  1759. this.safe_write32(tsr_offset + TSR_ES, this.sreg[reg_es]);
  1760. this.safe_write32(tsr_offset + TSR_CS, this.sreg[reg_cs]);
  1761. this.safe_write32(tsr_offset + TSR_SS, this.sreg[reg_ss]);
  1762. this.safe_write32(tsr_offset + TSR_DS, this.sreg[reg_ds]);
  1763. this.safe_write32(tsr_offset + TSR_FS, this.sreg[reg_fs]);
  1764. this.safe_write32(tsr_offset + TSR_GS, this.sreg[reg_gs]);
  1765. //this.safe_write32(tsr_offset + TSR_LDT, this.sreg[reg_ldtr]);
  1766. if(true /* is jump or call or int */)
  1767. {
  1768. // mark as busy
  1769. this.write8(descriptor.table_offset + 5 | 0, this.read8(descriptor.table_offset + 5 | 0) | 2);
  1770. }
  1771. //var new_tsr_size = descriptor.effective_limit;
  1772. var new_tsr_offset = descriptor.base;
  1773. dbg_assert(!tss_is_16, "unimplemented");
  1774. if(true /* is call or int */)
  1775. {
  1776. this.safe_write16(new_tsr_offset + TSR_BACKLINK, this.sreg[reg_tr]);
  1777. }
  1778. var new_cr3 = this.safe_read32s(new_tsr_offset + TSR_CR3);
  1779. this.flags[0] &= ~flag_vm;
  1780. var new_eip = this.safe_read32s(new_tsr_offset + TSR_EIP);
  1781. var new_cs = this.safe_read16(new_tsr_offset + TSR_CS);
  1782. var info = this.lookup_segment_selector(new_cs);
  1783. if(info.is_null)
  1784. {
  1785. dbg_log("null cs", LOG_CPU);
  1786. throw this.debug.unimpl("#TS handler");
  1787. }
  1788. if(!info.is_valid)
  1789. {
  1790. dbg_log("invalid cs: " + h(selector), LOG_CPU);
  1791. throw this.debug.unimpl("#TS handler");
  1792. }
  1793. if(info.is_system)
  1794. {
  1795. throw this.debug.unimpl("#TS handler");
  1796. }
  1797. if(!info.is_executable)
  1798. {
  1799. throw this.debug.unimpl("#TS handler");
  1800. }
  1801. if(info.dc_bit && info.dpl > info.rpl)
  1802. {
  1803. dbg_log("cs conforming and dpl > rpl: " + h(selector), LOG_CPU);
  1804. throw this.debug.unimpl("#TS handler");
  1805. }
  1806. if(!info.dc_bit && info.dpl !== info.rpl)
  1807. {
  1808. dbg_log("cs non-conforming and dpl != rpl: " + h(selector), LOG_CPU);
  1809. throw this.debug.unimpl("#TS handler");
  1810. }
  1811. if(!info.is_present)
  1812. {
  1813. dbg_log("#NP for loading not-present in cs sel=" + h(selector, 4), LOG_CPU);
  1814. throw this.debug.unimpl("#TS handler");
  1815. }
  1816. this.segment_is_null[reg_cs] = 0;
  1817. this.segment_limits[reg_cs] = info.effective_limit;
  1818. this.segment_offsets[reg_cs] = info.base;
  1819. this.sreg[reg_cs] = new_cs;
  1820. this.cpl = info.dpl;
  1821. this.cpl_changed();
  1822. dbg_assert((this.sreg[reg_cs] & 3) === this.cpl);
  1823. dbg_assert((new_eip >>> 0) <= info.effective_limit, "todo: #gp");
  1824. this.update_cs_size(info.size);
  1825. var new_eflags = this.safe_read32s(new_tsr_offset + TSR_EFLAGS);
  1826. if(true /* is call or int */)
  1827. {
  1828. this.safe_write32(tsr_offset + TSR_BACKLINK, selector);
  1829. new_eflags |= flag_nt;
  1830. }
  1831. if(new_eflags & flag_vm)
  1832. {
  1833. throw this.debug.unimpl("task switch to VM mode");
  1834. }
  1835. this.update_eflags(new_eflags);
  1836. if(true /* call or int */)
  1837. {
  1838. this.flags[0] |= flag_nt;
  1839. }
  1840. var new_ldt = this.safe_read16(new_tsr_offset + TSR_LDT);
  1841. this.load_ldt(new_ldt);
  1842. this.reg32s[reg_eax] = this.safe_read32s(new_tsr_offset + TSR_EAX);
  1843. this.reg32s[reg_ecx] = this.safe_read32s(new_tsr_offset + TSR_ECX);
  1844. this.reg32s[reg_edx] = this.safe_read32s(new_tsr_offset + TSR_EDX);
  1845. this.reg32s[reg_ebx] = this.safe_read32s(new_tsr_offset + TSR_EBX);
  1846. this.reg32s[reg_esp] = this.safe_read32s(new_tsr_offset + TSR_ESP);
  1847. this.reg32s[reg_ebp] = this.safe_read32s(new_tsr_offset + TSR_EBP);
  1848. this.reg32s[reg_esi] = this.safe_read32s(new_tsr_offset + TSR_ESI);
  1849. this.reg32s[reg_edi] = this.safe_read32s(new_tsr_offset + TSR_EDI);
  1850. if(
  1851. !this.switch_seg(reg_es, this.safe_read16(new_tsr_offset + TSR_ES)) ||
  1852. !this.switch_seg(reg_ss, this.safe_read16(new_tsr_offset + TSR_SS)) ||
  1853. !this.switch_seg(reg_ds, this.safe_read16(new_tsr_offset + TSR_DS)) ||
  1854. !this.switch_seg(reg_fs, this.safe_read16(new_tsr_offset + TSR_FS)) ||
  1855. !this.switch_seg(reg_gs, this.safe_read16(new_tsr_offset + TSR_GS))
  1856. )
  1857. {
  1858. // XXX: Should be checked before side effects
  1859. dbg_assert(false);
  1860. }
  1861. this.instruction_pointer[0] = this.get_seg(reg_cs) + new_eip | 0;
  1862. this.segment_offsets[reg_tr] = descriptor.base;
  1863. this.segment_limits[reg_tr] = descriptor.effective_limit;
  1864. this.sreg[reg_tr] = selector;
  1865. this.cr[3] = new_cr3;
  1866. dbg_assert((this.cr[3] & 0xFFF) === 0);
  1867. this.clear_tlb();
  1868. this.cr[0] |= CR0_TS;
  1869. if(has_error_code !== false)
  1870. {
  1871. if(tss_is_16)
  1872. {
  1873. this.push16(error_code & 0xFFFF);
  1874. }
  1875. else
  1876. {
  1877. this.push32(error_code);
  1878. }
  1879. }
  1880. };
  1881. CPU.prototype.hlt_op = function()
  1882. {
  1883. if(this.cpl[0])
  1884. {
  1885. dbg_log("#gp hlt with cpl != 0", LOG_CPU);
  1886. this.trigger_gp(0);
  1887. return;
  1888. }
  1889. if((this.get_eflags_no_arith() & flag_interrupt) === 0)
  1890. {
  1891. // execution can never resume (until NMIs are supported)
  1892. this.bus.send("cpu-event-halt");
  1893. }
  1894. // get out of here and into hlt_loop
  1895. this.in_hlt[0] = +true;
  1896. // Try an hlt loop right now: This will run timer interrupts, and if one is
  1897. // due it will immediately call call_interrupt_vector and continue
  1898. // execution without an unnecessary cycle through do_run
  1899. this.hlt_loop();
  1900. };
  1901. CPU.prototype.undefined_instruction = function()
  1902. {
  1903. dbg_assert(false, "Possible fault: undefined instruction");
  1904. this.trigger_ud();
  1905. };
  1906. CPU.prototype.unimplemented_sse = function()
  1907. {
  1908. const opcode = this.safe_read32s(this.previous_ip[0]);
  1909. console.log("No SSE: " + h(opcode & 0xFF) + " " + h(opcode >> 8 & 0xFF) + " " + h(opcode >> 16 & 0xFF), LOG_CPU);
  1910. dbg_assert(false);
  1911. this.trigger_ud();
  1912. };
  1913. CPU.prototype.handle_irqs = function()
  1914. {
  1915. //dbg_assert(this.prefixes[0] === 0);
  1916. if(this.get_eflags_no_arith() & flag_interrupt)
  1917. {
  1918. this.pic_acknowledge();
  1919. }
  1920. };
  1921. CPU.prototype.pic_acknowledge = function()
  1922. {
  1923. dbg_assert(this.get_eflags_no_arith() & flag_interrupt);
  1924. if(this.devices.pic)
  1925. {
  1926. this.devices.pic.acknowledge_irq();
  1927. }
  1928. if(this.devices.apic)
  1929. {
  1930. this.devices.apic.acknowledge_irq();
  1931. }
  1932. };
  1933. CPU.prototype.device_raise_irq = function(i)
  1934. {
  1935. dbg_assert(arguments.length === 1);
  1936. if(this.devices.pic)
  1937. {
  1938. this.devices.pic.set_irq(i);
  1939. }
  1940. if(this.devices.ioapic)
  1941. {
  1942. this.devices.ioapic.set_irq(i);
  1943. }
  1944. };
  1945. CPU.prototype.device_lower_irq = function(i)
  1946. {
  1947. if(this.devices.pic)
  1948. {
  1949. this.devices.pic.clear_irq(i);
  1950. }
  1951. if(this.devices.ioapic)
  1952. {
  1953. this.devices.ioapic.clear_irq(i);
  1954. }
  1955. };
  1956. CPU.prototype.cpuid = function()
  1957. {
  1958. // cpuid
  1959. // TODO: Fill in with less bogus values
  1960. // http://lxr.linux.no/linux+%2a/arch/x86/include/asm/cpufeature.h
  1961. // http://www.sandpile.org/x86/cpuid.htm
  1962. var eax = 0;
  1963. var ecx = 0;
  1964. var edx = 0;
  1965. var ebx = 0;
  1966. const winnt_fix = false;
  1967. const level = this.reg32s[reg_eax];
  1968. switch(level)
  1969. {
  1970. case 0:
  1971. // maximum supported level
  1972. if(winnt_fix)
  1973. {
  1974. eax = 2;
  1975. }
  1976. else
  1977. {
  1978. eax = 0x16;
  1979. }
  1980. ebx = 0x756E6547|0; // Genu
  1981. edx = 0x49656E69|0; // ineI
  1982. ecx = 0x6C65746E|0; // ntel
  1983. break;
  1984. case 1:
  1985. // pentium
  1986. eax = 3 | 6 << 4 | 15 << 8;
  1987. ebx = 1 << 16 | 8 << 8; // cpu count, clflush size
  1988. ecx = 1 << 23 | 1 << 30; // popcnt, rdrand
  1989. var vme = 0 << 1;
  1990. if(VMWARE_HYPERVISOR_PORT) ecx |= 1 << 31; // hypervisor
  1991. edx = (true /* have fpu */ ? 1 : 0) | // fpu
  1992. vme | 1 << 3 | 1 << 4 | 1 << 5 | // vme, pse, tsc, msr
  1993. 1 << 8 | 1 << 11 | 1 << 13 | 1 << 15 | // cx8, sep, pge, cmov
  1994. 1 << 23 | 1 << 24 | 1 << 25 | 1 << 26; // mmx, fxsr, sse1, sse2
  1995. if(ENABLE_ACPI && this.apic_enabled)
  1996. {
  1997. edx |= 1 << 9; // apic
  1998. }
  1999. break;
  2000. case 2:
  2001. // Taken from http://siyobik.info.gf/main/reference/instruction/CPUID
  2002. eax = 0x665B5001|0;
  2003. ebx = 0;
  2004. ecx = 0;
  2005. edx = 0x007A7000;
  2006. break;
  2007. case 4:
  2008. // from my local machine
  2009. switch(this.reg32s[reg_ecx])
  2010. {
  2011. case 0:
  2012. eax = 0x00000121;
  2013. ebx = 0x01c0003f;
  2014. ecx = 0x0000003f;
  2015. edx = 0x00000001;
  2016. break;
  2017. case 1:
  2018. eax = 0x00000122;
  2019. ebx = 0x01c0003f;
  2020. ecx = 0x0000003f;
  2021. edx = 0x00000001;
  2022. break;
  2023. case 2:
  2024. eax = 0x00000143;
  2025. ebx = 0x05c0003f;
  2026. ecx = 0x00000fff;
  2027. edx = 0x00000001;
  2028. break;
  2029. }
  2030. break;
  2031. case 5:
  2032. // from my local machine
  2033. eax = 0x40;
  2034. ebx = 0x40;
  2035. ecx = 3;
  2036. edx = 0x00142120;
  2037. break;
  2038. case 7:
  2039. eax = 0; // maximum supported sub-level
  2040. ebx = 1 << 9; // enhanced REP MOVSB/STOSB
  2041. ecx = 0;
  2042. edx = 0;
  2043. break;
  2044. case 0x80000000|0:
  2045. // maximum supported extended level
  2046. eax = 5;
  2047. // other registers are reserved
  2048. break;
  2049. case 0x40000000|0: // hypervisor
  2050. if(VMWARE_HYPERVISOR_PORT)
  2051. {
  2052. // h("Ware".split("").reduce((a, c, i) => a | c.charCodeAt(0) << i * 8, 0))
  2053. ebx = 0x61774D56|0; // VMwa
  2054. ecx = 0x4D566572|0; // reVM
  2055. edx = 0x65726177|0; // ware
  2056. }
  2057. break;
  2058. case 0x15:
  2059. eax = 1; // denominator
  2060. ebx = 1; // numerator
  2061. ecx = TSC_RATE * 1000; // core crystal clock frequency in Hz
  2062. // (TSC frequency = core crystal clock frequency * EBX/EAX)
  2063. break;
  2064. case 0x16:
  2065. eax = Math.floor(TSC_RATE / 1000); // core base frequency in MHz
  2066. ebx = Math.floor(TSC_RATE / 1000); // core maximum frequency in MHz
  2067. ecx = 10; // bus (reference) frequency in MHz
  2068. break;
  2069. default:
  2070. dbg_log("cpuid: unimplemented eax: " + h(this.reg32[reg_eax]), LOG_CPU);
  2071. }
  2072. if(level === 4)
  2073. {
  2074. dbg_log("cpuid: eax=" + h(this.reg32[reg_eax], 8) + " cl=" + h(this.reg8[reg_cl], 2), LOG_CPU);
  2075. }
  2076. else if(level !== 0 && level !== 2 && level !== (0x80000000 | 0))
  2077. {
  2078. dbg_log("cpuid: eax=" + h(this.reg32[reg_eax], 8), LOG_CPU);
  2079. }
  2080. this.reg32s[reg_eax] = eax;
  2081. this.reg32s[reg_ecx] = ecx;
  2082. this.reg32s[reg_edx] = edx;
  2083. this.reg32s[reg_ebx] = ebx;
  2084. };
  2085. CPU.prototype.update_cs_size = function(new_size)
  2086. {
  2087. new_size = Boolean(new_size);
  2088. if(Boolean(this.is_32[0]) !== new_size)
  2089. {
  2090. this.is_32[0] = +new_size;
  2091. this.update_operand_size();
  2092. }
  2093. };
  2094. CPU.prototype.update_operand_size = function() {};
  2095. /**
  2096. * @param {number} selector
  2097. */
  2098. CPU.prototype.lookup_segment_selector = function(selector)
  2099. {
  2100. dbg_assert(typeof selector === "number" && selector >= 0 && selector < 0x10000);
  2101. var is_gdt = (selector & 4) === 0,
  2102. selector_offset = selector & ~7,
  2103. info,
  2104. table_offset,
  2105. table_limit;
  2106. info = {
  2107. rpl: selector & 3,
  2108. from_gdt: is_gdt,
  2109. is_null: false,
  2110. is_valid: true,
  2111. base: 0,
  2112. access: 0,
  2113. flags: 0,
  2114. type: 0,
  2115. dpl: 0,
  2116. is_system: false,
  2117. is_present: false,
  2118. is_executable: false,
  2119. rw_bit: false,
  2120. dc_bit: false,
  2121. size: false,
  2122. is_conforming_executable: false,
  2123. // limit after applying granularity
  2124. effective_limit: 0,
  2125. is_writable: false,
  2126. is_readable: false,
  2127. table_offset: 0,
  2128. raw0: 0,
  2129. raw1: 0,
  2130. };
  2131. if(is_gdt)
  2132. {
  2133. table_offset = this.gdtr_offset[0];
  2134. table_limit = this.gdtr_size[0];
  2135. }
  2136. else
  2137. {
  2138. table_offset = this.segment_offsets[reg_ldtr];
  2139. table_limit = this.segment_limits[reg_ldtr];
  2140. }
  2141. if(is_gdt && selector_offset === 0)
  2142. {
  2143. info.is_null = true;
  2144. return info;
  2145. }
  2146. // limit is the number of entries in the table minus one
  2147. if((selector | 7) > table_limit)
  2148. {
  2149. dbg_log("Selector " + h(selector, 4) + " is outside of the " +
  2150. (is_gdt ? "g" : "l") + "dt limits", LOG_CPU);
  2151. info.is_valid = false;
  2152. return info;
  2153. }
  2154. table_offset = table_offset + selector_offset | 0;
  2155. if(this.cr[0] & CR0_PG)
  2156. {
  2157. table_offset = this.translate_address_system_read(table_offset);
  2158. }
  2159. info.table_offset = table_offset;
  2160. info.base = this.read16(table_offset + 2 | 0) | this.read8(table_offset + 4 | 0) << 16 |
  2161. this.read8(table_offset + 7 | 0) << 24;
  2162. info.access = this.read8(table_offset + 5 | 0);
  2163. info.flags = this.read8(table_offset + 6 | 0) >> 4;
  2164. info.raw0 = this.read32s(table_offset | 0);
  2165. info.raw1 = this.read32s(table_offset + 4 | 0);
  2166. //this.write8(table_offset + 5 | 0, info.access | 1);
  2167. // used if system
  2168. info.type = info.access & 0xF;
  2169. info.dpl = info.access >> 5 & 3;
  2170. info.is_system = (info.access & 0x10) === 0;
  2171. info.is_present = (info.access & 0x80) === 0x80;
  2172. info.is_executable = (info.access & 8) === 8;
  2173. info.rw_bit = (info.access & 2) === 2;
  2174. info.dc_bit = (info.access & 4) === 4;
  2175. info.is_conforming_executable = info.dc_bit && info.is_executable;
  2176. info.size = (info.flags & 4) === 4;
  2177. var limit = this.read16(table_offset) |
  2178. (this.read8(table_offset + 6 | 0) & 0xF) << 16;
  2179. if(info.flags & 8)
  2180. {
  2181. // granularity set
  2182. info.effective_limit = (limit << 12 | 0xFFF) >>> 0;
  2183. }
  2184. else
  2185. {
  2186. info.effective_limit = limit;
  2187. }
  2188. info.is_writable = info.rw_bit && !info.is_executable;
  2189. info.is_readable = info.rw_bit || !info.is_executable;
  2190. return info;
  2191. };
  2192. /**
  2193. * Returns false if changing was aborted due to an exception
  2194. *
  2195. * @param {number} reg
  2196. * @param {number} selector
  2197. */
  2198. CPU.prototype.switch_seg = function(reg, selector)
  2199. {
  2200. dbg_assert(reg >= 0 && reg <= 5);
  2201. dbg_assert(typeof selector === "number" && selector < 0x10000 && selector >= 0);
  2202. if(!this.protected_mode[0] || this.vm86_mode())
  2203. {
  2204. this.sreg[reg] = selector;
  2205. this.segment_is_null[reg] = 0;
  2206. this.segment_offsets[reg] = selector << 4;
  2207. if(reg === reg_ss)
  2208. {
  2209. this.stack_size_32[0] = +false;
  2210. }
  2211. return true;
  2212. }
  2213. var info = this.lookup_segment_selector(selector);
  2214. if(reg === reg_ss)
  2215. {
  2216. if(info.is_null)
  2217. {
  2218. dbg_log("#GP for loading 0 in SS sel=" + h(selector, 4), LOG_CPU);
  2219. dbg_trace(LOG_CPU);
  2220. this.trigger_gp(0);
  2221. return false;
  2222. }
  2223. if(!info.is_valid ||
  2224. info.is_system ||
  2225. info.rpl !== this.cpl[0] ||
  2226. !info.is_writable ||
  2227. info.dpl !== this.cpl[0])
  2228. {
  2229. dbg_log("#GP for loading invalid in SS sel=" + h(selector, 4), LOG_CPU);
  2230. dbg_trace(LOG_CPU);
  2231. this.trigger_gp(selector & ~3);
  2232. return false;
  2233. }
  2234. if(!info.is_present)
  2235. {
  2236. dbg_log("#SS for loading non-present in SS sel=" + h(selector, 4), LOG_CPU);
  2237. dbg_trace(LOG_CPU);
  2238. this.trigger_ss(selector & ~3);
  2239. return false;
  2240. }
  2241. this.stack_size_32[0] = info.size;
  2242. }
  2243. else if(reg === reg_cs)
  2244. {
  2245. // handled by switch_cs_real_mode, far_return or far_jump
  2246. dbg_assert(false);
  2247. }
  2248. else
  2249. {
  2250. // es, ds, fs, gs
  2251. if(info.is_null)
  2252. {
  2253. //dbg_log("0 loaded in seg=" + reg + " sel=" + h(selector, 4), LOG_CPU);
  2254. //dbg_trace(LOG_CPU);
  2255. this.sreg[reg] = selector;
  2256. this.segment_is_null[reg] = 1;
  2257. return true;
  2258. }
  2259. if(!info.is_valid ||
  2260. info.is_system ||
  2261. !info.is_readable ||
  2262. (!info.is_conforming_executable &&
  2263. (info.rpl > info.dpl || this.cpl[0] > info.dpl))
  2264. ) {
  2265. dbg_log("#GP for loading invalid in seg " + reg + " sel=" + h(selector, 4), LOG_CPU);
  2266. this.debug.dump_state();
  2267. this.debug.dump_regs();
  2268. dbg_trace(LOG_CPU);
  2269. this.trigger_gp(selector & ~3);
  2270. return false;
  2271. }
  2272. if(!info.is_present)
  2273. {
  2274. dbg_log("#NP for loading not-present in seg " + reg + " sel=" + h(selector, 4), LOG_CPU);
  2275. dbg_trace(LOG_CPU);
  2276. this.trigger_np(selector & ~3);
  2277. return false;
  2278. }
  2279. }
  2280. this.segment_is_null[reg] = 0;
  2281. this.segment_limits[reg] = info.effective_limit;
  2282. //this.segment_infos[reg] = 0; // TODO
  2283. this.segment_offsets[reg] = info.base;
  2284. this.sreg[reg] = selector;
  2285. return true;
  2286. };
  2287. CPU.prototype.load_tr = function(selector)
  2288. {
  2289. var info = this.lookup_segment_selector(selector);
  2290. dbg_assert(info.is_valid);
  2291. //dbg_log("load tr: " + h(selector, 4) + " offset=" + h(info.base >>> 0, 8) + " limit=" + h(info.effective_limit >>> 0, 8), LOG_CPU);
  2292. if(!info.from_gdt)
  2293. {
  2294. throw this.debug.unimpl("TR can only be loaded from GDT");
  2295. }
  2296. if(info.is_null)
  2297. {
  2298. dbg_log("#GP(0) | tried to load null selector (ltr)");
  2299. throw this.debug.unimpl("#GP handler");
  2300. }
  2301. if(!info.is_system)
  2302. {
  2303. dbg_log("#GP | ltr: not a system entry");
  2304. throw this.debug.unimpl("#GP handler (happens when running kvm-unit-test without ACPI)");
  2305. }
  2306. if(info.type !== 9 && info.type !== 1)
  2307. {
  2308. // 0xB: busy 386 TSS (GP)
  2309. // 0x9: 386 TSS
  2310. // 0x3: busy 286 TSS (GP)
  2311. // 0x1: 286 TSS (??)
  2312. dbg_log("#GP | ltr: invalid type (type = " + h(info.type) + ")");
  2313. throw this.debug.unimpl("#GP handler");
  2314. }
  2315. if(!info.is_present)
  2316. {
  2317. dbg_log("#NT | present bit not set (ltr)");
  2318. throw this.debug.unimpl("#NT handler");
  2319. }
  2320. this.tss_size_32[0] = info.type === 9;
  2321. this.segment_offsets[reg_tr] = info.base;
  2322. this.segment_limits[reg_tr] = info.effective_limit;
  2323. this.sreg[reg_tr] = selector;
  2324. // Mark task as busy
  2325. this.write8(info.table_offset + 5 | 0, this.read8(info.table_offset + 5 | 0) | 2);
  2326. //dbg_log("tsr at " + h(info.base) + "; (" + info.effective_limit + " bytes)");
  2327. };
  2328. CPU.prototype.load_ldt = function(selector)
  2329. {
  2330. var info = this.lookup_segment_selector(selector);
  2331. if(info.is_null)
  2332. {
  2333. // invalid
  2334. this.segment_offsets[reg_ldtr] = 0;
  2335. this.segment_limits[reg_ldtr] = 0;
  2336. return;
  2337. }
  2338. dbg_assert(info.is_valid);
  2339. if(!info.from_gdt)
  2340. {
  2341. throw this.debug.unimpl("LDTR can only be loaded from GDT");
  2342. }
  2343. if(!info.is_present)
  2344. {
  2345. dbg_log("lldt: present bit not set");
  2346. throw this.debug.unimpl("#GP handler");
  2347. }
  2348. if(!info.is_system)
  2349. {
  2350. dbg_log("lldt: not a system entry");
  2351. throw this.debug.unimpl("#GP handler");
  2352. }
  2353. if(info.type !== 2)
  2354. {
  2355. dbg_log("lldt: invalid type (" + info.type + ")");
  2356. throw this.debug.unimpl("#GP handler");
  2357. }
  2358. this.segment_offsets[reg_ldtr] = info.base;
  2359. this.segment_limits[reg_ldtr] = info.effective_limit;
  2360. this.sreg[reg_ldtr] = selector;
  2361. //dbg_log("ldt at " + h(info.base >>> 0) + "; (" + info.effective_limit + " bytes)", LOG_CPU);
  2362. };
  2363. CPU.prototype.arpl = function(seg, r16)
  2364. {
  2365. this.flags_changed[0] &= ~flag_zero;
  2366. if((seg & 3) < (r16 & 3))
  2367. {
  2368. this.flags[0] |= flag_zero;
  2369. return seg & ~3 | r16 & 3;
  2370. }
  2371. else
  2372. {
  2373. this.flags[0] &= ~flag_zero;
  2374. return seg;
  2375. }
  2376. };
  2377. CPU.prototype.lar = function(selector, original)
  2378. {
  2379. if(CPU_LOG_VERBOSE)
  2380. {
  2381. dbg_log("lar sel=" + h(selector, 4), LOG_CPU);
  2382. }
  2383. /** @const */
  2384. var LAR_INVALID_TYPE = 1 << 0 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 0xA |
  2385. 1 << 0xD | 1 << 0xE | 1 << 0xF;
  2386. var info = this.lookup_segment_selector(selector);
  2387. this.flags_changed[0] &= ~flag_zero;
  2388. var dpl_bad = info.dpl < this.cpl[0] || info.dpl < info.rpl;
  2389. if(info.is_null || !info.is_valid ||
  2390. (info.is_system ? (LAR_INVALID_TYPE >> info.type & 1) || dpl_bad :
  2391. !info.is_conforming_executable && dpl_bad)
  2392. ) {
  2393. this.flags[0] &= ~flag_zero;
  2394. dbg_log("lar: invalid selector=" + h(selector, 4) + " is_null=" + info.is_null, LOG_CPU);
  2395. return original;
  2396. }
  2397. else
  2398. {
  2399. this.flags[0] |= flag_zero;
  2400. return info.raw1 & 0x00FFFF00;
  2401. }
  2402. };
  2403. CPU.prototype.lsl = function(selector, original)
  2404. {
  2405. if(CPU_LOG_VERBOSE)
  2406. {
  2407. dbg_log("lsl sel=" + h(selector, 4), LOG_CPU);
  2408. }
  2409. /** @const */
  2410. var LSL_INVALID_TYPE = 1 << 0 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 |
  2411. 1 << 0xA | 1 << 0xC | 1 << 0xD | 1 << 0xE | 1 << 0xF;
  2412. var info = this.lookup_segment_selector(selector);
  2413. this.flags_changed[0] &= ~flag_zero;
  2414. var dpl_bad = info.dpl < this.cpl[0] || info.dpl < info.rpl;
  2415. if(info.is_null || !info.is_valid ||
  2416. (info.is_system ? (LSL_INVALID_TYPE >> info.type & 1) || dpl_bad :
  2417. !info.is_conforming_executable && dpl_bad)
  2418. ) {
  2419. this.flags[0] &= ~flag_zero;
  2420. dbg_log("lsl: invalid selector=" + h(selector, 4) + " is_null=" + info.is_null, LOG_CPU);
  2421. return original;
  2422. }
  2423. else
  2424. {
  2425. this.flags[0] |= flag_zero;
  2426. return info.effective_limit | 0;
  2427. }
  2428. };
  2429. CPU.prototype.verr = function(selector)
  2430. {
  2431. var info = this.lookup_segment_selector(selector);
  2432. this.flags_changed[0] &= ~flag_zero;
  2433. if(info.is_null || !info.is_valid || info.is_system || !info.is_readable ||
  2434. (!info.is_conforming_executable && (info.dpl < this.cpl[0] || info.dpl < info.rpl)))
  2435. {
  2436. dbg_log("verr -> invalid. selector=" + h(selector, 4), LOG_CPU);
  2437. this.flags[0] &= ~flag_zero;
  2438. }
  2439. else
  2440. {
  2441. dbg_log("verr -> valid. selector=" + h(selector, 4), LOG_CPU);
  2442. this.flags[0] |= flag_zero;
  2443. }
  2444. };
  2445. CPU.prototype.verw = function(selector)
  2446. {
  2447. var info = this.lookup_segment_selector(selector);
  2448. this.flags_changed[0] &= ~flag_zero;
  2449. if(info.is_null || !info.is_valid || info.is_system || !info.is_writable ||
  2450. info.dpl < this.cpl[0] || info.dpl < info.rpl)
  2451. {
  2452. dbg_log("verw invalid " + " " + h(selector) + " " + info.is_null + " " +
  2453. !info.is_valid + " " + info.is_system + " " + !info.is_writable + " " +
  2454. (info.dpl < this.cpl[0]) + " " + (info.dpl < info.rpl) + " " + LOG_CPU);
  2455. this.flags[0] &= ~flag_zero;
  2456. }
  2457. else
  2458. {
  2459. this.flags[0] |= flag_zero;
  2460. }
  2461. };
  2462. CPU.prototype.is_osize_32 = function()
  2463. {
  2464. return Boolean(this.is_32[0]) !== ((this.prefixes[0] & PREFIX_MASK_OPSIZE) === PREFIX_MASK_OPSIZE);
  2465. };
  2466. CPU.prototype.is_asize_32 = function()
  2467. {
  2468. return Boolean(this.is_32[0]) !== ((this.prefixes[0] & PREFIX_MASK_ADDRSIZE) === PREFIX_MASK_ADDRSIZE);
  2469. };
  2470. CPU.prototype.lss16 = function(addr, reg, seg)
  2471. {
  2472. var new_reg = this.safe_read16(addr),
  2473. new_seg = this.safe_read16(addr + 2 | 0);
  2474. if(!this.switch_seg(seg, new_seg)) return;
  2475. this.reg16[reg] = new_reg;
  2476. };
  2477. CPU.prototype.lss32 = function(addr, reg, seg)
  2478. {
  2479. var new_reg = this.safe_read32s(addr),
  2480. new_seg = this.safe_read16(addr + 4 | 0);
  2481. if(!this.switch_seg(seg, new_seg)) return;
  2482. this.reg32s[reg] = new_reg;
  2483. };
  2484. CPU.prototype.enter16 = function(size, nesting_level)
  2485. {
  2486. nesting_level &= 31;
  2487. if(nesting_level) dbg_log("enter16 stack=" + (this.stack_size_32[0] ? 32 : 16) + " size=" + size + " nest=" + nesting_level, LOG_CPU);
  2488. var ss_mask = this.stack_size_32[0] ? -1 : 0xFFFF;
  2489. var ss = this.get_seg(reg_ss);
  2490. var frame_temp = this.reg32s[reg_esp] - 2;
  2491. if(nesting_level > 0)
  2492. {
  2493. var tmp_ebp = this.reg32s[reg_ebp];
  2494. for(var i = 1; i < nesting_level; i++)
  2495. {
  2496. tmp_ebp -= 2;
  2497. this.push16(this.safe_read16(ss + (tmp_ebp & ss_mask) | 0));
  2498. }
  2499. this.push16(frame_temp);
  2500. }
  2501. // check if write to final stack pointer would case a page fault
  2502. if(!this.writable_or_pagefault(ss + (frame_temp - size & ss_mask), 2))
  2503. {
  2504. return;
  2505. }
  2506. this.safe_write16(ss + (frame_temp & ss_mask) | 0, this.reg16[reg_bp]);
  2507. this.reg16[reg_bp] = frame_temp;
  2508. this.adjust_stack_reg(-size - 2);
  2509. };
  2510. CPU.prototype.enter32 = function(size, nesting_level)
  2511. {
  2512. nesting_level &= 31;
  2513. if(nesting_level) dbg_log("enter32 stack=" + (this.stack_size_32[0] ? 32 : 16) + " size=" + size + " nest=" + nesting_level, LOG_CPU);
  2514. var ss_mask = this.stack_size_32[0] ? -1 : 0xFFFF;
  2515. var ss = this.get_seg(reg_ss);
  2516. var frame_temp = this.reg32s[reg_esp] - 4;
  2517. if(nesting_level > 0)
  2518. {
  2519. var tmp_ebp = this.reg32s[reg_ebp];
  2520. for(var i = 1; i < nesting_level; i++)
  2521. {
  2522. tmp_ebp -= 4;
  2523. this.push32(this.safe_read32s(ss + (tmp_ebp & ss_mask) | 0));
  2524. }
  2525. this.push32(frame_temp);
  2526. }
  2527. // check if write to final stack pointer would case a page fault
  2528. if(!this.writable_or_pagefault(ss + (frame_temp - size & ss_mask), 4))
  2529. {
  2530. return;
  2531. }
  2532. this.safe_write32(ss + (frame_temp & ss_mask) | 0, this.reg32s[reg_ebp]);
  2533. this.reg32s[reg_ebp] = frame_temp;
  2534. this.adjust_stack_reg(-size - 4);
  2535. };
  2536. CPU.prototype.bswap = function(reg)
  2537. {
  2538. var temp = this.reg32s[reg];
  2539. this.reg32s[reg] = temp >>> 24 | temp << 24 | (temp >> 8 & 0xFF00) | (temp << 8 & 0xFF0000);
  2540. };
  2541. // Closure Compiler's way of exporting
  2542. if(typeof window !== "undefined")
  2543. {
  2544. window["CPU"] = CPU;
  2545. }
  2546. else if(typeof module !== "undefined" && typeof module.exports !== "undefined")
  2547. {
  2548. module.exports["CPU"] = CPU;
  2549. }
  2550. else if(typeof importScripts === "function")
  2551. {
  2552. self["CPU"] = CPU;
  2553. }