cpu.js 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747
  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, codegen, coverage_logger)
  10. {
  11. this.wm = wm;
  12. this.codegen = codegen;
  13. this.coverage_logger = coverage_logger;
  14. this.wasm_patch(wm);
  15. this.create_jit_imports();
  16. this.memory_size = new Uint32Array(wm.memory.buffer, 812, 1);
  17. // Note: Currently unused (degrades performance and not required by any OS
  18. // that we support)
  19. this.a20_enabled = new Int32Array(wm.memory.buffer, 552, 1);
  20. this.a20_enabled[0] = +true;
  21. this.mem_page_infos = undefined;
  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 = new Uint8Array(wm.memory.buffer, 724, 8);
  26. this.segment_offsets = new Int32Array(wm.memory.buffer, 736, 8);
  27. this.segment_limits = new Uint32Array(wm.memory.buffer, 768, 8);
  28. //this.segment_infos = [];
  29. /**
  30. * Wheter or not in protected mode
  31. */
  32. this.protected_mode = new Int32Array(wm.memory.buffer, 800, 1);
  33. this.idtr_size = new Int32Array(wm.memory.buffer, 564, 1);
  34. this.idtr_offset = new Int32Array(wm.memory.buffer, 568, 1);
  35. /**
  36. * global descriptor table register
  37. */
  38. this.gdtr_size = new Int32Array(wm.memory.buffer, 572, 1);
  39. this.gdtr_offset = new Int32Array(wm.memory.buffer, 576, 1);
  40. this.tss_size_32 = false;
  41. /*
  42. * whether or not a page fault occured
  43. */
  44. this.page_fault = new Uint32Array(wm.memory.buffer, 540, 8);
  45. this.cr = new Int32Array(wm.memory.buffer, 580, 8);
  46. /** @type {number} */
  47. this.cr[0] = 0;
  48. /** @type {number} */
  49. this.cr[2] = 0;
  50. /** @type {number} */
  51. this.cr[3] = 0;
  52. /** @type {number} */
  53. this.cr[4] = 0;
  54. // current privilege level
  55. this.cpl = new Int32Array(wm.memory.buffer, 612, 1);
  56. // if false, pages are 4 KiB, else 4 Mib
  57. this.page_size_extensions = new Int32Array(wm.memory.buffer, 616, 1);
  58. // current operand/address size
  59. this.is_32 = new Int32Array(wm.memory.buffer, 804, 1);
  60. this.stack_size_32 = new Int32Array(wm.memory.buffer, 808, 1);
  61. /**
  62. * Was the last instruction a hlt?
  63. * @type {boolean}
  64. */
  65. this.in_hlt = false;
  66. this.last_virt_eip = new Int32Array(wm.memory.buffer, 620, 1);
  67. this.eip_phys = new Int32Array(wm.memory.buffer, 624, 1);
  68. this.last_virt_esp = new Int32Array(wm.memory.buffer, 628, 1);
  69. this.esp_phys = new Int32Array(wm.memory.buffer, 632, 1);
  70. this.sysenter_cs = new Int32Array(wm.memory.buffer, 636, 1);
  71. this.sysenter_esp = new Int32Array(wm.memory.buffer, 640, 1);
  72. this.sysenter_eip = new Int32Array(wm.memory.buffer, 644, 1);
  73. this.prefixes = new Int32Array(wm.memory.buffer, 648, 1);
  74. this.flags = new Int32Array(wm.memory.buffer, 536, 1);
  75. /**
  76. * bitmap of flags which are not updated in the flags variable
  77. * changed by arithmetic instructions, so only relevant to arithmetic flags
  78. */
  79. this.flags_changed = new Int32Array(wm.memory.buffer, 532, 1);
  80. /**
  81. * the last 2 operators and the result and size of the last arithmetic operation
  82. */
  83. this.last_op1 = new Int32Array(wm.memory.buffer, 512, 1);
  84. this.last_op2 = new Int32Array(wm.memory.buffer, 516, 1);
  85. this.last_op_size = new Int32Array(wm.memory.buffer, 520, 1);
  86. this.last_add_result = new Int32Array(wm.memory.buffer, 524, 1);
  87. this.last_result = new Int32Array(wm.memory.buffer, 528, 1);
  88. this.current_tsc = new Uint32Array(wm.memory.buffer, 956, 2); // 64 bit
  89. /** @type {!Object} */
  90. this.devices = {};
  91. // paging enabled
  92. this.paging = new Uint8Array(wm.memory.buffer, 820, 1);
  93. this.instruction_pointer = new Int32Array(wm.memory.buffer, 556, 1);
  94. this.previous_ip = new Int32Array(wm.memory.buffer, 560, 1);
  95. this.apic_enabled = true;
  96. // managed in io.js
  97. /** @const */ this.memory_map_read8 = [];
  98. /** @const */ this.memory_map_write8 = [];
  99. /** @const */ this.memory_map_read32 = [];
  100. /** @const */ this.memory_map_write32 = [];
  101. /**
  102. * @const
  103. * @type {{main: ArrayBuffer, vga: ArrayBuffer}}
  104. */
  105. this.bios = {
  106. main: null,
  107. vga: null,
  108. };
  109. this.timestamp_counter = new Uint32Array(wm.memory.buffer, 664, 1);
  110. // registers
  111. this.reg32s = new Int32Array(wm.memory.buffer, 4, 8);
  112. this.reg32 = new Uint32Array(this.reg32s.buffer, 4, 8);
  113. this.reg16s = new Int16Array(this.reg32s.buffer, 4, 16);
  114. this.reg16 = new Uint16Array(this.reg32s.buffer, 4, 16);
  115. this.reg8s = new Int8Array(this.reg32s.buffer, 4, 32);
  116. this.reg8 = new Uint8Array(this.reg32s.buffer, 4, 32);
  117. // Why no Float80Array :-(
  118. this.fpu_st = new Float64Array(wm.memory.buffer, 968, 8);
  119. this.fpu_stack_empty = new Int32Array(wm.memory.buffer, 816, 1);
  120. this.fpu_stack_empty[0] = 0xff;
  121. this.fpu_stack_ptr = new Uint32Array(wm.memory.buffer, 1032, 1);
  122. this.fpu_stack_ptr[0] = 0;
  123. this.fpu_control_word = new Int32Array(wm.memory.buffer, 1036, 1);
  124. this.fpu_control_word[0] = 0x37F;
  125. this.fpu_status_word = new Int32Array(wm.memory.buffer, 1040, 1);
  126. this.fpu_status_word[0] = 0;
  127. this.fpu_ip = new Int32Array(wm.memory.buffer, 1048, 1);
  128. this.fpu_ip[0] = 0;
  129. this.fpu_ip_selector = new Int32Array(wm.memory.buffer, 1052, 1);
  130. this.fpu_ip_selector[0] = 0;
  131. this.fpu_opcode = new Int32Array(wm.memory.buffer, 1044, 1);
  132. this.fpu_opcode[0] = 0;
  133. this.fpu_dp = new Int32Array(wm.memory.buffer, 1056, 1);
  134. this.fpu_dp[0] = 0;
  135. this.fpu_dp_selector = new Int32Array(wm.memory.buffer, 1060, 1);
  136. this.fpu_dp_selector[0] = 0;
  137. // mm0-mm7 split up into 32 bit pairs
  138. this.reg_mmxs = new Int32Array(wm.memory.buffer, 1064, 16);
  139. this.reg_mmx = new Uint32Array(this.reg_mmxs.buffer, 1064, 16);
  140. this.reg_mmx8s = new Int8Array(this.reg_mmxs.buffer, 1064, 64);
  141. this.reg_mmx8 = new Uint8Array(this.reg_mmxs.buffer, 1064, 64);
  142. this.reg_xmm32s = new Int32Array(wm.memory.buffer, 828, 8 * 4);
  143. this.mxcsr = new Int32Array(wm.memory.buffer, 824, 1);
  144. // segment registers, tr and ldtr
  145. this.sreg = new Uint16Array(wm.memory.buffer, 668, 8);
  146. // debug registers
  147. this.dreg = new Int32Array(wm.memory.buffer, 684, 8);
  148. this.fw_value = new Int32Array(wm.memory.buffer, 720, 1);
  149. this.io = undefined;
  150. this.bus = bus;
  151. this.update_operand_size();
  152. wm.exports["_set_tsc"](0, 0);
  153. this.debug_init();
  154. //Object.seal(this);
  155. }
  156. CPU.prototype.create_jit_imports = function()
  157. {
  158. // Set this.jit_imports as generated WASM modules will expect
  159. /** @constructor */
  160. function JITImports()
  161. {
  162. // put all imports that change here
  163. this["next_block_branched"] = null;
  164. this["next_block_not_branched"] = null;
  165. }
  166. // put all imports that don't change on the prototype
  167. JITImports.prototype["m"] = this.wm.memory;
  168. const exports = this.wm.instance.exports;
  169. for(let name of Object.keys(exports))
  170. {
  171. if(name[0] !== "_")
  172. {
  173. continue;
  174. }
  175. JITImports.prototype[name.slice(1)] = exports[name];
  176. }
  177. this.jit_imports = new JITImports();
  178. };
  179. CPU.prototype.set_jit_import = function(function_index, wasm_index)
  180. {
  181. const fn = this.wm.imports["env"].table.get(wasm_index);
  182. dbg_assert(fn);
  183. switch(function_index)
  184. {
  185. case JIT_NEXT_BLOCK_BRANCHED_IDX:
  186. var function_name = JIT_NEXT_BLOCK_BRANCHED;
  187. break;
  188. case JIT_NEXT_BLOCK_NOT_BRANCHED_IDX:
  189. var function_name = JIT_NEXT_BLOCK_NOT_BRANCHED;
  190. break;
  191. }
  192. dbg_assert(function_name);
  193. this.jit_imports[function_name] = fn;
  194. };
  195. CPU.prototype.wasm_patch = function(wm)
  196. {
  197. this.getiopl = this.wm.exports["_getiopl"];
  198. this.vm86_mode = this.wm.exports["_vm86_mode"];
  199. this.get_eflags = this.wm.exports["_get_eflags"];
  200. this.update_eflags = this.wm.exports["_update_eflags"];
  201. this.trigger_gp = this.wm.exports["_trigger_gp"];
  202. this.trigger_ud = this.wm.exports["_trigger_ud"];
  203. this.trigger_np = this.wm.exports["_trigger_np"];
  204. this.trigger_ss = this.wm.exports["_trigger_ss"];
  205. this.do_many_cycles_unsafe = this.wm.exports["_do_many_cycles_unsafe"];
  206. this.cycle_internal = this.wm.exports["_cycle_internal"];
  207. this.read8 = this.wm.exports["_read8"];
  208. this.read16 = this.wm.exports["_read16"];
  209. this.read32s = this.wm.exports["_read32s"];
  210. this.write8 = this.wm.exports["_write8"];
  211. this.write16 = this.wm.exports["_write16"];
  212. this.write32 = this.wm.exports["_write32"];
  213. this.in_mapped_range = this.wm.exports["_in_mapped_range"];
  214. this.push16 = this.wm.exports["_push16"];
  215. this.push32 = this.wm.exports["_push32"];
  216. this.pop16 = this.wm.exports["_pop16"];
  217. this.pop32s = this.wm.exports["_pop32s"];
  218. this.set_stack_reg = this.wm.exports["_set_stack_reg"];
  219. this.translate_address_read = this.wm.exports["_translate_address_read"];
  220. this.translate_address_system_read = this.wm.exports["_translate_address_system_read"];
  221. this.translate_address_system_write = this.wm.exports["_translate_address_system_write"];
  222. this.get_seg = this.wm.exports["_get_seg"];
  223. this.adjust_stack_reg = this.wm.exports["_adjust_stack_reg"];
  224. this.get_real_eip = this.wm.exports["_get_real_eip"];
  225. this.get_stack_pointer = this.wm.exports["_get_stack_pointer"];
  226. this.writable_or_pagefault = this.wm.exports["_writable_or_pagefault"];
  227. this.safe_write32 = this.wm.exports["_safe_write32"];
  228. this.safe_read32s = this.wm.exports["_safe_read32s"];
  229. this.safe_write16 = this.wm.exports["_safe_write16"];
  230. this.safe_read16 = this.wm.exports["_safe_read16"];
  231. this.clear_tlb = this.wm.exports["_clear_tlb"];
  232. this.full_clear_tlb = this.wm.exports["_full_clear_tlb"];
  233. };
  234. CPU.prototype.jit_clear_func = function(index)
  235. {
  236. dbg_assert(index >= 0 && index < WASM_TABLE_SIZE);
  237. this.wm.imports.env.table.set(index, null);
  238. };
  239. CPU.prototype.get_state = function()
  240. {
  241. var state = [];
  242. state[0] = this.memory_size[0];
  243. state[1] = this.segment_is_null;
  244. state[2] = this.segment_offsets;
  245. state[3] = this.segment_limits;
  246. state[4] = this.protected_mode[0];
  247. state[5] = this.idtr_offset[0];
  248. state[6] = this.idtr_size[0];
  249. state[7] = this.gdtr_offset[0];
  250. state[8] = this.gdtr_size[0];
  251. state[9] = this.page_fault[0];
  252. state[10] = this.cr;
  253. state[11] = this.cpl[0];
  254. state[12] = this.page_size_extensions[0];
  255. state[13] = this.is_32[0];
  256. state[16] = this.stack_size_32[0];
  257. state[17] = this.in_hlt;
  258. state[18] = this.last_virt_eip[0];
  259. state[19] = this.eip_phys[0];
  260. state[20] = this.last_virt_esp[0];
  261. state[21] = this.esp_phys[0];
  262. state[22] = this.sysenter_cs[0];
  263. state[23] = this.sysenter_eip[0];
  264. state[24] = this.sysenter_esp[0];
  265. state[25] = this.prefixes[0];
  266. state[26] = this.flags[0];
  267. state[27] = this.flags_changed[0];
  268. state[28] = this.last_op1[0];
  269. state[29] = this.last_op2[0];
  270. state[30] = this.last_op_size[0];
  271. state[31] = this.last_add_result[0];
  272. state[36] = this.paging[0];
  273. state[37] = this.instruction_pointer[0];
  274. state[38] = this.previous_ip[0];
  275. state[39] = this.reg32s;
  276. state[40] = this.sreg;
  277. state[41] = this.dreg;
  278. state[42] = this.mem8;
  279. this.wm.exports["_store_current_tsc"]();
  280. state[43] = this.current_tsc;
  281. state[45] = this.devices.virtio;
  282. state[46] = this.devices.apic;
  283. state[47] = this.devices.rtc;
  284. state[48] = this.devices.pci;
  285. state[49] = this.devices.dma;
  286. state[50] = this.devices.acpi;
  287. state[51] = this.devices.hpet;
  288. state[52] = this.devices.vga;
  289. state[53] = this.devices.ps2;
  290. state[54] = this.devices.uart;
  291. state[55] = this.devices.fdc;
  292. state[56] = this.devices.cdrom;
  293. state[57] = this.devices.hda;
  294. state[58] = this.devices.pit;
  295. state[59] = this.devices.net;
  296. state[60] = this.devices.pic;
  297. state[61] = this.a20_enabled[0];
  298. state[62] = this.fw_value[0];
  299. state[63] = this.devices.ioapic;
  300. state[64] = this.tss_size_32;
  301. state[65] = this.reg_mmxs;
  302. state[66] = this.reg_xmm32s;
  303. state[67] = this.fpu_st;
  304. state[68] = this.fpu_stack_empty[0];
  305. state[69] = this.fpu_stack_ptr[0];
  306. state[70] = this.fpu_control_word[0];
  307. state[71] = this.fpu_ip[0];
  308. state[72] = this.fpu_ip_selector[0];
  309. state[73] = this.fpu_dp[0];
  310. state[74] = this.fpu_dp_selector[0];
  311. state[75] = this.fpu_opcode[0];
  312. return state;
  313. };
  314. CPU.prototype.set_state = function(state)
  315. {
  316. this.memory_size[0] = state[0];
  317. this.segment_is_null.set(state[1]);
  318. this.segment_offsets.set(state[2]);
  319. this.segment_limits.set(state[3]);
  320. this.protected_mode[0] = state[4];
  321. this.idtr_offset[0] = state[5];
  322. this.idtr_size[0] = state[6];
  323. this.gdtr_offset[0] = state[7];
  324. this.gdtr_size[0] = state[8];
  325. this.page_fault[0] = state[9];
  326. this.cr.set(state[10]);
  327. this.cpl[0] = state[11];
  328. this.page_size_extensions[0] = state[12];
  329. this.is_32[0] = state[13];
  330. this.stack_size_32[0] = state[16];
  331. this.in_hlt = state[17];
  332. this.last_virt_eip[0] = state[18];
  333. this.eip_phys[0] = state[19];
  334. this.last_virt_esp[0] = state[20];
  335. this.esp_phys[0] = state[21];
  336. this.sysenter_cs[0] = state[22];
  337. this.sysenter_eip[0] = state[23];
  338. this.sysenter_esp[0] = state[24];
  339. this.prefixes[0] = state[25];
  340. this.flags[0] = state[26];
  341. this.flags_changed[0] = state[27];
  342. this.last_op1[0] = state[28];
  343. this.last_op2[0] = state[29];
  344. this.last_op_size[0] = state[30];
  345. this.last_add_result[0] = state[31];
  346. this.paging[0] = state[36];
  347. this.instruction_pointer[0] = state[37];
  348. this.previous_ip[0] = state[38];
  349. this.reg32s.set(state[39]);
  350. this.sreg.set(state[40]);
  351. this.dreg.set(state[41]);
  352. this.mem8.set(state[42]);
  353. this.wm.exports["_set_tsc"](state[43][0], state[43][1]);
  354. this.devices.virtio = state[45];
  355. this.devices.apic = state[46];
  356. this.devices.rtc = state[47];
  357. this.devices.pci = state[48];
  358. this.devices.dma = state[49];
  359. this.devices.acpi = state[50];
  360. this.devices.hpet = state[51];
  361. this.devices.vga = state[52];
  362. this.devices.ps2 = state[53];
  363. this.devices.uart = state[54];
  364. this.devices.fdc = state[55];
  365. this.devices.cdrom = state[56];
  366. this.devices.hda = state[57];
  367. this.devices.pit = state[58];
  368. this.devices.net = state[59];
  369. this.devices.pic = state[60];
  370. this.a20_enabled[0] = state[61];
  371. this.fw_value[0] = state[62];
  372. this.devices.ioapic = state[63];
  373. this.tss_size_32 = state[64];
  374. this.reg_mmxs.set(state[65]);
  375. this.reg_xmm32s.set(state[66]);
  376. this.fpu_st.set(state[67]);
  377. this.fpu_stack_empty[0] = state[68];
  378. this.fpu_stack_ptr[0] = state[69];
  379. this.fpu_control_word[0] = state[70];
  380. this.fpu_ip[0] = state[71];
  381. this.fpu_ip_selector[0] = state[72];
  382. this.fpu_dp[0] = state[73];
  383. this.fpu_dp_selector[0] = state[74];
  384. this.fpu_opcode[0] = state[75];
  385. this.full_clear_tlb();
  386. this.update_operand_size();
  387. };
  388. /**
  389. * @return {number} time in ms until this method should becalled again
  390. */
  391. CPU.prototype.main_run = function()
  392. {
  393. if(this.in_hlt)
  394. {
  395. //if(false)
  396. //{
  397. // var _t = this.hlt_loop();
  398. // var t = 0;
  399. //}
  400. //else
  401. //{
  402. var t = this.hlt_loop();
  403. //}
  404. if(this.in_hlt)
  405. {
  406. return t;
  407. }
  408. }
  409. this.do_run();
  410. return 0;
  411. };
  412. CPU.prototype.exception_cleanup = function(e)
  413. {
  414. if(e === MAGIC_CPU_EXCEPTION)
  415. {
  416. // A legit CPU exception (for instance, a page fault happened)
  417. // call_interrupt_vector has already been called at this point,
  418. // so we just need to reset some state
  419. this.page_fault[0] = 0;
  420. // restore state from prefixes
  421. this.prefixes[0] = 0;
  422. }
  423. else
  424. {
  425. console.log(e);
  426. console.log(e.stack);
  427. //var e = new Error(e.message);
  428. //Error.captureStackTrace && Error.captureStackTrace(e);
  429. throw e;
  430. }
  431. };
  432. CPU.prototype.reboot_internal = function()
  433. {
  434. this.reset();
  435. this.load_bios();
  436. throw MAGIC_CPU_EXCEPTION;
  437. };
  438. CPU.prototype.reset = function()
  439. {
  440. this.a20_enabled[0] = +true;
  441. this.segment_is_null.fill(0);
  442. this.segment_limits.fill(0);
  443. //this.segment_infos = new Uint32Array(8);
  444. this.segment_offsets.fill(0);
  445. this.reg32s.fill(0);
  446. this.sreg.fill(0);
  447. this.dreg.fill(0);
  448. for(let i = 0; i < this.reg_mmxs.length; i++)
  449. {
  450. this.reg_mmxs[i] = 0;
  451. }
  452. for(let i = 0; i < this.reg_xmm32s.length; i++)
  453. {
  454. this.reg_xmm32s[i] = 0;
  455. }
  456. this.mxcsr[0] = 0x1F80;
  457. this.full_clear_tlb();
  458. this.protected_mode[0] = +false;
  459. // http://www.sandpile.org/x86/initial.htm
  460. this.idtr_size[0] = 0;
  461. this.idtr_offset[0] = 0;
  462. this.gdtr_size[0] = 0;
  463. this.gdtr_offset[0] = 0;
  464. this.page_fault[0] = 0;
  465. this.cr[0] = 1 << 30 | 1 << 29 | 1 << 4;
  466. this.cr[2] = 0;
  467. this.cr[3] = 0;
  468. this.cr[4] = 0;
  469. this.dreg[6] = 0xFFFF0FF0|0;
  470. this.dreg[7] = 0x400;
  471. this.cpl[0] = 0;
  472. this.paging[0] = 0;
  473. this.page_size_extensions[0] = 0;
  474. this.is_32[0] = +false;
  475. this.stack_size_32[0] = +false;
  476. this.prefixes[0] = 0;
  477. this.last_virt_eip[0] = -1;
  478. this.last_virt_esp[0] = -1;
  479. this.update_operand_size();
  480. this.timestamp_counter[0] = 0;
  481. this.previous_ip[0] = 0;
  482. this.in_hlt = false;
  483. this.sysenter_cs[0] = 0;
  484. this.sysenter_esp[0] = 0;
  485. this.sysenter_eip[0] = 0;
  486. this.flags[0] = flags_default;
  487. this.flags_changed.fill(0);
  488. this.last_result.fill(0);
  489. this.last_add_result.fill(0);
  490. this.last_op1.fill(0);
  491. this.last_op2.fill(0);
  492. this.last_op_size.fill(0);
  493. this.wm.exports["_set_tsc"](0, 0);
  494. this.instruction_pointer[0] = 0xFFFF0;
  495. this.switch_cs_real_mode(0xF000);
  496. this.switch_seg(reg_ss, 0x30);
  497. this.reg16[reg_sp] = 0x100;
  498. if(this.devices.virtio)
  499. {
  500. this.devices.virtio.reset();
  501. }
  502. this.fw_value[0] = 0;
  503. };
  504. CPU.prototype.reset_memory = function()
  505. {
  506. this.mem8.fill(0);
  507. };
  508. /** @export */
  509. CPU.prototype.create_memory = function(size)
  510. {
  511. if(size < 1024 * 1024)
  512. {
  513. size = 1024 * 1024;
  514. }
  515. else if((size | 0) < 0)
  516. {
  517. size = Math.pow(2, 31) - MMAP_BLOCK_SIZE;
  518. }
  519. size = ((size - 1) | (MMAP_BLOCK_SIZE - 1)) + 1 | 0;
  520. dbg_assert((size | 0) > 0);
  521. dbg_assert((size & MMAP_BLOCK_SIZE - 1) === 0);
  522. this.memory_size[0] = size;
  523. var buffer = this.wm.memory.buffer;
  524. this.mem8 = new Uint8Array(buffer, GUEST_MEMORY_START, size);
  525. this.mem16 = new Uint16Array(buffer, GUEST_MEMORY_START, size >> 1);
  526. this.mem32s = new Int32Array(buffer, GUEST_MEMORY_START, size >> 2);
  527. };
  528. CPU.prototype.init = function(settings, device_bus)
  529. {
  530. this.create_memory(typeof settings.memory_size === "number" ?
  531. settings.memory_size : 1024 * 1024 * 64);
  532. this.reset();
  533. if(typeof settings.log_level === "number")
  534. {
  535. // XXX: Shared between all emulator instances
  536. LOG_LEVEL = settings.log_level;
  537. }
  538. var io = new IO(this);
  539. this.io = io;
  540. this.bios.main = settings.bios;
  541. this.bios.vga = settings.vga_bios;
  542. this.load_bios();
  543. var a20_byte = 0;
  544. io.register_read(0xB3, this, function()
  545. {
  546. // seabios smm_relocate_and_restore
  547. dbg_log("port 0xB3 read");
  548. return 0;
  549. });
  550. io.register_read(0x92, this, function()
  551. {
  552. return a20_byte;
  553. });
  554. io.register_write(0x92, this, function(out_byte)
  555. {
  556. a20_byte = out_byte;
  557. });
  558. io.register_read(0x511, this, function()
  559. {
  560. // bios config port (used by seabios and kvm-unit-test)
  561. let result = this.fw_value[0] & 0xFF;
  562. this.fw_value[0] >>>= 8;
  563. return result;
  564. });
  565. io.register_write(0x510, this, undefined, function(value)
  566. {
  567. dbg_log("bios config port, index=" + h(value));
  568. if(value === FW_CFG_SIGNATURE)
  569. {
  570. // We could pretend to be QEMU here to control certain options in
  571. // seabios, but for now this isn't needed
  572. this.fw_value[0] = 0xfab0fab0|0;
  573. }
  574. else if(value === FW_CFG_RAM_SIZE)
  575. {
  576. this.fw_value[0] = this.memory_size[0];
  577. }
  578. else if(value === FW_CFG_NB_CPUS)
  579. {
  580. this.fw_value[0] = 1;
  581. }
  582. else
  583. {
  584. dbg_assert(false, "Unimplemented fw index: " + h(value));
  585. this.fw_value[0] = 0;
  586. }
  587. });
  588. if(DEBUG)
  589. {
  590. // Use by linux for port-IO delay
  591. // Avoid generating tons of debug messages
  592. io.register_write(0x80, this, function(out_byte)
  593. {
  594. });
  595. }
  596. this.devices = {};
  597. // TODO: Make this more configurable
  598. if(settings.load_devices)
  599. {
  600. this.devices.pic = new PIC(this);
  601. this.devices.pci = new PCI(this);
  602. if(ENABLE_ACPI)
  603. {
  604. this.devices.ioapic = new IOAPIC(this);
  605. this.devices.apic = new APIC(this);
  606. this.devices.acpi = new ACPI(this);
  607. }
  608. this.devices.rtc = new RTC(this);
  609. this.fill_cmos(this.devices.rtc, settings);
  610. this.devices.dma = new DMA(this);
  611. if(ENABLE_HPET)
  612. {
  613. this.devices.hpet = new HPET(this);
  614. }
  615. this.devices.vga = new VGAScreen(this, device_bus,
  616. settings.vga_memory_size || 8 * 1024 * 1024);
  617. this.devices.ps2 = new PS2(this, device_bus);
  618. this.devices.uart = new UART(this, 0x3F8, device_bus);
  619. this.devices.fdc = new FloppyController(this, settings.fda, settings.fdb);
  620. var ide_device_count = 0;
  621. if(settings.hda)
  622. {
  623. this.devices.hda = new IDEDevice(this, settings.hda, false, ide_device_count++, device_bus);
  624. }
  625. if(settings.cdrom)
  626. {
  627. this.devices.cdrom = new IDEDevice(this, settings.cdrom, true, ide_device_count++, device_bus);
  628. }
  629. if(settings.hdb)
  630. {
  631. this.devices.hdb = new IDEDevice(this, settings.hdb, false, ide_device_count++, device_bus);
  632. }
  633. this.devices.pit = new PIT(this);
  634. if(settings.enable_ne2k)
  635. {
  636. this.devices.net = new Ne2k(this, device_bus);
  637. }
  638. if(settings.fs9p)
  639. {
  640. this.devices.virtio = new VirtIO(this, device_bus, settings.fs9p);
  641. }
  642. }
  643. if(settings.multiboot)
  644. {
  645. dbg_assert(settings.multiboot.buffer);
  646. this.load_multiboot(settings.multiboot.buffer);
  647. }
  648. if(DEBUG)
  649. {
  650. this.debug.init();
  651. }
  652. this.wm.exports["_profiler_init"]();
  653. };
  654. CPU.prototype.load_multiboot = function(buffer)
  655. {
  656. // https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
  657. dbg_log("Trying multiboot from buffer of size " + buffer.byteLength, LOG_CPU);
  658. const MAGIC = 0x1BADB002;
  659. const ELF_MAGIC = 0x464C457F;
  660. const MULTIBOOT_HEADER_ADDRESS = 0x10000;
  661. const MULTIBOOT_SEARCH_BYTES = 8192;
  662. if(buffer.byteLength < MULTIBOOT_SEARCH_BYTES)
  663. {
  664. var buf32 = new Int32Array(MULTIBOOT_SEARCH_BYTES / 4);
  665. new Uint8Array(buf32.buffer).set(new Uint8Array(buffer));
  666. }
  667. else
  668. {
  669. var buf32 = new Int32Array(buffer, 0, MULTIBOOT_SEARCH_BYTES / 4);
  670. }
  671. for(var offset = 0; offset < MULTIBOOT_SEARCH_BYTES; offset += 4)
  672. {
  673. if(buf32[offset >> 2] === MAGIC)
  674. {
  675. var flags = buf32[offset + 4 >> 2];
  676. var checksum = buf32[offset + 8 >> 2];
  677. var total = MAGIC + flags + checksum | 0;
  678. if(total)
  679. {
  680. dbg_log("Multiboot checksum check failed", LOG_CPU);
  681. continue;
  682. }
  683. }
  684. else
  685. {
  686. continue;
  687. }
  688. dbg_log("Multiboot magic found, flags: " + h(flags >>> 0, 8), LOG_CPU);
  689. dbg_assert((flags & ~MULTIBOOT_HEADER_ADDRESS) === 0, "TODO");
  690. this.reg32s[reg_eax] = 0x2BADB002;
  691. let multiboot_info_addr = 0x7C00;
  692. this.reg32s[reg_ebx] = multiboot_info_addr;
  693. this.write32(multiboot_info_addr, 0);
  694. this.cr[0] = 1;
  695. this.protected_mode[0] = +true;
  696. this.flags[0] = flags_default;
  697. this.update_cs_size(true);
  698. this.stack_size_32[0] = +true;
  699. for(var i = 0; i < 6; i++)
  700. {
  701. this.segment_is_null[i] = 0;
  702. this.segment_offsets[i] = 0;
  703. this.segment_limits[i] = 0xFFFFFFFF;
  704. // Value doesn't matter, OS isn't allowed to reload without setting
  705. // up a proper GDT
  706. this.sreg[i] = 0xB002;
  707. }
  708. if(flags & MULTIBOOT_HEADER_ADDRESS)
  709. {
  710. dbg_log("Multiboot specifies its own address table", LOG_CPU);
  711. var header_addr = buf32[offset + 12 >> 2];
  712. var load_addr = buf32[offset + 16 >> 2];
  713. var load_end_addr = buf32[offset + 20 >> 2];
  714. var bss_end_addr = buf32[offset + 24 >> 2];
  715. var entry_addr = buf32[offset + 28 >> 2];
  716. dbg_log("header=" + h(header_addr, 8) +
  717. " load=" + h(load_addr, 8) +
  718. " load_end=" + h(load_end_addr, 8) +
  719. " bss_end=" + h(bss_end_addr, 8) +
  720. " entry=" + h(entry_addr, 8));
  721. dbg_assert(load_addr <= header_addr);
  722. var file_start = offset - (header_addr - load_addr);
  723. if(load_end_addr === 0)
  724. {
  725. var length = undefined;
  726. }
  727. else
  728. {
  729. dbg_assert(load_end_addr >= load_addr);
  730. var length = load_end_addr - load_addr;
  731. }
  732. let blob = new Uint8Array(buffer, file_start, length);
  733. this.write_blob(blob, load_addr);
  734. this.instruction_pointer[0] = this.get_seg(reg_cs) + entry_addr | 0;
  735. }
  736. else if(buf32[0] === ELF_MAGIC)
  737. {
  738. dbg_log("Multiboot image is in elf format", LOG_CPU);
  739. let elf = read_elf(buffer);
  740. this.instruction_pointer[0] = this.get_seg(reg_cs) + elf.header.entry | 0;
  741. for(let program of elf.program_headers)
  742. {
  743. if(program.type === 0)
  744. {
  745. // null
  746. }
  747. else if(program.type === 1)
  748. {
  749. // load
  750. // Since multiboot specifies that paging is disabled,
  751. // virtual and physical address must be equal
  752. dbg_assert(program.paddr === program.vaddr);
  753. dbg_assert(program.filesz <= program.memsz);
  754. dbg_assert(program.paddr + program.memsz < this.memory_size[0]);
  755. if(program.filesz) // offset mighty be outside of buffer if filesz is 0
  756. {
  757. let blob = new Uint8Array(buffer, program.offset, program.filesz);
  758. this.write_blob(blob, program.paddr);
  759. }
  760. }
  761. else if(
  762. program.type === 2 ||
  763. program.type === 3 ||
  764. program.type === 4 ||
  765. program.type === 6 ||
  766. program.type === 0x6474e550 ||
  767. program.type === 0x6474e551)
  768. {
  769. // ignore for now
  770. }
  771. else
  772. {
  773. dbg_assert(false, "unimplemented elf section type");
  774. }
  775. }
  776. }
  777. else
  778. {
  779. dbg_assert(false, "Not a bootable multiboot format");
  780. }
  781. // only for kvm-unit-test
  782. this.io.register_write_consecutive(0xF4, this,
  783. function(value)
  784. {
  785. console.log("Test exited with code " + h(value, 2));
  786. throw "HALT";
  787. },
  788. function() {},
  789. function() {},
  790. function() {});
  791. // only for kvm-unit-test
  792. for(let i = 0xE; i <= 0xF; i++)
  793. {
  794. this.io.register_write(0x2000 + i, this,
  795. function(value)
  796. {
  797. dbg_log("kvm-unit-test: Set irq " + h(i) + " to " + h(value, 2));
  798. if(value)
  799. {
  800. this.device_raise_irq(i);
  801. }
  802. else
  803. {
  804. this.device_lower_irq(i);
  805. }
  806. });
  807. }
  808. dbg_log("Starting multiboot kernel at:", LOG_CPU);
  809. this.debug.dump_state();
  810. this.debug.dump_regs();
  811. break;
  812. }
  813. };
  814. CPU.prototype.fill_cmos = function(rtc, settings)
  815. {
  816. var boot_order = settings.boot_order || 0x213;
  817. // Used by seabios to determine the boot order
  818. // Nibble
  819. // 1: FloppyPrio
  820. // 2: HDPrio
  821. // 3: CDPrio
  822. // 4: BEVPrio
  823. // bootflag 1, high nibble, lowest priority
  824. // Low nibble: Disable floppy signature check (1)
  825. rtc.cmos_write(CMOS_BIOS_BOOTFLAG1 , 1 | boot_order >> 4 & 0xF0);
  826. // bootflag 2, both nibbles, high and middle priority
  827. rtc.cmos_write(CMOS_BIOS_BOOTFLAG2, boot_order & 0xFF);
  828. // 640k or less if less memory is used
  829. rtc.cmos_write(CMOS_MEM_BASE_LOW, 640 & 0xFF);
  830. rtc.cmos_write(CMOS_MEM_BASE_HIGH, 640 >> 8);
  831. var memory_above_1m = 0; // in k
  832. if(this.memory_size[0] >= 1024 * 1024)
  833. {
  834. memory_above_1m = (this.memory_size[0] - 1024 * 1024) >> 10;
  835. memory_above_1m = Math.min(memory_above_1m, 0xFFFF);
  836. }
  837. rtc.cmos_write(CMOS_MEM_OLD_EXT_LOW, memory_above_1m & 0xFF);
  838. rtc.cmos_write(CMOS_MEM_OLD_EXT_HIGH, memory_above_1m >> 8 & 0xFF);
  839. rtc.cmos_write(CMOS_MEM_EXTMEM_LOW, memory_above_1m & 0xFF);
  840. rtc.cmos_write(CMOS_MEM_EXTMEM_HIGH, memory_above_1m >> 8 & 0xFF);
  841. var memory_above_16m = 0; // in 64k blocks
  842. if(this.memory_size[0] >= 16 * 1024 * 1024)
  843. {
  844. memory_above_16m = (this.memory_size[0] - 16 * 1024 * 1024) >> 16;
  845. memory_above_16m = Math.min(memory_above_16m, 0xFFFF);
  846. }
  847. rtc.cmos_write(CMOS_MEM_EXTMEM2_LOW, memory_above_16m & 0xFF);
  848. rtc.cmos_write(CMOS_MEM_EXTMEM2_HIGH, memory_above_16m >> 8 & 0xFF);
  849. // memory above 4G (not supported by this emulator)
  850. rtc.cmos_write(CMOS_MEM_HIGHMEM_LOW, 0);
  851. rtc.cmos_write(CMOS_MEM_HIGHMEM_MID, 0);
  852. rtc.cmos_write(CMOS_MEM_HIGHMEM_HIGH, 0);
  853. rtc.cmos_write(CMOS_EQUIPMENT_INFO, 0x2F);
  854. rtc.cmos_write(CMOS_BIOS_SMP_COUNT, 0);
  855. };
  856. CPU.prototype.load_bios = function()
  857. {
  858. var bios = this.bios.main;
  859. var vga_bios = this.bios.vga;
  860. if(!bios)
  861. {
  862. dbg_log("Warning: No BIOS");
  863. return;
  864. }
  865. // load bios
  866. var data = new Uint8Array(bios),
  867. start = 0x100000 - bios.byteLength;
  868. this.write_blob(data, start);
  869. if(vga_bios)
  870. {
  871. // load vga bios
  872. var vga_bios8 = new Uint8Array(vga_bios);
  873. // older versions of seabios
  874. this.write_blob(vga_bios8, 0xC0000);
  875. // newer versions of seabios (needs to match pci rom address, see vga.js)
  876. this.io.mmap_register(0xFEB00000, 0x100000,
  877. function(addr)
  878. {
  879. addr = (addr - 0xFEB00000) | 0;
  880. if(addr < vga_bios8.length)
  881. {
  882. return vga_bios8[addr];
  883. }
  884. else
  885. {
  886. return 0;
  887. }
  888. },
  889. function(addr, value)
  890. {
  891. dbg_assert(false, "Unexpected write to VGA rom");
  892. });
  893. }
  894. else
  895. {
  896. dbg_log("Warning: No VGA BIOS");
  897. }
  898. // seabios expects the bios to be mapped to 0xFFF00000 also
  899. this.io.mmap_register(0xFFF00000, 0x100000,
  900. function(addr)
  901. {
  902. addr &= 0xFFFFF;
  903. return this.mem8[addr];
  904. }.bind(this),
  905. function(addr, value)
  906. {
  907. addr &= 0xFFFFF;
  908. this.mem8[addr] = value;
  909. }.bind(this));
  910. };
  911. CPU.prototype.do_run = function()
  912. {
  913. // Idle time is when no instructions are being executed
  914. this.wm.exports["_profiler_end"](P_IDLE);
  915. /** @type {number} */
  916. var start = v86.microtick();
  917. /** @type {number} */
  918. var now = start;
  919. // outer loop:
  920. // runs cycles + timers
  921. for(; now - start < TIME_PER_FRAME;)
  922. {
  923. this.run_hardware_timers(now);
  924. this.handle_irqs();
  925. this.do_many_cycles();
  926. if(this.in_hlt)
  927. {
  928. return;
  929. }
  930. now = v86.microtick();
  931. }
  932. this.wm.exports["_profiler_start"](P_IDLE);
  933. };
  934. CPU.prototype.do_many_cycles = function()
  935. {
  936. // Capture the total time we were executing instructions
  937. this.wm.exports["_profiler_start"](P_DO_MANY_CYCLES);
  938. this.coverage_logger.log_start();
  939. try {
  940. this.do_many_cycles_unsafe();
  941. }
  942. catch(e)
  943. {
  944. this.exception_cleanup(e);
  945. }
  946. this.coverage_logger.log_end();
  947. this.wm.exports["_profiler_end"](P_DO_MANY_CYCLES);
  948. this.wm.exports["_profiler_end"](P_GEN_INSTR);
  949. this.wm.exports["_profiler_end"](P_RUN_FROM_CACHE);
  950. this.wm.exports["_profiler_end"](P_RUN_INTERPRETED);
  951. };
  952. /** @export */
  953. CPU.prototype.cycle = function()
  954. {
  955. try {
  956. // XXX: May do several cycles
  957. this.cycle_internal();
  958. }
  959. catch(e)
  960. {
  961. this.exception_cleanup(e);
  962. }
  963. };
  964. // Some functions must not be inlined, because then more code is in the
  965. // deoptimized try-catch block.
  966. // This trick is a bit ugly, but it works without further complication.
  967. if(typeof window !== "undefined")
  968. {
  969. window["__no_inline_for_closure_compiler__"] = [
  970. CPU.prototype.exception_cleanup,
  971. CPU.prototype.do_many_cycles_unsafe,
  972. CPU.prototype.do_many_cycles,
  973. ];
  974. }
  975. /** @const */
  976. var PROFILING = false;
  977. if(PROFILING)
  978. {
  979. var instruction_total = new Float64Array(256);
  980. var instruction_count = new Float64Array(256);
  981. window["print_profiling"] = function print_profiling()
  982. {
  983. var prof_instructions = [];
  984. for(var i = 0; i < 256; i++) prof_instructions[i] = {
  985. n: h(i, 2),
  986. total: instruction_total[i],
  987. count: instruction_count[i],
  988. per: (instruction_total[i] / instruction_count[i]) || 0,
  989. };
  990. console.log("count:");
  991. console.table(prof_instructions.sort((p0, p1) => p1.count - p0.count));
  992. console.log("time:");
  993. console.table(prof_instructions.sort((p0, p1) => p1.total - p0.total));
  994. console.log("time/count:");
  995. console.table(prof_instructions.sort((p0, p1) => p1.per - p0.per));
  996. };
  997. }
  998. var seen_code = {};
  999. var seen_code_uncompiled = {};
  1000. CPU.prototype.codegen_finalize = function(wasm_table_index, start, end, first_opcode, state_flags, page_dirtiness)
  1001. {
  1002. dbg_assert(wasm_table_index >= 0 && wasm_table_index < WASM_TABLE_SIZE);
  1003. //dbg_log("finalize");
  1004. const code = this.codegen.get_module_code();
  1005. if(DEBUG)
  1006. {
  1007. if(DUMP_GENERATED_WASM && !seen_code[start])
  1008. {
  1009. this.debug.dump_wasm(code);
  1010. seen_code[start] = true;
  1011. if((start ^ end) & ~0xFFF)
  1012. {
  1013. dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0));
  1014. end = (start | 0xFFF) + 1; // until the end of the page
  1015. }
  1016. dbg_assert(end >= start);
  1017. const buffer = new Uint8Array(end - start);
  1018. for(let i = start; i < end; i++)
  1019. {
  1020. buffer[i - start] = this.read8(i);
  1021. }
  1022. this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start);
  1023. }
  1024. }
  1025. // Make a copy of jit_imports, since some imports change and
  1026. // WebAssembly.instantiate looks them up asynchronously
  1027. const jit_imports = new this.jit_imports.constructor();
  1028. jit_imports["next_block_branched"] = this.jit_imports["next_block_branched"];
  1029. jit_imports["next_block_not_branched"] = this.jit_imports["next_block_not_branched"];
  1030. const result = WebAssembly.instantiate(code, { "e": jit_imports }).then(result => {
  1031. const f = result.instance.exports["f"];
  1032. this.wm.exports["_codegen_finalize_finished"](
  1033. wasm_table_index, start, end,
  1034. first_opcode, state_flags, page_dirtiness);
  1035. // The following will throw if f isn't an exported function
  1036. this.wm.imports["env"].table.set(wasm_table_index, f);
  1037. });
  1038. if(DEBUG)
  1039. {
  1040. result.catch(e => {
  1041. console.log(e);
  1042. debugger;
  1043. throw e;
  1044. });
  1045. }
  1046. };
  1047. CPU.prototype.log_uncompiled_code = function(start, end)
  1048. {
  1049. if(!DEBUG || !DUMP_UNCOMPILED_ASSEMBLY)
  1050. {
  1051. return;
  1052. }
  1053. if((seen_code_uncompiled[start] || 0) < 100)
  1054. {
  1055. seen_code_uncompiled[start] = (seen_code_uncompiled[start] || 0) + 1;
  1056. end += 8; // final jump is not included
  1057. if((start ^ end) & ~0xFFF)
  1058. {
  1059. dbg_log("truncated disassembly start=" + h(start >>> 0) + " end=" + h(end >>> 0));
  1060. end = (start | 0xFFF) + 1; // until the end of the page
  1061. }
  1062. if(end < start) end = start;
  1063. dbg_assert(end >= start);
  1064. const buffer = new Uint8Array(end - start);
  1065. for(let i = start; i < end; i++)
  1066. {
  1067. buffer[i - start] = this.read8(i);
  1068. }
  1069. dbg_log("Uncompiled code:");
  1070. this.debug.dump_code(this.is_32[0] ? 1 : 0, buffer, start);
  1071. }
  1072. };
  1073. CPU.prototype.dbg_log = function()
  1074. {
  1075. dbg_log("from wasm: " + [].join.call(arguments));
  1076. };
  1077. CPU.prototype.dbg_assert = function(x)
  1078. {
  1079. dbg_assert(x);
  1080. };
  1081. CPU.prototype.hlt_loop = function()
  1082. {
  1083. if(this.flags[0] & flag_interrupt)
  1084. {
  1085. //dbg_log("In HLT loop", LOG_CPU);
  1086. this.run_hardware_timers(v86.microtick());
  1087. this.handle_irqs();
  1088. return 0;
  1089. }
  1090. else
  1091. {
  1092. return 100;
  1093. }
  1094. };
  1095. CPU.prototype.run_hardware_timers = function(now)
  1096. {
  1097. if(ENABLE_HPET)
  1098. {
  1099. var pit_time = this.devices.pit.timer(now, this.devices.hpet.legacy_mode);
  1100. var rtc_time = this.devices.rtc.timer(now, this.devices.hpet.legacy_mode);
  1101. this.devices.hpet.timer(now);
  1102. }
  1103. else
  1104. {
  1105. var pit_time = this.devices.pit.timer(now, false);
  1106. var rtc_time = this.devices.rtc.timer(now, false);
  1107. }
  1108. if(ENABLE_ACPI)
  1109. {
  1110. this.devices.acpi.timer(now);
  1111. this.devices.apic.timer(now);
  1112. }
  1113. };
  1114. CPU.prototype.set_cr0 = function(cr0)
  1115. {
  1116. //dbg_log("cr0 = " + h(this.cr[0] >>> 0), LOG_CPU);
  1117. if(cr0 & CR0_AM)
  1118. {
  1119. dbg_log("Warning: Unimplemented: cr0 alignment mask", LOG_CPU);
  1120. }
  1121. if((cr0 & (CR0_PE | CR0_PG)) === CR0_PG)
  1122. {
  1123. // cannot load PG without PE
  1124. throw this.debug.unimpl("#GP handler");
  1125. }
  1126. const old_cr0 = this.cr[0];
  1127. this.cr[0] = cr0;
  1128. //if(!have_fpu)
  1129. //{
  1130. // // if there's no FPU, keep emulation set
  1131. // this.cr[0] |= CR0_EM;
  1132. //}
  1133. this.cr[0] |= CR0_ET;
  1134. if((old_cr0 & (CR0_PG | CR0_WP)) !== (cr0 & (CR0_PG | CR0_WP)))
  1135. {
  1136. this.paging[0] = +((this.cr[0] & CR0_PG) === CR0_PG);
  1137. this.full_clear_tlb();
  1138. }
  1139. this.protected_mode[0] = +((this.cr[0] & CR0_PE) === CR0_PE);
  1140. //this.jit_empty_cache();
  1141. };
  1142. CPU.prototype.set_cr4 = function(cr4)
  1143. {
  1144. if(cr4 & (1 << 11 | 1 << 12 | 1 << 15 | 1 << 16 | 1 << 19 | 0xFFC00000))
  1145. {
  1146. dbg_log("trigger_gp: Invalid cr4 bit", LOG_CPU);
  1147. this.trigger_gp(0);
  1148. }
  1149. if((this.cr[4] ^ cr4) & CR4_PGE)
  1150. {
  1151. if(cr4 & CR4_PGE)
  1152. {
  1153. // The PGE bit has been enabled. The global TLB is
  1154. // still empty, so we only have to copy it over
  1155. this.clear_tlb();
  1156. }
  1157. else
  1158. {
  1159. // Clear the global TLB
  1160. this.full_clear_tlb();
  1161. }
  1162. }
  1163. this.cr[4] = cr4;
  1164. this.page_size_extensions[0] = (cr4 & CR4_PSE) ? PSE_ENABLED : 0;
  1165. if(cr4 & CR4_PAE)
  1166. {
  1167. throw this.debug.unimpl("PAE");
  1168. }
  1169. if(cr4 & 0xFFFFF900)
  1170. {
  1171. dbg_assert(false, "Unimplemented CR4 bits: " + h(cr4));
  1172. this.trigger_ud();
  1173. }
  1174. dbg_log("cr4=" + h(cr4 >>> 0), LOG_CPU);
  1175. };
  1176. CPU.prototype.cpl_changed = function()
  1177. {
  1178. this.last_virt_eip[0] = -1;
  1179. this.last_virt_esp[0] = -1;
  1180. };
  1181. CPU.prototype.after_block_boundary = function ()
  1182. {
  1183. // May be called through JS imports in the WASM module, such as loop or handle_irqs (through popf, sti)
  1184. this.wm.exports["_after_block_boundary"]();
  1185. };
  1186. CPU.prototype.branch_taken = function () {
  1187. this.after_block_boundary();
  1188. };
  1189. CPU.prototype.branch_not_taken = function () {
  1190. this.after_block_boundary();
  1191. };
  1192. CPU.prototype.diverged = function () {
  1193. this.after_block_boundary();
  1194. };
  1195. CPU.prototype.jit_empty_cache = function()
  1196. {
  1197. this.wm.exports["_jit_empty_cache"]();
  1198. const table = this.wm.imports["env"].table;
  1199. for(let i = 0; i < WASM_TABLE_SIZE; i++)
  1200. {
  1201. table.set(i, null);
  1202. }
  1203. };
  1204. CPU.prototype.call_interrupt_vector = function(interrupt_nr, is_software_int, has_error_code, error_code)
  1205. {
  1206. //dbg_log("int " + h(interrupt_nr, 2) + " (" + (is_software_int ? "soft" : "hard") + "ware)", LOG_CPU);
  1207. CPU_LOG_VERBOSE && this.debug.dump_state("int " + h(interrupt_nr) + " start" +
  1208. " (" + (is_software_int ? "soft" : "hard") + "ware)");
  1209. CPU_LOG_VERBOSE && this.debug.dump_regs();
  1210. this.debug.debug_interrupt(interrupt_nr);
  1211. dbg_assert(typeof has_error_code === "boolean");
  1212. dbg_assert(has_error_code === false || typeof error_code === "number");
  1213. // we have to leave hlt_loop at some point, this is a
  1214. // good place to do it
  1215. //this.in_hlt && dbg_log("Leave HLT loop", LOG_CPU);
  1216. this.in_hlt = false;
  1217. if(this.protected_mode[0])
  1218. {
  1219. if(this.vm86_mode() && (this.cr[4] & CR4_VME))
  1220. {
  1221. throw this.debug.unimpl("VME");
  1222. }
  1223. if(this.vm86_mode() && is_software_int && this.getiopl() < 3)
  1224. {
  1225. dbg_log("call_interrupt_vector #GP. vm86 && software int && iopl < 3", LOG_CPU);
  1226. dbg_trace(LOG_CPU);
  1227. this.trigger_gp(0);
  1228. }
  1229. if((interrupt_nr << 3 | 7) > this.idtr_size[0])
  1230. {
  1231. dbg_log(interrupt_nr, LOG_CPU);
  1232. dbg_trace(LOG_CPU);
  1233. throw this.debug.unimpl("#GP handler");
  1234. }
  1235. var addr = this.idtr_offset[0] + (interrupt_nr << 3) | 0;
  1236. dbg_assert((addr & 0xFFF) < 0xFF8);
  1237. if(this.paging[0])
  1238. {
  1239. addr = this.translate_address_system_read(addr);
  1240. }
  1241. var base = this.read16(addr) | this.read16(addr + 6 | 0) << 16;
  1242. var selector = this.read16(addr + 2 | 0);
  1243. var access = this.read8(addr + 5 | 0);
  1244. var dpl = access >> 5 & 3;
  1245. var type = access & 31;
  1246. if((access & 0x80) === 0)
  1247. {
  1248. // present bit not set
  1249. throw this.debug.unimpl("#NP handler");
  1250. }
  1251. if(is_software_int && dpl < this.cpl[0])
  1252. {
  1253. dbg_log("#gp software interrupt (" + h(interrupt_nr, 2) + ") and dpl < cpl", LOG_CPU);
  1254. dbg_trace(LOG_CPU);
  1255. this.trigger_gp(interrupt_nr << 3 | 2);
  1256. }
  1257. if(type === 5)
  1258. {
  1259. // task gate
  1260. dbg_log("interrupt to task gate: int=" + h(interrupt_nr, 2) + " sel=" + h(selector, 4) + " dpl=" + dpl, LOG_CPU);
  1261. dbg_trace(LOG_CPU);
  1262. this.do_task_switch(selector, error_code);
  1263. CPU_LOG_VERBOSE && this.debug.dump_state("int end");
  1264. return;
  1265. }
  1266. if((type & ~1 & ~8) !== 6)
  1267. {
  1268. // invalid type
  1269. dbg_trace(LOG_CPU);
  1270. dbg_log("invalid type: " + h(type));
  1271. dbg_log(h(addr) + " " + h(base >>> 0) + " " + h(selector));
  1272. throw this.debug.unimpl("#GP handler");
  1273. }
  1274. var is_trap = (type & 1) === 1;
  1275. var is_16 = (type & 8) === 0;
  1276. var info = this.lookup_segment_selector(selector);
  1277. dbg_assert((base >>> 0) <= info.effective_limit);
  1278. dbg_assert(info.is_valid);
  1279. if(info.is_null)
  1280. {
  1281. dbg_log("is null");
  1282. throw this.debug.unimpl("#GP handler");
  1283. }
  1284. if(!info.is_executable || info.dpl > this.cpl[0])
  1285. {
  1286. dbg_log("not exec");
  1287. throw this.debug.unimpl("#GP handler");
  1288. }
  1289. if(!info.is_present)
  1290. {
  1291. // kvm-unit-test
  1292. dbg_log("not present");
  1293. this.trigger_np(interrupt_nr << 3 | 2);
  1294. }
  1295. var old_flags = this.get_eflags();
  1296. //dbg_log("interrupt " + h(interrupt_nr, 2) + " (" + (is_software_int ? "soft" : "hard") + "ware) from cpl=" + this.cpl[0] + " vm=" + (this.flags[0] & flag_vm) + " cs:eip=" + h(this.sreg[reg_cs], 4) + ":" + h(this.get_real_eip(), 8) + " to cpl="
  1297. if(!info.dc_bit && info.dpl < this.cpl[0])
  1298. {
  1299. // inter privilege level interrupt
  1300. // interrupt from vm86 mode
  1301. //dbg_log("Inter privilege interrupt gate=" + h(selector, 4) + ":" + h(base >>> 0, 8) + " trap=" + is_trap + " 16bit=" + is_16, LOG_CPU);
  1302. //this.debug.dump_regs();
  1303. var tss_stack_addr = this.get_tss_stack_addr(info.dpl);
  1304. if(this.tss_size_32)
  1305. {
  1306. var new_esp = this.read32s(tss_stack_addr);
  1307. var new_ss = this.read16(tss_stack_addr + 4 | 0);
  1308. }
  1309. else
  1310. {
  1311. var new_esp = this.read16(tss_stack_addr);
  1312. var new_ss = this.read16(tss_stack_addr + 2 | 0);
  1313. }
  1314. var ss_info = this.lookup_segment_selector(new_ss);
  1315. // Disabled: Incorrect handling of direction bit
  1316. // See http://css.csail.mit.edu/6.858/2014/readings/i386/s06_03.htm
  1317. //if(!((new_esp >>> 0) <= ss_info.effective_limit))
  1318. // debugger;
  1319. //dbg_assert((new_esp >>> 0) <= ss_info.effective_limit);
  1320. dbg_assert(ss_info.is_valid && !ss_info.is_system && ss_info.is_writable);
  1321. if(ss_info.is_null)
  1322. {
  1323. throw this.debug.unimpl("#TS handler");
  1324. }
  1325. if(ss_info.rpl !== info.dpl) // xxx: 0 in v86 mode
  1326. {
  1327. throw this.debug.unimpl("#TS handler");
  1328. }
  1329. if(ss_info.dpl !== info.dpl || !ss_info.rw_bit)
  1330. {
  1331. throw this.debug.unimpl("#TS handler");
  1332. }
  1333. if(!ss_info.is_present)
  1334. {
  1335. throw this.debug.unimpl("#TS handler");
  1336. }
  1337. var old_esp = this.reg32s[reg_esp];
  1338. var old_ss = this.sreg[reg_ss];
  1339. if(old_flags & flag_vm)
  1340. {
  1341. //dbg_log("return from vm86 mode");
  1342. //this.debug.dump_regs();
  1343. dbg_assert(info.dpl === 0, "switch to non-0 dpl from vm86 mode");
  1344. }
  1345. var stack_space = (is_16 ? 2 : 4) * (5 + (has_error_code === true) + 4 * ((old_flags & flag_vm) === flag_vm));
  1346. var new_stack_pointer = ss_info.base + (ss_info.size ? new_esp - stack_space : (new_esp - stack_space & 0xFFFF));
  1347. // XXX: with new cpl or with cpl 0?
  1348. this.translate_address_system_write(new_stack_pointer);
  1349. this.translate_address_system_write(ss_info.base + new_esp - 1);
  1350. // no exceptions below
  1351. this.cpl[0] = info.dpl;
  1352. this.cpl_changed();
  1353. this.update_cs_size(info.size);
  1354. this.flags[0] &= ~flag_vm & ~flag_rf;
  1355. this.switch_seg(reg_ss, new_ss);
  1356. this.set_stack_reg(new_esp);
  1357. if(old_flags & flag_vm)
  1358. {
  1359. if(is_16)
  1360. {
  1361. dbg_assert(false);
  1362. }
  1363. else
  1364. {
  1365. this.push32(this.sreg[reg_gs]);
  1366. this.push32(this.sreg[reg_fs]);
  1367. this.push32(this.sreg[reg_ds]);
  1368. this.push32(this.sreg[reg_es]);
  1369. }
  1370. }
  1371. if(is_16)
  1372. {
  1373. this.push16(old_ss);
  1374. this.push16(old_esp);
  1375. }
  1376. else
  1377. {
  1378. this.push32(old_ss);
  1379. this.push32(old_esp);
  1380. }
  1381. }
  1382. else if(info.dc_bit || info.dpl === this.cpl[0])
  1383. {
  1384. // intra privilege level interrupt
  1385. //dbg_log("Intra privilege interrupt gate=" + h(selector, 4) + ":" + h(base >>> 0, 8) +
  1386. // " trap=" + is_trap + " 16bit=" + is_16 +
  1387. // " cpl=" + this.cpl[0] + " dpl=" + info.dpl + " conforming=" + +info.dc_bit, LOG_CPU);
  1388. //this.debug.dump_regs_short();
  1389. if(this.flags[0] & flag_vm)
  1390. {
  1391. dbg_assert(false, "check error code");
  1392. this.trigger_gp(selector & ~3);
  1393. }
  1394. var stack_space = (is_16 ? 2 : 4) * (3 + (has_error_code === true));
  1395. // XXX: with current cpl or with cpl 0?
  1396. this.writable_or_pagefault(this.get_stack_pointer(-stack_space), stack_space);
  1397. // no exceptions below
  1398. }
  1399. else
  1400. {
  1401. throw this.debug.unimpl("#GP handler");
  1402. }
  1403. if(is_16)
  1404. {
  1405. this.push16(old_flags);
  1406. this.push16(this.sreg[reg_cs]);
  1407. this.push16(this.get_real_eip());
  1408. if(has_error_code === true)
  1409. {
  1410. this.push16(error_code);
  1411. }
  1412. base &= 0xFFFF;
  1413. }
  1414. else
  1415. {
  1416. this.push32(old_flags);
  1417. this.push32(this.sreg[reg_cs]);
  1418. this.push32(this.get_real_eip());
  1419. if(has_error_code === true)
  1420. {
  1421. this.push32(error_code);
  1422. }
  1423. }
  1424. if(old_flags & flag_vm)
  1425. {
  1426. this.switch_seg(reg_gs, 0);
  1427. this.switch_seg(reg_fs, 0);
  1428. this.switch_seg(reg_ds, 0);
  1429. this.switch_seg(reg_es, 0);
  1430. }
  1431. this.sreg[reg_cs] = selector & ~3 | this.cpl[0];
  1432. dbg_assert((this.sreg[reg_cs] & 3) === this.cpl[0]);
  1433. this.update_cs_size(info.size);
  1434. this.segment_limits[reg_cs] = info.effective_limit;
  1435. this.segment_offsets[reg_cs] = info.base;
  1436. this.instruction_pointer[0] = this.get_seg(reg_cs) + base | 0;
  1437. this.flags[0] &= ~flag_nt & ~flag_vm & ~flag_rf & ~flag_trap;
  1438. if(!is_trap)
  1439. {
  1440. // clear int flag for interrupt gates
  1441. this.flags[0] &= ~flag_interrupt;
  1442. }
  1443. else
  1444. {
  1445. if(!this.page_fault[0]) // XXX
  1446. {
  1447. this.handle_irqs();
  1448. }
  1449. }
  1450. }
  1451. else
  1452. {
  1453. // call 4 byte cs:ip interrupt vector from ivt at cpu.memory 0
  1454. var index = interrupt_nr << 2;
  1455. var new_ip = this.read16(index);
  1456. var new_cs = this.read16(index + 2 | 0);
  1457. // push flags, cs:ip
  1458. this.push16(this.get_eflags());
  1459. this.push16(this.sreg[reg_cs]);
  1460. this.push16(this.get_real_eip());
  1461. this.flags[0] &= ~flag_interrupt;
  1462. this.switch_cs_real_mode(new_cs);
  1463. this.instruction_pointer[0] = this.get_seg(reg_cs) + new_ip | 0;
  1464. }
  1465. //dbg_log("int to:", LOG_CPU);
  1466. CPU_LOG_VERBOSE && this.debug.dump_state("int end");
  1467. };
  1468. CPU.prototype.iret16 = function()
  1469. {
  1470. this.iret(true);
  1471. };
  1472. CPU.prototype.iret32 = function()
  1473. {
  1474. this.iret(false);
  1475. };
  1476. CPU.prototype.iret = function(is_16)
  1477. {
  1478. //dbg_log("iret is_16=" + is_16, LOG_CPU);
  1479. CPU_LOG_VERBOSE && this.debug.dump_state("iret" + (is_16 ? "16" : "32") + " start");
  1480. //this.debug.dump_regs();
  1481. if(this.vm86_mode() && this.getiopl() < 3)
  1482. {
  1483. // vm86 mode, iopl != 3
  1484. dbg_log("#gp iret vm86 mode, iopl != 3", LOG_CPU);
  1485. this.trigger_gp(0);
  1486. }
  1487. if(is_16)
  1488. {
  1489. var new_eip = this.safe_read16(this.get_stack_pointer(0));
  1490. var new_cs = this.safe_read16(this.get_stack_pointer(2));
  1491. var new_flags = this.safe_read16(this.get_stack_pointer(4));
  1492. }
  1493. else
  1494. {
  1495. var new_eip = this.safe_read32s(this.get_stack_pointer(0));
  1496. var new_cs = this.safe_read16(this.get_stack_pointer(4));
  1497. var new_flags = this.safe_read32s(this.get_stack_pointer(8));
  1498. }
  1499. if(!this.protected_mode[0] || (this.vm86_mode() && this.getiopl() === 3))
  1500. {
  1501. if(new_eip & 0xFFFF0000)
  1502. {
  1503. throw this.debug.unimpl("#GP handler");
  1504. }
  1505. this.switch_cs_real_mode(new_cs);
  1506. this.instruction_pointer[0] = new_eip + this.get_seg(reg_cs) | 0;
  1507. if(is_16)
  1508. {
  1509. this.update_eflags(new_flags | this.flags[0] & ~0xFFFF);
  1510. this.adjust_stack_reg(3 * 2);
  1511. }
  1512. else
  1513. {
  1514. this.update_eflags(new_flags);
  1515. this.adjust_stack_reg(3 * 4);
  1516. }
  1517. //dbg_log("iret32 to:", LOG_CPU);
  1518. CPU_LOG_VERBOSE && this.debug.dump_state("iret end");
  1519. this.handle_irqs();
  1520. return;
  1521. }
  1522. dbg_assert(!this.vm86_mode());
  1523. if(this.flags[0] & flag_nt)
  1524. {
  1525. if(DEBUG) throw this.debug.unimpl("nt");
  1526. this.trigger_gp(0);
  1527. }
  1528. if(new_flags & flag_vm)
  1529. {
  1530. if(this.cpl[0] === 0)
  1531. {
  1532. // return to virtual 8086 mode
  1533. // vm86 cannot be set in 16 bit flag
  1534. dbg_assert(!is_16);
  1535. dbg_assert((new_eip & ~0xFFFF) === 0);
  1536. //dbg_log("in vm86 mode now " +
  1537. // " cs:eip=" + h(new_cs, 4) + ":" + h(this.instruction_pointer >>> 0, 8) +
  1538. // " iopl=" + this.getiopl() + " flags=" + h(new_flags, 8), LOG_CPU);
  1539. var temp_esp = this.safe_read32s(this.get_stack_pointer(12));
  1540. var temp_ss = this.safe_read16(this.get_stack_pointer(16));
  1541. var new_es = this.safe_read16(this.get_stack_pointer(20));
  1542. var new_ds = this.safe_read16(this.get_stack_pointer(24));
  1543. var new_fs = this.safe_read16(this.get_stack_pointer(28));
  1544. var new_gs = this.safe_read16(this.get_stack_pointer(32));
  1545. // no exceptions below
  1546. this.update_eflags(new_flags);
  1547. this.flags[0] |= flag_vm;
  1548. this.switch_cs_real_mode(new_cs);
  1549. this.instruction_pointer[0] = (new_eip & 0xFFFF) + this.get_seg(reg_cs) | 0;
  1550. this.switch_seg(reg_es, new_es);
  1551. this.switch_seg(reg_ds, new_ds);
  1552. this.switch_seg(reg_fs, new_fs);
  1553. this.switch_seg(reg_gs, new_gs);
  1554. this.adjust_stack_reg(9 * 4); // 9 dwords: eip, cs, flags, esp, ss, es, ds, fs, gs
  1555. this.reg32s[reg_esp] = temp_esp;
  1556. this.switch_seg(reg_ss, temp_ss);
  1557. this.cpl[0] = 3;
  1558. this.cpl_changed();
  1559. this.update_cs_size(false);
  1560. //dbg_log("iret32 to:", LOG_CPU);
  1561. CPU_LOG_VERBOSE && this.debug.dump_state("iret end");
  1562. //this.debug.dump_regs();
  1563. return;
  1564. }
  1565. else
  1566. {
  1567. dbg_log("vm86 flag ignored because cpl != 0", LOG_CPU);
  1568. new_flags &= ~flag_vm;
  1569. }
  1570. }
  1571. // protected mode return
  1572. var info = this.lookup_segment_selector(new_cs);
  1573. dbg_assert(info.is_valid);
  1574. dbg_assert((new_eip >>> 0) <= info.effective_limit);
  1575. if(info.is_null)
  1576. {
  1577. throw this.debug.unimpl("is null");
  1578. }
  1579. if(!info.is_present)
  1580. {
  1581. throw this.debug.unimpl("not present");
  1582. }
  1583. if(!info.is_executable)
  1584. {
  1585. throw this.debug.unimpl("not exec");
  1586. }
  1587. if(info.rpl < this.cpl[0])
  1588. {
  1589. throw this.debug.unimpl("rpl < cpl");
  1590. }
  1591. if(info.dc_bit && info.dpl > info.rpl)
  1592. {
  1593. throw this.debug.unimpl("conforming and dpl > rpl");
  1594. }
  1595. if(!info.dc_bit && info.rpl !== info.dpl)
  1596. {
  1597. dbg_log("#gp iret: non-conforming cs and rpl != dpl, dpl=" + info.dpl + " rpl=" + info.rpl, LOG_CPU);
  1598. this.trigger_gp(new_cs & ~3);
  1599. }
  1600. if(info.rpl > this.cpl[0])
  1601. {
  1602. // outer privilege return
  1603. if(is_16)
  1604. {
  1605. var temp_esp = this.safe_read16(this.get_stack_pointer(6));
  1606. var temp_ss = this.safe_read16(this.get_stack_pointer(8));
  1607. }
  1608. else
  1609. {
  1610. var temp_esp = this.safe_read32s(this.get_stack_pointer(12));
  1611. var temp_ss = this.safe_read16(this.get_stack_pointer(16));
  1612. }
  1613. var ss_info = this.lookup_segment_selector(temp_ss);
  1614. var new_cpl = info.rpl;
  1615. if(ss_info.is_null)
  1616. {
  1617. dbg_log("#GP for loading 0 in SS sel=" + h(temp_ss, 4), LOG_CPU);
  1618. dbg_trace(LOG_CPU);
  1619. this.trigger_gp(0);
  1620. }
  1621. if(!ss_info.is_valid ||
  1622. ss_info.is_system ||
  1623. ss_info.rpl !== new_cpl ||
  1624. !ss_info.is_writable ||
  1625. ss_info.dpl !== new_cpl)
  1626. {
  1627. dbg_log("#GP for loading invalid in SS sel=" + h(temp_ss, 4), LOG_CPU);
  1628. dbg_trace(LOG_CPU);
  1629. this.trigger_gp(temp_ss & ~3);
  1630. }
  1631. if(!ss_info.is_present)
  1632. {
  1633. dbg_log("#SS for loading non-present in SS sel=" + h(temp_ss, 4), LOG_CPU);
  1634. dbg_trace(LOG_CPU);
  1635. this.trigger_ss(temp_ss & ~3);
  1636. }
  1637. // no exceptions below
  1638. if(is_16)
  1639. {
  1640. this.update_eflags(new_flags | this.flags[0] & ~0xFFFF);
  1641. }
  1642. else
  1643. {
  1644. this.update_eflags(new_flags);
  1645. }
  1646. this.cpl[0] = info.rpl;
  1647. this.cpl_changed();
  1648. //dbg_log("outer privilege return: from=" + this.cpl[0] + " to=" + info.rpl + " ss:esp=" + h(temp_ss, 4) + ":" + h(temp_esp >>> 0, 8), LOG_CPU);
  1649. this.switch_seg(reg_ss, temp_ss);
  1650. this.set_stack_reg(temp_esp);
  1651. if(this.cpl[0] === 0)
  1652. {
  1653. this.flags[0] = this.flags[0] & ~flag_vif & ~flag_vip | (new_flags & (flag_vif | flag_vip));
  1654. }
  1655. // XXX: Set segment to 0 if it's not usable in the new cpl
  1656. // XXX: Use cached segment information
  1657. //var ds_info = this.lookup_segment_selector(this.sreg[reg_ds]);
  1658. //if(this.cpl[0] > ds_info.dpl && (!ds_info.is_executable || !ds_info.dc_bit)) this.switch_seg(reg_ds, 0);
  1659. // ...
  1660. }
  1661. else if(info.rpl === this.cpl[0])
  1662. {
  1663. // same privilege return
  1664. // no exceptions below
  1665. if(is_16)
  1666. {
  1667. this.adjust_stack_reg(3 * 2);
  1668. this.update_eflags(new_flags | this.flags[0] & ~0xFFFF);
  1669. }
  1670. else
  1671. {
  1672. this.adjust_stack_reg(3 * 4);
  1673. this.update_eflags(new_flags);
  1674. }
  1675. // update vip and vif, which are not changed by update_eflags
  1676. if(this.cpl[0] === 0)
  1677. {
  1678. this.flags[0] = this.flags[0] & ~flag_vif & ~flag_vip | (new_flags & (flag_vif | flag_vip));
  1679. }
  1680. }
  1681. else
  1682. {
  1683. dbg_assert(false);
  1684. }
  1685. this.sreg[reg_cs] = new_cs;
  1686. dbg_assert((new_cs & 3) === this.cpl[0]);
  1687. this.update_cs_size(info.size);
  1688. this.segment_limits[reg_cs] = info.effective_limit;
  1689. this.segment_offsets[reg_cs] = info.base;
  1690. this.instruction_pointer[0] = new_eip + this.get_seg(reg_cs) | 0;
  1691. CPU_LOG_VERBOSE && this.debug.dump_state("iret" + (is_16 ? "16" : "32") + " end");
  1692. this.handle_irqs();
  1693. };
  1694. CPU.prototype.switch_cs_real_mode = function(selector)
  1695. {
  1696. dbg_assert(!this.protected_mode[0] || this.vm86_mode());
  1697. this.sreg[reg_cs] = selector;
  1698. this.segment_is_null[reg_cs] = 0;
  1699. this.segment_offsets[reg_cs] = selector << 4;
  1700. };
  1701. CPU.prototype.far_return = function(eip, selector, stack_adjust)
  1702. {
  1703. dbg_assert(typeof selector === "number" && selector < 0x10000 && selector >= 0);
  1704. //dbg_log("far return eip=" + h(eip >>> 0, 8) + " cs=" + h(selector, 4) + " stack_adjust=" + h(stack_adjust), LOG_CPU);
  1705. CPU_LOG_VERBOSE && this.debug.dump_state("far ret start");
  1706. if(!this.protected_mode[0])
  1707. {
  1708. dbg_assert(!this.is_32[0]);
  1709. //dbg_assert(!this.stack_size_32[0]);
  1710. }
  1711. if(!this.protected_mode[0] || this.vm86_mode())
  1712. {
  1713. this.switch_cs_real_mode(selector);
  1714. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1715. this.adjust_stack_reg(2 * (this.is_osize_32() ? 4 : 2) + stack_adjust);
  1716. return;
  1717. }
  1718. var info = this.lookup_segment_selector(selector);
  1719. if(info.is_null)
  1720. {
  1721. dbg_log("null cs", LOG_CPU);
  1722. this.trigger_gp(0);
  1723. }
  1724. if(!info.is_valid)
  1725. {
  1726. dbg_log("invalid cs: " + h(selector), LOG_CPU);
  1727. this.trigger_gp(selector & ~3);
  1728. }
  1729. if(info.is_system)
  1730. {
  1731. dbg_assert(false, "is system in far return");
  1732. this.trigger_gp(selector & ~3);
  1733. }
  1734. if(!info.is_executable)
  1735. {
  1736. dbg_log("non-executable cs: " + h(selector), LOG_CPU);
  1737. this.trigger_gp(selector & ~3);
  1738. }
  1739. if(info.rpl < this.cpl[0])
  1740. {
  1741. dbg_log("cs rpl < cpl: " + h(selector), LOG_CPU);
  1742. this.trigger_gp(selector & ~3);
  1743. }
  1744. if(info.dc_bit && info.dpl > info.rpl)
  1745. {
  1746. dbg_log("cs conforming and dpl > rpl: " + h(selector), LOG_CPU);
  1747. this.trigger_gp(selector & ~3);
  1748. }
  1749. if(!info.dc_bit && info.dpl !== info.rpl)
  1750. {
  1751. dbg_log("cs non-conforming and dpl != rpl: " + h(selector), LOG_CPU);
  1752. this.trigger_gp(selector & ~3);
  1753. }
  1754. if(!info.is_present)
  1755. {
  1756. dbg_log("#NP for loading not-present in cs sel=" + h(selector, 4), LOG_CPU);
  1757. dbg_trace(LOG_CPU);
  1758. this.trigger_np(selector & ~3);
  1759. }
  1760. if(info.rpl > this.cpl[0])
  1761. {
  1762. dbg_log("far return privilege change cs: " + h(selector) + " from=" + this.cpl[0] + " to=" + info.rpl + " is_16=" + this.is_osize_32(), LOG_CPU);
  1763. if(this.is_osize_32())
  1764. {
  1765. //dbg_log("esp read from " + h(this.translate_address_system_read(this.get_stack_pointer(stack_adjust + 8))))
  1766. var temp_esp = this.safe_read32s(this.get_stack_pointer(stack_adjust + 8));
  1767. //dbg_log("esp=" + h(temp_esp));
  1768. var temp_ss = this.safe_read16(this.get_stack_pointer(stack_adjust + 12));
  1769. }
  1770. else
  1771. {
  1772. //dbg_log("esp read from " + h(this.translate_address_system_read(this.get_stack_pointer(stack_adjust + 4))));
  1773. var temp_esp = this.safe_read16(this.get_stack_pointer(stack_adjust + 4));
  1774. //dbg_log("esp=" + h(temp_esp));
  1775. var temp_ss = this.safe_read16(this.get_stack_pointer(stack_adjust + 6));
  1776. }
  1777. this.cpl[0] = info.rpl;
  1778. this.cpl_changed();
  1779. // XXX: Can raise, conditions should be checked before side effects
  1780. this.switch_seg(reg_ss, temp_ss);
  1781. this.set_stack_reg(temp_esp + stack_adjust);
  1782. //if(this.is_osize_32())
  1783. //{
  1784. // this.adjust_stack_reg(2 * 4);
  1785. //}
  1786. //else
  1787. //{
  1788. // this.adjust_stack_reg(2 * 2);
  1789. //}
  1790. //throw this.debug.unimpl("privilege change");
  1791. //this.adjust_stack_reg(stack_adjust);
  1792. }
  1793. else
  1794. {
  1795. if(this.is_osize_32())
  1796. {
  1797. this.adjust_stack_reg(2 * 4 + stack_adjust);
  1798. }
  1799. else
  1800. {
  1801. this.adjust_stack_reg(2 * 2 + stack_adjust);
  1802. }
  1803. }
  1804. //dbg_assert(this.cpl[0] === info.dpl);
  1805. this.update_cs_size(info.size);
  1806. this.segment_is_null[reg_cs] = 0;
  1807. this.segment_limits[reg_cs] = info.effective_limit;
  1808. //this.segment_infos[reg_cs] = 0; // TODO
  1809. this.segment_offsets[reg_cs] = info.base;
  1810. this.sreg[reg_cs] = selector;
  1811. dbg_assert((selector & 3) === this.cpl[0]);
  1812. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1813. //dbg_log("far return to:", LOG_CPU)
  1814. CPU_LOG_VERBOSE && this.debug.dump_state("far ret end");
  1815. };
  1816. CPU.prototype.far_jump = function(eip, selector, is_call)
  1817. {
  1818. is_call = !!is_call;
  1819. dbg_assert(typeof selector === "number" && selector < 0x10000 && selector >= 0);
  1820. //dbg_log("far " + ["jump", "call"][+is_call] + " eip=" + h(eip >>> 0, 8) + " cs=" + h(selector, 4), LOG_CPU);
  1821. CPU_LOG_VERBOSE && this.debug.dump_state("far " + ["jump", "call"][+is_call]);
  1822. if(!this.protected_mode[0] || this.vm86_mode())
  1823. {
  1824. if(is_call)
  1825. {
  1826. if(this.is_osize_32())
  1827. {
  1828. this.writable_or_pagefault(this.get_stack_pointer(-8), 8);
  1829. this.push32(this.sreg[reg_cs]);
  1830. this.push32(this.get_real_eip());
  1831. }
  1832. else
  1833. {
  1834. this.writable_or_pagefault(this.get_stack_pointer(-4), 4);
  1835. this.push16(this.sreg[reg_cs]);
  1836. this.push16(this.get_real_eip());
  1837. }
  1838. }
  1839. this.switch_cs_real_mode(selector);
  1840. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  1841. return;
  1842. }
  1843. var info = this.lookup_segment_selector(selector);
  1844. if(info.is_null)
  1845. {
  1846. dbg_log("#gp null cs", LOG_CPU);
  1847. this.trigger_gp(0);
  1848. }
  1849. if(!info.is_valid)
  1850. {
  1851. dbg_log("#gp invalid cs: " + h(selector), LOG_CPU);
  1852. this.trigger_gp(selector & ~3);
  1853. }
  1854. if(info.is_system)
  1855. {
  1856. dbg_assert(is_call, "TODO: Jump");
  1857. dbg_log("system type cs: " + h(selector), LOG_CPU);
  1858. if(info.type === 0xC || info.type === 4)
  1859. {
  1860. // call gate
  1861. var is_16 = info.type === 4;
  1862. if(info.dpl < this.cpl[0] || info.dpl < info.rpl)
  1863. {
  1864. dbg_log("#gp cs gate dpl < cpl or dpl < rpl: " + h(selector), LOG_CPU);
  1865. this.trigger_gp(selector & ~3);
  1866. }
  1867. if(!info.is_present)
  1868. {
  1869. dbg_log("#NP for loading not-present in gate cs sel=" + h(selector, 4), LOG_CPU);
  1870. this.trigger_np(selector & ~3);
  1871. }
  1872. var cs_selector = info.raw0 >>> 16;
  1873. var cs_info = this.lookup_segment_selector(cs_selector);
  1874. if(cs_info.is_null)
  1875. {
  1876. dbg_log("#gp null cs", LOG_CPU);
  1877. this.trigger_gp(0);
  1878. }
  1879. if(!cs_info.is_valid)
  1880. {
  1881. dbg_log("#gp invalid cs: " + h(cs_selector), LOG_CPU);
  1882. this.trigger_gp(cs_selector & ~3);
  1883. }
  1884. if(!cs_info.is_executable)
  1885. {
  1886. dbg_log("#gp non-executable cs: " + h(cs_selector), LOG_CPU);
  1887. this.trigger_gp(cs_selector & ~3);
  1888. }
  1889. if(cs_info.dpl > this.cpl[0])
  1890. {
  1891. dbg_log("#gp dpl > cpl: " + h(cs_selector), LOG_CPU);
  1892. this.trigger_gp(cs_selector & ~3);
  1893. }
  1894. if(!cs_info.is_present)
  1895. {
  1896. dbg_log("#NP for loading not-present in cs sel=" + h(cs_selector, 4), LOG_CPU);
  1897. this.trigger_np(cs_selector & ~3);
  1898. }
  1899. if(!cs_info.dc_bit && cs_info.dpl < this.cpl[0])
  1900. {
  1901. dbg_log("more privilege call gate is_16=" + is_16 + " from=" + this.cpl[0] + " to=" + cs_info.dpl);
  1902. var tss_stack_addr = this.get_tss_stack_addr(cs_info.dpl);
  1903. if(this.tss_size_32)
  1904. {
  1905. var new_esp = this.read32s(tss_stack_addr);
  1906. var new_ss = this.read16(tss_stack_addr + 4 | 0);
  1907. }
  1908. else
  1909. {
  1910. var new_esp = this.read16(tss_stack_addr);
  1911. var new_ss = this.read16(tss_stack_addr + 2 | 0);
  1912. }
  1913. var ss_info = this.lookup_segment_selector(new_ss);
  1914. // Disabled: Incorrect handling of direction bit
  1915. // See http://css.csail.mit.edu/6.858/2014/readings/i386/s06_03.htm
  1916. //if(!((new_esp >>> 0) <= ss_info.effective_limit))
  1917. // debugger;
  1918. //dbg_assert((new_esp >>> 0) <= ss_info.effective_limit);
  1919. dbg_assert(ss_info.is_valid && !ss_info.is_system && ss_info.is_writable);
  1920. if(ss_info.is_null)
  1921. {
  1922. throw this.debug.unimpl("#TS handler");
  1923. }
  1924. if(ss_info.rpl !== cs_info.dpl) // xxx: 0 in v86 mode
  1925. {
  1926. throw this.debug.unimpl("#TS handler");
  1927. }
  1928. if(ss_info.dpl !== cs_info.dpl || !ss_info.rw_bit)
  1929. {
  1930. throw this.debug.unimpl("#TS handler");
  1931. }
  1932. if(!ss_info.is_present)
  1933. {
  1934. throw this.debug.unimpl("#SS handler");
  1935. }
  1936. var parameter_count = info.raw1 & 0x1F;
  1937. var stack_space = is_16 ? 4 : 8;
  1938. if(is_call)
  1939. {
  1940. stack_space += is_16 ? 4 + 2 * parameter_count : 8 + 4 * parameter_count;
  1941. }
  1942. if(ss_info.size)
  1943. {
  1944. //try {
  1945. this.writable_or_pagefault(ss_info.base + new_esp - stack_space | 0, stack_space); // , cs_info.dpl
  1946. //} catch(e) { debugger; }
  1947. }
  1948. else
  1949. {
  1950. //try {
  1951. this.writable_or_pagefault(ss_info.base + (new_esp - stack_space & 0xFFFF) | 0, stack_space); // , cs_info.dpl
  1952. //} catch(e) { debugger; }
  1953. }
  1954. var old_esp = this.reg32s[reg_esp];
  1955. var old_ss = this.sreg[reg_ss];
  1956. var old_stack_pointer = this.get_stack_pointer(0);
  1957. //dbg_log("old_esp=" + h(old_esp));
  1958. this.cpl[0] = cs_info.dpl;
  1959. this.cpl_changed();
  1960. this.update_cs_size(cs_info.size);
  1961. this.switch_seg(reg_ss, new_ss);
  1962. this.set_stack_reg(new_esp);
  1963. //dbg_log("parameter_count=" + parameter_count);
  1964. //dbg_assert(parameter_count === 0, "TODO");
  1965. if(is_16)
  1966. {
  1967. this.push16(old_ss);
  1968. this.push16(old_esp);
  1969. //dbg_log("old esp written to " + h(this.translate_address_system_read(this.get_stack_pointer(0))));
  1970. }
  1971. else
  1972. {
  1973. this.push32(old_ss);
  1974. this.push32(old_esp);
  1975. //dbg_log("old esp written to " + h(this.translate_address_system_read(this.get_stack_pointer(0))));
  1976. }
  1977. if(is_call)
  1978. {
  1979. if(is_16)
  1980. {
  1981. for(var i = parameter_count - 1; i >= 0; i--)
  1982. {
  1983. var parameter = this.safe_read16(old_stack_pointer + 2 * i);
  1984. this.push16(parameter);
  1985. }
  1986. //this.writable_or_pagefault(this.get_stack_pointer(-4), 4);
  1987. this.push16(this.sreg[reg_cs]);
  1988. this.push16(this.get_real_eip());
  1989. }
  1990. else
  1991. {
  1992. for(var i = parameter_count - 1; i >= 0; i--)
  1993. {
  1994. var parameter = this.safe_read32s(old_stack_pointer + 4 * i);
  1995. this.push32(parameter);
  1996. }
  1997. //this.writable_or_pagefault(this.get_stack_pointer(-8), 8);
  1998. this.push32(this.sreg[reg_cs]);
  1999. this.push32(this.get_real_eip());
  2000. }
  2001. }
  2002. }
  2003. else
  2004. {
  2005. dbg_log("same privilege call gate is_16=" + is_16 + " from=" + this.cpl[0] + " to=" + cs_info.dpl + " conforming=" + cs_info.dc_bit);
  2006. // ok
  2007. if(is_call)
  2008. {
  2009. if(is_16)
  2010. {
  2011. this.writable_or_pagefault(this.get_stack_pointer(-4), 4);
  2012. this.push16(this.sreg[reg_cs]);
  2013. this.push16(this.get_real_eip());
  2014. }
  2015. else
  2016. {
  2017. this.writable_or_pagefault(this.get_stack_pointer(-8), 8);
  2018. this.push32(this.sreg[reg_cs]);
  2019. this.push32(this.get_real_eip());
  2020. }
  2021. }
  2022. }
  2023. // Note: eip from call is ignored
  2024. var new_eip = info.raw0 & 0xFFFF;
  2025. if(!is_16)
  2026. {
  2027. new_eip |= info.raw1 & 0xFFFF0000;
  2028. }
  2029. dbg_log("call gate eip=" + h(new_eip >>> 0) + " cs=" + h(cs_selector) + " conforming=" + cs_info.dc_bit);
  2030. dbg_assert((new_eip >>> 0) <= cs_info.effective_limit, "todo: #gp");
  2031. this.update_cs_size(cs_info.size);
  2032. this.segment_is_null[reg_cs] = 0;
  2033. this.segment_limits[reg_cs] = cs_info.effective_limit;
  2034. //this.segment_infos[reg_cs] = 0; // TODO
  2035. this.segment_offsets[reg_cs] = cs_info.base;
  2036. this.sreg[reg_cs] = cs_selector & ~3 | this.cpl[0];
  2037. dbg_assert((this.sreg[reg_cs] & 3) === this.cpl[0]);
  2038. this.instruction_pointer[0] = this.get_seg(reg_cs) + new_eip | 0;
  2039. }
  2040. else
  2041. {
  2042. var types = { 9: "Available 386 TSS", 0xb: "Busy 386 TSS", 4: "286 Call Gate", 0xc: "386 Call Gate" };
  2043. throw this.debug.unimpl("load system segment descriptor, type = " + (info.access & 15) + " (" + types[info.access & 15] + ")");
  2044. }
  2045. }
  2046. else
  2047. {
  2048. if(!info.is_executable)
  2049. {
  2050. dbg_log("#gp non-executable cs: " + h(selector), LOG_CPU);
  2051. this.trigger_gp(selector & ~3);
  2052. }
  2053. if(info.dc_bit)
  2054. {
  2055. // conforming code segment
  2056. if(info.dpl > this.cpl[0])
  2057. {
  2058. dbg_log("#gp cs dpl > cpl: " + h(selector), LOG_CPU);
  2059. this.trigger_gp(selector & ~3);
  2060. }
  2061. }
  2062. else
  2063. {
  2064. // non-conforming code segment
  2065. if(info.rpl > this.cpl[0] || info.dpl !== this.cpl[0])
  2066. {
  2067. dbg_log("#gp cs rpl > cpl or dpl != cpl: " + h(selector), LOG_CPU);
  2068. this.trigger_gp(selector & ~3);
  2069. }
  2070. }
  2071. if(!info.is_present)
  2072. {
  2073. dbg_log("#NP for loading not-present in cs sel=" + h(selector, 4), LOG_CPU);
  2074. dbg_trace(LOG_CPU);
  2075. this.trigger_np(selector & ~3);
  2076. }
  2077. if(is_call)
  2078. {
  2079. if(this.is_osize_32())
  2080. {
  2081. this.writable_or_pagefault(this.get_stack_pointer(-8), 8);
  2082. this.push32(this.sreg[reg_cs]);
  2083. this.push32(this.get_real_eip());
  2084. }
  2085. else
  2086. {
  2087. this.writable_or_pagefault(this.get_stack_pointer(-4), 4);
  2088. this.push16(this.sreg[reg_cs]);
  2089. this.push16(this.get_real_eip());
  2090. }
  2091. }
  2092. dbg_assert((eip >>> 0) <= info.effective_limit, "todo: #gp");
  2093. this.update_cs_size(info.size);
  2094. this.segment_is_null[reg_cs] = 0;
  2095. this.segment_limits[reg_cs] = info.effective_limit;
  2096. //this.segment_infos[reg_cs] = 0; // TODO
  2097. this.segment_offsets[reg_cs] = info.base;
  2098. this.sreg[reg_cs] = selector & ~3 | this.cpl[0];
  2099. this.instruction_pointer[0] = this.get_seg(reg_cs) + eip | 0;
  2100. }
  2101. //dbg_log("far " + ["jump", "call"][+is_call] + " to:", LOG_CPU)
  2102. CPU_LOG_VERBOSE && this.debug.dump_state("far " + ["jump", "call"][+is_call] + " end");
  2103. };
  2104. CPU.prototype.get_tss_stack_addr = function(dpl)
  2105. {
  2106. if(this.tss_size_32)
  2107. {
  2108. var tss_stack_addr = (dpl << 3) + 4 | 0;
  2109. if((tss_stack_addr + 5 | 0) > this.segment_limits[reg_tr])
  2110. {
  2111. throw this.debug.unimpl("#TS handler");
  2112. }
  2113. tss_stack_addr = tss_stack_addr + this.segment_offsets[reg_tr] | 0;
  2114. dbg_assert((tss_stack_addr & 0xFFF) <= 0x1000 - 6);
  2115. }
  2116. else
  2117. {
  2118. var tss_stack_addr = (dpl << 2) + 2 | 0;
  2119. if((tss_stack_addr + 5 | 0) > this.segment_limits[reg_tr])
  2120. {
  2121. throw this.debug.unimpl("#TS handler");
  2122. }
  2123. tss_stack_addr = tss_stack_addr + this.segment_offsets[reg_tr] | 0;
  2124. dbg_assert((tss_stack_addr & 0xFFF) <= 0x1000 - 4);
  2125. }
  2126. if(this.paging[0])
  2127. {
  2128. tss_stack_addr = this.translate_address_system_read(tss_stack_addr);
  2129. }
  2130. return tss_stack_addr;
  2131. };
  2132. CPU.prototype.do_task_switch = function(selector, error_code)
  2133. {
  2134. dbg_assert(this.tss_size_32, "TODO");
  2135. dbg_log("do_task_switch sel=" + h(selector), LOG_CPU);
  2136. var descriptor = this.lookup_segment_selector(selector);
  2137. dbg_assert((descriptor.type | 2) === 3 || (descriptor.type | 2) === 0xb);
  2138. var tss_is_16 = descriptor.type <= 3;
  2139. var tss_is_busy = (descriptor.type & 2) === 2;
  2140. if(!descriptor.is_valid || descriptor.is_null || !descriptor.from_gdt)
  2141. {
  2142. throw this.debug.unimpl("#GP handler");
  2143. }
  2144. if((descriptor.access & 31) === 0xB)
  2145. {
  2146. // is busy
  2147. throw this.debug.unimpl("#GP handler");
  2148. }
  2149. if(!descriptor.is_present)
  2150. {
  2151. throw this.debug.unimpl("#NP handler");
  2152. }
  2153. if(descriptor.effective_limit < 103)
  2154. {
  2155. throw this.debug.unimpl("#NP handler");
  2156. }
  2157. var tsr_size = this.segment_limits[reg_tr];
  2158. var tsr_offset = this.segment_offsets[reg_tr];
  2159. var old_eflags = this.get_eflags();
  2160. if(tss_is_busy)
  2161. {
  2162. old_eflags &= ~flag_nt;
  2163. }
  2164. this.writable_or_pagefault(tsr_offset, 0x66);
  2165. //this.safe_write32(tsr_offset + TSR_CR3, this.cr[3]);
  2166. // TODO: Write 16 bit values if old tss is 16 bit
  2167. this.safe_write32(tsr_offset + TSR_EIP, this.get_real_eip());
  2168. this.safe_write32(tsr_offset + TSR_EFLAGS, old_eflags);
  2169. this.safe_write32(tsr_offset + TSR_EAX, this.reg32s[reg_eax]);
  2170. this.safe_write32(tsr_offset + TSR_ECX, this.reg32s[reg_ecx]);
  2171. this.safe_write32(tsr_offset + TSR_EDX, this.reg32s[reg_edx]);
  2172. this.safe_write32(tsr_offset + TSR_EBX, this.reg32s[reg_ebx]);
  2173. this.safe_write32(tsr_offset + TSR_ESP, this.reg32s[reg_esp]);
  2174. this.safe_write32(tsr_offset + TSR_EBP, this.reg32s[reg_ebp]);
  2175. this.safe_write32(tsr_offset + TSR_ESI, this.reg32s[reg_esi]);
  2176. this.safe_write32(tsr_offset + TSR_EDI, this.reg32s[reg_edi]);
  2177. this.safe_write32(tsr_offset + TSR_ES, this.sreg[reg_es]);
  2178. this.safe_write32(tsr_offset + TSR_CS, this.sreg[reg_cs]);
  2179. this.safe_write32(tsr_offset + TSR_SS, this.sreg[reg_ss]);
  2180. this.safe_write32(tsr_offset + TSR_DS, this.sreg[reg_ds]);
  2181. this.safe_write32(tsr_offset + TSR_FS, this.sreg[reg_fs]);
  2182. this.safe_write32(tsr_offset + TSR_GS, this.sreg[reg_gs]);
  2183. //this.safe_write32(tsr_offset + TSR_LDT, this.sreg[reg_ldtr]);
  2184. if(true /* is jump or call or int */)
  2185. {
  2186. // mark as busy
  2187. this.write8(descriptor.table_offset + 5 | 0, this.read8(descriptor.table_offset + 5 | 0) | 2);
  2188. }
  2189. //var new_tsr_size = descriptor.effective_limit;
  2190. var new_tsr_offset = descriptor.base;
  2191. dbg_assert(!tss_is_16, "unimplemented");
  2192. if(true /* is call or int */)
  2193. {
  2194. this.safe_write16(new_tsr_offset + TSR_BACKLINK, this.sreg[reg_tr]);
  2195. }
  2196. var new_cr3 = this.safe_read32s(new_tsr_offset + TSR_CR3);
  2197. this.flags[0] &= ~flag_vm;
  2198. var new_eip = this.safe_read32s(new_tsr_offset + TSR_EIP);
  2199. var new_cs = this.safe_read16(new_tsr_offset + TSR_CS);
  2200. var info = this.lookup_segment_selector(new_cs);
  2201. if(info.is_null)
  2202. {
  2203. dbg_log("null cs", LOG_CPU);
  2204. throw this.debug.unimpl("#TS handler");
  2205. }
  2206. if(!info.is_valid)
  2207. {
  2208. dbg_log("invalid cs: " + h(selector), LOG_CPU);
  2209. throw this.debug.unimpl("#TS handler");
  2210. }
  2211. if(info.is_system)
  2212. {
  2213. throw this.debug.unimpl("#TS handler");
  2214. }
  2215. if(!info.is_executable)
  2216. {
  2217. throw this.debug.unimpl("#TS handler");
  2218. }
  2219. if(info.dc_bit && info.dpl > info.rpl)
  2220. {
  2221. dbg_log("cs conforming and dpl > rpl: " + h(selector), LOG_CPU);
  2222. throw this.debug.unimpl("#TS handler");
  2223. }
  2224. if(!info.dc_bit && info.dpl !== info.rpl)
  2225. {
  2226. dbg_log("cs non-conforming and dpl != rpl: " + h(selector), LOG_CPU);
  2227. throw this.debug.unimpl("#TS handler");
  2228. }
  2229. if(!info.is_present)
  2230. {
  2231. dbg_log("#NP for loading not-present in cs sel=" + h(selector, 4), LOG_CPU);
  2232. throw this.debug.unimpl("#TS handler");
  2233. }
  2234. this.segment_is_null[reg_cs] = 0;
  2235. this.segment_limits[reg_cs] = info.effective_limit;
  2236. this.segment_offsets[reg_cs] = info.base;
  2237. this.sreg[reg_cs] = new_cs;
  2238. this.cpl = info.dpl;
  2239. this.cpl_changed();
  2240. dbg_assert((this.sreg[reg_cs] & 3) === this.cpl);
  2241. dbg_assert((new_eip >>> 0) <= info.effective_limit, "todo: #gp");
  2242. this.update_cs_size(info.size);
  2243. var new_eflags = this.safe_read32s(new_tsr_offset + TSR_EFLAGS);
  2244. if(true /* is call or int */)
  2245. {
  2246. this.safe_write32(tsr_offset + TSR_BACKLINK, selector);
  2247. new_eflags |= flag_nt;
  2248. }
  2249. if(new_eflags & flag_vm)
  2250. {
  2251. throw this.debug.unimpl("task switch to VM mode");
  2252. }
  2253. this.update_eflags(new_eflags);
  2254. if(true /* call or int */)
  2255. {
  2256. this.flags[0] |= flag_nt;
  2257. }
  2258. var new_ldt = this.safe_read16(new_tsr_offset + TSR_LDT);
  2259. this.load_ldt(new_ldt);
  2260. this.reg32s[reg_eax] = this.safe_read32s(new_tsr_offset + TSR_EAX);
  2261. this.reg32s[reg_ecx] = this.safe_read32s(new_tsr_offset + TSR_ECX);
  2262. this.reg32s[reg_edx] = this.safe_read32s(new_tsr_offset + TSR_EDX);
  2263. this.reg32s[reg_ebx] = this.safe_read32s(new_tsr_offset + TSR_EBX);
  2264. this.reg32s[reg_esp] = this.safe_read32s(new_tsr_offset + TSR_ESP);
  2265. this.reg32s[reg_ebp] = this.safe_read32s(new_tsr_offset + TSR_EBP);
  2266. this.reg32s[reg_esi] = this.safe_read32s(new_tsr_offset + TSR_ESI);
  2267. this.reg32s[reg_edi] = this.safe_read32s(new_tsr_offset + TSR_EDI);
  2268. this.switch_seg(reg_es, this.safe_read16(new_tsr_offset + TSR_ES));
  2269. this.switch_seg(reg_ss, this.safe_read16(new_tsr_offset + TSR_SS));
  2270. this.switch_seg(reg_ds, this.safe_read16(new_tsr_offset + TSR_DS));
  2271. this.switch_seg(reg_fs, this.safe_read16(new_tsr_offset + TSR_FS));
  2272. this.switch_seg(reg_gs, this.safe_read16(new_tsr_offset + TSR_GS));
  2273. this.instruction_pointer[0] = this.get_seg(reg_cs) + new_eip | 0;
  2274. this.segment_offsets[reg_tr] = descriptor.base;
  2275. this.segment_limits[reg_tr] = descriptor.effective_limit;
  2276. this.sreg[reg_tr] = selector;
  2277. this.cr[3] = new_cr3;
  2278. dbg_assert((this.cr[3] & 0xFFF) === 0);
  2279. this.clear_tlb();
  2280. this.cr[0] |= CR0_TS;
  2281. if(error_code !== false)
  2282. {
  2283. if(tss_is_16)
  2284. {
  2285. this.push16(error_code & 0xFFFF);
  2286. }
  2287. else
  2288. {
  2289. this.push32(error_code);
  2290. }
  2291. }
  2292. };
  2293. CPU.prototype.hlt_op = function()
  2294. {
  2295. if(this.cpl[0])
  2296. {
  2297. dbg_log("#gp hlt with cpl != 0", LOG_CPU);
  2298. this.trigger_gp(0);
  2299. }
  2300. if((this.flags[0] & flag_interrupt) === 0)
  2301. {
  2302. // execution can never resume (until NMIs are supported)
  2303. this.bus.send("cpu-event-halt");
  2304. }
  2305. // get out of here and into hlt_loop
  2306. this.in_hlt = true;
  2307. //if(false) // possibly unsafe, test in safari
  2308. //{
  2309. // this.hlt_loop();
  2310. // this.diverged();
  2311. // if(this.in_hlt)
  2312. // {
  2313. // throw MAGIC_CPU_EXCEPTION;
  2314. // }
  2315. //}
  2316. //else
  2317. {
  2318. throw MAGIC_CPU_EXCEPTION;
  2319. }
  2320. };
  2321. CPU.prototype.todo = function()
  2322. {
  2323. if(DEBUG)
  2324. {
  2325. dbg_trace();
  2326. throw "TODO";
  2327. }
  2328. this.trigger_ud();
  2329. };
  2330. CPU.prototype.undefined_instruction = function()
  2331. {
  2332. dbg_assert(false, "Possible fault: undefined instruction");
  2333. this.trigger_ud();
  2334. };
  2335. CPU.prototype.unimplemented_sse = function()
  2336. {
  2337. dbg_log("No SSE", LOG_CPU);
  2338. dbg_assert(false);
  2339. this.trigger_ud();
  2340. };
  2341. CPU.prototype.pic_call_irq = function(int)
  2342. {
  2343. //dbg_log("pic_call_irq", LOG_CPU);
  2344. try
  2345. {
  2346. this.previous_ip[0] = this.instruction_pointer[0];
  2347. this.call_interrupt_vector(int, false, false, 0);
  2348. //dbg_log("to " + h(this.instruction_pointer[0] >>> 0), LOG_CPU);
  2349. }
  2350. catch(e)
  2351. {
  2352. this.exception_cleanup(e);
  2353. }
  2354. };
  2355. CPU.prototype.handle_irqs = function()
  2356. {
  2357. dbg_assert(!this.page_fault[0]);
  2358. //dbg_assert(this.prefixes[0] === 0);
  2359. this.diverged();
  2360. if((this.flags[0] & flag_interrupt) && !this.page_fault[0])
  2361. {
  2362. if(this.devices.pic)
  2363. {
  2364. this.devices.pic.acknowledge_irq();
  2365. }
  2366. if(this.devices.apic)
  2367. {
  2368. this.devices.apic.acknowledge_irq();
  2369. }
  2370. }
  2371. };
  2372. CPU.prototype.device_raise_irq = function(i)
  2373. {
  2374. dbg_assert(arguments.length === 1);
  2375. if(this.devices.pic)
  2376. {
  2377. this.devices.pic.set_irq(i);
  2378. }
  2379. if(this.devices.ioapic)
  2380. {
  2381. this.devices.ioapic.set_irq(i);
  2382. }
  2383. };
  2384. CPU.prototype.device_lower_irq = function(i)
  2385. {
  2386. if(this.devices.pic)
  2387. {
  2388. this.devices.pic.clear_irq(i);
  2389. }
  2390. if(this.devices.ioapic)
  2391. {
  2392. this.devices.ioapic.clear_irq(i);
  2393. }
  2394. };
  2395. CPU.prototype.test_privileges_for_io = function(port, size)
  2396. {
  2397. if(this.protected_mode[0] && (this.cpl[0] > this.getiopl() || (this.flags[0] & flag_vm)))
  2398. {
  2399. if(!this.tss_size_32)
  2400. {
  2401. dbg_log("#GP for port io, 16-bit TSS port=" + h(port) + " size=" + size, LOG_CPU);
  2402. CPU_LOG_VERBOSE && this.debug.dump_state();
  2403. this.trigger_gp(0);
  2404. }
  2405. var tsr_size = this.segment_limits[reg_tr];
  2406. var tsr_offset = this.segment_offsets[reg_tr];
  2407. if(tsr_size >= 0x67)
  2408. {
  2409. dbg_assert((tsr_offset + 0x64 + 2 & 0xFFF) < 0xFFF);
  2410. var iomap_base = this.read16(this.translate_address_system_read(tsr_offset + 0x64 + 2 | 0)),
  2411. high_port = port + size - 1 | 0;
  2412. if(tsr_size >= (iomap_base + (high_port >> 3) | 0))
  2413. {
  2414. var mask = ((1 << size) - 1) << (port & 7),
  2415. addr = this.translate_address_system_read(tsr_offset + iomap_base + (port >> 3) | 0),
  2416. port_info = (mask & 0xFF00) ?
  2417. this.read16(addr) : this.read8(addr);
  2418. dbg_assert((addr & 0xFFF) < 0xFFF);
  2419. if(!(port_info & mask))
  2420. {
  2421. return;
  2422. }
  2423. }
  2424. }
  2425. dbg_log("#GP for port io port=" + h(port) + " size=" + size, LOG_CPU);
  2426. CPU_LOG_VERBOSE && this.debug.dump_state();
  2427. this.trigger_gp(0);
  2428. }
  2429. };
  2430. CPU.prototype.cpuid = function()
  2431. {
  2432. // cpuid
  2433. // TODO: Fill in with less bogus values
  2434. // http://lxr.linux.no/linux+%2a/arch/x86/include/asm/cpufeature.h
  2435. // http://www.sandpile.org/x86/cpuid.htm
  2436. var eax = 0;
  2437. var ecx = 0;
  2438. var edx = 0;
  2439. var ebx = 0;
  2440. const winnt_fix = false;
  2441. const level = this.reg32s[reg_eax];
  2442. switch(level)
  2443. {
  2444. case 0:
  2445. // maximum supported level
  2446. if(winnt_fix)
  2447. {
  2448. eax = 2;
  2449. }
  2450. else
  2451. {
  2452. eax = 0x16;
  2453. }
  2454. ebx = 0x756E6547|0; // Genu
  2455. edx = 0x49656E69|0; // ineI
  2456. ecx = 0x6C65746E|0; // ntel
  2457. break;
  2458. case 1:
  2459. // pentium
  2460. eax = 3 | 6 << 4 | 15 << 8;
  2461. ebx = 1 << 16 | 8 << 8; // cpu count, clflush size
  2462. ecx = 1 << 23 | 1 << 30; // popcnt, rdrand
  2463. var vme = 0 << 1;
  2464. if(VMWARE_HYPERVISOR_PORT) ecx |= 1 << 31; // hypervisor
  2465. edx = (true /* have fpu */ ? 1 : 0) | // fpu
  2466. vme | 1 << 3 | 1 << 4 | 1 << 5 | // vme, pse, tsc, msr
  2467. 1 << 8 | 1 << 11 | 1 << 13 | 1 << 15 | // cx8, sep, pge, cmov
  2468. 1 << 23 | 1 << 24 | 1 << 25 | 1 << 26; // mmx, fxsr, sse1, sse2
  2469. if(ENABLE_ACPI && this.apic_enabled)
  2470. {
  2471. edx |= 1 << 9; // apic
  2472. }
  2473. break;
  2474. case 2:
  2475. // Taken from http://siyobik.info.gf/main/reference/instruction/CPUID
  2476. eax = 0x665B5001|0;
  2477. ebx = 0;
  2478. ecx = 0;
  2479. edx = 0x007A7000;
  2480. break;
  2481. case 4:
  2482. // from my local machine
  2483. switch(this.reg32s[reg_ecx])
  2484. {
  2485. case 0:
  2486. eax = 0x00000121;
  2487. ebx = 0x01c0003f;
  2488. ecx = 0x0000003f;
  2489. edx = 0x00000001;
  2490. break;
  2491. case 1:
  2492. eax = 0x00000122;
  2493. ebx = 0x01c0003f;
  2494. ecx = 0x0000003f;
  2495. edx = 0x00000001;
  2496. break;
  2497. case 2:
  2498. eax = 0x00000143;
  2499. ebx = 0x05c0003f;
  2500. ecx = 0x00000fff;
  2501. edx = 0x00000001;
  2502. break;
  2503. }
  2504. break;
  2505. case 5:
  2506. // from my local machine
  2507. eax = 0x40;
  2508. ebx = 0x40;
  2509. ecx = 3;
  2510. edx = 0x00142120;
  2511. break;
  2512. case 7:
  2513. eax = 0; // maximum supported sub-level
  2514. ebx = 1 << 9; // enhanced REP MOVSB/STOSB
  2515. ecx = 0;
  2516. edx = 0;
  2517. break;
  2518. case 0x80000000|0:
  2519. // maximum supported extended level
  2520. eax = 5;
  2521. // other registers are reserved
  2522. break;
  2523. case 0x40000000|0: // hypervisor
  2524. if(VMWARE_HYPERVISOR_PORT)
  2525. {
  2526. // h("Ware".split("").reduce((a, c, i) => a | c.charCodeAt(0) << i * 8, 0))
  2527. ebx = 0x61774D56|0; // VMwa
  2528. ecx = 0x4D566572|0; // reVM
  2529. edx = 0x65726177|0; // ware
  2530. }
  2531. break;
  2532. case 0x15:
  2533. eax = 1; // denominator
  2534. ebx = 1; // numerator
  2535. ecx = TSC_RATE * 1000; // core crystal clock frequency in Hz
  2536. // (TSC frequency = core crystal clock frequency * EBX/EAX)
  2537. break;
  2538. case 0x16:
  2539. eax = Math.floor(TSC_RATE / 1000); // core base frequency in MHz
  2540. ebx = Math.floor(TSC_RATE / 1000); // core maximum frequency in MHz
  2541. ecx = 10; // bus (reference) frequency in MHz
  2542. break;
  2543. default:
  2544. dbg_log("cpuid: unimplemented eax: " + h(this.reg32[reg_eax]), LOG_CPU);
  2545. }
  2546. if(level === 4)
  2547. {
  2548. dbg_log("cpuid: eax=" + h(this.reg32[reg_eax], 8) + " cl=" + h(this.reg8[reg_cl], 2), LOG_CPU);
  2549. }
  2550. else if(level !== 0 && level !== 2 && level !== (0x80000000 | 0))
  2551. {
  2552. dbg_log("cpuid: eax=" + h(this.reg32[reg_eax], 8), LOG_CPU);
  2553. }
  2554. this.reg32s[reg_eax] = eax;
  2555. this.reg32s[reg_ecx] = ecx;
  2556. this.reg32s[reg_edx] = edx;
  2557. this.reg32s[reg_ebx] = ebx;
  2558. };
  2559. CPU.prototype.update_cs_size = function(new_size)
  2560. {
  2561. new_size = Boolean(new_size);
  2562. if(Boolean(this.is_32[0]) !== new_size)
  2563. {
  2564. //dbg_log("clear instruction cache", LOG_CPU);
  2565. //this.jit_empty_cache();
  2566. this.is_32[0] = +new_size;
  2567. this.update_operand_size();
  2568. }
  2569. };
  2570. CPU.prototype.update_operand_size = function() {};
  2571. /**
  2572. * @param {number} selector
  2573. */
  2574. CPU.prototype.lookup_segment_selector = function(selector)
  2575. {
  2576. dbg_assert(typeof selector === "number" && selector >= 0 && selector < 0x10000);
  2577. var is_gdt = (selector & 4) === 0,
  2578. selector_offset = selector & ~7,
  2579. info,
  2580. table_offset,
  2581. table_limit;
  2582. info = {
  2583. rpl: selector & 3,
  2584. from_gdt: is_gdt,
  2585. is_null: false,
  2586. is_valid: true,
  2587. base: 0,
  2588. access: 0,
  2589. flags: 0,
  2590. type: 0,
  2591. dpl: 0,
  2592. is_system: false,
  2593. is_present: false,
  2594. is_executable: false,
  2595. rw_bit: false,
  2596. dc_bit: false,
  2597. size: false,
  2598. is_conforming_executable: false,
  2599. // limit after applying granularity
  2600. effective_limit: 0,
  2601. is_writable: false,
  2602. is_readable: false,
  2603. table_offset: 0,
  2604. raw0: 0,
  2605. raw1: 0,
  2606. };
  2607. if(is_gdt)
  2608. {
  2609. table_offset = this.gdtr_offset[0];
  2610. table_limit = this.gdtr_size[0];
  2611. }
  2612. else
  2613. {
  2614. table_offset = this.segment_offsets[reg_ldtr];
  2615. table_limit = this.segment_limits[reg_ldtr];
  2616. }
  2617. if(is_gdt && selector_offset === 0)
  2618. {
  2619. info.is_null = true;
  2620. return info;
  2621. }
  2622. // limit is the number of entries in the table minus one
  2623. if((selector | 7) > table_limit)
  2624. {
  2625. dbg_log("Selector " + h(selector, 4) + " is outside of the " +
  2626. (is_gdt ? "g" : "l") + "dt limits", LOG_CPU);
  2627. info.is_valid = false;
  2628. return info;
  2629. }
  2630. table_offset = table_offset + selector_offset | 0;
  2631. if(this.paging[0])
  2632. {
  2633. table_offset = this.translate_address_system_read(table_offset);
  2634. }
  2635. info.table_offset = table_offset;
  2636. info.base = this.read16(table_offset + 2 | 0) | this.read8(table_offset + 4 | 0) << 16 |
  2637. this.read8(table_offset + 7 | 0) << 24;
  2638. info.access = this.read8(table_offset + 5 | 0);
  2639. info.flags = this.read8(table_offset + 6 | 0) >> 4;
  2640. info.raw0 = this.read32s(table_offset | 0);
  2641. info.raw1 = this.read32s(table_offset + 4 | 0);
  2642. //this.write8(table_offset + 5 | 0, info.access | 1);
  2643. // used if system
  2644. info.type = info.access & 0xF;
  2645. info.dpl = info.access >> 5 & 3;
  2646. info.is_system = (info.access & 0x10) === 0;
  2647. info.is_present = (info.access & 0x80) === 0x80;
  2648. info.is_executable = (info.access & 8) === 8;
  2649. info.rw_bit = (info.access & 2) === 2;
  2650. info.dc_bit = (info.access & 4) === 4;
  2651. info.is_conforming_executable = info.dc_bit && info.is_executable;
  2652. info.size = (info.flags & 4) === 4;
  2653. var limit = this.read16(table_offset) |
  2654. (this.read8(table_offset + 6 | 0) & 0xF) << 16;
  2655. if(info.flags & 8)
  2656. {
  2657. // granularity set
  2658. info.effective_limit = (limit << 12 | 0xFFF) >>> 0;
  2659. }
  2660. else
  2661. {
  2662. info.effective_limit = limit;
  2663. }
  2664. info.is_writable = info.rw_bit && !info.is_executable;
  2665. info.is_readable = info.rw_bit || !info.is_executable;
  2666. return info;
  2667. };
  2668. /**
  2669. * @param {number} reg
  2670. * @param {number} selector
  2671. */
  2672. CPU.prototype.switch_seg = function(reg, selector)
  2673. {
  2674. dbg_assert(reg >= 0 && reg <= 5);
  2675. dbg_assert(typeof selector === "number" && selector < 0x10000 && selector >= 0);
  2676. if(!this.protected_mode[0] || this.vm86_mode())
  2677. {
  2678. this.sreg[reg] = selector;
  2679. this.segment_is_null[reg] = 0;
  2680. this.segment_offsets[reg] = selector << 4;
  2681. if(reg === reg_ss)
  2682. {
  2683. this.stack_size_32[0] = +false;
  2684. }
  2685. return;
  2686. }
  2687. var info = this.lookup_segment_selector(selector);
  2688. if(reg === reg_ss)
  2689. {
  2690. if(info.is_null)
  2691. {
  2692. dbg_log("#GP for loading 0 in SS sel=" + h(selector, 4), LOG_CPU);
  2693. dbg_trace(LOG_CPU);
  2694. this.trigger_gp(0);
  2695. }
  2696. if(!info.is_valid ||
  2697. info.is_system ||
  2698. info.rpl !== this.cpl[0] ||
  2699. !info.is_writable ||
  2700. info.dpl !== this.cpl[0])
  2701. {
  2702. dbg_log("#GP for loading invalid in SS sel=" + h(selector, 4), LOG_CPU);
  2703. dbg_trace(LOG_CPU);
  2704. this.trigger_gp(selector & ~3);
  2705. }
  2706. if(!info.is_present)
  2707. {
  2708. dbg_log("#SS for loading non-present in SS sel=" + h(selector, 4), LOG_CPU);
  2709. dbg_trace(LOG_CPU);
  2710. this.trigger_ss(selector & ~3);
  2711. }
  2712. this.stack_size_32[0] = info.size;
  2713. }
  2714. else if(reg === reg_cs)
  2715. {
  2716. // handled by switch_cs_real_mode, far_return or far_jump
  2717. dbg_assert(false);
  2718. }
  2719. else
  2720. {
  2721. // es, ds, fs, gs
  2722. if(info.is_null)
  2723. {
  2724. //dbg_log("0 loaded in seg=" + reg + " sel=" + h(selector, 4), LOG_CPU);
  2725. //dbg_trace(LOG_CPU);
  2726. this.sreg[reg] = selector;
  2727. this.segment_is_null[reg] = 1;
  2728. return;
  2729. }
  2730. if(!info.is_valid ||
  2731. info.is_system ||
  2732. !info.is_readable ||
  2733. (!info.is_conforming_executable &&
  2734. (info.rpl > info.dpl || this.cpl[0] > info.dpl))
  2735. ) {
  2736. dbg_log("#GP for loading invalid in seg " + reg + " sel=" + h(selector, 4), LOG_CPU);
  2737. this.debug.dump_state();
  2738. this.debug.dump_regs();
  2739. dbg_trace(LOG_CPU);
  2740. this.trigger_gp(selector & ~3);
  2741. }
  2742. if(!info.is_present)
  2743. {
  2744. dbg_log("#NP for loading not-present in seg " + reg + " sel=" + h(selector, 4), LOG_CPU);
  2745. dbg_trace(LOG_CPU);
  2746. this.trigger_np(selector & ~3);
  2747. }
  2748. }
  2749. this.segment_is_null[reg] = 0;
  2750. this.segment_limits[reg] = info.effective_limit;
  2751. //this.segment_infos[reg] = 0; // TODO
  2752. this.segment_offsets[reg] = info.base;
  2753. this.sreg[reg] = selector;
  2754. };
  2755. CPU.prototype.load_tr = function(selector)
  2756. {
  2757. var info = this.lookup_segment_selector(selector);
  2758. dbg_assert(info.is_valid);
  2759. //dbg_log("load tr: " + h(selector, 4) + " offset=" + h(info.base >>> 0, 8) + " limit=" + h(info.effective_limit >>> 0, 8), LOG_CPU);
  2760. if(!info.from_gdt)
  2761. {
  2762. throw this.debug.unimpl("TR can only be loaded from GDT");
  2763. }
  2764. if(info.is_null)
  2765. {
  2766. dbg_log("#GP(0) | tried to load null selector (ltr)");
  2767. throw this.debug.unimpl("#GP handler");
  2768. }
  2769. if(!info.is_system)
  2770. {
  2771. dbg_log("#GP | ltr: not a system entry");
  2772. throw this.debug.unimpl("#GP handler (happens when running kvm-unit-test without ACPI)");
  2773. }
  2774. if(info.type !== 9 && info.type !== 1)
  2775. {
  2776. // 0xB: busy 386 TSS (GP)
  2777. // 0x9: 386 TSS
  2778. // 0x3: busy 286 TSS (GP)
  2779. // 0x1: 286 TSS (??)
  2780. dbg_log("#GP | ltr: invalid type (type = " + h(info.type) + ")");
  2781. throw this.debug.unimpl("#GP handler");
  2782. }
  2783. if(!info.is_present)
  2784. {
  2785. dbg_log("#NT | present bit not set (ltr)");
  2786. throw this.debug.unimpl("#NT handler");
  2787. }
  2788. this.tss_size_32 = info.type === 9;
  2789. this.segment_offsets[reg_tr] = info.base;
  2790. this.segment_limits[reg_tr] = info.effective_limit;
  2791. this.sreg[reg_tr] = selector;
  2792. // Mark task as busy
  2793. this.write8(info.table_offset + 5 | 0, this.read8(info.table_offset + 5 | 0) | 2);
  2794. //dbg_log("tsr at " + h(info.base) + "; (" + info.effective_limit + " bytes)");
  2795. };
  2796. CPU.prototype.load_ldt = function(selector)
  2797. {
  2798. var info = this.lookup_segment_selector(selector);
  2799. if(info.is_null)
  2800. {
  2801. // invalid
  2802. this.segment_offsets[reg_ldtr] = 0;
  2803. this.segment_limits[reg_ldtr] = 0;
  2804. return;
  2805. }
  2806. dbg_assert(info.is_valid);
  2807. if(!info.from_gdt)
  2808. {
  2809. throw this.debug.unimpl("LDTR can only be loaded from GDT");
  2810. }
  2811. if(!info.is_present)
  2812. {
  2813. dbg_log("lldt: present bit not set");
  2814. throw this.debug.unimpl("#GP handler");
  2815. }
  2816. if(!info.is_system)
  2817. {
  2818. dbg_log("lldt: not a system entry");
  2819. throw this.debug.unimpl("#GP handler");
  2820. }
  2821. if(info.type !== 2)
  2822. {
  2823. dbg_log("lldt: invalid type (" + info.type + ")");
  2824. throw this.debug.unimpl("#GP handler");
  2825. }
  2826. this.segment_offsets[reg_ldtr] = info.base;
  2827. this.segment_limits[reg_ldtr] = info.effective_limit;
  2828. this.sreg[reg_ldtr] = selector;
  2829. //dbg_log("ldt at " + h(info.base >>> 0) + "; (" + info.effective_limit + " bytes)", LOG_CPU);
  2830. };
  2831. CPU.prototype.arpl = function(seg, r16)
  2832. {
  2833. if(!this.protected_mode[0] || this.vm86_mode())
  2834. {
  2835. this.trigger_ud();
  2836. }
  2837. this.flags_changed[0] &= ~flag_zero;
  2838. if((seg & 3) < (r16 & 3))
  2839. {
  2840. this.flags[0] |= flag_zero;
  2841. return seg & ~3 | r16 & 3;
  2842. }
  2843. else
  2844. {
  2845. this.flags[0] &= ~flag_zero;
  2846. return seg;
  2847. }
  2848. };
  2849. CPU.prototype.lar = function(selector, original)
  2850. {
  2851. if(CPU_LOG_VERBOSE)
  2852. {
  2853. dbg_log("lar sel=" + h(selector, 4), LOG_CPU);
  2854. }
  2855. if(!this.protected_mode[0] || this.vm86_mode())
  2856. {
  2857. dbg_log("lar #ud");
  2858. this.trigger_ud();
  2859. }
  2860. /** @const */
  2861. var LAR_INVALID_TYPE = 1 << 0 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 0xA |
  2862. 1 << 0xD | 1 << 0xE | 1 << 0xF;
  2863. var info = this.lookup_segment_selector(selector);
  2864. this.flags_changed[0] &= ~flag_zero;
  2865. var dpl_bad = info.dpl < this.cpl[0] || info.dpl < info.rpl;
  2866. if(info.is_null || !info.is_valid ||
  2867. (info.is_system ? (LAR_INVALID_TYPE >> info.type & 1) || dpl_bad :
  2868. !info.is_conforming_executable && dpl_bad)
  2869. ) {
  2870. this.flags[0] &= ~flag_zero;
  2871. dbg_log("lar: invalid selector=" + h(selector, 4) + " is_null=" + info.is_null, LOG_CPU);
  2872. return original;
  2873. }
  2874. else
  2875. {
  2876. this.flags[0] |= flag_zero;
  2877. return info.raw1 & 0x00FFFF00;
  2878. }
  2879. };
  2880. CPU.prototype.lsl = function(selector, original)
  2881. {
  2882. if(CPU_LOG_VERBOSE)
  2883. {
  2884. dbg_log("lsl sel=" + h(selector, 4), LOG_CPU);
  2885. }
  2886. if(!this.protected_mode[0] || this.vm86_mode())
  2887. {
  2888. dbg_log("lsl #ud");
  2889. this.trigger_ud();
  2890. }
  2891. /** @const */
  2892. var LSL_INVALID_TYPE = 1 << 0 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 |
  2893. 1 << 0xA | 1 << 0xC | 1 << 0xD | 1 << 0xE | 1 << 0xF;
  2894. var info = this.lookup_segment_selector(selector);
  2895. this.flags_changed[0] &= ~flag_zero;
  2896. var dpl_bad = info.dpl < this.cpl[0] || info.dpl < info.rpl;
  2897. if(info.is_null || !info.is_valid ||
  2898. (info.is_system ? (LSL_INVALID_TYPE >> info.type & 1) || dpl_bad :
  2899. !info.is_conforming_executable && dpl_bad)
  2900. ) {
  2901. this.flags[0] &= ~flag_zero;
  2902. dbg_log("lsl: invalid selector=" + h(selector, 4) + " is_null=" + info.is_null, LOG_CPU);
  2903. return original;
  2904. }
  2905. else
  2906. {
  2907. this.flags[0] |= flag_zero;
  2908. return info.effective_limit | 0;
  2909. }
  2910. };
  2911. CPU.prototype.verr = function(selector)
  2912. {
  2913. var info = this.lookup_segment_selector(selector);
  2914. this.flags_changed[0] &= ~flag_zero;
  2915. if(info.is_null || !info.is_valid || info.is_system || !info.is_readable ||
  2916. (!info.is_conforming_executable && (info.dpl < this.cpl[0] || info.dpl < info.rpl)))
  2917. {
  2918. dbg_log("verr -> invalid. selector=" + h(selector, 4), LOG_CPU);
  2919. this.flags[0] &= ~flag_zero;
  2920. }
  2921. else
  2922. {
  2923. dbg_log("verr -> valid. selector=" + h(selector, 4), LOG_CPU);
  2924. this.flags[0] |= flag_zero;
  2925. }
  2926. };
  2927. CPU.prototype.verw = function(selector)
  2928. {
  2929. var info = this.lookup_segment_selector(selector);
  2930. this.flags_changed[0] &= ~flag_zero;
  2931. if(info.is_null || !info.is_valid || info.is_system || !info.is_writable ||
  2932. info.dpl < this.cpl[0] || info.dpl < info.rpl)
  2933. {
  2934. dbg_log("verw invalid " + " " + h(selector) + " " + info.is_null + " " +
  2935. !info.is_valid + " " + info.is_system + " " + !info.is_writable + " " +
  2936. (info.dpl < this.cpl[0]) + " " + (info.dpl < info.rpl) + " " + LOG_CPU);
  2937. this.flags[0] &= ~flag_zero;
  2938. }
  2939. else
  2940. {
  2941. this.flags[0] |= flag_zero;
  2942. }
  2943. };
  2944. CPU.prototype.is_osize_32 = function()
  2945. {
  2946. return Boolean(this.is_32[0]) !== ((this.prefixes[0] & PREFIX_MASK_OPSIZE) === PREFIX_MASK_OPSIZE);
  2947. };
  2948. CPU.prototype.is_asize_32 = function()
  2949. {
  2950. return Boolean(this.is_32[0]) !== ((this.prefixes[0] & PREFIX_MASK_ADDRSIZE) === PREFIX_MASK_ADDRSIZE);
  2951. };
  2952. CPU.prototype.popa16 = function()
  2953. {
  2954. this.translate_address_read(this.get_stack_pointer(0));
  2955. this.translate_address_read(this.get_stack_pointer(15));
  2956. this.reg16[reg_di] = this.pop16();
  2957. this.reg16[reg_si] = this.pop16();
  2958. this.reg16[reg_bp] = this.pop16();
  2959. this.adjust_stack_reg(2);
  2960. this.reg16[reg_bx] = this.pop16();
  2961. this.reg16[reg_dx] = this.pop16();
  2962. this.reg16[reg_cx] = this.pop16();
  2963. this.reg16[reg_ax] = this.pop16();
  2964. };
  2965. CPU.prototype.popa32 = function()
  2966. {
  2967. this.translate_address_read(this.get_stack_pointer(0));
  2968. this.translate_address_read(this.get_stack_pointer(31));
  2969. this.reg32s[reg_edi] = this.pop32s();
  2970. this.reg32s[reg_esi] = this.pop32s();
  2971. this.reg32s[reg_ebp] = this.pop32s();
  2972. this.adjust_stack_reg(4);
  2973. this.reg32s[reg_ebx] = this.pop32s();
  2974. this.reg32s[reg_edx] = this.pop32s();
  2975. this.reg32s[reg_ecx] = this.pop32s();
  2976. this.reg32s[reg_eax] = this.pop32s();
  2977. };
  2978. CPU.prototype.lss16 = function(addr, reg, seg)
  2979. {
  2980. var new_reg = this.safe_read16(addr),
  2981. new_seg = this.safe_read16(addr + 2 | 0);
  2982. this.switch_seg(seg, new_seg);
  2983. this.reg16[reg] = new_reg;
  2984. };
  2985. CPU.prototype.lss32 = function(addr, reg, seg)
  2986. {
  2987. var new_reg = this.safe_read32s(addr),
  2988. new_seg = this.safe_read16(addr + 4 | 0);
  2989. this.switch_seg(seg, new_seg);
  2990. this.reg32s[reg] = new_reg;
  2991. };
  2992. CPU.prototype.enter16 = function(size, nesting_level)
  2993. {
  2994. nesting_level &= 31;
  2995. if(nesting_level) dbg_log("enter16 stack=" + (this.stack_size_32[0] ? 32 : 16) + " size=" + size + " nest=" + nesting_level, LOG_CPU);
  2996. var ss_mask = this.stack_size_32[0] ? -1 : 0xFFFF;
  2997. var ss = this.get_seg(reg_ss);
  2998. var frame_temp = this.reg32s[reg_esp] - 2;
  2999. if(nesting_level > 0)
  3000. {
  3001. var tmp_ebp = this.reg32s[reg_ebp];
  3002. for(var i = 1; i < nesting_level; i++)
  3003. {
  3004. tmp_ebp -= 2;
  3005. this.push16(this.safe_read16(ss + (tmp_ebp & ss_mask) | 0));
  3006. }
  3007. this.push16(frame_temp);
  3008. }
  3009. // check if write to final stack pointer would case a page fault
  3010. this.writable_or_pagefault(ss + (frame_temp - size & ss_mask), 2);
  3011. this.safe_write16(ss + (frame_temp & ss_mask) | 0, this.reg16[reg_bp]);
  3012. this.reg16[reg_bp] = frame_temp;
  3013. this.adjust_stack_reg(-size - 2);
  3014. };
  3015. CPU.prototype.enter32 = function(size, nesting_level)
  3016. {
  3017. nesting_level &= 31;
  3018. if(nesting_level) dbg_log("enter32 stack=" + (this.stack_size_32[0] ? 32 : 16) + " size=" + size + " nest=" + nesting_level, LOG_CPU);
  3019. var ss_mask = this.stack_size_32[0] ? -1 : 0xFFFF;
  3020. var ss = this.get_seg(reg_ss);
  3021. var frame_temp = this.reg32s[reg_esp] - 4;
  3022. if(nesting_level > 0)
  3023. {
  3024. var tmp_ebp = this.reg32s[reg_ebp];
  3025. for(var i = 1; i < nesting_level; i++)
  3026. {
  3027. tmp_ebp -= 4;
  3028. this.push32(this.safe_read32s(ss + (tmp_ebp & ss_mask) | 0));
  3029. }
  3030. this.push32(frame_temp);
  3031. }
  3032. // check if write to final stack pointer would case a page fault
  3033. this.writable_or_pagefault(ss + (frame_temp - size & ss_mask), 4);
  3034. this.safe_write32(ss + (frame_temp & ss_mask) | 0, this.reg32s[reg_ebp]);
  3035. this.reg32s[reg_ebp] = frame_temp;
  3036. this.adjust_stack_reg(-size - 4);
  3037. };
  3038. CPU.prototype.bswap = function(reg)
  3039. {
  3040. var temp = this.reg32s[reg];
  3041. this.reg32s[reg] = temp >>> 24 | temp << 24 | (temp >> 8 & 0xFF00) | (temp << 8 & 0xFF0000);
  3042. };
  3043. // Closure Compiler's way of exporting
  3044. if(typeof window !== "undefined")
  3045. {
  3046. window["CPU"] = CPU;
  3047. }
  3048. else if(typeof module !== "undefined" && typeof module.exports !== "undefined")
  3049. {
  3050. module.exports["CPU"] = CPU;
  3051. }
  3052. else if(typeof importScripts === "function")
  3053. {
  3054. self["CPU"] = CPU;
  3055. }