JavascriptOperators.cpp 471 KB

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