JavascriptOperators.cpp 477 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLanguagePch.h"
  6. #include "Types/PathTypeHandler.h"
  7. #include "Types/PropertyIndexRanges.h"
  8. #include "Types/WithScopeObject.h"
  9. #include "Types/SpreadArgument.h"
  10. #include "Library/JavascriptPromise.h"
  11. #include "Library/JavascriptRegularExpression.h"
  12. #include "Library/ThrowErrorObject.h"
  13. #include "Library/JavascriptGeneratorFunction.h"
  14. #include "Types/DynamicObjectEnumerator.h"
  15. #include "Types/DynamicObjectSnapshotEnumerator.h"
  16. #include "Types/DynamicObjectSnapshotEnumeratorWPCache.h"
  17. #include "Library/ForInObjectEnumerator.h"
  18. #include "Library/ES5Array.h"
  19. #ifndef SCRIPT_DIRECT_TYPE
  20. typedef enum JsNativeValueType: int
  21. {
  22. JsInt8Type,
  23. JsUint8Type,
  24. JsInt16Type,
  25. JsUint16Type,
  26. JsInt32Type,
  27. JsUint32Type,
  28. JsInt64Type,
  29. JsUint64Type,
  30. JsFloatType,
  31. JsDoubleType,
  32. JsNativeStringType
  33. } JsNativeValueType;
  34. typedef struct JsNativeString
  35. {
  36. unsigned int length;
  37. LPCWSTR str;
  38. } JsNativeString;
  39. #endif
  40. namespace Js
  41. {
  42. DEFINE_RECYCLER_TRACKER_ARRAY_PERF_COUNTER(Var);
  43. DEFINE_RECYCLER_TRACKER_PERF_COUNTER(FrameDisplay);
  44. enum IndexType
  45. {
  46. IndexType_Number,
  47. IndexType_PropertyId,
  48. IndexType_JavascriptString
  49. };
  50. IndexType GetIndexTypeFromString(char16 const * propertyName, charcount_t propertyLength, ScriptContext* scriptContext, uint32* index, PropertyRecord const** propertyRecord, bool createIfNotFound)
  51. {
  52. if (JavascriptOperators::TryConvertToUInt32(propertyName, propertyLength, index) &&
  53. (*index != JavascriptArray::InvalidIndex))
  54. {
  55. return IndexType_Number;
  56. }
  57. else
  58. {
  59. if (createIfNotFound)
  60. {
  61. scriptContext->GetOrAddPropertyRecord(propertyName, propertyLength, propertyRecord);
  62. }
  63. else
  64. {
  65. scriptContext->FindPropertyRecord(propertyName, propertyLength, propertyRecord);
  66. }
  67. return IndexType_PropertyId;
  68. }
  69. }
  70. IndexType GetIndexTypeFromPrimitive(Var indexVar, ScriptContext* scriptContext, uint32* index, PropertyRecord const ** propertyRecord, JavascriptString ** propertyNameString, bool createIfNotFound, bool preferJavascriptStringOverPropertyRecord)
  71. {
  72. // CONSIDER: Only OP_SetElementI and OP_GetElementI use and take advantage of the
  73. // IndexType_JavascriptString result. Consider modifying other callers of GetIndexType to take
  74. // advantage of non-interned property strings where appropriate.
  75. if (TaggedInt::Is(indexVar))
  76. {
  77. int indexInt = TaggedInt::ToInt32(indexVar);
  78. if (indexInt >= 0)
  79. {
  80. *index = (uint)indexInt;
  81. return IndexType_Number;
  82. }
  83. else
  84. {
  85. char16 buffer[20];
  86. ::_itow_s(indexInt, buffer, sizeof(buffer) / sizeof(char16), 10);
  87. charcount_t length = JavascriptString::GetBufferLength(buffer);
  88. if (createIfNotFound || preferJavascriptStringOverPropertyRecord)
  89. {
  90. // When preferring JavascriptString objects, just return a PropertyRecord instead
  91. // of creating temporary JavascriptString objects for every negative integer that
  92. // comes through here.
  93. scriptContext->GetOrAddPropertyRecord(buffer, length, propertyRecord);
  94. }
  95. else
  96. {
  97. scriptContext->FindPropertyRecord(buffer, length, propertyRecord);
  98. }
  99. return IndexType_PropertyId;
  100. }
  101. }
  102. else if (JavascriptSymbol::Is(indexVar))
  103. {
  104. JavascriptSymbol* symbol = JavascriptSymbol::FromVar(indexVar);
  105. // JavascriptSymbols cannot add a new PropertyRecord - they correspond to one and only one existing PropertyRecord.
  106. // We already know what the PropertyRecord is since it is stored in the JavascriptSymbol itself so just return it.
  107. *propertyRecord = symbol->GetValue();
  108. return IndexType_PropertyId;
  109. }
  110. else
  111. {
  112. JavascriptString* indexStr = JavascriptConversion::ToString(indexVar, scriptContext);
  113. char16 const * propertyName = indexStr->GetString();
  114. charcount_t const propertyLength = indexStr->GetLength();
  115. if (!createIfNotFound && preferJavascriptStringOverPropertyRecord)
  116. {
  117. if (JavascriptOperators::TryConvertToUInt32(propertyName, propertyLength, index) &&
  118. (*index != JavascriptArray::InvalidIndex))
  119. {
  120. return IndexType_Number;
  121. }
  122. *propertyNameString = indexStr;
  123. return IndexType_JavascriptString;
  124. }
  125. return GetIndexTypeFromString(propertyName, propertyLength, scriptContext, index, propertyRecord, createIfNotFound);
  126. }
  127. }
  128. IndexType GetIndexTypeFromPrimitive(Var indexVar, ScriptContext* scriptContext, uint32* index, PropertyRecord const ** propertyRecord, bool createIfNotFound)
  129. {
  130. return GetIndexTypeFromPrimitive(indexVar, scriptContext, index, propertyRecord, nullptr, createIfNotFound, false);
  131. }
  132. IndexType GetIndexType(Var& indexVar, ScriptContext* scriptContext, uint32* index, PropertyRecord const ** propertyRecord, JavascriptString ** propertyNameString, bool createIfNotFound, bool preferJavascriptStringOverPropertyRecord)
  133. {
  134. indexVar = JavascriptConversion::ToPrimitive(indexVar, JavascriptHint::HintString, scriptContext);
  135. return GetIndexTypeFromPrimitive(indexVar, scriptContext, index, propertyRecord, propertyNameString, createIfNotFound, preferJavascriptStringOverPropertyRecord);
  136. }
  137. IndexType GetIndexType(Var& indexVar, ScriptContext* scriptContext, uint32* index, PropertyRecord const ** propertyRecord, bool createIfNotFound)
  138. {
  139. return GetIndexType(indexVar, scriptContext, index, propertyRecord, nullptr, createIfNotFound, false);
  140. }
  141. BOOL FEqualDbl(double dbl1, double dbl2)
  142. {
  143. // If the low ulongs don't match, they can't be equal.
  144. if (Js::NumberUtilities::LuLoDbl(dbl1) != Js::NumberUtilities::LuLoDbl(dbl2))
  145. return FALSE;
  146. // If the high ulongs don't match, they can be equal iff one is -0 and
  147. // the other is +0.
  148. if (Js::NumberUtilities::LuHiDbl(dbl1) != Js::NumberUtilities::LuHiDbl(dbl2))
  149. {
  150. return 0x80000000 == (Js::NumberUtilities::LuHiDbl(dbl1) | Js::NumberUtilities::LuHiDbl(dbl2)) &&
  151. 0 == Js::NumberUtilities::LuLoDbl(dbl1);
  152. }
  153. // The bit patterns match. They are equal iff they are not Nan.
  154. return !Js::NumberUtilities::IsNan(dbl1);
  155. }
  156. Var JavascriptOperators::OP_ApplyArgs(Var func, Var instance, __in_xcount(8) void** stackPtr, CallInfo callInfo, ScriptContext* scriptContext)
  157. {
  158. int argCount = callInfo.Count;
  159. ///
  160. /// Check func has internal [[Call]] property
  161. /// If not, throw TypeError
  162. ///
  163. if (!JavascriptConversion::IsCallable(func)) {
  164. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedFunction);
  165. }
  166. // Fix callInfo: expect result/value, and none of other flags are currently applicable.
  167. // OP_ApplyArgs expects a result. Neither of {jit, interpreted} mode sends correct callFlags:
  168. // LdArgCnt -- jit sends whatever was passed to current function, interpreter always sends 0.
  169. // See Win8 bug 490489.
  170. callInfo.Flags = CallFlags_Value;
  171. RecyclableObject *funcPtr = RecyclableObject::FromVar(func);
  172. PROBE_STACK(scriptContext, Js::Constants::MinStackDefault + argCount * 4);
  173. JavascriptMethod entryPoint = funcPtr->GetEntryPoint();
  174. Var ret;
  175. switch (argCount) {
  176. case 0:
  177. Assert(false);
  178. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo);
  179. break;
  180. case 1:
  181. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance);
  182. break;
  183. case 2:
  184. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance, stackPtr[0]);
  185. break;
  186. case 3:
  187. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance, stackPtr[0], stackPtr[1]);
  188. break;
  189. case 4:
  190. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance, stackPtr[0], stackPtr[1], stackPtr[2]);
  191. break;
  192. case 5:
  193. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance, stackPtr[0], stackPtr[1], stackPtr[2], stackPtr[3]);
  194. break;
  195. case 6:
  196. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance, stackPtr[0], stackPtr[1], stackPtr[2], stackPtr[3], stackPtr[4]);
  197. break;
  198. case 7:
  199. ret = CALL_ENTRYPOINT(entryPoint, funcPtr, callInfo, instance, stackPtr[0], stackPtr[1], stackPtr[2], stackPtr[3], stackPtr[4], stackPtr[5]);
  200. break;
  201. default: {
  202. // Don't need stack probe here- we just did so above
  203. Arguments args(callInfo, stackPtr - 1);
  204. ret = JavascriptFunction::CallFunction<false>(funcPtr, entryPoint, args);
  205. }
  206. break;
  207. }
  208. return ret;
  209. }
  210. #ifdef _M_IX86
  211. // Alias for overloaded JavascriptNumber::ToVar so it can be called unambiguously from native code
  212. Var JavascriptOperators::Int32ToVar(int32 value, ScriptContext* scriptContext)
  213. {
  214. return JavascriptNumber::ToVar(value, scriptContext);
  215. }
  216. // Alias for overloaded JavascriptNumber::ToVar so it can be called unambiguously from native code
  217. Var JavascriptOperators::Int32ToVarInPlace(int32 value, ScriptContext* scriptContext, JavascriptNumber* result)
  218. {
  219. return JavascriptNumber::ToVarInPlace(value, scriptContext, result);
  220. }
  221. // Alias for overloaded JavascriptNumber::ToVar so it can be called unambiguously from native code
  222. Var JavascriptOperators::UInt32ToVar(uint32 value, ScriptContext* scriptContext)
  223. {
  224. return JavascriptNumber::ToVar(value, scriptContext);
  225. }
  226. // Alias for overloaded JavascriptNumber::ToVar so it can be called unambiguously from native code
  227. Var JavascriptOperators::UInt32ToVarInPlace(uint32 value, ScriptContext* scriptContext, JavascriptNumber* result)
  228. {
  229. return JavascriptNumber::ToVarInPlace(value, scriptContext, result);
  230. }
  231. #endif
  232. Var JavascriptOperators::OP_FinishOddDivBy2(uint32 value, ScriptContext *scriptContext)
  233. {
  234. return JavascriptNumber::New((double)(value + 0.5), scriptContext);
  235. }
  236. Var JavascriptOperators::ToNumberInPlace(Var aRight, ScriptContext* scriptContext, JavascriptNumber* result)
  237. {
  238. if (TaggedInt::Is(aRight) || JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  239. {
  240. return aRight;
  241. }
  242. return JavascriptNumber::ToVarInPlace(JavascriptConversion::ToNumber(aRight, scriptContext), scriptContext, result);
  243. }
  244. Var JavascriptOperators::Typeof(Var var, ScriptContext* scriptContext)
  245. {
  246. #ifdef ENABLE_SIMDJS
  247. if (SIMDUtils::IsSimdType(var) && scriptContext->GetConfig()->IsSimdjsEnabled())
  248. {
  249. switch ((JavascriptOperators::GetTypeId(var)))
  250. {
  251. case TypeIds_SIMDFloat32x4:
  252. return scriptContext->GetLibrary()->GetSIMDFloat32x4DisplayString();
  253. //case TypeIds_SIMDFloat64x2: //Type under review by the spec.
  254. // return scriptContext->GetLibrary()->GetSIMDFloat64x2DisplayString();
  255. case TypeIds_SIMDInt32x4:
  256. return scriptContext->GetLibrary()->GetSIMDInt32x4DisplayString();
  257. case TypeIds_SIMDInt16x8:
  258. return scriptContext->GetLibrary()->GetSIMDInt16x8DisplayString();
  259. case TypeIds_SIMDInt8x16:
  260. return scriptContext->GetLibrary()->GetSIMDInt8x16DisplayString();
  261. case TypeIds_SIMDUint32x4:
  262. return scriptContext->GetLibrary()->GetSIMDUint32x4DisplayString();
  263. case TypeIds_SIMDUint16x8:
  264. return scriptContext->GetLibrary()->GetSIMDUint16x8DisplayString();
  265. case TypeIds_SIMDUint8x16:
  266. return scriptContext->GetLibrary()->GetSIMDUint8x16DisplayString();
  267. case TypeIds_SIMDBool32x4:
  268. return scriptContext->GetLibrary()->GetSIMDBool32x4DisplayString();
  269. case TypeIds_SIMDBool16x8:
  270. return scriptContext->GetLibrary()->GetSIMDBool16x8DisplayString();
  271. case TypeIds_SIMDBool8x16:
  272. return scriptContext->GetLibrary()->GetSIMDBool8x16DisplayString();
  273. default:
  274. Assert(UNREACHED);
  275. }
  276. }
  277. #endif
  278. //All remaining types.
  279. switch (JavascriptOperators::GetTypeId(var))
  280. {
  281. case TypeIds_Undefined:
  282. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  283. case TypeIds_Null:
  284. //null
  285. return scriptContext->GetLibrary()->GetObjectTypeDisplayString();
  286. case TypeIds_Integer:
  287. case TypeIds_Number:
  288. case TypeIds_Int64Number:
  289. case TypeIds_UInt64Number:
  290. return scriptContext->GetLibrary()->GetNumberTypeDisplayString();
  291. default:
  292. // Falsy objects are typeof 'undefined'.
  293. if (RecyclableObject::FromVar(var)->GetType()->IsFalsy())
  294. {
  295. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  296. }
  297. else
  298. {
  299. return RecyclableObject::FromVar(var)->GetTypeOfString(scriptContext);
  300. }
  301. }
  302. }
  303. Var JavascriptOperators::TypeofFld(Var instance, PropertyId propertyId, ScriptContext* scriptContext)
  304. {
  305. return TypeofFld_Internal(instance, false, propertyId, scriptContext);
  306. }
  307. Var JavascriptOperators::TypeofRootFld(Var instance, PropertyId propertyId, ScriptContext* scriptContext)
  308. {
  309. return TypeofFld_Internal(instance, true, propertyId, scriptContext);
  310. }
  311. Var JavascriptOperators::TypeofFld_Internal(Var instance, const bool isRoot, PropertyId propertyId, ScriptContext* scriptContext)
  312. {
  313. RecyclableObject* object = nullptr;
  314. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  315. {
  316. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined , scriptContext->GetPropertyName(propertyId)->GetBuffer());
  317. }
  318. Var value;
  319. try
  320. {
  321. Js::JavascriptExceptionOperators::AutoCatchHandlerExists autoCatchHandlerExists(scriptContext);
  322. // In edge mode, spec compat is more important than backward compat. Use spec/web behavior here
  323. if (isRoot
  324. ? !JavascriptOperators::GetRootProperty(instance, propertyId, &value, scriptContext)
  325. : !JavascriptOperators::GetProperty(instance, object, propertyId, &value, scriptContext))
  326. {
  327. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  328. }
  329. if (!scriptContext->IsUndeclBlockVar(value))
  330. {
  331. return JavascriptOperators::Typeof(value, scriptContext);
  332. }
  333. }
  334. catch(Js::JavascriptExceptionObject * )
  335. {
  336. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  337. }
  338. Assert(scriptContext->IsUndeclBlockVar(value));
  339. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  340. }
  341. Var JavascriptOperators::TypeofElem_UInt32(Var instance, uint32 index, ScriptContext* scriptContext)
  342. {
  343. if (JavascriptOperators::IsNumberFromNativeArray(instance, index, scriptContext))
  344. return scriptContext->GetLibrary()->GetNumberTypeDisplayString();
  345. #if FLOATVAR
  346. return TypeofElem(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext);
  347. #else
  348. char buffer[sizeof(Js::JavascriptNumber)];
  349. return TypeofElem(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  350. (Js::JavascriptNumber *)buffer), scriptContext);
  351. #endif
  352. }
  353. Var JavascriptOperators::TypeofElem_Int32(Var instance, int32 index, ScriptContext* scriptContext)
  354. {
  355. if (JavascriptOperators::IsNumberFromNativeArray(instance, index, scriptContext))
  356. return scriptContext->GetLibrary()->GetNumberTypeDisplayString();
  357. #if FLOATVAR
  358. return TypeofElem(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext);
  359. #else
  360. char buffer[sizeof(Js::JavascriptNumber)];
  361. return TypeofElem(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  362. (Js::JavascriptNumber *)buffer), scriptContext);
  363. #endif
  364. }
  365. Js::JavascriptString* GetPropertyDisplayNameForError(Var prop, ScriptContext* scriptContext)
  366. {
  367. JavascriptString* str;
  368. if (JavascriptSymbol::Is(prop))
  369. {
  370. str = JavascriptSymbol::ToString(JavascriptSymbol::FromVar(prop)->GetValue(), scriptContext);
  371. }
  372. else
  373. {
  374. str = JavascriptConversion::ToString(prop, scriptContext);
  375. }
  376. return str;
  377. }
  378. Var JavascriptOperators::TypeofElem(Var instance, Var index, ScriptContext* scriptContext)
  379. {
  380. RecyclableObject* object = nullptr;
  381. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  382. {
  383. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined, GetPropertyDisplayNameForError(index, scriptContext));
  384. }
  385. Var member;
  386. uint32 indexVal;
  387. PropertyRecord const * propertyRecord = nullptr;
  388. ThreadContext* threadContext = scriptContext->GetThreadContext();
  389. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  390. threadContext->ClearImplicitCallFlags();
  391. try
  392. {
  393. Js::JavascriptExceptionOperators::AutoCatchHandlerExists autoCatchHandlerExists(scriptContext);
  394. IndexType indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, false);
  395. // For JS Objects, don't create the propertyId if not already added
  396. if (indexType == IndexType_Number)
  397. {
  398. // In edge mode, we don't need to worry about the special "unknown" behavior. If the item is not available from Get,
  399. // just return undefined.
  400. if (!JavascriptOperators::GetItem(instance, object, indexVal, &member, scriptContext))
  401. {
  402. // If the instance doesn't have the item, typeof result is "undefined".
  403. threadContext->CheckAndResetImplicitCallAccessorFlag();
  404. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  405. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  406. }
  407. }
  408. else
  409. {
  410. Assert(indexType == IndexType_PropertyId);
  411. if (propertyRecord == nullptr && !JavascriptOperators::CanShortcutOnUnknownPropertyName(object))
  412. {
  413. indexType = GetIndexTypeFromPrimitive(index, scriptContext, &indexVal, &propertyRecord, true);
  414. Assert(indexType == IndexType_PropertyId);
  415. Assert(propertyRecord != nullptr);
  416. }
  417. if (propertyRecord != nullptr)
  418. {
  419. if (!JavascriptOperators::GetProperty(instance, object, propertyRecord->GetPropertyId(), &member, scriptContext))
  420. {
  421. // If the instance doesn't have the property, typeof result is "undefined".
  422. threadContext->CheckAndResetImplicitCallAccessorFlag();
  423. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  424. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  425. }
  426. }
  427. else
  428. {
  429. #if DBG
  430. JavascriptString* indexStr = JavascriptConversion::ToString(index, scriptContext);
  431. PropertyRecord const * debugPropertyRecord;
  432. scriptContext->GetOrAddPropertyRecord(indexStr->GetString(), indexStr->GetLength(), &debugPropertyRecord);
  433. AssertMsg(!JavascriptOperators::GetProperty(instance, object, debugPropertyRecord->GetPropertyId(), &member, scriptContext), "how did this property come? See OS Bug 2727708 if you see this come from the web");
  434. #endif
  435. // If the instance doesn't have the property, typeof result is "undefined".
  436. threadContext->CheckAndResetImplicitCallAccessorFlag();
  437. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  438. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  439. }
  440. }
  441. threadContext->CheckAndResetImplicitCallAccessorFlag();
  442. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  443. return JavascriptOperators::Typeof(member, scriptContext);
  444. }
  445. catch(Js::JavascriptExceptionObject * )
  446. {
  447. threadContext->CheckAndResetImplicitCallAccessorFlag();
  448. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  449. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  450. }
  451. }
  452. //
  453. // Delete the given Var
  454. //
  455. Var JavascriptOperators::Delete(Var var, ScriptContext* scriptContext)
  456. {
  457. return scriptContext->GetLibrary()->GetTrue();
  458. }
  459. BOOL JavascriptOperators::Equal_Full(Var aLeft, Var aRight, ScriptContext* requestContext)
  460. {
  461. //
  462. // Fast-path SmInts and paired Number combinations.
  463. //
  464. if (aLeft == aRight)
  465. {
  466. if (JavascriptNumber::Is(aLeft) && JavascriptNumber::IsNan(JavascriptNumber::GetValue(aLeft)))
  467. {
  468. return false;
  469. }
  470. else if (JavascriptVariantDate::Is(aLeft) == false) // only need to check on aLeft - since they are the same var, aRight would do the same
  471. {
  472. return true;
  473. }
  474. else
  475. {
  476. //In ES5 mode strict equals (===) on same instance of object type VariantDate succeeds.
  477. //Hence equals needs to succeed.
  478. return true;
  479. }
  480. }
  481. BOOL result = false;
  482. if (TaggedInt::Is(aLeft))
  483. {
  484. if (TaggedInt::Is(aRight))
  485. {
  486. // If aLeft == aRight, we would already have returned true above.
  487. return false;
  488. }
  489. else if (JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  490. {
  491. return TaggedInt::ToDouble(aLeft) == JavascriptNumber::GetValue(aRight);
  492. }
  493. else
  494. {
  495. BOOL res = RecyclableObject::FromVar(aRight)->Equals(aLeft, &result, requestContext);
  496. AssertMsg(res, "Should have handled this");
  497. return result;
  498. }
  499. }
  500. else if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft))
  501. {
  502. if (TaggedInt::Is(aRight))
  503. {
  504. return TaggedInt::ToDouble(aRight) == JavascriptNumber::GetValue(aLeft);
  505. }
  506. else if(JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  507. {
  508. return JavascriptNumber::GetValue(aLeft) == JavascriptNumber::GetValue(aRight);
  509. }
  510. else
  511. {
  512. BOOL res = RecyclableObject::FromVar(aRight)->Equals(aLeft, &result, requestContext);
  513. AssertMsg(res, "Should have handled this");
  514. return result;
  515. }
  516. }
  517. #ifdef ENABLE_SIMDJS
  518. else if (SIMDUtils::IsSimdType(aLeft) && SIMDUtils::IsSimdType(aRight))
  519. {
  520. return StrictEqualSIMD(aLeft, aRight, requestContext);
  521. }
  522. #endif
  523. if (RecyclableObject::FromVar(aLeft)->Equals(aRight, &result, requestContext))
  524. {
  525. return result;
  526. }
  527. else
  528. {
  529. return false;
  530. }
  531. }
  532. BOOL JavascriptOperators::Greater_Full(Var aLeft,Var aRight,ScriptContext* scriptContext)
  533. {
  534. return RelationalComparisonHelper(aRight, aLeft, scriptContext, false, false);
  535. }
  536. BOOL JavascriptOperators::Less_Full(Var aLeft, Var aRight, ScriptContext* scriptContext)
  537. {
  538. return RelationalComparisonHelper(aLeft, aRight, scriptContext, true, false);
  539. }
  540. BOOL JavascriptOperators::RelationalComparisonHelper(Var aLeft, Var aRight, ScriptContext* scriptContext, bool leftFirst, bool undefinedAs)
  541. {
  542. TypeId typeId = JavascriptOperators::GetTypeId(aLeft);
  543. if (typeId == TypeIds_Null)
  544. {
  545. aLeft=TaggedInt::ToVarUnchecked(0);
  546. }
  547. else if (typeId == TypeIds_Undefined)
  548. {
  549. aLeft=scriptContext->GetLibrary()->GetNaN();
  550. }
  551. typeId = JavascriptOperators::GetTypeId(aRight);
  552. if (typeId == TypeIds_Null)
  553. {
  554. aRight=TaggedInt::ToVarUnchecked(0);
  555. }
  556. else if (typeId == TypeIds_Undefined)
  557. {
  558. aRight=scriptContext->GetLibrary()->GetNaN();
  559. }
  560. double dblLeft, dblRight;
  561. #ifdef ENABLE_SIMDJS
  562. if (SIMDUtils::IsSimdType(aLeft) || SIMDUtils::IsSimdType(aRight))
  563. {
  564. JavascriptError::ThrowTypeError(scriptContext, JSERR_SIMDConversion, _u("SIMD type"));
  565. }
  566. #endif
  567. TypeId leftType = JavascriptOperators::GetTypeId(aLeft);
  568. TypeId rightType = JavascriptOperators::GetTypeId(aRight);
  569. switch (leftType)
  570. {
  571. case TypeIds_Integer:
  572. dblLeft = TaggedInt::ToDouble(aLeft);
  573. switch (rightType)
  574. {
  575. case TypeIds_Integer:
  576. dblRight = TaggedInt::ToDouble(aRight);
  577. break;
  578. case TypeIds_Number:
  579. dblRight = JavascriptNumber::GetValue(aRight);
  580. break;
  581. default:
  582. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  583. break;
  584. }
  585. break;
  586. case TypeIds_Number:
  587. dblLeft = JavascriptNumber::GetValue(aLeft);
  588. switch (rightType)
  589. {
  590. case TypeIds_Integer:
  591. dblRight = TaggedInt::ToDouble(aRight);
  592. break;
  593. case TypeIds_Number:
  594. dblRight = JavascriptNumber::GetValue(aRight);
  595. break;
  596. default:
  597. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  598. break;
  599. }
  600. break;
  601. case TypeIds_Int64Number:
  602. {
  603. switch (rightType)
  604. {
  605. case TypeIds_Int64Number:
  606. {
  607. __int64 leftValue = JavascriptInt64Number::FromVar(aLeft)->GetValue();
  608. __int64 rightValue = JavascriptInt64Number::FromVar(aRight)->GetValue();
  609. return leftValue < rightValue;
  610. }
  611. break;
  612. case TypeIds_UInt64Number:
  613. {
  614. __int64 leftValue = JavascriptInt64Number::FromVar(aLeft)->GetValue();
  615. unsigned __int64 rightValue = JavascriptUInt64Number::FromVar(aRight)->GetValue();
  616. if (rightValue <= INT_MAX && leftValue >= 0)
  617. {
  618. return leftValue < (__int64)rightValue;
  619. }
  620. }
  621. break;
  622. }
  623. dblLeft = (double)JavascriptInt64Number::FromVar(aLeft)->GetValue();
  624. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  625. }
  626. break;
  627. // we cannot do double conversion between 2 int64 numbers as we can get wrong result after conversion
  628. // i.e., two different numbers become the same after losing precision. We'll continue dbl comparison
  629. // if either number is not an int64 number.
  630. case TypeIds_UInt64Number:
  631. {
  632. switch (rightType)
  633. {
  634. case TypeIds_Int64Number:
  635. {
  636. unsigned __int64 leftValue = JavascriptUInt64Number::FromVar(aLeft)->GetValue();
  637. __int64 rightValue = JavascriptInt64Number::FromVar(aRight)->GetValue();
  638. if (leftValue < INT_MAX && rightValue >= 0)
  639. {
  640. return (__int64)leftValue < rightValue;
  641. }
  642. }
  643. break;
  644. case TypeIds_UInt64Number:
  645. {
  646. unsigned __int64 leftValue = JavascriptUInt64Number::FromVar(aLeft)->GetValue();
  647. unsigned __int64 rightValue = JavascriptUInt64Number::FromVar(aRight)->GetValue();
  648. return leftValue < rightValue;
  649. }
  650. break;
  651. }
  652. dblLeft = (double)JavascriptUInt64Number::FromVar(aLeft)->GetValue();
  653. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  654. }
  655. break;
  656. case TypeIds_String:
  657. switch (rightType)
  658. {
  659. case TypeIds_Integer:
  660. case TypeIds_Number:
  661. case TypeIds_Boolean:
  662. break;
  663. default:
  664. aRight = JavascriptConversion::ToPrimitive(aRight, JavascriptHint::HintNumber, scriptContext);
  665. rightType = JavascriptOperators::GetTypeId(aRight);
  666. if (rightType != TypeIds_String)
  667. {
  668. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  669. break;
  670. }
  671. case TypeIds_String:
  672. return JavascriptString::LessThan(aLeft, aRight);
  673. }
  674. dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);
  675. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  676. break;
  677. case TypeIds_Boolean:
  678. case TypeIds_Null:
  679. case TypeIds_Undefined:
  680. case TypeIds_Symbol:
  681. dblLeft = JavascriptConversion::ToNumber(aLeft, scriptContext);
  682. dblRight = JavascriptConversion::ToNumber(aRight, scriptContext);
  683. break;
  684. default:
  685. if (leftFirst)
  686. {
  687. aLeft = JavascriptConversion::ToPrimitive(aLeft, JavascriptHint::HintNumber, scriptContext);
  688. aRight = JavascriptConversion::ToPrimitive(aRight, JavascriptHint::HintNumber, scriptContext);
  689. }
  690. else
  691. {
  692. aRight = JavascriptConversion::ToPrimitive(aRight, JavascriptHint::HintNumber, scriptContext);
  693. aLeft = JavascriptConversion::ToPrimitive(aLeft, JavascriptHint::HintNumber, scriptContext);
  694. }
  695. //BugFix: When @@ToPrimitive of an object is overridden with a function that returns null/undefined
  696. //this helper will fall into a inescapable goto loop as the checks for null/undefined were outside of the path
  697. return RelationalComparisonHelper(aLeft, aRight, scriptContext, leftFirst, undefinedAs);
  698. }
  699. //
  700. // And +0,-0 that is not implemented fully
  701. //
  702. if (JavascriptNumber::IsNan(dblLeft) || JavascriptNumber::IsNan(dblRight))
  703. {
  704. return undefinedAs;
  705. }
  706. // this will succeed for -0.0 == 0.0 case as well
  707. if (dblLeft == dblRight)
  708. {
  709. return false;
  710. }
  711. return dblLeft < dblRight;
  712. }
  713. #ifdef ENABLE_SIMDJS
  714. BOOL JavascriptOperators::StrictEqualSIMD(Var aLeft, Var aRight, ScriptContext* scriptContext)
  715. {
  716. TypeId leftTid = JavascriptOperators::GetTypeId(aLeft);
  717. TypeId rightTid = JavascriptOperators::GetTypeId(aRight);
  718. bool result = false;
  719. if (leftTid != rightTid)
  720. {
  721. return result;
  722. }
  723. SIMDValue leftSimd;
  724. SIMDValue rightSimd;
  725. switch (leftTid)
  726. {
  727. case TypeIds_SIMDBool8x16:
  728. leftSimd = JavascriptSIMDBool8x16::FromVar(aLeft)->GetValue();
  729. rightSimd = JavascriptSIMDBool8x16::FromVar(aRight)->GetValue();
  730. return (leftSimd == rightSimd);
  731. case TypeIds_SIMDBool16x8:
  732. leftSimd = JavascriptSIMDBool16x8::FromVar(aLeft)->GetValue();
  733. rightSimd = JavascriptSIMDBool16x8::FromVar(aRight)->GetValue();
  734. return (leftSimd == rightSimd);
  735. case TypeIds_SIMDBool32x4:
  736. leftSimd = JavascriptSIMDBool32x4::FromVar(aLeft)->GetValue();
  737. rightSimd = JavascriptSIMDBool32x4::FromVar(aRight)->GetValue();
  738. return (leftSimd == rightSimd);
  739. case TypeIds_SIMDInt8x16:
  740. leftSimd = JavascriptSIMDInt8x16::FromVar(aLeft)->GetValue();
  741. rightSimd = JavascriptSIMDInt8x16::FromVar(aRight)->GetValue();
  742. return (leftSimd == rightSimd);
  743. case TypeIds_SIMDInt16x8:
  744. leftSimd = JavascriptSIMDInt16x8::FromVar(aLeft)->GetValue();
  745. rightSimd = JavascriptSIMDInt16x8::FromVar(aRight)->GetValue();
  746. return (leftSimd == rightSimd);
  747. case TypeIds_SIMDInt32x4:
  748. leftSimd = JavascriptSIMDInt32x4::FromVar(aLeft)->GetValue();
  749. rightSimd = JavascriptSIMDInt32x4::FromVar(aRight)->GetValue();
  750. return (leftSimd == rightSimd);
  751. case TypeIds_SIMDUint8x16:
  752. leftSimd = JavascriptSIMDUint8x16::FromVar(aLeft)->GetValue();
  753. rightSimd = JavascriptSIMDUint8x16::FromVar(aRight)->GetValue();
  754. return (leftSimd == rightSimd);
  755. case TypeIds_SIMDUint16x8:
  756. leftSimd = JavascriptSIMDUint16x8::FromVar(aLeft)->GetValue();
  757. rightSimd = JavascriptSIMDUint16x8::FromVar(aRight)->GetValue();
  758. return (leftSimd == rightSimd);
  759. case TypeIds_SIMDUint32x4:
  760. leftSimd = JavascriptSIMDUint32x4::FromVar(aLeft)->GetValue();
  761. rightSimd = JavascriptSIMDUint32x4::FromVar(aRight)->GetValue();
  762. return (leftSimd == rightSimd);
  763. case TypeIds_SIMDFloat32x4:
  764. leftSimd = JavascriptSIMDFloat32x4::FromVar(aLeft)->GetValue();
  765. rightSimd = JavascriptSIMDFloat32x4::FromVar(aRight)->GetValue();
  766. result = true;
  767. for (int i = 0; i < 4; ++i)
  768. {
  769. Var laneVarLeft = JavascriptNumber::ToVarWithCheck(leftSimd.f32[i], scriptContext);
  770. Var laneVarRight = JavascriptNumber::ToVarWithCheck(rightSimd.f32[i], scriptContext);
  771. result = result && JavascriptOperators::Equal(laneVarLeft, laneVarRight, scriptContext);
  772. }
  773. return result;
  774. default:
  775. Assert(UNREACHED);
  776. }
  777. return result;
  778. }
  779. #endif
  780. BOOL JavascriptOperators::StrictEqualString(Var aLeft, Var aRight)
  781. {
  782. Assert(JavascriptOperators::GetTypeId(aRight) == TypeIds_String);
  783. if (JavascriptOperators::GetTypeId(aLeft) != TypeIds_String)
  784. return false;
  785. return JavascriptString::Equals(aLeft, aRight);
  786. }
  787. BOOL JavascriptOperators::StrictEqualEmptyString(Var aLeft)
  788. {
  789. TypeId leftType = JavascriptOperators::GetTypeId(aLeft);
  790. if (leftType != TypeIds_String)
  791. return false;
  792. return JavascriptString::FromVar(aLeft)->GetLength() == 0;
  793. }
  794. BOOL JavascriptOperators::StrictEqual(Var aLeft, Var aRight, ScriptContext* requestContext)
  795. {
  796. double dblLeft, dblRight;
  797. TypeId leftType = JavascriptOperators::GetTypeId(aLeft);
  798. TypeId rightType = JavascriptOperators::GetTypeId(aRight);
  799. switch (leftType)
  800. {
  801. case TypeIds_String:
  802. switch (rightType)
  803. {
  804. case TypeIds_String:
  805. return JavascriptString::Equals(aLeft, aRight);
  806. }
  807. return FALSE;
  808. case TypeIds_Integer:
  809. switch (rightType)
  810. {
  811. case TypeIds_Integer:
  812. return aLeft == aRight;
  813. // we don't need to worry about int64: it cannot equal as we create
  814. // JavascriptInt64Number only in overflow scenarios.
  815. case TypeIds_Number:
  816. dblLeft = TaggedInt::ToDouble(aLeft);
  817. dblRight = JavascriptNumber::GetValue(aRight);
  818. goto CommonNumber;
  819. }
  820. return FALSE;
  821. case TypeIds_Int64Number:
  822. switch (rightType)
  823. {
  824. case TypeIds_Int64Number:
  825. {
  826. __int64 leftValue = JavascriptInt64Number::FromVar(aLeft)->GetValue();
  827. __int64 rightValue = JavascriptInt64Number::FromVar(aRight)->GetValue();
  828. return leftValue == rightValue;
  829. }
  830. case TypeIds_UInt64Number:
  831. {
  832. __int64 leftValue = JavascriptInt64Number::FromVar(aLeft)->GetValue();
  833. unsigned __int64 rightValue = JavascriptInt64Number::FromVar(aRight)->GetValue();
  834. return ((unsigned __int64)leftValue == rightValue);
  835. }
  836. case TypeIds_Number:
  837. dblLeft = (double)JavascriptInt64Number::FromVar(aLeft)->GetValue();
  838. dblRight = JavascriptNumber::GetValue(aRight);
  839. goto CommonNumber;
  840. }
  841. return FALSE;
  842. case TypeIds_UInt64Number:
  843. switch (rightType)
  844. {
  845. case TypeIds_Int64Number:
  846. {
  847. unsigned __int64 leftValue = JavascriptUInt64Number::FromVar(aLeft)->GetValue();
  848. __int64 rightValue = JavascriptInt64Number::FromVar(aRight)->GetValue();
  849. return (leftValue == (unsigned __int64)rightValue);
  850. }
  851. case TypeIds_UInt64Number:
  852. {
  853. unsigned __int64 leftValue = JavascriptUInt64Number::FromVar(aLeft)->GetValue();
  854. unsigned __int64 rightValue = JavascriptInt64Number::FromVar(aRight)->GetValue();
  855. return leftValue == rightValue;
  856. }
  857. case TypeIds_Number:
  858. dblLeft = (double)JavascriptUInt64Number::FromVar(aLeft)->GetValue();
  859. dblRight = JavascriptNumber::GetValue(aRight);
  860. goto CommonNumber;
  861. }
  862. return FALSE;
  863. case TypeIds_Number:
  864. switch (rightType)
  865. {
  866. case TypeIds_Integer:
  867. dblLeft = JavascriptNumber::GetValue(aLeft);
  868. dblRight = TaggedInt::ToDouble(aRight);
  869. goto CommonNumber;
  870. case TypeIds_Int64Number:
  871. dblLeft = JavascriptNumber::GetValue(aLeft);
  872. dblRight = (double)JavascriptInt64Number::FromVar(aRight)->GetValue();
  873. goto CommonNumber;
  874. case TypeIds_UInt64Number:
  875. dblLeft = JavascriptNumber::GetValue(aLeft);
  876. dblRight = (double)JavascriptUInt64Number::FromVar(aRight)->GetValue();
  877. goto CommonNumber;
  878. case TypeIds_Number:
  879. dblLeft = JavascriptNumber::GetValue(aLeft);
  880. dblRight = JavascriptNumber::GetValue(aRight);
  881. CommonNumber:
  882. return FEqualDbl(dblLeft, dblRight);
  883. }
  884. return FALSE;
  885. case TypeIds_Boolean:
  886. switch (rightType)
  887. {
  888. case TypeIds_Boolean:
  889. return aLeft == aRight;
  890. }
  891. return FALSE;
  892. case TypeIds_Undefined:
  893. return rightType == TypeIds_Undefined;
  894. case TypeIds_Null:
  895. return rightType == TypeIds_Null;
  896. case TypeIds_Array:
  897. return (rightType == TypeIds_Array && aLeft == aRight);
  898. case TypeIds_Symbol:
  899. switch (rightType)
  900. {
  901. case TypeIds_Symbol:
  902. {
  903. const PropertyRecord* leftValue = JavascriptSymbol::FromVar(aLeft)->GetValue();
  904. const PropertyRecord* rightValue = JavascriptSymbol::FromVar(aRight)->GetValue();
  905. return leftValue == rightValue;
  906. }
  907. }
  908. return false;
  909. case TypeIds_GlobalObject:
  910. case TypeIds_HostDispatch:
  911. switch (rightType)
  912. {
  913. case TypeIds_HostDispatch:
  914. case TypeIds_GlobalObject:
  915. {
  916. BOOL result;
  917. if(RecyclableObject::FromVar(aLeft)->StrictEquals(aRight, &result, requestContext))
  918. {
  919. return result;
  920. }
  921. return false;
  922. }
  923. }
  924. break;
  925. case TypeIds_Function:
  926. if (rightType == TypeIds_Function)
  927. {
  928. // In ES5 in certain cases (ES5 10.6.14(strict), 13.2.19(strict), 15.3.4.5.20-21) we return a function that throws type error.
  929. // For different scenarios we return different instances of the function, which differ by exception/error message.
  930. // According to ES5, this is the same [[ThrowTypeError]] (thrower) internal function, thus they should be equal.
  931. if (JavascriptFunction::FromVar(aLeft)->IsThrowTypeErrorFunction() &&
  932. JavascriptFunction::FromVar(aRight)->IsThrowTypeErrorFunction())
  933. {
  934. return true;
  935. }
  936. }
  937. break;
  938. #ifdef ENABLE_SIMDJS
  939. case TypeIds_SIMDBool8x16:
  940. case TypeIds_SIMDInt8x16:
  941. case TypeIds_SIMDUint8x16:
  942. case TypeIds_SIMDBool16x8:
  943. case TypeIds_SIMDInt16x8:
  944. case TypeIds_SIMDUint16x8:
  945. case TypeIds_SIMDBool32x4:
  946. case TypeIds_SIMDInt32x4:
  947. case TypeIds_SIMDUint32x4:
  948. case TypeIds_SIMDFloat32x4:
  949. case TypeIds_SIMDFloat64x2:
  950. return StrictEqualSIMD(aLeft, aRight, requestContext);
  951. break;
  952. #endif
  953. }
  954. if (RecyclableObject::FromVar(aLeft)->CanHaveInterceptors())
  955. {
  956. BOOL result;
  957. if (RecyclableObject::FromVar(aLeft)->StrictEquals(aRight, &result, requestContext))
  958. {
  959. if (result)
  960. {
  961. return TRUE;
  962. }
  963. }
  964. }
  965. if (!TaggedNumber::Is(aRight) && RecyclableObject::FromVar(aRight)->CanHaveInterceptors())
  966. {
  967. BOOL result;
  968. if (RecyclableObject::FromVar(aRight)->StrictEquals(aLeft, &result, requestContext))
  969. {
  970. if (result)
  971. {
  972. return TRUE;
  973. }
  974. }
  975. }
  976. return aLeft == aRight;
  977. }
  978. BOOL JavascriptOperators::HasOwnProperty(Var instance, PropertyId propertyId, ScriptContext *requestContext)
  979. {
  980. if (TaggedNumber::Is(instance))
  981. {
  982. return FALSE;
  983. }
  984. else
  985. {
  986. RecyclableObject* object = RecyclableObject::FromVar(instance);
  987. if (JavascriptProxy::Is(instance))
  988. {
  989. PropertyDescriptor desc;
  990. return GetOwnPropertyDescriptor(object, propertyId, requestContext, &desc);
  991. }
  992. else
  993. {
  994. PropertyString *propString = requestContext->TryGetPropertyString(propertyId);
  995. if (propString != nullptr)
  996. {
  997. const PropertyCache *propCache = propString->GetPropertyCache();
  998. if (object->GetType() == propCache->type)
  999. {
  1000. // The type cached for the property was the same as the type of this object
  1001. // (i.e. obj in obj.hasOwnProperty), so we know the answer is "true".
  1002. Assert(TRUE == (object && object->HasOwnProperty(propertyId))); // sanity check on the fastpath result
  1003. return TRUE;
  1004. }
  1005. }
  1006. return object && object->HasOwnProperty(propertyId);
  1007. }
  1008. }
  1009. }
  1010. BOOL JavascriptOperators::GetOwnAccessors(Var instance, PropertyId propertyId, Var* getter, Var* setter, ScriptContext * requestContext)
  1011. {
  1012. BOOL result;
  1013. if (TaggedNumber::Is(instance))
  1014. {
  1015. result = false;
  1016. }
  1017. else
  1018. {
  1019. RecyclableObject* object = RecyclableObject::FromVar(instance);
  1020. result = object && object->GetAccessors(propertyId, getter, setter, requestContext);
  1021. }
  1022. return result;
  1023. }
  1024. JavascriptArray* JavascriptOperators::GetOwnPropertyNames(Var instance, ScriptContext *scriptContext)
  1025. {
  1026. RecyclableObject *object = RecyclableObject::FromVar(ToObject(instance, scriptContext));
  1027. if (JavascriptProxy::Is(instance))
  1028. {
  1029. JavascriptProxy* proxy = JavascriptProxy::FromVar(instance);
  1030. return proxy->PropertyKeysTrap(JavascriptProxy::KeysTrapKind::GetOwnPropertyNamesKind);
  1031. }
  1032. return JavascriptObject::CreateOwnStringPropertiesHelper(object, scriptContext);
  1033. }
  1034. JavascriptArray* JavascriptOperators::GetOwnPropertySymbols(Var instance, ScriptContext *scriptContext)
  1035. {
  1036. RecyclableObject *object = RecyclableObject::FromVar(ToObject(instance, scriptContext));
  1037. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(GetOwnPropertySymbolsCount);
  1038. if (JavascriptProxy::Is(instance))
  1039. {
  1040. JavascriptProxy* proxy = JavascriptProxy::FromVar(instance);
  1041. return proxy->PropertyKeysTrap(JavascriptProxy::KeysTrapKind::GetOwnPropertySymbolKind);
  1042. }
  1043. return JavascriptObject::CreateOwnSymbolPropertiesHelper(object, scriptContext);
  1044. }
  1045. JavascriptArray* JavascriptOperators::GetOwnPropertyKeys(Var instance, ScriptContext* scriptContext)
  1046. {
  1047. RecyclableObject *object = RecyclableObject::FromVar(ToObject(instance, scriptContext));
  1048. if (JavascriptProxy::Is(instance))
  1049. {
  1050. JavascriptProxy* proxy = JavascriptProxy::FromVar(instance);
  1051. return proxy->PropertyKeysTrap(JavascriptProxy::KeysTrapKind::KeysKind);
  1052. }
  1053. return JavascriptObject::CreateOwnStringSymbolPropertiesHelper(object, scriptContext);
  1054. }
  1055. JavascriptArray* JavascriptOperators::GetOwnEnumerablePropertyNames(Var instance, ScriptContext* scriptContext)
  1056. {
  1057. RecyclableObject *object = RecyclableObject::FromVar(ToObject(instance, scriptContext));
  1058. if (JavascriptProxy::Is(instance))
  1059. {
  1060. JavascriptProxy* proxy = JavascriptProxy::FromVar(instance);
  1061. JavascriptArray* proxyResult = proxy->PropertyKeysTrap(JavascriptProxy::KeysTrapKind::GetOwnPropertyNamesKind);
  1062. JavascriptArray* proxyResultToReturn = scriptContext->GetLibrary()->CreateArray(0);
  1063. // filter enumerable keys
  1064. uint32 resultLength = proxyResult->GetLength();
  1065. Var element;
  1066. const Js::PropertyRecord *propertyRecord;
  1067. uint32 index = 0;
  1068. for (uint32 i = 0; i < resultLength; i++)
  1069. {
  1070. element = proxyResult->DirectGetItem(i);
  1071. Assert(!JavascriptSymbol::Is(element));
  1072. PropertyDescriptor propertyDescriptor;
  1073. JavascriptConversion::ToPropertyKey(element, scriptContext, &propertyRecord);
  1074. if (JavascriptOperators::GetOwnPropertyDescriptor(RecyclableObject::FromVar(instance), propertyRecord->GetPropertyId(), scriptContext, &propertyDescriptor))
  1075. {
  1076. if (propertyDescriptor.IsEnumerable())
  1077. {
  1078. proxyResultToReturn->DirectSetItemAt(index++, element);
  1079. }
  1080. }
  1081. }
  1082. return proxyResultToReturn;
  1083. }
  1084. return JavascriptObject::CreateOwnEnumerableStringPropertiesHelper(object, scriptContext);
  1085. }
  1086. JavascriptArray* JavascriptOperators::GetOwnEnumerablePropertyNamesSymbols(Var instance, ScriptContext* scriptContext)
  1087. {
  1088. RecyclableObject *object = RecyclableObject::FromVar(ToObject(instance, scriptContext));
  1089. if (JavascriptProxy::Is(instance))
  1090. {
  1091. JavascriptProxy* proxy = JavascriptProxy::FromVar(instance);
  1092. return proxy->PropertyKeysTrap(JavascriptProxy::KeysTrapKind::KeysKind);
  1093. }
  1094. return JavascriptObject::CreateOwnEnumerableStringSymbolPropertiesHelper(object, scriptContext);
  1095. }
  1096. BOOL JavascriptOperators::GetOwnProperty(Var instance, PropertyId propertyId, Var* value, ScriptContext* requestContext)
  1097. {
  1098. BOOL result;
  1099. if (TaggedNumber::Is(instance))
  1100. {
  1101. result = false;
  1102. }
  1103. else
  1104. {
  1105. RecyclableObject* object = RecyclableObject::FromVar(instance);
  1106. result = object && object->GetProperty(object, propertyId, value, NULL, requestContext);
  1107. }
  1108. return result;
  1109. }
  1110. BOOL JavascriptOperators::GetOwnPropertyDescriptor(RecyclableObject* obj, JavascriptString* propertyKey, ScriptContext* scriptContext, PropertyDescriptor* propertyDescriptor)
  1111. {
  1112. return JavascriptOperators::GetOwnPropertyDescriptor(obj, JavascriptOperators::GetPropertyId(propertyKey, scriptContext), scriptContext, propertyDescriptor);
  1113. }
  1114. // ES5's [[GetOwnProperty]].
  1115. // Return value:
  1116. // FALSE means "undefined" PD.
  1117. // TRUE means success. The propertyDescriptor parameter gets the descriptor.
  1118. //
  1119. BOOL JavascriptOperators::GetOwnPropertyDescriptor(RecyclableObject* obj, PropertyId propertyId, ScriptContext* scriptContext, PropertyDescriptor* propertyDescriptor)
  1120. {
  1121. Assert(obj);
  1122. Assert(scriptContext);
  1123. Assert(propertyDescriptor);
  1124. if (JavascriptProxy::Is(obj))
  1125. {
  1126. return JavascriptProxy::GetOwnPropertyDescriptor(obj, propertyId, scriptContext, propertyDescriptor);
  1127. }
  1128. Var getter, setter;
  1129. if (false == JavascriptOperators::GetOwnAccessors(obj, propertyId, &getter, &setter, scriptContext))
  1130. {
  1131. Var value;
  1132. if (false == JavascriptOperators::GetOwnProperty(obj, propertyId, &value, scriptContext))
  1133. {
  1134. return FALSE;
  1135. }
  1136. if (nullptr != value)
  1137. {
  1138. propertyDescriptor->SetValue(value);
  1139. }
  1140. //CONSIDER : Its expensive to query for each flag from type system. Combine this with the GetOwnProperty to get all the flags
  1141. //at once. This will require a new API from type system and override in all the types which overrides IsEnumerable etc.
  1142. //Currently there is no performance tuning for ES5. This should be ok.
  1143. propertyDescriptor->SetWritable(FALSE != obj->IsWritable(propertyId));
  1144. }
  1145. else
  1146. {
  1147. if (nullptr == getter)
  1148. {
  1149. getter = scriptContext->GetLibrary()->GetUndefined();
  1150. }
  1151. propertyDescriptor->SetGetter(getter);
  1152. if (nullptr == setter)
  1153. {
  1154. setter = scriptContext->GetLibrary()->GetUndefined();
  1155. }
  1156. propertyDescriptor->SetSetter(setter);
  1157. }
  1158. propertyDescriptor->SetConfigurable(FALSE != obj->IsConfigurable(propertyId));
  1159. propertyDescriptor->SetEnumerable(FALSE != obj->IsEnumerable(propertyId));
  1160. return TRUE;
  1161. }
  1162. inline RecyclableObject* JavascriptOperators::GetPrototypeNoTrap(RecyclableObject* instance)
  1163. {
  1164. Type* type = instance->GetType();
  1165. if (type->HasSpecialPrototype())
  1166. {
  1167. if (type->GetTypeId() == TypeIds_Proxy)
  1168. {
  1169. // get back null
  1170. Assert(type->GetPrototype() == instance->GetScriptContext()->GetLibrary()->GetNull());
  1171. return type->GetPrototype();
  1172. }
  1173. else
  1174. {
  1175. return instance->GetPrototypeSpecial();
  1176. }
  1177. }
  1178. return type->GetPrototype();
  1179. }
  1180. BOOL JavascriptOperators::IsArray(Var instanceVar)
  1181. {
  1182. if (!RecyclableObject::Is(instanceVar))
  1183. {
  1184. return FALSE;
  1185. }
  1186. RecyclableObject* instance = RecyclableObject::FromVar(instanceVar);
  1187. if (DynamicObject::IsAnyArray(instance))
  1188. {
  1189. return TRUE;
  1190. }
  1191. if (JavascriptProxy::Is(instanceVar))
  1192. {
  1193. JavascriptProxy* proxy = JavascriptProxy::FromVar(instanceVar);
  1194. return IsArray(proxy->GetTarget());
  1195. }
  1196. TypeId remoteTypeId = TypeIds_Limit;
  1197. if (JavascriptOperators::GetRemoteTypeId(instanceVar, &remoteTypeId) &&
  1198. DynamicObject::IsAnyArrayTypeId(remoteTypeId))
  1199. {
  1200. return TRUE;
  1201. }
  1202. return FALSE;
  1203. }
  1204. BOOL JavascriptOperators::IsConstructor(Var instanceVar)
  1205. {
  1206. if (!RecyclableObject::Is(instanceVar))
  1207. {
  1208. return FALSE;
  1209. }
  1210. if (JavascriptProxy::Is(instanceVar))
  1211. {
  1212. JavascriptProxy* proxy = JavascriptProxy::FromVar(instanceVar);
  1213. return IsConstructor(proxy->GetTarget());
  1214. }
  1215. if (!JavascriptFunction::Is(instanceVar))
  1216. {
  1217. return FALSE;
  1218. }
  1219. return JavascriptFunction::FromVar(instanceVar)->IsConstructor();
  1220. }
  1221. BOOL JavascriptOperators::IsConcatSpreadable(Var instanceVar)
  1222. {
  1223. // an object is spreadable under two condition, either it is a JsArray
  1224. // or you define an isconcatSpreadable flag on it.
  1225. if (!JavascriptOperators::IsObject(instanceVar))
  1226. {
  1227. return false;
  1228. }
  1229. RecyclableObject* instance = RecyclableObject::FromVar(instanceVar);
  1230. ScriptContext* scriptContext = instance->GetScriptContext();
  1231. if (!PHASE_OFF1(IsConcatSpreadableCachePhase))
  1232. {
  1233. BOOL retVal = FALSE;
  1234. Type *instanceType = instance->GetType();
  1235. IsConcatSpreadableCache *isConcatSpreadableCache = scriptContext->GetThreadContext()->GetIsConcatSpreadableCache();
  1236. if (isConcatSpreadableCache->TryGetIsConcatSpreadable(instanceType, &retVal))
  1237. {
  1238. OUTPUT_TRACE(Phase::IsConcatSpreadableCachePhase, _u("IsConcatSpreadableCache hit: %p\n"), instanceType);
  1239. return retVal;
  1240. }
  1241. Var spreadable = nullptr;
  1242. BOOL hasUserDefinedSpreadable = JavascriptOperators::GetProperty(instance, instance, PropertyIds::_symbolIsConcatSpreadable, &spreadable, scriptContext);
  1243. if (hasUserDefinedSpreadable && spreadable != scriptContext->GetLibrary()->GetUndefined())
  1244. {
  1245. return JavascriptConversion::ToBoolean(spreadable, scriptContext);
  1246. }
  1247. retVal = JavascriptOperators::IsArray(instance);
  1248. if (!hasUserDefinedSpreadable)
  1249. {
  1250. OUTPUT_TRACE(Phase::IsConcatSpreadableCachePhase, _u("IsConcatSpreadableCache saved: %p\n"), instanceType);
  1251. isConcatSpreadableCache->CacheIsConcatSpreadable(instanceType, retVal);
  1252. }
  1253. return retVal;
  1254. }
  1255. Var spreadable = JavascriptOperators::GetProperty(instance, PropertyIds::_symbolIsConcatSpreadable, scriptContext);
  1256. if (spreadable != scriptContext->GetLibrary()->GetUndefined())
  1257. {
  1258. return JavascriptConversion::ToBoolean(spreadable, scriptContext);
  1259. }
  1260. return JavascriptOperators::IsArray(instance);
  1261. }
  1262. Var JavascriptOperators::OP_LdCustomSpreadIteratorList(Var aRight, ScriptContext* scriptContext)
  1263. {
  1264. #if ENABLE_COPYONACCESS_ARRAY
  1265. // We know we're going to read from this array. Do the conversion before we try to perform checks on the head segment.
  1266. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(aRight);
  1267. #endif
  1268. RecyclableObject* function = GetIteratorFunction(aRight, scriptContext);
  1269. JavascriptMethod method = function->GetEntryPoint();
  1270. if (((JavascriptArray::Is(aRight) &&
  1271. (
  1272. method == JavascriptArray::EntryInfo::Values.GetOriginalEntryPoint()
  1273. // Verify that the head segment of the array covers all elements with no gaps.
  1274. // Accessing an element on the prototype could have side-effects that would invalidate the optimization.
  1275. && JavascriptArray::FromVar(aRight)->GetHead()->next == nullptr
  1276. && JavascriptArray::FromVar(aRight)->GetHead()->left == 0
  1277. && JavascriptArray::FromVar(aRight)->GetHead()->length == JavascriptArray::FromVar(aRight)->GetLength()
  1278. && JavascriptArray::FromVar(aRight)->HasNoMissingValues()
  1279. )) ||
  1280. (TypedArrayBase::Is(aRight) && method == TypedArrayBase::EntryInfo::Values.GetOriginalEntryPoint()))
  1281. // We can't optimize away the iterator if the array iterator prototype is user defined.
  1282. && !JavascriptLibrary::ArrayIteratorPrototypeHasUserDefinedNext(scriptContext))
  1283. {
  1284. return aRight;
  1285. }
  1286. ThreadContext *threadContext = scriptContext->GetThreadContext();
  1287. Var iteratorVar =
  1288. threadContext->ExecuteImplicitCall(function, ImplicitCall_Accessor, [=]() -> Var
  1289. {
  1290. return CALL_FUNCTION(function, CallInfo(Js::CallFlags_Value, 1), aRight);
  1291. });
  1292. if (!JavascriptOperators::IsObject(iteratorVar))
  1293. {
  1294. if (!threadContext->RecordImplicitException())
  1295. {
  1296. return scriptContext->GetLibrary()->GetUndefined();
  1297. }
  1298. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  1299. }
  1300. RecyclableObject* iterator = RecyclableObject::FromVar(iteratorVar);
  1301. return RecyclerNew(scriptContext->GetRecycler(), SpreadArgument, aRight, iterator, scriptContext->GetLibrary()->GetSpreadArgumentType());
  1302. }
  1303. BOOL JavascriptOperators::IsPropertyUnscopable(Var instanceVar, JavascriptString *propertyString)
  1304. {
  1305. // This never gets called.
  1306. Throw::InternalError();
  1307. }
  1308. BOOL JavascriptOperators::IsPropertyUnscopable(Var instanceVar, PropertyId propertyId)
  1309. {
  1310. RecyclableObject* instance = RecyclableObject::FromVar(instanceVar);
  1311. ScriptContext * scriptContext = instance->GetScriptContext();
  1312. Var unscopables = JavascriptOperators::GetProperty(instance, PropertyIds::_symbolUnscopables, scriptContext);
  1313. if (JavascriptOperators::IsObject(unscopables))
  1314. {
  1315. DynamicObject *unscopablesList = DynamicObject::FromVar(unscopables);
  1316. Var value;
  1317. //8.1.1.2.1.9.c If blocked is not undefined
  1318. if (JavascriptOperators::GetProperty(unscopablesList, propertyId, &value, scriptContext))
  1319. {
  1320. return JavascriptConversion::ToBoolean(value, scriptContext);
  1321. }
  1322. }
  1323. return false;
  1324. }
  1325. BOOL JavascriptOperators::HasProperty(RecyclableObject* instance, PropertyId propertyId)
  1326. {
  1327. while (JavascriptOperators::GetTypeId(instance) != TypeIds_Null)
  1328. {
  1329. if (instance->HasProperty(propertyId))
  1330. {
  1331. return true;
  1332. }
  1333. instance = JavascriptOperators::GetPrototypeNoTrap(instance);
  1334. }
  1335. return false;
  1336. }
  1337. BOOL JavascriptOperators::HasPropertyUnscopables(RecyclableObject* instance, PropertyId propertyId)
  1338. {
  1339. return JavascriptOperators::HasProperty(instance, propertyId)
  1340. && !IsPropertyUnscopable(instance, propertyId);
  1341. }
  1342. BOOL JavascriptOperators::HasRootProperty(RecyclableObject* instance, PropertyId propertyId)
  1343. {
  1344. Assert(RootObjectBase::Is(instance));
  1345. RootObjectBase* rootObject = static_cast<RootObjectBase*>(instance);
  1346. if (rootObject->HasRootProperty(propertyId))
  1347. {
  1348. return true;
  1349. }
  1350. instance = instance->GetPrototype();
  1351. return HasProperty(instance, propertyId);
  1352. }
  1353. BOOL JavascriptOperators::HasProxyOrPrototypeInlineCacheProperty(RecyclableObject* instance, PropertyId propertyId)
  1354. {
  1355. TypeId typeId;
  1356. typeId = JavascriptOperators::GetTypeId(instance);
  1357. if (typeId == Js::TypeIds_Proxy)
  1358. {
  1359. // let's be more aggressive to disable inline prototype cache when proxy is presented in the prototypechain
  1360. return true;
  1361. }
  1362. do
  1363. {
  1364. instance = instance->GetPrototype();
  1365. typeId = JavascriptOperators::GetTypeId(instance);
  1366. if (typeId == Js::TypeIds_Proxy)
  1367. {
  1368. // let's be more aggressive to disable inline prototype cache when proxy is presented in the prototypechain
  1369. return true;
  1370. }
  1371. if (typeId == TypeIds_Null)
  1372. {
  1373. break;
  1374. }
  1375. /* We can rule out object with deferred type handler, because they would have expanded if they are in the cache */
  1376. if (!instance->HasDeferredTypeHandler() && instance->HasProperty(propertyId)) { return true; }
  1377. } while (typeId != TypeIds_Null);
  1378. return false;
  1379. }
  1380. BOOL JavascriptOperators::OP_HasProperty(Var instance, PropertyId propertyId, ScriptContext* scriptContext)
  1381. {
  1382. RecyclableObject* object = TaggedNumber::Is(instance) ?
  1383. scriptContext->GetLibrary()->GetNumberPrototype() :
  1384. RecyclableObject::FromVar(instance);
  1385. BOOL result = HasProperty(object, propertyId);
  1386. return result;
  1387. }
  1388. BOOL JavascriptOperators::OP_HasOwnProperty(Var instance, PropertyId propertyId, ScriptContext* scriptContext)
  1389. {
  1390. RecyclableObject* object = TaggedNumber::Is(instance) ?
  1391. scriptContext->GetLibrary()->GetNumberPrototype() :
  1392. RecyclableObject::FromVar(instance);
  1393. BOOL result = HasOwnProperty(object, propertyId, scriptContext);
  1394. return result;
  1395. }
  1396. // CONSIDER: Have logic similar to HasOwnPropertyNoHostObjectForHeapEnum
  1397. BOOL JavascriptOperators::HasOwnPropertyNoHostObject(Var instance, PropertyId propertyId)
  1398. {
  1399. AssertMsg(!TaggedNumber::Is(instance), "HasOwnPropertyNoHostObject int passed");
  1400. RecyclableObject* object = RecyclableObject::FromVar(instance);
  1401. return object && object->HasOwnPropertyNoHostObject(propertyId);
  1402. }
  1403. // CONSIDER: Remove HasOwnPropertyNoHostObjectForHeapEnum and use GetOwnPropertyNoHostObjectForHeapEnum in its place by changing it
  1404. // to return BOOL, true or false with whether the property exists or not, and return the value if not getter/setter as an out param.
  1405. BOOL JavascriptOperators::HasOwnPropertyNoHostObjectForHeapEnum(Var instance, PropertyId propertyId, ScriptContext* requestContext, Var& getter, Var& setter)
  1406. {
  1407. AssertMsg(!TaggedNumber::Is(instance), "HasOwnPropertyNoHostObjectForHeapEnum int passed");
  1408. RecyclableObject * object = RecyclableObject::FromVar(instance);
  1409. if (StaticType::Is(object->GetTypeId()))
  1410. {
  1411. return FALSE;
  1412. }
  1413. getter = setter = NULL;
  1414. DynamicObject* dynamicObject = DynamicObject::FromVar(instance);
  1415. Assert(dynamicObject->GetScriptContext()->IsHeapEnumInProgress());
  1416. if (dynamicObject->UseDynamicObjectForNoHostObjectAccess())
  1417. {
  1418. if (!dynamicObject->DynamicObject::GetAccessors(propertyId, &getter, &setter, requestContext))
  1419. {
  1420. Var value;
  1421. if (!dynamicObject->DynamicObject::GetProperty(instance, propertyId, &value, NULL, requestContext) ||
  1422. (requestContext->IsUndeclBlockVar(value) && (ActivationObject::Is(instance) || RootObjectBase::Is(instance))))
  1423. {
  1424. return FALSE;
  1425. }
  1426. }
  1427. }
  1428. else
  1429. {
  1430. if (!object->GetAccessors(propertyId, &getter, &setter, requestContext))
  1431. {
  1432. Var value;
  1433. if (!object->GetProperty(instance, propertyId, &value, NULL, requestContext) ||
  1434. (requestContext->IsUndeclBlockVar(value) && (ActivationObject::Is(instance) || RootObjectBase::Is(instance))))
  1435. {
  1436. return FALSE;
  1437. }
  1438. }
  1439. }
  1440. return TRUE;
  1441. }
  1442. Var JavascriptOperators::GetOwnPropertyNoHostObjectForHeapEnum(Var instance, PropertyId propertyId, ScriptContext* requestContext, Var& getter, Var& setter)
  1443. {
  1444. AssertMsg(!TaggedNumber::Is(instance), "GetDataPropertyNoHostObject int passed");
  1445. Assert(HasOwnPropertyNoHostObjectForHeapEnum(instance, propertyId, requestContext, getter, setter) || getter || setter);
  1446. DynamicObject* dynamicObject = DynamicObject::FromVar(instance);
  1447. getter = setter = NULL;
  1448. if (NULL == dynamicObject)
  1449. {
  1450. return requestContext->GetLibrary()->GetUndefined();
  1451. }
  1452. Var returnVar = requestContext->GetLibrary()->GetUndefined();
  1453. BOOL result = FALSE;
  1454. if (dynamicObject->UseDynamicObjectForNoHostObjectAccess())
  1455. {
  1456. if (! dynamicObject->DynamicObject::GetAccessors(propertyId, &getter, &setter, requestContext))
  1457. {
  1458. result = dynamicObject->DynamicObject::GetProperty(instance, propertyId, &returnVar, NULL, requestContext);
  1459. }
  1460. }
  1461. else
  1462. {
  1463. if (! dynamicObject->GetAccessors(propertyId, &getter, &setter, requestContext))
  1464. {
  1465. result = dynamicObject->GetProperty(instance, propertyId, &returnVar, NULL, requestContext);
  1466. }
  1467. }
  1468. if (result)
  1469. {
  1470. return returnVar;
  1471. }
  1472. return requestContext->GetLibrary()->GetUndefined();
  1473. }
  1474. BOOL JavascriptOperators::OP_HasOwnPropScoped(Var scope, PropertyId propertyId, Var defaultInstance, ScriptContext* scriptContext)
  1475. {
  1476. AssertMsg(scope == scriptContext->GetLibrary()->GetNull() || JavascriptArray::Is(scope),
  1477. "Invalid scope chain pointer passed - should be null or an array");
  1478. if (JavascriptArray::Is(scope))
  1479. {
  1480. JavascriptArray* arrScope = JavascriptArray::FromVar(scope);
  1481. Var instance = arrScope->DirectGetItem(0);
  1482. return JavascriptOperators::OP_HasOwnProperty(instance, propertyId, scriptContext);
  1483. }
  1484. return JavascriptOperators::OP_HasOwnProperty(defaultInstance, propertyId, scriptContext);
  1485. }
  1486. BOOL JavascriptOperators::GetPropertyUnscopable(Var instance, RecyclableObject* propertyObject, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1487. {
  1488. return GetProperty_Internal<true>(instance, propertyObject, false, propertyId, value, requestContext, info);
  1489. }
  1490. BOOL JavascriptOperators::GetProperty(Var instance, RecyclableObject* propertyObject, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1491. {
  1492. return GetProperty_Internal<false>(instance, propertyObject, false, propertyId, value, requestContext, info);
  1493. }
  1494. BOOL JavascriptOperators::GetRootProperty(Var instance, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1495. {
  1496. return GetProperty_Internal<false>(instance, RecyclableObject::FromVar(instance), true, propertyId, value, requestContext, info);
  1497. }
  1498. template <bool unscopables>
  1499. BOOL JavascriptOperators::GetProperty_Internal(Var instance, RecyclableObject* propertyObject, const bool isRoot, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1500. {
  1501. if (TaggedNumber::Is(instance))
  1502. {
  1503. PropertyValueInfo::ClearCacheInfo(info);
  1504. }
  1505. RecyclableObject* object = propertyObject;
  1506. BOOL foundProperty = FALSE;
  1507. if (isRoot)
  1508. {
  1509. Assert(RootObjectBase::Is(object));
  1510. RootObjectBase* rootObject = static_cast<RootObjectBase*>(object);
  1511. foundProperty = rootObject->GetRootProperty(instance, propertyId, value, info, requestContext);
  1512. }
  1513. while (!foundProperty && JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  1514. {
  1515. if (unscopables && IsPropertyUnscopable(object, propertyId))
  1516. {
  1517. break;
  1518. }
  1519. else
  1520. {
  1521. if (object->GetProperty(instance, propertyId, value, info, requestContext))
  1522. {
  1523. foundProperty = true;
  1524. break;
  1525. }
  1526. }
  1527. if (object->SkipsPrototype())
  1528. {
  1529. break;
  1530. }
  1531. object = JavascriptOperators::GetPrototypeNoTrap(object);
  1532. }
  1533. if (foundProperty)
  1534. {
  1535. #if DBG
  1536. if (DynamicObject::Is(object))
  1537. {
  1538. DynamicObject* dynamicObject = (DynamicObject*)object;
  1539. DynamicTypeHandler* dynamicTypeHandler = dynamicObject->GetDynamicType()->GetTypeHandler();
  1540. Var property;
  1541. if (dynamicTypeHandler->CheckFixedProperty(requestContext->GetPropertyName(propertyId), &property, requestContext))
  1542. {
  1543. Assert(value == nullptr || *value == property);
  1544. }
  1545. }
  1546. #endif
  1547. // Don't cache the information if the value is undecl block var
  1548. // REVIEW: We might want to only check this if we need to (For LdRootFld or ScopedLdFld)
  1549. // Also we might want to throw here instead of checking it again in the caller
  1550. if (value && !requestContext->IsUndeclBlockVar(*value) && !WithScopeObject::Is(object))
  1551. {
  1552. CacheOperators::CachePropertyRead(instance, object, isRoot, propertyId, false, info, requestContext);
  1553. }
  1554. #ifdef TELEMETRY_JSO
  1555. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  1556. {
  1557. requestContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, value, /*successful: */true);
  1558. }
  1559. #endif
  1560. return TRUE;
  1561. }
  1562. else
  1563. {
  1564. #ifdef MISSING_PROPERTY_STATS
  1565. if (PHASE_STATS1(MissingPropertyCachePhase))
  1566. {
  1567. requestContext->RecordMissingPropertyMiss();
  1568. }
  1569. #endif
  1570. if (PHASE_TRACE1(MissingPropertyCachePhase))
  1571. {
  1572. Output::Print(_u("MissingPropertyCaching: Missing property %d on slow path.\n"), propertyId);
  1573. }
  1574. // Only cache missing property lookups for non-root field loads on objects that have PathTypeHandlers, because only these objects guarantee a type change when the property is added,
  1575. // which obviates the need to explicitly invalidate missing property inline caches.
  1576. if (!PHASE_OFF1(MissingPropertyCachePhase) && !isRoot && DynamicObject::Is(instance) && ((DynamicObject*)instance)->GetDynamicType()->GetTypeHandler()->IsPathTypeHandler())
  1577. {
  1578. #ifdef MISSING_PROPERTY_STATS
  1579. if (PHASE_STATS1(MissingPropertyCachePhase))
  1580. {
  1581. requestContext->RecordMissingPropertyCacheAttempt();
  1582. }
  1583. #endif
  1584. if (PHASE_TRACE1(MissingPropertyCachePhase))
  1585. {
  1586. Output::Print(_u("MissingPropertyCache: Caching missing property for property %d.\n"), propertyId);
  1587. }
  1588. PropertyValueInfo::Set(info, requestContext->GetLibrary()->GetMissingPropertyHolder(), 0);
  1589. CacheOperators::CachePropertyRead(instance, requestContext->GetLibrary()->GetMissingPropertyHolder(), isRoot, propertyId, true, info, requestContext);
  1590. }
  1591. #if defined(TELEMETRY_JSO) || defined(TELEMETRY_AddToCache) // enabled for `TELEMETRY_AddToCache`, because this is the property-not-found codepath where the normal TELEMETRY_AddToCache code wouldn't be executed.
  1592. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  1593. {
  1594. if (info && info->AllowResizingPolymorphicInlineCache()) // If in interpreted mode, not JIT.
  1595. {
  1596. requestContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, nullptr, /*successful: */false);
  1597. }
  1598. }
  1599. #endif
  1600. *value = requestContext->GetMissingPropertyResult();
  1601. return FALSE;
  1602. }
  1603. }
  1604. template<typename PropertyKeyType>
  1605. BOOL JavascriptOperators::GetPropertyWPCache(Var instance, RecyclableObject* propertyObject, PropertyKeyType propertyKey, Var* value, ScriptContext* requestContext, PropertyString * propertyString)
  1606. {
  1607. if (TaggedNumber::Is(instance))
  1608. {
  1609. propertyString = NULL;
  1610. }
  1611. PropertyValueInfo info;
  1612. RecyclableObject* object = propertyObject;
  1613. while (JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  1614. {
  1615. if (object->GetProperty(instance, propertyKey, value, &info, requestContext))
  1616. {
  1617. if (propertyString != NULL)
  1618. {
  1619. uint16 slotIndex = info.GetPropertyIndex();
  1620. if (slotIndex != Constants::NoSlot &&
  1621. info.GetInstance() == object &&
  1622. info.IsWritable() && !object->CanHaveInterceptors() &&
  1623. requestContext == object->GetScriptContext() &&
  1624. ((info.GetFlags() & (InlineCacheGetterFlag | InlineCacheSetterFlag)) == 0))
  1625. {
  1626. uint16 inlineOrAuxSlotIndex;
  1627. bool isInlineSlot;
  1628. DynamicObject::FromVar(info.GetInstance())->GetTypeHandler()->PropertyIndexToInlineOrAuxSlotIndex(slotIndex, &inlineOrAuxSlotIndex, &isInlineSlot);
  1629. propertyString->UpdateCache(info.GetInstance()->GetType(), inlineOrAuxSlotIndex, isInlineSlot, info.IsStoreFieldCacheEnabled());
  1630. }
  1631. }
  1632. return TRUE;
  1633. }
  1634. if (object->SkipsPrototype())
  1635. {
  1636. break;
  1637. }
  1638. object = JavascriptOperators::GetPrototypeNoTrap(object);
  1639. }
  1640. *value = requestContext->GetMissingPropertyResult();
  1641. return FALSE;
  1642. }
  1643. BOOL JavascriptOperators::GetPropertyObject(Var instance, ScriptContext * scriptContext, RecyclableObject** propertyObject)
  1644. {
  1645. Assert(propertyObject);
  1646. if (TaggedNumber::Is(instance))
  1647. {
  1648. *propertyObject = scriptContext->GetLibrary()->GetNumberPrototype();
  1649. return TRUE;
  1650. }
  1651. RecyclableObject* object = RecyclableObject::FromVar(instance);
  1652. TypeId typeId = object->GetTypeId();
  1653. *propertyObject = object;
  1654. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  1655. {
  1656. return FALSE;
  1657. }
  1658. return TRUE;
  1659. }
  1660. #if DBG
  1661. BOOL JavascriptOperators::IsPropertyObject(RecyclableObject * instance)
  1662. {
  1663. TypeId typeId = JavascriptOperators::GetTypeId(instance);
  1664. return (typeId != TypeIds_Integer && typeId != TypeIds_Null && typeId != TypeIds_Undefined);
  1665. }
  1666. #endif
  1667. Var JavascriptOperators::OP_GetProperty(Var instance, PropertyId propertyId, ScriptContext* scriptContext)
  1668. {
  1669. RecyclableObject* object = nullptr;
  1670. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  1671. {
  1672. if (scriptContext->GetThreadContext()->RecordImplicitException())
  1673. {
  1674. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined, scriptContext->GetPropertyName(propertyId)->GetBuffer());
  1675. }
  1676. else
  1677. {
  1678. return scriptContext->GetLibrary()->GetUndefined();
  1679. }
  1680. }
  1681. Var result = JavascriptOperators::GetProperty(instance, object, propertyId, scriptContext);
  1682. AssertMsg(result != nullptr, "result null in OP_GetProperty");
  1683. return result;
  1684. }
  1685. Var JavascriptOperators::OP_GetRootProperty(Var instance, PropertyId propertyId, PropertyValueInfo * info, ScriptContext* scriptContext)
  1686. {
  1687. AssertMsg(RootObjectBase::Is(instance), "Root must be an object!");
  1688. Var value;
  1689. if (JavascriptOperators::GetRootProperty(RecyclableObject::FromVar(instance), propertyId, &value, scriptContext, info))
  1690. {
  1691. if (scriptContext->IsUndeclBlockVar(value))
  1692. {
  1693. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  1694. }
  1695. return value;
  1696. }
  1697. const char16* propertyName = scriptContext->GetPropertyName(propertyId)->GetBuffer();
  1698. JavascriptFunction * caller = nullptr;
  1699. if (JavascriptStackWalker::GetCaller(&caller, scriptContext))
  1700. {
  1701. FunctionBody * callerBody = caller->GetFunctionBody();
  1702. if (callerBody && callerBody->GetUtf8SourceInfo()->GetIsXDomain())
  1703. {
  1704. propertyName = nullptr;
  1705. }
  1706. }
  1707. // Don't error if we disabled implicit calls
  1708. if (scriptContext->GetThreadContext()->RecordImplicitException())
  1709. {
  1710. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UndefVariable, propertyName);
  1711. }
  1712. return scriptContext->GetMissingPropertyResult();
  1713. }
  1714. Var JavascriptOperators::OP_GetThisScoped(FrameDisplay *pScope, Var defaultInstance, ScriptContext* scriptContext)
  1715. {
  1716. // NOTE: If changes are made to this logic be sure to update the debuggers as well
  1717. int length = pScope->GetLength();
  1718. for (int i = 0; i < length; i += 1)
  1719. {
  1720. Var value;
  1721. DynamicObject *obj = DynamicObject::FromVar(pScope->GetItem(i));
  1722. if (JavascriptOperators::GetProperty(obj, Js::PropertyIds::_lexicalThisSlotSymbol, &value, scriptContext))
  1723. {
  1724. return value;
  1725. }
  1726. }
  1727. return defaultInstance;
  1728. }
  1729. Var JavascriptOperators::OP_UnwrapWithObj(Var aValue)
  1730. {
  1731. return RecyclableObject::FromVar(aValue)->GetThisObjectOrUnWrap();
  1732. }
  1733. Var JavascriptOperators::OP_GetInstanceScoped(FrameDisplay *pScope, PropertyId propertyId, Var rootObject, Var* thisVar, ScriptContext* scriptContext)
  1734. {
  1735. // Similar to GetPropertyScoped, but instead of returning the property value, we return the instance that
  1736. // owns it, or the global object if no instance is found.
  1737. int i;
  1738. int length = pScope->GetLength();
  1739. for (i = 0; i < length; i++)
  1740. {
  1741. RecyclableObject *obj = (RecyclableObject*)pScope->GetItem(i);
  1742. if (JavascriptOperators::HasProperty(obj, propertyId))
  1743. {
  1744. // HasProperty will call WithObjects HasProperty which will do the filtering
  1745. // All we have to do here is unwrap the object hence the api call
  1746. *thisVar = obj->GetThisObjectOrUnWrap();
  1747. return *thisVar;
  1748. }
  1749. }
  1750. *thisVar = scriptContext->GetLibrary()->GetUndefined();
  1751. if (rootObject != scriptContext->GetGlobalObject())
  1752. {
  1753. if (JavascriptOperators::OP_HasProperty(rootObject, propertyId, scriptContext))
  1754. {
  1755. return rootObject;
  1756. }
  1757. }
  1758. return scriptContext->GetGlobalObject();
  1759. }
  1760. Var JavascriptOperators::GetPropertyReference(RecyclableObject *instance, PropertyId propertyId, ScriptContext* requestContext)
  1761. {
  1762. Var value = nullptr;
  1763. PropertyValueInfo info;
  1764. if (JavascriptOperators::GetPropertyReference(instance, propertyId, &value, requestContext, &info))
  1765. {
  1766. Assert(value != nullptr);
  1767. return value;
  1768. }
  1769. return requestContext->GetMissingPropertyResult();
  1770. }
  1771. BOOL JavascriptOperators::GetPropertyReference(Var instance, RecyclableObject* propertyObject, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1772. {
  1773. return GetPropertyReference_Internal(instance, propertyObject, false, propertyId, value, requestContext, info);
  1774. }
  1775. BOOL JavascriptOperators::GetRootPropertyReference(RecyclableObject* instance, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1776. {
  1777. return GetPropertyReference_Internal(instance, instance, true, propertyId, value, requestContext, info);
  1778. }
  1779. BOOL JavascriptOperators::PropertyReferenceWalkUnscopable(Var instance, RecyclableObject** propertyObject, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  1780. {
  1781. return PropertyReferenceWalk_Impl<true>(instance, propertyObject, propertyId, value, info, requestContext);
  1782. }
  1783. BOOL JavascriptOperators::PropertyReferenceWalk(Var instance, RecyclableObject** propertyObject, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  1784. {
  1785. return PropertyReferenceWalk_Impl<false>(instance, propertyObject, propertyId, value, info, requestContext);
  1786. }
  1787. template <bool unscopables>
  1788. BOOL JavascriptOperators::PropertyReferenceWalk_Impl(Var instance, RecyclableObject** propertyObject, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  1789. {
  1790. BOOL foundProperty = false;
  1791. RecyclableObject* object = *propertyObject;
  1792. while (!foundProperty && JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  1793. {
  1794. if (unscopables && JavascriptOperators::IsPropertyUnscopable(object, propertyId))
  1795. {
  1796. break;
  1797. }
  1798. else
  1799. {
  1800. if (object->GetPropertyReference(instance, propertyId, value, info, requestContext))
  1801. {
  1802. foundProperty = true;
  1803. break;
  1804. }
  1805. }
  1806. if (object->SkipsPrototype())
  1807. {
  1808. break; // will return false
  1809. }
  1810. object = JavascriptOperators::GetPrototypeNoTrap(object);
  1811. }
  1812. *propertyObject = object;
  1813. return foundProperty;
  1814. }
  1815. BOOL JavascriptOperators::GetPropertyReference_Internal(Var instance, RecyclableObject* propertyObject, const bool isRoot, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  1816. {
  1817. if (TaggedNumber::Is(instance))
  1818. {
  1819. PropertyValueInfo::ClearCacheInfo(info);
  1820. }
  1821. BOOL foundProperty = FALSE;
  1822. RecyclableObject* object = propertyObject;
  1823. if (isRoot)
  1824. {
  1825. foundProperty = RootObjectBase::FromVar(object)->GetRootPropertyReference(instance, propertyId, value, info, requestContext);
  1826. }
  1827. if (!foundProperty)
  1828. {
  1829. foundProperty = PropertyReferenceWalk(instance, &object, propertyId, value, info, requestContext);
  1830. }
  1831. if (!foundProperty)
  1832. {
  1833. #if defined(TELEMETRY_JSO) || defined(TELEMETRY_AddToCache) // enabled for `TELEMETRY_AddToCache`, because this is the property-not-found codepath where the normal TELEMETRY_AddToCache code wouldn't be executed.
  1834. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  1835. {
  1836. if (info && info->AllowResizingPolymorphicInlineCache()) // If in interpreted mode, not JIT.
  1837. {
  1838. requestContext->GetTelemetry().GetOpcodeTelemetry().GetProperty(instance, propertyId, nullptr, /*successful: */false);
  1839. }
  1840. }
  1841. #endif
  1842. *value = requestContext->GetMissingPropertyResult();
  1843. return foundProperty;
  1844. }
  1845. if (requestContext->IsUndeclBlockVar(*value))
  1846. {
  1847. JavascriptError::ThrowReferenceError(requestContext, JSERR_UseBeforeDeclaration);
  1848. }
  1849. #if DBG
  1850. if (DynamicObject::Is(object))
  1851. {
  1852. DynamicObject* dynamicObject = (DynamicObject*)object;
  1853. DynamicTypeHandler* dynamicTypeHandler = dynamicObject->GetDynamicType()->GetTypeHandler();
  1854. Var property;
  1855. if (dynamicTypeHandler->CheckFixedProperty(requestContext->GetPropertyName(propertyId), &property, requestContext))
  1856. {
  1857. Assert(value == nullptr || *value == property);
  1858. }
  1859. }
  1860. #endif
  1861. CacheOperators::CachePropertyRead(instance, object, isRoot, propertyId, false, info, requestContext);
  1862. return TRUE;
  1863. }
  1864. template <typename PropertyKeyType, bool unscopable>
  1865. DescriptorFlags JavascriptOperators::GetterSetter_Impl(RecyclableObject* instance, PropertyKeyType propertyKey, Var* setterValue, PropertyValueInfo* info, ScriptContext* scriptContext)
  1866. {
  1867. DescriptorFlags flags = None;
  1868. RecyclableObject* object = instance;
  1869. while (flags == None && JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  1870. {
  1871. if (unscopable && IsPropertyUnscopable(object, propertyKey))
  1872. {
  1873. break;
  1874. }
  1875. else
  1876. {
  1877. flags = object->GetSetter(propertyKey, setterValue, info, scriptContext);
  1878. if (flags != None)
  1879. {
  1880. break;
  1881. }
  1882. }
  1883. // CONSIDER: we should add SkipsPrototype support. DOM has no ES 5 concepts built in that aren't
  1884. // already part of our prototype objects which are chakra objects.
  1885. object = object->GetPrototype();
  1886. }
  1887. return flags;
  1888. }
  1889. DescriptorFlags JavascriptOperators::GetterSetterUnscopable(RecyclableObject* instance, PropertyId propertyId, Var* setterValue, PropertyValueInfo* info, ScriptContext* scriptContext)
  1890. {
  1891. return GetterSetter_Impl<PropertyId, true>(instance, propertyId, setterValue, info, scriptContext);
  1892. }
  1893. DescriptorFlags JavascriptOperators::GetterSetter(RecyclableObject* instance, PropertyId propertyId, Var* setterValue, PropertyValueInfo* info, ScriptContext* scriptContext)
  1894. {
  1895. return GetterSetter_Impl<PropertyId, false>(instance, propertyId, setterValue, info, scriptContext);
  1896. }
  1897. DescriptorFlags JavascriptOperators::GetterSetter(RecyclableObject* instance, JavascriptString * propertyName, Var* setterValue, PropertyValueInfo* info, ScriptContext* scriptContext)
  1898. {
  1899. return GetterSetter_Impl<JavascriptString*, false>(instance, propertyName, setterValue, info, scriptContext);
  1900. }
  1901. // Checks to see if any object in the prototype chain has a property descriptor for the given property
  1902. // that specifies either an accessor or a non-writable attribute.
  1903. // If TRUE, check flags for details.
  1904. template<typename PropertyKeyType, bool doFastProtoChainCheck, bool isRoot>
  1905. BOOL JavascriptOperators::CheckPrototypesForAccessorOrNonWritablePropertyCore(RecyclableObject* instance,
  1906. PropertyKeyType propertyKey, Var* setterValue, DescriptorFlags* flags, PropertyValueInfo* info, ScriptContext* scriptContext)
  1907. {
  1908. Assert(setterValue);
  1909. Assert(flags);
  1910. // Do a quick check to see if all objects in the prototype chain are known to have only
  1911. // writable data properties (i.e. no accessors or non-writable properties).
  1912. if (doFastProtoChainCheck && CheckIfObjectAndPrototypeChainHasOnlyWritableDataProperties(instance))
  1913. {
  1914. return FALSE;
  1915. }
  1916. if (isRoot)
  1917. {
  1918. *flags = JavascriptOperators::GetRootSetter(instance, propertyKey, setterValue, info, scriptContext);
  1919. }
  1920. if (*flags == None)
  1921. {
  1922. *flags = JavascriptOperators::GetterSetter(instance, propertyKey, setterValue, info, scriptContext);
  1923. }
  1924. return ((*flags & Accessor) == Accessor) || ((*flags & Proxy) == Proxy)|| ((*flags & Data) == Data && (*flags & Writable) == None);
  1925. }
  1926. void JavascriptOperators::OP_InvalidateProtoCaches(PropertyId propertyId, ScriptContext *scriptContext)
  1927. {
  1928. scriptContext->InvalidateProtoCaches(propertyId);
  1929. }
  1930. // Checks to see if any object in the prototype chain has a property descriptor for the given index
  1931. // that specifies either an accessor or a non-writable attribute.
  1932. // If TRUE, check flags for details.
  1933. BOOL JavascriptOperators::CheckPrototypesForAccessorOrNonWritableItem(RecyclableObject* instance, uint32 index,
  1934. Var* setterValue, DescriptorFlags *flags, ScriptContext* scriptContext, BOOL skipPrototypeCheck /* = FALSE */)
  1935. {
  1936. Assert(setterValue);
  1937. Assert(flags);
  1938. // Do a quick walk up the prototype chain to see if any of the prototypes has ever had ANY setter or non-writable property.
  1939. if (CheckIfObjectAndPrototypeChainHasOnlyWritableDataProperties(instance))
  1940. {
  1941. return FALSE;
  1942. }
  1943. RecyclableObject* object = instance;
  1944. while (JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  1945. {
  1946. *flags = object->GetItemSetter(index, setterValue, scriptContext);
  1947. if (*flags != None || skipPrototypeCheck)
  1948. {
  1949. break;
  1950. }
  1951. object = object->GetPrototype();
  1952. }
  1953. return ((*flags & Accessor) == Accessor) || ((*flags & Proxy) == Proxy) || ((*flags & Data) == Data && (*flags & Writable) == None);
  1954. }
  1955. BOOL JavascriptOperators::SetGlobalPropertyNoHost(char16 const * propertyName, charcount_t propertyLength, Var value, ScriptContext * scriptContext)
  1956. {
  1957. GlobalObject * globalObject = scriptContext->GetGlobalObject();
  1958. uint32 index;
  1959. PropertyRecord const * propertyRecord;
  1960. IndexType indexType = GetIndexTypeFromString(propertyName, propertyLength, scriptContext, &index, &propertyRecord, true);
  1961. if (indexType == IndexType_Number)
  1962. {
  1963. return globalObject->DynamicObject::SetItem(index, value, PropertyOperation_None);
  1964. }
  1965. return globalObject->DynamicObject::SetProperty(propertyRecord->GetPropertyId(), value, PropertyOperation_None, NULL);
  1966. }
  1967. template<typename PropertyKeyType>
  1968. BOOL JavascriptOperators::SetPropertyWPCache(Var receiver, RecyclableObject* object, PropertyKeyType propertyKey, Var newValue, ScriptContext* requestContext, PropertyString * propertyString, PropertyOperationFlags propertyOperationFlags)
  1969. {
  1970. if (receiver)
  1971. {
  1972. AnalysisAssert(object);
  1973. Assert(!TaggedNumber::Is(receiver));
  1974. Var setterValueOrProxy = nullptr;
  1975. DescriptorFlags flags = None;
  1976. if (JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(object, propertyKey, &setterValueOrProxy, &flags, NULL, requestContext))
  1977. {
  1978. if ((flags & Accessor) == Accessor)
  1979. {
  1980. if (JavascriptError::ThrowIfStrictModeUndefinedSetter(propertyOperationFlags, setterValueOrProxy, requestContext))
  1981. {
  1982. return TRUE;
  1983. }
  1984. if (setterValueOrProxy)
  1985. {
  1986. receiver = (RecyclableObject::FromVar(receiver))->GetThisObjectOrUnWrap();
  1987. RecyclableObject* func = RecyclableObject::FromVar(setterValueOrProxy);
  1988. JavascriptOperators::CallSetter(func, receiver, newValue, requestContext);
  1989. }
  1990. return TRUE;
  1991. }
  1992. else if ((flags & Proxy) == Proxy)
  1993. {
  1994. Assert(JavascriptProxy::Is(setterValueOrProxy));
  1995. JavascriptProxy* proxy = JavascriptProxy::FromVar(setterValueOrProxy);
  1996. auto fn = [&](RecyclableObject* target) -> BOOL {
  1997. return JavascriptOperators::SetPropertyWPCache(receiver, target, propertyKey, newValue, requestContext, propertyString, propertyOperationFlags);
  1998. };
  1999. return proxy->SetPropertyTrap(receiver, JavascriptProxy::SetPropertyTrapKind::SetPropertyWPCacheKind, propertyKey, newValue, requestContext);
  2000. }
  2001. else
  2002. {
  2003. Assert((flags & Data) == Data && (flags & Writable) == None);
  2004. requestContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  2005. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2006. return FALSE;
  2007. }
  2008. }
  2009. else if (!JavascriptOperators::IsObject(receiver))
  2010. {
  2011. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2012. return FALSE;
  2013. }
  2014. RecyclableObject* receiverObject = RecyclableObject::FromVar(receiver);
  2015. if (receiver != object)
  2016. {
  2017. // If the receiver object has the property and it is an accessor then return false
  2018. PropertyDescriptor existingDesc;
  2019. if (JavascriptOperators::GetOwnPropertyDescriptor(receiverObject, propertyKey, requestContext, &existingDesc)
  2020. && existingDesc.IsAccessorDescriptor())
  2021. {
  2022. return FALSE;
  2023. }
  2024. }
  2025. // in 9.1.9, step 5, we should return false if receiver is not object, and that will happen in default RecyclableObject operation anyhow.
  2026. PropertyValueInfo info;
  2027. if (receiverObject->SetProperty(propertyKey, newValue, propertyOperationFlags, &info))
  2028. {
  2029. if (propertyString != NULL)
  2030. {
  2031. uint16 slotIndex = info.GetPropertyIndex();
  2032. if (slotIndex != Constants::NoSlot &&
  2033. info.GetInstance() == receiverObject &&
  2034. !object->CanHaveInterceptors() &&
  2035. requestContext == receiverObject->GetScriptContext() &&
  2036. (info.GetFlags() != InlineCacheSetterFlag))
  2037. {
  2038. uint16 inlineOrAuxSlotIndex;
  2039. bool isInlineSlot;
  2040. DynamicObject::FromVar(info.GetInstance())->GetTypeHandler()->PropertyIndexToInlineOrAuxSlotIndex(info.GetPropertyIndex(), &inlineOrAuxSlotIndex, &isInlineSlot);
  2041. propertyString->UpdateCache(info.GetInstance()->GetType(), inlineOrAuxSlotIndex, isInlineSlot, info.IsStoreFieldCacheEnabled());
  2042. }
  2043. }
  2044. return TRUE;
  2045. }
  2046. }
  2047. return FALSE;
  2048. }
  2049. BOOL JavascriptOperators::SetItemOnTaggedNumber(Var receiver, RecyclableObject* object, uint32 index, Var newValue, ScriptContext* requestContext,
  2050. PropertyOperationFlags propertyOperationFlags)
  2051. {
  2052. Assert(TaggedNumber::Is(receiver));
  2053. if (requestContext->optimizationOverrides.GetSideEffects() & SideEffects_Accessor)
  2054. {
  2055. Var setterValueOrProxy = nullptr;
  2056. DescriptorFlags flags = None;
  2057. if (object == nullptr)
  2058. {
  2059. GetPropertyObject(receiver, requestContext, &object);
  2060. }
  2061. if (JavascriptOperators::CheckPrototypesForAccessorOrNonWritableItem(object, index, &setterValueOrProxy, &flags, requestContext))
  2062. {
  2063. if ((flags & Accessor) == Accessor)
  2064. {
  2065. if (JavascriptError::ThrowIfStrictModeUndefinedSetter(propertyOperationFlags, setterValueOrProxy, requestContext))
  2066. {
  2067. return TRUE;
  2068. }
  2069. if (setterValueOrProxy)
  2070. {
  2071. RecyclableObject* func = RecyclableObject::FromVar(setterValueOrProxy);
  2072. JavascriptOperators::CallSetter(func, receiver, newValue, requestContext);
  2073. return TRUE;
  2074. }
  2075. }
  2076. else if ((flags & Proxy) == Proxy)
  2077. {
  2078. Assert(JavascriptProxy::Is(setterValueOrProxy));
  2079. JavascriptProxy* proxy = JavascriptProxy::FromVar(setterValueOrProxy);
  2080. const PropertyRecord* propertyRecord;
  2081. proxy->PropertyIdFromInt(index, &propertyRecord);
  2082. return proxy->SetPropertyTrap(receiver, JavascriptProxy::SetPropertyTrapKind::SetItemOnTaggedNumberKind, propertyRecord->GetPropertyId(), newValue, requestContext);
  2083. }
  2084. else
  2085. {
  2086. Assert((flags & Data) == Data && (flags & Writable) == None);
  2087. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2088. }
  2089. }
  2090. }
  2091. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2092. return FALSE;
  2093. }
  2094. BOOL JavascriptOperators::SetPropertyOnTaggedNumber(Var receiver, RecyclableObject* object, PropertyId propertyId, Var newValue, ScriptContext* requestContext,
  2095. PropertyOperationFlags propertyOperationFlags)
  2096. {
  2097. Assert (TaggedNumber::Is(receiver));
  2098. if (requestContext->optimizationOverrides.GetSideEffects() & SideEffects_Accessor)
  2099. {
  2100. Var setterValueOrProxy = nullptr;
  2101. PropertyValueInfo info;
  2102. DescriptorFlags flags = None;
  2103. if (object == nullptr)
  2104. {
  2105. GetPropertyObject(receiver, requestContext, &object);
  2106. }
  2107. if (JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(object, propertyId, &setterValueOrProxy, &flags, &info, requestContext))
  2108. {
  2109. if ((flags & Accessor) == Accessor)
  2110. {
  2111. if (JavascriptError::ThrowIfStrictModeUndefinedSetter(propertyOperationFlags, setterValueOrProxy, requestContext))
  2112. {
  2113. return TRUE;
  2114. }
  2115. if (setterValueOrProxy)
  2116. {
  2117. RecyclableObject* func = RecyclableObject::FromVar(setterValueOrProxy);
  2118. Assert(info.GetFlags() == InlineCacheSetterFlag || info.GetPropertyIndex() == Constants::NoSlot);
  2119. JavascriptOperators::CallSetter(func, receiver, newValue, requestContext);
  2120. return TRUE;
  2121. }
  2122. }
  2123. else if ((flags & Proxy) == Proxy)
  2124. {
  2125. Assert(JavascriptProxy::Is(setterValueOrProxy));
  2126. JavascriptProxy* proxy = JavascriptProxy::FromVar(setterValueOrProxy);
  2127. return proxy->SetPropertyTrap(receiver, JavascriptProxy::SetPropertyTrapKind::SetPropertyOnTaggedNumberKind, propertyId, newValue, requestContext);
  2128. }
  2129. else
  2130. {
  2131. Assert((flags & Data) == Data && (flags & Writable) == None);
  2132. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2133. }
  2134. }
  2135. }
  2136. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  2137. requestContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  2138. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2139. return FALSE;
  2140. }
  2141. BOOL JavascriptOperators::SetPropertyUnscopable(Var instance, RecyclableObject* receiver, PropertyId propertyId, Var newValue, PropertyValueInfo * info, ScriptContext* requestContext, PropertyOperationFlags propertyOperationFlags)
  2142. {
  2143. return SetProperty_Internal<true>(instance, receiver, false, propertyId, newValue, info, requestContext, propertyOperationFlags);
  2144. }
  2145. BOOL JavascriptOperators::SetProperty(Var receiver, RecyclableObject* object, PropertyId propertyId, Var newValue, PropertyValueInfo * info, ScriptContext* requestContext, PropertyOperationFlags propertyOperationFlags)
  2146. {
  2147. return SetProperty_Internal<false>(receiver, object, false, propertyId, newValue, info, requestContext, propertyOperationFlags);
  2148. }
  2149. BOOL JavascriptOperators::SetRootProperty(RecyclableObject* instance, PropertyId propertyId, Var newValue, PropertyValueInfo * info, ScriptContext* requestContext, PropertyOperationFlags propertyOperationFlags)
  2150. {
  2151. return SetProperty_Internal<false>(instance, instance, true, propertyId, newValue, info, requestContext, propertyOperationFlags);
  2152. }
  2153. template <bool unscopables>
  2154. BOOL JavascriptOperators::SetProperty_Internal(Var receiver, RecyclableObject* object, const bool isRoot, PropertyId propertyId, Var newValue, PropertyValueInfo * info, ScriptContext* requestContext, PropertyOperationFlags propertyOperationFlags)
  2155. {
  2156. if (receiver)
  2157. {
  2158. Assert(!TaggedNumber::Is(receiver));
  2159. Var setterValueOrProxy = nullptr;
  2160. DescriptorFlags flags = None;
  2161. if ((isRoot && JavascriptOperators::CheckPrototypesForAccessorOrNonWritableRootProperty(object, propertyId, &setterValueOrProxy, &flags, info, requestContext)) ||
  2162. (!isRoot && JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(object, propertyId, &setterValueOrProxy, &flags, info, requestContext)))
  2163. {
  2164. if ((flags & Accessor) == Accessor)
  2165. {
  2166. if (JavascriptError::ThrowIfStrictModeUndefinedSetter(propertyOperationFlags, setterValueOrProxy, requestContext) ||
  2167. JavascriptError::ThrowIfNotExtensibleUndefinedSetter(propertyOperationFlags, setterValueOrProxy, requestContext))
  2168. {
  2169. return TRUE;
  2170. }
  2171. if (setterValueOrProxy)
  2172. {
  2173. RecyclableObject* func = RecyclableObject::FromVar(setterValueOrProxy);
  2174. Assert(!info || info->GetFlags() == InlineCacheSetterFlag || info->GetPropertyIndex() == Constants::NoSlot);
  2175. if (WithScopeObject::Is(receiver))
  2176. {
  2177. receiver = (RecyclableObject::FromVar(receiver))->GetThisObjectOrUnWrap();
  2178. }
  2179. else
  2180. {
  2181. CacheOperators::CachePropertyWrite(RecyclableObject::FromVar(receiver), isRoot, object->GetType(), propertyId, info, requestContext);
  2182. }
  2183. #ifdef ENABLE_MUTATION_BREAKPOINT
  2184. if (MutationBreakpoint::IsFeatureEnabled(requestContext))
  2185. {
  2186. MutationBreakpoint::HandleSetProperty(requestContext, object, propertyId, newValue);
  2187. }
  2188. #endif
  2189. JavascriptOperators::CallSetter(func, receiver, newValue, requestContext);
  2190. }
  2191. return TRUE;
  2192. }
  2193. else if ((flags & Proxy) == Proxy)
  2194. {
  2195. Assert(JavascriptProxy::Is(setterValueOrProxy));
  2196. JavascriptProxy* proxy = JavascriptProxy::FromVar(setterValueOrProxy);
  2197. // We can't cache the property at this time. both target and handler can be changed outside of the proxy, so the inline cache needs to be
  2198. // invalidate when target, handler, or handler prototype has changed. We don't have a way to achieve this yet.
  2199. PropertyValueInfo::SetNoCache(info, proxy);
  2200. PropertyValueInfo::DisablePrototypeCache(info, proxy); // We can't cache prototype property either
  2201. return proxy->SetPropertyTrap(receiver, JavascriptProxy::SetPropertyTrapKind::SetPropertyKind, propertyId, newValue, requestContext);
  2202. }
  2203. else
  2204. {
  2205. Assert((flags & Data) == Data && (flags & Writable) == None);
  2206. if (flags & Const)
  2207. {
  2208. JavascriptError::ThrowTypeError(requestContext, ERRAssignmentToConst);
  2209. }
  2210. JavascriptError::ThrowCantAssign(propertyOperationFlags, requestContext, propertyId);
  2211. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2212. return FALSE;
  2213. }
  2214. }
  2215. else if (!JavascriptOperators::IsObject(receiver))
  2216. {
  2217. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, requestContext);
  2218. return FALSE;
  2219. }
  2220. #ifdef ENABLE_MUTATION_BREAKPOINT
  2221. // Break on mutation if needed
  2222. bool doNotUpdateCacheForMbp = MutationBreakpoint::IsFeatureEnabled(requestContext) ?
  2223. MutationBreakpoint::HandleSetProperty(requestContext, object, propertyId, newValue) : false;
  2224. #endif
  2225. // Get the original type before setting the property
  2226. Type *typeWithoutProperty = object->GetType();
  2227. BOOL didSetProperty = false;
  2228. if (isRoot)
  2229. {
  2230. AssertMsg(JavascriptOperators::GetTypeId(receiver) == TypeIds_GlobalObject
  2231. || JavascriptOperators::GetTypeId(receiver) == TypeIds_ModuleRoot,
  2232. "Root must be a global object!");
  2233. RootObjectBase* rootObject = static_cast<RootObjectBase*>(receiver);
  2234. didSetProperty = rootObject->SetRootProperty(propertyId, newValue, propertyOperationFlags, info);
  2235. }
  2236. else
  2237. {
  2238. RecyclableObject* instanceObject = RecyclableObject::FromVar(receiver);
  2239. while (JavascriptOperators::GetTypeId(instanceObject) != TypeIds_Null)
  2240. {
  2241. if (unscopables && JavascriptOperators::IsPropertyUnscopable(instanceObject, propertyId))
  2242. {
  2243. break;
  2244. }
  2245. else
  2246. {
  2247. didSetProperty = instanceObject->SetProperty(propertyId, newValue, propertyOperationFlags, info);
  2248. if (didSetProperty || !unscopables)
  2249. {
  2250. break;
  2251. }
  2252. }
  2253. instanceObject = JavascriptOperators::GetPrototypeNoTrap(instanceObject);
  2254. }
  2255. }
  2256. if (didSetProperty)
  2257. {
  2258. bool updateCache = true;
  2259. #ifdef ENABLE_MUTATION_BREAKPOINT
  2260. updateCache = updateCache && !doNotUpdateCacheForMbp;
  2261. #endif
  2262. if (updateCache)
  2263. {
  2264. if (!JavascriptProxy::Is(receiver))
  2265. {
  2266. CacheOperators::CachePropertyWrite(RecyclableObject::FromVar(receiver), isRoot, typeWithoutProperty, propertyId, info, requestContext);
  2267. }
  2268. }
  2269. return TRUE;
  2270. }
  2271. }
  2272. return FALSE;
  2273. }
  2274. BOOL JavascriptOperators::IsNumberFromNativeArray(Var instance, uint32 index, ScriptContext* scriptContext)
  2275. {
  2276. #if ENABLE_COPYONACCESS_ARRAY
  2277. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  2278. #endif
  2279. Js::TypeId instanceType = JavascriptOperators::GetTypeId(instance);
  2280. // Fast path for native and typed arrays.
  2281. if ( (instanceType == TypeIds_NativeIntArray || instanceType == TypeIds_NativeFloatArray) || (instanceType >= TypeIds_Int8Array && instanceType <= TypeIds_Uint64Array) )
  2282. {
  2283. RecyclableObject* object = RecyclableObject::FromVar(instance);
  2284. Var member;
  2285. // If the item is found in the array own body, then it is a number
  2286. if (JavascriptOperators::GetOwnItem(object, index, &member, scriptContext)
  2287. && !JavascriptOperators::IsUndefined(member))
  2288. {
  2289. return TRUE;
  2290. }
  2291. }
  2292. return FALSE;
  2293. }
  2294. BOOL JavascriptOperators::GetAccessors(RecyclableObject* instance, PropertyId propertyId, ScriptContext* requestContext, Var* getter, Var* setter)
  2295. {
  2296. RecyclableObject* object = instance;
  2297. while (JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  2298. {
  2299. if (object->GetAccessors(propertyId, getter, setter, requestContext))
  2300. {
  2301. *getter = JavascriptOperators::CanonicalizeAccessor(*getter, requestContext);
  2302. *setter = JavascriptOperators::CanonicalizeAccessor(*setter, requestContext);
  2303. return TRUE;
  2304. }
  2305. if (object->SkipsPrototype())
  2306. {
  2307. break;
  2308. }
  2309. object = JavascriptOperators::GetPrototype(object);
  2310. }
  2311. return FALSE;
  2312. }
  2313. BOOL JavascriptOperators::SetAccessors(RecyclableObject* instance, PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  2314. {
  2315. BOOL result = instance && instance->SetAccessors(propertyId, getter, setter, flags);
  2316. return result;
  2317. }
  2318. BOOL JavascriptOperators::OP_SetProperty(Var instance, PropertyId propertyId, Var newValue, ScriptContext* scriptContext, PropertyValueInfo * info, PropertyOperationFlags flags, Var thisInstance)
  2319. {
  2320. // The call into ToObject(dynamicObject) is avoided here by checking for null and undefined and doing nothing when dynamicObject is a primitive value.
  2321. if (thisInstance == nullptr)
  2322. {
  2323. thisInstance = instance;
  2324. }
  2325. TypeId typeId = JavascriptOperators::GetTypeId(thisInstance);
  2326. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  2327. {
  2328. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2329. {
  2330. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotSet_NullOrUndefined, scriptContext->GetPropertyName(propertyId)->GetBuffer());
  2331. }
  2332. return TRUE;
  2333. }
  2334. else if (typeId == TypeIds_VariantDate)
  2335. {
  2336. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2337. {
  2338. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_VarDate, scriptContext->GetPropertyName(propertyId)->GetBuffer());
  2339. }
  2340. return TRUE;
  2341. }
  2342. if (!TaggedNumber::Is(thisInstance))
  2343. {
  2344. return JavascriptOperators::SetProperty(RecyclableObject::FromVar(thisInstance), RecyclableObject::FromVar(instance), propertyId, newValue, info, scriptContext, flags);
  2345. }
  2346. JavascriptError::ThrowCantAssignIfStrictMode(flags, scriptContext);
  2347. return false;
  2348. }
  2349. BOOL JavascriptOperators::OP_StFunctionExpression(Var obj, PropertyId propertyId, Var newValue)
  2350. {
  2351. RecyclableObject* instance = RecyclableObject::FromVar(obj);
  2352. instance->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  2353. instance->SetWritable(propertyId, FALSE);
  2354. instance->SetConfigurable(propertyId, FALSE);
  2355. return TRUE;
  2356. }
  2357. BOOL JavascriptOperators::OP_InitClassMember(Var obj, PropertyId propertyId, Var newValue)
  2358. {
  2359. RecyclableObject* instance = RecyclableObject::FromVar(obj);
  2360. PropertyOperationFlags flags = PropertyOperation_None;
  2361. PropertyAttributes attributes = PropertyClassMemberDefaults;
  2362. instance->SetPropertyWithAttributes(propertyId, newValue, attributes, NULL, flags);
  2363. return TRUE;
  2364. }
  2365. BOOL JavascriptOperators::OP_InitLetProperty(Var obj, PropertyId propertyId, Var newValue)
  2366. {
  2367. RecyclableObject* instance = RecyclableObject::FromVar(obj);
  2368. PropertyOperationFlags flags = instance->GetScriptContext()->IsUndeclBlockVar(newValue) ? PropertyOperation_SpecialValue : PropertyOperation_None;
  2369. PropertyAttributes attributes = PropertyLetDefaults;
  2370. if (RootObjectBase::Is(instance))
  2371. {
  2372. attributes |= PropertyLetConstGlobal;
  2373. }
  2374. instance->SetPropertyWithAttributes(propertyId, newValue, attributes, NULL, (PropertyOperationFlags)(flags | PropertyOperation_AllowUndecl));
  2375. return TRUE;
  2376. }
  2377. BOOL JavascriptOperators::OP_InitConstProperty(Var obj, PropertyId propertyId, Var newValue)
  2378. {
  2379. RecyclableObject* instance = RecyclableObject::FromVar(obj);
  2380. PropertyOperationFlags flags = instance->GetScriptContext()->IsUndeclBlockVar(newValue) ? PropertyOperation_SpecialValue : PropertyOperation_None;
  2381. PropertyAttributes attributes = PropertyConstDefaults;
  2382. if (RootObjectBase::Is(instance))
  2383. {
  2384. attributes |= PropertyLetConstGlobal;
  2385. }
  2386. instance->SetPropertyWithAttributes(propertyId, newValue, attributes, NULL, (PropertyOperationFlags)(flags | PropertyOperation_AllowUndecl));
  2387. return TRUE;
  2388. }
  2389. BOOL JavascriptOperators::OP_InitUndeclRootLetProperty(Var obj, PropertyId propertyId)
  2390. {
  2391. RecyclableObject* instance = RecyclableObject::FromVar(obj);
  2392. PropertyOperationFlags flags = static_cast<PropertyOperationFlags>(PropertyOperation_SpecialValue | PropertyOperation_AllowUndecl);
  2393. PropertyAttributes attributes = PropertyLetDefaults | PropertyLetConstGlobal;
  2394. instance->SetPropertyWithAttributes(propertyId, instance->GetLibrary()->GetUndeclBlockVar(), attributes, NULL, flags);
  2395. return TRUE;
  2396. }
  2397. BOOL JavascriptOperators::OP_InitUndeclRootConstProperty(Var obj, PropertyId propertyId)
  2398. {
  2399. RecyclableObject* instance = RecyclableObject::FromVar(obj);
  2400. PropertyOperationFlags flags = static_cast<PropertyOperationFlags>(PropertyOperation_SpecialValue | PropertyOperation_AllowUndecl);
  2401. PropertyAttributes attributes = PropertyConstDefaults | PropertyLetConstGlobal;
  2402. instance->SetPropertyWithAttributes(propertyId, instance->GetLibrary()->GetUndeclBlockVar(), attributes, NULL, flags);
  2403. return TRUE;
  2404. }
  2405. BOOL JavascriptOperators::OP_InitUndeclConsoleLetProperty(Var obj, PropertyId propertyId)
  2406. {
  2407. FrameDisplay *pScope = (FrameDisplay*)obj;
  2408. AssertMsg(ConsoleScopeActivationObject::Is((DynamicObject*)pScope->GetItem(pScope->GetLength() - 1)), "How come we got this opcode without ConsoleScopeActivationObject?");
  2409. RecyclableObject* instance = RecyclableObject::FromVar(pScope->GetItem(0));
  2410. PropertyOperationFlags flags = static_cast<PropertyOperationFlags>(PropertyOperation_SpecialValue | PropertyOperation_AllowUndecl);
  2411. PropertyAttributes attributes = PropertyLetDefaults;
  2412. instance->SetPropertyWithAttributes(propertyId, instance->GetLibrary()->GetUndeclBlockVar(), attributes, NULL, flags);
  2413. return TRUE;
  2414. }
  2415. BOOL JavascriptOperators::OP_InitUndeclConsoleConstProperty(Var obj, PropertyId propertyId)
  2416. {
  2417. FrameDisplay *pScope = (FrameDisplay*)obj;
  2418. AssertMsg(ConsoleScopeActivationObject::Is((DynamicObject*)pScope->GetItem(pScope->GetLength() - 1)), "How come we got this opcode without ConsoleScopeActivationObject?");
  2419. RecyclableObject* instance = RecyclableObject::FromVar(pScope->GetItem(0));
  2420. PropertyOperationFlags flags = static_cast<PropertyOperationFlags>(PropertyOperation_SpecialValue | PropertyOperation_AllowUndecl);
  2421. PropertyAttributes attributes = PropertyConstDefaults;
  2422. instance->SetPropertyWithAttributes(propertyId, instance->GetLibrary()->GetUndeclBlockVar(), attributes, NULL, flags);
  2423. return TRUE;
  2424. }
  2425. BOOL JavascriptOperators::InitProperty(RecyclableObject* instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  2426. {
  2427. return instance && instance->InitProperty(propertyId, newValue, flags);
  2428. }
  2429. BOOL JavascriptOperators::OP_InitProperty(Var instance, PropertyId propertyId, Var newValue)
  2430. {
  2431. if(TaggedNumber::Is(instance)) { return false; }
  2432. return JavascriptOperators::InitProperty(RecyclableObject::FromVar(instance), propertyId, newValue);
  2433. }
  2434. BOOL JavascriptOperators::DeleteProperty(RecyclableObject* instance, PropertyId propertyId, PropertyOperationFlags propertyOperationFlags)
  2435. {
  2436. return DeleteProperty_Impl<false>(instance, propertyId, propertyOperationFlags);
  2437. }
  2438. BOOL JavascriptOperators::DeletePropertyUnscopables(RecyclableObject* instance, PropertyId propertyId, PropertyOperationFlags propertyOperationFlags)
  2439. {
  2440. return DeleteProperty_Impl<true>(instance, propertyId, propertyOperationFlags);
  2441. }
  2442. template<bool unscopables>
  2443. BOOL JavascriptOperators::DeleteProperty_Impl(RecyclableObject* instance, PropertyId propertyId, PropertyOperationFlags propertyOperationFlags)
  2444. {
  2445. if (unscopables && JavascriptOperators::IsPropertyUnscopable(instance, propertyId))
  2446. {
  2447. return false;
  2448. }
  2449. #ifdef ENABLE_MUTATION_BREAKPOINT
  2450. ScriptContext *scriptContext = instance->GetScriptContext();
  2451. if (MutationBreakpoint::IsFeatureEnabled(scriptContext)
  2452. && scriptContext->HasMutationBreakpoints())
  2453. {
  2454. MutationBreakpoint::HandleDeleteProperty(scriptContext, instance, propertyId);
  2455. }
  2456. #endif
  2457. // !unscopables will hit the return statement on the first iteration
  2458. return instance->DeleteProperty(propertyId, propertyOperationFlags);
  2459. }
  2460. Var JavascriptOperators::OP_DeleteProperty(Var instance, PropertyId propertyId, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags)
  2461. {
  2462. if(TaggedNumber::Is(instance))
  2463. {
  2464. return scriptContext->GetLibrary()->GetTrue();
  2465. }
  2466. TypeId typeId = JavascriptOperators::GetTypeId(instance);
  2467. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  2468. {
  2469. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotDelete_NullOrUndefined,
  2470. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  2471. }
  2472. RecyclableObject *recyclableObject = RecyclableObject::FromVar(instance);
  2473. return scriptContext->GetLibrary()->CreateBoolean(
  2474. JavascriptOperators::DeleteProperty(recyclableObject, propertyId, propertyOperationFlags));
  2475. }
  2476. Var JavascriptOperators::OP_DeleteRootProperty(Var instance, PropertyId propertyId, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags)
  2477. {
  2478. AssertMsg(RootObjectBase::Is(instance), "Root must be a global object!");
  2479. RootObjectBase* rootObject = static_cast<RootObjectBase*>(instance);
  2480. return scriptContext->GetLibrary()->CreateBoolean(
  2481. rootObject->DeleteRootProperty(propertyId, propertyOperationFlags));
  2482. }
  2483. template <bool IsFromFullJit, class TInlineCache>
  2484. inline void JavascriptOperators::PatchSetPropertyScoped(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var newValue, Var defaultInstance, PropertyOperationFlags propertyOperationFlags)
  2485. {
  2486. // Set the property using a scope stack rather than an individual instance.
  2487. // Walk the stack until we find an instance that has the property and store
  2488. // the new value there.
  2489. //
  2490. // To propagate 'this' pointer, walk up the stack and update scopes
  2491. // where field '_lexicalThisSlotSymbol' exists and stop at the
  2492. // scope where field '_lexicalNewTargetSymbol' also exists, which
  2493. // indicates class constructor.
  2494. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  2495. uint16 length = pDisplay->GetLength();
  2496. DynamicObject *object;
  2497. PropertyValueInfo info;
  2498. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  2499. bool allowUndecInConsoleScope = (propertyOperationFlags & PropertyOperation_AllowUndeclInConsoleScope) == PropertyOperation_AllowUndeclInConsoleScope;
  2500. bool isLexicalThisSlotSymbol = (propertyId == PropertyIds::_lexicalThisSlotSymbol);
  2501. for (uint16 i = 0; i < length; i++)
  2502. {
  2503. object = (DynamicObject*)pDisplay->GetItem(i);
  2504. AssertMsg(!ConsoleScopeActivationObject::Is(object) || (i == length - 1), "Invalid location for ConsoleScopeActivationObject");
  2505. Type* type = object->GetType();
  2506. if (CacheOperators::TrySetProperty<true, true, true, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  2507. object, false, propertyId, newValue, scriptContext, propertyOperationFlags, nullptr, &info))
  2508. {
  2509. if (isLexicalThisSlotSymbol && !JavascriptOperators::HasProperty(object, PropertyIds::_lexicalNewTargetSymbol))
  2510. {
  2511. continue;
  2512. }
  2513. return;
  2514. }
  2515. // In scoped set property, we need to set the property when it is available; it could be a setter
  2516. // or normal property. we need to check setter first, and if no setter is available, but HasProperty
  2517. // is true, this must be a normal property.
  2518. // TODO: merge OP_HasProperty and GetSetter in one pass if there is perf problem. In fastDOM we have quite
  2519. // a lot of setters so separating the two might be actually faster.
  2520. Var setterValueOrProxy = nullptr;
  2521. DescriptorFlags flags = None;
  2522. if (JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(object, propertyId, &setterValueOrProxy, &flags, &info, scriptContext))
  2523. {
  2524. if ((flags & Accessor) == Accessor)
  2525. {
  2526. if (setterValueOrProxy)
  2527. {
  2528. JavascriptFunction* func = (JavascriptFunction*)setterValueOrProxy;
  2529. Assert(info.GetFlags() == InlineCacheSetterFlag || info.GetPropertyIndex() == Constants::NoSlot);
  2530. CacheOperators::CachePropertyWrite(object, false, type, propertyId, &info, scriptContext);
  2531. JavascriptOperators::CallSetter(func, object, newValue, scriptContext);
  2532. }
  2533. Assert(!isLexicalThisSlotSymbol);
  2534. return;
  2535. }
  2536. else if ((flags & Proxy) == Proxy)
  2537. {
  2538. Assert(JavascriptProxy::Is(setterValueOrProxy));
  2539. JavascriptProxy* proxy = JavascriptProxy::FromVar(setterValueOrProxy);
  2540. auto fn = [&](RecyclableObject* target) -> BOOL {
  2541. return JavascriptOperators::SetProperty(object, target, propertyId, newValue, scriptContext, propertyOperationFlags);
  2542. };
  2543. // We can't cache the property at this time. both target and handler can be changed outside of the proxy, so the inline cache needs to be
  2544. // invalidate when target, handler, or handler prototype has changed. We don't have a way to achieve this yet.
  2545. PropertyValueInfo::SetNoCache(&info, proxy);
  2546. PropertyValueInfo::DisablePrototypeCache(&info, proxy); // We can't cache prototype property either
  2547. proxy->SetPropertyTrap(object, JavascriptProxy::SetPropertyTrapKind::SetPropertyKind, propertyId, newValue, scriptContext);
  2548. }
  2549. else
  2550. {
  2551. Assert((flags & Data) == Data && (flags & Writable) == None);
  2552. if (!allowUndecInConsoleScope)
  2553. {
  2554. if (flags & Const)
  2555. {
  2556. JavascriptError::ThrowTypeError(scriptContext, ERRAssignmentToConst);
  2557. }
  2558. Assert(!isLexicalThisSlotSymbol);
  2559. return;
  2560. }
  2561. }
  2562. }
  2563. else if (!JavascriptOperators::IsObject(object))
  2564. {
  2565. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, scriptContext);
  2566. }
  2567. // Need to do a "get" of the current value (if any) to make sure that we're not writing to
  2568. // let/const before declaration, but we need to disable implicit calls around the "get",
  2569. // so we need to do a "has" first to make sure the "get" is valid (e.g., "get" on a HostDispatch
  2570. // with implicit calls disabled will always "succeed").
  2571. if (JavascriptOperators::HasProperty(object, propertyId))
  2572. {
  2573. DisableImplicitFlags disableImplicitFlags = scriptContext->GetThreadContext()->GetDisableImplicitFlags();
  2574. scriptContext->GetThreadContext()->SetDisableImplicitFlags(DisableImplicitCallAndExceptionFlag);
  2575. Var value;
  2576. BOOL result = JavascriptOperators::GetProperty(object, propertyId, &value, scriptContext, nullptr);
  2577. scriptContext->GetThreadContext()->SetDisableImplicitFlags(disableImplicitFlags);
  2578. if (result && scriptContext->IsUndeclBlockVar(value) && !allowUndecInConsoleScope && !isLexicalThisSlotSymbol)
  2579. {
  2580. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  2581. }
  2582. PropertyValueInfo info2;
  2583. PropertyValueInfo::SetCacheInfo(&info2, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  2584. PropertyOperationFlags setPropertyOpFlags = allowUndecInConsoleScope ? PropertyOperation_AllowUndeclInConsoleScope : PropertyOperation_None;
  2585. object->SetProperty(propertyId, newValue, setPropertyOpFlags, &info2);
  2586. #if DBG_DUMP
  2587. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  2588. {
  2589. CacheOperators::TraceCache(inlineCache, _u("PatchSetPropertyScoped"), propertyId, scriptContext, object);
  2590. }
  2591. #endif
  2592. if (!JavascriptProxy::Is(object) && !allowUndecInConsoleScope)
  2593. {
  2594. CacheOperators::CachePropertyWrite(object, false, type, propertyId, &info2, scriptContext);
  2595. }
  2596. if (isLexicalThisSlotSymbol && !JavascriptOperators::HasProperty(object, PropertyIds::_lexicalNewTargetSymbol))
  2597. {
  2598. continue;
  2599. }
  2600. return;
  2601. }
  2602. }
  2603. Assert(!isLexicalThisSlotSymbol);
  2604. // If we have console scope and no one in the scope had the property add it to console scope
  2605. if ((length > 0) && ConsoleScopeActivationObject::Is(pDisplay->GetItem(length - 1)))
  2606. {
  2607. // CheckPrototypesForAccessorOrNonWritableProperty does not check for const in global object. We should check it here.
  2608. if ((length > 1) && GlobalObject::Is(pDisplay->GetItem(length - 2)))
  2609. {
  2610. GlobalObject* globalObject = GlobalObject::FromVar(pDisplay->GetItem(length - 2));
  2611. Var setterValue = nullptr;
  2612. DescriptorFlags flags = JavascriptOperators::GetRootSetter(globalObject, propertyId, &setterValue, &info, scriptContext);
  2613. Assert((flags & Accessor) != Accessor);
  2614. Assert((flags & Proxy) != Proxy);
  2615. if ((flags & Data) == Data && (flags & Writable) == None)
  2616. {
  2617. if (!allowUndecInConsoleScope)
  2618. {
  2619. if (flags & Const)
  2620. {
  2621. JavascriptError::ThrowTypeError(scriptContext, ERRAssignmentToConst);
  2622. }
  2623. Assert(!isLexicalThisSlotSymbol);
  2624. return;
  2625. }
  2626. }
  2627. }
  2628. RecyclableObject* obj = RecyclableObject::FromVar((DynamicObject*)pDisplay->GetItem(length - 1));
  2629. OUTPUT_TRACE(Js::ConsoleScopePhase, _u("Adding property '%s' to console scope object\n"), scriptContext->GetPropertyName(propertyId)->GetBuffer());
  2630. JavascriptOperators::SetProperty(obj, obj, propertyId, newValue, scriptContext, propertyOperationFlags);
  2631. return;
  2632. }
  2633. // No one in the scope stack has the property, so add it to the default instance provided by the caller.
  2634. AssertMsg(!TaggedNumber::Is(defaultInstance), "Root object is an int or tagged float?");
  2635. Assert(defaultInstance != nullptr);
  2636. RecyclableObject* obj = RecyclableObject::FromVar(defaultInstance);
  2637. {
  2638. //SetPropertyScoped does not use inline cache for default instance
  2639. PropertyValueInfo info2;
  2640. JavascriptOperators::SetRootProperty(obj, propertyId, newValue, &info2, scriptContext, (PropertyOperationFlags)(propertyOperationFlags | PropertyOperation_Root));
  2641. }
  2642. }
  2643. template void JavascriptOperators::PatchSetPropertyScoped<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var newValue, Var defaultInstance, PropertyOperationFlags propertyOperationFlags);
  2644. template void JavascriptOperators::PatchSetPropertyScoped<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var newValue, Var defaultInstance, PropertyOperationFlags propertyOperationFlags);
  2645. template void JavascriptOperators::PatchSetPropertyScoped<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var newValue, Var defaultInstance, PropertyOperationFlags propertyOperationFlags);
  2646. template void JavascriptOperators::PatchSetPropertyScoped<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var newValue, Var defaultInstance, PropertyOperationFlags propertyOperationFlags);
  2647. BOOL JavascriptOperators::OP_InitFuncScoped(FrameDisplay *pScope, PropertyId propertyId, Var newValue, Var defaultInstance, ScriptContext* scriptContext)
  2648. {
  2649. int i;
  2650. int length = pScope->GetLength();
  2651. DynamicObject *obj;
  2652. for (i = 0; i < length; i++)
  2653. {
  2654. obj = (DynamicObject*)pScope->GetItem(i);
  2655. if (obj->InitFuncScoped(propertyId, newValue))
  2656. {
  2657. return TRUE;
  2658. }
  2659. }
  2660. AssertMsg(!TaggedNumber::Is(defaultInstance), "Root object is an int or tagged float?");
  2661. return RecyclableObject::FromVar(defaultInstance)->InitFuncScoped(propertyId, newValue);
  2662. }
  2663. BOOL JavascriptOperators::OP_InitPropertyScoped(FrameDisplay *pScope, PropertyId propertyId, Var newValue, Var defaultInstance, ScriptContext* scriptContext)
  2664. {
  2665. int i;
  2666. int length = pScope->GetLength();
  2667. DynamicObject *obj;
  2668. for (i = 0; i < length; i++)
  2669. {
  2670. obj = (DynamicObject*)pScope->GetItem(i);
  2671. if (obj->InitPropertyScoped(propertyId, newValue))
  2672. {
  2673. return TRUE;
  2674. }
  2675. }
  2676. AssertMsg(!TaggedNumber::Is(defaultInstance), "Root object is an int or tagged float?");
  2677. return RecyclableObject::FromVar(defaultInstance)->InitPropertyScoped(propertyId, newValue);
  2678. }
  2679. Var JavascriptOperators::OP_DeletePropertyScoped(
  2680. FrameDisplay *pScope,
  2681. PropertyId propertyId,
  2682. Var defaultInstance,
  2683. ScriptContext* scriptContext,
  2684. PropertyOperationFlags propertyOperationFlags)
  2685. {
  2686. int i;
  2687. int length = pScope->GetLength();
  2688. for (i = 0; i < length; i++)
  2689. {
  2690. DynamicObject *obj = (DynamicObject*)pScope->GetItem(i);
  2691. if (JavascriptOperators::HasProperty(obj, propertyId))
  2692. {
  2693. return scriptContext->GetLibrary()->CreateBoolean(JavascriptOperators::DeleteProperty(obj, propertyId, propertyOperationFlags));
  2694. }
  2695. }
  2696. return JavascriptOperators::OP_DeleteRootProperty(RecyclableObject::FromVar(defaultInstance), propertyId, scriptContext, propertyOperationFlags);
  2697. }
  2698. Var JavascriptOperators::OP_TypeofPropertyScoped(FrameDisplay *pScope, PropertyId propertyId, Var defaultInstance, ScriptContext* scriptContext)
  2699. {
  2700. int i;
  2701. int length = pScope->GetLength();
  2702. for (i = 0; i < length; i++)
  2703. {
  2704. DynamicObject *obj = (DynamicObject*)pScope->GetItem(i);
  2705. if (JavascriptOperators::HasProperty(obj, propertyId))
  2706. {
  2707. return JavascriptOperators::TypeofFld(obj, propertyId, scriptContext);
  2708. }
  2709. }
  2710. return JavascriptOperators::TypeofRootFld(RecyclableObject::FromVar(defaultInstance), propertyId, scriptContext);
  2711. }
  2712. BOOL JavascriptOperators::HasOwnItem(RecyclableObject* object, uint32 index)
  2713. {
  2714. return object->HasOwnItem(index);
  2715. }
  2716. BOOL JavascriptOperators::HasItem(RecyclableObject* object, uint64 index)
  2717. {
  2718. PropertyRecord const * propertyRecord;
  2719. ScriptContext* scriptContext = object->GetScriptContext();
  2720. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  2721. return JavascriptOperators::HasProperty(object, propertyRecord->GetPropertyId());
  2722. }
  2723. BOOL JavascriptOperators::HasItem(RecyclableObject* object, uint32 index)
  2724. {
  2725. #if ENABLE_COPYONACCESS_ARRAY
  2726. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(object);
  2727. #endif
  2728. while (JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  2729. {
  2730. if (object->HasItem(index))
  2731. {
  2732. return true;
  2733. }
  2734. // CONSIDER: Numeric property values shouldn't be on the prototype for now but if this changes
  2735. // we should add SkipsPrototype support here as well
  2736. object = JavascriptOperators::GetPrototypeNoTrap(object);
  2737. }
  2738. return false;
  2739. }
  2740. BOOL JavascriptOperators::GetOwnItem(RecyclableObject* object, uint32 index, Var* value, ScriptContext* requestContext)
  2741. {
  2742. return object->GetItem(object, index, value, requestContext);
  2743. }
  2744. BOOL JavascriptOperators::GetItem(Var instance, RecyclableObject* propertyObject, uint32 index, Var* value, ScriptContext* requestContext)
  2745. {
  2746. RecyclableObject* object = propertyObject;
  2747. while (JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  2748. {
  2749. if (object->GetItem(instance, index, value, requestContext))
  2750. {
  2751. return true;
  2752. }
  2753. if (object->SkipsPrototype())
  2754. {
  2755. break;
  2756. }
  2757. object = JavascriptOperators::GetPrototypeNoTrap(object);
  2758. }
  2759. *value = requestContext->GetMissingItemResult();
  2760. return false;
  2761. }
  2762. BOOL JavascriptOperators::GetItemReference(Var instance, RecyclableObject* propertyObject, uint32 index, Var* value, ScriptContext* requestContext)
  2763. {
  2764. RecyclableObject* object = propertyObject;
  2765. while (JavascriptOperators::GetTypeId(object) != TypeIds_Null)
  2766. {
  2767. if (object->GetItemReference(instance, index, value, requestContext))
  2768. {
  2769. return true;
  2770. }
  2771. if (object->SkipsPrototype())
  2772. {
  2773. break;
  2774. }
  2775. object = JavascriptOperators::GetPrototypeNoTrap(object);
  2776. }
  2777. *value = requestContext->GetMissingItemResult();
  2778. return false;
  2779. }
  2780. BOOL JavascriptOperators::SetItem(Var receiver, RecyclableObject* object, uint64 index, Var value, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags)
  2781. {
  2782. PropertyRecord const * propertyRecord;
  2783. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  2784. return JavascriptOperators::SetProperty(receiver, object, propertyRecord->GetPropertyId(), value, scriptContext, propertyOperationFlags);
  2785. }
  2786. BOOL JavascriptOperators::SetItem(Var receiver, RecyclableObject* object, uint32 index, Var value, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags, BOOL skipPrototypeCheck /* = FALSE */)
  2787. {
  2788. Var setterValueOrProxy = nullptr;
  2789. DescriptorFlags flags = None;
  2790. Assert(!TaggedNumber::Is(receiver));
  2791. if (JavascriptOperators::CheckPrototypesForAccessorOrNonWritableItem(object, index, &setterValueOrProxy, &flags, scriptContext, skipPrototypeCheck))
  2792. {
  2793. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  2794. if ((flags & Accessor) == Accessor)
  2795. {
  2796. if (JavascriptError::ThrowIfStrictModeUndefinedSetter(propertyOperationFlags, setterValueOrProxy, scriptContext) ||
  2797. JavascriptError::ThrowIfNotExtensibleUndefinedSetter(propertyOperationFlags, setterValueOrProxy, scriptContext))
  2798. {
  2799. return TRUE;
  2800. }
  2801. if (setterValueOrProxy)
  2802. {
  2803. RecyclableObject* func = RecyclableObject::FromVar(setterValueOrProxy);
  2804. JavascriptOperators::CallSetter(func, receiver, value, scriptContext);
  2805. }
  2806. return TRUE;
  2807. }
  2808. else if ((flags & Proxy) == Proxy)
  2809. {
  2810. Assert(JavascriptProxy::Is(setterValueOrProxy));
  2811. JavascriptProxy* proxy = JavascriptProxy::FromVar(setterValueOrProxy);
  2812. const PropertyRecord* propertyRecord;
  2813. proxy->PropertyIdFromInt(index, &propertyRecord);
  2814. return proxy->SetPropertyTrap(receiver, JavascriptProxy::SetPropertyTrapKind::SetItemKind, propertyRecord->GetPropertyId(), value, scriptContext, skipPrototypeCheck);
  2815. }
  2816. else
  2817. {
  2818. Assert((flags & Data) == Data && (flags & Writable) == None);
  2819. if ((propertyOperationFlags & PropertyOperationFlags::PropertyOperation_ThrowIfNotExtensible) == PropertyOperationFlags::PropertyOperation_ThrowIfNotExtensible)
  2820. {
  2821. JavascriptError::ThrowTypeError(scriptContext, JSERR_NonExtensibleObject);
  2822. }
  2823. JavascriptError::ThrowCantAssign(propertyOperationFlags, scriptContext, index);
  2824. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, scriptContext);
  2825. return FALSE;
  2826. }
  2827. }
  2828. else if (!JavascriptOperators::IsObject(receiver))
  2829. {
  2830. JavascriptError::ThrowCantAssignIfStrictMode(propertyOperationFlags, scriptContext);
  2831. return FALSE;
  2832. }
  2833. return (RecyclableObject::FromVar(receiver))->SetItem(index, value, propertyOperationFlags);
  2834. }
  2835. BOOL JavascriptOperators::DeleteItem(RecyclableObject* object, uint32 index, PropertyOperationFlags propertyOperationFlags)
  2836. {
  2837. return object->DeleteItem(index, propertyOperationFlags);
  2838. }
  2839. BOOL JavascriptOperators::DeleteItem(RecyclableObject* object, uint64 index, PropertyOperationFlags propertyOperationFlags)
  2840. {
  2841. PropertyRecord const * propertyRecord;
  2842. JavascriptOperators::GetPropertyIdForInt(index, object->GetScriptContext(), &propertyRecord);
  2843. return JavascriptOperators::DeleteProperty(object, propertyRecord->GetPropertyId(), propertyOperationFlags);
  2844. }
  2845. BOOL JavascriptOperators::OP_HasItem(Var instance, Var index, ScriptContext* scriptContext)
  2846. {
  2847. RecyclableObject* object = TaggedNumber::Is(instance) ?
  2848. scriptContext->GetLibrary()->GetNumberPrototype() :
  2849. RecyclableObject::FromVar(instance);
  2850. uint32 indexVal;
  2851. PropertyRecord const * propertyRecord;
  2852. IndexType indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, false);
  2853. if (indexType == IndexType_Number)
  2854. {
  2855. return HasItem(object, indexVal);
  2856. }
  2857. else
  2858. {
  2859. Assert(indexType == IndexType_PropertyId);
  2860. if (propertyRecord == nullptr && !JavascriptOperators::CanShortcutOnUnknownPropertyName(object))
  2861. {
  2862. indexType = GetIndexTypeFromPrimitive(index, scriptContext, &indexVal, &propertyRecord, true);
  2863. Assert(indexType == IndexType_PropertyId);
  2864. Assert(propertyRecord != nullptr);
  2865. }
  2866. if (propertyRecord != nullptr)
  2867. {
  2868. return HasProperty(object, propertyRecord->GetPropertyId());
  2869. }
  2870. else
  2871. {
  2872. #if DBG
  2873. JavascriptString* indexStr = JavascriptConversion::ToString(index, scriptContext);
  2874. PropertyRecord const * debugPropertyRecord;
  2875. scriptContext->GetOrAddPropertyRecord(indexStr->GetString(), indexStr->GetLength(), &debugPropertyRecord);
  2876. AssertMsg(!JavascriptOperators::HasProperty(object, debugPropertyRecord->GetPropertyId()), "how did this property come? See OS Bug 2727708 if you see this come from the web");
  2877. #endif
  2878. return FALSE;
  2879. }
  2880. }
  2881. }
  2882. #if ENABLE_PROFILE_INFO
  2883. void JavascriptOperators::UpdateNativeArrayProfileInfoToCreateVarArray(Var instance, const bool expectingNativeFloatArray, const bool expectingVarArray)
  2884. {
  2885. Assert(instance);
  2886. Assert(expectingNativeFloatArray ^ expectingVarArray);
  2887. if (!JavascriptNativeArray::Is(instance))
  2888. {
  2889. return;
  2890. }
  2891. ArrayCallSiteInfo *const arrayCallSiteInfo = JavascriptNativeArray::FromVar(instance)->GetArrayCallSiteInfo();
  2892. if (!arrayCallSiteInfo)
  2893. {
  2894. return;
  2895. }
  2896. if (expectingNativeFloatArray)
  2897. {
  2898. // Profile data is expecting a native float array. Ensure that at the array's creation site, that a native int array
  2899. // is not created, such that the profiled array type would be correct.
  2900. arrayCallSiteInfo->SetIsNotNativeIntArray();
  2901. }
  2902. else
  2903. {
  2904. // Profile data is expecting a var array. Ensure that at the array's creation site, that a native array is not
  2905. // created, such that the profiled array type would be correct.
  2906. Assert(expectingVarArray);
  2907. arrayCallSiteInfo->SetIsNotNativeArray();
  2908. }
  2909. }
  2910. bool JavascriptOperators::SetElementMayHaveImplicitCalls(ScriptContext *const scriptContext)
  2911. {
  2912. return
  2913. scriptContext->optimizationOverrides.GetArraySetElementFastPathVtable() ==
  2914. ScriptContextOptimizationOverrideInfo::InvalidVtable;
  2915. }
  2916. #endif
  2917. RecyclableObject *JavascriptOperators::GetCallableObjectOrThrow(const Var callee, ScriptContext *const scriptContext)
  2918. {
  2919. Assert(callee);
  2920. Assert(scriptContext);
  2921. if (TaggedNumber::Is(callee))
  2922. {
  2923. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedFunction /* TODO-ERROR: get arg name - aFunc */);
  2924. }
  2925. return RecyclableObject::FromVar(callee);
  2926. }
  2927. #if ENABLE_NATIVE_CODEGEN
  2928. Var JavascriptOperators::OP_GetElementI_JIT(Var instance, Var index, ScriptContext *scriptContext)
  2929. {
  2930. Assert(Js::JavascriptStackWalker::ValidateTopJitFrame(scriptContext));
  2931. return OP_GetElementI(instance, index, scriptContext);
  2932. }
  2933. #else
  2934. Var JavascriptOperators::OP_GetElementI_JIT(Var instance, Var index, ScriptContext *scriptContext)
  2935. {
  2936. return OP_GetElementI(instance, index, scriptContext);
  2937. }
  2938. #endif
  2939. #if ENABLE_NATIVE_CODEGEN
  2940. Var JavascriptOperators::OP_GetElementI_JIT_ExpectingNativeFloatArray(Var instance, Var index, ScriptContext *scriptContext)
  2941. {
  2942. Assert(Js::JavascriptStackWalker::ValidateTopJitFrame(scriptContext));
  2943. UpdateNativeArrayProfileInfoToCreateVarArray(instance, true, false);
  2944. return OP_GetElementI_JIT(instance, index, scriptContext);
  2945. }
  2946. Var JavascriptOperators::OP_GetElementI_JIT_ExpectingVarArray(Var instance, Var index, ScriptContext *scriptContext)
  2947. {
  2948. Assert(Js::JavascriptStackWalker::ValidateTopJitFrame(scriptContext));
  2949. UpdateNativeArrayProfileInfoToCreateVarArray(instance, false, true);
  2950. return OP_GetElementI_JIT(instance, index, scriptContext);
  2951. }
  2952. #endif
  2953. Var JavascriptOperators::OP_GetElementI_UInt32(Var instance, uint32 index, ScriptContext* scriptContext)
  2954. {
  2955. #if FLOATVAR
  2956. return OP_GetElementI_JIT(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext);
  2957. #else
  2958. char buffer[sizeof(Js::JavascriptNumber)];
  2959. return OP_GetElementI_JIT(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  2960. (Js::JavascriptNumber *)buffer), scriptContext);
  2961. #endif
  2962. }
  2963. Var JavascriptOperators::OP_GetElementI_UInt32_ExpectingNativeFloatArray(Var instance, uint32 index, ScriptContext* scriptContext)
  2964. {
  2965. #if ENABLE_PROFILE_INFO
  2966. UpdateNativeArrayProfileInfoToCreateVarArray(instance, true, false);
  2967. #endif
  2968. return OP_GetElementI_UInt32(instance, index, scriptContext);
  2969. }
  2970. Var JavascriptOperators::OP_GetElementI_UInt32_ExpectingVarArray(Var instance, uint32 index, ScriptContext* scriptContext)
  2971. {
  2972. #if ENABLE_PROFILE_INFO
  2973. UpdateNativeArrayProfileInfoToCreateVarArray(instance, false, true);
  2974. #endif
  2975. return OP_GetElementI_UInt32(instance, index, scriptContext);
  2976. }
  2977. Var JavascriptOperators::OP_GetElementI_Int32(Var instance, int32 index, ScriptContext* scriptContext)
  2978. {
  2979. #if FLOATVAR
  2980. return OP_GetElementI_JIT(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext);
  2981. #else
  2982. char buffer[sizeof(Js::JavascriptNumber)];
  2983. return OP_GetElementI_JIT(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  2984. (Js::JavascriptNumber *)buffer), scriptContext);
  2985. #endif
  2986. }
  2987. Var JavascriptOperators::OP_GetElementI_Int32_ExpectingNativeFloatArray(Var instance, int32 index, ScriptContext* scriptContext)
  2988. {
  2989. #if ENABLE_PROFILE_INFO
  2990. UpdateNativeArrayProfileInfoToCreateVarArray(instance, true, false);
  2991. #endif
  2992. return OP_GetElementI_Int32(instance, index, scriptContext);
  2993. }
  2994. Var JavascriptOperators::OP_GetElementI_Int32_ExpectingVarArray(Var instance, int32 index, ScriptContext* scriptContext)
  2995. {
  2996. #if ENABLE_PROFILE_INFO
  2997. UpdateNativeArrayProfileInfoToCreateVarArray(instance, false, true);
  2998. #endif
  2999. return OP_GetElementI_Int32(instance, index, scriptContext);
  3000. }
  3001. BOOL JavascriptOperators::GetItemFromArrayPrototype(JavascriptArray * arr, int32 indexInt, Var * result, ScriptContext * scriptContext)
  3002. {
  3003. // try get from Array prototype
  3004. RecyclableObject* prototype = arr->GetPrototype();
  3005. if (JavascriptOperators::GetTypeId(prototype) != TypeIds_Array) //This can be TypeIds_ES5Array (or any other object changed through __proto__).
  3006. {
  3007. return false;
  3008. }
  3009. JavascriptArray* arrayPrototype = JavascriptArray::FromVar(prototype); //Prototype must be Array.prototype (unless changed through __proto__)
  3010. if (arrayPrototype->GetLength() && arrayPrototype->GetItem(arrayPrototype, (uint32)indexInt, result, scriptContext))
  3011. {
  3012. return true;
  3013. }
  3014. prototype = arrayPrototype->GetPrototype(); //Its prototype must be Object.prototype (unless changed through __proto__)
  3015. if (prototype->GetScriptContext()->GetLibrary()->GetObjectPrototype() != prototype)
  3016. {
  3017. return false;
  3018. }
  3019. if (DynamicObject::FromVar(prototype)->HasNonEmptyObjectArray())
  3020. {
  3021. if (prototype->GetItem(arr, (uint32)indexInt, result, scriptContext))
  3022. {
  3023. return true;
  3024. }
  3025. }
  3026. *result = scriptContext->GetMissingItemResult();
  3027. return true;
  3028. }
  3029. template <typename T>
  3030. BOOL JavascriptOperators::OP_GetElementI_ArrayFastPath(T * arr, int indexInt, Var * result, ScriptContext * scriptContext)
  3031. {
  3032. #if ENABLE_COPYONACCESS_ARRAY
  3033. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  3034. #endif
  3035. if (indexInt >= 0)
  3036. {
  3037. if (!CrossSite::IsCrossSiteObjectTyped(arr))
  3038. {
  3039. if (arr->T::DirectGetVarItemAt((uint32)indexInt, result, scriptContext))
  3040. {
  3041. return true;
  3042. }
  3043. }
  3044. else
  3045. {
  3046. if (arr->GetItem(arr, (uint32)indexInt, result, scriptContext))
  3047. {
  3048. return true;
  3049. }
  3050. }
  3051. return GetItemFromArrayPrototype(arr, indexInt, result, scriptContext);
  3052. }
  3053. return false;
  3054. }
  3055. Var JavascriptOperators::OP_GetElementI(Var instance, Var index, ScriptContext* scriptContext)
  3056. {
  3057. JavascriptString *temp = NULL;
  3058. #if ENABLE_COPYONACCESS_ARRAY
  3059. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3060. #endif
  3061. if (TaggedInt::Is(index))
  3062. {
  3063. TaggedIntIndex:
  3064. switch (JavascriptOperators::GetTypeId(instance))
  3065. {
  3066. case TypeIds_Array: //fast path for array
  3067. {
  3068. Var result;
  3069. if (OP_GetElementI_ArrayFastPath(JavascriptArray::FromVar(instance), TaggedInt::ToInt32(index), &result, scriptContext))
  3070. {
  3071. return result;
  3072. }
  3073. break;
  3074. }
  3075. case TypeIds_NativeIntArray:
  3076. {
  3077. Var result;
  3078. if (OP_GetElementI_ArrayFastPath(JavascriptNativeIntArray::FromVar(instance), TaggedInt::ToInt32(index), &result, scriptContext))
  3079. {
  3080. return result;
  3081. }
  3082. break;
  3083. }
  3084. case TypeIds_NativeFloatArray:
  3085. {
  3086. Var result;
  3087. if (OP_GetElementI_ArrayFastPath(JavascriptNativeFloatArray::FromVar(instance), TaggedInt::ToInt32(index), &result, scriptContext))
  3088. {
  3089. return result;
  3090. }
  3091. break;
  3092. }
  3093. case TypeIds_String: // fast path for string
  3094. {
  3095. charcount_t indexInt = TaggedInt::ToUInt32(index);
  3096. JavascriptString* string = JavascriptString::FromVar(instance);
  3097. Var result;
  3098. if (string->JavascriptString::GetItem(instance, indexInt, &result, scriptContext))
  3099. {
  3100. return result;
  3101. }
  3102. break;
  3103. }
  3104. case TypeIds_Int8Array:
  3105. {
  3106. // The typed array will deal with all possible values for the index
  3107. int32 indexInt = TaggedInt::ToInt32(index);
  3108. if (VirtualTableInfo<Int8VirtualArray>::HasVirtualTable(instance))
  3109. {
  3110. Int8VirtualArray* int8Array = Int8VirtualArray::FromVar(instance);
  3111. if (!CrossSite::IsCrossSiteObjectTyped(int8Array) && indexInt >= 0)
  3112. {
  3113. return int8Array->DirectGetItem(indexInt);
  3114. }
  3115. }
  3116. else
  3117. {
  3118. Int8Array* int8Array = Int8Array::FromVar(instance);
  3119. if (!CrossSite::IsCrossSiteObjectTyped(int8Array) && indexInt >= 0)
  3120. {
  3121. return int8Array->DirectGetItem(indexInt);
  3122. }
  3123. }
  3124. break;
  3125. }
  3126. case TypeIds_Uint8Array:
  3127. {
  3128. // The typed array will deal with all possible values for the index
  3129. int32 indexInt = TaggedInt::ToInt32(index);
  3130. if (VirtualTableInfo<Uint8VirtualArray>::HasVirtualTable(instance))
  3131. {
  3132. Uint8VirtualArray* uint8Array = Uint8VirtualArray::FromVar(instance);
  3133. if (!CrossSite::IsCrossSiteObjectTyped(uint8Array) && indexInt >= 0)
  3134. {
  3135. return uint8Array->DirectGetItem(indexInt);
  3136. }
  3137. }
  3138. else
  3139. {
  3140. Uint8Array* uint8Array = Uint8Array::FromVar(instance);
  3141. if (!CrossSite::IsCrossSiteObjectTyped(uint8Array) && indexInt >= 0)
  3142. {
  3143. return uint8Array->DirectGetItem(indexInt);
  3144. }
  3145. }
  3146. break;
  3147. }
  3148. case TypeIds_Uint8ClampedArray:
  3149. {
  3150. // The typed array will deal with all possible values for the index
  3151. int32 indexInt = TaggedInt::ToInt32(index);
  3152. if (VirtualTableInfo<Uint8ClampedVirtualArray>::HasVirtualTable(instance))
  3153. {
  3154. Uint8ClampedVirtualArray* uint8ClampedArray = Uint8ClampedVirtualArray::FromVar(instance);
  3155. if (!CrossSite::IsCrossSiteObjectTyped(uint8ClampedArray) && indexInt >= 0)
  3156. {
  3157. return uint8ClampedArray->DirectGetItem(indexInt);
  3158. }
  3159. }
  3160. else
  3161. {
  3162. Uint8ClampedArray* uint8ClampedArray = Uint8ClampedArray::FromVar(instance);
  3163. if (!CrossSite::IsCrossSiteObjectTyped(uint8ClampedArray) && indexInt >= 0)
  3164. {
  3165. return uint8ClampedArray->DirectGetItem(indexInt);
  3166. }
  3167. }
  3168. break;
  3169. }
  3170. case TypeIds_Int16Array:
  3171. {
  3172. // The type array will deal with all possible values for the index
  3173. int32 indexInt = TaggedInt::ToInt32(index);
  3174. if (VirtualTableInfo<Int16VirtualArray>::HasVirtualTable(instance))
  3175. {
  3176. Int16VirtualArray* int16Array = Int16VirtualArray::FromVar(instance);
  3177. if (!CrossSite::IsCrossSiteObjectTyped(int16Array) && indexInt >= 0)
  3178. {
  3179. return int16Array->DirectGetItem(indexInt);
  3180. }
  3181. }
  3182. else
  3183. {
  3184. Int16Array* int16Array = Int16Array::FromVar(instance);
  3185. if (!CrossSite::IsCrossSiteObjectTyped(int16Array) && indexInt >= 0)
  3186. {
  3187. return int16Array->DirectGetItem(indexInt);
  3188. }
  3189. }
  3190. break;
  3191. }
  3192. case TypeIds_Uint16Array:
  3193. {
  3194. // The type array will deal with all possible values for the index
  3195. int32 indexInt = TaggedInt::ToInt32(index);
  3196. if (VirtualTableInfo<Uint16VirtualArray>::HasVirtualTable(instance))
  3197. {
  3198. Uint16VirtualArray* uint16Array = Uint16VirtualArray::FromVar(instance);
  3199. if (!CrossSite::IsCrossSiteObjectTyped(uint16Array) && indexInt >= 0)
  3200. {
  3201. return uint16Array->DirectGetItem(indexInt);
  3202. }
  3203. }
  3204. else
  3205. {
  3206. Uint16Array* uint16Array = Uint16Array::FromVar(instance);
  3207. if (!CrossSite::IsCrossSiteObjectTyped(uint16Array) && indexInt >= 0)
  3208. {
  3209. return uint16Array->DirectGetItem(indexInt);
  3210. }
  3211. }
  3212. break;
  3213. }
  3214. case TypeIds_Int32Array:
  3215. {
  3216. // The type array will deal with all possible values for the index
  3217. int32 indexInt = TaggedInt::ToInt32(index);
  3218. if (VirtualTableInfo<Int32VirtualArray>::HasVirtualTable(instance))
  3219. {
  3220. Int32VirtualArray* int32Array = Int32VirtualArray::FromVar(instance);
  3221. if (!CrossSite::IsCrossSiteObjectTyped(int32Array) && indexInt >= 0)
  3222. {
  3223. return int32Array->DirectGetItem(indexInt);
  3224. }
  3225. }
  3226. else
  3227. {
  3228. Int32Array* int32Array = Int32Array::FromVar(instance);
  3229. if (!CrossSite::IsCrossSiteObjectTyped(int32Array) && indexInt >= 0)
  3230. {
  3231. return int32Array->DirectGetItem(indexInt);
  3232. }
  3233. }
  3234. break;
  3235. }
  3236. case TypeIds_Uint32Array:
  3237. {
  3238. // The type array will deal with all possible values for the index
  3239. int32 indexInt = TaggedInt::ToInt32(index);
  3240. if (VirtualTableInfo<Uint32VirtualArray>::HasVirtualTable(instance))
  3241. {
  3242. Uint32VirtualArray* uint32Array = Uint32VirtualArray::FromVar(instance);
  3243. if (!CrossSite::IsCrossSiteObjectTyped(uint32Array) && indexInt >= 0)
  3244. {
  3245. return uint32Array->DirectGetItem(indexInt);
  3246. }
  3247. }
  3248. else
  3249. {
  3250. Uint32Array* uint32Array = Uint32Array::FromVar(instance);
  3251. if (!CrossSite::IsCrossSiteObjectTyped(uint32Array) && indexInt >= 0)
  3252. {
  3253. return uint32Array->DirectGetItem(indexInt);
  3254. }
  3255. }
  3256. break;
  3257. }
  3258. case TypeIds_Float32Array:
  3259. {
  3260. // The type array will deal with all possible values for the index
  3261. int32 indexInt = TaggedInt::ToInt32(index);
  3262. if (VirtualTableInfo<Float32VirtualArray>::HasVirtualTable(instance))
  3263. {
  3264. Float32VirtualArray* float32Array = Float32VirtualArray::FromVar(instance);
  3265. if (!CrossSite::IsCrossSiteObjectTyped(float32Array) && indexInt >= 0)
  3266. {
  3267. return float32Array->DirectGetItem(indexInt);
  3268. }
  3269. }
  3270. else
  3271. {
  3272. Float32Array* float32Array = Float32Array::FromVar(instance);
  3273. if (!CrossSite::IsCrossSiteObjectTyped(float32Array) && indexInt >= 0)
  3274. {
  3275. return float32Array->DirectGetItem(indexInt);
  3276. }
  3277. }
  3278. break;
  3279. }
  3280. case TypeIds_Float64Array:
  3281. {
  3282. // The type array will deal with all possible values for the index
  3283. int32 indexInt = TaggedInt::ToInt32(index);
  3284. if (VirtualTableInfo<Float64VirtualArray>::HasVirtualTable(instance))
  3285. {
  3286. Float64VirtualArray* float64Array = Float64VirtualArray::FromVar(instance);
  3287. if (!CrossSite::IsCrossSiteObjectTyped(float64Array) && indexInt >= 0)
  3288. {
  3289. return float64Array->DirectGetItem(indexInt);
  3290. }
  3291. }
  3292. else
  3293. {
  3294. Float64Array* float64Array = Float64Array::FromVar(instance);
  3295. if (!CrossSite::IsCrossSiteObjectTyped(float64Array) && indexInt >= 0)
  3296. {
  3297. return float64Array->DirectGetItem(indexInt);
  3298. }
  3299. }
  3300. break;
  3301. }
  3302. default:
  3303. break;
  3304. }
  3305. }
  3306. else if (JavascriptNumber::Is_NoTaggedIntCheck(index))
  3307. {
  3308. uint32 uint32Index = JavascriptConversion::ToUInt32(index, scriptContext);
  3309. if ((double)uint32Index == JavascriptNumber::GetValue(index) && !TaggedInt::IsOverflow(uint32Index))
  3310. {
  3311. index = TaggedInt::ToVarUnchecked(uint32Index);
  3312. goto TaggedIntIndex;
  3313. }
  3314. }
  3315. else if (JavascriptString::Is(index)) // fastpath for PropertyStrings
  3316. {
  3317. temp = JavascriptString::FromVar(index);
  3318. Assert(temp->GetScriptContext() == scriptContext);
  3319. if (VirtualTableInfo<Js::PropertyString>::HasVirtualTable(temp))
  3320. {
  3321. PropertyString * propertyString = (PropertyString*)temp;
  3322. PropertyCache const *cache = propertyString->GetPropertyCache();
  3323. RecyclableObject* object = nullptr;
  3324. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  3325. {
  3326. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  3327. JavascriptString::FromVar(index)->GetSz());
  3328. }
  3329. if (object->GetType() == cache->type)
  3330. {
  3331. #if DBG_DUMP
  3332. scriptContext->forinCache++;
  3333. #endif
  3334. Assert(object->GetScriptContext() == scriptContext);
  3335. Var value;
  3336. if (cache->isInlineSlot)
  3337. {
  3338. value = DynamicObject::FromVar(object)->GetInlineSlot(cache->dataSlotIndex);
  3339. }
  3340. else
  3341. {
  3342. value = DynamicObject::FromVar(object)->GetAuxSlot(cache->dataSlotIndex);
  3343. }
  3344. Assert(!CrossSite::NeedMarshalVar(value, scriptContext));
  3345. Assert(value == JavascriptOperators::GetProperty(object, propertyString->GetPropertyRecord()->GetPropertyId(), scriptContext)
  3346. || value == JavascriptOperators::GetRootProperty(object, propertyString->GetPropertyRecord()->GetPropertyId(), scriptContext));
  3347. return value;
  3348. }
  3349. #if DBG_DUMP
  3350. scriptContext->forinNoCache++;
  3351. #endif
  3352. PropertyRecord const * propertyRecord = propertyString->GetPropertyRecord();
  3353. Var value;
  3354. if (propertyRecord->IsNumeric())
  3355. {
  3356. if (JavascriptOperators::GetItem(instance, object, propertyRecord->GetNumericValue(), &value, scriptContext))
  3357. {
  3358. return value;
  3359. }
  3360. }
  3361. else
  3362. {
  3363. if (JavascriptOperators::GetPropertyWPCache(instance, object, propertyRecord->GetPropertyId(), &value, scriptContext, propertyString))
  3364. {
  3365. return value;
  3366. }
  3367. }
  3368. return scriptContext->GetLibrary()->GetUndefined();
  3369. }
  3370. #if DBG_DUMP
  3371. scriptContext->forinNoCache++;
  3372. #endif
  3373. }
  3374. return JavascriptOperators::GetElementIHelper(instance, index, instance, scriptContext);
  3375. }
  3376. Var JavascriptOperators::GetElementIHelper(Var instance, Var index, Var receiver, ScriptContext* scriptContext)
  3377. {
  3378. RecyclableObject* object = nullptr;
  3379. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  3380. {
  3381. if (scriptContext->GetThreadContext()->RecordImplicitException())
  3382. {
  3383. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined, GetPropertyDisplayNameForError(index, scriptContext));
  3384. }
  3385. else
  3386. {
  3387. return scriptContext->GetLibrary()->GetUndefined();
  3388. }
  3389. }
  3390. uint32 indexVal;
  3391. PropertyRecord const * propertyRecord;
  3392. JavascriptString * propertyNameString;
  3393. Var value;
  3394. IndexType indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, &propertyNameString, false, true);
  3395. if (indexType == IndexType_Number)
  3396. {
  3397. if (JavascriptOperators::GetItem(receiver, object, indexVal, &value, scriptContext))
  3398. {
  3399. return value;
  3400. }
  3401. }
  3402. else if (indexType == IndexType_JavascriptString)
  3403. {
  3404. if (JavascriptOperators::GetPropertyWPCache(receiver, object, propertyNameString, &value, scriptContext, nullptr))
  3405. {
  3406. return value;
  3407. }
  3408. }
  3409. else
  3410. {
  3411. Assert(indexType == IndexType_PropertyId);
  3412. if (propertyRecord == nullptr && !JavascriptOperators::CanShortcutOnUnknownPropertyName(object))
  3413. {
  3414. indexType = GetIndexTypeFromPrimitive(index, scriptContext, &indexVal, &propertyRecord, &propertyNameString, true, true);
  3415. Assert(indexType == IndexType_PropertyId);
  3416. Assert(propertyRecord != nullptr);
  3417. }
  3418. if (propertyRecord != nullptr)
  3419. {
  3420. if (JavascriptOperators::GetPropertyWPCache(receiver, object, propertyRecord->GetPropertyId(), &value, scriptContext, nullptr))
  3421. {
  3422. return value;
  3423. }
  3424. }
  3425. #if DBG
  3426. else
  3427. {
  3428. JavascriptString* indexStr = JavascriptConversion::ToString(index, scriptContext);
  3429. PropertyRecord const * debugPropertyRecord;
  3430. scriptContext->GetOrAddPropertyRecord(indexStr->GetString(), indexStr->GetLength(), &debugPropertyRecord);
  3431. AssertMsg(!JavascriptOperators::GetProperty(receiver, object, debugPropertyRecord->GetPropertyId(), &value, scriptContext), "how did this property come? See OS Bug 2727708 if you see this come from the web");
  3432. }
  3433. #endif
  3434. }
  3435. return scriptContext->GetMissingItemResult();
  3436. }
  3437. int32 JavascriptOperators::OP_GetNativeIntElementI(Var instance, Var index)
  3438. {
  3439. #if ENABLE_COPYONACCESS_ARRAY
  3440. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3441. #endif
  3442. if (TaggedInt::Is(index))
  3443. {
  3444. int32 indexInt = TaggedInt::ToInt32(index);
  3445. if (indexInt < 0)
  3446. {
  3447. return JavascriptNativeIntArray::MissingItem;
  3448. }
  3449. JavascriptArray * arr = JavascriptArray::FromVar(instance);
  3450. int32 result;
  3451. if (arr->DirectGetItemAt((uint32)indexInt, &result))
  3452. {
  3453. return result;
  3454. }
  3455. }
  3456. else if (JavascriptNumber::Is_NoTaggedIntCheck(index))
  3457. {
  3458. int32 indexInt;
  3459. bool isInt32;
  3460. double dIndex = JavascriptNumber::GetValue(index);
  3461. if (JavascriptNumber::TryGetInt32OrUInt32Value(dIndex, &indexInt, &isInt32))
  3462. {
  3463. if (isInt32 && indexInt < 0)
  3464. {
  3465. return JavascriptNativeIntArray::MissingItem;
  3466. }
  3467. JavascriptArray * arr = JavascriptArray::FromVar(instance);
  3468. int32 result;
  3469. if (arr->DirectGetItemAt((uint32)indexInt, &result))
  3470. {
  3471. return result;
  3472. }
  3473. }
  3474. }
  3475. else
  3476. {
  3477. AssertMsg(false, "Non-numerical index in this helper?");
  3478. }
  3479. return JavascriptNativeIntArray::MissingItem;
  3480. }
  3481. int32 JavascriptOperators::OP_GetNativeIntElementI_UInt32(Var instance, uint32 index, ScriptContext* scriptContext)
  3482. {
  3483. #if FLOATVAR
  3484. return OP_GetNativeIntElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext));
  3485. #else
  3486. char buffer[sizeof(Js::JavascriptNumber)];
  3487. return OP_GetNativeIntElementI(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3488. (Js::JavascriptNumber *)buffer));
  3489. #endif
  3490. }
  3491. int32 JavascriptOperators::OP_GetNativeIntElementI_Int32(Var instance, int32 index, ScriptContext* scriptContext)
  3492. {
  3493. #if FLOATVAR
  3494. return OP_GetNativeIntElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext));
  3495. #else
  3496. char buffer[sizeof(Js::JavascriptNumber)];
  3497. return OP_GetNativeIntElementI(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3498. (Js::JavascriptNumber *)buffer));
  3499. #endif
  3500. }
  3501. double JavascriptOperators::OP_GetNativeFloatElementI(Var instance, Var index)
  3502. {
  3503. double result = 0;
  3504. if (TaggedInt::Is(index))
  3505. {
  3506. int32 indexInt = TaggedInt::ToInt32(index);
  3507. if (indexInt < 0)
  3508. {
  3509. result = JavascriptNativeFloatArray::MissingItem;
  3510. }
  3511. else
  3512. {
  3513. JavascriptArray * arr = JavascriptArray::FromVar(instance);
  3514. if (!arr->DirectGetItemAt((uint32)indexInt, &result))
  3515. {
  3516. result = JavascriptNativeFloatArray::MissingItem;
  3517. }
  3518. }
  3519. }
  3520. else if (JavascriptNumber::Is_NoTaggedIntCheck(index))
  3521. {
  3522. int32 indexInt;
  3523. bool isInt32;
  3524. double dIndex = JavascriptNumber::GetValue(index);
  3525. if (JavascriptNumber::TryGetInt32OrUInt32Value(dIndex, &indexInt, &isInt32))
  3526. {
  3527. if (isInt32 && indexInt < 0)
  3528. {
  3529. result = JavascriptNativeFloatArray::MissingItem;
  3530. }
  3531. else
  3532. {
  3533. JavascriptArray * arr = JavascriptArray::FromVar(instance);
  3534. if (!arr->DirectGetItemAt((uint32)indexInt, &result))
  3535. {
  3536. result = JavascriptNativeFloatArray::MissingItem;
  3537. }
  3538. }
  3539. }
  3540. }
  3541. else
  3542. {
  3543. AssertMsg(false, "Non-numerical index in this helper?");
  3544. }
  3545. return result;
  3546. }
  3547. double JavascriptOperators::OP_GetNativeFloatElementI_UInt32(Var instance, uint32 index, ScriptContext* scriptContext)
  3548. {
  3549. #if FLOATVAR
  3550. return OP_GetNativeFloatElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext));
  3551. #else
  3552. char buffer[sizeof(Js::JavascriptNumber)];
  3553. return OP_GetNativeFloatElementI(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3554. (Js::JavascriptNumber *)buffer));
  3555. #endif
  3556. }
  3557. double JavascriptOperators::OP_GetNativeFloatElementI_Int32(Var instance, int32 index, ScriptContext* scriptContext)
  3558. {
  3559. #if FLOATVAR
  3560. return OP_GetNativeFloatElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext));
  3561. #else
  3562. char buffer[sizeof(Js::JavascriptNumber)];
  3563. return OP_GetNativeFloatElementI(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3564. (Js::JavascriptNumber *)buffer));
  3565. #endif
  3566. }
  3567. Var JavascriptOperators::OP_GetMethodElement_UInt32(Var instance, uint32 index, ScriptContext* scriptContext)
  3568. {
  3569. #if FLOATVAR
  3570. return OP_GetMethodElement(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext);
  3571. #else
  3572. char buffer[sizeof(Js::JavascriptNumber)];
  3573. return OP_GetMethodElement(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3574. (Js::JavascriptNumber *)buffer), scriptContext);
  3575. #endif
  3576. }
  3577. Var JavascriptOperators::OP_GetMethodElement_Int32(Var instance, int32 index, ScriptContext* scriptContext)
  3578. {
  3579. #if FLOATVAR
  3580. return OP_GetElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext);
  3581. #else
  3582. char buffer[sizeof(Js::JavascriptNumber)];
  3583. return OP_GetMethodElement(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3584. (Js::JavascriptNumber *)buffer), scriptContext);
  3585. #endif
  3586. }
  3587. Var JavascriptOperators::OP_GetMethodElement(Var instance, Var index, ScriptContext* scriptContext)
  3588. {
  3589. RecyclableObject* object = nullptr;
  3590. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  3591. {
  3592. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined, GetPropertyDisplayNameForError(index, scriptContext));
  3593. }
  3594. ThreadContext* threadContext = scriptContext->GetThreadContext();
  3595. ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  3596. threadContext->ClearImplicitCallFlags();
  3597. uint32 indexVal;
  3598. PropertyRecord const * propertyRecord;
  3599. Var value = NULL;
  3600. BOOL hasProperty = FALSE;
  3601. IndexType indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, false);
  3602. if (indexType == IndexType_Number)
  3603. {
  3604. hasProperty = JavascriptOperators::GetItemReference(instance, object, indexVal, &value, scriptContext);
  3605. }
  3606. else
  3607. {
  3608. Assert(indexType == IndexType_PropertyId);
  3609. if (propertyRecord == nullptr && !JavascriptOperators::CanShortcutOnUnknownPropertyName(object))
  3610. {
  3611. indexType = GetIndexTypeFromPrimitive(index, scriptContext, &indexVal, &propertyRecord, true);
  3612. Assert(indexType == IndexType_PropertyId);
  3613. Assert(propertyRecord != nullptr);
  3614. }
  3615. if (propertyRecord != nullptr)
  3616. {
  3617. hasProperty = JavascriptOperators::GetPropertyReference(instance, object, propertyRecord->GetPropertyId(), &value, scriptContext, NULL);
  3618. }
  3619. #if DBG
  3620. else
  3621. {
  3622. JavascriptString* indexStr = JavascriptConversion::ToString(index, scriptContext);
  3623. PropertyRecord const * debugPropertyRecord;
  3624. scriptContext->GetOrAddPropertyRecord(indexStr->GetString(), indexStr->GetLength(), &debugPropertyRecord);
  3625. AssertMsg(!JavascriptOperators::GetPropertyReference(instance, object, debugPropertyRecord->GetPropertyId(), &value, scriptContext, NULL),
  3626. "how did this property come? See OS Bug 2727708 if you see this come from the web");
  3627. }
  3628. #endif
  3629. }
  3630. if (!hasProperty)
  3631. {
  3632. JavascriptString* varName = JavascriptConversion::ToString(index, scriptContext);
  3633. // ES5 11.2.3 #2: We evaluate the call target but don't throw yet if target member is missing. We need to evaluate argList
  3634. // first (#3). Postpone throwing error to invoke time.
  3635. value = ThrowErrorObject::CreateThrowTypeErrorObject(scriptContext, VBSERR_OLENoPropOrMethod, varName);
  3636. }
  3637. else if(!JavascriptConversion::IsCallable(value))
  3638. {
  3639. // ES5 11.2.3 #2: We evaluate the call target but don't throw yet if target member is missing. We need to evaluate argList
  3640. // first (#3). Postpone throwing error to invoke time.
  3641. JavascriptString* varName = JavascriptConversion::ToString(index, scriptContext);
  3642. value = ThrowErrorObject::CreateThrowTypeErrorObject(scriptContext, JSERR_Property_NeedFunction, varName);
  3643. }
  3644. threadContext->CheckAndResetImplicitCallAccessorFlag();
  3645. threadContext->AddImplicitCallFlags(savedImplicitCallFlags);
  3646. return value;
  3647. }
  3648. BOOL JavascriptOperators::OP_SetElementI_UInt32(Var instance, uint32 index, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  3649. {
  3650. #if FLOATVAR
  3651. return OP_SetElementI_JIT(instance, Js::JavascriptNumber::ToVar(index, scriptContext), value, scriptContext, flags);
  3652. #else
  3653. char buffer[sizeof(Js::JavascriptNumber)];
  3654. return OP_SetElementI_JIT(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3655. (Js::JavascriptNumber *)buffer), value, scriptContext, flags);
  3656. #endif
  3657. }
  3658. BOOL JavascriptOperators::OP_SetElementI_Int32(Var instance, int32 index, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  3659. {
  3660. #if FLOATVAR
  3661. return OP_SetElementI_JIT(instance, Js::JavascriptNumber::ToVar(index, scriptContext), value, scriptContext, flags);
  3662. #else
  3663. char buffer[sizeof(Js::JavascriptNumber)];
  3664. return OP_SetElementI_JIT(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  3665. (Js::JavascriptNumber *)buffer), value, scriptContext, flags);
  3666. #endif
  3667. }
  3668. BOOL JavascriptOperators::OP_SetElementI_JIT(Var instance, Var index, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  3669. {
  3670. if (TaggedNumber::Is(instance))
  3671. {
  3672. return OP_SetElementI(instance, index, value, scriptContext, flags);
  3673. }
  3674. INT_PTR vt = VirtualTableInfoBase::GetVirtualTable(instance);
  3675. OP_SetElementI(instance, index, value, scriptContext, flags);
  3676. return vt != VirtualTableInfoBase::GetVirtualTable(instance);
  3677. }
  3678. BOOL JavascriptOperators::OP_SetElementI(Var instance, Var index, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  3679. {
  3680. #if ENABLE_COPYONACCESS_ARRAY
  3681. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  3682. #endif
  3683. TypeId instanceType = JavascriptOperators::GetTypeId(instance);
  3684. bool isTypedArray = (instanceType >= TypeIds_Int8Array && instanceType <= TypeIds_Float64Array);
  3685. if (isTypedArray)
  3686. {
  3687. if (TaggedInt::Is(index) || JavascriptNumber::Is_NoTaggedIntCheck(index) || JavascriptString::Is(index))
  3688. {
  3689. BOOL returnValue = FALSE;
  3690. bool isNumericIndex = false;
  3691. switch (instanceType)
  3692. {
  3693. case TypeIds_Int8Array:
  3694. {
  3695. // The typed array will deal with all possible values for the index
  3696. if (VirtualTableInfo<Int8VirtualArray>::HasVirtualTable(instance))
  3697. {
  3698. Int8VirtualArray* int8Array = Int8VirtualArray::FromVar(instance);
  3699. if (!CrossSite::IsCrossSiteObjectTyped(int8Array))
  3700. {
  3701. returnValue = int8Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3702. }
  3703. }
  3704. else
  3705. {
  3706. Int8Array* int8Array = Int8Array::FromVar(instance);
  3707. if (!CrossSite::IsCrossSiteObjectTyped(int8Array))
  3708. {
  3709. returnValue = int8Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3710. }
  3711. }
  3712. break;
  3713. }
  3714. case TypeIds_Uint8Array:
  3715. {
  3716. // The typed array will deal with all possible values for the index
  3717. if (VirtualTableInfo<Uint8VirtualArray>::HasVirtualTable(instance))
  3718. {
  3719. Uint8VirtualArray* uint8Array = Uint8VirtualArray::FromVar(instance);
  3720. if (!CrossSite::IsCrossSiteObjectTyped(uint8Array))
  3721. {
  3722. returnValue = uint8Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3723. }
  3724. }
  3725. else
  3726. {
  3727. Uint8Array* uint8Array = Uint8Array::FromVar(instance);
  3728. if (!CrossSite::IsCrossSiteObjectTyped(uint8Array))
  3729. {
  3730. returnValue = uint8Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3731. }
  3732. }
  3733. break;
  3734. }
  3735. case TypeIds_Uint8ClampedArray:
  3736. {
  3737. // The typed array will deal with all possible values for the index
  3738. if (VirtualTableInfo<Uint8ClampedVirtualArray>::HasVirtualTable(instance))
  3739. {
  3740. Uint8ClampedVirtualArray* uint8ClampedArray = Uint8ClampedVirtualArray::FromVar(instance);
  3741. if (!CrossSite::IsCrossSiteObjectTyped(uint8ClampedArray))
  3742. {
  3743. returnValue = uint8ClampedArray->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3744. }
  3745. }
  3746. else
  3747. {
  3748. Uint8ClampedArray* uint8ClampedArray = Uint8ClampedArray::FromVar(instance);
  3749. if (!CrossSite::IsCrossSiteObjectTyped(uint8ClampedArray))
  3750. {
  3751. returnValue = uint8ClampedArray->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3752. }
  3753. }
  3754. break;
  3755. }
  3756. case TypeIds_Int16Array:
  3757. {
  3758. // The type array will deal with all possible values for the index
  3759. if (VirtualTableInfo<Int16VirtualArray>::HasVirtualTable(instance))
  3760. {
  3761. Int16VirtualArray* int16Array = Int16VirtualArray::FromVar(instance);
  3762. if (!CrossSite::IsCrossSiteObjectTyped(int16Array))
  3763. {
  3764. returnValue = int16Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3765. }
  3766. }
  3767. else
  3768. {
  3769. Int16Array* int16Array = Int16Array::FromVar(instance);
  3770. if (!CrossSite::IsCrossSiteObjectTyped(int16Array))
  3771. {
  3772. returnValue = int16Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3773. }
  3774. }
  3775. break;
  3776. }
  3777. case TypeIds_Uint16Array:
  3778. {
  3779. // The type array will deal with all possible values for the index
  3780. if (VirtualTableInfo<Uint16VirtualArray>::HasVirtualTable(instance))
  3781. {
  3782. Uint16VirtualArray* uint16Array = Uint16VirtualArray::FromVar(instance);
  3783. if (!CrossSite::IsCrossSiteObjectTyped(uint16Array))
  3784. {
  3785. returnValue = uint16Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3786. }
  3787. }
  3788. else
  3789. {
  3790. Uint16Array* uint16Array = Uint16Array::FromVar(instance);
  3791. if (!CrossSite::IsCrossSiteObjectTyped(uint16Array))
  3792. {
  3793. returnValue = uint16Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3794. }
  3795. }
  3796. break;
  3797. }
  3798. case TypeIds_Int32Array:
  3799. {
  3800. // The type array will deal with all possible values for the index
  3801. if (VirtualTableInfo<Int32VirtualArray>::HasVirtualTable(instance))
  3802. {
  3803. Int32VirtualArray* int32Array = Int32VirtualArray::FromVar(instance);
  3804. if (!CrossSite::IsCrossSiteObjectTyped(int32Array))
  3805. {
  3806. returnValue = int32Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3807. }
  3808. }
  3809. else
  3810. {
  3811. Int32Array* int32Array = Int32Array::FromVar(instance);
  3812. if (!CrossSite::IsCrossSiteObjectTyped(int32Array))
  3813. {
  3814. returnValue = int32Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3815. }
  3816. }
  3817. break;
  3818. }
  3819. case TypeIds_Uint32Array:
  3820. {
  3821. // The type array will deal with all possible values for the index
  3822. if (VirtualTableInfo<Uint32VirtualArray>::HasVirtualTable(instance))
  3823. {
  3824. Uint32VirtualArray* uint32Array = Uint32VirtualArray::FromVar(instance);
  3825. if (!CrossSite::IsCrossSiteObjectTyped(uint32Array))
  3826. {
  3827. returnValue = uint32Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3828. }
  3829. }
  3830. else
  3831. {
  3832. Uint32Array* uint32Array = Uint32Array::FromVar(instance);
  3833. if (!CrossSite::IsCrossSiteObjectTyped(uint32Array))
  3834. {
  3835. returnValue = uint32Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3836. }
  3837. }
  3838. break;
  3839. }
  3840. case TypeIds_Float32Array:
  3841. {
  3842. // The type array will deal with all possible values for the index
  3843. if (VirtualTableInfo<Float32VirtualArray>::HasVirtualTable(instance))
  3844. {
  3845. Float32VirtualArray* float32Array = Float32VirtualArray::FromVar(instance);
  3846. if (!CrossSite::IsCrossSiteObjectTyped(float32Array))
  3847. {
  3848. returnValue = float32Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3849. }
  3850. }
  3851. else
  3852. {
  3853. Float32Array* float32Array = Float32Array::FromVar(instance);
  3854. if (!CrossSite::IsCrossSiteObjectTyped(float32Array))
  3855. {
  3856. returnValue = float32Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3857. }
  3858. }
  3859. break;
  3860. }
  3861. case TypeIds_Float64Array:
  3862. {
  3863. // The type array will deal with all possible values for the index
  3864. if (VirtualTableInfo<Float64VirtualArray>::HasVirtualTable(instance))
  3865. {
  3866. Float64VirtualArray* float64Array = Float64VirtualArray::FromVar(instance);
  3867. if (!CrossSite::IsCrossSiteObjectTyped(float64Array))
  3868. {
  3869. returnValue = float64Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3870. }
  3871. }
  3872. else
  3873. {
  3874. Float64Array* float64Array = Float64Array::FromVar(instance);
  3875. if (!CrossSite::IsCrossSiteObjectTyped(float64Array))
  3876. {
  3877. returnValue = float64Array->ValidateIndexAndDirectSetItem(index, value, &isNumericIndex);
  3878. }
  3879. }
  3880. break;
  3881. }
  3882. }
  3883. // if this was numeric index, return operation status else
  3884. // Return the result of calling the default ordinary object [[Set]] internal method (9.1.8) on O passing P, V, and Receiver as arguments.
  3885. if (isNumericIndex)
  3886. return returnValue;
  3887. }
  3888. }
  3889. else
  3890. {
  3891. if (TaggedInt::Is(index))
  3892. {
  3893. TaggedIntIndex:
  3894. switch (instanceType)
  3895. {
  3896. case TypeIds_NativeIntArray:
  3897. case TypeIds_NativeFloatArray:
  3898. case TypeIds_Array: // fast path for array
  3899. {
  3900. int indexInt = TaggedInt::ToInt32(index);
  3901. if (indexInt >= 0 && scriptContext->optimizationOverrides.IsEnabledArraySetElementFastPath())
  3902. {
  3903. JavascriptArray::FromVar(instance)->SetItem((uint32)indexInt, value, flags);
  3904. return true;
  3905. }
  3906. break;
  3907. }
  3908. }
  3909. }
  3910. else if (JavascriptNumber::Is_NoTaggedIntCheck(index))
  3911. {
  3912. double dIndexValue = JavascriptNumber::GetValue(index);
  3913. uint32 uint32Index = JavascriptConversion::ToUInt32(index, scriptContext);
  3914. if ((double)uint32Index == dIndexValue && !TaggedInt::IsOverflow(uint32Index))
  3915. {
  3916. index = TaggedInt::ToVarUnchecked(uint32Index);
  3917. goto TaggedIntIndex;
  3918. }
  3919. }
  3920. }
  3921. RecyclableObject* object;
  3922. BOOL isNullOrUndefined = !GetPropertyObject(instance, scriptContext, &object);
  3923. Assert(object == instance || TaggedNumber::Is(instance));
  3924. if (isNullOrUndefined)
  3925. {
  3926. if (!scriptContext->GetThreadContext()->RecordImplicitException())
  3927. {
  3928. return FALSE;
  3929. }
  3930. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotSet_NullOrUndefined, GetPropertyDisplayNameForError(index, scriptContext));
  3931. }
  3932. return JavascriptOperators::SetElementIHelper(instance, object, index, value, scriptContext, flags);
  3933. }
  3934. BOOL JavascriptOperators::SetElementIHelper(Var receiver, RecyclableObject* object, Var index, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  3935. {
  3936. PropertyString * propertyString = nullptr;
  3937. Js::IndexType indexType;
  3938. uint32 indexVal = 0;
  3939. PropertyRecord const * propertyRecord = nullptr;
  3940. JavascriptString * propertyNameString = nullptr;
  3941. if (TaggedNumber::Is(receiver))
  3942. {
  3943. indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, true);
  3944. if (indexType == IndexType_Number)
  3945. {
  3946. return JavascriptOperators::SetItemOnTaggedNumber(receiver, object, indexVal, value, scriptContext, flags);
  3947. }
  3948. else
  3949. {
  3950. return JavascriptOperators::SetPropertyOnTaggedNumber(receiver, object, propertyRecord->GetPropertyId(), value, scriptContext, flags);
  3951. }
  3952. }
  3953. // fastpath for PropertyStrings only if receiver == object
  3954. if (!TaggedInt::Is(index) && JavascriptString::Is(index) &&
  3955. VirtualTableInfo<Js::PropertyString>::HasVirtualTable(JavascriptString::FromVar(index)))
  3956. {
  3957. propertyString = (PropertyString *)JavascriptString::FromVar(index);
  3958. Assert(propertyString->GetScriptContext() == scriptContext);
  3959. PropertyCache const * cache = propertyString->GetPropertyCache();
  3960. if (receiver == object && object->GetType() == cache->type && cache->isStoreFieldEnabled)
  3961. {
  3962. #if DBG
  3963. propertyRecord = propertyString->GetPropertyRecord();
  3964. #endif
  3965. #if DBG_DUMP
  3966. scriptContext->forinCache++;
  3967. #endif
  3968. Assert(object->GetScriptContext() == scriptContext);
  3969. Assert(!CrossSite::NeedMarshalVar(value, scriptContext));
  3970. if (cache->isInlineSlot)
  3971. {
  3972. DynamicObject::FromVar(object)->SetInlineSlot(SetSlotArguments(propertyRecord->GetPropertyId(), cache->dataSlotIndex, value));
  3973. }
  3974. else
  3975. {
  3976. DynamicObject::FromVar(object)->SetAuxSlot(SetSlotArguments(propertyRecord->GetPropertyId(), cache->dataSlotIndex, value));
  3977. }
  3978. return true;
  3979. }
  3980. propertyRecord = propertyString->GetPropertyRecord();
  3981. if (propertyRecord->IsNumeric())
  3982. {
  3983. indexType = IndexType_Number;
  3984. indexVal = propertyRecord->GetNumericValue();
  3985. }
  3986. else
  3987. {
  3988. indexType = IndexType_PropertyId;
  3989. }
  3990. #if DBG_DUMP
  3991. scriptContext->forinNoCache++;
  3992. #endif
  3993. }
  3994. else
  3995. {
  3996. #if DBG_DUMP
  3997. scriptContext->forinNoCache += (!TaggedInt::Is(index) && JavascriptString::Is(index));
  3998. #endif
  3999. indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, &propertyNameString, false, true);
  4000. if (scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4001. scriptContext->GetThreadContext()->GetImplicitCallFlags() != ImplicitCall_None)
  4002. {
  4003. // We hit an implicit call trying to convert the index, and implicit calls are disabled, so
  4004. // quit before we try to store the element.
  4005. return FALSE;
  4006. }
  4007. }
  4008. if (indexType == IndexType_Number)
  4009. {
  4010. return JavascriptOperators::SetItem(receiver, object, indexVal, value, scriptContext, flags);
  4011. }
  4012. else if (indexType == IndexType_JavascriptString)
  4013. {
  4014. Assert(propertyNameString);
  4015. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  4016. if (BuiltInPropertyRecords::NaN.Equals(propertyName))
  4017. {
  4018. // Follow SetProperty convention for NaN
  4019. return JavascriptOperators::SetProperty(receiver, object, PropertyIds::NaN, value, scriptContext, flags);
  4020. }
  4021. else if (BuiltInPropertyRecords::Infinity.Equals(propertyName))
  4022. {
  4023. // Follow SetProperty convention for Infinity
  4024. return JavascriptOperators::SetProperty(receiver, object, PropertyIds::Infinity, value, scriptContext, flags);
  4025. }
  4026. return JavascriptOperators::SetPropertyWPCache(receiver, object, propertyNameString, value, scriptContext, nullptr, flags);
  4027. }
  4028. else if (indexType == IndexType_PropertyId)
  4029. {
  4030. Assert(propertyRecord);
  4031. PropertyId propId = propertyRecord->GetPropertyId();
  4032. if (propId == PropertyIds::NaN || propId == PropertyIds::Infinity)
  4033. {
  4034. // As we no longer convert o[x] into o.x for NaN and Infinity, we need to follow SetProperty convention for these,
  4035. // which would check for read-only properties, strict mode, etc.
  4036. // Note that "-Infinity" does not qualify as property name, so we don't have to take care of it.
  4037. return JavascriptOperators::SetProperty(receiver, object, propId, value, scriptContext, flags);
  4038. }
  4039. }
  4040. return JavascriptOperators::SetPropertyWPCache(receiver, object, propertyRecord->GetPropertyId(), value, scriptContext, propertyString, flags);
  4041. }
  4042. BOOL JavascriptOperators::OP_SetNativeIntElementI(
  4043. Var instance,
  4044. Var aElementIndex,
  4045. int32 iValue,
  4046. ScriptContext* scriptContext,
  4047. PropertyOperationFlags flags)
  4048. {
  4049. if (TaggedInt::Is(aElementIndex))
  4050. {
  4051. int32 indexInt = TaggedInt::ToInt32(aElementIndex);
  4052. if (indexInt >= 0 && scriptContext->optimizationOverrides.IsEnabledArraySetElementFastPath())
  4053. {
  4054. JavascriptNativeIntArray *arr = JavascriptNativeIntArray::FromVar(instance);
  4055. if (!(arr->TryGrowHeadSegmentAndSetItem<int32, JavascriptNativeIntArray>((uint32)indexInt, iValue)))
  4056. {
  4057. arr->SetItem(indexInt, iValue);
  4058. }
  4059. return TRUE;
  4060. }
  4061. }
  4062. return JavascriptOperators::OP_SetElementI(instance, aElementIndex, JavascriptNumber::ToVar(iValue, scriptContext), scriptContext, flags);
  4063. }
  4064. BOOL JavascriptOperators::OP_SetNativeIntElementI_UInt32(
  4065. Var instance,
  4066. uint32 aElementIndex,
  4067. int32 iValue,
  4068. ScriptContext* scriptContext,
  4069. PropertyOperationFlags flags)
  4070. {
  4071. #if FLOATVAR
  4072. return OP_SetNativeIntElementI(instance, Js::JavascriptNumber::ToVar(aElementIndex, scriptContext), iValue, scriptContext, flags);
  4073. #else
  4074. char buffer[sizeof(Js::JavascriptNumber)];
  4075. return OP_SetNativeIntElementI(instance, Js::JavascriptNumber::ToVarInPlace(aElementIndex, scriptContext,
  4076. (Js::JavascriptNumber *)buffer), iValue, scriptContext, flags);
  4077. #endif
  4078. }
  4079. BOOL JavascriptOperators::OP_SetNativeIntElementI_Int32(
  4080. Var instance,
  4081. int aElementIndex,
  4082. int32 iValue,
  4083. ScriptContext* scriptContext,
  4084. PropertyOperationFlags flags)
  4085. {
  4086. #if FLOATVAR
  4087. return OP_SetNativeIntElementI(instance, Js::JavascriptNumber::ToVar(aElementIndex, scriptContext), iValue, scriptContext, flags);
  4088. #else
  4089. char buffer[sizeof(Js::JavascriptNumber)];
  4090. return OP_SetNativeIntElementI(instance, Js::JavascriptNumber::ToVarInPlace(aElementIndex, scriptContext,
  4091. (Js::JavascriptNumber *)buffer), iValue, scriptContext, flags);
  4092. #endif
  4093. }
  4094. BOOL JavascriptOperators::OP_SetNativeFloatElementI(
  4095. Var instance,
  4096. Var aElementIndex,
  4097. ScriptContext* scriptContext,
  4098. PropertyOperationFlags flags,
  4099. double dValue)
  4100. {
  4101. if (TaggedInt::Is(aElementIndex))
  4102. {
  4103. int32 indexInt = TaggedInt::ToInt32(aElementIndex);
  4104. if (indexInt >= 0 && scriptContext->optimizationOverrides.IsEnabledArraySetElementFastPath())
  4105. {
  4106. JavascriptNativeFloatArray *arr = JavascriptNativeFloatArray::FromVar(instance);
  4107. if (!(arr->TryGrowHeadSegmentAndSetItem<double, JavascriptNativeFloatArray>((uint32)indexInt, dValue)))
  4108. {
  4109. arr->SetItem(indexInt, dValue);
  4110. }
  4111. return TRUE;
  4112. }
  4113. }
  4114. return JavascriptOperators::OP_SetElementI(instance, aElementIndex, JavascriptNumber::ToVarWithCheck(dValue, scriptContext), scriptContext, flags);
  4115. }
  4116. BOOL JavascriptOperators::OP_SetNativeFloatElementI_UInt32(
  4117. Var instance, uint32
  4118. aElementIndex,
  4119. ScriptContext* scriptContext,
  4120. PropertyOperationFlags flags,
  4121. double dValue)
  4122. {
  4123. #if FLOATVAR
  4124. return OP_SetNativeFloatElementI(instance, JavascriptNumber::ToVar(aElementIndex, scriptContext), scriptContext, flags, dValue);
  4125. #else
  4126. char buffer[sizeof(Js::JavascriptNumber)];
  4127. return OP_SetNativeFloatElementI(instance, JavascriptNumber::ToVarInPlace(aElementIndex, scriptContext,
  4128. (Js::JavascriptNumber *)buffer), scriptContext, flags, dValue);
  4129. #endif
  4130. }
  4131. BOOL JavascriptOperators::OP_SetNativeFloatElementI_Int32(
  4132. Var instance,
  4133. int aElementIndex,
  4134. ScriptContext* scriptContext,
  4135. PropertyOperationFlags flags,
  4136. double dValue)
  4137. {
  4138. #if FLOATVAR
  4139. return OP_SetNativeFloatElementI(instance, JavascriptNumber::ToVar(aElementIndex, scriptContext), scriptContext, flags, dValue);
  4140. #else
  4141. char buffer[sizeof(Js::JavascriptNumber)];
  4142. return OP_SetNativeFloatElementI(instance, JavascriptNumber::ToVarInPlace(aElementIndex, scriptContext,
  4143. (Js::JavascriptNumber *)buffer), scriptContext, flags, dValue);
  4144. #endif
  4145. }
  4146. BOOL JavascriptOperators::OP_Memcopy(Var dstInstance, int32 dstStart, Var srcInstance, int32 srcStart, int32 length, ScriptContext* scriptContext)
  4147. {
  4148. if (length <= 0)
  4149. {
  4150. return false;
  4151. }
  4152. TypeId instanceType = JavascriptOperators::GetTypeId(srcInstance);
  4153. if (instanceType != JavascriptOperators::GetTypeId(dstInstance))
  4154. {
  4155. return false;
  4156. }
  4157. if (srcStart != dstStart)
  4158. {
  4159. return false;
  4160. }
  4161. BOOL returnValue = false;
  4162. #define MEMCOPY_TYPED_ARRAY(type, conversion) type ## ::FromVar(dstInstance)->DirectSetItemAtRange( type ## ::FromVar(srcInstance), srcStart, dstStart, length, JavascriptConversion:: ## conversion)
  4163. switch (instanceType)
  4164. {
  4165. case TypeIds_Int8Array:
  4166. {
  4167. returnValue = MEMCOPY_TYPED_ARRAY(Int8Array, ToInt8);
  4168. break;
  4169. }
  4170. case TypeIds_Uint8Array:
  4171. {
  4172. returnValue = MEMCOPY_TYPED_ARRAY(Uint8Array, ToUInt8);
  4173. break;
  4174. }
  4175. case TypeIds_Uint8ClampedArray:
  4176. {
  4177. returnValue = MEMCOPY_TYPED_ARRAY(Uint8ClampedArray, ToUInt8Clamped);
  4178. break;
  4179. }
  4180. case TypeIds_Int16Array:
  4181. {
  4182. returnValue = MEMCOPY_TYPED_ARRAY(Int16Array, ToInt16);
  4183. break;
  4184. }
  4185. case TypeIds_Uint16Array:
  4186. {
  4187. returnValue = MEMCOPY_TYPED_ARRAY(Uint16Array, ToUInt16);
  4188. break;
  4189. }
  4190. case TypeIds_Int32Array:
  4191. {
  4192. returnValue = MEMCOPY_TYPED_ARRAY(Int32Array, ToInt32);
  4193. break;
  4194. }
  4195. case TypeIds_Uint32Array:
  4196. {
  4197. returnValue = MEMCOPY_TYPED_ARRAY(Uint32Array, ToUInt32);
  4198. break;
  4199. }
  4200. case TypeIds_Float32Array:
  4201. {
  4202. returnValue = MEMCOPY_TYPED_ARRAY(Float32Array, ToFloat);
  4203. break;
  4204. }
  4205. case TypeIds_Float64Array:
  4206. {
  4207. returnValue = MEMCOPY_TYPED_ARRAY(Float64Array, ToNumber);
  4208. break;
  4209. }
  4210. case TypeIds_Array:
  4211. case TypeIds_NativeFloatArray:
  4212. case TypeIds_NativeIntArray:
  4213. {
  4214. if (dstStart < 0 || srcStart < 0)
  4215. {
  4216. // This is not supported, Bailout
  4217. break;
  4218. }
  4219. // Upper bounds check for source array
  4220. JavascriptArray* srcArray = JavascriptArray::FromVar(srcInstance);
  4221. JavascriptArray* dstArray = JavascriptArray::FromVar(dstInstance);
  4222. if (scriptContext->optimizationOverrides.IsEnabledArraySetElementFastPath())
  4223. {
  4224. INT_PTR vt = VirtualTableInfoBase::GetVirtualTable(dstInstance);
  4225. if (instanceType == TypeIds_Array)
  4226. {
  4227. returnValue = dstArray->DirectSetItemAtRangeFromArray<Var>(dstStart, length, srcArray, srcStart);
  4228. }
  4229. else if (instanceType == TypeIds_NativeIntArray)
  4230. {
  4231. returnValue = dstArray->DirectSetItemAtRangeFromArray<int32>(dstStart, length, srcArray, srcStart);
  4232. }
  4233. else
  4234. {
  4235. returnValue = dstArray->DirectSetItemAtRangeFromArray<double>(dstStart, length, srcArray, srcStart);
  4236. }
  4237. returnValue &= vt == VirtualTableInfoBase::GetVirtualTable(dstInstance);
  4238. }
  4239. break;
  4240. }
  4241. default:
  4242. AssertMsg(false, "We don't support this type for memcopy yet.");
  4243. break;
  4244. }
  4245. #undef MEMCOPY_TYPED_ARRAY
  4246. return returnValue;
  4247. }
  4248. BOOL JavascriptOperators::OP_Memset(Var instance, int32 start, Var value, int32 length, ScriptContext* scriptContext)
  4249. {
  4250. if (length <= 0)
  4251. {
  4252. return false;
  4253. }
  4254. TypeId instanceType = JavascriptOperators::GetTypeId(instance);
  4255. BOOL returnValue = false;
  4256. // The typed array will deal with all possible values for the index
  4257. #define MEMSET_TYPED_ARRAY(type, conversion) type ## ::FromVar(instance)->DirectSetItemAtRange(start, length, value, JavascriptConversion:: ## conversion)
  4258. switch (instanceType)
  4259. {
  4260. case TypeIds_Int8Array:
  4261. {
  4262. returnValue = MEMSET_TYPED_ARRAY(Int8Array, ToInt8);
  4263. break;
  4264. }
  4265. case TypeIds_Uint8Array:
  4266. {
  4267. returnValue = MEMSET_TYPED_ARRAY(Uint8Array, ToUInt8);
  4268. break;
  4269. }
  4270. case TypeIds_Uint8ClampedArray:
  4271. {
  4272. returnValue = MEMSET_TYPED_ARRAY(Uint8ClampedArray, ToUInt8Clamped);
  4273. break;
  4274. }
  4275. case TypeIds_Int16Array:
  4276. {
  4277. returnValue = MEMSET_TYPED_ARRAY(Int16Array, ToInt16);
  4278. break;
  4279. }
  4280. case TypeIds_Uint16Array:
  4281. {
  4282. returnValue = MEMSET_TYPED_ARRAY(Uint16Array, ToUInt16);
  4283. break;
  4284. }
  4285. case TypeIds_Int32Array:
  4286. {
  4287. returnValue = MEMSET_TYPED_ARRAY(Int32Array, ToInt32);
  4288. break;
  4289. }
  4290. case TypeIds_Uint32Array:
  4291. {
  4292. returnValue = MEMSET_TYPED_ARRAY(Uint32Array, ToUInt32);
  4293. break;
  4294. }
  4295. case TypeIds_Float32Array:
  4296. {
  4297. returnValue = MEMSET_TYPED_ARRAY(Float32Array, ToFloat);
  4298. break;
  4299. }
  4300. case TypeIds_Float64Array:
  4301. {
  4302. returnValue = MEMSET_TYPED_ARRAY(Float64Array, ToNumber);
  4303. break;
  4304. }
  4305. case TypeIds_NativeFloatArray:
  4306. case TypeIds_NativeIntArray:
  4307. case TypeIds_Array:
  4308. {
  4309. if (start < 0)
  4310. {
  4311. for (start; start < 0 && length > 0; ++start, --length)
  4312. {
  4313. if (!OP_SetElementI(instance, JavascriptNumber::ToVar(start, scriptContext), value, scriptContext))
  4314. {
  4315. return false;
  4316. }
  4317. }
  4318. }
  4319. if (scriptContext->optimizationOverrides.IsEnabledArraySetElementFastPath())
  4320. {
  4321. INT_PTR vt = VirtualTableInfoBase::GetVirtualTable(instance);
  4322. if (instanceType == TypeIds_Array)
  4323. {
  4324. returnValue = JavascriptArray::FromVar(instance)->DirectSetItemAtRange<Var>(start, length, value);
  4325. }
  4326. else if (instanceType == TypeIds_NativeIntArray)
  4327. {
  4328. // Only accept tagged int. Also covers case for MissingItem
  4329. if (!TaggedInt::Is(value))
  4330. {
  4331. return false;
  4332. }
  4333. int32 intValue = JavascriptConversion::ToInt32(value, scriptContext);
  4334. returnValue = JavascriptArray::FromVar(instance)->DirectSetItemAtRange<int32>(start, length, intValue);
  4335. }
  4336. else
  4337. {
  4338. // For native float arrays, the jit doesn't check the type of the source so we have to do it here
  4339. if (!JavascriptNumber::Is(value) && !TaggedNumber::Is(value))
  4340. {
  4341. return false;
  4342. }
  4343. double doubleValue = JavascriptConversion::ToNumber(value, scriptContext);
  4344. // Special case for missing item
  4345. if (SparseArraySegment<double>::IsMissingItem(&doubleValue))
  4346. {
  4347. return false;
  4348. }
  4349. returnValue = JavascriptArray::FromVar(instance)->DirectSetItemAtRange<double>(start, length, doubleValue);
  4350. }
  4351. returnValue &= vt == VirtualTableInfoBase::GetVirtualTable(instance);
  4352. }
  4353. break;
  4354. }
  4355. default:
  4356. AssertMsg(false, "We don't support this type for memset yet.");
  4357. break;
  4358. }
  4359. #undef MEMSET_TYPED_ARRAY
  4360. return returnValue;
  4361. }
  4362. Var JavascriptOperators::OP_DeleteElementI_UInt32(Var instance, uint32 index, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags)
  4363. {
  4364. #if FLOATVAR
  4365. return OP_DeleteElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext, propertyOperationFlags);
  4366. #else
  4367. char buffer[sizeof(Js::JavascriptNumber)];
  4368. return OP_DeleteElementI(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  4369. (Js::JavascriptNumber *)buffer), scriptContext, propertyOperationFlags);
  4370. #endif
  4371. }
  4372. Var JavascriptOperators::OP_DeleteElementI_Int32(Var instance, int32 index, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags)
  4373. {
  4374. #if FLOATVAR
  4375. return OP_DeleteElementI(instance, Js::JavascriptNumber::ToVar(index, scriptContext), scriptContext, propertyOperationFlags);
  4376. #else
  4377. char buffer[sizeof(Js::JavascriptNumber)];
  4378. return OP_DeleteElementI(instance, Js::JavascriptNumber::ToVarInPlace(index, scriptContext,
  4379. (Js::JavascriptNumber *)buffer), scriptContext, propertyOperationFlags);
  4380. #endif
  4381. }
  4382. Var JavascriptOperators::OP_DeleteElementI(Var instance, Var index, ScriptContext* scriptContext, PropertyOperationFlags propertyOperationFlags)
  4383. {
  4384. if(TaggedNumber::Is(instance))
  4385. {
  4386. return scriptContext->GetLibrary()->GetTrue();
  4387. }
  4388. #if ENABLE_COPYONACCESS_ARRAY
  4389. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  4390. #endif
  4391. TypeId typeId = JavascriptOperators::GetTypeId(instance);
  4392. if (typeId == TypeIds_Null || typeId == TypeIds_Undefined)
  4393. {
  4394. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotDelete_NullOrUndefined, GetPropertyDisplayNameForError(index, scriptContext));
  4395. }
  4396. RecyclableObject* object = RecyclableObject::FromVar(instance);
  4397. uint32 indexVal;
  4398. PropertyRecord const * propertyRecord;
  4399. BOOL result = TRUE;
  4400. IndexType indexType = GetIndexType(index, scriptContext, &indexVal, &propertyRecord, false);
  4401. if (indexType == IndexType_Number)
  4402. {
  4403. result = JavascriptOperators::DeleteItem(object, indexVal, propertyOperationFlags);
  4404. }
  4405. else
  4406. {
  4407. Assert(indexType == IndexType_PropertyId);
  4408. if (propertyRecord == nullptr && !JavascriptOperators::CanShortcutOnUnknownPropertyName(object))
  4409. {
  4410. indexType = GetIndexTypeFromPrimitive(index, scriptContext, &indexVal, &propertyRecord, true);
  4411. Assert(indexType == IndexType_PropertyId);
  4412. Assert(propertyRecord != nullptr);
  4413. }
  4414. if (propertyRecord != nullptr)
  4415. {
  4416. result = JavascriptOperators::DeleteProperty(object, propertyRecord->GetPropertyId(), propertyOperationFlags);
  4417. }
  4418. #if DBG
  4419. else
  4420. {
  4421. JavascriptString* indexStr = JavascriptConversion::ToString(index, scriptContext);
  4422. PropertyRecord const * debugPropertyRecord;
  4423. scriptContext->GetOrAddPropertyRecord(indexStr->GetString(), indexStr->GetLength(), &debugPropertyRecord);
  4424. AssertMsg(JavascriptOperators::DeleteProperty(object, debugPropertyRecord->GetPropertyId(), propertyOperationFlags), "delete should have been true. See OS Bug 2727708 if you see this come from the web");
  4425. }
  4426. #endif
  4427. }
  4428. return scriptContext->GetLibrary()->CreateBoolean(result);
  4429. }
  4430. Var JavascriptOperators::OP_GetLength(Var instance, ScriptContext* scriptContext)
  4431. {
  4432. return JavascriptOperators::OP_GetProperty(instance, PropertyIds::length, scriptContext);
  4433. }
  4434. inline Var JavascriptOperators::GetThisFromModuleRoot(Var thisVar)
  4435. {
  4436. RootObjectBase * rootObject = static_cast<RootObjectBase*>(thisVar);
  4437. RecyclableObject* hostObject = rootObject->GetHostObject();
  4438. //
  4439. // if the module root has the host object, use that as "this"
  4440. //
  4441. if (hostObject)
  4442. {
  4443. thisVar = hostObject->GetHostDispatchVar();
  4444. }
  4445. return thisVar;
  4446. }
  4447. inline void JavascriptOperators::TryLoadRoot(Var& thisVar, TypeId typeId, int moduleID, ScriptContext* scriptContext)
  4448. {
  4449. bool loadRoot = false;
  4450. if (JavascriptOperators::IsUndefinedOrNullType(typeId) || typeId == TypeIds_ActivationObject)
  4451. {
  4452. loadRoot = true;
  4453. }
  4454. else if (typeId == TypeIds_HostDispatch)
  4455. {
  4456. TypeId remoteTypeId;
  4457. if (RecyclableObject::FromVar(thisVar)->GetRemoteTypeId(&remoteTypeId))
  4458. {
  4459. if (remoteTypeId == TypeIds_Null || remoteTypeId == TypeIds_Undefined || remoteTypeId == TypeIds_ActivationObject)
  4460. {
  4461. loadRoot = true;
  4462. }
  4463. }
  4464. }
  4465. if (loadRoot)
  4466. {
  4467. if (moduleID == 0)
  4468. {
  4469. thisVar = JavascriptOperators::OP_LdRoot(scriptContext)->ToThis();
  4470. }
  4471. else
  4472. {
  4473. Js::ModuleRoot * moduleRoot = JavascriptOperators::GetModuleRoot(moduleID, scriptContext);
  4474. if (moduleRoot == nullptr)
  4475. {
  4476. Assert(false);
  4477. thisVar = scriptContext->GetLibrary()->GetUndefined();
  4478. }
  4479. else
  4480. {
  4481. thisVar = GetThisFromModuleRoot(moduleRoot);
  4482. }
  4483. }
  4484. }
  4485. }
  4486. Var JavascriptOperators::OP_GetThis(Var thisVar, int moduleID, ScriptContext* scriptContext)
  4487. {
  4488. //
  4489. // if "this" is null or undefined
  4490. // Pass the global object
  4491. // Else
  4492. // Pass ToObject(this)
  4493. //
  4494. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4495. Assert(!JavascriptOperators::IsThisSelf(typeId));
  4496. return JavascriptOperators::GetThisHelper(thisVar, typeId, moduleID, scriptContext);
  4497. }
  4498. Var JavascriptOperators::OP_GetThisNoFastPath(Var thisVar, int moduleID, ScriptContext* scriptContext)
  4499. {
  4500. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4501. if (JavascriptOperators::IsThisSelf(typeId))
  4502. {
  4503. Assert(typeId != TypeIds_GlobalObject || ((Js::GlobalObject*)thisVar)->ToThis() == thisVar);
  4504. Assert(typeId != TypeIds_ModuleRoot || JavascriptOperators::GetThisFromModuleRoot(thisVar) == thisVar);
  4505. return thisVar;
  4506. }
  4507. return JavascriptOperators::GetThisHelper(thisVar, typeId, moduleID, scriptContext);
  4508. }
  4509. bool JavascriptOperators::IsThisSelf(TypeId typeId)
  4510. {
  4511. return (JavascriptOperators::IsObjectType(typeId) && ! JavascriptOperators::IsSpecialObjectType(typeId));
  4512. }
  4513. Var JavascriptOperators::GetThisHelper(Var thisVar, TypeId typeId, int moduleID, ScriptContext *scriptContext)
  4514. {
  4515. if (! JavascriptOperators::IsObjectType(typeId) && ! JavascriptOperators::IsUndefinedOrNullType(typeId))
  4516. {
  4517. #if !FLOATVAR
  4518. // We allowed stack number to be used as the "this" for getter and setter activation of
  4519. // n.x and n[prop], where n is the Javascript Number
  4520. return JavascriptOperators::ToObject(
  4521. JavascriptNumber::BoxStackNumber(thisVar, scriptContext), scriptContext);
  4522. #else
  4523. return JavascriptOperators::ToObject(thisVar, scriptContext);
  4524. #endif
  4525. }
  4526. else
  4527. {
  4528. TryLoadRoot(thisVar, typeId, moduleID, scriptContext);
  4529. return thisVar;
  4530. }
  4531. }
  4532. Var JavascriptOperators::OP_StrictGetThis(Var thisVar, ScriptContext* scriptContext)
  4533. {
  4534. TypeId typeId = JavascriptOperators::GetTypeId(thisVar);
  4535. if (typeId == TypeIds_ActivationObject)
  4536. {
  4537. return scriptContext->GetLibrary()->GetUndefined();
  4538. }
  4539. return thisVar;
  4540. }
  4541. BOOL JavascriptOperators::GetRemoteTypeId(Var aValue, TypeId* typeId)
  4542. {
  4543. if (GetTypeId(aValue) != TypeIds_HostDispatch)
  4544. {
  4545. return FALSE;
  4546. }
  4547. return RecyclableObject::FromVar(aValue)->GetRemoteTypeId(typeId);
  4548. }
  4549. BOOL JavascriptOperators::IsJsNativeObject(Var aValue)
  4550. {
  4551. switch(GetTypeId(aValue))
  4552. {
  4553. case TypeIds_Object:
  4554. case TypeIds_Function:
  4555. case TypeIds_Array:
  4556. case TypeIds_NativeIntArray:
  4557. #if ENABLE_COPYONACCESS_ARRAY
  4558. case TypeIds_CopyOnAccessNativeIntArray:
  4559. #endif
  4560. case TypeIds_NativeFloatArray:
  4561. case TypeIds_ES5Array:
  4562. case TypeIds_Date:
  4563. case TypeIds_WinRTDate:
  4564. case TypeIds_RegEx:
  4565. case TypeIds_Error:
  4566. case TypeIds_BooleanObject:
  4567. case TypeIds_NumberObject:
  4568. #ifdef ENABLE_SIMDJS
  4569. case TypeIds_SIMDObject:
  4570. #endif
  4571. case TypeIds_StringObject:
  4572. case TypeIds_Symbol:
  4573. case TypeIds_SymbolObject:
  4574. //case TypeIds_GlobalObject:
  4575. //case TypeIds_ModuleRoot:
  4576. //case TypeIds_HostObject:
  4577. case TypeIds_Arguments:
  4578. case TypeIds_ActivationObject:
  4579. case TypeIds_Map:
  4580. case TypeIds_Set:
  4581. case TypeIds_WeakMap:
  4582. case TypeIds_WeakSet:
  4583. case TypeIds_ArrayIterator:
  4584. case TypeIds_MapIterator:
  4585. case TypeIds_SetIterator:
  4586. case TypeIds_StringIterator:
  4587. case TypeIds_Generator:
  4588. case TypeIds_Promise:
  4589. case TypeIds_Proxy:
  4590. return true;
  4591. default:
  4592. return false;
  4593. }
  4594. }
  4595. bool JavascriptOperators::CanShortcutOnUnknownPropertyName(RecyclableObject *instance)
  4596. {
  4597. if (!CanShortcutInstanceOnUnknownPropertyName(instance))
  4598. {
  4599. return false;
  4600. }
  4601. return CanShortcutPrototypeChainOnUnknownPropertyName(instance->GetPrototype());
  4602. }
  4603. bool JavascriptOperators::CanShortcutInstanceOnUnknownPropertyName(RecyclableObject *instance)
  4604. {
  4605. if (PHASE_OFF1(Js::OptUnknownElementNamePhase))
  4606. {
  4607. return false;
  4608. }
  4609. TypeId typeId = instance->GetTypeId();
  4610. if (typeId == TypeIds_Proxy || typeId == TypeIds_HostDispatch)
  4611. {
  4612. return false;
  4613. }
  4614. if (DynamicType::Is(typeId) &&
  4615. static_cast<DynamicObject*>(instance)->GetTypeHandler()->IsStringTypeHandler())
  4616. {
  4617. return false;
  4618. }
  4619. if (instance->IsExternal())
  4620. {
  4621. return false;
  4622. }
  4623. return !(instance->HasDeferredTypeHandler() &&
  4624. JavascriptFunction::Is(instance) &&
  4625. JavascriptFunction::FromVar(instance)->IsExternalFunction());
  4626. }
  4627. bool JavascriptOperators::CanShortcutPrototypeChainOnUnknownPropertyName(RecyclableObject *prototype)
  4628. {
  4629. Assert(prototype);
  4630. for (; prototype->GetTypeId() != TypeIds_Null; prototype = prototype->GetPrototype())
  4631. {
  4632. if (!CanShortcutInstanceOnUnknownPropertyName(prototype))
  4633. {
  4634. return false;
  4635. }
  4636. }
  4637. return true;
  4638. }
  4639. RecyclableObject* JavascriptOperators::GetPrototype(RecyclableObject* instance)
  4640. {
  4641. if (JavascriptOperators::GetTypeId(instance) == TypeIds_Null)
  4642. {
  4643. return instance;
  4644. }
  4645. return instance->GetPrototype();
  4646. }
  4647. RecyclableObject* JavascriptOperators::OP_GetPrototype(Var instance, ScriptContext* scriptContext)
  4648. {
  4649. if (TaggedNumber::Is(instance))
  4650. {
  4651. return scriptContext->GetLibrary()->GetNumberPrototype();
  4652. }
  4653. else if (JavascriptOperators::GetTypeId(instance) != TypeIds_Null)
  4654. {
  4655. return JavascriptOperators::GetPrototype(RecyclableObject::FromVar(instance));
  4656. }
  4657. else
  4658. {
  4659. return scriptContext->GetLibrary()->GetNull();
  4660. }
  4661. }
  4662. BOOL JavascriptOperators::OP_BrFncEqApply(Var instance, ScriptContext *scriptContext)
  4663. {
  4664. // JavascriptFunction && !HostDispatch
  4665. if (JavascriptOperators::GetTypeId(instance) == TypeIds_Function)
  4666. {
  4667. FunctionProxy *bod= ((JavascriptFunction*)instance)->GetFunctionProxy();
  4668. if (bod != nullptr)
  4669. {
  4670. return bod->GetDirectEntryPoint(bod->GetDefaultEntryPointInfo()) == &Js::JavascriptFunction::EntryApply;
  4671. }
  4672. else
  4673. {
  4674. FunctionInfo* info = ((JavascriptFunction *)instance)->GetFunctionInfo();
  4675. if (info != nullptr)
  4676. {
  4677. return &Js::JavascriptFunction::EntryApply == info->GetOriginalEntryPoint();
  4678. }
  4679. else
  4680. {
  4681. return false;
  4682. }
  4683. }
  4684. }
  4685. return false;
  4686. }
  4687. BOOL JavascriptOperators::OP_BrFncNeqApply(Var instance, ScriptContext *scriptContext)
  4688. {
  4689. // JavascriptFunction and !HostDispatch
  4690. if (JavascriptOperators::GetTypeId(instance) == TypeIds_Function)
  4691. {
  4692. FunctionProxy *bod = ((JavascriptFunction *)instance)->GetFunctionProxy();
  4693. if (bod != nullptr)
  4694. {
  4695. return bod->GetDirectEntryPoint(bod->GetDefaultEntryPointInfo()) != &Js::JavascriptFunction::EntryApply;
  4696. }
  4697. else
  4698. {
  4699. FunctionInfo* info = ((JavascriptFunction *)instance)->GetFunctionInfo();
  4700. if (info != nullptr)
  4701. {
  4702. return &Js::JavascriptFunction::EntryApply != info->GetOriginalEntryPoint();
  4703. }
  4704. else
  4705. {
  4706. return true;
  4707. }
  4708. }
  4709. }
  4710. return true;
  4711. }
  4712. BOOL JavascriptOperators::OP_BrHasSideEffects(int se, ScriptContext* scriptContext)
  4713. {
  4714. return (scriptContext->optimizationOverrides.GetSideEffects() & se) != SideEffects_None;
  4715. }
  4716. BOOL JavascriptOperators::OP_BrNotHasSideEffects(int se, ScriptContext* scriptContext)
  4717. {
  4718. return (scriptContext->optimizationOverrides.GetSideEffects() & se) == SideEffects_None;
  4719. }
  4720. // returns NULL if there is no more elements to enumerate.
  4721. Var JavascriptOperators::OP_BrOnEmpty(ForInObjectEnumerator * aEnumerator)
  4722. {
  4723. PropertyId id;
  4724. return aEnumerator->MoveAndGetNext(id);
  4725. }
  4726. ForInObjectEnumerator * JavascriptOperators::OP_GetForInEnumerator(Var enumerable, ScriptContext* scriptContext)
  4727. {
  4728. RecyclableObject* enumerableObject;
  4729. bool isCrossSite;
  4730. #if ENABLE_COPYONACCESS_ARRAY
  4731. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(enumerable);
  4732. #endif
  4733. if (GetPropertyObject(enumerable, scriptContext, &enumerableObject))
  4734. {
  4735. isCrossSite = enumerableObject->GetScriptContext() != scriptContext;
  4736. }
  4737. else
  4738. {
  4739. enumerableObject = nullptr;
  4740. isCrossSite = false;
  4741. }
  4742. if (!isCrossSite)
  4743. {
  4744. ForInObjectEnumerator * enumerator = scriptContext->GetLibrary()->GetAndClearForInEnumeratorCache();
  4745. if(enumerator != NULL)
  4746. {
  4747. enumerator->Initialize(enumerableObject, scriptContext);
  4748. return enumerator;
  4749. }
  4750. }
  4751. return RecyclerNew(scriptContext->GetRecycler(), ForInObjectEnumerator, enumerableObject, scriptContext);
  4752. }
  4753. void JavascriptOperators::OP_ReleaseForInEnumerator(ForInObjectEnumerator * enumerator, ScriptContext* scriptContext)
  4754. {
  4755. // Debugger SetNextStatement may skip OP_GetForInEnumerator and result in NULL ForInObjectEnumerator here. See Win8 391556
  4756. if (enumerator && enumerator->CanBeReused())
  4757. {
  4758. enumerator->Clear();
  4759. scriptContext->GetLibrary()->SetForInEnumeratorCache(enumerator);
  4760. }
  4761. }
  4762. Js::Var JavascriptOperators::OP_CmEq_A(Var a, Var b, ScriptContext* scriptContext)
  4763. {
  4764. return JavascriptBoolean::ToVar(JavascriptOperators::Equal(a, b, scriptContext), scriptContext);
  4765. }
  4766. Var JavascriptOperators::OP_CmNeq_A(Var a, Var b, ScriptContext* scriptContext)
  4767. {
  4768. return JavascriptBoolean::ToVar(JavascriptOperators::NotEqual(a,b,scriptContext), scriptContext);
  4769. }
  4770. Var JavascriptOperators::OP_CmSrEq_A(Var a, Var b, ScriptContext* scriptContext)
  4771. {
  4772. return JavascriptBoolean::ToVar(JavascriptOperators::StrictEqual(a, b, scriptContext), scriptContext);
  4773. }
  4774. Var JavascriptOperators::OP_CmSrEq_String(Var a, Var b, ScriptContext *scriptContext)
  4775. {
  4776. return JavascriptBoolean::ToVar(JavascriptOperators::StrictEqualString(a, b), scriptContext);
  4777. }
  4778. Var JavascriptOperators::OP_CmSrEq_EmptyString(Var a, ScriptContext *scriptContext)
  4779. {
  4780. return JavascriptBoolean::ToVar(JavascriptOperators::StrictEqualEmptyString(a), scriptContext);
  4781. }
  4782. Var JavascriptOperators::OP_CmSrNeq_A(Var a, Var b, ScriptContext* scriptContext)
  4783. {
  4784. return JavascriptBoolean::ToVar(JavascriptOperators::NotStrictEqual(a, b, scriptContext), scriptContext);
  4785. }
  4786. Var JavascriptOperators::OP_CmLt_A(Var a, Var b, ScriptContext* scriptContext)
  4787. {
  4788. return JavascriptBoolean::ToVar(JavascriptOperators::Less(a, b, scriptContext), scriptContext);
  4789. }
  4790. Var JavascriptOperators::OP_CmLe_A(Var a, Var b, ScriptContext* scriptContext)
  4791. {
  4792. return JavascriptBoolean::ToVar(JavascriptOperators::LessEqual(a, b, scriptContext), scriptContext);
  4793. }
  4794. Var JavascriptOperators::OP_CmGt_A(Var a, Var b, ScriptContext* scriptContext)
  4795. {
  4796. return JavascriptBoolean::ToVar(JavascriptOperators::Greater(a, b, scriptContext), scriptContext);
  4797. }
  4798. Var JavascriptOperators::OP_CmGe_A(Var a, Var b, ScriptContext* scriptContext)
  4799. {
  4800. return JavascriptBoolean::ToVar(JavascriptOperators::GreaterEqual(a, b, scriptContext), scriptContext);
  4801. }
  4802. DetachedStateBase* JavascriptOperators::DetachVarAndGetState(Var var)
  4803. {
  4804. switch (GetTypeId(var))
  4805. {
  4806. case TypeIds_ArrayBuffer:
  4807. return Js::ArrayBuffer::FromVar(var)->DetachAndGetState();
  4808. default:
  4809. if (!Js::RecyclableObject::FromVar(var)->IsExternal())
  4810. {
  4811. AssertMsg(false, "We should explicitly have a case statement for each non-external object that can be detached.");
  4812. }
  4813. return nullptr;
  4814. }
  4815. }
  4816. bool JavascriptOperators::IsObjectDetached(Var var)
  4817. {
  4818. switch (GetTypeId(var))
  4819. {
  4820. case TypeIds_ArrayBuffer:
  4821. return Js::ArrayBuffer::FromVar(var)->IsDetached();
  4822. default:
  4823. return false;
  4824. }
  4825. }
  4826. Var JavascriptOperators::NewVarFromDetachedState(DetachedStateBase* state, JavascriptLibrary *library)
  4827. {
  4828. switch (state->GetTypeId())
  4829. {
  4830. case TypeIds_ArrayBuffer:
  4831. return Js::ArrayBuffer::NewFromDetachedState(state, library);
  4832. break;
  4833. default:
  4834. AssertMsg(false, "We should explicitly have a case statement for each object which has detached state.");
  4835. return nullptr;
  4836. }
  4837. }
  4838. DynamicType *
  4839. JavascriptOperators::EnsureObjectLiteralType(ScriptContext* scriptContext, const Js::PropertyIdArray *propIds, DynamicType ** literalType)
  4840. {
  4841. DynamicType * newType = *literalType;
  4842. if (newType != nullptr)
  4843. {
  4844. if (!newType->GetIsShared())
  4845. {
  4846. newType->ShareType();
  4847. }
  4848. }
  4849. else
  4850. {
  4851. DynamicType* objectType =
  4852. FunctionBody::DoObjectHeaderInliningForObjectLiteral(propIds, scriptContext)
  4853. ? scriptContext->GetLibrary()->GetObjectHeaderInlinedLiteralType((uint16)propIds->count)
  4854. : scriptContext->GetLibrary()->GetObjectLiteralType(
  4855. static_cast<PropertyIndex>(
  4856. min(propIds->count, static_cast<uint32>(MaxPreInitializedObjectTypeInlineSlotCount))));
  4857. newType = PathTypeHandlerBase::CreateTypeForNewScObject(scriptContext, objectType, propIds, false);
  4858. *literalType = newType;
  4859. }
  4860. Assert(GetLiteralInlineSlotCapacity(propIds, scriptContext) == newType->GetTypeHandler()->GetInlineSlotCapacity());
  4861. Assert(newType->GetTypeHandler()->GetSlotCapacity() >= 0);
  4862. Assert(GetLiteralSlotCapacity(propIds, scriptContext) == (uint)newType->GetTypeHandler()->GetSlotCapacity());
  4863. return newType;
  4864. }
  4865. Var JavascriptOperators::NewScObjectLiteral(ScriptContext* scriptContext, const Js::PropertyIdArray *propIds, DynamicType ** literalType)
  4866. {
  4867. Assert(propIds->count != 0);
  4868. Assert(!propIds->hadDuplicates); // duplicates are removed by parser
  4869. #ifdef PROFILE_OBJECT_LITERALS
  4870. // Empty objects not counted in the object literal counts
  4871. scriptContext->objectLiteralInstanceCount++;
  4872. if (propIds->count > scriptContext->objectLiteralMaxLength)
  4873. {
  4874. scriptContext->objectLiteralMaxLength = propIds->count;
  4875. }
  4876. #endif
  4877. DynamicType* newType = EnsureObjectLiteralType(scriptContext, propIds, literalType);
  4878. DynamicObject* instance = DynamicObject::New(scriptContext->GetRecycler(), newType);
  4879. if (!newType->GetIsShared())
  4880. {
  4881. newType->GetTypeHandler()->SetSingletonInstanceIfNeeded(instance);
  4882. }
  4883. #ifdef PROFILE_OBJECT_LITERALS
  4884. else
  4885. {
  4886. scriptContext->objectLiteralCacheCount++;
  4887. }
  4888. #endif
  4889. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(instance));
  4890. // can't auto-proxy here as object literal is not exactly "new" object and cannot be intercepted as proxy.
  4891. return instance;
  4892. }
  4893. uint JavascriptOperators::GetLiteralSlotCapacity(Js::PropertyIdArray const * propIds, ScriptContext *const scriptContext)
  4894. {
  4895. const uint inlineSlotCapacity = GetLiteralInlineSlotCapacity(propIds, scriptContext);
  4896. return DynamicTypeHandler::RoundUpSlotCapacity(propIds->count, static_cast<PropertyIndex>(inlineSlotCapacity));
  4897. }
  4898. uint JavascriptOperators::GetLiteralInlineSlotCapacity(
  4899. Js::PropertyIdArray const * propIds,
  4900. ScriptContext *const scriptContext)
  4901. {
  4902. if (propIds->hadDuplicates)
  4903. {
  4904. return 0;
  4905. }
  4906. return
  4907. FunctionBody::DoObjectHeaderInliningForObjectLiteral(propIds, scriptContext)
  4908. ? DynamicTypeHandler::RoundUpObjectHeaderInlinedInlineSlotCapacity(static_cast<PropertyIndex>(propIds->count))
  4909. : DynamicTypeHandler::RoundUpInlineSlotCapacity(
  4910. static_cast<PropertyIndex>(
  4911. min(propIds->count, static_cast<uint32>(MaxPreInitializedObjectTypeInlineSlotCount))));
  4912. }
  4913. Var JavascriptOperators::OP_InitCachedScope(Var varFunc, const Js::PropertyIdArray *propIds, DynamicType ** literalType, bool formalsAreLetDecls, ScriptContext *scriptContext)
  4914. {
  4915. ScriptFunction *func = JavascriptGeneratorFunction::Is(varFunc) || JavascriptAsyncFunction::Is(varFunc) ?
  4916. JavascriptGeneratorFunction::FromVar(varFunc)->GetGeneratorVirtualScriptFunction() :
  4917. ScriptFunction::FromVar(varFunc);
  4918. #ifdef PROFILE_OBJECT_LITERALS
  4919. // Empty objects not counted in the object literal counts
  4920. scriptContext->objectLiteralInstanceCount++;
  4921. if (propIds->count > scriptContext->objectLiteralMaxLength)
  4922. {
  4923. scriptContext->objectLiteralMaxLength = propIds->count;
  4924. }
  4925. #endif
  4926. PropertyId cachedFuncCount = ActivationObjectEx::GetCachedFuncCount(propIds);
  4927. PropertyId firstFuncSlot = ActivationObjectEx::GetFirstFuncSlot(propIds);
  4928. PropertyId firstVarSlot = ActivationObjectEx::GetFirstVarSlot(propIds);
  4929. PropertyId lastFuncSlot = Constants::NoProperty;
  4930. if (firstFuncSlot != Constants::NoProperty)
  4931. {
  4932. if (firstVarSlot == Constants::NoProperty)
  4933. {
  4934. lastFuncSlot = propIds->count - 1;
  4935. }
  4936. else
  4937. {
  4938. lastFuncSlot = firstVarSlot - 1;
  4939. }
  4940. }
  4941. DynamicType *type = *literalType;
  4942. if (type != nullptr)
  4943. {
  4944. #ifdef PROFILE_OBJECT_LITERALS
  4945. scriptContext->objectLiteralCacheCount++;
  4946. #endif
  4947. }
  4948. else
  4949. {
  4950. type = scriptContext->GetLibrary()->GetActivationObjectType();
  4951. if (formalsAreLetDecls)
  4952. {
  4953. uint formalsSlotLimit = (firstFuncSlot != Constants::NoProperty) ? (uint)firstFuncSlot :
  4954. (firstVarSlot != Constants::NoProperty) ? (uint)firstVarSlot :
  4955. propIds->count;
  4956. type = PathTypeHandlerBase::CreateNewScopeObject(scriptContext, type, propIds, PropertyLet, formalsSlotLimit);
  4957. }
  4958. else
  4959. {
  4960. type = PathTypeHandlerBase::CreateNewScopeObject(scriptContext, type, propIds);
  4961. }
  4962. *literalType = type;
  4963. }
  4964. Var undef = scriptContext->GetLibrary()->GetUndefined();
  4965. ActivationObjectEx *scopeObjEx = func->GetCachedScope();
  4966. if (scopeObjEx && scopeObjEx->IsCommitted())
  4967. {
  4968. scopeObjEx->ReplaceType(type);
  4969. scopeObjEx->SetCommit(false);
  4970. #if DBG
  4971. for (uint i = firstVarSlot; i < propIds->count; i++)
  4972. {
  4973. AssertMsg(scopeObjEx->GetSlot(i) == undef, "Var attached to cached scope");
  4974. }
  4975. #endif
  4976. }
  4977. else
  4978. {
  4979. ActivationObjectEx *tmp = RecyclerNewPlus(scriptContext->GetRecycler(), (cachedFuncCount == 0 ? 0 : cachedFuncCount - 1) * sizeof(FuncCacheEntry), ActivationObjectEx, type, func, cachedFuncCount, firstFuncSlot, lastFuncSlot);
  4980. if (!scopeObjEx)
  4981. {
  4982. func->SetCachedScope(tmp);
  4983. }
  4984. scopeObjEx = tmp;
  4985. for (uint i = firstVarSlot; i < propIds->count; i++)
  4986. {
  4987. scopeObjEx->SetSlot(SetSlotArguments(propIds->elements[i], i, undef));
  4988. }
  4989. }
  4990. return scopeObjEx;
  4991. }
  4992. void JavascriptOperators::OP_InvalidateCachedScope(void* varEnv, int32 envIndex)
  4993. {
  4994. FrameDisplay *disp = (FrameDisplay*)varEnv;
  4995. RecyclableObject *objScope = RecyclableObject::FromVar(disp->GetItem(envIndex));
  4996. objScope->InvalidateCachedScope();
  4997. }
  4998. void JavascriptOperators::OP_InitCachedFuncs(Var varScope, FrameDisplay *pDisplay, const FuncInfoArray *info, ScriptContext *scriptContext)
  4999. {
  5000. ActivationObjectEx *scopeObj = (ActivationObjectEx*)ActivationObjectEx::FromVar(varScope);
  5001. Assert(scopeObj->GetTypeHandler()->GetInlineSlotCapacity() == 0);
  5002. uint funcCount = info->count;
  5003. if (funcCount == 0)
  5004. {
  5005. // Degenerate case: no nested funcs at all
  5006. return;
  5007. }
  5008. if (scopeObj->HasCachedFuncs())
  5009. {
  5010. for (uint i = 0; i < funcCount; i++)
  5011. {
  5012. const FuncCacheEntry *entry = scopeObj->GetFuncCacheEntry(i);
  5013. ScriptFunction *func = entry->func;
  5014. FunctionProxy * proxy = func->GetFunctionProxy();
  5015. if (proxy != proxy->GetFunctionProxy())
  5016. {
  5017. // The FunctionProxy has changed since the object was cached, e.g., due to execution
  5018. // of a deferred function through a different object.
  5019. proxy = proxy->GetFunctionProxy();
  5020. func->SetFunctionInfo(proxy);
  5021. }
  5022. // Reset the function's type to the default type with no properties
  5023. // Use the cached type on the function proxy rather than the type in the func cache entry
  5024. // CONSIDER: Stop caching the function types in the scope object
  5025. func->ReplaceType(proxy->EnsureDeferredPrototypeType());
  5026. func->ResetConstructorCacheToDefault();
  5027. uint scopeSlot = info->elements[i].scopeSlot;
  5028. if (scopeSlot != Constants::NoProperty)
  5029. {
  5030. // CONSIDER: Store property IDs in FuncInfoArray in debug builds so we can properly assert in SetAuxSlot
  5031. scopeObj->SetAuxSlot(SetSlotArguments(Constants::NoProperty, scopeSlot, entry->func));
  5032. }
  5033. }
  5034. return;
  5035. }
  5036. // No cached functions, so create them and cache them.
  5037. JavascriptFunction *funcParent = scopeObj->GetParentFunc();
  5038. for (uint i = 0; i < funcCount; i++)
  5039. {
  5040. const FuncInfoEntry *entry = &info->elements[i];
  5041. uint nestedIndex = entry->nestedIndex;
  5042. uint scopeSlot = entry->scopeSlot;
  5043. FunctionProxy * proxy = funcParent->GetFunctionBody()->GetNestedFunc(nestedIndex);
  5044. ScriptFunction *func = scriptContext->GetLibrary()->CreateScriptFunction(proxy);
  5045. func->SetEnvironment(pDisplay);
  5046. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_FUNCTION(func, EtwTrace::GetFunctionId(proxy)));
  5047. scopeObj->SetCachedFunc(i, func);
  5048. if (scopeSlot != Constants::NoProperty)
  5049. {
  5050. // CONSIDER: Store property IDs in FuncInfoArray in debug builds so we can properly assert in SetAuxSlot
  5051. scopeObj->SetAuxSlot(SetSlotArguments(Constants::NoProperty, scopeSlot, func));
  5052. }
  5053. }
  5054. }
  5055. Var JavascriptOperators::AddVarsToArraySegment(SparseArraySegment<Var> * segment, const Js::VarArray *vars)
  5056. {
  5057. uint32 count = vars->count;
  5058. Assert(segment->left == 0);
  5059. Assert(count <= segment->size);
  5060. if(count > segment->length)
  5061. {
  5062. segment->length = count;
  5063. }
  5064. js_memcpy_s(segment->elements, sizeof(Var) * segment->length, vars->elements, sizeof(Var) * count);
  5065. return segment;
  5066. }
  5067. void JavascriptOperators::AddIntsToArraySegment(SparseArraySegment<int32> * segment, const Js::AuxArray<int32> *ints)
  5068. {
  5069. uint32 count = ints->count;
  5070. Assert(segment->left == 0);
  5071. Assert(count <= segment->size);
  5072. if(count > segment->length)
  5073. {
  5074. segment->length = count;
  5075. }
  5076. js_memcpy_s(segment->elements, sizeof(int32) * segment->length, ints->elements, sizeof(int32) * count);
  5077. }
  5078. void JavascriptOperators::AddFloatsToArraySegment(SparseArraySegment<double> * segment, const Js::AuxArray<double> *doubles)
  5079. {
  5080. uint32 count = doubles->count;
  5081. Assert(segment->left == 0);
  5082. Assert(count <= segment->size);
  5083. if(count > segment->length)
  5084. {
  5085. segment->length = count;
  5086. }
  5087. js_memcpy_s(segment->elements, sizeof(double) * segment->length, doubles->elements, sizeof(double) * count);
  5088. }
  5089. RecyclableObject * JavascriptOperators::GetPrototypeObject(RecyclableObject * constructorFunction, ScriptContext * scriptContext)
  5090. {
  5091. Var prototypeProperty = JavascriptOperators::GetProperty(constructorFunction, PropertyIds::prototype, scriptContext);
  5092. RecyclableObject* prototypeObject;
  5093. PrototypeObject(prototypeProperty, constructorFunction, scriptContext, &prototypeObject);
  5094. return prototypeObject;
  5095. }
  5096. RecyclableObject * JavascriptOperators::GetPrototypeObjectForConstructorCache(RecyclableObject * constructor, ScriptContext* requestContext, bool& canBeCached)
  5097. {
  5098. PropertyValueInfo info;
  5099. Var prototypeValue;
  5100. RecyclableObject* prototypeObject;
  5101. canBeCached = false;
  5102. // Do a local property lookup. Since a function's prototype property is a non-configurable data property, we don't need to worry
  5103. // about the prototype being an accessor property, whose getter returns different values every time it's called.
  5104. if (constructor->GetProperty(constructor, PropertyIds::prototype, &prototypeValue, &info, requestContext))
  5105. {
  5106. if (!JavascriptOperators::PrototypeObject(prototypeValue, constructor, requestContext, &prototypeObject))
  5107. {
  5108. // The value returned by the property lookup is not a valid prototype object, default to object prototype.
  5109. Assert(prototypeObject == constructor->GetLibrary()->GetObjectPrototype());
  5110. }
  5111. // For these scenarios, we do not want to populate the cache.
  5112. if (constructor->GetScriptContext() != requestContext || info.GetInstance() != constructor)
  5113. {
  5114. return prototypeObject;
  5115. }
  5116. }
  5117. else
  5118. {
  5119. // It's ok to cache Object.prototype, because Object.prototype cannot be overwritten.
  5120. prototypeObject = constructor->GetLibrary()->GetObjectPrototype();
  5121. }
  5122. canBeCached = true;
  5123. return prototypeObject;
  5124. }
  5125. bool JavascriptOperators::PrototypeObject(Var prototypeProperty, RecyclableObject * constructorFunction, ScriptContext * scriptContext, RecyclableObject** prototypeObject)
  5126. {
  5127. TypeId prototypeType = JavascriptOperators::GetTypeId(prototypeProperty);
  5128. if (JavascriptOperators::IsObjectType(prototypeType))
  5129. {
  5130. *prototypeObject = RecyclableObject::FromVar(prototypeProperty);
  5131. return true;
  5132. }
  5133. *prototypeObject = constructorFunction->GetLibrary()->GetObjectPrototype();
  5134. return false;
  5135. }
  5136. FunctionInfo* JavascriptOperators::GetConstructorFunctionInfo(Var instance, ScriptContext * scriptContext)
  5137. {
  5138. TypeId typeId = JavascriptOperators::GetTypeId(instance);
  5139. if (typeId == TypeIds_Function)
  5140. {
  5141. JavascriptFunction * function = JavascriptFunction::FromVar(instance);
  5142. return function->GetFunctionInfo();
  5143. }
  5144. if (typeId != TypeIds_HostDispatch && typeId != TypeIds_Proxy)
  5145. {
  5146. if (typeId == TypeIds_Null)
  5147. {
  5148. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  5149. }
  5150. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  5151. }
  5152. return nullptr;
  5153. }
  5154. Var JavascriptOperators::NewJavascriptObjectNoArg(ScriptContext* requestContext)
  5155. {
  5156. DynamicObject * newObject = requestContext->GetLibrary()->CreateObject(true);
  5157. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newObject));
  5158. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5159. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5160. {
  5161. newObject = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(newObject));
  5162. }
  5163. #endif
  5164. return newObject;
  5165. }
  5166. Var JavascriptOperators::NewJavascriptArrayNoArg(ScriptContext* requestContext)
  5167. {
  5168. JavascriptArray * newArray = requestContext->GetLibrary()->CreateArray();
  5169. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newArray));
  5170. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5171. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5172. {
  5173. newArray = static_cast<JavascriptArray*>(JavascriptProxy::AutoProxyWrapper(newArray));
  5174. }
  5175. #endif
  5176. return newArray;
  5177. }
  5178. Var JavascriptOperators::NewScObjectNoArgNoCtorFull(Var instance, ScriptContext* requestContext)
  5179. {
  5180. return NewScObjectNoArgNoCtorCommon(instance, requestContext, true);
  5181. }
  5182. Var JavascriptOperators::NewScObjectNoArgNoCtor(Var instance, ScriptContext* requestContext)
  5183. {
  5184. return NewScObjectNoArgNoCtorCommon(instance, requestContext, false);
  5185. }
  5186. Var JavascriptOperators::NewScObjectNoArgNoCtorCommon(Var instance, ScriptContext* requestContext, bool isBaseClassConstructorNewScObject)
  5187. {
  5188. RecyclableObject * object = RecyclableObject::FromVar(instance);
  5189. FunctionInfo* functionInfo = JavascriptOperators::GetConstructorFunctionInfo(instance, requestContext);
  5190. Assert(functionInfo != &JavascriptObject::EntryInfo::NewInstance); // built-ins are not inlined
  5191. Assert(functionInfo != &JavascriptArray::EntryInfo::NewInstance); // built-ins are not inlined
  5192. return functionInfo != nullptr ?
  5193. JavascriptOperators::NewScObjectCommon(object, functionInfo, requestContext, isBaseClassConstructorNewScObject) :
  5194. JavascriptOperators::NewScObjectHostDispatchOrProxy(object, requestContext);
  5195. }
  5196. Var JavascriptOperators::NewScObjectNoArg(Var instance, ScriptContext * requestContext)
  5197. {
  5198. if (JavascriptProxy::Is(instance))
  5199. {
  5200. Arguments args(CallInfo(CallFlags_New, 1), &instance);
  5201. JavascriptProxy* proxy = JavascriptProxy::FromVar(instance);
  5202. return proxy->ConstructorTrap(args, requestContext, 0);
  5203. }
  5204. FunctionInfo* functionInfo = JavascriptOperators::GetConstructorFunctionInfo(instance, requestContext);
  5205. RecyclableObject * object = RecyclableObject::FromVar(instance);
  5206. if (functionInfo == &JavascriptObject::EntryInfo::NewInstance)
  5207. {
  5208. // Fast path for new Object()
  5209. Assert((functionInfo->GetAttributes() & FunctionInfo::ErrorOnNew) == 0);
  5210. JavascriptLibrary* library = object->GetLibrary();
  5211. DynamicObject * newObject = library->CreateObject(true);
  5212. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newObject));
  5213. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5214. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5215. {
  5216. newObject = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(newObject));
  5217. }
  5218. #endif
  5219. #if DBG
  5220. DynamicType* newObjectType = newObject->GetDynamicType();
  5221. Assert(newObjectType->GetIsShared());
  5222. JavascriptFunction* constructor = JavascriptFunction::FromVar(instance);
  5223. Assert(!constructor->GetConstructorCache()->NeedsUpdateAfterCtor());
  5224. #endif
  5225. ScriptContext * scriptContext = library->GetScriptContext();
  5226. if (scriptContext != requestContext)
  5227. {
  5228. CrossSite::MarshalDynamicObjectAndPrototype(requestContext, newObject);
  5229. }
  5230. return newObject;
  5231. }
  5232. else if (functionInfo == &JavascriptArray::EntryInfo::NewInstance)
  5233. {
  5234. Assert((functionInfo->GetAttributes() & FunctionInfo::ErrorOnNew) == 0);
  5235. JavascriptLibrary* library = object->GetLibrary();
  5236. JavascriptArray * newArray = library->CreateArray();
  5237. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newArray));
  5238. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5239. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5240. {
  5241. newArray = static_cast<JavascriptArray*>(JavascriptProxy::AutoProxyWrapper(newArray));
  5242. }
  5243. #endif
  5244. #if DBG
  5245. DynamicType* newArrayType = newArray->GetDynamicType();
  5246. Assert(newArrayType->GetIsShared());
  5247. JavascriptFunction* constructor = JavascriptFunction::FromVar(instance);
  5248. Assert(!constructor->GetConstructorCache()->NeedsUpdateAfterCtor());
  5249. #endif
  5250. ScriptContext * scriptContext = library->GetScriptContext();
  5251. if (scriptContext != requestContext)
  5252. {
  5253. CrossSite::MarshalDynamicObjectAndPrototype(requestContext, newArray);
  5254. }
  5255. return newArray;
  5256. }
  5257. Var newObject = functionInfo != nullptr ?
  5258. JavascriptOperators::NewScObjectCommon(object, functionInfo, requestContext) :
  5259. JavascriptOperators::NewScObjectHostDispatchOrProxy(object, requestContext);
  5260. Var returnVar = CALL_FUNCTION(object, CallInfo(CallFlags_New, 1), newObject);
  5261. if (JavascriptOperators::IsObject(returnVar))
  5262. {
  5263. newObject = returnVar;
  5264. }
  5265. ConstructorCache * constructorCache = nullptr;
  5266. if (JavascriptFunction::Is(instance))
  5267. {
  5268. constructorCache = JavascriptFunction::FromVar(instance)->GetConstructorCache();
  5269. }
  5270. if (constructorCache != nullptr && constructorCache->NeedsUpdateAfterCtor())
  5271. {
  5272. JavascriptOperators::UpdateNewScObjectCache(object, newObject, requestContext);
  5273. }
  5274. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5275. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5276. {
  5277. newObject = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(newObject));
  5278. // this might come from a different scriptcontext.
  5279. newObject = CrossSite::MarshalVar(requestContext, newObject);
  5280. }
  5281. #endif
  5282. return newObject;
  5283. }
  5284. Var JavascriptOperators::NewScObjectNoCtorFull(Var instance, ScriptContext* requestContext)
  5285. {
  5286. return NewScObjectNoCtorCommon(instance, requestContext, true);
  5287. }
  5288. Var JavascriptOperators::NewScObjectNoCtor(Var instance, ScriptContext * requestContext)
  5289. {
  5290. return NewScObjectNoCtorCommon(instance, requestContext, false);
  5291. }
  5292. Var JavascriptOperators::NewScObjectNoCtorCommon(Var instance, ScriptContext* requestContext, bool isBaseClassConstructorNewScObject)
  5293. {
  5294. FunctionInfo* functionInfo = JavascriptOperators::GetConstructorFunctionInfo(instance, requestContext);
  5295. if (functionInfo)
  5296. {
  5297. return JavascriptOperators::NewScObjectCommon(RecyclableObject::FromVar(instance), functionInfo, requestContext, isBaseClassConstructorNewScObject);
  5298. }
  5299. else
  5300. {
  5301. return JavascriptOperators::NewScObjectHostDispatchOrProxy(RecyclableObject::FromVar(instance), requestContext);
  5302. }
  5303. }
  5304. Var JavascriptOperators::NewScObjectHostDispatchOrProxy(RecyclableObject * function, ScriptContext * requestContext)
  5305. {
  5306. ScriptContext* functionScriptContext = function->GetScriptContext();
  5307. if (JavascriptProxy::Is(function))
  5308. {
  5309. // We can still call into NewScObjectNoCtor variations in JIT code for performance; however for proxy we don't
  5310. // really need the new object as the trap will handle the "this" pointer separately. pass back nullptr to ensure
  5311. // failure in invalid case.
  5312. return nullptr;
  5313. }
  5314. RecyclableObject * prototype = JavascriptOperators::GetPrototypeObject(function, functionScriptContext);
  5315. prototype = RecyclableObject::FromVar(CrossSite::MarshalVar(requestContext, prototype));
  5316. Var object = requestContext->GetLibrary()->CreateObject(prototype);
  5317. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object));
  5318. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5319. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5320. {
  5321. object = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(object));
  5322. }
  5323. #endif
  5324. return object;
  5325. }
  5326. Var JavascriptOperators::NewScObjectCommon(RecyclableObject * function, FunctionInfo* functionInfo, ScriptContext * requestContext, bool isBaseClassConstructorNewScObject)
  5327. {
  5328. // CONSIDER: Allow for the cache to be repopulated if the type got collected, and a new one got populated with
  5329. // the same number of inlined slots. This requires that the JIT-ed code actually load the type from the cache
  5330. // (instead of hard-coding it), but it can (and must) keep the hard-coded number of inline slots.
  5331. // CONSIDER: Consider also not pinning the type in the cache. This can be done by using a registration based
  5332. // weak reference (we need to control the memory address), which we don't yet have, or by allocating the cache from
  5333. // the inline cache arena to allow it to be zeroed, but retain a recycler-allocated portion to hold on to the size of
  5334. // inlined slots.
  5335. JavascriptFunction* constructor = JavascriptFunction::FromVar(function);
  5336. if (functionInfo->IsClassConstructor() && !isBaseClassConstructorNewScObject)
  5337. {
  5338. // If we are calling new on a class constructor, the contract is that we pass new.target as the 'this' argument.
  5339. // function is the constructor on which we called new - which is new.target.
  5340. // If we are trying to construct the object for a base class constructor as part of a super call, we should not
  5341. // store new.target in the 'this' argument.
  5342. return function;
  5343. }
  5344. ConstructorCache* constructorCache = constructor->GetConstructorCache();
  5345. AssertMsg(constructorCache->GetScriptContext() == nullptr || constructorCache->GetScriptContext() == constructor->GetScriptContext(),
  5346. "Why did we populate a constructor cache with a mismatched script context?");
  5347. Assert(constructorCache != nullptr);
  5348. DynamicType* type = constructorCache->GetGuardValueAsType();
  5349. if (type != nullptr && constructorCache->GetScriptContext() == requestContext)
  5350. {
  5351. #if DBG
  5352. bool cachedProtoCanBeCached;
  5353. Assert(type->GetPrototype() == JavascriptOperators::GetPrototypeObjectForConstructorCache(constructor, requestContext, cachedProtoCanBeCached));
  5354. Assert(cachedProtoCanBeCached);
  5355. Assert(type->GetIsShared());
  5356. #endif
  5357. #if DBG_DUMP
  5358. TraceUseConstructorCache(constructorCache, constructor, true);
  5359. #endif
  5360. Var object = DynamicObject::New(requestContext->GetRecycler(), type);
  5361. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object));
  5362. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5363. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5364. {
  5365. object = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(object));
  5366. }
  5367. #endif
  5368. return object;
  5369. }
  5370. if (constructorCache->SkipDefaultNewObject())
  5371. {
  5372. Assert(!constructorCache->NeedsUpdateAfterCtor());
  5373. #if DBG_DUMP
  5374. TraceUseConstructorCache(constructorCache, constructor, true);
  5375. #endif
  5376. if (isBaseClassConstructorNewScObject)
  5377. {
  5378. return JavascriptOperators::CreateFromConstructor(function, requestContext);
  5379. }
  5380. return nullptr;
  5381. }
  5382. #if DBG_DUMP
  5383. TraceUseConstructorCache(constructorCache, constructor, false);
  5384. #endif
  5385. ScriptContext* constructorScriptContext = function->GetScriptContext();
  5386. Assert(!constructorScriptContext->GetThreadContext()->IsDisableImplicitException());
  5387. // we shouldn't try to call the constructor if it's closed already.
  5388. constructorScriptContext->VerifyAlive(TRUE, requestContext);
  5389. FunctionInfo::Attributes attributes = functionInfo->GetAttributes();
  5390. if (attributes & FunctionInfo::ErrorOnNew)
  5391. {
  5392. JavascriptError::ThrowTypeError(requestContext, JSERR_ErrorOnNew);
  5393. }
  5394. // Slow path
  5395. FunctionProxy * ctorProxy = constructor->GetFunctionProxy();
  5396. FunctionBody * functionBody = ctorProxy != nullptr ? ctorProxy->EnsureDeserialized()->Parse() : nullptr;
  5397. if (attributes & FunctionInfo::SkipDefaultNewObject)
  5398. {
  5399. // The constructor doesn't use the default new object.
  5400. #pragma prefast(suppress:6236, "DevDiv bug 830883. False positive when PHASE_OFF is #defined as '(false)'.")
  5401. if (!PHASE_OFF1(ConstructorCachePhase) && (functionBody == nullptr || !PHASE_OFF(ConstructorCachePhase, functionBody)))
  5402. {
  5403. constructorCache = constructor->EnsureValidConstructorCache();
  5404. constructorCache->PopulateForSkipDefaultNewObject(constructorScriptContext);
  5405. #if DBG_DUMP
  5406. if ((functionBody != nullptr && PHASE_TRACE(Js::ConstructorCachePhase, functionBody)) || (functionBody == nullptr && PHASE_TRACE1(Js::ConstructorCachePhase)))
  5407. {
  5408. const char16* ctorName = functionBody != nullptr ? functionBody->GetDisplayName() : _u("<unknown>");
  5409. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5410. Output::Print(_u("CtorCache: populated cache (0x%p) for ctor %s (%s): "), constructorCache, ctorName,
  5411. functionBody ? functionBody->GetDebugNumberSet(debugStringBuffer) : _u("(null)"));
  5412. constructorCache->Dump();
  5413. Output::Print(_u("\n"));
  5414. Output::Flush();
  5415. }
  5416. #endif
  5417. }
  5418. Assert(!constructorCache->NeedsUpdateAfterCtor());
  5419. return nullptr;
  5420. }
  5421. // CONSIDER: Create some form of PatchGetProtoObjForCtorCache, which actually caches the prototype object in the constructor cache.
  5422. // Make sure that it does NOT populate the guard field. On the slow path (the only path for cross-context calls) we can do a faster lookup
  5423. // after we fail the guard check. When invalidating the cache for proto change, make sure we zap the prototype field of the cache in
  5424. // addition to the guard value.
  5425. bool prototypeCanBeCached;
  5426. RecyclableObject* prototype = JavascriptOperators::GetPrototypeObjectForConstructorCache(function, constructorScriptContext, prototypeCanBeCached);
  5427. prototype = RecyclableObject::FromVar(CrossSite::MarshalVar(requestContext, prototype));
  5428. DynamicObject* newObject = requestContext->GetLibrary()->CreateObject(prototype, 8);
  5429. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(newObject));
  5430. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5431. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  5432. {
  5433. newObject = DynamicObject::FromVar(JavascriptProxy::AutoProxyWrapper(newObject));
  5434. }
  5435. #endif
  5436. Assert(newObject->GetTypeHandler()->GetPropertyCount() == 0);
  5437. if (prototypeCanBeCached && functionBody != nullptr && requestContext == constructorScriptContext &&
  5438. !Js::JavascriptProxy::Is(newObject) &&
  5439. !PHASE_OFF1(ConstructorCachePhase) && !PHASE_OFF(ConstructorCachePhase, functionBody))
  5440. {
  5441. DynamicType* newObjectType = newObject->GetDynamicType();
  5442. // Initial type (without any properties) should always be shared up-front. This allows us to populate the cache right away.
  5443. Assert(newObjectType->GetIsShared());
  5444. // Populate the cache here and set the updateAfterCtor flag. This way, if the ctor is called recursively the
  5445. // recursive calls will hit the cache and use the initial type. On the unwind path, we will update the cache
  5446. // after the innermost ctor and clear the flag. After subsequent ctors we won't attempt an update anymore.
  5447. // As long as the updateAfterCtor flag is set it is safe to update the cache, because it would not have been
  5448. // hard-coded in the JIT-ed code.
  5449. constructorCache = constructor->EnsureValidConstructorCache();
  5450. constructorCache->Populate(newObjectType, constructorScriptContext, functionBody->GetHasNoExplicitReturnValue(), true);
  5451. Assert(constructorCache->IsConsistent());
  5452. #if DBG_DUMP
  5453. if ((functionBody != nullptr && PHASE_TRACE(Js::ConstructorCachePhase, functionBody)) || (functionBody == nullptr && PHASE_TRACE1(Js::ConstructorCachePhase)))
  5454. {
  5455. const char16* ctorName = functionBody != nullptr ? functionBody->GetDisplayName() : _u("<unknown>");
  5456. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5457. Output::Print(_u("CtorCache: populated cache (0x%p) for ctor %s (%s): "), constructorCache, ctorName,
  5458. functionBody ? functionBody->GetDebugNumberSet(debugStringBuffer) : _u("(null)"));
  5459. constructorCache->Dump();
  5460. Output::Print(_u("\n"));
  5461. Output::Flush();
  5462. }
  5463. #endif
  5464. }
  5465. else
  5466. {
  5467. #if DBG_DUMP
  5468. if ((functionBody != nullptr && PHASE_TRACE(Js::ConstructorCachePhase, functionBody)) || (functionBody == nullptr && PHASE_TRACE1(Js::ConstructorCachePhase)))
  5469. {
  5470. const char16* ctorName = functionBody != nullptr ? functionBody->GetDisplayName() : _u("<unknown>");
  5471. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5472. Output::Print(_u("CtorCache: did not populate cache (0x%p) for ctor %s (%s), because %s: prototype = 0x%p, functionBody = 0x%p, ctor context = 0x%p, request context = 0x%p"),
  5473. constructorCache, ctorName, functionBody ? functionBody->GetDebugNumberSet(debugStringBuffer) : _u("(null)"),
  5474. !prototypeCanBeCached ? _u("prototype cannot be cached") :
  5475. functionBody == nullptr ? _u("function has no body") :
  5476. requestContext != constructorScriptContext ? _u("of cross-context call") : _u("constructor cache phase is off"),
  5477. prototype, functionBody, constructorScriptContext, requestContext);
  5478. Output::Print(_u("\n"));
  5479. Output::Flush();
  5480. }
  5481. #endif
  5482. }
  5483. return newObject;
  5484. }
  5485. void JavascriptOperators::UpdateNewScObjectCache(Var function, Var instance, ScriptContext* requestContext)
  5486. {
  5487. JavascriptFunction* constructor = JavascriptFunction::FromVar(function);
  5488. if(constructor->GetScriptContext() != requestContext)
  5489. {
  5490. // The cache is populated only when the constructor function's context is the same as the calling context. However,
  5491. // the cached type is not finalized yet and may not be until multiple calls to the constructor have been made (see
  5492. // flag ConstructorCallsRequiredToFinalizeCachedType). A subsequent call to the constructor may be made from a
  5493. // different context, so ignore those cross-context calls and wait for the constructor to be called from its own
  5494. // context again to finalize the cached type.
  5495. return;
  5496. }
  5497. // Review : What happens if the cache got invalidated between NewScObject and here?
  5498. // Should we allocate new? Should we mark it as polymorphic?
  5499. ConstructorCache* constructorCache = constructor->GetConstructorCache();
  5500. Assert(constructorCache->IsConsistent());
  5501. Assert(!ConstructorCache::IsDefault(constructorCache));
  5502. AssertMsg(constructorCache->GetScriptContext() == constructor->GetScriptContext(), "Why did we populate a constructor cache with a mismatched script context?");
  5503. AssertMsg(constructorCache->IsPopulated(), "Why are we updating a constructor cache that hasn't been populated?");
  5504. // The presence of the updateAfterCtor flag guarantees that this cache hasn't been used in JIT-ed fast path. Even, if the
  5505. // cache is invalidated, this flag is not changed.
  5506. AssertMsg(constructorCache->NeedsUpdateAfterCtor(), "Why are we updating a constructor cache that doesn't need to be updated?");
  5507. const bool finalizeCachedType =
  5508. constructorCache->CallCount() >= CONFIG_FLAG(ConstructorCallsRequiredToFinalizeCachedType);
  5509. if(!finalizeCachedType)
  5510. {
  5511. constructorCache->IncCallCount();
  5512. }
  5513. else
  5514. {
  5515. constructorCache->ClearUpdateAfterCtor();
  5516. }
  5517. FunctionBody* constructorBody = constructor->GetFunctionBody();
  5518. AssertMsg(constructorBody != nullptr, "Constructor function doesn't have a function body.");
  5519. Assert(RecyclableObject::Is(instance));
  5520. // The cache might have been invalidated between NewScObjectCommon and UpdateNewScObjectCache. This could occur, for example, if
  5521. // the constructor updates its own prototype property. If that happens we don't want to re-populate it here. A new cache will
  5522. // be created when the constructor is called again.
  5523. if (constructorCache->IsInvalidated())
  5524. {
  5525. #if DBG_DUMP
  5526. TraceUpdateConstructorCache(constructorCache, constructorBody, false, _u("because cache is invalidated"));
  5527. #endif
  5528. return;
  5529. }
  5530. Assert(constructorCache->GetGuardValueAsType() != nullptr);
  5531. if (DynamicType::Is(RecyclableObject::FromVar(instance)->GetTypeId()))
  5532. {
  5533. DynamicObject *object = DynamicObject::FromVar(instance);
  5534. DynamicType* type = object->GetDynamicType();
  5535. DynamicTypeHandler* typeHandler = type->GetTypeHandler();
  5536. if (constructorBody->GetHasOnlyThisStmts())
  5537. {
  5538. if (typeHandler->IsSharable())
  5539. {
  5540. #if DBG
  5541. bool cachedProtoCanBeCached;
  5542. Assert(type->GetPrototype() == JavascriptOperators::GetPrototypeObjectForConstructorCache(constructor, requestContext, cachedProtoCanBeCached));
  5543. Assert(cachedProtoCanBeCached);
  5544. Assert(type->GetScriptContext() == constructorCache->GetScriptContext());
  5545. Assert(type->GetPrototype() == constructorCache->GetType()->GetPrototype());
  5546. #endif
  5547. typeHandler->SetMayBecomeShared();
  5548. // CONSIDER: Remove only this for delayed type sharing.
  5549. type->ShareType();
  5550. #if ENABLE_PROFILE_INFO
  5551. DynamicProfileInfo* profileInfo = constructorBody->HasDynamicProfileInfo() ? constructorBody->GetAnyDynamicProfileInfo() : nullptr;
  5552. if ((profileInfo != nullptr && profileInfo->GetImplicitCallFlags() <= ImplicitCall_None) ||
  5553. CheckIfPrototypeChainHasOnlyWritableDataProperties(type->GetPrototype()))
  5554. {
  5555. Assert(typeHandler->GetPropertyCount() < Js::PropertyIndexRanges<PropertyIndex>::MaxValue);
  5556. for (PropertyIndex pi = 0; pi < typeHandler->GetPropertyCount(); pi++)
  5557. {
  5558. requestContext->RegisterConstructorCache(typeHandler->GetPropertyId(requestContext, pi), constructorCache);
  5559. }
  5560. Assert(constructorBody->GetUtf8SourceInfo()->GetIsLibraryCode() || !constructor->GetScriptContext()->IsScriptContextInDebugMode());
  5561. if (constructorCache->TryUpdateAfterConstructor(type, constructor->GetScriptContext()))
  5562. {
  5563. #if DBG_DUMP
  5564. TraceUpdateConstructorCache(constructorCache, constructorBody, true, _u(""));
  5565. #endif
  5566. }
  5567. else
  5568. {
  5569. #if DBG_DUMP
  5570. TraceUpdateConstructorCache(constructorCache, constructorBody, false, _u("because number of slots > MaxCachedSlotCount"));
  5571. #endif
  5572. }
  5573. }
  5574. #if DBG_DUMP
  5575. else
  5576. {
  5577. if (profileInfo &&
  5578. ((profileInfo->GetImplicitCallFlags() & ~(Js::ImplicitCall_External | Js::ImplicitCall_Accessor)) == 0) &&
  5579. profileInfo != nullptr && CheckIfPrototypeChainHasOnlyWritableDataProperties(type->GetPrototype()) &&
  5580. Js::Configuration::Global.flags.Trace.IsEnabled(Js::HostOptPhase))
  5581. {
  5582. const char16* ctorName = constructorBody->GetDisplayName();
  5583. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5584. Output::Print(_u("CtorCache: %s cache (0x%p) for ctor %s (#%u) did not update because external call"),
  5585. constructorCache, constructorBody, ctorName, constructorBody ? constructorBody->GetDebugNumberSet(debugStringBuffer) : _u("(null)"));
  5586. Output::Print(_u("\n"));
  5587. Output::Flush();
  5588. }
  5589. }
  5590. #endif
  5591. #endif
  5592. }
  5593. else
  5594. {
  5595. // Dynamic type created is not sharable.
  5596. // So in future don't try to check for "this assignment optimization".
  5597. constructorBody->SetHasOnlyThisStmts(false);
  5598. #if DBG_DUMP
  5599. TraceUpdateConstructorCache(constructorCache, constructorBody, false, _u("because final type is not shareable"));
  5600. #endif
  5601. }
  5602. }
  5603. else
  5604. {
  5605. #if DBG_DUMP
  5606. TraceUpdateConstructorCache(constructorCache, constructorBody, false, _u("because ctor has not only this statements"));
  5607. #endif
  5608. }
  5609. }
  5610. else
  5611. {
  5612. // Even though this constructor apparently returned something other than the default object we created,
  5613. // it still makes sense to cache the parameters of the default object, since we must create it every time, anyway.
  5614. #if DBG_DUMP
  5615. TraceUpdateConstructorCache(constructorCache, constructorBody, false, _u("because ctor return a non-object value"));
  5616. #endif
  5617. return;
  5618. }
  5619. // Whatever the constructor returned, if we're caching a type we want to be sure we shrink its inline slot capacity.
  5620. if (finalizeCachedType && constructorCache->IsEnabled())
  5621. {
  5622. DynamicType* cachedType = constructorCache->NeedsTypeUpdate() ? constructorCache->GetPendingType() : constructorCache->GetType();
  5623. DynamicTypeHandler* cachedTypeHandler = cachedType->GetTypeHandler();
  5624. // Consider: We could delay inline slot capacity shrinking until the second time this constructor is invoked. In some cases
  5625. // this might permit more properties to remain inlined if the objects grow after constructor. This would require flagging
  5626. // the cache as special (already possible) and forcing the shrinking during work item creation if we happen to JIT this
  5627. // constructor while the cache is in this special state.
  5628. if (cachedTypeHandler->GetInlineSlotCapacity())
  5629. {
  5630. #if DBG_DUMP
  5631. int inlineSlotCapacityBeforeShrink = cachedTypeHandler->GetInlineSlotCapacity();
  5632. #endif
  5633. // Note that after the cache has been updated and might have been used in the JIT-ed code, it is no longer legal to
  5634. // shrink the inline slot capacity of the type. That's because we allocate memory for a fixed number of inlined properties
  5635. // and if that number changed on the type, this update wouldn't get reflected in JIT-ed code and we would allocate objects
  5636. // of a wrong size. This could conceivably happen if the original object got collected, and with it some of the successor
  5637. // types also. If then another constructor has the same prototype and needs to populate its own cache, it would attempt to
  5638. // shrink inlined slots again. If all surviving type handlers have smaller inline slot capacity, we would shrink it further.
  5639. // To address this problem the type handler has a bit indicating its inline slots have been shrunk already. If that bit is
  5640. // set ShrinkSlotAndInlineSlotCapacity does nothing.
  5641. cachedTypeHandler->ShrinkSlotAndInlineSlotCapacity();
  5642. constructorCache->UpdateInlineSlotCount();
  5643. #if DBG_DUMP
  5644. Assert(inlineSlotCapacityBeforeShrink >= cachedTypeHandler->GetInlineSlotCapacity());
  5645. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::InlineSlotsPhase))
  5646. {
  5647. if (inlineSlotCapacityBeforeShrink != cachedTypeHandler->GetInlineSlotCapacity())
  5648. {
  5649. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5650. Output::Print(_u("Inline slot capacity shrunk: Function:%04s Before:%d After:%d\n"),
  5651. constructorBody->GetDebugNumberSet(debugStringBuffer), inlineSlotCapacityBeforeShrink, cachedTypeHandler->GetInlineSlotCapacity());
  5652. }
  5653. }
  5654. #endif
  5655. }
  5656. }
  5657. }
  5658. void JavascriptOperators::TraceUseConstructorCache(const ConstructorCache* ctorCache, const JavascriptFunction* ctor, bool isHit)
  5659. {
  5660. #if DBG_DUMP
  5661. // We are under debug, so we can incur the extra check here.
  5662. FunctionProxy* ctorBody = ctor->GetFunctionProxy();
  5663. if (ctorBody != nullptr && !ctorBody->GetScriptContext()->IsClosed())
  5664. {
  5665. ctorBody = ctorBody->EnsureDeserialized();
  5666. }
  5667. if ((ctorBody != nullptr && PHASE_TRACE(Js::ConstructorCachePhase, ctorBody)) || (ctorBody == nullptr && PHASE_TRACE1(Js::ConstructorCachePhase)))
  5668. {
  5669. const char16* ctorName = ctorBody != nullptr ? ctorBody->GetDisplayName() : _u("<unknown>");
  5670. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5671. Output::Print(_u("CtorCache: %s cache (0x%p) for ctor %s (%s): "), isHit ? _u("hit") : _u("missed"), ctorCache, ctorName,
  5672. ctorBody ? ctorBody->GetDebugNumberSet(debugStringBuffer) : _u("(null)"));
  5673. ctorCache->Dump();
  5674. Output::Print(_u("\n"));
  5675. Output::Flush();
  5676. }
  5677. #endif
  5678. }
  5679. void JavascriptOperators::TraceUpdateConstructorCache(const ConstructorCache* ctorCache, const FunctionBody* ctorBody, bool updated, const char16* reason)
  5680. {
  5681. #if DBG_DUMP
  5682. if (PHASE_TRACE(Js::ConstructorCachePhase, ctorBody))
  5683. {
  5684. const char16* ctorName = ctorBody->GetDisplayName();
  5685. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5686. Output::Print(_u("CtorCache: %s cache (0x%p) for ctor %s (%s)%s %s: "),
  5687. updated ? _u("updated") : _u("did not update"), ctorBody, ctorName,
  5688. ctorBody ? const_cast<Js::FunctionBody *>(ctorBody)->GetDebugNumberSet(debugStringBuffer) : _u("(null)"),
  5689. updated ? _u("") : _u(", because") , reason);
  5690. ctorCache->Dump();
  5691. Output::Print(_u("\n"));
  5692. Output::Flush();
  5693. }
  5694. #endif
  5695. }
  5696. Var JavascriptOperators::NewScObject(const Var callee, const Arguments args, ScriptContext *const scriptContext, const Js::AuxArray<uint32> *spreadIndices)
  5697. {
  5698. Assert(callee);
  5699. Assert(args.Info.Count != 0);
  5700. Assert(scriptContext);
  5701. // Always save and restore implicit call flags when calling out
  5702. // REVIEW: Can we avoid it if we don't collect dynamic profile info?
  5703. ThreadContext *const threadContext = scriptContext->GetThreadContext();
  5704. const ImplicitCallFlags savedImplicitCallFlags = threadContext->GetImplicitCallFlags();
  5705. const Var newVarInstance = JavascriptFunction::CallAsConstructor(callee, /* overridingNewTarget = */nullptr, args, scriptContext, spreadIndices);
  5706. threadContext->SetImplicitCallFlags(savedImplicitCallFlags);
  5707. return newVarInstance;
  5708. }
  5709. Js::GlobalObject * JavascriptOperators::OP_LdRoot(ScriptContext* scriptContext)
  5710. {
  5711. return scriptContext->GetGlobalObject();
  5712. }
  5713. Js::ModuleRoot * JavascriptOperators::GetModuleRoot(int moduleID, ScriptContext* scriptContext)
  5714. {
  5715. Assert(moduleID != kmodGlobal);
  5716. JavascriptLibrary* library = scriptContext->GetLibrary();
  5717. HostObjectBase *hostObject = library->GetGlobalObject()->GetHostObject();
  5718. if (hostObject)
  5719. {
  5720. Js::ModuleRoot * moduleRoot = hostObject->GetModuleRoot(moduleID);
  5721. Assert(!CrossSite::NeedMarshalVar(moduleRoot, scriptContext));
  5722. return moduleRoot;
  5723. }
  5724. HostScriptContext *hostScriptContext = scriptContext->GetHostScriptContext();
  5725. if (hostScriptContext)
  5726. {
  5727. Js::ModuleRoot * moduleRoot = hostScriptContext->GetModuleRoot(moduleID);
  5728. Assert(!CrossSite::NeedMarshalVar(moduleRoot, scriptContext));
  5729. return moduleRoot;
  5730. }
  5731. Assert(FALSE);
  5732. return nullptr;
  5733. }
  5734. Var JavascriptOperators::OP_LoadModuleRoot(int moduleID, ScriptContext* scriptContext)
  5735. {
  5736. Js::ModuleRoot * moduleRoot = GetModuleRoot(moduleID, scriptContext);
  5737. if (moduleRoot)
  5738. {
  5739. return moduleRoot;
  5740. }
  5741. Assert(false);
  5742. return scriptContext->GetLibrary()->GetUndefined();
  5743. }
  5744. Var JavascriptOperators::OP_LdNull(ScriptContext* scriptContext)
  5745. {
  5746. return scriptContext->GetLibrary()->GetNull();
  5747. }
  5748. Var JavascriptOperators::OP_LdUndef(ScriptContext* scriptContext)
  5749. {
  5750. return scriptContext->GetLibrary()->GetUndefined();
  5751. }
  5752. Var JavascriptOperators::OP_LdNaN(ScriptContext* scriptContext)
  5753. {
  5754. return scriptContext->GetLibrary()->GetNaN();
  5755. }
  5756. Var JavascriptOperators::OP_LdInfinity(ScriptContext* scriptContext)
  5757. {
  5758. return scriptContext->GetLibrary()->GetPositiveInfinite();
  5759. }
  5760. void JavascriptOperators::BuildHandlerScope(Var argThis, RecyclableObject * hostObject, FrameDisplay * pDisplay, ScriptContext * scriptContext)
  5761. {
  5762. Assert(argThis != nullptr);
  5763. pDisplay->SetItem(0, TaggedNumber::Is(argThis) ? scriptContext->GetLibrary()->CreateNumberObject(argThis) : argThis);
  5764. uint16 i = 1;
  5765. Var aChild = argThis;
  5766. uint16 length = pDisplay->GetLength();
  5767. // Now add any parent scopes
  5768. // We need to support the namespace parent lookup in both fastDOM on and off scenario.
  5769. while (aChild != NULL)
  5770. {
  5771. Var aParent = hostObject->GetNamespaceParent(aChild);
  5772. if (aParent == nullptr)
  5773. {
  5774. break;
  5775. }
  5776. aParent = CrossSite::MarshalVar(scriptContext, aParent);
  5777. if (i == length)
  5778. {
  5779. length += 8;
  5780. FrameDisplay * tmp = RecyclerNewPlus(scriptContext->GetRecycler(), length * sizeof(void*), FrameDisplay, length);
  5781. js_memcpy_s((char*)tmp + tmp->GetOffsetOfScopes(), tmp->GetLength() * sizeof(void *), (char*)pDisplay + pDisplay->GetOffsetOfScopes(), pDisplay->GetLength() * sizeof(void*));
  5782. pDisplay = tmp;
  5783. }
  5784. pDisplay->SetItem(i, aParent);
  5785. aChild = aParent;
  5786. i++;
  5787. }
  5788. Assert(i <= pDisplay->GetLength());
  5789. pDisplay->SetLength(i);
  5790. }
  5791. FrameDisplay * JavascriptOperators::OP_LdHandlerScope(Var argThis, ScriptContext* scriptContext)
  5792. {
  5793. // The idea here is to build a stack of nested scopes in the form of a JS array.
  5794. //
  5795. // The scope stack for an event handler looks like this:
  5796. //
  5797. // implicit "this"
  5798. // implicit namespace parent scopes
  5799. // Put the implicit "this"
  5800. if (argThis != NULL)
  5801. {
  5802. RecyclableObject* hostObject = scriptContext->GetGlobalObject()->GetHostObject();
  5803. if (hostObject == nullptr)
  5804. {
  5805. hostObject = scriptContext->GetGlobalObject()->GetDirectHostObject();
  5806. }
  5807. if (hostObject != nullptr)
  5808. {
  5809. uint16 length = 7;
  5810. FrameDisplay *pDisplay =
  5811. RecyclerNewPlus(scriptContext->GetRecycler(), length * sizeof(void*), FrameDisplay, length);
  5812. BuildHandlerScope(argThis, hostObject, pDisplay, scriptContext);
  5813. return pDisplay;
  5814. }
  5815. }
  5816. return const_cast<FrameDisplay *>(&Js::NullFrameDisplay);
  5817. }
  5818. FrameDisplay* JavascriptOperators::OP_LdFrameDisplay(void *argHead, void *argEnv, ScriptContext* scriptContext)
  5819. {
  5820. // Build a display of nested frame objects.
  5821. // argHead is the current scope; argEnv is either the lone trailing scope or an array of scopes
  5822. // which we append to the new display.
  5823. // Note that there are cases in which a function with no local frame must construct a display to pass
  5824. // to the function(s) nested within it. In such a case, argHead will be a null object, and it's not
  5825. // strictly necessary to include it. But such cases are rare and not perf critical, so it's not
  5826. // worth the extra complexity to notify the nested functions that they can "skip" this slot in the
  5827. // frame display when they're loading scopes nested outside it.
  5828. FrameDisplay *pDisplay = nullptr;
  5829. FrameDisplay *envDisplay = (FrameDisplay*)argEnv;
  5830. uint16 length = envDisplay->GetLength() + 1;
  5831. pDisplay = RecyclerNewPlus(scriptContext->GetRecycler(), length * sizeof(void*), FrameDisplay, length);
  5832. for (int j = 0; j < length - 1; j++)
  5833. {
  5834. pDisplay->SetItem(j + 1, envDisplay->GetItem(j));
  5835. }
  5836. pDisplay->SetItem(0, argHead);
  5837. return pDisplay;
  5838. }
  5839. FrameDisplay* JavascriptOperators::OP_LdFrameDisplayNoParent(void *argHead, ScriptContext* scriptContext)
  5840. {
  5841. return OP_LdFrameDisplay(argHead, (void*)&NullFrameDisplay, scriptContext);
  5842. }
  5843. FrameDisplay* JavascriptOperators::OP_LdStrictFrameDisplay(void *argHead, void *argEnv, ScriptContext* scriptContext)
  5844. {
  5845. FrameDisplay * pDisplay = OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  5846. pDisplay->SetStrictMode(true);
  5847. return pDisplay;
  5848. }
  5849. FrameDisplay* JavascriptOperators::OP_LdStrictFrameDisplayNoParent(void *argHead, ScriptContext* scriptContext)
  5850. {
  5851. return OP_LdStrictFrameDisplay(argHead, (void*)&StrictNullFrameDisplay, scriptContext);
  5852. }
  5853. FrameDisplay* JavascriptOperators::OP_LdInnerFrameDisplay(void *argHead, void *argEnv, ScriptContext* scriptContext)
  5854. {
  5855. CheckInnerFrameDisplayArgument(argHead);
  5856. return OP_LdFrameDisplay(argHead, argEnv, scriptContext);
  5857. }
  5858. FrameDisplay* JavascriptOperators::OP_LdInnerFrameDisplayNoParent(void *argHead, ScriptContext* scriptContext)
  5859. {
  5860. CheckInnerFrameDisplayArgument(argHead);
  5861. return OP_LdFrameDisplayNoParent(argHead, scriptContext);
  5862. }
  5863. FrameDisplay* JavascriptOperators::OP_LdStrictInnerFrameDisplay(void *argHead, void *argEnv, ScriptContext* scriptContext)
  5864. {
  5865. CheckInnerFrameDisplayArgument(argHead);
  5866. return OP_LdStrictFrameDisplay(argHead, argEnv, scriptContext);
  5867. }
  5868. FrameDisplay* JavascriptOperators::OP_LdStrictInnerFrameDisplayNoParent(void *argHead, ScriptContext* scriptContext)
  5869. {
  5870. CheckInnerFrameDisplayArgument(argHead);
  5871. return OP_LdStrictFrameDisplayNoParent(argHead, scriptContext);
  5872. }
  5873. void JavascriptOperators::CheckInnerFrameDisplayArgument(void *argHead)
  5874. {
  5875. if (ThreadContext::IsOnStack(argHead))
  5876. {
  5877. AssertMsg(false, "Illegal byte code: stack object as with scope");
  5878. Js::Throw::FatalInternalError();
  5879. }
  5880. if (!RecyclableObject::Is(argHead))
  5881. {
  5882. AssertMsg(false, "Illegal byte code: non-object as with scope");
  5883. Js::Throw::FatalInternalError();
  5884. }
  5885. }
  5886. Js::PropertyId JavascriptOperators::GetPropertyId(Var propertyName, ScriptContext* scriptContext)
  5887. {
  5888. PropertyRecord const * propertyRecord = nullptr;
  5889. if (JavascriptSymbol::Is(propertyName))
  5890. {
  5891. propertyRecord = JavascriptSymbol::FromVar(propertyName)->GetValue();
  5892. }
  5893. else if (JavascriptSymbolObject::Is(propertyName))
  5894. {
  5895. propertyRecord = JavascriptSymbolObject::FromVar(propertyName)->GetValue();
  5896. }
  5897. else
  5898. {
  5899. JavascriptString * indexStr = JavascriptConversion::ToString(propertyName, scriptContext);
  5900. scriptContext->GetOrAddPropertyRecord(indexStr->GetString(), indexStr->GetLength(), &propertyRecord);
  5901. }
  5902. return propertyRecord->GetPropertyId();
  5903. }
  5904. void JavascriptOperators::OP_InitSetter(Var object, PropertyId propertyId, Var setter)
  5905. {
  5906. AssertMsg(!TaggedNumber::Is(object), "SetMember on a non-object?");
  5907. RecyclableObject::FromVar(object)->SetAccessors(propertyId, nullptr, setter);
  5908. }
  5909. void JavascriptOperators::OP_InitClassMemberSet(Var object, PropertyId propertyId, Var setter)
  5910. {
  5911. JavascriptOperators::OP_InitSetter(object, propertyId, setter);
  5912. RecyclableObject::FromVar(object)->SetAttributes(propertyId, PropertyClassMemberDefaults);
  5913. }
  5914. Js::PropertyId JavascriptOperators::OP_InitElemSetter(Var object, Var elementName, Var setter, ScriptContext* scriptContext, PropertyOperationFlags flags)
  5915. {
  5916. AssertMsg(!TaggedNumber::Is(object), "SetMember on a non-object?");
  5917. PropertyId propertyId = JavascriptOperators::GetPropertyId(elementName, scriptContext);
  5918. RecyclableObject::FromVar(object)->SetAccessors(propertyId, nullptr, setter);
  5919. return propertyId;
  5920. }
  5921. Var* JavascriptOperators::OP_GetModuleExportSlotArrayAddress(uint moduleIndex, uint slotIndex, ScriptContext* scriptContext)
  5922. {
  5923. Js::SourceTextModuleRecord* moduleRecord = scriptContext->GetLibrary()->GetModuleRecord(moduleIndex);
  5924. Assert(moduleRecord != nullptr);
  5925. // Require caller to also provide the intended access slot so we can do bounds check now.
  5926. if (moduleRecord->GetLocalExportCount() + 1 <= slotIndex)
  5927. {
  5928. Js::Throw::FatalInternalError();
  5929. }
  5930. return moduleRecord->GetLocalExportSlots();
  5931. }
  5932. Var* JavascriptOperators::OP_GetModuleExportSlotAddress(uint moduleIndex, uint slotIndex, ScriptContext* scriptContext)
  5933. {
  5934. Var* moduleRecordSlots = OP_GetModuleExportSlotArrayAddress(moduleIndex, slotIndex, scriptContext);
  5935. Assert(moduleRecordSlots != nullptr);
  5936. return &moduleRecordSlots[slotIndex];
  5937. }
  5938. Var JavascriptOperators::OP_LdModuleSlot(uint moduleIndex, uint slotIndex, ScriptContext* scriptContext)
  5939. {
  5940. Var* addr = OP_GetModuleExportSlotAddress(moduleIndex, slotIndex, scriptContext);
  5941. Assert(addr != nullptr);
  5942. return *addr;
  5943. }
  5944. void JavascriptOperators::OP_StModuleSlot(uint moduleIndex, uint slotIndex, Var value, ScriptContext* scriptContext)
  5945. {
  5946. Assert(value != nullptr);
  5947. Var* addr = OP_GetModuleExportSlotAddress(moduleIndex, slotIndex, scriptContext);
  5948. Assert(addr != nullptr);
  5949. *addr = value;
  5950. }
  5951. void JavascriptOperators::OP_InitClassMemberSetComputedName(Var object, Var elementName, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  5952. {
  5953. Js::PropertyId propertyId = JavascriptOperators::OP_InitElemSetter(object, elementName, value, scriptContext);
  5954. RecyclableObject* instance = RecyclableObject::FromVar(object);
  5955. // instance will be a function if it is the class constructor (otherwise it would be an object)
  5956. if (JavascriptFunction::Is(instance) && Js::PropertyIds::prototype == propertyId)
  5957. {
  5958. // It is a TypeError to have a static member with a computed name that evaluates to 'prototype'
  5959. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassStaticMethodCannotBePrototype);
  5960. }
  5961. instance->SetAttributes(propertyId, PropertyClassMemberDefaults);
  5962. }
  5963. BOOL JavascriptOperators::IsClassConstructor(Var instance)
  5964. {
  5965. return JavascriptFunction::Is(instance) && (JavascriptFunction::FromVar(instance)->GetFunctionInfo()->IsClassConstructor() || !JavascriptFunction::FromVar(instance)->IsScriptFunction());
  5966. }
  5967. void JavascriptOperators::OP_InitGetter(Var object, PropertyId propertyId, Var getter)
  5968. {
  5969. AssertMsg(!TaggedNumber::Is(object), "GetMember on a non-object?");
  5970. RecyclableObject::FromVar(object)->SetAccessors(propertyId, getter, nullptr);
  5971. }
  5972. void JavascriptOperators::OP_InitClassMemberGet(Var object, PropertyId propertyId, Var getter)
  5973. {
  5974. JavascriptOperators::OP_InitGetter(object, propertyId, getter);
  5975. RecyclableObject::FromVar(object)->SetAttributes(propertyId, PropertyClassMemberDefaults);
  5976. }
  5977. Js::PropertyId JavascriptOperators::OP_InitElemGetter(Var object, Var elementName, Var getter, ScriptContext* scriptContext, PropertyOperationFlags flags)
  5978. {
  5979. AssertMsg(!TaggedNumber::Is(object), "GetMember on a non-object?");
  5980. PropertyId propertyId = JavascriptOperators::GetPropertyId(elementName, scriptContext);
  5981. RecyclableObject::FromVar(object)->SetAccessors(propertyId, getter, nullptr);
  5982. return propertyId;
  5983. }
  5984. void JavascriptOperators::OP_InitClassMemberGetComputedName(Var object, Var elementName, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  5985. {
  5986. Js::PropertyId propertyId = JavascriptOperators::OP_InitElemGetter(object, elementName, value, scriptContext);
  5987. RecyclableObject* instance = RecyclableObject::FromVar(object);
  5988. // instance will be a function if it is the class constructor (otherwise it would be an object)
  5989. if (JavascriptFunction::Is(instance) && Js::PropertyIds::prototype == propertyId)
  5990. {
  5991. // It is a TypeError to have a static member with a computed name that evaluates to 'prototype'
  5992. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassStaticMethodCannotBePrototype);
  5993. }
  5994. instance->SetAttributes(propertyId, PropertyClassMemberDefaults);
  5995. }
  5996. void JavascriptOperators::OP_InitComputedProperty(Var object, Var elementName, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  5997. {
  5998. PropertyId propertyId = JavascriptOperators::GetPropertyId(elementName, scriptContext);
  5999. RecyclableObject::FromVar(object)->InitProperty(propertyId, value, flags);
  6000. }
  6001. void JavascriptOperators::OP_InitClassMemberComputedName(Var object, Var elementName, Var value, ScriptContext* scriptContext, PropertyOperationFlags flags)
  6002. {
  6003. PropertyId propertyId = JavascriptOperators::GetPropertyId(elementName, scriptContext);
  6004. RecyclableObject* instance = RecyclableObject::FromVar(object);
  6005. // instance will be a function if it is the class constructor (otherwise it would be an object)
  6006. if (JavascriptFunction::Is(instance) && Js::PropertyIds::prototype == propertyId)
  6007. {
  6008. // It is a TypeError to have a static member with a computed name that evaluates to 'prototype'
  6009. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassStaticMethodCannotBePrototype);
  6010. }
  6011. instance->SetPropertyWithAttributes(propertyId, value, PropertyClassMemberDefaults, NULL, flags);
  6012. }
  6013. //
  6014. // Used by object literal {..., __proto__: ..., }.
  6015. //
  6016. void JavascriptOperators::OP_InitProto(Var instance, PropertyId propertyId, Var value)
  6017. {
  6018. AssertMsg(RecyclableObject::Is(instance), "__proto__ member on a non-object?");
  6019. Assert(propertyId == PropertyIds::__proto__);
  6020. RecyclableObject* object = RecyclableObject::FromVar(instance);
  6021. ScriptContext* scriptContext = object->GetScriptContext();
  6022. // B.3.1 __proto___ Property Names in Object Initializers
  6023. //6.If propKey is the string value "__proto__" and if isComputedPropertyName(propKey) is false, then
  6024. // a.If Type(v) is either Object or Null, then
  6025. // i.Return the result of calling the [[SetInheritance]] internal method of object with argument propValue.
  6026. // b.Return NormalCompletion(empty).
  6027. if (JavascriptOperators::IsObjectOrNull(value))
  6028. {
  6029. JavascriptObject::ChangePrototype(object, RecyclableObject::FromVar(value), /*validate*/false, scriptContext);
  6030. }
  6031. }
  6032. Var JavascriptOperators::ConvertToUnmappedArguments(HeapArgumentsObject *argumentsObject,
  6033. uint32 paramCount,
  6034. Var *paramAddr,
  6035. DynamicObject* frameObject,
  6036. Js::PropertyIdArray *propIds,
  6037. uint32 formalsCount,
  6038. ScriptContext* scriptContext)
  6039. {
  6040. Var *paramIter = paramAddr;
  6041. uint32 i = 0;
  6042. for (paramIter = paramAddr + i; i < paramCount; i++, paramIter++)
  6043. {
  6044. JavascriptOperators::SetItem(argumentsObject, argumentsObject, i, *paramIter, scriptContext, PropertyOperation_None, /* skipPrototypeCheck = */ TRUE);
  6045. }
  6046. argumentsObject = argumentsObject->ConvertToUnmappedArgumentsObject();
  6047. // Now as the unmapping is done we need to fill those frame object with Undecl
  6048. for (i = 0; i < formalsCount; i++)
  6049. {
  6050. frameObject->SetSlot(SetSlotArguments(propIds != nullptr ? propIds->elements[i] : Js::Constants::NoProperty, i, scriptContext->GetLibrary()->GetUndeclBlockVar()));
  6051. }
  6052. return argumentsObject;
  6053. }
  6054. Var JavascriptOperators::LoadHeapArguments(JavascriptFunction *funcCallee, uint32 actualsCount, Var *paramAddr, Var frameObj, Var vArray, ScriptContext* scriptContext, bool nonSimpleParamList)
  6055. {
  6056. AssertMsg(actualsCount != (unsigned int)-1, "Loading the arguments object in the global function?");
  6057. // Create and initialize the Arguments object.
  6058. uint32 formalsCount = 0;
  6059. Js::PropertyIdArray *propIds = nullptr;
  6060. if (vArray != scriptContext->GetLibrary()->GetNull())
  6061. {
  6062. propIds = (Js::PropertyIdArray *)vArray;
  6063. formalsCount = propIds->count;
  6064. Assert(formalsCount != 0 && propIds != nullptr);
  6065. }
  6066. HeapArgumentsObject *argsObj = JavascriptOperators::CreateHeapArguments(funcCallee, actualsCount, formalsCount, frameObj, scriptContext);
  6067. return FillScopeObject(funcCallee, actualsCount, formalsCount, frameObj, paramAddr, propIds, argsObj, scriptContext, nonSimpleParamList, false);
  6068. }
  6069. Var JavascriptOperators::LoadHeapArgsCached(JavascriptFunction *funcCallee, uint32 actualsCount, uint32 formalsCount, Var *paramAddr, Var frameObj, ScriptContext* scriptContext, bool nonSimpleParamList)
  6070. {
  6071. // Disregard the "this" param.
  6072. AssertMsg(actualsCount != (uint32)-1 && formalsCount != (uint32)-1,
  6073. "Loading the arguments object in the global function?");
  6074. HeapArgumentsObject *argsObj = JavascriptOperators::CreateHeapArguments(funcCallee, actualsCount, formalsCount, frameObj, scriptContext);
  6075. return FillScopeObject(funcCallee, actualsCount, formalsCount, frameObj, paramAddr, nullptr, argsObj, scriptContext, nonSimpleParamList, true);
  6076. }
  6077. Var JavascriptOperators::FillScopeObject(JavascriptFunction *funcCallee, uint32 actualsCount, uint32 formalsCount, Var frameObj, Var * paramAddr,
  6078. Js::PropertyIdArray *propIds, HeapArgumentsObject * argsObj, ScriptContext * scriptContext, bool nonSimpleParamList, bool useCachedScope)
  6079. {
  6080. Assert(frameObj);
  6081. // Transfer formal arguments (that were actually passed) from their ArgIn slots to the local frame object.
  6082. uint32 i;
  6083. Var *tmpAddr = paramAddr;
  6084. if (formalsCount != 0)
  6085. {
  6086. DynamicObject* frameObject = nullptr;
  6087. if (useCachedScope)
  6088. {
  6089. frameObject = DynamicObject::FromVar(frameObj);
  6090. __analysis_assume((uint32)frameObject->GetDynamicType()->GetTypeHandler()->GetSlotCapacity() >= formalsCount);
  6091. }
  6092. else
  6093. {
  6094. frameObject = (DynamicObject*)frameObj;
  6095. // No fixed fields for formal parameters of the arguments object. Also, mark all fields as initialized up-front, because
  6096. // we will set them directly using SetSlot below, so the type handler will not have a chance to mark them as initialized later.
  6097. // CONSIDER : When we delay type sharing until the second instance is created, pass an argument indicating we want the types
  6098. // and handlers created here to be marked as shared up-front. This is to ensure we don't get any fixed fields and that the handler
  6099. // is ready for storing values directly to slots.
  6100. DynamicType* newType = PathTypeHandlerBase::CreateNewScopeObject(scriptContext, frameObject->GetDynamicType(), propIds, nonSimpleParamList ? PropertyLetDefaults : PropertyNone);
  6101. int oldSlotCapacity = frameObject->GetDynamicType()->GetTypeHandler()->GetSlotCapacity();
  6102. int newSlotCapacity = newType->GetTypeHandler()->GetSlotCapacity();
  6103. __analysis_assume((uint32)newSlotCapacity >= formalsCount);
  6104. frameObject->EnsureSlots(oldSlotCapacity, newSlotCapacity, scriptContext, newType->GetTypeHandler());
  6105. frameObject->ReplaceType(newType);
  6106. }
  6107. if (argsObj && nonSimpleParamList)
  6108. {
  6109. return ConvertToUnmappedArguments(argsObj, actualsCount, paramAddr, frameObject, propIds, formalsCount, scriptContext);
  6110. }
  6111. for (i = 0; i < formalsCount && i < actualsCount; i++, tmpAddr++)
  6112. {
  6113. frameObject->SetSlot(SetSlotArguments(propIds != nullptr? propIds->elements[i] : Constants::NoProperty, i, *tmpAddr));
  6114. }
  6115. if (i < formalsCount)
  6116. {
  6117. // The formals that weren't passed still need to be put in the frame object so that
  6118. // their names will be found. Initialize them to "undefined".
  6119. for (; i < formalsCount; i++)
  6120. {
  6121. frameObject->SetSlot(SetSlotArguments(propIds != nullptr? propIds->elements[i] : Constants::NoProperty, i, scriptContext->GetLibrary()->GetUndefined()));
  6122. }
  6123. }
  6124. }
  6125. if (argsObj != nullptr)
  6126. {
  6127. // Transfer the unnamed actual arguments, if any, to the Arguments object itself.
  6128. for (i = formalsCount, tmpAddr = paramAddr + i; i < actualsCount; i++, tmpAddr++)
  6129. {
  6130. // ES5 10.6.11: use [[DefineOwnProperty]] semantics (instead of [[Put]]):
  6131. // do not check whether property is non-writable/etc in the prototype.
  6132. // ES3 semantics is same.
  6133. JavascriptOperators::SetItem(argsObj, argsObj, i, *tmpAddr, scriptContext, PropertyOperation_None, /* skipPrototypeCheck = */ TRUE);
  6134. }
  6135. if (funcCallee->IsStrictMode())
  6136. {
  6137. // If the formals are let decls, then we just overwrote the frame object slots with
  6138. // Undecl sentinels, and we can use the original arguments that were passed to the HeapArgumentsObject.
  6139. return argsObj->ConvertToUnmappedArgumentsObject(!nonSimpleParamList);
  6140. }
  6141. }
  6142. return argsObj;
  6143. }
  6144. HeapArgumentsObject *JavascriptOperators::CreateHeapArguments(JavascriptFunction *funcCallee, uint32 actualsCount, uint32 formalsCount, Var frameObj, ScriptContext* scriptContext)
  6145. {
  6146. JavascriptLibrary *library = scriptContext->GetLibrary();
  6147. HeapArgumentsObject *argsObj = library->CreateHeapArguments(frameObj, formalsCount, !!funcCallee->IsStrictMode());
  6148. //
  6149. // Set the number of arguments of Arguments Object
  6150. //
  6151. argsObj->SetNumberOfArguments(actualsCount);
  6152. JavascriptOperators::SetProperty(argsObj, argsObj, PropertyIds::length, JavascriptNumber::ToVar(actualsCount, scriptContext), scriptContext);
  6153. JavascriptOperators::SetProperty(argsObj, argsObj, PropertyIds::_symbolIterator, library->GetArrayPrototypeValuesFunction(), scriptContext);
  6154. if (funcCallee->IsStrictMode())
  6155. {
  6156. JavascriptFunction* callerAccessor = library->GetThrowTypeErrorCallerAccessorFunction();
  6157. argsObj->SetAccessors(PropertyIds::caller, callerAccessor, callerAccessor, PropertyOperation_NonFixedValue);
  6158. JavascriptFunction* calleeAccessor = library->GetThrowTypeErrorCalleeAccessorFunction();
  6159. argsObj->SetAccessors(PropertyIds::callee, calleeAccessor, calleeAccessor, PropertyOperation_NonFixedValue);
  6160. }
  6161. else
  6162. {
  6163. JavascriptOperators::SetProperty(argsObj, argsObj, PropertyIds::callee,
  6164. StackScriptFunction::EnsureBoxed(BOX_PARAM(funcCallee, nullptr, _u("callee"))), scriptContext);
  6165. }
  6166. return argsObj;
  6167. }
  6168. Var JavascriptOperators::OP_NewScopeObject(ScriptContext*scriptContext)
  6169. {
  6170. return scriptContext->GetLibrary()->CreateActivationObject();
  6171. }
  6172. Var* JavascriptOperators::OP_NewScopeSlots(unsigned int size, ScriptContext *scriptContext, Var scope)
  6173. {
  6174. Assert(size > ScopeSlots::FirstSlotIndex); // Should never see empty slot array
  6175. Var* slotArray = RecyclerNewArray(scriptContext->GetRecycler(), Var, size); // last initialized slot contains reference to array of propertyIds, correspondent to objects in previous slots
  6176. uint count = size - ScopeSlots::FirstSlotIndex;
  6177. ScopeSlots slots(slotArray);
  6178. slots.SetCount(count);
  6179. slots.SetScopeMetadata(scope);
  6180. Var undef = scriptContext->GetLibrary()->GetUndefined();
  6181. for (unsigned int i = 0; i < count; i++)
  6182. {
  6183. slots.Set(i, undef);
  6184. }
  6185. return slotArray;
  6186. }
  6187. Var* JavascriptOperators::OP_NewScopeSlotsWithoutPropIds(unsigned int count, int scopeIndex, ScriptContext *scriptContext, FunctionBody *functionBody)
  6188. {
  6189. DebuggerScope* scope = reinterpret_cast<DebuggerScope*>(Constants::FunctionBodyUnavailable);
  6190. if (scopeIndex != DebuggerScope::InvalidScopeIndex)
  6191. {
  6192. AssertMsg(functionBody->GetScopeObjectChain(), "A scope chain should always be created when there are new scope slots for blocks.");
  6193. scope = functionBody->GetScopeObjectChain()->pScopeChain->Item(scopeIndex);
  6194. }
  6195. return OP_NewScopeSlots(count, scriptContext, scope);
  6196. }
  6197. Var* JavascriptOperators::OP_CloneScopeSlots(Var *slotArray, ScriptContext *scriptContext)
  6198. {
  6199. ScopeSlots slots(slotArray);
  6200. uint size = ScopeSlots::FirstSlotIndex + slots.GetCount();
  6201. Var* slotArrayClone = RecyclerNewArray(scriptContext->GetRecycler(), Var, size);
  6202. memcpy_s(slotArrayClone, sizeof(Var) * size, slotArray, sizeof(Var) * size);
  6203. return slotArrayClone;
  6204. }
  6205. Var JavascriptOperators::OP_NewPseudoScope(ScriptContext *scriptContext)
  6206. {
  6207. return scriptContext->GetLibrary()->CreatePseudoActivationObject();
  6208. }
  6209. Var JavascriptOperators::OP_NewBlockScope(ScriptContext *scriptContext)
  6210. {
  6211. return scriptContext->GetLibrary()->CreateBlockActivationObject();
  6212. }
  6213. Var JavascriptOperators::OP_CloneBlockScope(BlockActivationObject *blockScope, ScriptContext *scriptContext)
  6214. {
  6215. return blockScope->Clone(scriptContext);
  6216. }
  6217. Var JavascriptOperators::OP_IsInst(Var instance, Var aClass, ScriptContext* scriptContext, IsInstInlineCache* inlineCache)
  6218. {
  6219. if (!RecyclableObject::Is(aClass))
  6220. {
  6221. JavascriptError::ThrowTypeError(scriptContext, JSERR_Operand_Invalid_NeedFunction, _u("instanceof"));
  6222. }
  6223. RecyclableObject* constructor = RecyclableObject::FromVar(aClass);
  6224. if (scriptContext->GetConfig()->IsES6HasInstanceEnabled())
  6225. {
  6226. Var instOfHandler = JavascriptOperators::GetProperty(constructor, PropertyIds::_symbolHasInstance, scriptContext);
  6227. if (JavascriptOperators::IsUndefinedObject(instOfHandler)
  6228. || instOfHandler == scriptContext->GetBuiltInLibraryFunction(JavascriptFunction::EntryInfo::SymbolHasInstance.GetOriginalEntryPoint()))
  6229. {
  6230. return JavascriptBoolean::ToVar(constructor->HasInstance(instance, scriptContext, inlineCache), scriptContext);
  6231. }
  6232. else
  6233. {
  6234. if (!JavascriptConversion::IsCallable(instOfHandler))
  6235. {
  6236. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, _u("Symbol[Symbol.hasInstance]"));
  6237. }
  6238. RecyclableObject *instFunc = RecyclableObject::FromVar(instOfHandler);
  6239. Js::Var values[2];
  6240. Js::CallInfo info(Js::CallFlags_Value, 2);
  6241. Js::Arguments args(info, values);
  6242. values[0] = constructor;
  6243. values[1] = instance;
  6244. Var result = JavascriptFunction::CallFunction<true>(instFunc, instFunc->GetEntryPoint(), args);
  6245. return JavascriptBoolean::ToVar(JavascriptConversion::ToBoolean(result, scriptContext) ? TRUE : FALSE, scriptContext);
  6246. }
  6247. }
  6248. else
  6249. {
  6250. return JavascriptBoolean::ToVar(constructor->HasInstance(instance, scriptContext, inlineCache), scriptContext);
  6251. }
  6252. }
  6253. void JavascriptOperators::OP_InitClass(Var constructor, Var extends, ScriptContext * scriptContext)
  6254. {
  6255. if (JavascriptOperators::GetTypeId(constructor) != Js::TypeId::TypeIds_Function)
  6256. {
  6257. JavascriptError::ThrowTypeError(scriptContext, JSERR_Operand_Invalid_NeedFunction, _u("class"));
  6258. }
  6259. RecyclableObject * ctor = RecyclableObject::FromVar(constructor);
  6260. // This is a circular reference to the constructor, it associate the constructor with the class and also allows us to check if a
  6261. // function is a constructor by comparing the homeObj to the this pointer. see ScriptFunction::IsClassConstructor() for implementation
  6262. JavascriptOperators::OP_SetHomeObj(constructor, constructor);
  6263. if (extends)
  6264. {
  6265. switch (JavascriptOperators::GetTypeId(extends))
  6266. {
  6267. case Js::TypeId::TypeIds_Null:
  6268. {
  6269. Var ctorProto = JavascriptOperators::GetProperty(constructor, ctor, Js::PropertyIds::prototype, scriptContext);
  6270. RecyclableObject * ctorProtoObj = RecyclableObject::FromVar(ctorProto);
  6271. ctorProtoObj->SetPrototype(RecyclableObject::FromVar(extends));
  6272. ctorProtoObj->EnsureProperty(Js::PropertyIds::constructor);
  6273. ctorProtoObj->SetEnumerable(Js::PropertyIds::constructor, FALSE);
  6274. break;
  6275. }
  6276. default:
  6277. {
  6278. if (!RecyclableObject::Is(extends))
  6279. {
  6280. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidPrototype, _u("extends"));
  6281. }
  6282. RecyclableObject * extendsObj = RecyclableObject::FromVar(extends);
  6283. if (!JavascriptOperators::IsConstructor(extendsObj))
  6284. {
  6285. JavascriptError::ThrowTypeError(scriptContext, JSERR_ErrorOnNew);
  6286. }
  6287. if (!extendsObj->HasProperty(Js::PropertyIds::prototype))
  6288. {
  6289. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidPrototype);
  6290. }
  6291. Var extendsProto = JavascriptOperators::GetProperty(extends, extendsObj, Js::PropertyIds::prototype, scriptContext);
  6292. uint extendsProtoTypeId = JavascriptOperators::GetTypeId(extendsProto);
  6293. if (extendsProtoTypeId <= Js::TypeId::TypeIds_LastJavascriptPrimitiveType && extendsProtoTypeId != Js::TypeId::TypeIds_Null)
  6294. {
  6295. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidPrototype);
  6296. }
  6297. Var ctorProto = JavascriptOperators::GetProperty(constructor, ctor, Js::PropertyIds::prototype, scriptContext);
  6298. RecyclableObject * ctorProtoObj = RecyclableObject::FromVar(ctorProto);
  6299. ctorProtoObj->SetPrototype(RecyclableObject::FromVar(extendsProto));
  6300. ctorProtoObj->EnsureProperty(Js::PropertyIds::constructor);
  6301. ctorProtoObj->SetEnumerable(Js::PropertyIds::constructor, FALSE);
  6302. Var protoCtor = JavascriptOperators::GetProperty(ctorProto, ctorProtoObj, Js::PropertyIds::constructor, scriptContext);
  6303. RecyclableObject * protoCtorObj = RecyclableObject::FromVar(protoCtor);
  6304. protoCtorObj->SetPrototype(extendsObj);
  6305. break;
  6306. }
  6307. }
  6308. }
  6309. }
  6310. void JavascriptOperators::OP_LoadUndefinedToElement(Var instance, PropertyId propertyId)
  6311. {
  6312. AssertMsg(!TaggedNumber::Is(instance), "Invalid scope/root object");
  6313. JavascriptOperators::EnsureProperty(instance, propertyId);
  6314. }
  6315. void JavascriptOperators::OP_LoadUndefinedToElementScoped(FrameDisplay *pScope, PropertyId propertyId, Var defaultInstance, ScriptContext* scriptContext)
  6316. {
  6317. int i;
  6318. int length = pScope->GetLength();
  6319. Var argInstance;
  6320. for (i = 0; i < length; i++)
  6321. {
  6322. argInstance = pScope->GetItem(i);
  6323. if (JavascriptOperators::EnsureProperty(argInstance, propertyId))
  6324. {
  6325. return;
  6326. }
  6327. }
  6328. if (!JavascriptOperators::HasOwnPropertyNoHostObject(defaultInstance, propertyId))
  6329. {
  6330. // CONSIDER : Consider adding pre-initialization support to activation objects.
  6331. JavascriptOperators::OP_InitPropertyScoped(pScope, propertyId, scriptContext->GetLibrary()->GetUndefined(), defaultInstance, scriptContext);
  6332. }
  6333. }
  6334. void JavascriptOperators::OP_LoadUndefinedToElementDynamic(Var instance, PropertyId propertyId, ScriptContext *scriptContext)
  6335. {
  6336. if (!JavascriptOperators::HasOwnPropertyNoHostObject(instance, propertyId))
  6337. {
  6338. RecyclableObject::FromVar(instance)->InitPropertyScoped(propertyId, scriptContext->GetLibrary()->GetUndefined());
  6339. }
  6340. }
  6341. BOOL JavascriptOperators::EnsureProperty(Var instance, PropertyId propertyId)
  6342. {
  6343. RecyclableObject *obj = RecyclableObject::FromVar(instance);
  6344. return (obj && obj->EnsureProperty(propertyId));
  6345. }
  6346. void JavascriptOperators::OP_EnsureNoRootProperty(Var instance, PropertyId propertyId)
  6347. {
  6348. Assert(RootObjectBase::Is(instance));
  6349. RootObjectBase *obj = RootObjectBase::FromVar(instance);
  6350. obj->EnsureNoProperty(propertyId);
  6351. }
  6352. void JavascriptOperators::OP_EnsureNoRootRedeclProperty(Var instance, PropertyId propertyId)
  6353. {
  6354. Assert(RootObjectBase::Is(instance));
  6355. RecyclableObject *obj = RecyclableObject::FromVar(instance);
  6356. obj->EnsureNoRedeclProperty(propertyId);
  6357. }
  6358. void JavascriptOperators::OP_ScopedEnsureNoRedeclProperty(FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance)
  6359. {
  6360. int i;
  6361. int length = pDisplay->GetLength();
  6362. RecyclableObject *object;
  6363. for (i = 0; i < length; i++)
  6364. {
  6365. object = RecyclableObject::FromVar(pDisplay->GetItem(i));
  6366. if (object->EnsureNoRedeclProperty(propertyId))
  6367. {
  6368. return;
  6369. }
  6370. }
  6371. object = RecyclableObject::FromVar(defaultInstance);
  6372. object->EnsureNoRedeclProperty(propertyId);
  6373. }
  6374. Var JavascriptOperators::IsIn(Var argProperty, Var instance, ScriptContext* scriptContext)
  6375. {
  6376. // Note that the fact that we haven't seen a given name before doesn't mean that the instance doesn't
  6377. if (!IsObject(instance))
  6378. {
  6379. JavascriptError::ThrowTypeError(scriptContext, JSERR_Operand_Invalid_NeedObject, _u("in"));
  6380. }
  6381. PropertyRecord const * propertyRecord;
  6382. uint32 index;
  6383. IndexType indexType = GetIndexType(argProperty, scriptContext, &index, &propertyRecord, true);
  6384. RecyclableObject* object = RecyclableObject::FromVar(instance);
  6385. BOOL result;
  6386. if( indexType == Js::IndexType_Number )
  6387. {
  6388. result = JavascriptOperators::HasItem( object, index );
  6389. }
  6390. else
  6391. {
  6392. PropertyId propertyId = propertyRecord->GetPropertyId();
  6393. result = JavascriptOperators::HasProperty( object, propertyId );
  6394. #ifdef TELEMETRY_JSO
  6395. {
  6396. Assert(indexType != Js::IndexType_JavascriptString);
  6397. if( indexType == Js::IndexType_PropertyId )
  6398. {
  6399. scriptContext->GetTelemetry().GetOpcodeTelemetry().IsIn( instance, propertyId, result != 0 );
  6400. }
  6401. }
  6402. #endif
  6403. }
  6404. return JavascriptBoolean::ToVar(result, scriptContext);
  6405. }
  6406. template <bool IsFromFullJit, class TInlineCache>
  6407. inline Var JavascriptOperators::PatchGetValue(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6408. {
  6409. return PatchGetValueWithThisPtr<IsFromFullJit, TInlineCache>(functionBody, inlineCache, inlineCacheIndex, instance, propertyId, instance);
  6410. }
  6411. template <bool IsFromFullJit, class TInlineCache>
  6412. __forceinline Var JavascriptOperators::PatchGetValueWithThisPtr(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var thisInstance)
  6413. {
  6414. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6415. Assert(Js::JavascriptStackWalker::ValidateTopJitFrame(scriptContext));
  6416. RecyclableObject* object = nullptr;
  6417. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  6418. {
  6419. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6420. {
  6421. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  6422. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6423. }
  6424. else
  6425. {
  6426. return scriptContext->GetLibrary()->GetUndefined();
  6427. }
  6428. }
  6429. PropertyValueInfo info;
  6430. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6431. Var value;
  6432. if (CacheOperators::TryGetProperty<true, true, true, true, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6433. thisInstance, false, object, propertyId, &value, scriptContext, nullptr, &info))
  6434. {
  6435. return value;
  6436. }
  6437. #if DBG_DUMP
  6438. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6439. {
  6440. CacheOperators::TraceCache(inlineCache, _u("PatchGetValue"), propertyId, scriptContext, object);
  6441. }
  6442. #endif
  6443. return JavascriptOperators::GetProperty(thisInstance, object, propertyId, scriptContext, &info);
  6444. }
  6445. template Var JavascriptOperators::PatchGetValue<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6446. template Var JavascriptOperators::PatchGetValue<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6447. template Var JavascriptOperators::PatchGetValue<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6448. template Var JavascriptOperators::PatchGetValue<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6449. template Var JavascriptOperators::PatchGetValueWithThisPtr<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var thisInstance);
  6450. template Var JavascriptOperators::PatchGetValueWithThisPtr<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var thisInstance);
  6451. template Var JavascriptOperators::PatchGetValueWithThisPtr<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var thisInstance);
  6452. template Var JavascriptOperators::PatchGetValueWithThisPtr<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var thisInstance);
  6453. template <bool IsFromFullJit, class TInlineCache>
  6454. Var JavascriptOperators::PatchGetValueForTypeOf(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6455. {
  6456. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6457. Assert(Js::JavascriptStackWalker::ValidateTopJitFrame(scriptContext));
  6458. RecyclableObject* object = nullptr;
  6459. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  6460. {
  6461. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6462. {
  6463. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  6464. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6465. }
  6466. else
  6467. {
  6468. return scriptContext->GetLibrary()->GetUndefined();
  6469. }
  6470. }
  6471. PropertyValueInfo info;
  6472. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6473. Var value;
  6474. if (CacheOperators::TryGetProperty<true, true, true, true, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6475. instance, false, object, propertyId, &value, scriptContext, nullptr, &info))
  6476. {
  6477. return value;
  6478. }
  6479. #if DBG_DUMP
  6480. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6481. {
  6482. CacheOperators::TraceCache(inlineCache, _u("PatchGetValueForTypeOf"), propertyId, scriptContext, object);
  6483. }
  6484. #endif
  6485. Var prop = nullptr;
  6486. BEGIN_TYPEOF_ERROR_HANDLER(scriptContext);
  6487. prop = JavascriptOperators::GetProperty(instance, object, propertyId, scriptContext, &info);
  6488. END_TYPEOF_ERROR_HANDLER(scriptContext, prop);
  6489. return prop;
  6490. }
  6491. template Var JavascriptOperators::PatchGetValueForTypeOf<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6492. template Var JavascriptOperators::PatchGetValueForTypeOf<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6493. template Var JavascriptOperators::PatchGetValueForTypeOf<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6494. template Var JavascriptOperators::PatchGetValueForTypeOf<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6495. Var JavascriptOperators::PatchGetValueUsingSpecifiedInlineCache(InlineCache * inlineCache, Var instance, RecyclableObject * object, PropertyId propertyId, ScriptContext* scriptContext)
  6496. {
  6497. PropertyValueInfo info;
  6498. PropertyValueInfo::SetCacheInfo(&info, inlineCache);
  6499. Var value;
  6500. if (CacheOperators::TryGetProperty<true, true, true, true, false, true, !InlineCache::IsPolymorphic, InlineCache::IsPolymorphic, false>(
  6501. instance, false, object, propertyId, &value, scriptContext, nullptr, &info))
  6502. {
  6503. return value;
  6504. }
  6505. #if DBG_DUMP
  6506. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6507. {
  6508. CacheOperators::TraceCache(inlineCache, _u("PatchGetValue"), propertyId, scriptContext, object);
  6509. }
  6510. #endif
  6511. return JavascriptOperators::GetProperty(instance, object, propertyId, scriptContext, &info);
  6512. }
  6513. Var JavascriptOperators::PatchGetValueNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6514. {
  6515. return PatchGetValueWithThisPtrNoFastPath(functionBody, inlineCache, inlineCacheIndex, instance, propertyId, instance);
  6516. }
  6517. Var JavascriptOperators::PatchGetValueWithThisPtrNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var thisInstance)
  6518. {
  6519. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6520. RecyclableObject* object = nullptr;
  6521. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  6522. {
  6523. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6524. {
  6525. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  6526. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6527. }
  6528. else
  6529. {
  6530. return scriptContext->GetLibrary()->GetUndefined();
  6531. }
  6532. }
  6533. PropertyValueInfo info;
  6534. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  6535. return JavascriptOperators::GetProperty(thisInstance, object, propertyId, scriptContext, &info);
  6536. }
  6537. template <bool IsFromFullJit, class TInlineCache>
  6538. inline Var JavascriptOperators::PatchGetRootValue(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId)
  6539. {
  6540. AssertMsg(RootObjectBase::Is(object), "Root must be a global object!");
  6541. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6542. PropertyValueInfo info;
  6543. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6544. Var value;
  6545. if (CacheOperators::TryGetProperty<true, true, true, false, true, false, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6546. object, true, object, propertyId, &value, scriptContext, nullptr, &info))
  6547. {
  6548. return value;
  6549. }
  6550. #if DBG_DUMP
  6551. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6552. {
  6553. CacheOperators::TraceCache(inlineCache, _u("PatchGetRootValue"), propertyId, scriptContext, object);
  6554. }
  6555. #endif
  6556. return JavascriptOperators::OP_GetRootProperty(object, propertyId, &info, scriptContext);
  6557. }
  6558. template Var JavascriptOperators::PatchGetRootValue<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6559. template Var JavascriptOperators::PatchGetRootValue<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6560. template Var JavascriptOperators::PatchGetRootValue<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6561. template Var JavascriptOperators::PatchGetRootValue<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6562. template <bool IsFromFullJit, class TInlineCache>
  6563. Var JavascriptOperators::PatchGetRootValueForTypeOf(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId)
  6564. {
  6565. AssertMsg(RootObjectBase::Is(object), "Root must be a global object!");
  6566. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6567. PropertyValueInfo info;
  6568. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6569. Var value = nullptr;
  6570. if (CacheOperators::TryGetProperty<true, true, true, false, true, false, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6571. object, true, object, propertyId, &value, scriptContext, nullptr, &info))
  6572. {
  6573. return value;
  6574. }
  6575. #if DBG_DUMP
  6576. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6577. {
  6578. CacheOperators::TraceCache(inlineCache, _u("PatchGetRootValueForTypeOf"), propertyId, scriptContext, object);
  6579. }
  6580. #endif
  6581. value = nullptr;
  6582. BEGIN_TYPEOF_ERROR_HANDLER(scriptContext);
  6583. if (JavascriptOperators::GetRootProperty(RecyclableObject::FromVar(object), propertyId, &value, scriptContext, &info))
  6584. {
  6585. if (scriptContext->IsUndeclBlockVar(value))
  6586. {
  6587. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  6588. }
  6589. return value;
  6590. }
  6591. END_TYPEOF_ERROR_HANDLER(scriptContext, value);
  6592. value = scriptContext->GetLibrary()->GetUndefined();
  6593. return value;
  6594. }
  6595. template Var JavascriptOperators::PatchGetRootValueForTypeOf<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6596. template Var JavascriptOperators::PatchGetRootValueForTypeOf<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6597. template Var JavascriptOperators::PatchGetRootValueForTypeOf<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6598. template Var JavascriptOperators::PatchGetRootValueForTypeOf<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject * object, PropertyId propertyId);
  6599. Var JavascriptOperators::PatchGetRootValueNoFastPath_Var(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6600. {
  6601. return
  6602. PatchGetRootValueNoFastPath(
  6603. functionBody,
  6604. inlineCache,
  6605. inlineCacheIndex,
  6606. DynamicObject::FromVar(instance),
  6607. propertyId);
  6608. }
  6609. Var JavascriptOperators::PatchGetRootValueNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId)
  6610. {
  6611. AssertMsg(RootObjectBase::Is(object), "Root must be a global object!");
  6612. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6613. PropertyValueInfo info;
  6614. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  6615. return JavascriptOperators::OP_GetRootProperty(object, propertyId, &info, scriptContext);
  6616. }
  6617. template <bool IsFromFullJit, class TInlineCache>
  6618. inline Var JavascriptOperators::PatchGetPropertyScoped(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance)
  6619. {
  6620. // Get the property, using a scope stack rather than an individual instance.
  6621. // Walk the stack until we find an instance that has the property.
  6622. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6623. uint16 length = pDisplay->GetLength();
  6624. PropertyValueInfo info;
  6625. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6626. for (uint16 i = 0; i < length; i++)
  6627. {
  6628. DynamicObject* object = (DynamicObject*)pDisplay->GetItem(i);
  6629. Var value;
  6630. if (CacheOperators::TryGetProperty<true, true, true, false, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6631. object, false, object, propertyId, &value, scriptContext, nullptr, &info))
  6632. {
  6633. return value;
  6634. }
  6635. #if DBG_DUMP
  6636. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6637. {
  6638. CacheOperators::TraceCache(inlineCache, _u("PatchGetPropertyScoped"), propertyId, scriptContext, object);
  6639. }
  6640. #endif
  6641. if (JavascriptOperators::GetProperty(object, propertyId, &value, scriptContext, &info))
  6642. {
  6643. if (scriptContext->IsUndeclBlockVar(value) && propertyId != PropertyIds::_lexicalThisSlotSymbol)
  6644. {
  6645. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  6646. }
  6647. return value;
  6648. }
  6649. }
  6650. // No one in the scope stack has the property, so get it from the default instance provided by the caller.
  6651. Var value = JavascriptOperators::PatchGetRootValue<IsFromFullJit>(functionBody, inlineCache, inlineCacheIndex, DynamicObject::FromVar(defaultInstance), propertyId);
  6652. if (scriptContext->IsUndeclBlockVar(value))
  6653. {
  6654. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UseBeforeDeclaration);
  6655. }
  6656. return value;
  6657. }
  6658. template Var JavascriptOperators::PatchGetPropertyScoped<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6659. template Var JavascriptOperators::PatchGetPropertyScoped<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6660. template Var JavascriptOperators::PatchGetPropertyScoped<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6661. template Var JavascriptOperators::PatchGetPropertyScoped<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6662. template <bool IsFromFullJit, class TInlineCache>
  6663. Var JavascriptOperators::PatchGetPropertyForTypeOfScoped(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance)
  6664. {
  6665. Var value = nullptr;
  6666. ScriptContext *scriptContext = functionBody->GetScriptContext();
  6667. BEGIN_TYPEOF_ERROR_HANDLER(scriptContext);
  6668. value = JavascriptOperators::PatchGetPropertyScoped<IsFromFullJit, TInlineCache>(functionBody, inlineCache, inlineCacheIndex, pDisplay, propertyId, defaultInstance);
  6669. END_TYPEOF_ERROR_HANDLER(scriptContext, value)
  6670. return value;
  6671. }
  6672. template Var JavascriptOperators::PatchGetPropertyForTypeOfScoped<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6673. template Var JavascriptOperators::PatchGetPropertyForTypeOfScoped<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6674. template Var JavascriptOperators::PatchGetPropertyForTypeOfScoped<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6675. template Var JavascriptOperators::PatchGetPropertyForTypeOfScoped<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, FrameDisplay *pDisplay, PropertyId propertyId, Var defaultInstance);
  6676. template <bool IsFromFullJit, class TInlineCache>
  6677. inline Var JavascriptOperators::PatchGetMethod(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6678. {
  6679. Assert(inlineCache != nullptr);
  6680. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6681. RecyclableObject* object = nullptr;
  6682. #if ENABLE_COPYONACCESS_ARRAY
  6683. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  6684. #endif
  6685. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  6686. {
  6687. // Don't error if we disabled implicit calls
  6688. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6689. {
  6690. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  6691. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6692. }
  6693. else
  6694. {
  6695. #ifdef TELEMETRY_JSO
  6696. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  6697. {
  6698. // `successful` will be true as PatchGetMethod throws an exception if not found.
  6699. scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(object, propertyId, value, /*successful:*/false);
  6700. }
  6701. #endif
  6702. return scriptContext->GetLibrary()->GetUndefined();
  6703. }
  6704. }
  6705. PropertyValueInfo info;
  6706. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6707. Var value;
  6708. if (CacheOperators::TryGetProperty<true, true, true, false, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6709. instance, false, object, propertyId, &value, scriptContext, nullptr, &info))
  6710. {
  6711. return value;
  6712. }
  6713. #if DBG_DUMP
  6714. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6715. {
  6716. CacheOperators::TraceCache(inlineCache, _u("PatchGetMethod"), propertyId, scriptContext, object);
  6717. }
  6718. #endif
  6719. value = Js::JavascriptOperators::PatchGetMethodFromObject(instance, object, propertyId, &info, scriptContext, false);
  6720. #ifdef TELEMETRY_JSO
  6721. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  6722. {
  6723. // `successful` will be true as PatchGetMethod throws an exception if not found.
  6724. scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(object, propertyId, value, /*successful:*/true);
  6725. }
  6726. #endif
  6727. return value;
  6728. }
  6729. template Var JavascriptOperators::PatchGetMethod<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6730. template Var JavascriptOperators::PatchGetMethod<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6731. template Var JavascriptOperators::PatchGetMethod<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6732. template Var JavascriptOperators::PatchGetMethod<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6733. template <bool IsFromFullJit, class TInlineCache>
  6734. inline Var JavascriptOperators::PatchGetRootMethod(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId)
  6735. {
  6736. Assert(inlineCache != nullptr);
  6737. AssertMsg(RootObjectBase::Is(object), "Root must be a global object!");
  6738. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6739. PropertyValueInfo info;
  6740. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6741. Var value;
  6742. if (CacheOperators::TryGetProperty<true, true, true, false, true, false, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6743. object, true, object, propertyId, &value, scriptContext, nullptr, &info))
  6744. {
  6745. return value;
  6746. }
  6747. #if DBG_DUMP
  6748. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6749. {
  6750. CacheOperators::TraceCache(inlineCache, _u("PatchGetRootMethod"), propertyId, scriptContext, object);
  6751. }
  6752. #endif
  6753. value = Js::JavascriptOperators::PatchGetMethodFromObject(object, object, propertyId, &info, scriptContext, true);
  6754. #ifdef TELEMETRY_JSO
  6755. if (TELEMETRY_PROPERTY_OPCODE_FILTER(propertyId))
  6756. {
  6757. // `successful` will be true as PatchGetMethod throws an exception if not found.
  6758. scriptContext->GetTelemetry().GetOpcodeTelemetry().GetMethodProperty(object, propertyId, value, /*successful:*/ true);
  6759. }
  6760. #endif
  6761. return value;
  6762. }
  6763. template Var JavascriptOperators::PatchGetRootMethod<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId);
  6764. template Var JavascriptOperators::PatchGetRootMethod<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId);
  6765. template Var JavascriptOperators::PatchGetRootMethod<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId);
  6766. template Var JavascriptOperators::PatchGetRootMethod<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId);
  6767. template <bool IsFromFullJit, class TInlineCache>
  6768. inline Var JavascriptOperators::PatchScopedGetMethod(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6769. {
  6770. Assert(inlineCache != nullptr);
  6771. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6772. RecyclableObject* object = nullptr;
  6773. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  6774. {
  6775. // Don't error if we disabled implicit calls
  6776. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6777. {
  6778. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  6779. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6780. }
  6781. else
  6782. {
  6783. return scriptContext->GetLibrary()->GetUndefined();
  6784. }
  6785. }
  6786. PropertyValueInfo info;
  6787. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6788. const bool isRoot = RootObjectBase::Is(object);
  6789. Var value;
  6790. if (CacheOperators::TryGetProperty<true, true, true, false, true, false, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6791. instance, isRoot, object, propertyId, &value, scriptContext, nullptr, &info))
  6792. {
  6793. return value;
  6794. }
  6795. #if DBG_DUMP
  6796. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6797. {
  6798. CacheOperators::TraceCache(inlineCache, _u("PatchGetMethod"), propertyId, scriptContext, object);
  6799. }
  6800. #endif
  6801. return Js::JavascriptOperators::PatchGetMethodFromObject(instance, object, propertyId, &info, scriptContext, isRoot);
  6802. }
  6803. template Var JavascriptOperators::PatchScopedGetMethod<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6804. template Var JavascriptOperators::PatchScopedGetMethod<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6805. template Var JavascriptOperators::PatchScopedGetMethod<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6806. template Var JavascriptOperators::PatchScopedGetMethod<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId);
  6807. Var JavascriptOperators::PatchGetMethodNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6808. {
  6809. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6810. RecyclableObject* object = nullptr;
  6811. if (FALSE == JavascriptOperators::GetPropertyObject(instance, scriptContext, &object))
  6812. {
  6813. // Don't error if we disabled implicit calls
  6814. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6815. {
  6816. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotGet_NullOrUndefined,
  6817. scriptContext->GetPropertyName(propertyId)->GetBuffer());
  6818. }
  6819. else
  6820. {
  6821. return scriptContext->GetLibrary()->GetUndefined();
  6822. }
  6823. }
  6824. PropertyValueInfo info;
  6825. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  6826. return Js::JavascriptOperators::PatchGetMethodFromObject(instance, object, propertyId, &info, scriptContext, false);
  6827. }
  6828. Var JavascriptOperators::PatchGetRootMethodNoFastPath_Var(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId)
  6829. {
  6830. return
  6831. PatchGetRootMethodNoFastPath(
  6832. functionBody,
  6833. inlineCache,
  6834. inlineCacheIndex,
  6835. DynamicObject::FromVar(instance),
  6836. propertyId);
  6837. }
  6838. Var JavascriptOperators::PatchGetRootMethodNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, DynamicObject* object, PropertyId propertyId)
  6839. {
  6840. AssertMsg(RootObjectBase::Is(object), "Root must be a global object!");
  6841. PropertyValueInfo info;
  6842. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  6843. return Js::JavascriptOperators::PatchGetMethodFromObject(object, object, propertyId, &info, functionBody->GetScriptContext(), true);
  6844. }
  6845. Var JavascriptOperators::PatchGetMethodFromObject(Var instance, RecyclableObject* propertyObject, PropertyId propertyId, PropertyValueInfo * info, ScriptContext* scriptContext, bool isRootLd)
  6846. {
  6847. Assert(IsPropertyObject(propertyObject));
  6848. Var value = nullptr;
  6849. BOOL foundValue = FALSE;
  6850. if (isRootLd)
  6851. {
  6852. RootObjectBase* rootObject = RootObjectBase::FromVar(instance);
  6853. foundValue = JavascriptOperators::GetRootPropertyReference(rootObject, propertyId, &value, scriptContext, info);
  6854. }
  6855. else
  6856. {
  6857. foundValue = JavascriptOperators::GetPropertyReference(instance, propertyObject, propertyId, &value, scriptContext, info);
  6858. }
  6859. if (!foundValue)
  6860. {
  6861. // Don't error if we disabled implicit calls
  6862. if (scriptContext->GetThreadContext()->RecordImplicitException())
  6863. {
  6864. const char16* propertyName = scriptContext->GetPropertyName(propertyId)->GetBuffer();
  6865. value = scriptContext->GetLibrary()->GetUndefined();
  6866. JavascriptFunction * caller = NULL;
  6867. if (JavascriptStackWalker::GetCaller(&caller, scriptContext))
  6868. {
  6869. FunctionBody * callerBody = caller->GetFunctionBody();
  6870. if (callerBody && callerBody->GetUtf8SourceInfo()->GetIsXDomain())
  6871. {
  6872. propertyName = NULL;
  6873. }
  6874. }
  6875. // Prior to version 12 we had mistakenly immediately thrown an error for property reference method calls
  6876. // (i.e. <expr>.foo() form) when the target object is the global object. The spec says that a GetValue
  6877. // on a reference should throw if the reference is unresolved, of which a property reference can never be,
  6878. // however it can be unresolved in the case of an identifier expression, e.g. foo() with no qualification.
  6879. // Such a case would come down to the global object if foo was undefined, hence the check for root object,
  6880. // except that it should have been a check for isRootLd to be correct.
  6881. //
  6882. // // (at global scope)
  6883. // foo(x());
  6884. //
  6885. // should throw an error before evaluating x() if foo is not defined, but
  6886. //
  6887. // // (at global scope)
  6888. // this.foo(x());
  6889. //
  6890. // should evaluate x() before throwing an error if foo is not a property on the global object.
  6891. // Maintain old behavior prior to version 12.
  6892. bool isPropertyReference = !isRootLd;
  6893. if (!isPropertyReference)
  6894. {
  6895. JavascriptError::ThrowReferenceError(scriptContext, JSERR_UndefVariable, propertyName);
  6896. }
  6897. else
  6898. {
  6899. // ES5 11.2.3 #2: We evaluate the call target but don't throw yet if target member is missing. We need to evaluate argList
  6900. // first (#3). Postpone throwing error to invoke time.
  6901. value = ThrowErrorObject::CreateThrowTypeErrorObject(scriptContext, VBSERR_OLENoPropOrMethod, propertyName);
  6902. }
  6903. }
  6904. }
  6905. return value;
  6906. }
  6907. template <bool IsFromFullJit, class TInlineCache>
  6908. inline void JavascriptOperators::PatchPutValue(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  6909. {
  6910. return PatchPutValueWithThisPtr<IsFromFullJit, TInlineCache>(functionBody, inlineCache, inlineCacheIndex, instance, propertyId, newValue, instance, flags);
  6911. }
  6912. template <bool IsFromFullJit, class TInlineCache>
  6913. inline void JavascriptOperators::PatchPutValueWithThisPtr(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags)
  6914. {
  6915. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6916. if (TaggedNumber::Is(instance))
  6917. {
  6918. JavascriptOperators::SetPropertyOnTaggedNumber(instance, nullptr, propertyId, newValue, scriptContext, flags);
  6919. return;
  6920. }
  6921. #if ENABLE_COPYONACCESS_ARRAY
  6922. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  6923. #endif
  6924. RecyclableObject* object = RecyclableObject::FromVar(instance);
  6925. PropertyValueInfo info;
  6926. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6927. if (CacheOperators::TrySetProperty<true, true, true, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6928. object, false, propertyId, newValue, scriptContext, flags, nullptr, &info))
  6929. {
  6930. return;
  6931. }
  6932. #if DBG_DUMP
  6933. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6934. {
  6935. CacheOperators::TraceCache(inlineCache, _u("PatchPutValue"), propertyId, scriptContext, object);
  6936. }
  6937. #endif
  6938. ImplicitCallFlags prevImplicitCallFlags = ImplicitCall_None;
  6939. ImplicitCallFlags currImplicitCallFlags = ImplicitCall_None;
  6940. bool hasThisOnlyStatements = functionBody->GetHasOnlyThisStmts();
  6941. if (hasThisOnlyStatements)
  6942. {
  6943. prevImplicitCallFlags = CacheAndClearImplicitBit(scriptContext);
  6944. }
  6945. if (!JavascriptOperators::OP_SetProperty(object, propertyId, newValue, scriptContext, &info, flags, thisInstance))
  6946. {
  6947. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  6948. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  6949. }
  6950. if (hasThisOnlyStatements)
  6951. {
  6952. currImplicitCallFlags = CheckAndUpdateFunctionBodyWithImplicitFlag(functionBody);
  6953. RestoreImplicitFlag(scriptContext, prevImplicitCallFlags, currImplicitCallFlags);
  6954. }
  6955. }
  6956. template void JavascriptOperators::PatchPutValue<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6957. template void JavascriptOperators::PatchPutValue<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6958. template void JavascriptOperators::PatchPutValue<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6959. template void JavascriptOperators::PatchPutValue<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6960. template <bool IsFromFullJit, class TInlineCache>
  6961. inline void JavascriptOperators::PatchPutRootValue(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  6962. {
  6963. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  6964. RecyclableObject* object = RecyclableObject::FromVar(instance);
  6965. PropertyValueInfo info;
  6966. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  6967. if (CacheOperators::TrySetProperty<true, true, true, true, false, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  6968. object, true, propertyId, newValue, scriptContext, flags, nullptr, &info))
  6969. {
  6970. return;
  6971. }
  6972. #if DBG_DUMP
  6973. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  6974. {
  6975. CacheOperators::TraceCache(inlineCache, _u("PatchPutRootValue"), propertyId, scriptContext, object);
  6976. }
  6977. #endif
  6978. ImplicitCallFlags prevImplicitCallFlags = ImplicitCall_None;
  6979. ImplicitCallFlags currImplicitCallFlags = ImplicitCall_None;
  6980. bool hasThisOnlyStatements = functionBody->GetHasOnlyThisStmts();
  6981. if (hasThisOnlyStatements)
  6982. {
  6983. prevImplicitCallFlags = CacheAndClearImplicitBit(scriptContext);
  6984. }
  6985. if (!JavascriptOperators::SetRootProperty(object, propertyId, newValue, &info, scriptContext, flags))
  6986. {
  6987. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  6988. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  6989. }
  6990. if (hasThisOnlyStatements)
  6991. {
  6992. currImplicitCallFlags = CheckAndUpdateFunctionBodyWithImplicitFlag(functionBody);
  6993. RestoreImplicitFlag(scriptContext, prevImplicitCallFlags, currImplicitCallFlags);
  6994. }
  6995. }
  6996. template void JavascriptOperators::PatchPutRootValue<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6997. template void JavascriptOperators::PatchPutRootValue<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6998. template void JavascriptOperators::PatchPutRootValue<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  6999. template void JavascriptOperators::PatchPutRootValue<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7000. template <bool IsFromFullJit, class TInlineCache>
  7001. inline void JavascriptOperators::PatchPutValueNoLocalFastPath(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  7002. {
  7003. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  7004. if (TaggedNumber::Is(instance))
  7005. {
  7006. JavascriptOperators::SetPropertyOnTaggedNumber(instance,
  7007. nullptr,
  7008. propertyId,
  7009. newValue,
  7010. scriptContext,
  7011. flags);
  7012. return;
  7013. }
  7014. #if ENABLE_COPYONACCESS_ARRAY
  7015. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  7016. #endif
  7017. RecyclableObject *object = RecyclableObject::FromVar(instance);
  7018. PropertyValueInfo info;
  7019. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  7020. if (CacheOperators::TrySetProperty<!TInlineCache::IsPolymorphic, true, true, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  7021. object, false, propertyId, newValue, scriptContext, flags, nullptr, &info))
  7022. {
  7023. return;
  7024. }
  7025. #if DBG_DUMP
  7026. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  7027. {
  7028. CacheOperators::TraceCache(inlineCache, _u("PatchPutValueNoLocalFastPath"), propertyId, scriptContext, object);
  7029. }
  7030. #endif
  7031. ImplicitCallFlags prevImplicitCallFlags = ImplicitCall_None;
  7032. ImplicitCallFlags currImplicitCallFlags = ImplicitCall_None;
  7033. bool hasThisOnlyStatements = functionBody->GetHasOnlyThisStmts();
  7034. if (hasThisOnlyStatements)
  7035. {
  7036. prevImplicitCallFlags = CacheAndClearImplicitBit(scriptContext);
  7037. }
  7038. if (!JavascriptOperators::OP_SetProperty(instance, propertyId, newValue, scriptContext, &info, flags))
  7039. {
  7040. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  7041. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  7042. }
  7043. if (hasThisOnlyStatements)
  7044. {
  7045. currImplicitCallFlags = CheckAndUpdateFunctionBodyWithImplicitFlag(functionBody);
  7046. RestoreImplicitFlag(scriptContext, prevImplicitCallFlags, currImplicitCallFlags);
  7047. }
  7048. }
  7049. template void JavascriptOperators::PatchPutValueNoLocalFastPath<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7050. template void JavascriptOperators::PatchPutValueNoLocalFastPath<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7051. template void JavascriptOperators::PatchPutValueNoLocalFastPath<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7052. template void JavascriptOperators::PatchPutValueNoLocalFastPath<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7053. template <bool IsFromFullJit, class TInlineCache>
  7054. inline void JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags)
  7055. {
  7056. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  7057. if (TaggedNumber::Is(instance))
  7058. {
  7059. JavascriptOperators::SetPropertyOnTaggedNumber(instance,
  7060. nullptr,
  7061. propertyId,
  7062. newValue,
  7063. scriptContext,
  7064. flags);
  7065. return;
  7066. }
  7067. #if ENABLE_COPYONACCESS_ARRAY
  7068. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(instance);
  7069. #endif
  7070. RecyclableObject *object = RecyclableObject::FromVar(instance);
  7071. PropertyValueInfo info;
  7072. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  7073. if (CacheOperators::TrySetProperty<!TInlineCache::IsPolymorphic, true, true, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  7074. object, false, propertyId, newValue, scriptContext, flags, nullptr, &info))
  7075. {
  7076. return;
  7077. }
  7078. #if DBG_DUMP
  7079. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  7080. {
  7081. CacheOperators::TraceCache(inlineCache, _u("PatchPutValueNoLocalFastPath"), propertyId, scriptContext, object);
  7082. }
  7083. #endif
  7084. ImplicitCallFlags prevImplicitCallFlags = ImplicitCall_None;
  7085. ImplicitCallFlags currImplicitCallFlags = ImplicitCall_None;
  7086. bool hasThisOnlyStatements = functionBody->GetHasOnlyThisStmts();
  7087. if (hasThisOnlyStatements)
  7088. {
  7089. prevImplicitCallFlags = CacheAndClearImplicitBit(scriptContext);
  7090. }
  7091. if (!JavascriptOperators::OP_SetProperty(instance, propertyId, newValue, scriptContext, &info, flags, thisInstance))
  7092. {
  7093. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  7094. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  7095. }
  7096. if (hasThisOnlyStatements)
  7097. {
  7098. currImplicitCallFlags = CheckAndUpdateFunctionBodyWithImplicitFlag(functionBody);
  7099. RestoreImplicitFlag(scriptContext, prevImplicitCallFlags, currImplicitCallFlags);
  7100. }
  7101. }
  7102. template void JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags);
  7103. template void JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags);
  7104. template void JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags);
  7105. template void JavascriptOperators::PatchPutValueWithThisPtrNoLocalFastPath<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags);
  7106. template <bool IsFromFullJit, class TInlineCache>
  7107. inline void JavascriptOperators::PatchPutRootValueNoLocalFastPath(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  7108. {
  7109. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  7110. RecyclableObject *object = RecyclableObject::FromVar(instance);
  7111. PropertyValueInfo info;
  7112. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  7113. if (CacheOperators::TrySetProperty<!TInlineCache::IsPolymorphic, true, true, true, false, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  7114. object, true, propertyId, newValue, scriptContext, flags, nullptr, &info))
  7115. {
  7116. return;
  7117. }
  7118. #if DBG_DUMP
  7119. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  7120. {
  7121. CacheOperators::TraceCache(inlineCache, _u("PatchPutRootValueNoLocalFastPath"), propertyId, scriptContext, object);
  7122. }
  7123. #endif
  7124. ImplicitCallFlags prevImplicitCallFlags = ImplicitCall_None;
  7125. ImplicitCallFlags currImplicitCallFlags = ImplicitCall_None;
  7126. bool hasThisOnlyStatements = functionBody->GetHasOnlyThisStmts();
  7127. if (hasThisOnlyStatements)
  7128. {
  7129. prevImplicitCallFlags = CacheAndClearImplicitBit(scriptContext);
  7130. }
  7131. if (!JavascriptOperators::SetRootProperty(object, propertyId, newValue, &info, scriptContext, flags))
  7132. {
  7133. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  7134. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  7135. }
  7136. if (hasThisOnlyStatements)
  7137. {
  7138. currImplicitCallFlags = CheckAndUpdateFunctionBodyWithImplicitFlag(functionBody);
  7139. RestoreImplicitFlag(scriptContext, prevImplicitCallFlags, currImplicitCallFlags);
  7140. }
  7141. }
  7142. template void JavascriptOperators::PatchPutRootValueNoLocalFastPath<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7143. template void JavascriptOperators::PatchPutRootValueNoLocalFastPath<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7144. template void JavascriptOperators::PatchPutRootValueNoLocalFastPath<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7145. template void JavascriptOperators::PatchPutRootValueNoLocalFastPath<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags);
  7146. void JavascriptOperators::PatchPutValueNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  7147. {
  7148. PatchPutValueWithThisPtrNoFastPath(functionBody, inlineCache, inlineCacheIndex, instance, propertyId, newValue, instance, flags);
  7149. }
  7150. void JavascriptOperators::PatchPutValueWithThisPtrNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, Var thisInstance, PropertyOperationFlags flags)
  7151. {
  7152. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  7153. if (TaggedNumber::Is(instance))
  7154. {
  7155. JavascriptOperators::SetPropertyOnTaggedNumber(instance, nullptr, propertyId, newValue, scriptContext, flags);
  7156. return;
  7157. }
  7158. RecyclableObject* object = RecyclableObject::FromVar(instance);
  7159. PropertyValueInfo info;
  7160. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  7161. if (!JavascriptOperators::OP_SetProperty(object, propertyId, newValue, scriptContext, &info, flags, thisInstance))
  7162. {
  7163. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  7164. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  7165. }
  7166. }
  7167. void JavascriptOperators::PatchPutRootValueNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, Var instance, PropertyId propertyId, Var newValue, PropertyOperationFlags flags)
  7168. {
  7169. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  7170. RecyclableObject* object = RecyclableObject::FromVar(instance);
  7171. PropertyValueInfo info;
  7172. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  7173. if (!JavascriptOperators::SetRootProperty(object, propertyId, newValue, &info, scriptContext, flags))
  7174. {
  7175. // Add implicit call flags, to bail out if field copy prop may propagate the wrong value.
  7176. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_NoOpSet);
  7177. }
  7178. }
  7179. template <bool IsFromFullJit, class TInlineCache>
  7180. inline void JavascriptOperators::PatchInitValue(FunctionBody *const functionBody, TInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, RecyclableObject* object, PropertyId propertyId, Var newValue)
  7181. {
  7182. ScriptContext *const scriptContext = functionBody->GetScriptContext();
  7183. const PropertyOperationFlags flags = newValue == NULL ? PropertyOperation_SpecialValue : PropertyOperation_None;
  7184. PropertyValueInfo info;
  7185. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, !IsFromFullJit);
  7186. if (CacheOperators::TrySetProperty<true, true, false, true, true, !TInlineCache::IsPolymorphic, TInlineCache::IsPolymorphic, false>(
  7187. object, false, propertyId, newValue, scriptContext, flags, nullptr, &info))
  7188. {
  7189. return;
  7190. }
  7191. #if DBG_DUMP
  7192. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  7193. {
  7194. CacheOperators::TraceCache(inlineCache, _u("PatchInitValue"), propertyId, scriptContext, object);
  7195. }
  7196. #endif
  7197. Type *typeWithoutProperty = object->GetType();
  7198. // Ideally the lowerer would emit a call to the right flavor of PatchInitValue, so that we can ensure that we only
  7199. // ever initialize to NULL in the right cases. But the backend uses the StFld opcode for initialization, and it
  7200. // would be cumbersome to thread the different helper calls all the way down
  7201. if (object->InitProperty(propertyId, newValue, flags, &info))
  7202. {
  7203. CacheOperators::CachePropertyWrite(object, false, typeWithoutProperty, propertyId, &info, scriptContext);
  7204. }
  7205. }
  7206. template void JavascriptOperators::PatchInitValue<false, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, RecyclableObject* object, PropertyId propertyId, Var newValue);
  7207. template void JavascriptOperators::PatchInitValue<true, InlineCache>(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, RecyclableObject* object, PropertyId propertyId, Var newValue);
  7208. template void JavascriptOperators::PatchInitValue<false, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, RecyclableObject* object, PropertyId propertyId, Var newValue);
  7209. template void JavascriptOperators::PatchInitValue<true, PolymorphicInlineCache>(FunctionBody *const functionBody, PolymorphicInlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, RecyclableObject* object, PropertyId propertyId, Var newValue);
  7210. void JavascriptOperators::PatchInitValueNoFastPath(FunctionBody *const functionBody, InlineCache *const inlineCache, const InlineCacheIndex inlineCacheIndex, RecyclableObject* object, PropertyId propertyId, Var newValue)
  7211. {
  7212. PropertyValueInfo info;
  7213. PropertyValueInfo::SetCacheInfo(&info, functionBody, inlineCache, inlineCacheIndex, true);
  7214. Type *typeWithoutProperty = object->GetType();
  7215. if (object->InitProperty(propertyId, newValue, PropertyOperation_None, &info))
  7216. {
  7217. CacheOperators::CachePropertyWrite(object, false, typeWithoutProperty, propertyId, &info, functionBody->GetScriptContext());
  7218. }
  7219. }
  7220. #if ENABLE_DEBUG_CONFIG_OPTIONS
  7221. void JavascriptOperators::TracePropertyEquivalenceCheck(const JitEquivalentTypeGuard* guard, const Type* type, const Type* refType, bool isEquivalent, uint failedPropertyIndex)
  7222. {
  7223. if (PHASE_TRACE1(Js::EquivObjTypeSpecPhase))
  7224. {
  7225. uint propertyCount = guard->GetCache()->record.propertyCount;
  7226. Output::Print(_u("EquivObjTypeSpec: checking %u properties on operation %u, (type = 0x%p, ref type = 0x%p):\n"),
  7227. propertyCount, guard->GetObjTypeSpecFldId(), type, refType);
  7228. const Js::TypeEquivalenceRecord& record = guard->GetCache()->record;
  7229. ScriptContext* scriptContext = type->GetScriptContext();
  7230. if (isEquivalent)
  7231. {
  7232. if (Js::Configuration::Global.flags.Verbose)
  7233. {
  7234. Output::Print(_u(" <start>, "));
  7235. for (uint pi = 0; pi < propertyCount; pi++)
  7236. {
  7237. const EquivalentPropertyEntry* refInfo = &record.properties[pi];
  7238. const PropertyRecord* propertyRecord = scriptContext->GetPropertyName(refInfo->propertyId);
  7239. Output::Print(_u("%s(#%d)@%ua%dw%d, "), propertyRecord->GetBuffer(), propertyRecord->GetPropertyId(), refInfo->slotIndex, refInfo->isAuxSlot, refInfo->mustBeWritable);
  7240. }
  7241. Output::Print(_u("<end>\n"));
  7242. }
  7243. }
  7244. else
  7245. {
  7246. const EquivalentPropertyEntry* refInfo = &record.properties[failedPropertyIndex];
  7247. Js::PropertyEquivalenceInfo info(Constants::NoSlot, false, false);
  7248. const PropertyRecord* propertyRecord = scriptContext->GetPropertyName(refInfo->propertyId);
  7249. if (DynamicType::Is(type->GetTypeId()))
  7250. {
  7251. Js::DynamicTypeHandler* typeHandler = (static_cast<const DynamicType*>(type))->GetTypeHandler();
  7252. typeHandler->GetPropertyEquivalenceInfo(propertyRecord, info);
  7253. }
  7254. Output::Print(_u("EquivObjTypeSpec: check failed for %s (#%d) on operation %u:\n"),
  7255. propertyRecord->GetBuffer(), propertyRecord->GetPropertyId(), guard->GetObjTypeSpecFldId());
  7256. Output::Print(_u(" type = 0x%p, ref type = 0x%p, slot = 0x%u (%d), ref slot = 0x%u (%d), is writable = %d, required writable = %d\n"),
  7257. type, refType, info.slotIndex, refInfo->slotIndex, info.isAuxSlot, refInfo->isAuxSlot, info.isWritable, refInfo->mustBeWritable);
  7258. }
  7259. Output::Flush();
  7260. }
  7261. }
  7262. #endif
  7263. bool JavascriptOperators::IsStaticTypeObjTypeSpecEquivalent(const TypeEquivalenceRecord& equivalenceRecord, uint& failedIndex)
  7264. {
  7265. uint propertyCount = equivalenceRecord.propertyCount;
  7266. Js::EquivalentPropertyEntry* properties = equivalenceRecord.properties;
  7267. for (uint pi = 0; pi < propertyCount; pi++)
  7268. {
  7269. const EquivalentPropertyEntry* refInfo = &properties[pi];
  7270. if (!IsStaticTypeObjTypeSpecEquivalent(refInfo))
  7271. {
  7272. failedIndex = pi;
  7273. return false;
  7274. }
  7275. }
  7276. return true;
  7277. }
  7278. bool JavascriptOperators::IsStaticTypeObjTypeSpecEquivalent(const EquivalentPropertyEntry *entry)
  7279. {
  7280. // Objects of static types have no local properties, but they may load fields from their prototypes.
  7281. return entry->slotIndex == Constants::NoSlot && !entry->mustBeWritable;
  7282. }
  7283. bool JavascriptOperators::CheckIfTypeIsEquivalent(Type* type, JitEquivalentTypeGuard* guard)
  7284. {
  7285. if (guard->GetValue() == 0)
  7286. {
  7287. return false;
  7288. }
  7289. AssertMsg(type && type->GetScriptContext(), "type and it's ScriptContext should be valid.");
  7290. if (!guard->IsInvalidatedDuringSweep() && guard->GetType()->GetScriptContext() != type->GetScriptContext())
  7291. {
  7292. // For valid guard value, can't cache cross-context objects
  7293. return false;
  7294. }
  7295. // CONSIDER : Add stats on how often the cache hits, and simply force bailout if
  7296. // the efficacy is too low.
  7297. EquivalentTypeCache* cache = guard->GetCache();
  7298. // CONSIDER : Consider emitting o.type == equivTypes[hash(o.type)] in machine code before calling
  7299. // this helper, particularly if we want to handle polymorphism with frequently changing types.
  7300. Assert(EQUIVALENT_TYPE_CACHE_SIZE == 8);
  7301. Type** equivTypes = cache->types;
  7302. Type* refType = equivTypes[0];
  7303. if (refType == nullptr || refType->GetScriptContext() != type->GetScriptContext())
  7304. {
  7305. // We could have guard that was invalidated while sweeping and now we have type coming from
  7306. // different scriptContext. Make sure that it matches the scriptContext in cachedTypes.
  7307. // If not, return false because as mentioned above, we don't cache cross-context objects.
  7308. #if DBG
  7309. if (refType == nullptr)
  7310. {
  7311. for (int i = 1;i < EQUIVALENT_TYPE_CACHE_SIZE;i++)
  7312. {
  7313. AssertMsg(equivTypes[i] == nullptr, "In equiv typed caches, if first element is nullptr, all others should be nullptr");
  7314. }
  7315. }
  7316. #endif
  7317. return false;
  7318. }
  7319. if (type == equivTypes[0] || type == equivTypes[1] || type == equivTypes[2] || type == equivTypes[3] ||
  7320. type == equivTypes[4] || type == equivTypes[5] || type == equivTypes[6] || type == equivTypes[7])
  7321. {
  7322. #if DBG
  7323. if (PHASE_TRACE1(Js::EquivObjTypeSpecPhase))
  7324. {
  7325. if (guard->WasReincarnated())
  7326. {
  7327. Output::Print(_u("EquivObjTypeSpec: Guard 0x%p was reincarnated and working now \n"), guard);
  7328. Output::Flush();
  7329. }
  7330. }
  7331. #endif
  7332. guard->SetType(type);
  7333. return true;
  7334. }
  7335. // If we didn't find the type in the cache, let's check if it's equivalent the slow way, by comparing
  7336. // each of its relevant property slots to its equivalent in one of the cached types.
  7337. // We are making a few assumption that simplify the process:
  7338. // 1. If two types have the same prototype, any properties loaded from a prototype must come from the same slot.
  7339. // If any of the prototypes in the chain was altered such that this is no longer true, the corresponding
  7340. // property guard would have been invalidated and we would bail out at the guard check (either on this
  7341. // type check or downstream, but before the property load is attempted).
  7342. // 2. For polymorphic field loads fixed fields are only supported on prototypes. Hence, if two types have the
  7343. // same prototype, any of the equivalent fixed properties will match. If any has been overwritten, the
  7344. // corresponding guard would have been invalidated and we would bail out (as above).
  7345. if (cache->IsLoadedFromProto() && type->GetPrototype() != refType->GetPrototype())
  7346. {
  7347. if (PHASE_TRACE1(Js::EquivObjTypeSpecPhase))
  7348. {
  7349. Output::Print(_u("EquivObjTypeSpec: failed check on operation %u (type = 0x%x, ref type = 0x%x, proto = 0x%x, ref proto = 0x%x) \n"),
  7350. guard->GetObjTypeSpecFldId(), type, refType, type->GetPrototype(), refType->GetPrototype());
  7351. Output::Flush();
  7352. }
  7353. return false;
  7354. }
  7355. if (type->GetTypeId() != refType->GetTypeId())
  7356. {
  7357. if (PHASE_TRACE1(Js::EquivObjTypeSpecPhase))
  7358. {
  7359. Output::Print(_u("EquivObjTypeSpec: failed check on operation %u (type = 0x%x, ref type = 0x%x, proto = 0x%x, ref proto = 0x%x) \n"),
  7360. guard->GetObjTypeSpecFldId(), type, refType, type->GetPrototype(), refType->GetPrototype());
  7361. Output::Flush();
  7362. }
  7363. return false;
  7364. }
  7365. // Review : This is quite slow. We could make it somewhat faster, by keeping slot indexes instead
  7366. // of property IDs, but that would mean we would need to look up property IDs from slot indexes when installing
  7367. // property guards, or maintain a whole separate list of equivalent slot indexes.
  7368. Assert(cache->record.propertyCount > 0);
  7369. // CONSIDER (EquivObjTypeSpec): Impose a limit on the number of properties guarded by an equivalent type check.
  7370. // The trick is where in the glob opt to make the cut off. Perhaps in the forward pass we could track the number of
  7371. // field operations protected by a type check (keep a counter on the type's value info), and if that counter exceeds
  7372. // some threshold, simply stop optimizing any further instructions.
  7373. bool isEquivalent;
  7374. uint failedPropertyIndex;
  7375. if (DynamicType::Is(type->GetTypeId()))
  7376. {
  7377. Js::DynamicTypeHandler* typeHandler = (static_cast<DynamicType*>(type))->GetTypeHandler();
  7378. isEquivalent = typeHandler->IsObjTypeSpecEquivalent(type, cache->record, failedPropertyIndex);
  7379. }
  7380. else
  7381. {
  7382. Assert(StaticType::Is(type->GetTypeId()));
  7383. isEquivalent = IsStaticTypeObjTypeSpecEquivalent(cache->record, failedPropertyIndex);
  7384. }
  7385. #if ENABLE_DEBUG_CONFIG_OPTIONS
  7386. TracePropertyEquivalenceCheck(guard, type, refType, isEquivalent, failedPropertyIndex);
  7387. #endif
  7388. if (!isEquivalent)
  7389. {
  7390. return false;
  7391. }
  7392. int emptySlotIndex = -1;
  7393. for (int i = 0;i < EQUIVALENT_TYPE_CACHE_SIZE;i++)
  7394. {
  7395. if (equivTypes[i] == nullptr)
  7396. {
  7397. emptySlotIndex = i;
  7398. break;
  7399. };
  7400. }
  7401. // We have some empty slots, let us use those first
  7402. if (emptySlotIndex != -1)
  7403. {
  7404. if (PHASE_TRACE1(Js::EquivObjTypeSpecPhase))
  7405. {
  7406. Output::Print(_u("EquivObjTypeSpec: Saving type in unused slot of equiv types cache. \n"));
  7407. Output::Flush();
  7408. }
  7409. equivTypes[emptySlotIndex] = type;
  7410. }
  7411. else
  7412. {
  7413. // CONSIDER (EquivObjTypeSpec): Invent some form of least recently used eviction scheme.
  7414. uintptr_t index = (reinterpret_cast<uintptr_t>(type) >> 4) & (EQUIVALENT_TYPE_CACHE_SIZE - 1);
  7415. if (cache->nextEvictionVictim == EQUIVALENT_TYPE_CACHE_SIZE)
  7416. {
  7417. __analysis_assume(index < EQUIVALENT_TYPE_CACHE_SIZE);
  7418. // If nextEvictionVictim was never set, set it to next element after index
  7419. cache->nextEvictionVictim = (index + 1) & (EQUIVALENT_TYPE_CACHE_SIZE - 1);
  7420. }
  7421. else
  7422. {
  7423. Assert(cache->nextEvictionVictim < EQUIVALENT_TYPE_CACHE_SIZE);
  7424. __analysis_assume(cache->nextEvictionVictim < EQUIVALENT_TYPE_CACHE_SIZE);
  7425. equivTypes[cache->nextEvictionVictim] = equivTypes[index];
  7426. // Else, set it to next element after current nextEvictionVictim index
  7427. cache->nextEvictionVictim = (cache->nextEvictionVictim + 1) & (EQUIVALENT_TYPE_CACHE_SIZE - 1);
  7428. }
  7429. if (PHASE_TRACE1(Js::EquivObjTypeSpecPhase))
  7430. {
  7431. Output::Print(_u("EquivObjTypeSpec: Saving type in used slot of equiv types cache at index = %d. NextEvictionVictim = %d. \n"), index, cache->nextEvictionVictim);
  7432. Output::Flush();
  7433. }
  7434. Assert(index < EQUIVALENT_TYPE_CACHE_SIZE);
  7435. __analysis_assume(index < EQUIVALENT_TYPE_CACHE_SIZE);
  7436. equivTypes[index] = type;
  7437. }
  7438. // Fixed field checks allow us to assume a specific type ID, but the assumption is only
  7439. // valid if we lock the type. Otherwise, the type ID may change out from under us without
  7440. // evolving the type.
  7441. // We also need to lock the type in case of, for instance, adding a property to a dictionary type handler.
  7442. if (DynamicType::Is(type->GetTypeId()))
  7443. {
  7444. DynamicType *dynamicType = static_cast<DynamicType*>(type);
  7445. if (!dynamicType->GetIsLocked())
  7446. {
  7447. dynamicType->LockType();
  7448. }
  7449. }
  7450. guard->SetType(type);
  7451. return true;
  7452. }
  7453. void JavascriptOperators::GetPropertyIdForInt(uint64 value, ScriptContext* scriptContext, PropertyRecord const ** propertyRecord)
  7454. {
  7455. char16 buffer[20];
  7456. ::_ui64tow_s(value, buffer, sizeof(buffer)/sizeof(char16), 10);
  7457. scriptContext->GetOrAddPropertyRecord(buffer, JavascriptString::GetBufferLength(buffer), propertyRecord);
  7458. }
  7459. void JavascriptOperators::GetPropertyIdForInt(uint32 value, ScriptContext* scriptContext, PropertyRecord const ** propertyRecord)
  7460. {
  7461. GetPropertyIdForInt(static_cast<uint64>(value), scriptContext, propertyRecord);
  7462. }
  7463. Var JavascriptOperators::FromPropertyDescriptor(PropertyDescriptor descriptor, ScriptContext* scriptContext)
  7464. {
  7465. DynamicObject* object = scriptContext->GetLibrary()->CreateObject();
  7466. // ES5 Section 8.10.4 specifies the order for adding these properties.
  7467. if (descriptor.IsDataDescriptor())
  7468. {
  7469. if (descriptor.ValueSpecified())
  7470. {
  7471. JavascriptOperators::InitProperty(object, PropertyIds::value, descriptor.GetValue());
  7472. }
  7473. JavascriptOperators::InitProperty(object, PropertyIds::writable, JavascriptBoolean::ToVar(descriptor.IsWritable(),scriptContext));
  7474. }
  7475. else if (descriptor.IsAccessorDescriptor())
  7476. {
  7477. JavascriptOperators::InitProperty(object, PropertyIds::get, JavascriptOperators::CanonicalizeAccessor(descriptor.GetGetter(), scriptContext));
  7478. JavascriptOperators::InitProperty(object, PropertyIds::set, JavascriptOperators::CanonicalizeAccessor(descriptor.GetSetter(), scriptContext));
  7479. }
  7480. if (descriptor.EnumerableSpecified())
  7481. {
  7482. JavascriptOperators::InitProperty(object, PropertyIds::enumerable, JavascriptBoolean::ToVar(descriptor.IsEnumerable(), scriptContext));
  7483. }
  7484. if (descriptor.ConfigurableSpecified())
  7485. {
  7486. JavascriptOperators::InitProperty(object, PropertyIds::configurable, JavascriptBoolean::ToVar(descriptor.IsConfigurable(), scriptContext));
  7487. }
  7488. return object;
  7489. }
  7490. // ES5 8.12.9 [[DefineOwnProperty]].
  7491. // Return value:
  7492. // - TRUE = success.
  7493. // - FALSE (can throw depending on throwOnError parameter) = unsuccessful.
  7494. BOOL JavascriptOperators::DefineOwnPropertyDescriptor(RecyclableObject* obj, PropertyId propId, const PropertyDescriptor& descriptor, bool throwOnError, ScriptContext* scriptContext)
  7495. {
  7496. Assert(obj);
  7497. Assert(scriptContext);
  7498. if (JavascriptProxy::Is(obj))
  7499. {
  7500. return JavascriptProxy::DefineOwnPropertyDescriptor(obj, propId, descriptor, throwOnError, scriptContext);
  7501. }
  7502. PropertyDescriptor currentDescriptor;
  7503. BOOL isCurrentDescriptorDefined = JavascriptOperators::GetOwnPropertyDescriptor(obj, propId, scriptContext, &currentDescriptor);
  7504. bool isExtensible = !!obj->IsExtensible();
  7505. return ValidateAndApplyPropertyDescriptor<true>(obj, propId, descriptor, isCurrentDescriptorDefined ? &currentDescriptor : nullptr, isExtensible, throwOnError, scriptContext);
  7506. }
  7507. BOOL JavascriptOperators::IsCompatiblePropertyDescriptor(const PropertyDescriptor& descriptor, PropertyDescriptor* currentDescriptor, bool isExtensible, bool throwOnError, ScriptContext* scriptContext)
  7508. {
  7509. return ValidateAndApplyPropertyDescriptor<false>(nullptr, Constants::NoProperty, descriptor, currentDescriptor, isExtensible, throwOnError, scriptContext);
  7510. }
  7511. template<bool needToSetProperty>
  7512. BOOL JavascriptOperators::ValidateAndApplyPropertyDescriptor(RecyclableObject* obj, PropertyId propId, const PropertyDescriptor& descriptor,
  7513. PropertyDescriptor* currentDescriptor, bool isExtensible, bool throwOnError, ScriptContext* scriptContext)
  7514. {
  7515. Var defaultDataValue = scriptContext->GetLibrary()->GetUndefined();
  7516. Var defaultAccessorValue = scriptContext->GetLibrary()->GetDefaultAccessorFunction();
  7517. if (currentDescriptor == nullptr)
  7518. {
  7519. if (!isExtensible) // ES5 8.12.9.3.
  7520. {
  7521. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotExtensible, propId);
  7522. }
  7523. else // ES5 8.12.9.4.
  7524. {
  7525. if (needToSetProperty)
  7526. {
  7527. if (descriptor.IsGenericDescriptor() || descriptor.IsDataDescriptor())
  7528. {
  7529. // ES5 8.12.9.4a: Create an own data property named P of object O whose [[Value]], [[Writable]],
  7530. // [[Enumerable]] and [[Configurable]] attribute values are described by Desc.
  7531. // If the value of an attribute field of Desc is absent, the attribute of the newly created property
  7532. // is set to its default value.
  7533. PropertyDescriptor filledDescriptor = FillMissingPropertyDescriptorFields<false>(descriptor, scriptContext);
  7534. BOOL tempResult = obj->SetPropertyWithAttributes(propId, filledDescriptor.GetValue(), filledDescriptor.GetAttributes(), nullptr);
  7535. Assert(tempResult || obj->IsExternal());
  7536. }
  7537. else
  7538. {
  7539. // ES5 8.12.9.4b: Create an own accessor property named P of object O whose [[Get]], [[Set]], [[Enumerable]]
  7540. // and [[Configurable]] attribute values are described by Desc. If the value of an attribute field of Desc is absent,
  7541. // the attribute of the newly created property is set to its default value.
  7542. Assert(descriptor.IsAccessorDescriptor());
  7543. PropertyDescriptor filledDescriptor = FillMissingPropertyDescriptorFields<true>(descriptor, scriptContext);
  7544. BOOL isSetAccessorsSuccess = obj->SetAccessors(propId, filledDescriptor.GetGetter(), filledDescriptor.GetSetter());
  7545. // It is valid for some objects to not-support getters and setters, specifically, for projection of an ABI method
  7546. // (CustomExternalObject => MapWithStringKey) which SetAccessors returns VBSErr_ActionNotSupported.
  7547. // But for non-external objects SetAccessors should succeed.
  7548. Assert(isSetAccessorsSuccess || obj->CanHaveInterceptors());
  7549. // If SetAccessors failed, the property wasn't created, so no need to change the attributes.
  7550. if (isSetAccessorsSuccess)
  7551. {
  7552. JavascriptOperators::SetAttributes(obj, propId, filledDescriptor, true); // use 'force' as default attributes in type system are different from ES5.
  7553. }
  7554. }
  7555. }
  7556. return TRUE;
  7557. }
  7558. }
  7559. // ES5 8.12.9.5: Return true, if every field in Desc is absent.
  7560. if (!descriptor.ConfigurableSpecified() && !descriptor.EnumerableSpecified() && !descriptor.WritableSpecified() &&
  7561. !descriptor.ValueSpecified() && !descriptor.GetterSpecified() && !descriptor.SetterSpecified())
  7562. {
  7563. return TRUE;
  7564. }
  7565. // ES5 8.12.9.6: Return true, if every field in Desc also occurs in current and the value of every field in Desc is the same value
  7566. // as the corresponding field in current when compared using the SameValue algorithm (9.12).
  7567. PropertyDescriptor filledDescriptor = descriptor.IsAccessorDescriptor() ? FillMissingPropertyDescriptorFields<true>(descriptor, scriptContext)
  7568. : FillMissingPropertyDescriptorFields<false>(descriptor, scriptContext);
  7569. if (JavascriptOperators::AreSamePropertyDescriptors(&filledDescriptor, currentDescriptor, scriptContext))
  7570. {
  7571. return TRUE;
  7572. }
  7573. if (!currentDescriptor->IsConfigurable()) // ES5 8.12.9.7.
  7574. {
  7575. if (descriptor.ConfigurableSpecified() && descriptor.IsConfigurable())
  7576. {
  7577. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotConfigurable, propId);
  7578. }
  7579. if (descriptor.EnumerableSpecified() && descriptor.IsEnumerable() != currentDescriptor->IsEnumerable())
  7580. {
  7581. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotConfigurable, propId);
  7582. }
  7583. }
  7584. // Whether to merge attributes from tempDescriptor into descriptor to keep original values
  7585. // of some attributes from the object/use tempDescriptor for SetAttributes, or just use descriptor.
  7586. // This is optimization to avoid 2 calls to SetAttributes.
  7587. bool mergeDescriptors = false;
  7588. // Whether to call SetAttributes with 'force' flag which forces setting all attributes
  7589. // rather than only specified or which have true values.
  7590. // This is to make sure that the object has correct attributes, as default values in the object are not for ES5.
  7591. bool forceSetAttributes = false;
  7592. PropertyDescriptor tempDescriptor;
  7593. // ES5 8.12.9.8: If IsGenericDescriptor(Desc) is true, then no further validation is required.
  7594. if (!descriptor.IsGenericDescriptor())
  7595. {
  7596. if (currentDescriptor->IsDataDescriptor() != descriptor.IsDataDescriptor())
  7597. {
  7598. // ES5 8.12.9.9: Else, if IsDataDescriptor(current) and IsDataDescriptor(Desc) have different results...
  7599. if (!currentDescriptor->IsConfigurable())
  7600. {
  7601. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotConfigurable, propId);
  7602. }
  7603. if (needToSetProperty)
  7604. {
  7605. if (currentDescriptor->IsDataDescriptor())
  7606. {
  7607. // ES5 8.12.9.9.b: Convert the property named P of object O from a data property to an accessor property.
  7608. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes
  7609. // and set the rest of the property's attributes to their default values.
  7610. PropertyAttributes preserveFromObject = currentDescriptor->GetAttributes() & (PropertyConfigurable | PropertyEnumerable);
  7611. BOOL isSetAccessorsSuccess = obj->SetAccessors(propId, defaultAccessorValue, defaultAccessorValue);
  7612. // It is valid for some objects to not-support getters and setters, specifically, for projection of an ABI method
  7613. // (CustomExternalObject => MapWithStringKey) which SetAccessors returns VBSErr_ActionNotSupported.
  7614. // But for non-external objects SetAccessors should succeed.
  7615. Assert(isSetAccessorsSuccess || obj->CanHaveInterceptors());
  7616. if (isSetAccessorsSuccess)
  7617. {
  7618. tempDescriptor.SetAttributes(preserveFromObject, PropertyConfigurable | PropertyEnumerable);
  7619. forceSetAttributes = true; // use SetAttrbiutes with 'force' as default attributes in type system are different from ES5.
  7620. mergeDescriptors = true;
  7621. }
  7622. }
  7623. else
  7624. {
  7625. // ES5 8.12.9.9.c: Convert the property named P of object O from an accessor property to a data property.
  7626. // Preserve the existing values of the converted property's [[Configurable]] and [[Enumerable]] attributes
  7627. // and set the rest of the property's attributes to their default values.
  7628. // Note: avoid using SetProperty/SetPropertyWithAttributes here because they has undesired side-effects:
  7629. // it calls previous setter and in some cases of attribute values throws.
  7630. // To walk around, call DeleteProperty and then AddProperty.
  7631. PropertyAttributes preserveFromObject = currentDescriptor->GetAttributes() & (PropertyConfigurable | PropertyEnumerable);
  7632. tempDescriptor.SetAttributes(preserveFromObject, PropertyConfigurable | PropertyEnumerable);
  7633. tempDescriptor.MergeFrom(descriptor); // Update only fields specified in 'descriptor'.
  7634. Var descriptorValue = descriptor.ValueSpecified() ? descriptor.GetValue() : defaultDataValue;
  7635. // Note: HostDispath'es implementation of DeleteProperty currently throws E_NOTIMPL.
  7636. obj->DeleteProperty(propId, PropertyOperation_None);
  7637. BOOL tempResult = obj->SetPropertyWithAttributes(propId, descriptorValue, tempDescriptor.GetAttributes(), NULL, PropertyOperation_Force);
  7638. Assert(tempResult);
  7639. // At this time we already set value and attributes to desired values,
  7640. // thus we can skip step ES5 8.12.9.12 and simply return true.
  7641. return TRUE;
  7642. }
  7643. }
  7644. }
  7645. else if (currentDescriptor->IsDataDescriptor() && descriptor.IsDataDescriptor())
  7646. {
  7647. // ES5 8.12.9.10: Else, if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both true...
  7648. if (!currentDescriptor->IsConfigurable())
  7649. {
  7650. if (!currentDescriptor->IsWritable())
  7651. {
  7652. if ((descriptor.WritableSpecified() && descriptor.IsWritable()) || // ES5 8.12.9.10.a.i
  7653. (descriptor.ValueSpecified() &&
  7654. !JavascriptConversion::SameValue(descriptor.GetValue(), currentDescriptor->GetValue()))) // ES5 8.12.9.10.a.ii
  7655. {
  7656. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotWritable, propId);
  7657. }
  7658. }
  7659. }
  7660. // ES5 8.12.9.10.b: else, the [[Configurable]] field of current is true, so any change is acceptable.
  7661. }
  7662. else
  7663. {
  7664. // ES5 8.12.9.11: Else, IsAccessorDescriptor(current) and IsAccessorDescriptor(Desc) are both true, so...
  7665. Assert(currentDescriptor->IsAccessorDescriptor() && descriptor.IsAccessorDescriptor());
  7666. if (!currentDescriptor->IsConfigurable())
  7667. {
  7668. if ((descriptor.SetterSpecified() &&
  7669. !JavascriptConversion::SameValue(
  7670. JavascriptOperators::CanonicalizeAccessor(descriptor.GetSetter(), scriptContext),
  7671. JavascriptOperators::CanonicalizeAccessor(currentDescriptor->GetSetter(), scriptContext))) ||
  7672. (descriptor.GetterSpecified() &&
  7673. !JavascriptConversion::SameValue(
  7674. JavascriptOperators::CanonicalizeAccessor(descriptor.GetGetter(), scriptContext),
  7675. JavascriptOperators::CanonicalizeAccessor(currentDescriptor->GetGetter(), scriptContext))))
  7676. {
  7677. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotConfigurable, propId);
  7678. }
  7679. }
  7680. }
  7681. // This part is only for non-generic descriptors:
  7682. // ES5 8.12.9.12: For each attribute field of Desc that is present,
  7683. // set the correspondingly named attribute of the property named P of object O to the value of the field.
  7684. if (descriptor.IsDataDescriptor())
  7685. {
  7686. if (descriptor.ValueSpecified() && needToSetProperty)
  7687. {
  7688. // Set just the value by passing the current attributes of the property.
  7689. // If the property's attributes are also changing (perhaps becoming non-writable),
  7690. // this will be taken care of in the call to JavascriptOperators::SetAttributes below.
  7691. // Built-in Function.prototype properties 'length', 'arguments', and 'caller' are special cases.
  7692. BOOL tempResult = obj->SetPropertyWithAttributes(propId, descriptor.GetValue(), currentDescriptor->GetAttributes(), nullptr);
  7693. AssertMsg(tempResult || JavascriptFunction::IsBuiltinProperty(obj, propId), "If you hit this assert, most likely there is something wrong with the object/type.");
  7694. }
  7695. }
  7696. else if (descriptor.IsAccessorDescriptor() && needToSetProperty)
  7697. {
  7698. Assert(descriptor.GetterSpecified() || descriptor.SetterSpecified());
  7699. Var oldGetter = defaultAccessorValue, oldSetter = defaultAccessorValue;
  7700. if (!descriptor.GetterSpecified() || !descriptor.SetterSpecified())
  7701. {
  7702. // Unless both getter and setter are specified, make sure we don't overwrite old accessor.
  7703. obj->GetAccessors(propId, &oldGetter, &oldSetter, scriptContext);
  7704. }
  7705. Var getter = descriptor.GetterSpecified() ? descriptor.GetGetter() : oldGetter;
  7706. Var setter = descriptor.SetterSpecified() ? descriptor.GetSetter() : oldSetter;
  7707. obj->SetAccessors(propId, getter, setter);
  7708. }
  7709. } // if (!descriptor.IsGenericDescriptor())
  7710. // Continue for all descriptors including generic:
  7711. // ES5 8.12.9.12: For each attribute field of Desc that is present,
  7712. // set the correspondingly named attribute of the property named P of object O to the value of the field.
  7713. if (needToSetProperty)
  7714. {
  7715. if (mergeDescriptors)
  7716. {
  7717. tempDescriptor.MergeFrom(descriptor);
  7718. JavascriptOperators::SetAttributes(obj, propId, tempDescriptor, forceSetAttributes);
  7719. }
  7720. else
  7721. {
  7722. JavascriptOperators::SetAttributes(obj, propId, descriptor, forceSetAttributes);
  7723. }
  7724. }
  7725. return TRUE;
  7726. }
  7727. template <bool isAccessor>
  7728. PropertyDescriptor JavascriptOperators::FillMissingPropertyDescriptorFields(PropertyDescriptor descriptor, ScriptContext* scriptContext)
  7729. {
  7730. PropertyDescriptor newDescriptor;
  7731. const PropertyDescriptor* defaultDescriptor = scriptContext->GetLibrary()->GetDefaultPropertyDescriptor();
  7732. if (isAccessor)
  7733. {
  7734. newDescriptor.SetGetter(descriptor.GetterSpecified() ? descriptor.GetGetter() : defaultDescriptor->GetGetter());
  7735. newDescriptor.SetSetter(descriptor.SetterSpecified() ? descriptor.GetSetter() : defaultDescriptor->GetSetter());
  7736. }
  7737. else
  7738. {
  7739. newDescriptor.SetValue(descriptor.ValueSpecified() ? descriptor.GetValue() : defaultDescriptor->GetValue());
  7740. newDescriptor.SetWritable(descriptor.WritableSpecified() ? descriptor.IsWritable() : defaultDescriptor->IsWritable());
  7741. }
  7742. newDescriptor.SetConfigurable(descriptor.ConfigurableSpecified() ? descriptor.IsConfigurable() : defaultDescriptor->IsConfigurable());
  7743. newDescriptor.SetEnumerable(descriptor.EnumerableSpecified() ? descriptor.IsEnumerable() : defaultDescriptor->IsEnumerable());
  7744. return newDescriptor;
  7745. }
  7746. // ES5: 15.4.5.1
  7747. BOOL JavascriptOperators::DefineOwnPropertyForArray(JavascriptArray* arr, PropertyId propId, const PropertyDescriptor& descriptor, bool throwOnError, ScriptContext* scriptContext)
  7748. {
  7749. if (propId == PropertyIds::length)
  7750. {
  7751. if (!descriptor.ValueSpecified())
  7752. {
  7753. return DefineOwnPropertyDescriptor(arr, PropertyIds::length, descriptor, throwOnError, scriptContext);
  7754. }
  7755. PropertyDescriptor newLenDesc = descriptor;
  7756. uint32 newLen = ES5Array::ToLengthValue(descriptor.GetValue(), scriptContext);
  7757. newLenDesc.SetValue(JavascriptNumber::ToVar(newLen, scriptContext));
  7758. uint32 oldLen = arr->GetLength();
  7759. if (newLen >= oldLen)
  7760. {
  7761. return DefineOwnPropertyDescriptor(arr, PropertyIds::length, newLenDesc, throwOnError, scriptContext);
  7762. }
  7763. BOOL oldLenWritable = arr->IsWritable(PropertyIds::length);
  7764. if (!oldLenWritable)
  7765. {
  7766. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_NotWritable, propId);
  7767. }
  7768. bool newWritable = (!newLenDesc.WritableSpecified() || newLenDesc.IsWritable());
  7769. if (!newWritable)
  7770. {
  7771. // Need to defer setting writable to false in case any elements cannot be deleted
  7772. newLenDesc.SetWritable(true);
  7773. }
  7774. BOOL succeeded = DefineOwnPropertyDescriptor(arr, PropertyIds::length, newLenDesc, throwOnError, scriptContext);
  7775. //
  7776. // Our SetProperty(length) is also responsible to trim elements. When succeeded is
  7777. //
  7778. // false:
  7779. // * length attributes rejected
  7780. // * elements not touched
  7781. // true:
  7782. // * length attributes are set successfully
  7783. // * elements trimming may be either completed or incompleted, length value is correct
  7784. //
  7785. // * Strict mode TODO: Currently SetProperty(length) does not throw. If that throws, we need
  7786. // to update here to set correct newWritable even on exception.
  7787. //
  7788. if (!succeeded)
  7789. {
  7790. return false;
  7791. }
  7792. if (!newWritable) // Now set requested newWritable.
  7793. {
  7794. PropertyDescriptor newWritableDesc;
  7795. newWritableDesc.SetWritable(false);
  7796. DefineOwnPropertyDescriptor(arr, PropertyIds::length, newWritableDesc, false, scriptContext);
  7797. }
  7798. if (arr->GetLength() > newLen) // Delete incompleted
  7799. {
  7800. // Since SetProperty(length) not throwing, we'll reject here
  7801. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_Default, propId);
  7802. }
  7803. return true;
  7804. }
  7805. uint32 index;
  7806. if (scriptContext->IsNumericPropertyId(propId, &index))
  7807. {
  7808. if (index >= arr->GetLength() && !arr->IsWritable(PropertyIds::length))
  7809. {
  7810. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_LengthNotWritable, propId);
  7811. }
  7812. BOOL succeeded = DefineOwnPropertyDescriptor(arr, propId, descriptor, false, scriptContext);
  7813. if (!succeeded)
  7814. {
  7815. return Reject(throwOnError, scriptContext, JSERR_DefineProperty_Default, propId);
  7816. }
  7817. // Out SetItem takes care of growing "length". we are done.
  7818. return true;
  7819. }
  7820. return DefineOwnPropertyDescriptor(arr, propId, descriptor, throwOnError, scriptContext);
  7821. }
  7822. BOOL JavascriptOperators::SetPropertyDescriptor(RecyclableObject* object, PropertyId propId, PropertyDescriptor descriptor)
  7823. {
  7824. if (descriptor.ValueSpecified())
  7825. {
  7826. ScriptContext* requestContext = object->GetScriptContext(); // Real requestContext?
  7827. JavascriptOperators::SetProperty(object, object, propId, descriptor.GetValue(), requestContext);
  7828. }
  7829. else if (descriptor.GetterSpecified() || descriptor.SetterSpecified())
  7830. {
  7831. JavascriptOperators::SetAccessors(object, propId, descriptor.GetGetter(), descriptor.GetSetter());
  7832. }
  7833. if (descriptor.EnumerableSpecified())
  7834. {
  7835. object->SetEnumerable(propId, descriptor.IsEnumerable());
  7836. }
  7837. if (descriptor.ConfigurableSpecified())
  7838. {
  7839. object->SetConfigurable(propId, descriptor.IsConfigurable());
  7840. }
  7841. if (descriptor.WritableSpecified())
  7842. {
  7843. object->SetWritable(propId, descriptor.IsWritable());
  7844. }
  7845. return true;
  7846. }
  7847. BOOL JavascriptOperators::ToPropertyDescriptorForProxyObjects(Var propertySpec, PropertyDescriptor* descriptor, ScriptContext* scriptContext)
  7848. {
  7849. if (!JavascriptOperators::IsObject(propertySpec))
  7850. {
  7851. return FALSE;
  7852. }
  7853. Var value;
  7854. RecyclableObject* propertySpecObj = RecyclableObject::FromVar(propertySpec);
  7855. if (JavascriptOperators::HasProperty(propertySpecObj, PropertyIds::enumerable) == TRUE)
  7856. {
  7857. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::enumerable, &value, scriptContext))
  7858. {
  7859. descriptor->SetEnumerable(JavascriptConversion::ToBoolean(value, scriptContext) ? true : false);
  7860. }
  7861. else
  7862. {
  7863. // The proxy said we have the property, so we try to read the property and get the default value.
  7864. descriptor->SetEnumerable(false);
  7865. }
  7866. }
  7867. if (JavascriptOperators::HasProperty(propertySpecObj, PropertyIds::configurable) == TRUE)
  7868. {
  7869. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::configurable, &value, scriptContext))
  7870. {
  7871. descriptor->SetConfigurable(JavascriptConversion::ToBoolean(value, scriptContext) ? true : false);
  7872. }
  7873. else
  7874. {
  7875. // The proxy said we have the property, so we try to read the property and get the default value.
  7876. descriptor->SetConfigurable(false);
  7877. }
  7878. }
  7879. if (JavascriptOperators::HasProperty(propertySpecObj, PropertyIds::value) == TRUE)
  7880. {
  7881. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::value, &value, scriptContext))
  7882. {
  7883. descriptor->SetValue(value);
  7884. }
  7885. else
  7886. {
  7887. // The proxy said we have the property, so we try to read the property and get the default value.
  7888. descriptor->SetValue(scriptContext->GetLibrary()->GetUndefined());
  7889. }
  7890. }
  7891. if (JavascriptOperators::HasProperty(propertySpecObj, PropertyIds::writable) == TRUE)
  7892. {
  7893. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::writable, &value, scriptContext))
  7894. {
  7895. descriptor->SetWritable(JavascriptConversion::ToBoolean(value, scriptContext) ? true : false);
  7896. }
  7897. else
  7898. {
  7899. // The proxy said we have the property, so we try to read the property and get the default value.
  7900. descriptor->SetWritable(false);
  7901. }
  7902. }
  7903. if (JavascriptOperators::HasProperty(propertySpecObj, PropertyIds::get) == TRUE)
  7904. {
  7905. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::get, &value, scriptContext))
  7906. {
  7907. if (JavascriptOperators::GetTypeId(value) != TypeIds_Undefined && (false == JavascriptConversion::IsCallable(value)))
  7908. {
  7909. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, scriptContext->GetPropertyName(PropertyIds::get)->GetBuffer());
  7910. }
  7911. descriptor->SetGetter(value);
  7912. }
  7913. else
  7914. {
  7915. // The proxy said we have the property, so we try to read the property and get the default value.
  7916. descriptor->SetGetter(scriptContext->GetLibrary()->GetUndefined());
  7917. }
  7918. }
  7919. if (JavascriptOperators::HasProperty(propertySpecObj, PropertyIds::set) == TRUE)
  7920. {
  7921. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::set, &value, scriptContext))
  7922. {
  7923. if (JavascriptOperators::GetTypeId(value) != TypeIds_Undefined && (false == JavascriptConversion::IsCallable(value)))
  7924. {
  7925. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, scriptContext->GetPropertyName(PropertyIds::set)->GetBuffer());
  7926. }
  7927. descriptor->SetSetter(value);
  7928. }
  7929. else
  7930. {
  7931. // The proxy said we have the property, so we try to read the property and get the default value.
  7932. descriptor->SetSetter(scriptContext->GetLibrary()->GetUndefined());
  7933. }
  7934. }
  7935. return TRUE;
  7936. }
  7937. BOOL JavascriptOperators::ToPropertyDescriptorForGenericObjects(Var propertySpec, PropertyDescriptor* descriptor, ScriptContext* scriptContext)
  7938. {
  7939. if (!JavascriptOperators::IsObject(propertySpec))
  7940. {
  7941. return FALSE;
  7942. }
  7943. Var value;
  7944. RecyclableObject* propertySpecObj = RecyclableObject::FromVar(propertySpec);
  7945. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::enumerable, &value, scriptContext))
  7946. {
  7947. descriptor->SetEnumerable(JavascriptConversion::ToBoolean(value, scriptContext) ? true : false);
  7948. }
  7949. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::configurable, &value, scriptContext))
  7950. {
  7951. descriptor->SetConfigurable(JavascriptConversion::ToBoolean(value, scriptContext) ? true : false);
  7952. }
  7953. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::value, &value, scriptContext))
  7954. {
  7955. descriptor->SetValue(value);
  7956. }
  7957. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::writable, &value, scriptContext))
  7958. {
  7959. descriptor->SetWritable(JavascriptConversion::ToBoolean(value, scriptContext) ? true : false);
  7960. }
  7961. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::get, &value, scriptContext))
  7962. {
  7963. if (JavascriptOperators::GetTypeId(value) != TypeIds_Undefined && (false == JavascriptConversion::IsCallable(value)))
  7964. {
  7965. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, scriptContext->GetPropertyName(PropertyIds::get)->GetBuffer());
  7966. }
  7967. descriptor->SetGetter(value);
  7968. }
  7969. if (JavascriptOperators::GetProperty(propertySpecObj, PropertyIds::set, &value, scriptContext))
  7970. {
  7971. if (JavascriptOperators::GetTypeId(value) != TypeIds_Undefined && (false == JavascriptConversion::IsCallable(value)))
  7972. {
  7973. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, scriptContext->GetPropertyName(PropertyIds::set)->GetBuffer());
  7974. }
  7975. descriptor->SetSetter(value);
  7976. }
  7977. return TRUE;
  7978. }
  7979. BOOL JavascriptOperators::ToPropertyDescriptor(Var propertySpec, PropertyDescriptor* descriptor, ScriptContext* scriptContext)
  7980. {
  7981. if (JavascriptProxy::Is(propertySpec) || (
  7982. RecyclableObject::Is(propertySpec) &&
  7983. JavascriptOperators::CheckIfPrototypeChainContainsProxyObject(RecyclableObject::FromVar(propertySpec)->GetPrototype())))
  7984. {
  7985. if (ToPropertyDescriptorForProxyObjects(propertySpec, descriptor, scriptContext) == FALSE)
  7986. {
  7987. return FALSE;
  7988. }
  7989. }
  7990. else
  7991. {
  7992. if (ToPropertyDescriptorForGenericObjects(propertySpec, descriptor, scriptContext) == FALSE)
  7993. {
  7994. return FALSE;
  7995. }
  7996. }
  7997. if (descriptor->GetterSpecified() || descriptor->SetterSpecified())
  7998. {
  7999. if (descriptor->ValueSpecified())
  8000. {
  8001. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_CannotHaveAccessorsAndValue);
  8002. }
  8003. if (descriptor->WritableSpecified())
  8004. {
  8005. int32 hCode = descriptor->IsWritable() ? JSERR_InvalidAttributeTrue : JSERR_InvalidAttributeFalse;
  8006. JavascriptError::ThrowTypeError(scriptContext, hCode, _u("writable"));
  8007. }
  8008. }
  8009. descriptor->SetOriginal(propertySpec);
  8010. return TRUE;
  8011. }
  8012. void JavascriptOperators::CompletePropertyDescriptor(PropertyDescriptor* resultDescriptor, PropertyDescriptor* likeDescriptor, ScriptContext* requestContext)
  8013. {
  8014. const PropertyDescriptor* likePropertyDescriptor = likeDescriptor;
  8015. // 1. Assert: LikeDesc is either a Property Descriptor or undefined.
  8016. // 2. ReturnIfAbrupt(Desc).
  8017. // 3. Assert : Desc is a Property Descriptor
  8018. // 4. If LikeDesc is undefined, then set LikeDesc to Record{ [[Value]]: undefined, [[Writable]] : false, [[Get]] : undefined, [[Set]] : undefined, [[Enumerable]] : false, [[Configurable]] : false }.
  8019. if (likePropertyDescriptor == nullptr)
  8020. {
  8021. likePropertyDescriptor = requestContext->GetLibrary()->GetDefaultPropertyDescriptor();
  8022. }
  8023. // 5. If either IsGenericDescriptor(Desc) or IsDataDescriptor(Desc) is true, then
  8024. if (resultDescriptor->IsDataDescriptor() || resultDescriptor->IsGenericDescriptor())
  8025. {
  8026. // a.If Desc does not have a[[Value]] field, then set Desc.[[Value]] to LikeDesc.[[Value]].
  8027. // b.If Desc does not have a[[Writable]] field, then set Desc.[[Writable]] to LikeDesc.[[Writable]].
  8028. if (!resultDescriptor->ValueSpecified())
  8029. {
  8030. resultDescriptor->SetValue(likePropertyDescriptor->GetValue());
  8031. }
  8032. if (!resultDescriptor->WritableSpecified())
  8033. {
  8034. resultDescriptor->SetWritable(likePropertyDescriptor->IsWritable());
  8035. }
  8036. }
  8037. else
  8038. {
  8039. // 6. Else,
  8040. // a.If Desc does not have a[[Get]] field, then set Desc.[[Get]] to LikeDesc.[[Get]].
  8041. // b.If Desc does not have a[[Set]] field, then set Desc.[[Set]] to LikeDesc.[[Set]].
  8042. if (!resultDescriptor->GetterSpecified())
  8043. {
  8044. resultDescriptor->SetGetter(likePropertyDescriptor->GetGetter());
  8045. }
  8046. if (!resultDescriptor->SetterSpecified())
  8047. {
  8048. resultDescriptor->SetSetter(likePropertyDescriptor->GetSetter());
  8049. }
  8050. }
  8051. // 7. If Desc does not have an[[Enumerable]] field, then set Desc.[[Enumerable]] to LikeDesc.[[Enumerable]].
  8052. // 8. If Desc does not have a[[Configurable]] field, then set Desc.[[Configurable]] to LikeDesc.[[Configurable]].
  8053. // 9. Return Desc.
  8054. if (!resultDescriptor->EnumerableSpecified())
  8055. {
  8056. resultDescriptor->SetEnumerable(likePropertyDescriptor->IsEnumerable());
  8057. }
  8058. if (!resultDescriptor->ConfigurableSpecified())
  8059. {
  8060. resultDescriptor->SetConfigurable(likePropertyDescriptor->IsConfigurable());
  8061. }
  8062. }
  8063. Var JavascriptOperators::OP_InvokePut(Js::ScriptContext *scriptContext, Var instance, CallInfo callInfo, ...)
  8064. {
  8065. // Handle a store to a call result: x(y) = z.
  8066. // This is not strictly permitted in JScript, but some scripts expect to be able to use
  8067. // the syntax to set properties of ActiveX objects.
  8068. // We handle this by deferring to a virtual method of type. This incurs an extra level of
  8069. // indirection but seems preferable to adding the "put" method as a member of every type
  8070. // and using the normal JScript calling mechanism.
  8071. RUNTIME_ARGUMENTS(args, callInfo);
  8072. AssertMsg(args.Info.Count > 0, "Missing this argument in InvokePut");
  8073. if (TaggedNumber::Is(instance))
  8074. {
  8075. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedFunction /* TODO-ERROR: get arg name - aFunc */);
  8076. }
  8077. RecyclableObject* function = RecyclableObject::FromVar(instance);
  8078. return function->InvokePut(args);
  8079. }
  8080. // Conformance to: ES5 8.6.1.
  8081. // Set attributes on the object as provided by property descriptor.
  8082. // If force parameter is true, we force SetAttributes call even if none of the attributes are defined by the descriptor.
  8083. // NOTE: does not set [[Get]], [Set]], [[Value]]
  8084. void JavascriptOperators::SetAttributes(RecyclableObject* object, PropertyId propId, const PropertyDescriptor& descriptor, bool force)
  8085. {
  8086. Assert(object);
  8087. BOOL isWritable = FALSE;
  8088. if (descriptor.IsDataDescriptor())
  8089. {
  8090. isWritable = descriptor.WritableSpecified() ? descriptor.IsWritable() : FALSE;
  8091. }
  8092. else if (descriptor.IsAccessorDescriptor())
  8093. {
  8094. // The reason is that JavascriptOperators::OP_SetProperty checks for RecyclableObject::FromVar(instance)->IsWritableOrAccessor(propertyId),
  8095. // which should in fact check for 'is writable or accessor' but since there is no GetAttributes, we can't do that efficiently.
  8096. isWritable = TRUE;
  8097. }
  8098. // CONSIDER: call object->SetAttributes which is much more efficient as that's 1 call instead of 3.
  8099. // Can't do that now as object->SetAttributes doesn't provide a way which attributes to modify and which not.
  8100. if (force || descriptor.ConfigurableSpecified())
  8101. {
  8102. object->SetConfigurable(propId, descriptor.ConfigurableSpecified() ? descriptor.IsConfigurable() : FALSE);
  8103. }
  8104. if (force || descriptor.EnumerableSpecified())
  8105. {
  8106. object->SetEnumerable(propId, descriptor.EnumerableSpecified() ? descriptor.IsEnumerable() : FALSE);
  8107. }
  8108. if (force || descriptor.WritableSpecified() || isWritable)
  8109. {
  8110. object->SetWritable(propId, isWritable);
  8111. }
  8112. }
  8113. void JavascriptOperators::OP_ClearAttributes(Var instance, PropertyId propertyId)
  8114. {
  8115. Assert(instance);
  8116. if (RecyclableObject::Is(instance))
  8117. {
  8118. RecyclableObject* obj = RecyclableObject::FromVar(instance);
  8119. obj->SetAttributes(propertyId, PropertyNone);
  8120. }
  8121. }
  8122. void JavascriptOperators::OP_Freeze(Var instance)
  8123. {
  8124. Assert(instance);
  8125. if (RecyclableObject::Is(instance))
  8126. {
  8127. RecyclableObject* obj = RecyclableObject::FromVar(instance);
  8128. obj->Freeze();
  8129. }
  8130. }
  8131. BOOL JavascriptOperators::Reject(bool throwOnError, ScriptContext* scriptContext, int32 errorCode, PropertyId propertyId)
  8132. {
  8133. Assert(scriptContext);
  8134. if (throwOnError)
  8135. {
  8136. JavascriptError::ThrowTypeError(scriptContext, errorCode, scriptContext->GetThreadContext()->GetPropertyName(propertyId)->GetBuffer());
  8137. }
  8138. return FALSE;
  8139. }
  8140. bool JavascriptOperators::AreSamePropertyDescriptors(const PropertyDescriptor* x, const PropertyDescriptor* y, ScriptContext* scriptContext)
  8141. {
  8142. Assert(scriptContext);
  8143. if (x->ConfigurableSpecified() != y->ConfigurableSpecified() || x->IsConfigurable() != y->IsConfigurable() ||
  8144. x->EnumerableSpecified() != y->EnumerableSpecified() || x->IsEnumerable() != y->IsEnumerable())
  8145. {
  8146. return false;
  8147. }
  8148. if (x->IsDataDescriptor())
  8149. {
  8150. if (!y->IsDataDescriptor() || x->WritableSpecified() != y->WritableSpecified() || x->IsWritable() != y->IsWritable())
  8151. {
  8152. return false;
  8153. }
  8154. if (x->ValueSpecified())
  8155. {
  8156. if (!y->ValueSpecified() || !JavascriptConversion::SameValue(x->GetValue(), y->GetValue()))
  8157. {
  8158. return false;
  8159. }
  8160. }
  8161. }
  8162. else if (x->IsAccessorDescriptor())
  8163. {
  8164. if (!y->IsAccessorDescriptor())
  8165. {
  8166. return false;
  8167. }
  8168. if (x->GetterSpecified())
  8169. {
  8170. if (!y->GetterSpecified() || !JavascriptConversion::SameValue(
  8171. JavascriptOperators::CanonicalizeAccessor(x->GetGetter(), scriptContext),
  8172. JavascriptOperators::CanonicalizeAccessor(y->GetGetter(), scriptContext)))
  8173. {
  8174. return false;
  8175. }
  8176. }
  8177. if (x->SetterSpecified())
  8178. {
  8179. if (!y->SetterSpecified() || !JavascriptConversion::SameValue(
  8180. JavascriptOperators::CanonicalizeAccessor(x->GetSetter(), scriptContext),
  8181. JavascriptOperators::CanonicalizeAccessor(y->GetSetter(), scriptContext)))
  8182. {
  8183. return false;
  8184. }
  8185. }
  8186. }
  8187. return true;
  8188. }
  8189. // Check if an accessor is undefined (null or defaultAccessor)
  8190. bool JavascriptOperators::IsUndefinedAccessor(Var accessor, ScriptContext* scriptContext)
  8191. {
  8192. return nullptr == accessor || scriptContext->GetLibrary()->GetDefaultAccessorFunction() == accessor;
  8193. }
  8194. // Converts default accessor to undefined.
  8195. // Can be used when comparing accessors.
  8196. Var JavascriptOperators::CanonicalizeAccessor(Var accessor, ScriptContext* scriptContext)
  8197. {
  8198. Assert(scriptContext);
  8199. if (IsUndefinedAccessor(accessor, scriptContext))
  8200. {
  8201. return scriptContext->GetLibrary()->GetUndefined();
  8202. }
  8203. return accessor;
  8204. }
  8205. Var JavascriptOperators::DefaultAccessor(RecyclableObject* function, CallInfo callInfo, ...)
  8206. {
  8207. return function->GetLibrary()->GetUndefined();
  8208. }
  8209. void FrameDisplay::SetItem(uint index, void* item)
  8210. {
  8211. AssertMsg(index < this->length, "Invalid frame display access");
  8212. scopes[index] = item;
  8213. }
  8214. void *FrameDisplay::GetItem(uint index)
  8215. {
  8216. AssertMsg(index < this->length, "Invalid frame display access");
  8217. return scopes[index];
  8218. }
  8219. // Grab the "this" pointer, mapping a root object to its associated host object.
  8220. Var JavascriptOperators::RootToThisObject(const Var object, ScriptContext* scriptContext)
  8221. {
  8222. Js::Var thisVar = object;
  8223. TypeId typeId = Js::JavascriptOperators::GetTypeId(thisVar);
  8224. switch (typeId)
  8225. {
  8226. case Js::TypeIds_GlobalObject:
  8227. return ((Js::GlobalObject*)thisVar)->ToThis();
  8228. case Js::TypeIds_ModuleRoot:
  8229. return Js::JavascriptOperators::GetThisFromModuleRoot(thisVar);
  8230. default:
  8231. if (typeId == scriptContext->GetDirectHostTypeId())
  8232. {
  8233. return ((RecyclableObject*)thisVar)->GetLibrary()->GetGlobalObject()->ToThis();
  8234. }
  8235. }
  8236. return thisVar;
  8237. }
  8238. Var JavascriptOperators::CallGetter(RecyclableObject * const function, Var const object, ScriptContext * requestContext)
  8239. {
  8240. #if ENABLE_TTD_DEBUGGING
  8241. if(requestContext->ShouldSuppressGetterInvocationForDebuggerEvaluation())
  8242. {
  8243. return requestContext->GetLibrary()->GetUndefined();
  8244. }
  8245. #endif
  8246. ScriptContext * scriptContext = function->GetScriptContext();
  8247. ThreadContext * threadContext = scriptContext->GetThreadContext();
  8248. return threadContext->ExecuteImplicitCall(function, ImplicitCall_Accessor, [=]() -> Js::Var
  8249. {
  8250. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  8251. // Stack numbers are ok, as we will call ToObject to wrap it in a number object anyway
  8252. // See JavascriptOperators::GetThisHelper
  8253. Assert(JavascriptOperators::GetTypeId(object) == TypeIds_Integer ||
  8254. JavascriptOperators::GetTypeId(object) == TypeIds_Number ||
  8255. threadContext->HasNoSideEffect(function) ||
  8256. !ThreadContext::IsOnStack(object));
  8257. // Verify that the scriptcontext is alive before firing getter/setter
  8258. if (!scriptContext->VerifyAlive(!function->IsExternal(), requestContext))
  8259. {
  8260. return nullptr;
  8261. }
  8262. CallFlags flags = CallFlags_Value;
  8263. Var thisVar = RootToThisObject(object, scriptContext);
  8264. RecyclableObject* marshalledFunction = RecyclableObject::FromVar(CrossSite::MarshalVar(requestContext, function));
  8265. Var result = CALL_ENTRYPOINT(marshalledFunction->GetEntryPoint(), function, CallInfo(flags, 1), thisVar);
  8266. result = CrossSite::MarshalVar(requestContext, result);
  8267. return result;
  8268. });
  8269. }
  8270. void JavascriptOperators::CallSetter(RecyclableObject * const function, Var const object, Var const value, ScriptContext * requestContext)
  8271. {
  8272. ScriptContext * scriptContext = function->GetScriptContext();
  8273. ThreadContext * threadContext = scriptContext->GetThreadContext();
  8274. threadContext->ExecuteImplicitCall(function, ImplicitCall_Accessor, [=]() -> Js::Var
  8275. {
  8276. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  8277. // Stack numbers are ok, as we will call ToObject to wrap it in a number object anyway
  8278. // See JavascriptOperators::GetThisHelper
  8279. Assert(JavascriptOperators::GetTypeId(object) == TypeIds_Integer ||
  8280. JavascriptOperators::GetTypeId(object) == TypeIds_Number || !ThreadContext::IsOnStack(object));
  8281. // Verify that the scriptcontext is alive before firing getter/setter
  8282. if (!scriptContext->VerifyAlive(!function->IsExternal(), requestContext))
  8283. {
  8284. return nullptr;
  8285. }
  8286. CallFlags flags = CallFlags_Value;
  8287. Var putValue = value;
  8288. // CONSIDER: Have requestContext everywhere, even in the setProperty related codepath.
  8289. if (requestContext)
  8290. {
  8291. putValue = CrossSite::MarshalVar(requestContext, value);
  8292. }
  8293. Var thisVar = RootToThisObject(object, scriptContext);
  8294. RecyclableObject* marshalledFunction = function;
  8295. if (requestContext)
  8296. {
  8297. marshalledFunction = RecyclableObject::FromVar(CrossSite::MarshalVar(requestContext, function));
  8298. }
  8299. Var result = CALL_ENTRYPOINT(marshalledFunction->GetEntryPoint(), function, CallInfo(flags, 2), thisVar, putValue);
  8300. Assert(result);
  8301. return nullptr;
  8302. });
  8303. }
  8304. void * JavascriptOperators::AllocMemForVarArray(size_t size, Recycler* recycler)
  8305. {
  8306. TRACK_ALLOC_INFO(recycler, Js::Var, Recycler, 0, (size_t)(size / sizeof(Js::Var)));
  8307. return recycler->AllocZero(size);
  8308. }
  8309. void * JavascriptOperators::AllocUninitializedNumber(Js::RecyclerJavascriptNumberAllocator * allocator)
  8310. {
  8311. TRACK_ALLOC_INFO(allocator->GetRecycler(), Js::JavascriptNumber, Recycler, 0, (size_t)-1);
  8312. return allocator->Alloc(sizeof(Js::JavascriptNumber));
  8313. }
  8314. void JavascriptOperators::ScriptAbort()
  8315. {
  8316. throw ScriptAbortException();
  8317. }
  8318. void PolymorphicInlineCache::Finalize(bool isShutdown)
  8319. {
  8320. if (size == 0)
  8321. {
  8322. // Already finalized
  8323. Assert(!inlineCaches && !prev && !next);
  8324. return;
  8325. }
  8326. Assert(inlineCaches && size > 0);
  8327. // If we're not shutting down (as in closing the script context), we need to remove our inline caches from
  8328. // thread context's invalidation lists, and release memory back to the arena. During script context shutdown,
  8329. // we leave everything in place, because the inline cache arena will stay alive until script context is destroyed
  8330. // (as in destructor has been called) and thus the invalidation lists are safe to keep references to caches from this
  8331. // script context. We will, however, zero all inline caches so that we don't have to process them on subsequent
  8332. // collections, which may still happen from other script contexts.
  8333. if (isShutdown)
  8334. {
  8335. memset(inlineCaches, 0, size * sizeof(InlineCache));
  8336. }
  8337. else
  8338. {
  8339. for (int i = 0; i < size; i++)
  8340. {
  8341. inlineCaches[i].RemoveFromInvalidationList();
  8342. }
  8343. AllocatorDeleteArray(InlineCacheAllocator, functionBody->GetScriptContext()->GetInlineCacheAllocator(), size, inlineCaches);
  8344. #ifdef POLY_INLINE_CACHE_SIZE_STATS
  8345. functionBody->GetScriptContext()->GetInlineCacheAllocator()->LogPolyCacheFree(size * sizeof(InlineCache));
  8346. #endif
  8347. }
  8348. // Remove this PolymorphicInlineCache from the list
  8349. if (this == functionBody->GetPolymorphicInlineCachesHead())
  8350. {
  8351. Assert(!prev);
  8352. if (next)
  8353. {
  8354. Assert(next->prev == this);
  8355. next->prev = nullptr;
  8356. }
  8357. functionBody->SetPolymorphicInlineCachesHead(next);
  8358. }
  8359. else
  8360. {
  8361. if (prev)
  8362. {
  8363. Assert(prev->next == this);
  8364. prev->next = next;
  8365. }
  8366. if (next)
  8367. {
  8368. Assert(next->prev == this);
  8369. next->prev = prev;
  8370. }
  8371. }
  8372. prev = next = nullptr;
  8373. inlineCaches = nullptr;
  8374. size = 0;
  8375. }
  8376. JavascriptString * JavascriptOperators::Concat3(Var aLeft, Var aCenter, Var aRight, ScriptContext * scriptContext)
  8377. {
  8378. // Make sure we do the conversion in order from left to right
  8379. JavascriptString * strLeft = JavascriptConversion::ToPrimitiveString(aLeft, scriptContext);
  8380. JavascriptString * strCenter = JavascriptConversion::ToPrimitiveString(aCenter, scriptContext);
  8381. JavascriptString * strRight = JavascriptConversion::ToPrimitiveString(aRight, scriptContext);
  8382. return JavascriptString::Concat3(strLeft, strCenter, strRight);
  8383. }
  8384. JavascriptString *
  8385. JavascriptOperators::NewConcatStrMulti(Var a1, Var a2, uint count, ScriptContext * scriptContext)
  8386. {
  8387. // Make sure we do the conversion in order
  8388. JavascriptString * str1 = JavascriptConversion::ToPrimitiveString(a1, scriptContext);
  8389. JavascriptString * str2 = JavascriptConversion::ToPrimitiveString(a2, scriptContext);
  8390. return ConcatStringMulti::New(count, str1, str2, scriptContext);
  8391. }
  8392. void
  8393. JavascriptOperators::SetConcatStrMultiItem(Var concatStr, Var str, uint index, ScriptContext * scriptContext)
  8394. {
  8395. ConcatStringMulti::FromVar(concatStr)->SetItem(index,
  8396. JavascriptConversion::ToPrimitiveString(str, scriptContext));
  8397. }
  8398. void
  8399. JavascriptOperators::SetConcatStrMultiItem2(Var concatStr, Var str1, Var str2, uint index, ScriptContext * scriptContext)
  8400. {
  8401. ConcatStringMulti * cs = ConcatStringMulti::FromVar(concatStr);
  8402. cs->SetItem(index, JavascriptConversion::ToPrimitiveString(str1, scriptContext));
  8403. cs->SetItem(index + 1, JavascriptConversion::ToPrimitiveString(str2, scriptContext));
  8404. }
  8405. void JavascriptOperators::OP_SetComputedNameVar(Var method, Var computedNameVar)
  8406. {
  8407. ScriptFunctionBase *scriptFunction = ScriptFunctionBase::FromVar(method);
  8408. scriptFunction->SetComputedNameVar(computedNameVar);
  8409. }
  8410. void JavascriptOperators::OP_SetHomeObj(Var method, Var homeObj)
  8411. {
  8412. ScriptFunctionBase *scriptFunction = ScriptFunctionBase::FromVar(method);
  8413. scriptFunction->SetHomeObj(homeObj);
  8414. }
  8415. Var JavascriptOperators::OP_LdSuper(Var scriptFunction, ScriptContext * scriptContext)
  8416. {
  8417. // Ensure this is not a stack ScriptFunction
  8418. if (!ScriptFunction::Is(scriptFunction) || ThreadContext::IsOnStack(scriptFunction))
  8419. {
  8420. return scriptContext->GetLibrary()->GetUndefined();
  8421. }
  8422. ScriptFunction *instance = ScriptFunction::FromVar(scriptFunction);
  8423. // We keep a reference to the current class rather than its super prototype
  8424. // since the prototype could change.
  8425. Var homeObj = instance->GetHomeObj();
  8426. if (homeObj == nullptr || !RecyclableObject::Is(homeObj))
  8427. {
  8428. return scriptContext->GetLibrary()->GetUndefined();
  8429. }
  8430. RecyclableObject *thisObjPrototype = RecyclableObject::FromVar(homeObj);
  8431. Assert(thisObjPrototype != nullptr);
  8432. RecyclableObject *superBase = thisObjPrototype->GetPrototype();
  8433. if (superBase == nullptr || !RecyclableObject::Is(superBase))
  8434. {
  8435. return scriptContext->GetLibrary()->GetUndefined();
  8436. }
  8437. return superBase;
  8438. }
  8439. Var JavascriptOperators::OP_LdSuperCtor(Var scriptFunction, ScriptContext * scriptContext)
  8440. {
  8441. // use self as value of [[FunctionObject]] - this is true only for constructors
  8442. Assert(RecyclableObject::Is(scriptFunction));
  8443. Assert(JavascriptOperators::IsClassConstructor(scriptFunction)); // non-constructors cannot have direct super
  8444. RecyclableObject *superCtor = RecyclableObject::FromVar(scriptFunction)->GetPrototype();
  8445. if (superCtor == nullptr || !IsConstructor(superCtor))
  8446. {
  8447. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor);
  8448. }
  8449. return superCtor;
  8450. }
  8451. Var JavascriptOperators::ScopedLdSuperHelper(Var scriptFunction, Js::PropertyId propertyId, ScriptContext * scriptContext)
  8452. {
  8453. ScriptFunction *instance = ScriptFunction::FromVar(scriptFunction);
  8454. Var superRef = nullptr;
  8455. FrameDisplay *frameDisplay = instance->GetEnvironment();
  8456. if (frameDisplay->GetLength() == 0)
  8457. {
  8458. // Globally scoped evals are a syntax error
  8459. JavascriptError::ThrowSyntaxError(scriptContext, ERRSuperInGlobalEval, _u("super"));
  8460. }
  8461. // Iterate over the scopes in the FrameDisplay, looking for the super property.
  8462. for (unsigned i = 0; i < frameDisplay->GetLength(); ++i)
  8463. {
  8464. void *currScope = frameDisplay->GetItem(i);
  8465. if (RecyclableObject::Is(currScope))
  8466. {
  8467. if (BlockActivationObject::Is(currScope))
  8468. {
  8469. // We won't find super in a block scope.
  8470. continue;
  8471. }
  8472. RecyclableObject *recyclableObject = RecyclableObject::FromVar(currScope);
  8473. if (GetProperty(recyclableObject, propertyId, &superRef, scriptContext))
  8474. {
  8475. return superRef;
  8476. }
  8477. if (HasProperty(recyclableObject, Js::PropertyIds::_lexicalThisSlotSymbol))
  8478. {
  8479. // If we reach 'this' and haven't found the super reference, we don't need to look any further.
  8480. JavascriptError::ThrowReferenceError(scriptContext, JSERR_BadSuperReference, _u("super"));
  8481. }
  8482. }
  8483. }
  8484. // We didn't find a super reference. Emit a reference error.
  8485. JavascriptError::ThrowReferenceError(scriptContext, JSERR_BadSuperReference, _u("super"));
  8486. }
  8487. Var JavascriptOperators::OP_ScopedLdSuper(Var scriptFunction, ScriptContext * scriptContext)
  8488. {
  8489. return JavascriptOperators::ScopedLdSuperHelper(scriptFunction, Js::PropertyIds::_superReferenceSymbol, scriptContext);
  8490. }
  8491. Var JavascriptOperators::OP_ScopedLdSuperCtor(Var scriptFunction, ScriptContext * scriptContext)
  8492. {
  8493. return JavascriptOperators::ScopedLdSuperHelper(scriptFunction, Js::PropertyIds::_superCtorReferenceSymbol, scriptContext);
  8494. }
  8495. Var JavascriptOperators::OP_ResumeYield(ResumeYieldData* yieldData, RecyclableObject* iterator)
  8496. {
  8497. bool isNext = yieldData->exceptionObj == nullptr;
  8498. bool isThrow = !isNext && !yieldData->exceptionObj->IsGeneratorReturnException();
  8499. if (iterator != nullptr) // yield*
  8500. {
  8501. ScriptContext* scriptContext = iterator->GetScriptContext();
  8502. PropertyId propertyId = isNext ? PropertyIds::next : isThrow ? PropertyIds::throw_ : PropertyIds::return_;
  8503. Var prop = JavascriptOperators::GetProperty(iterator, propertyId, scriptContext);
  8504. if (!isNext && JavascriptOperators::IsUndefinedOrNull(prop))
  8505. {
  8506. if (isThrow)
  8507. {
  8508. // 5.b.iii.2
  8509. // NOTE: If iterator does not have a throw method, this throw is going to terminate the yield* loop.
  8510. // But first we need to give iterator a chance to clean up.
  8511. prop = JavascriptOperators::GetProperty(iterator, PropertyIds::return_, scriptContext);
  8512. if (!JavascriptOperators::IsUndefinedOrNull(prop))
  8513. {
  8514. if (!JavascriptConversion::IsCallable(prop))
  8515. {
  8516. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, _u("return"));
  8517. }
  8518. RecyclableObject* method = RecyclableObject::FromVar(prop);
  8519. Var args[] = { iterator, yieldData->data };
  8520. CallInfo callInfo(CallFlags_Value, _countof(args));
  8521. Var result = JavascriptFunction::CallFunction<true>(method, method->GetEntryPoint(), Arguments(callInfo, args));
  8522. if (!JavascriptOperators::IsObject(result))
  8523. {
  8524. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  8525. }
  8526. }
  8527. // 5.b.iii.3
  8528. // NOTE: The next step throws a TypeError to indicate that there was a yield* protocol violation:
  8529. // iterator does not have a throw method.
  8530. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, _u("throw"));
  8531. }
  8532. // Do not use ThrowExceptionObject for return() API exceptions since these exceptions are not real exceptions
  8533. throw yieldData->exceptionObj;
  8534. }
  8535. if (!JavascriptConversion::IsCallable(prop))
  8536. {
  8537. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction, isNext ? _u("next") : isThrow ? _u("throw") : _u("return"));
  8538. }
  8539. RecyclableObject* method = RecyclableObject::FromVar(prop);
  8540. Var args[] = { iterator, yieldData->data };
  8541. CallInfo callInfo(CallFlags_Value, _countof(args));
  8542. Var result = JavascriptFunction::CallFunction<true>(method, method->GetEntryPoint(), Arguments(callInfo, args));
  8543. if (!JavascriptOperators::IsObject(result))
  8544. {
  8545. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  8546. }
  8547. if (isThrow || isNext)
  8548. {
  8549. // 5.b.ii.2
  8550. // NOTE: Exceptions from the inner iterator throw method are propagated.
  8551. // Normal completions from an inner throw method are processed similarly to an inner next.
  8552. return result;
  8553. }
  8554. RecyclableObject* obj = RecyclableObject::FromVar(result);
  8555. Var done = JavascriptOperators::GetProperty(obj, PropertyIds::done, scriptContext);
  8556. if (done == iterator->GetLibrary()->GetTrue())
  8557. {
  8558. Var value = JavascriptOperators::GetProperty(obj, PropertyIds::value, scriptContext);
  8559. yieldData->exceptionObj->SetThrownObject(value);
  8560. // Do not use ThrowExceptionObject for return() API exceptions since these exceptions are not real exceptions
  8561. throw yieldData->exceptionObj;
  8562. }
  8563. return result;
  8564. }
  8565. // CONSIDER: Fast path this early out return path in JITed code before helper call to avoid the helper call overhead in the common case e.g. next() calls.
  8566. if (isNext)
  8567. {
  8568. return yieldData->data;
  8569. }
  8570. if (isThrow)
  8571. {
  8572. // Use ThrowExceptionObject() to get debugger support for breaking on throw
  8573. JavascriptExceptionOperators::ThrowExceptionObject(yieldData->exceptionObj, yieldData->exceptionObj->GetScriptContext(), true);
  8574. }
  8575. // CONSIDER: Using an exception to carry the return value and force finally code to execute is a bit of a janky
  8576. // solution since we have to override the value here in the case of yield* expressions. It works but is there
  8577. // a more elegant way?
  8578. //
  8579. // Instead what if ResumeYield was a "set Dst then optionally branch" opcode, that could also throw? Then we could
  8580. // avoid using a special exception entirely with byte code something like this:
  8581. //
  8582. // ;; Ry is the yieldData
  8583. //
  8584. // ResumeYield Rx Ry $returnPathLabel
  8585. // ... code like normal
  8586. // $returnPathLabel:
  8587. // Ld_A R0 Rx
  8588. // Br $exitFinallyAndReturn
  8589. //
  8590. // This would probably give better performance for the common case of calling next() on generators since we wouldn't
  8591. // have to wrap the call to the generator code in a try catch.
  8592. // Do not use ThrowExceptionObject for return() API exceptions since these exceptions are not real exceptions
  8593. throw yieldData->exceptionObj;
  8594. }
  8595. Js::Var
  8596. JavascriptOperators::BoxStackInstance(Js::Var instance, ScriptContext * scriptContext, bool allowStackFunction)
  8597. {
  8598. if (!ThreadContext::IsOnStack(instance) || (allowStackFunction && !TaggedNumber::Is(instance) && (*(int*)instance & 1)))
  8599. {
  8600. return instance;
  8601. }
  8602. TypeId typeId = JavascriptOperators::GetTypeId(instance);
  8603. switch (typeId)
  8604. {
  8605. case Js::TypeIds_Number:
  8606. #if !FLOATVAR
  8607. return JavascriptNumber::BoxStackInstance(instance, scriptContext);
  8608. #endif
  8609. // fall-through
  8610. case Js::TypeIds_Integer:
  8611. return instance;
  8612. case Js::TypeIds_RegEx:
  8613. return JavascriptRegExp::BoxStackInstance(JavascriptRegExp::FromVar(instance));
  8614. case Js::TypeIds_Object:
  8615. return DynamicObject::BoxStackInstance(DynamicObject::FromVar(instance));
  8616. case Js::TypeIds_Array:
  8617. return JavascriptArray::BoxStackInstance(JavascriptArray::FromVar(instance));
  8618. case Js::TypeIds_NativeIntArray:
  8619. return JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray::FromVar(instance));
  8620. case Js::TypeIds_NativeFloatArray:
  8621. return JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray::FromVar(instance));
  8622. case Js::TypeIds_Function:
  8623. Assert(allowStackFunction);
  8624. // Stack functions are deal with not mar mark them, but by nested function escape analysis
  8625. // in the front end. No need to box here.
  8626. return instance;
  8627. #if ENABLE_COPYONACCESS_ARRAY
  8628. case Js::TypeIds_CopyOnAccessNativeIntArray:
  8629. Assert(false);
  8630. // fall-through
  8631. #endif
  8632. default:
  8633. Assert(false);
  8634. return instance;
  8635. };
  8636. }
  8637. ImplicitCallFlags
  8638. JavascriptOperators::CacheAndClearImplicitBit(ScriptContext* scriptContext)
  8639. {
  8640. ImplicitCallFlags prevImplicitCallFlags = scriptContext->GetThreadContext()->GetImplicitCallFlags();
  8641. scriptContext->GetThreadContext()->ClearImplicitCallFlags();
  8642. return prevImplicitCallFlags;
  8643. }
  8644. ImplicitCallFlags
  8645. JavascriptOperators::CheckAndUpdateFunctionBodyWithImplicitFlag(FunctionBody* functionBody)
  8646. {
  8647. ScriptContext* scriptContext = functionBody->GetScriptContext();
  8648. ImplicitCallFlags currImplicitCallFlags = scriptContext->GetThreadContext()->GetImplicitCallFlags();
  8649. if ((currImplicitCallFlags > ImplicitCall_None))
  8650. {
  8651. functionBody->SetHasOnlyThisStmts(false);
  8652. }
  8653. return currImplicitCallFlags;
  8654. }
  8655. void
  8656. JavascriptOperators::RestoreImplicitFlag(ScriptContext* scriptContext, ImplicitCallFlags prevImplicitCallFlags, ImplicitCallFlags currImplicitCallFlags)
  8657. {
  8658. scriptContext->GetThreadContext()->SetImplicitCallFlags((ImplicitCallFlags)(prevImplicitCallFlags | currImplicitCallFlags));
  8659. }
  8660. FunctionProxy*
  8661. JavascriptOperators::GetDeferredDeserializedFunctionProxy(JavascriptFunction* func)
  8662. {
  8663. FunctionProxy* proxy = func->GetFunctionProxy();
  8664. if (proxy->GetFunctionProxy() != proxy)
  8665. {
  8666. proxy = proxy->GetFunctionProxy();
  8667. }
  8668. return proxy;
  8669. }
  8670. template <>
  8671. Js::Var JavascriptOperators::GetElementAtIndex(Js::JavascriptArray* arrayObject, UINT index, Js::ScriptContext* scriptContext)
  8672. {
  8673. Js::Var result;
  8674. if (Js::JavascriptOperators::OP_GetElementI_ArrayFastPath(arrayObject, index, &result, scriptContext))
  8675. {
  8676. return result;
  8677. }
  8678. return scriptContext->GetMissingItemResult();
  8679. }
  8680. template<>
  8681. Js::Var JavascriptOperators::GetElementAtIndex(Js::JavascriptNativeIntArray* arrayObject, UINT index, Js::ScriptContext* scriptContext)
  8682. {
  8683. Js::Var result;
  8684. if (Js::JavascriptOperators::OP_GetElementI_ArrayFastPath(arrayObject, index, &result, scriptContext))
  8685. {
  8686. return result;
  8687. }
  8688. return scriptContext->GetMissingItemResult();
  8689. }
  8690. template<>
  8691. Js::Var JavascriptOperators::GetElementAtIndex(Js::JavascriptNativeFloatArray* arrayObject, UINT index, Js::ScriptContext* scriptContext)
  8692. {
  8693. Js::Var result;
  8694. if (Js::JavascriptOperators::OP_GetElementI_ArrayFastPath(arrayObject, index, &result, scriptContext))
  8695. {
  8696. return result;
  8697. }
  8698. return scriptContext->GetMissingItemResult();
  8699. }
  8700. template<>
  8701. Js::Var JavascriptOperators::GetElementAtIndex(Js::Var* arrayObject, UINT index, Js::ScriptContext* scriptContext)
  8702. {
  8703. return Js::JavascriptOperators::OP_GetElementI_Int32(*arrayObject, index, scriptContext);
  8704. }
  8705. template<typename T>
  8706. void JavascriptOperators::ObjectToNativeArray(T* arrayObject,
  8707. JsNativeValueType valueType,
  8708. __in UINT length,
  8709. __in UINT elementSize,
  8710. __out_bcount(length*elementSize) byte* buffer,
  8711. Js::ScriptContext* scriptContext)
  8712. {
  8713. Var element;
  8714. uint64 allocSize = length * elementSize;
  8715. // TODO:further fast path the call for things like IntArray convert to int, floatarray convert to float etc.
  8716. // such that we don't need boxing.
  8717. switch (valueType)
  8718. {
  8719. case JsInt8Type:
  8720. AnalysisAssert(elementSize == sizeof(int8));
  8721. for (UINT i = 0; i < length; i++)
  8722. {
  8723. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8724. AnalysisAssert((i + 1) * sizeof(int8) <= allocSize);
  8725. #pragma prefast(suppress:22102)
  8726. ((int8*)buffer)[i] = Js::JavascriptConversion::ToInt8(element, scriptContext);
  8727. }
  8728. break;
  8729. case JsUint8Type:
  8730. AnalysisAssert(elementSize == sizeof(uint8));
  8731. for (UINT i = 0; i < length; i++)
  8732. {
  8733. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8734. AnalysisAssert((i + 1) * sizeof(uint8) <= allocSize);
  8735. ((uint8*)buffer)[i] = Js::JavascriptConversion::ToUInt8(element, scriptContext);
  8736. }
  8737. break;
  8738. case JsInt16Type:
  8739. AnalysisAssert(elementSize == sizeof(int16));
  8740. for (UINT i = 0; i < length; i++)
  8741. {
  8742. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8743. AnalysisAssert((i + 1) * sizeof(int16) <= allocSize);
  8744. ((int16*)buffer)[i] = Js::JavascriptConversion::ToInt16(element, scriptContext);
  8745. }
  8746. break;
  8747. case JsUint16Type:
  8748. AnalysisAssert(elementSize == sizeof(uint16));
  8749. for (UINT i = 0; i < length; i++)
  8750. {
  8751. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8752. AnalysisAssert((i + 1) * sizeof(uint16) <= allocSize);
  8753. ((uint16*)buffer)[i] = Js::JavascriptConversion::ToUInt16(element, scriptContext);
  8754. }
  8755. break;
  8756. case JsInt32Type:
  8757. AnalysisAssert(elementSize == sizeof(int32));
  8758. for (UINT i = 0; i < length; i++)
  8759. {
  8760. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8761. AnalysisAssert((i + 1) * sizeof(int32) <= allocSize);
  8762. ((int32*)buffer)[i] = Js::JavascriptConversion::ToInt32(element, scriptContext);
  8763. }
  8764. break;
  8765. case JsUint32Type:
  8766. AnalysisAssert(elementSize == sizeof(uint32));
  8767. for (UINT i = 0; i < length; i++)
  8768. {
  8769. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8770. AnalysisAssert((i + 1) * sizeof(uint32) <= allocSize);
  8771. ((uint32*)buffer)[i] = Js::JavascriptConversion::ToUInt32(element, scriptContext);
  8772. }
  8773. break;
  8774. case JsInt64Type:
  8775. AnalysisAssert(elementSize == sizeof(int64));
  8776. for (UINT i = 0; i < length; i++)
  8777. {
  8778. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8779. AnalysisAssert((i + 1) * sizeof(int64) <= allocSize);
  8780. ((int64*)buffer)[i] = Js::JavascriptConversion::ToInt64(element, scriptContext);
  8781. }
  8782. break;
  8783. case JsUint64Type:
  8784. AnalysisAssert(elementSize == sizeof(uint64));
  8785. for (UINT i = 0; i < length; i++)
  8786. {
  8787. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8788. AnalysisAssert((i + 1) * sizeof(uint64) <= allocSize);
  8789. ((uint64*)buffer)[i] = Js::JavascriptConversion::ToUInt64(element, scriptContext);
  8790. }
  8791. break;
  8792. case JsFloatType:
  8793. AnalysisAssert(elementSize == sizeof(float));
  8794. for (UINT i = 0; i < length; i++)
  8795. {
  8796. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8797. AnalysisAssert((i + 1) * sizeof(float) <= allocSize);
  8798. ((float*)buffer)[i] = Js::JavascriptConversion::ToFloat(element, scriptContext);
  8799. }
  8800. break;
  8801. case JsDoubleType:
  8802. AnalysisAssert(elementSize == sizeof(double));
  8803. for (UINT i = 0; i < length; i++)
  8804. {
  8805. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8806. AnalysisAssert((i + 1) * sizeof(double) <= allocSize);
  8807. ((double*)buffer)[i] = Js::JavascriptConversion::ToNumber(element, scriptContext);
  8808. }
  8809. break;
  8810. case JsNativeStringType:
  8811. AnalysisAssert(elementSize == sizeof(JsNativeString));
  8812. for (UINT i = 0; i < length; i++)
  8813. {
  8814. element = GetElementAtIndex(arrayObject, i, scriptContext);
  8815. AnalysisAssert((i + 1) * sizeof(JsNativeString) <= allocSize);
  8816. Js::JavascriptString* string = Js::JavascriptConversion::ToString(element, scriptContext);
  8817. (((JsNativeString*)buffer)[i]).str = string->GetSz();
  8818. (((JsNativeString*)buffer)[i]).length = string->GetLength();
  8819. }
  8820. break;
  8821. default:
  8822. Assert(FALSE);
  8823. }
  8824. }
  8825. void JavascriptOperators::VarToNativeArray(Var arrayObject,
  8826. JsNativeValueType valueType,
  8827. __in UINT length,
  8828. __in UINT elementSize,
  8829. __out_bcount(length*elementSize) byte* buffer,
  8830. Js::ScriptContext* scriptContext)
  8831. {
  8832. Js::DynamicObject* dynamicObject = DynamicObject::FromVar(arrayObject);
  8833. if (dynamicObject->IsCrossSiteObject() || Js::TaggedInt::IsOverflow(length))
  8834. {
  8835. Js::JavascriptOperators::ObjectToNativeArray(&arrayObject, valueType, length, elementSize, buffer, scriptContext);
  8836. }
  8837. else
  8838. {
  8839. #if ENABLE_COPYONACCESS_ARRAY
  8840. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayObject);
  8841. #endif
  8842. switch (Js::JavascriptOperators::GetTypeId(arrayObject))
  8843. {
  8844. case TypeIds_Array:
  8845. Js::JavascriptOperators::ObjectToNativeArray(Js::JavascriptArray::FromVar(arrayObject), valueType, length, elementSize, buffer, scriptContext);
  8846. break;
  8847. case TypeIds_NativeFloatArray:
  8848. Js::JavascriptOperators::ObjectToNativeArray(Js::JavascriptNativeFloatArray::FromVar(arrayObject), valueType, length, elementSize, buffer, scriptContext);
  8849. break;
  8850. case TypeIds_NativeIntArray:
  8851. Js::JavascriptOperators::ObjectToNativeArray(Js::JavascriptNativeIntArray::FromVar(arrayObject), valueType, length, elementSize, buffer, scriptContext);
  8852. break;
  8853. // We can have more specialized template if needed.
  8854. default:
  8855. Js::JavascriptOperators::ObjectToNativeArray(&arrayObject, valueType, length, elementSize, buffer, scriptContext);
  8856. }
  8857. }
  8858. }
  8859. // SpeciesConstructor abstract operation as described in ES6.0 Section 7.3.20
  8860. Var JavascriptOperators::SpeciesConstructor(RecyclableObject* object, Var defaultConstructor, ScriptContext* scriptContext)
  8861. {
  8862. //1.Assert: Type(O) is Object.
  8863. Assert(JavascriptOperators::IsObject(object));
  8864. //2.Let C be Get(O, "constructor").
  8865. //3.ReturnIfAbrupt(C).
  8866. Var constructor = JavascriptOperators::GetProperty(object, PropertyIds::constructor, scriptContext);
  8867. if (scriptContext->GetConfig()->IsES6SpeciesEnabled())
  8868. {
  8869. //4.If C is undefined, return defaultConstructor.
  8870. if (JavascriptOperators::IsUndefinedObject(constructor))
  8871. {
  8872. return defaultConstructor;
  8873. }
  8874. //5.If Type(C) is not Object, throw a TypeError exception.
  8875. if (!JavascriptOperators::IsObject(constructor))
  8876. {
  8877. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject, _u("[constructor]"));
  8878. }
  8879. //6.Let S be Get(C, @@species).
  8880. //7.ReturnIfAbrupt(S).
  8881. Var species = nullptr;
  8882. if (!JavascriptOperators::GetProperty(RecyclableObject::FromVar(constructor), PropertyIds::_symbolSpecies, &species, scriptContext)
  8883. || JavascriptOperators::IsUndefinedOrNull(species))
  8884. {
  8885. //8.If S is either undefined or null, return defaultConstructor.
  8886. return defaultConstructor;
  8887. }
  8888. constructor = species;
  8889. }
  8890. //9.If IsConstructor(S) is true, return S.
  8891. if (JavascriptOperators::IsConstructor(constructor))
  8892. {
  8893. return constructor;
  8894. }
  8895. //10.Throw a TypeError exception.
  8896. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  8897. }
  8898. BOOL JavascriptOperators::GreaterEqual(Var aLeft, Var aRight, ScriptContext* scriptContext)
  8899. {
  8900. if (TaggedInt::Is(aLeft))
  8901. {
  8902. if (TaggedInt::Is(aRight))
  8903. {
  8904. // Works whether it is TaggedInt31 or TaggedInt32
  8905. return ::Math::PointerCastToIntegralTruncate<int>(aLeft) >= ::Math::PointerCastToIntegralTruncate<int>(aRight);
  8906. }
  8907. if (JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  8908. {
  8909. return TaggedInt::ToDouble(aLeft) >= JavascriptNumber::GetValue(aRight);
  8910. }
  8911. }
  8912. else if (TaggedInt::Is(aRight))
  8913. {
  8914. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft))
  8915. {
  8916. return JavascriptNumber::GetValue(aLeft) >= TaggedInt::ToDouble(aRight);
  8917. }
  8918. }
  8919. else
  8920. {
  8921. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft) && JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  8922. {
  8923. return JavascriptNumber::GetValue(aLeft) >= JavascriptNumber::GetValue(aRight);
  8924. }
  8925. }
  8926. return !RelationalComparisonHelper(aLeft, aRight, scriptContext, true, true);
  8927. }
  8928. BOOL JavascriptOperators::LessEqual(Var aLeft, Var aRight, ScriptContext* scriptContext)
  8929. {
  8930. if (TaggedInt::Is(aLeft))
  8931. {
  8932. if (TaggedInt::Is(aRight))
  8933. {
  8934. // Works whether it is TaggedInt31 or TaggedInt32
  8935. return ::Math::PointerCastToIntegralTruncate<int>(aLeft) <= ::Math::PointerCastToIntegralTruncate<int>(aRight);
  8936. }
  8937. if (JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  8938. {
  8939. return TaggedInt::ToDouble(aLeft) <= JavascriptNumber::GetValue(aRight);
  8940. }
  8941. }
  8942. else if (TaggedInt::Is(aRight))
  8943. {
  8944. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft))
  8945. {
  8946. return JavascriptNumber::GetValue(aLeft) <= TaggedInt::ToDouble(aRight);
  8947. }
  8948. }
  8949. else
  8950. {
  8951. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft) && JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  8952. {
  8953. return JavascriptNumber::GetValue(aLeft) <= JavascriptNumber::GetValue(aRight);
  8954. }
  8955. }
  8956. return !RelationalComparisonHelper(aRight, aLeft, scriptContext, false, true);
  8957. }
  8958. BOOL JavascriptOperators::NotEqual(Var aLeft, Var aRight, ScriptContext* scriptContext)
  8959. {
  8960. //
  8961. // TODO: Change to use Abstract Equality Comparison Algorithm (ES3.0: S11.9.3):
  8962. // - Evaluate left, then right, operands to preserve correct evaluation order.
  8963. // - Call algorithm, potentially reversing arguments.
  8964. //
  8965. return !Equal(aLeft, aRight, scriptContext);
  8966. }
  8967. // NotStrictEqual() returns whether the two vars have strict equality, as
  8968. // described in (ES3.0: S11.9.5, S11.9.6).
  8969. BOOL JavascriptOperators::NotStrictEqual(Var aLeft, Var aRight, ScriptContext* scriptContext)
  8970. {
  8971. return !StrictEqual(aLeft, aRight, scriptContext);
  8972. }
  8973. bool JavascriptOperators::CheckIfObjectAndPrototypeChainHasOnlyWritableDataProperties(RecyclableObject* object)
  8974. {
  8975. Assert(object);
  8976. if (object->GetType()->HasSpecialPrototype())
  8977. {
  8978. TypeId typeId = object->GetTypeId();
  8979. if (typeId == TypeIds_Null)
  8980. {
  8981. return true;
  8982. }
  8983. if (typeId == TypeIds_Proxy)
  8984. {
  8985. return false;
  8986. }
  8987. }
  8988. if (!object->HasOnlyWritableDataProperties())
  8989. {
  8990. return false;
  8991. }
  8992. return CheckIfPrototypeChainHasOnlyWritableDataProperties(object->GetPrototype());
  8993. }
  8994. bool JavascriptOperators::CheckIfPrototypeChainHasOnlyWritableDataProperties(RecyclableObject* prototype)
  8995. {
  8996. Assert(prototype);
  8997. if (prototype->GetType()->AreThisAndPrototypesEnsuredToHaveOnlyWritableDataProperties())
  8998. {
  8999. Assert(DoCheckIfPrototypeChainHasOnlyWritableDataProperties(prototype));
  9000. return true;
  9001. }
  9002. return DoCheckIfPrototypeChainHasOnlyWritableDataProperties(prototype);
  9003. }
  9004. // Does a quick check to see if the specified object (which should be a prototype object) and all objects in its prototype
  9005. // chain have only writable data properties (i.e. no accessors or non-writable properties).
  9006. bool JavascriptOperators::DoCheckIfPrototypeChainHasOnlyWritableDataProperties(RecyclableObject* prototype)
  9007. {
  9008. Assert(prototype);
  9009. Type *const originalType = prototype->GetType();
  9010. ScriptContext *const scriptContext = prototype->GetScriptContext();
  9011. bool onlyOneScriptContext = true;
  9012. TypeId typeId;
  9013. for (; (typeId = prototype->GetTypeId()) != TypeIds_Null; prototype = prototype->GetPrototype())
  9014. {
  9015. if (typeId == TypeIds_Proxy)
  9016. {
  9017. return false;
  9018. }
  9019. if (!prototype->HasOnlyWritableDataProperties())
  9020. {
  9021. return false;
  9022. }
  9023. if (prototype->GetScriptContext() != scriptContext)
  9024. {
  9025. onlyOneScriptContext = false;
  9026. }
  9027. }
  9028. if (onlyOneScriptContext)
  9029. {
  9030. // See JavascriptLibrary::typesEnsuredToHaveOnlyWritableDataPropertiesInItAndPrototypeChain for a description of
  9031. // this cache. Technically, we could register all prototypes in the chain but this is good enough for now.
  9032. originalType->SetAreThisAndPrototypesEnsuredToHaveOnlyWritableDataProperties(true);
  9033. }
  9034. return true;
  9035. }
  9036. // Checks to see if the specified object (which should be a prototype object)
  9037. // contains a proxy anywhere in the prototype chain.
  9038. bool JavascriptOperators::CheckIfPrototypeChainContainsProxyObject(RecyclableObject* prototype)
  9039. {
  9040. if (prototype == nullptr)
  9041. {
  9042. return false;
  9043. }
  9044. Assert(JavascriptOperators::IsObjectOrNull(prototype));
  9045. while (prototype->GetTypeId() != TypeIds_Null)
  9046. {
  9047. if (prototype->GetTypeId() == TypeIds_Proxy)
  9048. {
  9049. return true;
  9050. }
  9051. prototype = prototype->GetPrototype();
  9052. }
  9053. return false;
  9054. }
  9055. BOOL JavascriptOperators::Equal(Var aLeft, Var aRight, ScriptContext* scriptContext)
  9056. {
  9057. if (aLeft == aRight)
  9058. {
  9059. if (TaggedInt::Is(aLeft) || JavascriptObject::Is(aLeft))
  9060. {
  9061. return true;
  9062. }
  9063. else
  9064. {
  9065. return Equal_Full(aLeft, aRight, scriptContext);
  9066. }
  9067. }
  9068. if (JavascriptString::Is(aLeft) && JavascriptString::Is(aRight))
  9069. {
  9070. JavascriptString* left = (JavascriptString*)aLeft;
  9071. JavascriptString* right = (JavascriptString*)aRight;
  9072. if (left->GetLength() == right->GetLength())
  9073. {
  9074. if (left->UnsafeGetBuffer() != NULL && right->UnsafeGetBuffer() != NULL)
  9075. {
  9076. if (left->GetLength() == 1)
  9077. {
  9078. return left->UnsafeGetBuffer()[0] == right->UnsafeGetBuffer()[0];
  9079. }
  9080. return memcmp(left->UnsafeGetBuffer(), right->UnsafeGetBuffer(), left->GetLength() * sizeof(left->UnsafeGetBuffer()[0])) == 0;
  9081. }
  9082. // fall through to Equal_Full
  9083. }
  9084. else
  9085. {
  9086. return false;
  9087. }
  9088. }
  9089. return Equal_Full(aLeft, aRight, scriptContext);
  9090. }
  9091. BOOL JavascriptOperators::Greater(Var aLeft, Var aRight, ScriptContext* scriptContext)
  9092. {
  9093. if (TaggedInt::Is(aLeft))
  9094. {
  9095. if (TaggedInt::Is(aRight))
  9096. {
  9097. // Works whether it is TaggedInt31 or TaggedInt32
  9098. return ::Math::PointerCastToIntegralTruncate<int>(aLeft) > ::Math::PointerCastToIntegralTruncate<int>(aRight);
  9099. }
  9100. if (JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  9101. {
  9102. return TaggedInt::ToDouble(aLeft) > JavascriptNumber::GetValue(aRight);
  9103. }
  9104. }
  9105. else if (TaggedInt::Is(aRight))
  9106. {
  9107. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft))
  9108. {
  9109. return JavascriptNumber::GetValue(aLeft) > TaggedInt::ToDouble(aRight);
  9110. }
  9111. }
  9112. else
  9113. {
  9114. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft) && JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  9115. {
  9116. return JavascriptNumber::GetValue(aLeft) > JavascriptNumber::GetValue(aRight);
  9117. }
  9118. }
  9119. return Greater_Full(aLeft, aRight, scriptContext);
  9120. }
  9121. BOOL JavascriptOperators::Less(Var aLeft, Var aRight, ScriptContext* scriptContext)
  9122. {
  9123. if (TaggedInt::Is(aLeft))
  9124. {
  9125. if (TaggedInt::Is(aRight))
  9126. {
  9127. // Works whether it is TaggedInt31 or TaggedInt32
  9128. return ::Math::PointerCastToIntegralTruncate<int>(aLeft) < ::Math::PointerCastToIntegralTruncate<int>(aRight);
  9129. }
  9130. if (JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  9131. {
  9132. return TaggedInt::ToDouble(aLeft) < JavascriptNumber::GetValue(aRight);
  9133. }
  9134. }
  9135. else if (TaggedInt::Is(aRight))
  9136. {
  9137. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft))
  9138. {
  9139. return JavascriptNumber::GetValue(aLeft) < TaggedInt::ToDouble(aRight);
  9140. }
  9141. }
  9142. else
  9143. {
  9144. if (JavascriptNumber::Is_NoTaggedIntCheck(aLeft) && JavascriptNumber::Is_NoTaggedIntCheck(aRight))
  9145. {
  9146. return JavascriptNumber::GetValue(aLeft) < JavascriptNumber::GetValue(aRight);
  9147. }
  9148. }
  9149. return Less_Full(aLeft, aRight, scriptContext);
  9150. }
  9151. Var JavascriptOperators::ToObject(Var aRight, ScriptContext* scriptContext)
  9152. {
  9153. RecyclableObject* object = nullptr;
  9154. if (FALSE == JavascriptConversion::ToObject(aRight, scriptContext, &object))
  9155. {
  9156. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject /* TODO-ERROR: get arg name - aValue */);
  9157. }
  9158. return object;
  9159. }
  9160. Var JavascriptOperators::ToWithObject(Var aRight, ScriptContext* scriptContext)
  9161. {
  9162. RecyclableObject* object = RecyclableObject::FromVar(aRight);
  9163. WithScopeObject* withWrapper = RecyclerNew(scriptContext->GetRecycler(), WithScopeObject, object, scriptContext->GetLibrary()->GetWithType());
  9164. return withWrapper;
  9165. }
  9166. Var JavascriptOperators::ToNumber(Var aRight, ScriptContext* scriptContext)
  9167. {
  9168. if (TaggedInt::Is(aRight) || (JavascriptNumber::Is_NoTaggedIntCheck(aRight)))
  9169. {
  9170. return aRight;
  9171. }
  9172. return JavascriptNumber::ToVarNoCheck(JavascriptConversion::ToNumber_Full(aRight, scriptContext), scriptContext);
  9173. }
  9174. BOOL JavascriptOperators::IsObject(Var aValue)
  9175. {
  9176. return GetTypeId(aValue) > TypeIds_LastJavascriptPrimitiveType;
  9177. }
  9178. BOOL JavascriptOperators::IsObjectType(TypeId typeId)
  9179. {
  9180. return typeId > TypeIds_LastJavascriptPrimitiveType;
  9181. }
  9182. BOOL JavascriptOperators::IsExposedType(TypeId typeId)
  9183. {
  9184. return typeId <= TypeIds_LastTrueJavascriptObjectType && typeId != TypeIds_HostDispatch;
  9185. }
  9186. BOOL JavascriptOperators::IsObjectOrNull(Var instance)
  9187. {
  9188. TypeId typeId = GetTypeId(instance);
  9189. return IsObjectType(typeId) || typeId == TypeIds_Null;
  9190. }
  9191. BOOL JavascriptOperators::IsUndefined(Var instance)
  9192. {
  9193. return JavascriptOperators::GetTypeId(instance) == TypeIds_Undefined;
  9194. }
  9195. BOOL JavascriptOperators::IsUndefinedOrNullType(TypeId typeId)
  9196. {
  9197. return typeId <= TypeIds_UndefinedOrNull;
  9198. }
  9199. BOOL JavascriptOperators::IsUndefinedOrNull(Var instance)
  9200. {
  9201. return IsUndefinedOrNullType(JavascriptOperators::GetTypeId(instance));
  9202. }
  9203. BOOL JavascriptOperators::IsNull(Var instance)
  9204. {
  9205. return JavascriptOperators::GetTypeId(instance) == TypeIds_Null;
  9206. }
  9207. BOOL JavascriptOperators::IsSpecialObjectType(TypeId typeId)
  9208. {
  9209. return typeId > TypeIds_LastTrueJavascriptObjectType;
  9210. }
  9211. BOOL JavascriptOperators::IsUndefinedObject(Var instance)
  9212. {
  9213. return JavascriptOperators::GetTypeId(instance) == TypeIds_Undefined;
  9214. }
  9215. BOOL JavascriptOperators::IsUndefinedObject(Var instance, RecyclableObject *libraryUndefined)
  9216. {
  9217. Assert(JavascriptOperators::IsUndefinedObject(libraryUndefined));
  9218. return instance == libraryUndefined;
  9219. }
  9220. BOOL JavascriptOperators::IsUndefinedObject(Var instance, ScriptContext *scriptContext)
  9221. {
  9222. return JavascriptOperators::IsUndefinedObject(instance, scriptContext->GetLibrary()->GetUndefined());
  9223. }
  9224. BOOL JavascriptOperators::IsUndefinedObject(Var instance, JavascriptLibrary* library)
  9225. {
  9226. return JavascriptOperators::IsUndefinedObject(instance, library->GetUndefined());
  9227. }
  9228. BOOL JavascriptOperators::IsAnyNumberValue(Var instance)
  9229. {
  9230. TypeId typeId = GetTypeId(instance);
  9231. return TypeIds_FirstNumberType <= typeId && typeId <= TypeIds_LastNumberType;
  9232. }
  9233. // GetIterator as described in ES6.0 (draft 22) Section 7.4.1
  9234. RecyclableObject* JavascriptOperators::GetIterator(Var iterable, ScriptContext* scriptContext, bool optional)
  9235. {
  9236. RecyclableObject* iterableObj = RecyclableObject::FromVar(JavascriptOperators::ToObject(iterable, scriptContext));
  9237. return JavascriptOperators::GetIterator(iterableObj, scriptContext, optional);
  9238. }
  9239. RecyclableObject* JavascriptOperators::GetIteratorFunction(Var iterable, ScriptContext* scriptContext, bool optional)
  9240. {
  9241. RecyclableObject* iterableObj = RecyclableObject::FromVar(JavascriptOperators::ToObject(iterable, scriptContext));
  9242. return JavascriptOperators::GetIteratorFunction(iterableObj, scriptContext, optional);
  9243. }
  9244. RecyclableObject* JavascriptOperators::GetIteratorFunction(RecyclableObject* instance, ScriptContext * scriptContext, bool optional)
  9245. {
  9246. Var func = JavascriptOperators::GetProperty(instance, PropertyIds::_symbolIterator, scriptContext);
  9247. if (optional && JavascriptOperators::IsUndefinedOrNull(func))
  9248. {
  9249. return nullptr;
  9250. }
  9251. if (!JavascriptConversion::IsCallable(func))
  9252. {
  9253. JavascriptError::ThrowTypeError(scriptContext, JSERR_Property_NeedFunction);
  9254. }
  9255. RecyclableObject* function = RecyclableObject::FromVar(func);
  9256. return function;
  9257. }
  9258. RecyclableObject* JavascriptOperators::GetIterator(RecyclableObject* instance, ScriptContext * scriptContext, bool optional)
  9259. {
  9260. RecyclableObject* function = GetIteratorFunction(instance, scriptContext, optional);
  9261. if (function == nullptr)
  9262. {
  9263. Assert(optional);
  9264. return nullptr;
  9265. }
  9266. Var iterator = CALL_FUNCTION(function, CallInfo(Js::CallFlags_Value, 1), instance);
  9267. if (!JavascriptOperators::IsObject(iterator))
  9268. {
  9269. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  9270. }
  9271. return RecyclableObject::FromVar(iterator);
  9272. }
  9273. void JavascriptOperators::IteratorClose(RecyclableObject* iterator, ScriptContext* scriptContext)
  9274. {
  9275. try
  9276. {
  9277. Var func = JavascriptOperators::GetProperty(iterator, PropertyIds::return_, scriptContext);
  9278. if (JavascriptConversion::IsCallable(func))
  9279. {
  9280. RecyclableObject* callable = RecyclableObject::FromVar(func);
  9281. Js::Var args[] = { iterator };
  9282. Js::CallInfo callInfo(Js::CallFlags_Value, _countof(args));
  9283. JavascriptFunction::CallFunction<true>(callable, callable->GetEntryPoint(), Js::Arguments(callInfo, args));
  9284. }
  9285. }
  9286. catch (JavascriptExceptionObject *)
  9287. {
  9288. // We have arrived in this function due to AbruptCompletion (which is an exception), so we don't need to
  9289. // propagate the exception of calling return function
  9290. }
  9291. }
  9292. // IteratorNext as described in ES6.0 (draft 22) Section 7.4.2
  9293. RecyclableObject* JavascriptOperators::IteratorNext(RecyclableObject* iterator, ScriptContext* scriptContext, Var value)
  9294. {
  9295. Var func = JavascriptOperators::GetProperty(iterator, PropertyIds::next, scriptContext);
  9296. ThreadContext *threadContext = scriptContext->GetThreadContext();
  9297. if (!JavascriptConversion::IsCallable(func))
  9298. {
  9299. if (!threadContext->RecordImplicitException())
  9300. {
  9301. return scriptContext->GetLibrary()->GetUndefined();
  9302. }
  9303. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedFunction);
  9304. }
  9305. RecyclableObject* callable = RecyclableObject::FromVar(func);
  9306. Var result = threadContext->ExecuteImplicitCall(callable, ImplicitCall_Accessor, [=]() -> Var
  9307. {
  9308. Js::Var args[] = { iterator, value };
  9309. Js::CallInfo callInfo(Js::CallFlags_Value, _countof(args) + (value == nullptr ? -1 : 0));
  9310. return JavascriptFunction::CallFunction<true>(callable, callable->GetEntryPoint(), Arguments(callInfo, args));
  9311. });
  9312. if (!JavascriptOperators::IsObject(result))
  9313. {
  9314. if (!threadContext->RecordImplicitException())
  9315. {
  9316. return scriptContext->GetLibrary()->GetUndefined();
  9317. }
  9318. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  9319. }
  9320. return RecyclableObject::FromVar(result);
  9321. }
  9322. // IteratorComplete as described in ES6.0 (draft 22) Section 7.4.3
  9323. bool JavascriptOperators::IteratorComplete(RecyclableObject* iterResult, ScriptContext* scriptContext)
  9324. {
  9325. Var done = JavascriptOperators::GetProperty(iterResult, Js::PropertyIds::done, scriptContext);
  9326. return JavascriptConversion::ToBool(done, scriptContext);
  9327. }
  9328. // IteratorValue as described in ES6.0 (draft 22) Section 7.4.4
  9329. Var JavascriptOperators::IteratorValue(RecyclableObject* iterResult, ScriptContext* scriptContext)
  9330. {
  9331. return JavascriptOperators::GetProperty(iterResult, Js::PropertyIds::value, scriptContext);
  9332. }
  9333. // IteratorStep as described in ES6.0 (draft 22) Section 7.4.5
  9334. bool JavascriptOperators::IteratorStep(RecyclableObject* iterator, ScriptContext* scriptContext, RecyclableObject** result)
  9335. {
  9336. Assert(result);
  9337. *result = JavascriptOperators::IteratorNext(iterator, scriptContext);
  9338. return !JavascriptOperators::IteratorComplete(*result, scriptContext);
  9339. }
  9340. bool JavascriptOperators::IteratorStepAndValue(RecyclableObject* iterator, ScriptContext* scriptContext, Var* resultValue)
  9341. {
  9342. // CONSIDER: Fast-pathing for iterators that are built-ins?
  9343. RecyclableObject* result = JavascriptOperators::IteratorNext(iterator, scriptContext);
  9344. if (!JavascriptOperators::IteratorComplete(result, scriptContext))
  9345. {
  9346. *resultValue = JavascriptOperators::IteratorValue(result, scriptContext);
  9347. return true;
  9348. }
  9349. return false;
  9350. }
  9351. RecyclableObject* JavascriptOperators::CreateFromConstructor(RecyclableObject* constructor, ScriptContext* scriptContext)
  9352. {
  9353. // Create a regular object and set the internal proto from the constructor
  9354. return JavascriptOperators::OrdinaryCreateFromConstructor(constructor, scriptContext->GetLibrary()->CreateObject(), nullptr, scriptContext);
  9355. }
  9356. RecyclableObject* JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject* constructor, RecyclableObject* obj, DynamicObject* intrinsicProto, ScriptContext* scriptContext)
  9357. {
  9358. // There isn't a good way for us to add internal properties to objects in Chakra.
  9359. // Thus, caller should take care to create obj with the correct internal properties.
  9360. Var proto = JavascriptOperators::GetProperty(constructor, Js::PropertyIds::prototype, scriptContext);
  9361. // If constructor.prototype is an object, we should use that as the [[Prototype]] for our obj.
  9362. // Else, we set the [[Prototype]] internal slot of obj to %intrinsicProto% - which should be the default.
  9363. if (JavascriptOperators::IsObjectType(JavascriptOperators::GetTypeId(proto)) &&
  9364. DynamicObject::FromVar(proto) != intrinsicProto)
  9365. {
  9366. JavascriptObject::ChangePrototype(obj, RecyclableObject::FromVar(proto), /*validate*/true, scriptContext);
  9367. }
  9368. return obj;
  9369. }
  9370. Var JavascriptOperators::GetProperty(RecyclableObject* instance, PropertyId propertyId, ScriptContext* requestContext, PropertyValueInfo* info)
  9371. {
  9372. return JavascriptOperators::GetProperty(instance, instance, propertyId, requestContext, info);
  9373. }
  9374. BOOL JavascriptOperators::GetProperty(RecyclableObject* instance, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  9375. {
  9376. return JavascriptOperators::GetProperty(instance, instance, propertyId, value, requestContext, info);
  9377. }
  9378. Var JavascriptOperators::GetProperty(Var instance, RecyclableObject* propertyObject, PropertyId propertyId, ScriptContext* requestContext, PropertyValueInfo* info)
  9379. {
  9380. Var value;
  9381. if (JavascriptOperators::GetProperty(instance, propertyObject, propertyId, &value, requestContext, info))
  9382. {
  9383. return value;
  9384. }
  9385. return requestContext->GetMissingPropertyResult();
  9386. }
  9387. Var JavascriptOperators::GetRootProperty(RecyclableObject* instance, PropertyId propertyId, ScriptContext* requestContext, PropertyValueInfo* info)
  9388. {
  9389. Var value;
  9390. if (JavascriptOperators::GetRootProperty(instance, propertyId, &value, requestContext, info))
  9391. {
  9392. return value;
  9393. }
  9394. return requestContext->GetMissingPropertyResult();
  9395. }
  9396. BOOL JavascriptOperators::GetPropertyReference(RecyclableObject *instance, PropertyId propertyId, Var* value, ScriptContext* requestContext, PropertyValueInfo* info)
  9397. {
  9398. return JavascriptOperators::GetPropertyReference(instance, instance, propertyId, value, requestContext, info);
  9399. }
  9400. Var JavascriptOperators::GetItem(RecyclableObject* instance, uint32 index, ScriptContext* requestContext)
  9401. {
  9402. Var value;
  9403. if (GetItem(instance, index, &value, requestContext))
  9404. {
  9405. return value;
  9406. }
  9407. return requestContext->GetMissingItemResult();
  9408. }
  9409. Var JavascriptOperators::GetItem(RecyclableObject* instance, uint64 index, ScriptContext* requestContext)
  9410. {
  9411. Var value;
  9412. if (GetItem(instance, index, &value, requestContext))
  9413. {
  9414. return value;
  9415. }
  9416. return requestContext->GetMissingItemResult();
  9417. }
  9418. BOOL JavascriptOperators::GetItem(RecyclableObject* instance, uint64 index, Var* value, ScriptContext* requestContext)
  9419. {
  9420. PropertyRecord const * propertyRecord;
  9421. JavascriptOperators::GetPropertyIdForInt(index, requestContext, &propertyRecord);
  9422. return JavascriptOperators::GetProperty(instance, propertyRecord->GetPropertyId(), value, requestContext);
  9423. }
  9424. BOOL JavascriptOperators::GetItem(RecyclableObject* instance, uint32 index, Var* value, ScriptContext* requestContext)
  9425. {
  9426. return JavascriptOperators::GetItem(instance, instance, index, value, requestContext);
  9427. }
  9428. BOOL JavascriptOperators::GetItemReference(RecyclableObject* instance, uint32 index, Var* value, ScriptContext* requestContext)
  9429. {
  9430. return GetItemReference(instance, instance, index, value, requestContext);
  9431. }
  9432. BOOL JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(RecyclableObject* instance, PropertyId propertyId, Var* setterValue, DescriptorFlags* flags, PropertyValueInfo* info, ScriptContext* scriptContext)
  9433. {
  9434. if (propertyId == Js::PropertyIds::__proto__)
  9435. {
  9436. return CheckPrototypesForAccessorOrNonWritablePropertyCore<PropertyId, false, false>(instance, propertyId, setterValue, flags, info, scriptContext);
  9437. }
  9438. else
  9439. {
  9440. return CheckPrototypesForAccessorOrNonWritablePropertyCore<PropertyId, true, false>(instance, propertyId, setterValue, flags, info, scriptContext);
  9441. }
  9442. }
  9443. BOOL JavascriptOperators::CheckPrototypesForAccessorOrNonWritableRootProperty(RecyclableObject* instance, PropertyId propertyId, Var* setterValue, DescriptorFlags* flags, PropertyValueInfo* info, ScriptContext* scriptContext)
  9444. {
  9445. if (propertyId == Js::PropertyIds::__proto__)
  9446. {
  9447. return CheckPrototypesForAccessorOrNonWritablePropertyCore<PropertyId, false, true>(instance, propertyId, setterValue, flags, info, scriptContext);
  9448. }
  9449. else
  9450. {
  9451. return CheckPrototypesForAccessorOrNonWritablePropertyCore<PropertyId, true, true>(instance, propertyId, setterValue, flags, info, scriptContext);
  9452. }
  9453. }
  9454. BOOL JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(RecyclableObject* instance, JavascriptString* propertyNameString, Var* setterValue, DescriptorFlags* flags, PropertyValueInfo* info, ScriptContext* scriptContext)
  9455. {
  9456. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  9457. if (Js::BuiltInPropertyRecords::__proto__.Equals(propertyName))
  9458. {
  9459. return CheckPrototypesForAccessorOrNonWritablePropertyCore<JavascriptString*, false, false>(instance, propertyNameString, setterValue, flags, info, scriptContext);
  9460. }
  9461. else
  9462. {
  9463. return CheckPrototypesForAccessorOrNonWritablePropertyCore<JavascriptString*, true, false>(instance, propertyNameString, setterValue, flags, info, scriptContext);
  9464. }
  9465. }
  9466. template<typename PropertyKeyType>
  9467. BOOL JavascriptOperators::CheckPrototypesForAccessorOrNonWritablePropertySlow(RecyclableObject* instance, PropertyKeyType propertyKey, Var* setterValue, DescriptorFlags* flags, bool isRoot, ScriptContext* scriptContext)
  9468. {
  9469. // This is used in debug verification, do not doFastProtoChainCheck to avoid side effect (doFastProtoChainCheck may update HasWritableDataOnly flags).
  9470. if (isRoot)
  9471. {
  9472. return CheckPrototypesForAccessorOrNonWritablePropertyCore<PropertyKeyType, /*doFastProtoChainCheck*/false, true>(instance, propertyKey, setterValue, flags, nullptr, scriptContext);
  9473. }
  9474. else
  9475. {
  9476. return CheckPrototypesForAccessorOrNonWritablePropertyCore<PropertyKeyType, /*doFastProtoChainCheck*/false, false>(instance, propertyKey, setterValue, flags, nullptr, scriptContext);
  9477. }
  9478. }
  9479. BOOL JavascriptOperators::SetProperty(Var instance, RecyclableObject* object, PropertyId propertyId, Var newValue, ScriptContext* requestContext, PropertyOperationFlags propertyOperationFlags)
  9480. {
  9481. PropertyValueInfo info;
  9482. return JavascriptOperators::SetProperty(instance, object, propertyId, newValue, &info, requestContext, propertyOperationFlags);
  9483. }
  9484. BOOL JavascriptOperators::TryConvertToUInt32(const char16* str, int length, uint32* intVal)
  9485. {
  9486. return NumberUtilities::TryConvertToUInt32(str, length, intVal);
  9487. }
  9488. template <typename TPropertyKey>
  9489. DescriptorFlags JavascriptOperators::GetRootSetter(RecyclableObject* instance, TPropertyKey propertyKey, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  9490. {
  9491. // This is provided only so that CheckPrototypesForAccessorOrNonWritablePropertyCore will compile.
  9492. // It will never be called.
  9493. Throw::FatalInternalError();
  9494. }
  9495. template <>
  9496. inline DescriptorFlags JavascriptOperators::GetRootSetter(RecyclableObject* instance, PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  9497. {
  9498. AssertMsg(JavascriptOperators::GetTypeId(instance) == TypeIds_GlobalObject
  9499. || JavascriptOperators::GetTypeId(instance) == TypeIds_ModuleRoot,
  9500. "Root must be a global object!");
  9501. RootObjectBase* rootObject = static_cast<RootObjectBase*>(instance);
  9502. return rootObject->GetRootSetter(propertyId, setterValue, info, requestContext);
  9503. }
  9504. // Helper to fetch @@species from a constructor object
  9505. Var JavascriptOperators::GetSpecies(RecyclableObject* constructor, ScriptContext* scriptContext)
  9506. {
  9507. if (scriptContext->GetConfig()->IsES6SpeciesEnabled())
  9508. {
  9509. Var species = nullptr;
  9510. // Let S be Get(C, @@species)
  9511. if (JavascriptOperators::GetProperty(constructor, PropertyIds::_symbolSpecies, &species, scriptContext)
  9512. && !JavascriptOperators::IsUndefinedOrNull(species))
  9513. {
  9514. // If S is neither undefined nor null, let C be S
  9515. return species;
  9516. }
  9517. }
  9518. return constructor;
  9519. }
  9520. } // namespace Js