JavascriptOperators.cpp 472 KB

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