cpu.js 106 KB

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