JavascriptArray.cpp 510 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090
  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 "RuntimeLibraryPch.h"
  6. #include "Types/PathTypeHandler.h"
  7. #include "Types/SpreadArgument.h"
  8. // TODO: Change this generic fatal error to the descriptive one.
  9. #define AssertAndFailFast(x) if (!(x)) { Assert(x); Js::Throw::FatalInternalError(); }
  10. #define AssertMsgAndFailFast(x, m) if (!(x)) { AssertMsg((x), m); Js::Throw::FatalInternalError(); }
  11. using namespace Js;
  12. // Make sure EmptySegment points to read-only memory.
  13. // Can't do this the easy way because SparseArraySegment has a constructor...
  14. static const char EmptySegmentData[sizeof(SparseArraySegmentBase)] = {0};
  15. const SparseArraySegmentBase *JavascriptArray::EmptySegment = (SparseArraySegmentBase *)&EmptySegmentData;
  16. // col0 : allocation bucket
  17. // col1 : No. of missing items to set during initialization depending on bucket.
  18. // col2 : allocation size for elements in given bucket.
  19. // col1 and col2 is calculated at runtime
  20. uint JavascriptNativeFloatArray::allocationBuckets[][AllocationBucketsInfoSize] =
  21. {
  22. { 3, 0, 0 }, // allocate space for 3 elements for array of length 0,1,2,3
  23. { 5, 0, 0 }, // allocate space for 5 elements for array of length 4,5
  24. { 8, 0, 0 }, // allocate space for 8 elements for array of length 6,7,8
  25. };
  26. const Var JavascriptArray::MissingItem = (Var)VarMissingItemPattern;
  27. #if defined(TARGET_64)
  28. const Var JavascriptArray::IntMissingItemVar = (Var)(((uint64)IntMissingItemPattern << 32) | (uint32)IntMissingItemPattern);
  29. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  30. {
  31. // See comments above on how to read this
  32. {2, 0, 0},
  33. {6, 0, 0},
  34. {8, 0, 0},
  35. };
  36. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  37. {
  38. // See comments above on how to read this
  39. {4, 0, 0},
  40. {6, 0, 0},
  41. {8, 0, 0},
  42. };
  43. #else
  44. const Var JavascriptArray::IntMissingItemVar = (Var)IntMissingItemPattern;
  45. uint JavascriptNativeIntArray::allocationBuckets[][AllocationBucketsInfoSize] =
  46. {
  47. // See comments above on how to read this
  48. { 3, 0, 0 },
  49. { 7, 0, 0 },
  50. { 8, 0, 0 },
  51. };
  52. uint JavascriptArray::allocationBuckets[][AllocationBucketsInfoSize] =
  53. {
  54. // See comments above on how to read this
  55. { 4, 0, 0 },
  56. { 8, 0, 0 },
  57. };
  58. #endif
  59. const int32 JavascriptNativeIntArray::MissingItem = IntMissingItemPattern;
  60. const double JavascriptNativeFloatArray::MissingItem = *(double*)&FloatMissingItemPattern;
  61. // Allocate enough space for 4 inline property slots and 16 inline element slots
  62. const size_t JavascriptArray::StackAllocationSize = DetermineAllocationSize<JavascriptArray, 4>(16);
  63. const size_t JavascriptNativeIntArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeIntArray, 4>(16);
  64. const size_t JavascriptNativeFloatArray::StackAllocationSize = DetermineAllocationSize<JavascriptNativeFloatArray, 4>(16);
  65. SegmentBTree::SegmentBTree()
  66. : segmentCount(0),
  67. segments(nullptr),
  68. keys(nullptr),
  69. children(nullptr)
  70. {
  71. }
  72. uint32 SegmentBTree::GetLazyCrossOverLimit()
  73. {
  74. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  75. if (Js::Configuration::Global.flags.DisableArrayBTree)
  76. {
  77. return Js::JavascriptArray::InvalidIndex;
  78. }
  79. else if (Js::Configuration::Global.flags.ForceArrayBTree)
  80. {
  81. return ARRAY_CROSSOVER_FOR_VALIDATE;
  82. }
  83. #endif
  84. #ifdef VALIDATE_ARRAY
  85. if (Js::Configuration::Global.flags.ArrayValidate)
  86. {
  87. return ARRAY_CROSSOVER_FOR_VALIDATE;
  88. }
  89. #endif
  90. return SegmentBTree::MinDegree * 3;
  91. }
  92. BOOL SegmentBTree::IsLeaf() const
  93. {
  94. return children == NULL;
  95. }
  96. BOOL SegmentBTree::IsFullNode() const
  97. {
  98. return segmentCount == MaxKeys;
  99. }
  100. void SegmentBTree::InternalFind(SegmentBTree* node, uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  101. {
  102. uint32 i = 0;
  103. for(; i < node->segmentCount; i++)
  104. {
  105. Assert(node->keys[i] == node->segments[i]->left);
  106. if (itemIndex < node->keys[i])
  107. {
  108. break;
  109. }
  110. }
  111. // i indicates the 1st segment in the node past any matching segment.
  112. // the i'th child is the children to the 'left' of the i'th segment.
  113. // If itemIndex matches segment i-1 (note that left is always a match even when length == 0)
  114. bool matches = i > 0 && (itemIndex == node->keys[i-1] || itemIndex < node->keys[i-1] + node->segments[i-1]->length);
  115. if (matches)
  116. {
  117. // Find prev segment
  118. if (node->IsLeaf())
  119. {
  120. if (i > 1)
  121. {
  122. // Previous is either sibling or set in a parent
  123. prev = node->segments[i-2];
  124. }
  125. }
  126. else
  127. {
  128. // prev is the right most leaf in children[i-1] tree
  129. SegmentBTree* child = &node->children[i - 1];
  130. while (!child->IsLeaf())
  131. {
  132. child = &child->children[child->segmentCount];
  133. }
  134. prev = child->segments[child->segmentCount - 1];
  135. }
  136. // Return the matching segment
  137. matchOrNext = node->segments[i-1];
  138. }
  139. else // itemIndex in between segment i-1 and i
  140. {
  141. if (i > 0)
  142. {
  143. // Store in previous in case a match or next is the first segment in a child.
  144. prev = node->segments[i-1];
  145. }
  146. if (node->IsLeaf())
  147. {
  148. matchOrNext = (i == 0 ? node->segments[0] : PointerValue(prev->next));
  149. }
  150. else
  151. {
  152. InternalFind(node->children + i, itemIndex, prev, matchOrNext);
  153. }
  154. }
  155. }
  156. void SegmentBTreeRoot::Find(uint32 itemIndex, SparseArraySegmentBase*& prev, SparseArraySegmentBase*& matchOrNext)
  157. {
  158. prev = matchOrNext = NULL;
  159. InternalFind(this, itemIndex, prev, matchOrNext);
  160. Assert(prev == NULL || (prev->next == matchOrNext));// If prev exists it is immediately before matchOrNext in the list of arraysegments
  161. Assert(prev == NULL || (prev->left < itemIndex && prev->left + prev->length <= itemIndex)); // prev should never be a match (left is a match if length == 0)
  162. Assert(matchOrNext == NULL || (matchOrNext->left >= itemIndex || matchOrNext->left + matchOrNext->length > itemIndex));
  163. }
  164. void SegmentBTreeRoot::Add(Recycler* recycler, SparseArraySegmentBase* newSeg)
  165. {
  166. if (IsFullNode())
  167. {
  168. SegmentBTree * children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  169. children[0] = *this;
  170. // Even though the segments point to a GC pointer, the main array should keep a references
  171. // as well. So just make it a leaf allocation
  172. this->segmentCount = 0;
  173. this->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  174. this->keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  175. this->children = children;
  176. // This split is the only way the tree gets deeper
  177. SplitChild(recycler, this, 0, &children[0]);
  178. }
  179. InsertNonFullNode(recycler, this, newSeg);
  180. }
  181. void SegmentBTree::SwapSegment(uint32 originalKey, SparseArraySegmentBase* oldSeg, SparseArraySegmentBase* newSeg)
  182. {
  183. // Find old segment
  184. uint32 itemIndex = originalKey;
  185. uint32 i = 0;
  186. for(; i < segmentCount; i++)
  187. {
  188. Assert(keys[i] == segments[i]->left || (oldSeg == newSeg && newSeg == segments[i]));
  189. if (itemIndex < keys[i])
  190. {
  191. break;
  192. }
  193. }
  194. // i is 1 past any match
  195. if (i > 0)
  196. {
  197. if (oldSeg == segments[i-1])
  198. {
  199. segments[i-1] = newSeg;
  200. keys[i-1] = newSeg->left;
  201. return;
  202. }
  203. }
  204. Assert(!IsLeaf());
  205. children[i].SwapSegment(originalKey, oldSeg, newSeg);
  206. }
  207. void SegmentBTree::SplitChild(Recycler* recycler, SegmentBTree* parent, uint32 iChild, SegmentBTree* child)
  208. {
  209. // Split child in two, move it's median key up to parent, and put the result of the split
  210. // on either side of the key moved up into parent
  211. Assert(child != NULL);
  212. Assert(parent != NULL);
  213. Assert(!parent->IsFullNode());
  214. Assert(child->IsFullNode());
  215. SegmentBTree newNode;
  216. newNode.segmentCount = MinKeys;
  217. // Even though the segments point to a GC pointer, the main array should keep a references
  218. // as well. So just make it a leaf allocation
  219. newNode.segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  220. newNode.keys = AllocatorNewArrayLeafZ(Recycler,recycler,uint32,MaxKeys);
  221. // Move the keys above the median into the new node
  222. for(uint32 i = 0; i < MinKeys; i++)
  223. {
  224. newNode.segments[i] = child->segments[i+MinDegree];
  225. newNode.keys[i] = child->keys[i+MinDegree];
  226. // Do not leave false positive references around in the b-tree
  227. child->segments[i+MinDegree] = nullptr;
  228. }
  229. // If children exist move those as well.
  230. if (!child->IsLeaf())
  231. {
  232. newNode.children = AllocatorNewArrayZ(Recycler, recycler, SegmentBTree, MaxDegree);
  233. for(uint32 j = 0; j < MinDegree; j++)
  234. {
  235. newNode.children[j] = child->children[j+MinDegree];
  236. // Do not leave false positive references around in the b-tree
  237. child->children[j+MinDegree].segments = nullptr;
  238. child->children[j+MinDegree].children = nullptr;
  239. }
  240. }
  241. child->segmentCount = MinKeys;
  242. // Make room for the new child in parent
  243. for(uint32 j = parent->segmentCount; j > iChild; j--)
  244. {
  245. parent->children[j+1] = parent->children[j];
  246. }
  247. // Copy the contents of the new node into the correct place in the parent's child array
  248. parent->children[iChild+1] = newNode;
  249. // Move the keys to make room for the median key
  250. for(uint32 k = parent->segmentCount; k > iChild; k--)
  251. {
  252. parent->segments[k] = parent->segments[k-1];
  253. parent->keys[k] = parent->keys[k-1];
  254. }
  255. // Move the median key into the proper place in the parent node
  256. parent->segments[iChild] = child->segments[MinKeys];
  257. parent->keys[iChild] = child->keys[MinKeys];
  258. // Do not leave false positive references around in the b-tree
  259. child->segments[MinKeys] = nullptr;
  260. parent->segmentCount++;
  261. }
  262. void SegmentBTree::InsertNonFullNode(Recycler* recycler, SegmentBTree* node, SparseArraySegmentBase* newSeg)
  263. {
  264. Assert(!node->IsFullNode());
  265. AnalysisAssert(node->segmentCount < MaxKeys); // Same as !node->IsFullNode()
  266. Assert(newSeg != NULL);
  267. if (node->IsLeaf())
  268. {
  269. // Move the keys
  270. uint32 i = node->segmentCount - 1;
  271. while( (i != -1) && (newSeg->left < node->keys[i]))
  272. {
  273. node->segments[i+1] = node->segments[i];
  274. node->keys[i+1] = node->keys[i];
  275. i--;
  276. }
  277. if (!node->segments)
  278. {
  279. // Even though the segments point to a GC pointer, the main array should keep a references
  280. // as well. So just make it a leaf allocation
  281. node->segments = AllocatorNewArrayLeafZ(Recycler, recycler, SparseArraySegmentBase*, MaxKeys);
  282. node->keys = AllocatorNewArrayLeafZ(Recycler, recycler, uint32, MaxKeys);
  283. }
  284. node->segments[i + 1] = newSeg;
  285. node->keys[i + 1] = newSeg->left;
  286. node->segmentCount++;
  287. }
  288. else
  289. {
  290. // find the correct child node
  291. uint32 i = node->segmentCount-1;
  292. while((i != -1) && (newSeg->left < node->keys[i]))
  293. {
  294. i--;
  295. }
  296. i++;
  297. // Make room if full
  298. if(node->children[i].IsFullNode())
  299. {
  300. // This split doesn't make the tree any deeper as node already has children.
  301. SplitChild(recycler, node, i, node->children+i);
  302. Assert(node->keys[i] == node->segments[i]->left);
  303. if (newSeg->left > node->keys[i])
  304. {
  305. i++;
  306. }
  307. }
  308. InsertNonFullNode(recycler, node->children+i, newSeg);
  309. }
  310. }
  311. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure(BOOL operationSucceeded)
  312. {
  313. if (IsThrowTypeError(operationSucceeded))
  314. {
  315. ThrowTypeErrorOnFailure();
  316. }
  317. }
  318. inline void ThrowTypeErrorOnFailureHelper::ThrowTypeErrorOnFailure()
  319. {
  320. JavascriptError::ThrowTypeError(m_scriptContext, VBSERR_ActionNotSupported, m_functionName);
  321. }
  322. inline BOOL ThrowTypeErrorOnFailureHelper::IsThrowTypeError(BOOL operationSucceeded)
  323. {
  324. return !operationSucceeded;
  325. }
  326. // Make sure EmptySegment points to read-only memory.
  327. // Can't do this the easy way because SparseArraySegment has a constructor...
  328. JavascriptArray::JavascriptArray(DynamicType * type)
  329. : ArrayObject(type, false, 0)
  330. {
  331. Assert(type->GetTypeId() == TypeIds_Array || type->GetTypeId() == TypeIds_NativeIntArray || type->GetTypeId() == TypeIds_NativeFloatArray || ((type->GetTypeId() == TypeIds_ES5Array || type->GetTypeId() == TypeIds_Object) && type->GetPrototype() == GetScriptContext()->GetLibrary()->GetArrayPrototype()));
  332. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  333. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  334. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  335. }
  336. JavascriptArray::JavascriptArray(uint32 length, DynamicType * type)
  337. : ArrayObject(type, false, length)
  338. {
  339. Assert(JavascriptArray::IsNonES5Array(type->GetTypeId()));
  340. Assert(EmptySegment->length == 0 && EmptySegment->size == 0 && EmptySegment->next == NULL);
  341. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  342. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase *>(EmptySegment));
  343. }
  344. JavascriptArray::JavascriptArray(uint32 length, uint32 size, DynamicType * type)
  345. : ArrayObject(type, false, length)
  346. {
  347. Assert(type->GetTypeId() == TypeIds_Array);
  348. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  349. Recycler* recycler = GetRecycler();
  350. SetHeadAndLastUsedSegment(SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, size, nullptr));
  351. }
  352. JavascriptArray::JavascriptArray(DynamicType * type, uint32 size)
  353. : ArrayObject(type, false)
  354. {
  355. InitArrayFlags(DynamicObjectFlags::InitialArrayValue);
  356. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptArray, 0, false>(this));
  357. head->size = size;
  358. head->CheckLengthvsSize();
  359. Var fill = Js::JavascriptArray::MissingItem;
  360. for (uint i = 0; i < size; i++)
  361. {
  362. SparseArraySegment<Var>::From(head)->elements[i] = fill;
  363. }
  364. }
  365. JavascriptNativeIntArray::JavascriptNativeIntArray(uint32 length, uint32 size, DynamicType * type)
  366. : JavascriptNativeArray(type)
  367. {
  368. Assert(type->GetTypeId() == TypeIds_NativeIntArray);
  369. this->length = length;
  370. Recycler* recycler = GetRecycler();
  371. SetHeadAndLastUsedSegment(SparseArraySegment<int32>::AllocateSegment(recycler, 0, 0, size, nullptr));
  372. }
  373. JavascriptNativeIntArray::JavascriptNativeIntArray(DynamicType * type, uint32 size)
  374. : JavascriptNativeArray(type)
  375. {
  376. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, false>(this));
  377. head->size = size;
  378. head->CheckLengthvsSize();
  379. SparseArraySegment<int32>::From(head)->FillSegmentBuffer(0, size);
  380. }
  381. JavascriptNativeFloatArray::JavascriptNativeFloatArray(uint32 length, uint32 size, DynamicType * type)
  382. : JavascriptNativeArray(type)
  383. {
  384. Assert(type->GetTypeId() == TypeIds_NativeFloatArray);
  385. this->length = length;
  386. Recycler* recycler = GetRecycler();
  387. SetHeadAndLastUsedSegment(SparseArraySegment<double>::AllocateSegment(recycler, 0, 0, size, nullptr));
  388. }
  389. JavascriptNativeFloatArray::JavascriptNativeFloatArray(DynamicType * type, uint32 size)
  390. : JavascriptNativeArray(type)
  391. {
  392. SetHeadAndLastUsedSegment(DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, false>(this));
  393. head->size = size;
  394. head->CheckLengthvsSize();
  395. SparseArraySegment<double>::From(head)->FillSegmentBuffer(0, size);
  396. }
  397. bool JavascriptArray::IsNonES5Array(Var aValue)
  398. {
  399. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  400. return JavascriptArray::IsNonES5Array(typeId);
  401. }
  402. bool JavascriptArray::IsNonES5Array(TypeId typeId)
  403. {
  404. return typeId >= TypeIds_ArrayFirst && typeId <= TypeIds_ArrayLast;
  405. }
  406. JavascriptArray* JavascriptArray::TryVarToNonES5Array(Var aValue)
  407. {
  408. return JavascriptArray::IsNonES5Array(aValue) ? UnsafeVarTo<JavascriptArray>(aValue) : nullptr;
  409. }
  410. bool JavascriptArray::IsVarArray(Var aValue)
  411. {
  412. TypeId typeId = JavascriptOperators::GetTypeId(aValue);
  413. return JavascriptArray::IsVarArray(typeId);
  414. }
  415. bool JavascriptArray::IsVarArray(TypeId typeId)
  416. {
  417. return typeId == TypeIds_Array;
  418. }
  419. template<typename T>
  420. bool JavascriptArray::IsMissingItemAt(uint32 index) const
  421. {
  422. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(this->head);
  423. return SparseArraySegment<T>::IsMissingItem(&headSeg->elements[index]);
  424. }
  425. bool JavascriptArray::IsMissingItem(uint32 index)
  426. {
  427. if (!(this->head->left <= index && index < (this->head->left+ this->head->length)))
  428. {
  429. return false;
  430. }
  431. bool isIntArray = false, isFloatArray = false;
  432. this->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  433. if (isIntArray)
  434. {
  435. return IsMissingItemAt<int32>(index);
  436. }
  437. else if (isFloatArray)
  438. {
  439. return IsMissingItemAt<double>(index);
  440. }
  441. else
  442. {
  443. return IsMissingItemAt<Var>(index);
  444. }
  445. }
  446. // Get JavascriptArray* from a Var, which is either a JavascriptArray* or ESArray*.
  447. JavascriptArray* JavascriptArray::FromAnyArray(Var aValue)
  448. {
  449. AssertOrFailFastMsg(VarIs<JavascriptArray>(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  450. return static_cast<JavascriptArray *>(VarTo<RecyclableObject>(aValue));
  451. }
  452. JavascriptArray* JavascriptArray::UnsafeFromAnyArray(Var aValue)
  453. {
  454. AssertMsg(VarIs<JavascriptArray>(aValue), "Ensure var is actually a 'JavascriptArray' or 'ES5Array'");
  455. return static_cast<JavascriptArray *>(UnsafeVarTo<RecyclableObject>(aValue));
  456. }
  457. // Check if a Var is a direct-accessible (fast path) JavascriptArray.
  458. bool JavascriptArray::IsDirectAccessArray(Var aValue)
  459. {
  460. return VarIs<RecyclableObject>(aValue) &&
  461. (VirtualTableInfo<JavascriptArray>::HasVirtualTable(aValue) ||
  462. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(aValue) ||
  463. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(aValue));
  464. }
  465. bool JavascriptArray::IsInlineSegment(SparseArraySegmentBase *seg, JavascriptArray *pArr)
  466. {
  467. if (seg == nullptr)
  468. {
  469. return false;
  470. }
  471. SparseArraySegmentBase* inlineHeadSegment = nullptr;
  472. if (VarIs<JavascriptNativeArray>(pArr))
  473. {
  474. if (VarIs<JavascriptNativeFloatArray>(pArr))
  475. {
  476. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeFloatArray, 0, true>((JavascriptNativeFloatArray*)pArr);
  477. }
  478. else
  479. {
  480. AssertOrFailFast(VarIs<JavascriptNativeIntArray>(pArr));
  481. inlineHeadSegment = DetermineInlineHeadSegmentPointer<JavascriptNativeIntArray, 0, true>((JavascriptNativeIntArray*)pArr);
  482. }
  483. Assert(inlineHeadSegment);
  484. return (seg == inlineHeadSegment);
  485. }
  486. // This will result in false positives. It is used because DetermineInlineHeadSegmentPointer
  487. // does not handle Arrays that change type e.g. from JavascriptNativeIntArray to JavascriptArray
  488. // This conversion in particular is problematic because JavascriptNativeIntArray is larger than JavascriptArray
  489. // so the returned head segment ptr never equals pArr->head. So we will default to using this and deal with
  490. // false positives. It is better than always doing a hard copy.
  491. return pArr->head != nullptr && HasInlineHeadSegment(pArr->head->length);
  492. }
  493. DynamicObjectFlags JavascriptArray::GetFlags() const
  494. {
  495. return GetArrayFlags();
  496. }
  497. DynamicObjectFlags JavascriptArray::GetFlags_Unchecked() const // do not use except in extreme circumstances
  498. {
  499. return GetArrayFlags_Unchecked();
  500. }
  501. void JavascriptArray::SetFlags(const DynamicObjectFlags flags)
  502. {
  503. SetArrayFlags(flags);
  504. }
  505. DynamicType * JavascriptArray::GetInitialType(ScriptContext * scriptContext)
  506. {
  507. return scriptContext->GetLibrary()->GetArrayType();
  508. }
  509. JavascriptArray *JavascriptArray::Jit_GetArrayForArrayOrObjectWithArray(const Var var)
  510. {
  511. bool isObjectWithArray;
  512. return Jit_GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray);
  513. }
  514. JavascriptArray *JavascriptArray::Jit_GetArrayForArrayOrObjectWithArray(const Var var, bool *const isObjectWithArrayRef)
  515. {
  516. Assert(var);
  517. Assert(isObjectWithArrayRef);
  518. *isObjectWithArrayRef = false;
  519. if (!VarIs<RecyclableObject>(var))
  520. {
  521. return nullptr;
  522. }
  523. JavascriptArray *array = nullptr;
  524. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  525. if (!Jit_TryGetArrayForObjectWithArray(var, isObjectWithArrayRef, &vtable, &array))
  526. {
  527. return nullptr;
  528. }
  529. if (vtable != VirtualTableInfo<JavascriptArray>::Address &&
  530. vtable != VirtualTableInfo<CrossSiteObject<JavascriptArray>>::Address &&
  531. vtable != VirtualTableInfo<JavascriptNativeIntArray>::Address &&
  532. vtable != VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::Address &&
  533. vtable != VirtualTableInfo<JavascriptNativeFloatArray>::Address &&
  534. vtable != VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::Address)
  535. {
  536. return nullptr;
  537. }
  538. if (!array)
  539. {
  540. array = VarTo<JavascriptArray>(var);
  541. }
  542. return array;
  543. }
  544. bool JavascriptArray::Jit_TryGetArrayForObjectWithArray(const Var var, bool *const isObjectWithArrayRef, INT_PTR* pVTable, JavascriptArray** pArray)
  545. {
  546. Assert(isObjectWithArrayRef);
  547. Assert(pVTable);
  548. Assert(pArray);
  549. if (*pVTable == VirtualTableInfo<DynamicObject>::Address ||
  550. *pVTable == VirtualTableInfo<CrossSiteObject<DynamicObject>>::Address)
  551. {
  552. ArrayObject* objectArray = VarTo<DynamicObject>(var)->GetObjectArray();
  553. *pArray = (objectArray && VarIs<JavascriptArray>(objectArray)) ? VarTo<JavascriptArray>(objectArray) : nullptr;
  554. if (!(*pArray))
  555. {
  556. return false;
  557. }
  558. *isObjectWithArrayRef = true;
  559. *pVTable = VirtualTableInfoBase::GetVirtualTable(*pArray);
  560. }
  561. return true;
  562. }
  563. JavascriptArray *JavascriptArray::GetArrayForArrayOrObjectWithArray(
  564. const Var var,
  565. bool *const isObjectWithArrayRef,
  566. TypeId *const arrayTypeIdRef)
  567. {
  568. // This is a helper function used by jitted code. The array checks done here match the array checks done by jitted code
  569. // (see Lowerer::GenerateArrayTest) to minimize bailouts.
  570. Assert(var);
  571. Assert(isObjectWithArrayRef);
  572. Assert(arrayTypeIdRef);
  573. *isObjectWithArrayRef = false;
  574. *arrayTypeIdRef = TypeIds_Undefined;
  575. if(!VarIs<RecyclableObject>(var))
  576. {
  577. return nullptr;
  578. }
  579. JavascriptArray *array = nullptr;
  580. INT_PTR vtable = VirtualTableInfoBase::GetVirtualTable(var);
  581. if(vtable == VirtualTableInfo<DynamicObject>::Address)
  582. {
  583. ArrayObject* objectArray = VarTo<DynamicObject>(var)->GetObjectArray();
  584. array = (objectArray && IsNonES5Array(objectArray)) ? VarTo<JavascriptArray>(objectArray) : nullptr;
  585. if(!array)
  586. {
  587. return nullptr;
  588. }
  589. *isObjectWithArrayRef = true;
  590. vtable = VirtualTableInfoBase::GetVirtualTable(array);
  591. }
  592. if(vtable == VirtualTableInfo<JavascriptArray>::Address)
  593. {
  594. *arrayTypeIdRef = TypeIds_Array;
  595. }
  596. else if(vtable == VirtualTableInfo<JavascriptNativeIntArray>::Address)
  597. {
  598. *arrayTypeIdRef = TypeIds_NativeIntArray;
  599. }
  600. else if(vtable == VirtualTableInfo<JavascriptNativeFloatArray>::Address)
  601. {
  602. *arrayTypeIdRef = TypeIds_NativeFloatArray;
  603. }
  604. else
  605. {
  606. return nullptr;
  607. }
  608. if(!array)
  609. {
  610. array = VarTo<JavascriptArray>(var);
  611. }
  612. return array;
  613. }
  614. const SparseArraySegmentBase *JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(const Var var)
  615. {
  616. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_GetArrayHeadSegmentForArrayOrObjectWithArray);
  617. JavascriptArray *const array = Jit_GetArrayForArrayOrObjectWithArray(var);
  618. return array ? array->head : nullptr;
  619. JIT_HELPER_END(Array_Jit_GetArrayHeadSegmentForArrayOrObjectWithArray);
  620. }
  621. uint32 JavascriptArray::Jit_GetArrayHeadSegmentLength(const SparseArraySegmentBase *const headSegment)
  622. {
  623. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_GetArrayHeadSegmentLength);
  624. return headSegment ? headSegment->length : 0;
  625. JIT_HELPER_END(Array_Jit_GetArrayHeadSegmentLength);
  626. }
  627. bool JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  628. const SparseArraySegmentBase *const headSegmentBeforeOperation,
  629. const uint32 headSegmentLengthBeforeOperation,
  630. const Var varAfterOperation)
  631. {
  632. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_OperationInvalidatedArrayHeadSegment);
  633. Assert(varAfterOperation);
  634. if(!headSegmentBeforeOperation)
  635. {
  636. return false;
  637. }
  638. const SparseArraySegmentBase *const headSegmentAfterOperation =
  639. Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(varAfterOperation);
  640. return
  641. headSegmentAfterOperation != headSegmentBeforeOperation ||
  642. headSegmentAfterOperation->length != headSegmentLengthBeforeOperation;
  643. JIT_HELPER_END(Array_Jit_OperationInvalidatedArrayHeadSegment);
  644. }
  645. uint32 JavascriptArray::Jit_GetArrayLength(const Var var)
  646. {
  647. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_GetArrayLength);
  648. bool isObjectWithArray;
  649. JavascriptArray *const array = Jit_GetArrayForArrayOrObjectWithArray(var, &isObjectWithArray);
  650. return array && !isObjectWithArray ? array->GetLength() : 0;
  651. JIT_HELPER_END(Array_Jit_GetArrayLength);
  652. }
  653. bool JavascriptArray::Jit_OperationInvalidatedArrayLength(const uint32 lengthBeforeOperation, const Var varAfterOperation)
  654. {
  655. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_OperationInvalidatedArrayLength);
  656. return Jit_GetArrayLength(varAfterOperation) != lengthBeforeOperation;
  657. JIT_HELPER_END(Array_Jit_OperationInvalidatedArrayLength);
  658. }
  659. DynamicObjectFlags JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(const Var var)
  660. {
  661. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_GetArrayFlagsForArrayOrObjectWithArray);
  662. JavascriptArray *const array = Jit_GetArrayForArrayOrObjectWithArray(var);
  663. return array && array->UsesObjectArrayOrFlagsAsFlags() ? array->GetFlags() : DynamicObjectFlags::None;
  664. JIT_HELPER_END(Array_Jit_GetArrayFlagsForArrayOrObjectWithArray);
  665. }
  666. bool JavascriptArray::Jit_OperationCreatedFirstMissingValue(
  667. const DynamicObjectFlags flagsBeforeOperation,
  668. const Var varAfterOperation)
  669. {
  670. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_Jit_OperationCreatedFirstMissingValue);
  671. Assert(varAfterOperation);
  672. return
  673. !!(flagsBeforeOperation & DynamicObjectFlags::HasNoMissingValues) &&
  674. !(Jit_GetArrayFlagsForArrayOrObjectWithArray(varAfterOperation) & DynamicObjectFlags::HasNoMissingValues);
  675. JIT_HELPER_END(Array_Jit_OperationCreatedFirstMissingValue);
  676. }
  677. bool JavascriptArray::HasNoMissingValues() const
  678. {
  679. return !!(GetFlags() & DynamicObjectFlags::HasNoMissingValues);
  680. }
  681. bool JavascriptArray::HasNoMissingValues_Unchecked() const // do not use except in extreme circumstances
  682. {
  683. return !!(GetFlags_Unchecked() & DynamicObjectFlags::HasNoMissingValues);
  684. }
  685. void JavascriptArray::SetHasNoMissingValues(const bool hasNoMissingValues)
  686. {
  687. SetFlags(
  688. hasNoMissingValues
  689. ? GetFlags() | DynamicObjectFlags::HasNoMissingValues
  690. : GetFlags() & ~DynamicObjectFlags::HasNoMissingValues);
  691. }
  692. template<class T>
  693. bool JavascriptArray::IsMissingHeadSegmentItemImpl(const uint32 index) const
  694. {
  695. Assert(index < head->length);
  696. return SparseArraySegment<T>::IsMissingItem(&SparseArraySegment<T>::From(head)->elements[index]);
  697. }
  698. bool JavascriptArray::IsMissingHeadSegmentItem(const uint32 index) const
  699. {
  700. return IsMissingHeadSegmentItemImpl<Var>(index);
  701. }
  702. #if ENABLE_COPYONACCESS_ARRAY
  703. void JavascriptCopyOnAccessNativeIntArray::ConvertCopyOnAccessSegment()
  704. {
  705. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  706. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  707. SparseArraySegment<int32> *newSeg = SparseArraySegment<int32>::AllocateLiteralHeadSegment(this->GetRecycler(), seg->length);
  708. #if ENABLE_DEBUG_CONFIG_OPTIONS
  709. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  710. {
  711. Output::Print(_u("Convert copy-on-access array: index(%d) length(%d)\n"), this->GetHead(), seg->length);
  712. Output::Flush();
  713. }
  714. #endif
  715. newSeg->CopySegment(this->GetRecycler(), newSeg, 0, seg, 0, seg->length);
  716. this->SetHeadAndLastUsedSegment(newSeg);
  717. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(this);
  718. this->type = JavascriptNativeIntArray::GetInitialType(this->GetScriptContext());
  719. ArrayCallSiteInfo *arrayInfo = this->GetArrayCallSiteInfo();
  720. if (arrayInfo && !arrayInfo->isNotCopyOnAccessArray)
  721. {
  722. arrayInfo->isNotCopyOnAccessArray = 1;
  723. }
  724. }
  725. uint32 JavascriptCopyOnAccessNativeIntArray::GetNextIndex(uint32 index) const
  726. {
  727. if (this->length == 0 || (index != Js::JavascriptArray::InvalidIndex && index >= this->length))
  728. {
  729. return Js::JavascriptArray::InvalidIndex;
  730. }
  731. else if (index == Js::JavascriptArray::InvalidIndex)
  732. {
  733. return 0;
  734. }
  735. else
  736. {
  737. return index + 1;
  738. }
  739. }
  740. BOOL JavascriptCopyOnAccessNativeIntArray::DirectGetItemAt(uint32 index, int* outVal)
  741. {
  742. Assert(this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->IsValidIndex(::Math::PointerCastToIntegral<uint32>(this->GetHead())));
  743. SparseArraySegment<int32> *seg = this->GetScriptContext()->GetLibrary()->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(::Math::PointerCastToIntegral<byte>(this->GetHead()));
  744. if (this->length == 0 || index == Js::JavascriptArray::InvalidIndex || index >= this->length)
  745. {
  746. return FALSE;
  747. }
  748. else
  749. {
  750. *outVal = seg->elements[index];
  751. return TRUE;
  752. }
  753. }
  754. #endif
  755. bool JavascriptNativeIntArray::IsMissingHeadSegmentItem(const uint32 index) const
  756. {
  757. return IsMissingHeadSegmentItemImpl<int32>(index);
  758. }
  759. bool JavascriptNativeFloatArray::IsMissingHeadSegmentItem(const uint32 index) const
  760. {
  761. return IsMissingHeadSegmentItemImpl<double>(index);
  762. }
  763. void JavascriptArray::InternalFillFromPrototype(JavascriptArray *dstArray, uint32 dstIndex, JavascriptArray *srcArray, uint32 start, uint32 end, uint32 count)
  764. {
  765. RecyclableObject* prototype = srcArray->GetPrototype();
  766. while (start + count != end && !JavascriptOperators::IsNull(prototype))
  767. {
  768. ForEachOwnMissingArrayIndexOfObject(srcArray, dstArray, prototype, start, end, dstIndex, [&](uint32 index, Var value) {
  769. uint32 n = dstIndex + (index - start);
  770. dstArray->SetItem(n, value, PropertyOperation_None);
  771. count++;
  772. });
  773. prototype = prototype->GetPrototype();
  774. }
  775. }
  776. /* static */
  777. bool JavascriptArray::HasInlineHeadSegment(uint32 length)
  778. {
  779. return length <= SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  780. }
  781. Var JavascriptArray::OP_NewScArray(uint32 elementCount, ScriptContext* scriptContext)
  782. {
  783. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_OP_NewScArray, reentrancylock, scriptContext->GetThreadContext());
  784. // Called only to create array literals: size is known.
  785. return scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  786. JIT_HELPER_END(ScrArr_OP_NewScArray);
  787. }
  788. Var JavascriptArray::OP_NewScArrayWithElements(uint32 elementCount, Var *elements, ScriptContext* scriptContext)
  789. {
  790. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_OP_NewScArrayWithElements, reentrancylock, scriptContext->GetThreadContext());
  791. // Called only to create array literals: size is known.
  792. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  793. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  794. Assert(elementCount <= head->length);
  795. CopyArray(head->elements, head->length, elements, elementCount);
  796. #ifdef VALIDATE_ARRAY
  797. arr->ValidateArray();
  798. #endif
  799. return arr;
  800. JIT_HELPER_END(ScrArr_OP_NewScArrayWithElements);
  801. }
  802. Var JavascriptArray::OP_NewScArrayWithMissingValues(uint32 elementCount, ScriptContext* scriptContext)
  803. {
  804. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_OP_NewScArrayWithMissingValues, reentrancylock, scriptContext->GetThreadContext());
  805. // Called only to create array literals: size is known.
  806. JavascriptArray *const array = static_cast<JavascriptArray *>(OP_NewScArray(elementCount, scriptContext));
  807. array->SetHasNoMissingValues(false);
  808. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(array->head);
  809. head->FillSegmentBuffer(0, elementCount);
  810. return array;
  811. JIT_HELPER_END(ScrArr_OP_NewScArrayWithMissingValues);
  812. }
  813. #if ENABLE_PROFILE_INFO
  814. Var JavascriptArray::ProfiledNewScArray(uint32 elementCount, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  815. {
  816. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_ProfiledNewScArray, reentrancylock, scriptContext->GetThreadContext());
  817. if (arrayInfo->IsNativeIntArray())
  818. {
  819. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(elementCount);
  820. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  821. return arr;
  822. }
  823. if (arrayInfo->IsNativeFloatArray())
  824. {
  825. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(elementCount);
  826. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  827. return arr;
  828. }
  829. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(elementCount);
  830. return arr;
  831. JIT_HELPER_END(ScrArr_ProfiledNewScArray);
  832. }
  833. #endif
  834. Var JavascriptArray::OP_NewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext)
  835. {
  836. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_OP_NewScIntArray, reentrancylock, scriptContext->GetThreadContext());
  837. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(ints->count);
  838. SparseArraySegment<int32> * segment = (SparseArraySegment<int32>*)arr->GetHead();
  839. JavascriptOperators::AddIntsToArraySegment(segment, ints);
  840. return arr;
  841. JIT_HELPER_END(ScrArr_OP_NewScIntArray);
  842. }
  843. #if ENABLE_PROFILE_INFO
  844. Var JavascriptArray::ProfiledNewScIntArray(AuxArray<int32> *ints, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  845. {
  846. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_ProfiledNewScIntArray, reentrancylock, scriptContext->GetThreadContext());
  847. // Called only to create array literals: size is known.
  848. uint32 count = ints->count;
  849. if (arrayInfo->IsNativeIntArray())
  850. {
  851. JavascriptNativeIntArray *arr;
  852. #if ENABLE_COPYONACCESS_ARRAY
  853. JavascriptLibrary *lib = scriptContext->GetLibrary();
  854. FunctionBody *functionBody = weakFuncRef->Get();
  855. if (JavascriptLibrary::IsCopyOnAccessArrayCallSite(lib, arrayInfo, count))
  856. {
  857. Assert(lib->cacheForCopyOnAccessArraySegments);
  858. arr = scriptContext->GetLibrary()->CreateCopyOnAccessNativeIntArrayLiteral(arrayInfo, functionBody, ints);
  859. }
  860. else
  861. #endif
  862. {
  863. arr = scriptContext->GetLibrary()->CreateNativeIntArrayLiteral(count);
  864. SparseArraySegment<int32> *head = SparseArraySegment<int32>::From(arr->head);
  865. Assert(count > 0 && count == head->length);
  866. CopyArray(head->elements, head->length, ints->elements, count);
  867. }
  868. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  869. return arr;
  870. }
  871. if (arrayInfo->IsNativeFloatArray())
  872. {
  873. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  874. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  875. Assert(count > 0 && count == head->length);
  876. for (uint i = 0; i < count; i++)
  877. {
  878. head->elements[i] = (double)ints->elements[i];
  879. }
  880. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  881. return arr;
  882. }
  883. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  884. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  885. Assert(count > 0 && count == head->length);
  886. for (uint i = 0; i < count; i++)
  887. {
  888. head->elements[i] = JavascriptNumber::ToVar(ints->elements[i], scriptContext);
  889. }
  890. return arr;
  891. JIT_HELPER_END(ScrArr_ProfiledNewScIntArray);
  892. }
  893. #endif
  894. Var JavascriptArray::OP_NewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext)
  895. {
  896. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_OP_NewScFltArray, reentrancylock, scriptContext->GetThreadContext());
  897. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(doubles->count);
  898. SparseArraySegment<double> * segment = (SparseArraySegment<double>*)arr->GetHead();
  899. JavascriptOperators::AddFloatsToArraySegment(segment, doubles);
  900. return arr;
  901. JIT_HELPER_END(ScrArr_OP_NewScFltArray);
  902. }
  903. #if ENABLE_PROFILE_INFO
  904. Var JavascriptArray::ProfiledNewScFltArray(AuxArray<double> *doubles, ScriptContext* scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  905. {
  906. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_ProfiledNewScFltArray, reentrancylock, scriptContext->GetThreadContext());
  907. // Called only to create array literals: size is known.
  908. if (arrayInfo->IsNativeFloatArray())
  909. {
  910. arrayInfo->SetIsNotNativeIntArray();
  911. uint32 count = doubles->count;
  912. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArrayLiteral(count);
  913. SparseArraySegment<double> *head = SparseArraySegment<double>::From(arr->head);
  914. Assert(count > 0 && count == head->length);
  915. CopyArray(head->elements, head->length, doubles->elements, count);
  916. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  917. return arr;
  918. }
  919. uint32 count = doubles->count;
  920. JavascriptArray *arr = scriptContext->GetLibrary()->CreateArrayLiteral(count);
  921. SparseArraySegment<Var> *head = SparseArraySegment<Var>::From(arr->head);
  922. Assert(count > 0 && count == head->length);
  923. for (uint i = 0; i < count; i++)
  924. {
  925. double dval = doubles->elements[i];
  926. int32 ival;
  927. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  928. {
  929. head->elements[i] = TaggedInt::ToVarUnchecked(ival);
  930. }
  931. else
  932. {
  933. head->elements[i] = JavascriptNumber::ToVarNoCheck(dval, scriptContext);
  934. }
  935. }
  936. return arr;
  937. JIT_HELPER_END(ScrArr_ProfiledNewScFltArray);
  938. }
  939. Var JavascriptArray::ProfiledNewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  940. {
  941. JIT_HELPER_REENTRANT_HEADER(ScrArr_ProfiledNewInstance);
  942. ARGUMENTS(args, callInfo);
  943. Assert(VarIs<JavascriptFunction>(function) &&
  944. VarTo<JavascriptFunction>(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  945. Assert(callInfo.Count >= 2);
  946. ArrayCallSiteInfo *arrayInfo = (ArrayCallSiteInfo*)args[0];
  947. JavascriptArray* pNew = nullptr;
  948. if (callInfo.Count == 2)
  949. {
  950. // Exactly one argument, which is the array length if it's a uint32.
  951. Var firstArgument = args[1];
  952. int elementCount;
  953. if (TaggedInt::Is(firstArgument))
  954. {
  955. elementCount = TaggedInt::ToInt32(firstArgument);
  956. if (elementCount < 0)
  957. {
  958. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  959. }
  960. if (arrayInfo && arrayInfo->IsNativeArray())
  961. {
  962. if (arrayInfo->IsNativeIntArray())
  963. {
  964. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  965. }
  966. else
  967. {
  968. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  969. }
  970. }
  971. else
  972. {
  973. pNew = function->GetLibrary()->CreateArray(elementCount);
  974. }
  975. }
  976. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  977. {
  978. // Non-tagged-int number: make sure the double value is really a uint32.
  979. double value = JavascriptNumber::GetValue(firstArgument);
  980. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  981. if (value != uvalue)
  982. {
  983. JavascriptError::ThrowRangeError(function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  984. }
  985. if (arrayInfo && arrayInfo->IsNativeArray())
  986. {
  987. if (arrayInfo->IsNativeIntArray())
  988. {
  989. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  990. }
  991. else
  992. {
  993. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  994. }
  995. }
  996. else
  997. {
  998. pNew = function->GetLibrary()->CreateArray(uvalue);
  999. }
  1000. }
  1001. else
  1002. {
  1003. //
  1004. // First element is not int/double
  1005. // create an array of length 1.
  1006. // Set first element as the passed Var
  1007. //
  1008. pNew = function->GetLibrary()->CreateArray(1);
  1009. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1010. }
  1011. }
  1012. else
  1013. {
  1014. // Called with a list of initial element values.
  1015. // Create an array of the appropriate length and walk the list.
  1016. if (arrayInfo && arrayInfo->IsNativeArray())
  1017. {
  1018. if (arrayInfo->IsNativeIntArray())
  1019. {
  1020. pNew = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1021. }
  1022. else
  1023. {
  1024. pNew = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1025. }
  1026. }
  1027. else
  1028. {
  1029. pNew = function->GetLibrary()->CreateArray(callInfo.Count - 1);
  1030. }
  1031. pNew->FillFromArgs(callInfo.Count - 1, 0, args.Values, arrayInfo);
  1032. }
  1033. #ifdef VALIDATE_ARRAY
  1034. pNew->ValidateArray();
  1035. #endif
  1036. return pNew;
  1037. JIT_HELPER_END(ScrArr_ProfiledNewInstance);
  1038. }
  1039. #endif
  1040. Var JavascriptArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1041. {
  1042. ARGUMENTS(args, callInfo);
  1043. return NewInstance(function, args);
  1044. }
  1045. Var JavascriptArray::NewInstance(RecyclableObject* function, Arguments args)
  1046. {
  1047. // Call to new Array(), possibly under another name.
  1048. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1049. // SkipDefaultNewObject function flag should have prevented the default object
  1050. // being created, except when call true a host dispatch.
  1051. const CallInfo &callInfo = args.Info;
  1052. Var newTarget = args.GetNewTarget();
  1053. bool isCtorSuperCall = JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);
  1054. ScriptContext* scriptContext = function->GetScriptContext();
  1055. JavascriptArray* pNew = nullptr;
  1056. if (callInfo.Count < 2)
  1057. {
  1058. // No arguments passed to Array(), so create with the default size (0).
  1059. pNew = CreateArrayFromConstructorNoArg(function, scriptContext);
  1060. return isCtorSuperCall ?
  1061. JavascriptOperators::OrdinaryCreateFromConstructor(VarTo<RecyclableObject>(newTarget), pNew, nullptr, scriptContext) :
  1062. pNew;
  1063. }
  1064. if (callInfo.Count == 2)
  1065. {
  1066. // Exactly one argument, which is the array length if it's a uint32.
  1067. Var firstArgument = args[1];
  1068. int elementCount;
  1069. if (TaggedInt::Is(firstArgument))
  1070. {
  1071. elementCount = TaggedInt::ToInt32(firstArgument);
  1072. if (elementCount < 0)
  1073. {
  1074. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1075. }
  1076. pNew = CreateArrayFromConstructor(function, elementCount, scriptContext);
  1077. }
  1078. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1079. {
  1080. // Non-tagged-int number: make sure the double value is really a uint32.
  1081. double value = JavascriptNumber::GetValue(firstArgument);
  1082. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1083. if (value != uvalue)
  1084. {
  1085. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  1086. }
  1087. pNew = CreateArrayFromConstructor(function, uvalue, scriptContext);
  1088. }
  1089. else
  1090. {
  1091. //
  1092. // First element is not int/double
  1093. // create an array of length 1.
  1094. // Set first element as the passed Var
  1095. //
  1096. pNew = CreateArrayFromConstructor(function, 1, scriptContext);
  1097. JavascriptOperators::SetItem(pNew, pNew, 0u, firstArgument, scriptContext, PropertyOperation_ThrowIfNotExtensible);
  1098. // If we were passed an uninitialized JavascriptArray as the this argument,
  1099. // we need to set the length. We must do this _after_ setting the first
  1100. // element as the array may have side effects such as a setter for property
  1101. // named '0' which would make the previous length of the array observable.
  1102. // If we weren't passed a JavascriptArray as the this argument, this is no-op.
  1103. pNew->SetLength(1);
  1104. }
  1105. }
  1106. else
  1107. {
  1108. // Called with a list of initial element values.
  1109. // Create an array of the appropriate length and walk the list.
  1110. pNew = CreateArrayFromConstructor(function, callInfo.Count - 1, scriptContext);
  1111. pNew->JavascriptArray::FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1112. }
  1113. #ifdef VALIDATE_ARRAY
  1114. pNew->ValidateArray();
  1115. #endif
  1116. return isCtorSuperCall ?
  1117. JavascriptOperators::OrdinaryCreateFromConstructor(VarTo<RecyclableObject>(newTarget), pNew, nullptr, scriptContext) :
  1118. pNew;
  1119. }
  1120. JavascriptArray* JavascriptArray::CreateArrayFromConstructor(RecyclableObject* constructor, uint32 length, ScriptContext* scriptContext)
  1121. {
  1122. JavascriptLibrary* library = constructor->GetLibrary();
  1123. // Create the Array object we'll return - this is the only way to create an object which is an exotic Array object.
  1124. // Note: We need to use the library from the ScriptContext of the constructor, not the currently executing function.
  1125. // This is for the case where a built-in @@create method from a different JavascriptLibrary is installed on
  1126. // constructor.
  1127. return library->CreateArray(length);
  1128. }
  1129. JavascriptArray* JavascriptArray::CreateArrayFromConstructorNoArg(RecyclableObject* constructor, ScriptContext* scriptContext)
  1130. {
  1131. JavascriptLibrary* library = constructor->GetLibrary();
  1132. return library->CreateArray();
  1133. }
  1134. #if ENABLE_PROFILE_INFO
  1135. Var JavascriptArray::ProfiledNewInstanceNoArg(RecyclableObject *function, ScriptContext *scriptContext, ArrayCallSiteInfo *arrayInfo, RecyclerWeakReference<FunctionBody> *weakFuncRef)
  1136. {
  1137. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_ProfiledNewInstanceNoArg, reentrancylock, scriptContext->GetThreadContext());
  1138. Assert(VarIs<JavascriptFunction>(function) &&
  1139. VarTo<JavascriptFunction>(function)->GetFunctionInfo() == &JavascriptArray::EntryInfo::NewInstance);
  1140. if (arrayInfo->IsNativeIntArray())
  1141. {
  1142. JavascriptNativeIntArray *arr = scriptContext->GetLibrary()->CreateNativeIntArray();
  1143. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1144. return arr;
  1145. }
  1146. if (arrayInfo->IsNativeFloatArray())
  1147. {
  1148. JavascriptNativeFloatArray *arr = scriptContext->GetLibrary()->CreateNativeFloatArray();
  1149. arr->SetArrayProfileInfo(weakFuncRef, arrayInfo);
  1150. return arr;
  1151. }
  1152. return scriptContext->GetLibrary()->CreateArray();
  1153. JIT_HELPER_END(ScrArr_ProfiledNewInstanceNoArg);
  1154. }
  1155. #endif
  1156. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1157. {
  1158. ARGUMENTS(args, callInfo);
  1159. return NewInstance(function, args);
  1160. }
  1161. Var JavascriptNativeIntArray::NewInstance(RecyclableObject* function, Arguments args)
  1162. {
  1163. Assert(!PHASE_OFF1(NativeArrayPhase));
  1164. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1165. const CallInfo &callInfo = args.Info;
  1166. if (callInfo.Count < 2)
  1167. {
  1168. // No arguments passed to Array(), so create with the default size (0).
  1169. return function->GetLibrary()->CreateNativeIntArray();
  1170. }
  1171. JavascriptArray* pNew = nullptr;
  1172. if (callInfo.Count == 2)
  1173. {
  1174. // Exactly one argument, which is the array length if it's a uint32.
  1175. Var firstArgument = args[1];
  1176. int elementCount;
  1177. if (TaggedInt::Is(firstArgument))
  1178. {
  1179. elementCount = TaggedInt::ToInt32(firstArgument);
  1180. if (elementCount < 0)
  1181. {
  1182. JavascriptError::ThrowRangeError(
  1183. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1184. }
  1185. pNew = function->GetLibrary()->CreateNativeIntArray(elementCount);
  1186. }
  1187. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1188. {
  1189. // Non-tagged-int number: make sure the double value is really a uint32.
  1190. double value = JavascriptNumber::GetValue(firstArgument);
  1191. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1192. if (value != uvalue)
  1193. {
  1194. JavascriptError::ThrowRangeError(
  1195. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1196. }
  1197. pNew = function->GetLibrary()->CreateNativeIntArray(uvalue);
  1198. }
  1199. else
  1200. {
  1201. //
  1202. // First element is not int/double
  1203. // create an array of length 1.
  1204. // Set first element as the passed Var
  1205. //
  1206. pNew = function->GetLibrary()->CreateArray(1);
  1207. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1208. }
  1209. }
  1210. else
  1211. {
  1212. // Called with a list of initial element values.
  1213. // Create an array of the appropriate length and walk the list.
  1214. JavascriptNativeIntArray *arr = function->GetLibrary()->CreateNativeIntArray(callInfo.Count - 1);
  1215. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1216. }
  1217. #ifdef VALIDATE_ARRAY
  1218. pNew->ValidateArray();
  1219. #endif
  1220. return pNew;
  1221. }
  1222. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  1223. {
  1224. ARGUMENTS(args, callInfo);
  1225. return NewInstance(function, args);
  1226. }
  1227. Var JavascriptNativeFloatArray::NewInstance(RecyclableObject* function, Arguments args)
  1228. {
  1229. Assert(!PHASE_OFF1(NativeArrayPhase));
  1230. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1231. const CallInfo &callInfo = args.Info;
  1232. if (callInfo.Count < 2)
  1233. {
  1234. // No arguments passed to Array(), so create with the default size (0).
  1235. return function->GetLibrary()->CreateNativeFloatArray();
  1236. }
  1237. JavascriptArray* pNew = nullptr;
  1238. if (callInfo.Count == 2)
  1239. {
  1240. // Exactly one argument, which is the array length if it's a uint32.
  1241. Var firstArgument = args[1];
  1242. int elementCount;
  1243. if (TaggedInt::Is(firstArgument))
  1244. {
  1245. elementCount = TaggedInt::ToInt32(firstArgument);
  1246. if (elementCount < 0)
  1247. {
  1248. JavascriptError::ThrowRangeError(
  1249. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1250. }
  1251. pNew = function->GetLibrary()->CreateNativeFloatArray(elementCount);
  1252. }
  1253. else if (JavascriptNumber::Is_NoTaggedIntCheck(firstArgument))
  1254. {
  1255. // Non-tagged-int number: make sure the double value is really a uint32.
  1256. double value = JavascriptNumber::GetValue(firstArgument);
  1257. uint32 uvalue = JavascriptConversion::ToUInt32(value);
  1258. if (value != uvalue)
  1259. {
  1260. JavascriptError::ThrowRangeError(
  1261. function->GetScriptContext(), JSERR_ArrayLengthConstructIncorrect);
  1262. }
  1263. pNew = function->GetLibrary()->CreateNativeFloatArray(uvalue);
  1264. }
  1265. else
  1266. {
  1267. //
  1268. // First element is not int/double
  1269. // create an array of length 1.
  1270. // Set first element as the passed Var
  1271. //
  1272. pNew = function->GetLibrary()->CreateArray(1);
  1273. pNew->DirectSetItemAt<Var>(0, firstArgument);
  1274. }
  1275. }
  1276. else
  1277. {
  1278. // Called with a list of initial element values.
  1279. // Create an array of the appropriate length and walk the list.
  1280. JavascriptNativeFloatArray *arr = function->GetLibrary()->CreateNativeFloatArray(callInfo.Count - 1);
  1281. pNew = arr->FillFromArgs(callInfo.Count - 1, 0, args.Values);
  1282. }
  1283. #ifdef VALIDATE_ARRAY
  1284. pNew->ValidateArray();
  1285. #endif
  1286. return pNew;
  1287. }
  1288. #if ENABLE_PROFILE_INFO
  1289. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1290. #else
  1291. JavascriptArray * JavascriptNativeIntArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1292. #endif
  1293. {
  1294. uint i;
  1295. for (i = start; i < length; i++)
  1296. {
  1297. Var item = args[i + 1];
  1298. bool isTaggedInt = TaggedInt::Is(item);
  1299. bool isTaggedIntMissingValue = false;
  1300. if (isTaggedInt)
  1301. {
  1302. int32 iValue = TaggedInt::ToInt32(item);
  1303. isTaggedIntMissingValue = Js::SparseArraySegment<int32>::IsMissingItem(&iValue);
  1304. }
  1305. if (isTaggedInt && !isTaggedIntMissingValue)
  1306. {
  1307. // This is taggedInt case and we verified that item is not missing value in AMD64.
  1308. this->DirectSetItemAt(i, TaggedInt::ToInt32(item));
  1309. }
  1310. else if (!isTaggedIntMissingValue && JavascriptNumber::Is_NoTaggedIntCheck(item))
  1311. {
  1312. double dvalue = JavascriptNumber::GetValue(item);
  1313. int32 ivalue;
  1314. if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !Js::SparseArraySegment<int32>::IsMissingItem(&ivalue))
  1315. {
  1316. this->DirectSetItemAt(i, ivalue);
  1317. }
  1318. else
  1319. {
  1320. #if ENABLE_PROFILE_INFO
  1321. if (arrayInfo)
  1322. {
  1323. arrayInfo->SetIsNotNativeIntArray();
  1324. }
  1325. #endif
  1326. if (HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1327. {
  1328. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1329. // array here, so go ahead.
  1330. JavascriptNativeFloatArray *fArr =
  1331. this->GetScriptContext()->GetLibrary()->CreateNativeFloatArrayLiteral(length);
  1332. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, 0, args);
  1333. }
  1334. JavascriptNativeFloatArray *fArr = JavascriptNativeIntArray::ToNativeFloatArray(this);
  1335. fArr->DirectSetItemAt(i, dvalue);
  1336. #if ENABLE_PROFILE_INFO
  1337. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, arrayInfo, dontCreateNewArray);
  1338. #else
  1339. return fArr->JavascriptNativeFloatArray::FillFromArgs(length, i + 1, args, dontCreateNewArray);
  1340. #endif
  1341. }
  1342. }
  1343. else
  1344. {
  1345. #if ENABLE_PROFILE_INFO
  1346. if (arrayInfo)
  1347. {
  1348. arrayInfo->SetIsNotNativeArray();
  1349. }
  1350. #endif
  1351. #pragma prefast(suppress:6237, "The right hand side condition does not have any side effects.")
  1352. if (sizeof(int32) < sizeof(Var) && HasInlineHeadSegment(length) && i < this->head->length && !dontCreateNewArray)
  1353. {
  1354. // Avoid shrinking the number of elements in the head segment. We can still create a new
  1355. // array here, so go ahead.
  1356. JavascriptArray *arr = this->GetScriptContext()->GetLibrary()->CreateArrayLiteral(length);
  1357. return arr->JavascriptArray::FillFromArgs(length, 0, args);
  1358. }
  1359. JavascriptArray *arr = JavascriptNativeIntArray::ToVarArray(this);
  1360. #if ENABLE_PROFILE_INFO
  1361. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1362. #else
  1363. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1364. #endif
  1365. }
  1366. }
  1367. return this;
  1368. }
  1369. #if ENABLE_PROFILE_INFO
  1370. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1371. #else
  1372. JavascriptArray * JavascriptNativeFloatArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1373. #endif
  1374. {
  1375. uint i;
  1376. for (i = start; i < length; i++)
  1377. {
  1378. Var item = args[i + 1];
  1379. if (TaggedInt::Is(item))
  1380. {
  1381. this->DirectSetItemAt(i, TaggedInt::ToDouble(item));
  1382. }
  1383. else if (JavascriptNumber::Is_NoTaggedIntCheck(item))
  1384. {
  1385. this->DirectSetItemAt(i, JavascriptNumber::GetValue(item));
  1386. }
  1387. else
  1388. {
  1389. JavascriptArray *arr = JavascriptNativeFloatArray::ToVarArray(this);
  1390. #if ENABLE_PROFILE_INFO
  1391. if (arrayInfo)
  1392. {
  1393. arrayInfo->SetIsNotNativeArray();
  1394. }
  1395. return arr->JavascriptArray::FillFromArgs(length, i, args, nullptr, dontCreateNewArray);
  1396. #else
  1397. return arr->JavascriptArray::FillFromArgs(length, i, args, dontCreateNewArray);
  1398. #endif
  1399. }
  1400. }
  1401. return this;
  1402. }
  1403. #if ENABLE_PROFILE_INFO
  1404. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, ArrayCallSiteInfo *arrayInfo, bool dontCreateNewArray)
  1405. #else
  1406. JavascriptArray * JavascriptArray::FillFromArgs(uint length, uint start, Var *args, bool dontCreateNewArray)
  1407. #endif
  1408. {
  1409. uint32 i;
  1410. for (i = start; i < length; i++)
  1411. {
  1412. Var item = args[i + 1];
  1413. this->DirectSetItemAt(i, item);
  1414. }
  1415. return this;
  1416. }
  1417. DynamicType * JavascriptNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1418. {
  1419. return scriptContext->GetLibrary()->GetNativeIntArrayType();
  1420. }
  1421. #if ENABLE_COPYONACCESS_ARRAY
  1422. DynamicType * JavascriptCopyOnAccessNativeIntArray::GetInitialType(ScriptContext * scriptContext)
  1423. {
  1424. return scriptContext->GetLibrary()->GetCopyOnAccessNativeIntArrayType();
  1425. }
  1426. #endif
  1427. JavascriptNativeFloatArray *JavascriptNativeIntArray::ToNativeFloatArray(JavascriptNativeIntArray *intArray)
  1428. {
  1429. ScriptContext *scriptContext = intArray->GetScriptContext();
  1430. JIT_HELPER_NOT_REENTRANT_HEADER(IntArr_ToNativeFloatArray, reentrancylock, scriptContext->GetThreadContext());
  1431. #if ENABLE_PROFILE_INFO
  1432. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1433. if (arrayInfo)
  1434. {
  1435. #if DBG
  1436. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1437. Js::JavascriptFunction* caller = nullptr;
  1438. bool foundScriptCaller = false;
  1439. while(walker.GetCaller(&caller))
  1440. {
  1441. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1442. {
  1443. foundScriptCaller = true;
  1444. break;
  1445. }
  1446. }
  1447. if(foundScriptCaller)
  1448. {
  1449. Assert(caller);
  1450. Assert(caller->GetFunctionBody());
  1451. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1452. {
  1453. Output::Print(_u("Conversion: Int array to Float array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1454. Output::Flush();
  1455. }
  1456. }
  1457. else
  1458. {
  1459. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1460. {
  1461. Output::Print(_u("Conversion: Int array to Float array across ScriptContexts"));
  1462. Output::Flush();
  1463. }
  1464. }
  1465. #else
  1466. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1467. {
  1468. Output::Print(_u("Conversion: Int array to Float array"));
  1469. Output::Flush();
  1470. }
  1471. #endif
  1472. arrayInfo->SetIsNotNativeIntArray();
  1473. }
  1474. #endif
  1475. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1476. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1477. // Grow the segments
  1478. Recycler *recycler = scriptContext->GetRecycler();
  1479. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1480. for (seg = intArray->head; seg; seg = nextSeg)
  1481. {
  1482. nextSeg = seg->next;
  1483. uint32 size = seg->size;
  1484. if (size == 0)
  1485. {
  1486. continue;
  1487. }
  1488. uint32 left = seg->left;
  1489. uint32 length = seg->length;
  1490. int i;
  1491. int32 ival;
  1492. // The old segment will have size/2 and length capped by the new size.
  1493. uint32 newSegSize = seg->size >> 1;
  1494. if (seg == intArray->head || seg->length > (newSegSize >> 1))
  1495. {
  1496. // Some live elements are being pushed out of this segment, so allocate a new one.
  1497. SparseArraySegment<double> *newSeg =
  1498. SparseArraySegment<double>::AllocateSegment(recycler, left, length, nextSeg);
  1499. Assert(newSeg != nullptr);
  1500. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1501. newSeg->next = nextSeg;
  1502. intArray->LinkSegments((SparseArraySegment<double>*)prevSeg, newSeg);
  1503. if (intArray->GetLastUsedSegment() == seg)
  1504. {
  1505. intArray->SetLastUsedSegment(newSeg);
  1506. }
  1507. prevSeg = newSeg;
  1508. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1509. if (segmentMap)
  1510. {
  1511. segmentMap->SwapSegment(left, seg, newSeg);
  1512. }
  1513. // Fill the new segment with the overflow.
  1514. for (i = 0; (uint)i < newSeg->length; i++)
  1515. {
  1516. ival = ((SparseArraySegment<int32>*)seg)->elements[i /*+ seg->length*/];
  1517. if (ival == JavascriptNativeIntArray::MissingItem)
  1518. {
  1519. AssertMsgAndFailFast(newSeg != intArray->head || !intArray->HasNoMissingValues(), "Unexpected missing item during array conversion");
  1520. continue;
  1521. }
  1522. newSeg->elements[i] = (double)ival;
  1523. }
  1524. }
  1525. else
  1526. {
  1527. seg->size = newSegSize >> 1;
  1528. seg->CheckLengthvsSize();
  1529. // Now convert the contents that will remain in the old segment.
  1530. for (i = seg->length - 1; i >= 0; i--)
  1531. {
  1532. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1533. if (ival == JavascriptNativeIntArray::MissingItem)
  1534. {
  1535. ((SparseArraySegment<double>*)seg)->elements[i] = (double)JavascriptNativeFloatArray::MissingItem;
  1536. }
  1537. else
  1538. {
  1539. ((SparseArraySegment<double>*)seg)->elements[i] = (double)ival;
  1540. }
  1541. }
  1542. prevSeg = seg;
  1543. }
  1544. }
  1545. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1546. {
  1547. intArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1548. }
  1549. else
  1550. {
  1551. if (intArray->GetDynamicType()->GetIsLocked())
  1552. {
  1553. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1554. if (typeHandler->IsPathTypeHandler())
  1555. {
  1556. // We can't allow a type with the new type ID to be promoted to the old type.
  1557. // So go to a dictionary type handler, which will orphan the new type.
  1558. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1559. // If it does matter, try building a path from the new type's built-in root.
  1560. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1561. }
  1562. else
  1563. {
  1564. intArray->ChangeType();
  1565. }
  1566. }
  1567. intArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1568. }
  1569. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1570. {
  1571. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1572. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(intArray);
  1573. }
  1574. else
  1575. {
  1576. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1577. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(intArray);
  1578. }
  1579. failFastError.Completed();
  1580. return (JavascriptNativeFloatArray*)intArray;
  1581. JIT_HELPER_END(IntArr_ToNativeFloatArray);
  1582. }
  1583. /*
  1584. * JavascriptArray::ChangeArrayTypeToNativeArray<double>
  1585. * - Converts the Var Array's type to NativeFloat.
  1586. * - Sets the VirtualTable to "JavascriptNativeFloatArray"
  1587. */
  1588. template<>
  1589. void JavascriptArray::ChangeArrayTypeToNativeArray<double>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1590. {
  1591. AssertMsg(!VarIs<JavascriptNativeArray>(varArray), "Ensure that the incoming Array is a Var array");
  1592. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1593. {
  1594. varArray->type = scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1595. }
  1596. else
  1597. {
  1598. if (varArray->GetDynamicType()->GetIsLocked())
  1599. {
  1600. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1601. if (typeHandler->IsPathTypeHandler())
  1602. {
  1603. // We can't allow a type with the new type ID to be promoted to the old type.
  1604. // So go to a dictionary type handler, which will orphan the new type.
  1605. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1606. // If it does matter, try building a path from the new type's built-in root.
  1607. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1608. }
  1609. else
  1610. {
  1611. varArray->ChangeType();
  1612. }
  1613. }
  1614. varArray->GetType()->SetTypeId(TypeIds_NativeFloatArray);
  1615. }
  1616. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1617. {
  1618. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1619. VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::SetVirtualTable(varArray);
  1620. }
  1621. else
  1622. {
  1623. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1624. VirtualTableInfo<JavascriptNativeFloatArray>::SetVirtualTable(varArray);
  1625. }
  1626. }
  1627. /*
  1628. * JavascriptArray::ChangeArrayTypeToNativeArray<int32>
  1629. * - Converts the Var Array's type to NativeInt.
  1630. * - Sets the VirtualTable to "JavascriptNativeIntArray"
  1631. */
  1632. template<>
  1633. void JavascriptArray::ChangeArrayTypeToNativeArray<int32>(JavascriptArray * varArray, ScriptContext * scriptContext)
  1634. {
  1635. AssertMsg(!VarIs<JavascriptNativeArray>(varArray), "Ensure that the incoming Array is a Var array");
  1636. if (varArray->GetType() == scriptContext->GetLibrary()->GetArrayType())
  1637. {
  1638. varArray->type = scriptContext->GetLibrary()->GetNativeIntArrayType();
  1639. }
  1640. else
  1641. {
  1642. if (varArray->GetDynamicType()->GetIsLocked())
  1643. {
  1644. DynamicTypeHandler *typeHandler = varArray->GetDynamicType()->GetTypeHandler();
  1645. if (typeHandler->IsPathTypeHandler())
  1646. {
  1647. // We can't allow a type with the new type ID to be promoted to the old type.
  1648. // So go to a dictionary type handler, which will orphan the new type.
  1649. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1650. // If it does matter, try building a path from the new type's built-in root.
  1651. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(varArray);
  1652. }
  1653. else
  1654. {
  1655. varArray->ChangeType();
  1656. }
  1657. }
  1658. varArray->GetType()->SetTypeId(TypeIds_NativeIntArray);
  1659. }
  1660. if (CrossSite::IsCrossSiteObjectTyped(varArray))
  1661. {
  1662. Assert(VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(varArray));
  1663. VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::SetVirtualTable(varArray);
  1664. }
  1665. else
  1666. {
  1667. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(varArray));
  1668. VirtualTableInfo<JavascriptNativeIntArray>::SetVirtualTable(varArray);
  1669. }
  1670. }
  1671. template<>
  1672. int32 JavascriptArray::GetNativeValue<int32>(Js::Var ival, ScriptContext * scriptContext)
  1673. {
  1674. return JavascriptConversion::ToInt32(ival, scriptContext);
  1675. }
  1676. template <>
  1677. double JavascriptArray::GetNativeValue<double>(Var ival, ScriptContext * scriptContext)
  1678. {
  1679. return JavascriptConversion::ToNumber(ival, scriptContext);
  1680. }
  1681. /*
  1682. * JavascriptArray::ConvertToNativeArrayInPlace
  1683. * In place conversion of all Var elements to Native Int/Double elements in an array.
  1684. * We do not update the DynamicProfileInfo of the array here.
  1685. */
  1686. template<typename NativeArrayType, typename T>
  1687. NativeArrayType *JavascriptArray::ConvertToNativeArrayInPlace(JavascriptArray *varArray)
  1688. {
  1689. AssertMsg(!VarIs<JavascriptNativeArray>(varArray), "Ensure that the incoming Array is a Var array");
  1690. ScriptContext *scriptContext = varArray->GetScriptContext();
  1691. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1692. for (seg = varArray->head; seg; seg = nextSeg)
  1693. {
  1694. nextSeg = seg->next;
  1695. uint32 size = seg->size;
  1696. if (size == 0)
  1697. {
  1698. continue;
  1699. }
  1700. int i;
  1701. Var ival;
  1702. uint32 growFactor = sizeof(Var) / sizeof(T);
  1703. AssertMsg(growFactor == 1, "We support only in place conversion of Var array to Native Array");
  1704. // Now convert the contents that will remain in the old segment.
  1705. for (i = seg->length - 1; i >= 0; i--)
  1706. {
  1707. ival = ((SparseArraySegment<Var>*)seg)->elements[i];
  1708. if (ival == JavascriptArray::MissingItem)
  1709. {
  1710. ((SparseArraySegment<T>*)seg)->elements[i] = NativeArrayType::MissingItem;
  1711. }
  1712. else
  1713. {
  1714. ((SparseArraySegment<T>*)seg)->elements[i] = GetNativeValue<T>(ival, scriptContext);
  1715. }
  1716. }
  1717. prevSeg = seg;
  1718. }
  1719. // Update the type of the Array
  1720. ChangeArrayTypeToNativeArray<T>(varArray, scriptContext);
  1721. return (NativeArrayType*)varArray;
  1722. }
  1723. JavascriptArray *JavascriptNativeIntArray::ConvertToVarArray(JavascriptNativeIntArray *intArray)
  1724. {
  1725. #if ENABLE_COPYONACCESS_ARRAY
  1726. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(intArray);
  1727. #endif
  1728. ScriptContext *scriptContext = intArray->GetScriptContext();
  1729. Recycler *recycler = scriptContext->GetRecycler();
  1730. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1731. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1732. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1733. for (seg = intArray->head; seg; seg = nextSeg)
  1734. {
  1735. nextSeg = seg->next;
  1736. uint32 size = seg->size;
  1737. if (size == 0)
  1738. {
  1739. continue;
  1740. }
  1741. uint32 left = seg->left;
  1742. uint32 length = seg->length;
  1743. int i;
  1744. int32 ival;
  1745. // Shrink?
  1746. uint32 growFactor = sizeof(Var) / sizeof(int32);
  1747. if ((growFactor != 1 && (seg == intArray->head || seg->length > (seg->size / growFactor))) ||
  1748. (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler)))
  1749. {
  1750. // Some live elements are being pushed out of this segment, so allocate a new one.
  1751. // And/or the old segment is not scanned by the recycler, so we need a new one to hold vars.
  1752. SparseArraySegment<Var> *newSeg =
  1753. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1754. AnalysisAssert(newSeg);
  1755. // Fill the new segment with the overflow.
  1756. for (i = 0; (uint)i < newSeg->length; i++)
  1757. {
  1758. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1759. if (ival == JavascriptNativeIntArray::MissingItem)
  1760. {
  1761. AssertMsgAndFailFast(seg != intArray->head || !intArray->HasNoMissingValues(), "Unexpected missing item during array conversion");
  1762. continue;
  1763. }
  1764. newSeg->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1765. }
  1766. // seg elements are copied over, now it is safe to replace seg with newSeg.
  1767. // seg could be GC collected if replaced by newSeg.
  1768. Assert((prevSeg == nullptr) == (seg == intArray->head));
  1769. newSeg->next = nextSeg;
  1770. intArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1771. if (intArray->GetLastUsedSegment() == seg)
  1772. {
  1773. intArray->SetLastUsedSegment(newSeg);
  1774. }
  1775. prevSeg = newSeg;
  1776. SegmentBTree * segmentMap = intArray->GetSegmentMap();
  1777. if (segmentMap)
  1778. {
  1779. segmentMap->SwapSegment(left, seg, newSeg);
  1780. }
  1781. }
  1782. else
  1783. {
  1784. seg->size = seg->size / growFactor;
  1785. seg->CheckLengthvsSize();
  1786. // Now convert the contents that will remain in the old segment.
  1787. // Walk backward in case we're growing the element size.
  1788. for (i = seg->length - 1; i >= 0; i--)
  1789. {
  1790. ival = ((SparseArraySegment<int32>*)seg)->elements[i];
  1791. if (ival == JavascriptNativeIntArray::MissingItem)
  1792. {
  1793. AssertMsgAndFailFast(seg != intArray->head || !intArray->HasNoMissingValues(), "Unexpected missing item during array conversion");
  1794. ((SparseArraySegment<Var>*)seg)->elements[i] = (Var)JavascriptArray::MissingItem;
  1795. }
  1796. else
  1797. {
  1798. ((SparseArraySegment<Var>*)seg)->elements[i] = JavascriptNumber::ToVar(ival, scriptContext);
  1799. }
  1800. SparseArraySegment<Var>* newSeg = (SparseArraySegment<Var>*)seg;
  1801. newSeg->FillSegmentBuffer(seg->length, seg->size);
  1802. }
  1803. prevSeg = seg;
  1804. }
  1805. }
  1806. if (intArray->GetType() == scriptContext->GetLibrary()->GetNativeIntArrayType())
  1807. {
  1808. intArray->type = scriptContext->GetLibrary()->GetArrayType();
  1809. }
  1810. else
  1811. {
  1812. if (intArray->GetDynamicType()->GetIsLocked())
  1813. {
  1814. DynamicTypeHandler *typeHandler = intArray->GetDynamicType()->GetTypeHandler();
  1815. if (typeHandler->IsPathTypeHandler())
  1816. {
  1817. // We can't allow a type with the new type ID to be promoted to the old type.
  1818. // So go to a dictionary type handler, which will orphan the new type.
  1819. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  1820. // If it does matter, try building a path from the new type's built-in root.
  1821. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(intArray);
  1822. }
  1823. else
  1824. {
  1825. intArray->ChangeType();
  1826. }
  1827. }
  1828. intArray->GetType()->SetTypeId(TypeIds_Array);
  1829. }
  1830. if (CrossSite::IsCrossSiteObjectTyped(intArray))
  1831. {
  1832. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(intArray));
  1833. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(intArray);
  1834. }
  1835. else
  1836. {
  1837. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(intArray));
  1838. VirtualTableInfo<JavascriptArray>::SetVirtualTable(intArray);
  1839. }
  1840. failFastError.Completed();
  1841. return intArray;
  1842. }
  1843. JavascriptArray *JavascriptNativeIntArray::ToVarArray(JavascriptNativeIntArray *intArray)
  1844. {
  1845. JIT_HELPER_NOT_REENTRANT_HEADER(IntArr_ToVarArray, reentrancylock, intArray->GetScriptContext()->GetThreadContext());
  1846. #if ENABLE_PROFILE_INFO
  1847. ArrayCallSiteInfo *arrayInfo = intArray->GetArrayCallSiteInfo();
  1848. if (arrayInfo)
  1849. {
  1850. #if DBG
  1851. Js::JavascriptStackWalker walker(intArray->GetScriptContext());
  1852. Js::JavascriptFunction* caller = nullptr;
  1853. bool foundScriptCaller = false;
  1854. while(walker.GetCaller(&caller))
  1855. {
  1856. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  1857. {
  1858. foundScriptCaller = true;
  1859. break;
  1860. }
  1861. }
  1862. if(foundScriptCaller)
  1863. {
  1864. Assert(caller);
  1865. Assert(caller->GetFunctionBody());
  1866. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  1867. {
  1868. Output::Print(_u("Conversion: Int array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  1869. Output::Flush();
  1870. }
  1871. }
  1872. else
  1873. {
  1874. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1875. {
  1876. Output::Print(_u("Conversion: Int array to Var array across ScriptContexts"));
  1877. Output::Flush();
  1878. }
  1879. }
  1880. #else
  1881. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  1882. {
  1883. Output::Print(_u("Conversion: Int array to Var array"));
  1884. Output::Flush();
  1885. }
  1886. #endif
  1887. arrayInfo->SetIsNotNativeArray();
  1888. }
  1889. #endif
  1890. intArray->ClearArrayCallSiteIndex();
  1891. return ConvertToVarArray(intArray);
  1892. JIT_HELPER_END(IntArr_ToVarArray);
  1893. }
  1894. DynamicType * JavascriptNativeFloatArray::GetInitialType(ScriptContext * scriptContext)
  1895. {
  1896. return scriptContext->GetLibrary()->GetNativeFloatArrayType();
  1897. }
  1898. /*
  1899. * JavascriptNativeFloatArray::ConvertToVarArray
  1900. * This function only converts all Float elements to Var elements in an array.
  1901. * DynamicProfileInfo of the array is not updated in this function.
  1902. */
  1903. JavascriptArray *JavascriptNativeFloatArray::ConvertToVarArray(JavascriptNativeFloatArray *fArray)
  1904. {
  1905. // We can't be growing the size of the element.
  1906. Assert(sizeof(double) >= sizeof(Var));
  1907. uint32 shrinkFactor = sizeof(double) / sizeof(Var);
  1908. ScriptContext *scriptContext = fArray->GetScriptContext();
  1909. Recycler *recycler = scriptContext->GetRecycler();
  1910. SparseArraySegmentBase *seg, *nextSeg, *prevSeg = nullptr;
  1911. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  1912. AutoDisableInterrupt failFastError(scriptContext->GetThreadContext());
  1913. #if defined(TARGET_32)
  1914. if (fArray->head && (fArray->head->size >= SparseArraySegmentBase::INLINE_CHUNK_SIZE / shrinkFactor))
  1915. {
  1916. CopyHeadIfInlinedHeadSegment<double>(fArray, recycler);
  1917. }
  1918. #endif
  1919. for (seg = fArray->head; seg; seg = nextSeg)
  1920. {
  1921. nextSeg = seg->next;
  1922. if (seg->size == 0)
  1923. {
  1924. continue;
  1925. }
  1926. uint32 left = seg->left;
  1927. uint32 length = seg->length;
  1928. SparseArraySegment<Var> *newSeg = nullptr;
  1929. if (seg->next == nullptr && SparseArraySegmentBase::IsLeafSegment(seg, recycler))
  1930. {
  1931. // The old segment is not scanned by the recycler, so we need a new one to hold vars.
  1932. newSeg =
  1933. SparseArraySegment<Var>::AllocateSegment(recycler, left, length, nextSeg);
  1934. }
  1935. else
  1936. {
  1937. newSeg = (SparseArraySegment<Var>*)seg;
  1938. prevSeg = seg;
  1939. if (shrinkFactor != 1)
  1940. {
  1941. uint32 newSize = seg->size * shrinkFactor;
  1942. uint32 limit;
  1943. if (seg->next)
  1944. {
  1945. limit = seg->next->left;
  1946. }
  1947. else
  1948. {
  1949. limit = JavascriptArray::MaxArrayLength;
  1950. }
  1951. seg->size = min(newSize, limit - seg->left);
  1952. seg->CheckLengthvsSize();
  1953. }
  1954. }
  1955. uint32 i;
  1956. for (i = 0; i < seg->length; i++)
  1957. {
  1958. if (SparseArraySegment<double>::IsMissingItem(&((SparseArraySegment<double>*)seg)->elements[i]))
  1959. {
  1960. AssertMsgAndFailFast(seg != fArray->head || !fArray->HasNoMissingValues(), "Unexpected missing item during conversion");
  1961. if (seg == newSeg)
  1962. {
  1963. newSeg->elements[i] = (Var)JavascriptArray::MissingItem;
  1964. }
  1965. Assert(newSeg->elements[i] == (Var)JavascriptArray::MissingItem);
  1966. }
  1967. else if (*(uint64*)&(((SparseArraySegment<double>*)seg)->elements[i]) == 0ull)
  1968. {
  1969. newSeg->elements[i] = TaggedInt::ToVarUnchecked(0);
  1970. }
  1971. else
  1972. {
  1973. int32 ival;
  1974. double dval = ((SparseArraySegment<double>*)seg)->elements[i];
  1975. if (JavascriptNumber::TryGetInt32Value(dval, &ival) && !TaggedInt::IsOverflow(ival))
  1976. {
  1977. newSeg->elements[i] = TaggedInt::ToVarUnchecked(ival);
  1978. }
  1979. else
  1980. {
  1981. newSeg->elements[i] = JavascriptNumber::ToVarWithCheck(dval, scriptContext);
  1982. }
  1983. }
  1984. }
  1985. if (seg == newSeg)
  1986. {
  1987. // Fill the remaining slots.
  1988. newSeg->FillSegmentBuffer(i, seg->size);
  1989. }
  1990. // seg elements are copied over, now it is safe to replace seg with newSeg.
  1991. // seg could be GC collected if replaced by newSeg.
  1992. if (newSeg != seg)
  1993. {
  1994. Assert((prevSeg == nullptr) == (seg == fArray->head));
  1995. newSeg->next = nextSeg;
  1996. fArray->LinkSegments((SparseArraySegment<Var>*)prevSeg, newSeg);
  1997. if (fArray->GetLastUsedSegment() == seg)
  1998. {
  1999. fArray->SetLastUsedSegment(newSeg);
  2000. }
  2001. prevSeg = newSeg;
  2002. SegmentBTree * segmentMap = fArray->GetSegmentMap();
  2003. if (segmentMap)
  2004. {
  2005. segmentMap->SwapSegment(left, seg, newSeg);
  2006. }
  2007. }
  2008. }
  2009. if (fArray->GetType() == scriptContext->GetLibrary()->GetNativeFloatArrayType())
  2010. {
  2011. fArray->type = scriptContext->GetLibrary()->GetArrayType();
  2012. }
  2013. else
  2014. {
  2015. if (fArray->GetDynamicType()->GetIsLocked())
  2016. {
  2017. DynamicTypeHandler *typeHandler = fArray->GetDynamicType()->GetTypeHandler();
  2018. if (typeHandler->IsPathTypeHandler())
  2019. {
  2020. // We can't allow a type with the new type ID to be promoted to the old type.
  2021. // So go to a dictionary type handler, which will orphan the new type.
  2022. // This should be a corner case, so the inability to share the new type is unlikely to matter.
  2023. // If it does matter, try building a path from the new type's built-in root.
  2024. static_cast<PathTypeHandlerBase*>(typeHandler)->ResetTypeHandler(fArray);
  2025. }
  2026. else
  2027. {
  2028. fArray->ChangeType();
  2029. }
  2030. }
  2031. fArray->GetType()->SetTypeId(TypeIds_Array);
  2032. }
  2033. if (CrossSite::IsCrossSiteObjectTyped(fArray))
  2034. {
  2035. Assert(VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(fArray));
  2036. VirtualTableInfo<CrossSiteObject<JavascriptArray>>::SetVirtualTable(fArray);
  2037. }
  2038. else
  2039. {
  2040. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(fArray));
  2041. VirtualTableInfo<JavascriptArray>::SetVirtualTable(fArray);
  2042. }
  2043. failFastError.Completed();
  2044. return fArray;
  2045. }
  2046. JavascriptArray *JavascriptNativeFloatArray::ToVarArray(JavascriptNativeFloatArray *fArray)
  2047. {
  2048. JIT_HELPER_NOT_REENTRANT_HEADER(FloatArr_ToVarArray, reentrancylock, fArray->GetScriptContext()->GetThreadContext());
  2049. #if ENABLE_PROFILE_INFO
  2050. ArrayCallSiteInfo *arrayInfo = fArray->GetArrayCallSiteInfo();
  2051. if (arrayInfo)
  2052. {
  2053. #if DBG
  2054. Js::JavascriptStackWalker walker(fArray->GetScriptContext());
  2055. Js::JavascriptFunction* caller = nullptr;
  2056. bool foundScriptCaller = false;
  2057. while(walker.GetCaller(&caller))
  2058. {
  2059. if(caller != nullptr && Js::ScriptFunction::Test(caller))
  2060. {
  2061. foundScriptCaller = true;
  2062. break;
  2063. }
  2064. }
  2065. if(foundScriptCaller)
  2066. {
  2067. Assert(caller);
  2068. Assert(caller->GetFunctionBody());
  2069. if(PHASE_TRACE(Js::NativeArrayConversionPhase, caller->GetFunctionBody()))
  2070. {
  2071. Output::Print(_u("Conversion: Float array to Var array ArrayCreationFunctionNumber:%2d CallSiteNumber:%2d \n"), arrayInfo->functionNumber, arrayInfo->callSiteNumber);
  2072. Output::Flush();
  2073. }
  2074. }
  2075. else
  2076. {
  2077. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  2078. {
  2079. Output::Print(_u("Conversion: Float array to Var array across ScriptContexts"));
  2080. Output::Flush();
  2081. }
  2082. }
  2083. #else
  2084. if(PHASE_TRACE1(Js::NativeArrayConversionPhase))
  2085. {
  2086. Output::Print(_u("Conversion: Float array to Var array"));
  2087. Output::Flush();
  2088. }
  2089. #endif
  2090. if(fArray->GetScriptContext()->IsScriptContextInNonDebugMode())
  2091. {
  2092. Assert(!arrayInfo->IsNativeIntArray());
  2093. }
  2094. arrayInfo->SetIsNotNativeArray();
  2095. }
  2096. #endif
  2097. fArray->ClearArrayCallSiteIndex();
  2098. return ConvertToVarArray(fArray);
  2099. JIT_HELPER_END(FloatArr_ToVarArray);
  2100. }
  2101. // Convert Var to index in the Array.
  2102. // Note: Spec calls out a few rules for these parameters:
  2103. // 1. if (arg > length) { return length; }
  2104. // clamp to length, not length-1
  2105. // 2. if (arg < 0) { return max(0, length + arg); }
  2106. // treat negative arg as index from the end of the array (with -1 mapping to length-1)
  2107. // Effectively, this function will return a value between 0 and length, inclusive.
  2108. int64 JavascriptArray::GetIndexFromVar(Js::Var arg, int64 length, ScriptContext* scriptContext)
  2109. {
  2110. int64 index;
  2111. if (TaggedInt::Is(arg))
  2112. {
  2113. int intValue = TaggedInt::ToInt32(arg);
  2114. if (intValue < 0)
  2115. {
  2116. index = max<int64>(0, length + intValue);
  2117. }
  2118. else
  2119. {
  2120. index = intValue;
  2121. }
  2122. if (index > length)
  2123. {
  2124. index = length;
  2125. }
  2126. }
  2127. else
  2128. {
  2129. double doubleValue = JavascriptConversion::ToInteger(arg, scriptContext);
  2130. // Handle the Number.POSITIVE_INFINITY case
  2131. if (doubleValue > length)
  2132. {
  2133. return length;
  2134. }
  2135. index = NumberUtilities::TryToInt64(doubleValue);
  2136. if (index < 0)
  2137. {
  2138. index = max<int64>(0, index + length);
  2139. }
  2140. }
  2141. return index;
  2142. }
  2143. TypeId JavascriptArray::OP_SetNativeIntElementC(JavascriptNativeIntArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2144. {
  2145. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_SetNativeIntElementC, reentrancylock, scriptContext->GetThreadContext());
  2146. int32 iValue;
  2147. double dValue;
  2148. TypeId typeId = arr->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  2149. if (typeId == TypeIds_NativeIntArray)
  2150. {
  2151. arr->SetArrayLiteralItem(index, iValue);
  2152. }
  2153. else if (typeId == TypeIds_NativeFloatArray)
  2154. {
  2155. arr->SetArrayLiteralItem(index, dValue);
  2156. }
  2157. else
  2158. {
  2159. arr->SetArrayLiteralItem(index, value);
  2160. }
  2161. return typeId;
  2162. JIT_HELPER_END(ScrArr_SetNativeIntElementC);
  2163. }
  2164. TypeId JavascriptArray::OP_SetNativeFloatElementC(JavascriptNativeFloatArray *arr, uint32 index, Var value, ScriptContext *scriptContext)
  2165. {
  2166. JIT_HELPER_NOT_REENTRANT_HEADER(ScrArr_SetNativeFloatElementC, reentrancylock, scriptContext->GetThreadContext());
  2167. double dValue;
  2168. TypeId typeId = arr->TrySetNativeFloatArrayItem(value, &dValue);
  2169. if (typeId == TypeIds_NativeFloatArray)
  2170. {
  2171. arr->SetArrayLiteralItem(index, dValue);
  2172. }
  2173. else
  2174. {
  2175. arr->SetArrayLiteralItem(index, value);
  2176. }
  2177. return typeId;
  2178. JIT_HELPER_END(ScrArr_SetNativeFloatElementC);
  2179. }
  2180. template<typename T>
  2181. void JavascriptArray::SetArrayLiteralItem(uint32 index, T value)
  2182. {
  2183. SparseArraySegment<T> * segment = SparseArraySegment<T>::From(this->head);
  2184. Assert(segment->left == 0);
  2185. Assert(index < segment->length);
  2186. segment->elements[index] = value;
  2187. }
  2188. void JavascriptNativeIntArray::SetIsPrototype()
  2189. {
  2190. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2191. ToVarArray(this);
  2192. __super::SetIsPrototype();
  2193. }
  2194. void JavascriptNativeFloatArray::SetIsPrototype()
  2195. {
  2196. // Force the array to be non-native to simplify inspection, filling from proto, etc.
  2197. ToVarArray(this);
  2198. __super::SetIsPrototype();
  2199. }
  2200. #if ENABLE_PROFILE_INFO
  2201. ArrayCallSiteInfo *JavascriptNativeArray::GetArrayCallSiteInfo()
  2202. {
  2203. RecyclerWeakReference<FunctionBody> *weakRef = this->weakRefToFuncBody;
  2204. if (weakRef)
  2205. {
  2206. FunctionBody *functionBody = weakRef->Get();
  2207. if (functionBody)
  2208. {
  2209. if (functionBody->HasDynamicProfileInfo())
  2210. {
  2211. Js::ProfileId profileId = this->GetArrayCallSiteIndex();
  2212. if (profileId < functionBody->GetProfiledArrayCallSiteCount())
  2213. {
  2214. return functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  2215. }
  2216. }
  2217. }
  2218. else
  2219. {
  2220. this->ClearArrayCallSiteIndex();
  2221. }
  2222. }
  2223. return nullptr;
  2224. }
  2225. void JavascriptNativeArray::SetArrayProfileInfo(RecyclerWeakReference<FunctionBody> *weakRef, ArrayCallSiteInfo *arrayInfo)
  2226. {
  2227. Assert(weakRef);
  2228. FunctionBody *functionBody = weakRef->Get();
  2229. if (functionBody && functionBody->HasDynamicProfileInfo())
  2230. {
  2231. ArrayCallSiteInfo *baseInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0);
  2232. Js::ProfileId index = (Js::ProfileId)(arrayInfo - baseInfo);
  2233. Assert(index < functionBody->GetProfiledArrayCallSiteCount());
  2234. SetArrayCallSite(index, weakRef);
  2235. }
  2236. }
  2237. void JavascriptNativeArray::CopyArrayProfileInfo(Js::JavascriptNativeArray* baseArray)
  2238. {
  2239. if (baseArray->weakRefToFuncBody)
  2240. {
  2241. if (baseArray->weakRefToFuncBody->Get())
  2242. {
  2243. SetArrayCallSite(baseArray->GetArrayCallSiteIndex(), baseArray->weakRefToFuncBody);
  2244. }
  2245. else
  2246. {
  2247. baseArray->ClearArrayCallSiteIndex();
  2248. }
  2249. }
  2250. }
  2251. #endif
  2252. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2253. {
  2254. if (VarIs<JavascriptNativeIntArray>(this))
  2255. {
  2256. return this->FindMinOrMax<int32, false>(scriptContext, findMax);
  2257. }
  2258. else
  2259. {
  2260. return this->FindMinOrMax<double, true>(scriptContext, findMax);
  2261. }
  2262. }
  2263. template <typename T, bool checkNaNAndNegZero>
  2264. Var JavascriptNativeArray::FindMinOrMax(Js::ScriptContext * scriptContext, bool findMax)
  2265. {
  2266. AssertMsg(this->HasNoMissingValues(), "Fastpath is only for arrays with one segment and no missing values");
  2267. uint len = this->GetLength();
  2268. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)this->GetHead());
  2269. uint headSegLen = headSegment->length;
  2270. Assert(headSegLen == len);
  2271. if (headSegment->next == nullptr)
  2272. {
  2273. T currentRes = headSegment->elements[0];
  2274. for (uint i = 0; i < headSegLen; i++)
  2275. {
  2276. T compare = headSegment->elements[i];
  2277. if (checkNaNAndNegZero && JavascriptNumber::IsNan(double(compare)))
  2278. {
  2279. return scriptContext->GetLibrary()->GetNaN();
  2280. }
  2281. if (findMax ? currentRes < compare : currentRes > compare ||
  2282. (checkNaNAndNegZero && compare == 0 && Js::JavascriptNumber::IsNegZero(double(currentRes))))
  2283. {
  2284. currentRes = compare;
  2285. }
  2286. }
  2287. return Js::JavascriptNumber::ToVarNoCheck(currentRes, scriptContext);
  2288. }
  2289. else
  2290. {
  2291. AssertMsg(false, "FindMinOrMax currently supports native arrays with only one segment");
  2292. Throw::FatalInternalError();
  2293. }
  2294. }
  2295. SparseArraySegmentBase * JavascriptArray::GetLastUsedSegment() const
  2296. {
  2297. return HasSegmentMap() ?
  2298. PointerValue(segmentUnion.segmentBTreeRoot->lastUsedSegment) :
  2299. PointerValue(segmentUnion.lastUsedSegment);
  2300. }
  2301. void JavascriptArray::SetHeadAndLastUsedSegment(SparseArraySegmentBase * segment)
  2302. {
  2303. Assert(!HasSegmentMap());
  2304. this->head = this->segmentUnion.lastUsedSegment = segment;
  2305. }
  2306. void JavascriptArray::SetLastUsedSegment(SparseArraySegmentBase * segment)
  2307. {
  2308. if (HasSegmentMap())
  2309. {
  2310. this->segmentUnion.segmentBTreeRoot->lastUsedSegment = segment;
  2311. }
  2312. else
  2313. {
  2314. this->segmentUnion.lastUsedSegment = segment;
  2315. }
  2316. }
  2317. bool JavascriptArray::HasSegmentMap() const
  2318. {
  2319. return !!(GetFlags() & DynamicObjectFlags::HasSegmentMap);
  2320. }
  2321. SegmentBTreeRoot * JavascriptArray::GetSegmentMap() const
  2322. {
  2323. return (HasSegmentMap() ? segmentUnion.segmentBTreeRoot : nullptr);
  2324. }
  2325. void JavascriptArray::SetSegmentMap(SegmentBTreeRoot * segmentMap)
  2326. {
  2327. Assert(!HasSegmentMap());
  2328. SparseArraySegmentBase * lastUsedSeg = this->segmentUnion.lastUsedSegment;
  2329. SetFlags(GetFlags() | DynamicObjectFlags::HasSegmentMap);
  2330. segmentUnion.segmentBTreeRoot = segmentMap;
  2331. segmentMap->lastUsedSegment = lastUsedSeg;
  2332. }
  2333. void JavascriptArray::ClearSegmentMap()
  2334. {
  2335. if (HasSegmentMap())
  2336. {
  2337. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  2338. SparseArraySegmentBase * lastUsedSeg = segmentUnion.segmentBTreeRoot->lastUsedSegment;
  2339. segmentUnion.segmentBTreeRoot = nullptr;
  2340. segmentUnion.lastUsedSegment = lastUsedSeg;
  2341. }
  2342. }
  2343. SegmentBTreeRoot * JavascriptArray::BuildSegmentMap()
  2344. {
  2345. Recycler* recycler = GetRecycler();
  2346. SegmentBTreeRoot* tmpSegmentMap = AllocatorNewStruct(Recycler, recycler, SegmentBTreeRoot);
  2347. ForEachSegment([recycler, tmpSegmentMap](SparseArraySegmentBase * current)
  2348. {
  2349. tmpSegmentMap->Add(recycler, current);
  2350. return false;
  2351. });
  2352. // There could be OOM during building segment map. Save to array only after its successful completion.
  2353. SetSegmentMap(tmpSegmentMap);
  2354. return tmpSegmentMap;
  2355. }
  2356. void JavascriptArray::TryAddToSegmentMap(Recycler* recycler, SparseArraySegmentBase* seg)
  2357. {
  2358. SegmentBTreeRoot * savedSegmentMap = GetSegmentMap();
  2359. if (savedSegmentMap)
  2360. {
  2361. //
  2362. // We could OOM and throw when adding to segmentMap, resulting in a corrupted segmentMap on this
  2363. // array. Set segmentMap to null temporarily to protect from this. It will be restored correctly
  2364. // if adding segment succeeds.
  2365. //
  2366. ClearSegmentMap();
  2367. savedSegmentMap->Add(recycler, seg);
  2368. SetSegmentMap(savedSegmentMap);
  2369. }
  2370. }
  2371. void JavascriptArray::InvalidateLastUsedSegment()
  2372. {
  2373. this->SetLastUsedSegment(this->head);
  2374. }
  2375. DescriptorFlags JavascriptArray::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2376. {
  2377. DescriptorFlags flags;
  2378. if (GetSetterBuiltIns(propertyId, info, &flags))
  2379. {
  2380. return flags;
  2381. }
  2382. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2383. }
  2384. DescriptorFlags JavascriptArray::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2385. {
  2386. DescriptorFlags flags;
  2387. PropertyRecord const* propertyRecord;
  2388. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2389. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), info, &flags))
  2390. {
  2391. return flags;
  2392. }
  2393. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2394. }
  2395. bool JavascriptArray::GetSetterBuiltIns(PropertyId propertyId, PropertyValueInfo* info, DescriptorFlags* descriptorFlags)
  2396. {
  2397. if (propertyId == PropertyIds::length)
  2398. {
  2399. PropertyValueInfo::SetNoCache(info, this);
  2400. *descriptorFlags = WritableData;
  2401. return true;
  2402. }
  2403. return false;
  2404. }
  2405. SparseArraySegmentBase * JavascriptArray::GetBeginLookupSegment(uint32 index, const bool useSegmentMap) const
  2406. {
  2407. SparseArraySegmentBase *seg = nullptr;
  2408. SparseArraySegmentBase * lastUsedSeg = this->GetLastUsedSegment();
  2409. if (lastUsedSeg != nullptr && lastUsedSeg->left <= index)
  2410. {
  2411. seg = lastUsedSeg;
  2412. if(index - lastUsedSeg->left < lastUsedSeg->size)
  2413. {
  2414. return seg;
  2415. }
  2416. }
  2417. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  2418. if(!useSegmentMap || !segmentMap)
  2419. {
  2420. return seg ? seg : PointerValue(this->head);
  2421. }
  2422. if(seg)
  2423. {
  2424. // If indexes are being accessed sequentially, check the segment after the last-used segment before checking the
  2425. // segment map, as it is likely to hit
  2426. SparseArraySegmentBase *const nextSeg = seg->next;
  2427. if(nextSeg)
  2428. {
  2429. if(index < nextSeg->left)
  2430. {
  2431. return seg;
  2432. }
  2433. else if(index - nextSeg->left < nextSeg->size)
  2434. {
  2435. return nextSeg;
  2436. }
  2437. }
  2438. }
  2439. SparseArraySegmentBase *matchOrNextSeg;
  2440. segmentMap->Find(index, seg, matchOrNextSeg);
  2441. return seg ? seg : matchOrNextSeg;
  2442. }
  2443. uint32 JavascriptArray::GetNextIndex(uint32 index) const
  2444. {
  2445. if (VarIs<JavascriptNativeIntArray>((Var)this))
  2446. {
  2447. return this->GetNextIndexHelper<int32>(index);
  2448. }
  2449. else if (VarIs<JavascriptNativeFloatArray>((Var)this))
  2450. {
  2451. return this->GetNextIndexHelper<double>(index);
  2452. }
  2453. return this->GetNextIndexHelper<Var>(index);
  2454. }
  2455. template<typename T>
  2456. uint32 JavascriptArray::GetNextIndexHelper(uint32 index) const
  2457. {
  2458. AssertMsg(this->head, "array head should never be null");
  2459. uint candidateIndex;
  2460. if (index == JavascriptArray::InvalidIndex)
  2461. {
  2462. candidateIndex = head->left;
  2463. }
  2464. else
  2465. {
  2466. candidateIndex = index + 1;
  2467. }
  2468. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(candidateIndex);
  2469. while (current != nullptr)
  2470. {
  2471. if ((current->left <= candidateIndex) && ((candidateIndex - current->left) < current->length))
  2472. {
  2473. for (uint i = candidateIndex - current->left; i < current->length; i++)
  2474. {
  2475. if (!SparseArraySegment<T>::IsMissingItem(&current->elements[i]))
  2476. {
  2477. return i + current->left;
  2478. }
  2479. }
  2480. }
  2481. current = SparseArraySegment<T>::From(current->next);
  2482. if (current != NULL)
  2483. {
  2484. if (candidateIndex < current->left)
  2485. {
  2486. candidateIndex = current->left;
  2487. }
  2488. }
  2489. }
  2490. return JavascriptArray::InvalidIndex;
  2491. }
  2492. // If new length > length, we just reset the length
  2493. // If new length < length, we need to remove the rest of the elements and segment
  2494. void JavascriptArray::SetLength(uint32 newLength)
  2495. {
  2496. if (newLength == length)
  2497. return;
  2498. if (head == EmptySegment)
  2499. {
  2500. // Do nothing to the segment.
  2501. }
  2502. else if (newLength == 0)
  2503. {
  2504. this->ClearElements(head, 0);
  2505. head->length = 0;
  2506. head->next = nullptr;
  2507. SetHasNoMissingValues();
  2508. ClearSegmentMap();
  2509. this->InvalidateLastUsedSegment();
  2510. }
  2511. else if (newLength < length)
  2512. {
  2513. // _ _ 2 3 _ _ 6 7 _ _
  2514. // SetLength(0)
  2515. // 0 <= left -> set *prev = null
  2516. // SetLength(2)
  2517. // 2 <= left -> set *prev = null
  2518. // SetLength(3)
  2519. // 3 !<= left; 3 <= right -> truncate to length - 1
  2520. // SetLength(5)
  2521. // 5 <=
  2522. SparseArraySegmentBase* next = GetBeginLookupSegment(newLength - 1); // head, or next.left < newLength
  2523. Field(SparseArraySegmentBase*)* prev = &head;
  2524. while(next != nullptr)
  2525. {
  2526. if (newLength <= next->left)
  2527. {
  2528. ClearSegmentMap(); // truncate segments, null out segmentMap
  2529. *prev = nullptr;
  2530. break;
  2531. }
  2532. else if (newLength <= (next->left + next->length))
  2533. {
  2534. if (next->next)
  2535. {
  2536. ClearSegmentMap(); // Will truncate segments, null out segmentMap
  2537. }
  2538. uint32 newSegmentLength = newLength - next->left;
  2539. this->ClearElements(next, newSegmentLength);
  2540. next->next = nullptr;
  2541. next->length = newSegmentLength;
  2542. next->CheckLengthvsSize();
  2543. break;
  2544. }
  2545. else
  2546. {
  2547. prev = &next->next;
  2548. next = next->next;
  2549. }
  2550. }
  2551. this->InvalidateLastUsedSegment();
  2552. }
  2553. this->length = newLength;
  2554. #ifdef VALIDATE_ARRAY
  2555. ValidateArray();
  2556. #endif
  2557. }
  2558. BOOL JavascriptArray::SetLength(Var newLength)
  2559. {
  2560. ScriptContext *scriptContext;
  2561. if(TaggedInt::Is(newLength))
  2562. {
  2563. int32 lenValue = TaggedInt::ToInt32(newLength);
  2564. if (lenValue < 0)
  2565. {
  2566. scriptContext = GetScriptContext();
  2567. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2568. {
  2569. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2570. }
  2571. }
  2572. else
  2573. {
  2574. this->SetLength(lenValue);
  2575. }
  2576. return TRUE;
  2577. }
  2578. scriptContext = GetScriptContext();
  2579. uint32 uintValue = JavascriptConversion::ToUInt32(newLength, scriptContext);
  2580. double dblValue = JavascriptConversion::ToNumber(newLength, scriptContext);
  2581. if (dblValue == uintValue)
  2582. {
  2583. // Conversion can change the type (e.g. from String), invalidating assumptions made by the JIT
  2584. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_Accessor);
  2585. this->SetLength(uintValue);
  2586. }
  2587. else
  2588. {
  2589. ThreadContext* threadContext = scriptContext->GetThreadContext();
  2590. ImplicitCallFlags flags = threadContext->GetImplicitCallFlags();
  2591. if (flags != ImplicitCall_None && threadContext->IsDisableImplicitCall())
  2592. {
  2593. // We couldn't execute the implicit call(s) needed to convert the newLength to an integer.
  2594. // Do nothing and let the jitted code bail out.
  2595. return TRUE;
  2596. }
  2597. if (threadContext->RecordImplicitException())
  2598. {
  2599. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  2600. }
  2601. }
  2602. return TRUE;
  2603. }
  2604. void JavascriptArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2605. {
  2606. SparseArraySegment<Var>::ClearElements(((SparseArraySegment<Var>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2607. }
  2608. void JavascriptNativeIntArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2609. {
  2610. SparseArraySegment<int32>::ClearElements(((SparseArraySegment<int32>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2611. }
  2612. void JavascriptNativeFloatArray::ClearElements(SparseArraySegmentBase *seg, uint32 newSegmentLength)
  2613. {
  2614. SparseArraySegment<double>::ClearElements(((SparseArraySegment<double>*)seg)->elements + newSegmentLength, seg->length - newSegmentLength);
  2615. }
  2616. Var JavascriptArray::DirectGetItem(uint32 index)
  2617. {
  2618. SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
  2619. uint32 offset = index - seg->left;
  2620. if (index >= seg->left && offset < seg->length)
  2621. {
  2622. if (!SparseArraySegment<Var>::IsMissingItem(&seg->elements[offset]))
  2623. {
  2624. return seg->elements[offset];
  2625. }
  2626. }
  2627. Var element = nullptr;
  2628. if (DirectGetItemAtFull(index, &element))
  2629. {
  2630. return element;
  2631. }
  2632. return GetType()->GetLibrary()->GetUndefined();
  2633. }
  2634. Var JavascriptNativeIntArray::DirectGetItem(uint32 index)
  2635. {
  2636. #if ENABLE_COPYONACCESS_ARRAY
  2637. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2638. #endif
  2639. SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
  2640. uint32 offset = index - seg->left;
  2641. if (index >= seg->left && offset < seg->length)
  2642. {
  2643. if (!SparseArraySegment<int32>::IsMissingItem(&seg->elements[offset]))
  2644. {
  2645. return JavascriptNumber::ToVar(seg->elements[offset], GetScriptContext());
  2646. }
  2647. }
  2648. Var element = nullptr;
  2649. if (DirectGetItemAtFull(index, &element))
  2650. {
  2651. return element;
  2652. }
  2653. return GetType()->GetLibrary()->GetUndefined();
  2654. }
  2655. DescriptorFlags JavascriptNativeIntArray::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
  2656. {
  2657. #if ENABLE_COPYONACCESS_ARRAY
  2658. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  2659. #endif
  2660. int32 value = 0;
  2661. return this->DirectGetItemAt(index, &value) ? WritableData : None;
  2662. }
  2663. Var JavascriptNativeFloatArray::DirectGetItem(uint32 index)
  2664. {
  2665. SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
  2666. uint32 offset = index - seg->left;
  2667. if (index >= seg->left && offset < seg->length)
  2668. {
  2669. if (!SparseArraySegment<double>::IsMissingItem(&seg->elements[offset]))
  2670. {
  2671. return JavascriptNumber::ToVarWithCheck(seg->elements[offset], GetScriptContext());
  2672. }
  2673. }
  2674. Var element = nullptr;
  2675. if (DirectGetItemAtFull(index, &element))
  2676. {
  2677. return element;
  2678. }
  2679. return GetType()->GetLibrary()->GetUndefined();
  2680. }
  2681. Var JavascriptArray::DirectGetItem(JavascriptString *propName, ScriptContext* scriptContext)
  2682. {
  2683. PropertyRecord const * propertyRecord;
  2684. scriptContext->GetOrAddPropertyRecord(propName, &propertyRecord);
  2685. return JavascriptOperators::GetProperty(this, propertyRecord->GetPropertyId(), scriptContext, NULL);
  2686. }
  2687. BOOL JavascriptArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  2688. {
  2689. if (this->DirectGetItemAt(index, outVal))
  2690. {
  2691. return TRUE;
  2692. }
  2693. ScriptContext* requestContext = type->GetScriptContext();
  2694. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  2695. }
  2696. //
  2697. // Link prev and current. If prev is NULL, make current the head segment.
  2698. //
  2699. void JavascriptArray::LinkSegmentsCommon(SparseArraySegmentBase* prev, SparseArraySegmentBase* current)
  2700. {
  2701. if (prev)
  2702. {
  2703. prev->next = current;
  2704. }
  2705. else
  2706. {
  2707. Assert(current);
  2708. head = current;
  2709. }
  2710. }
  2711. template<typename T>
  2712. BOOL JavascriptArray::DirectDeleteItemAt(uint32 itemIndex)
  2713. {
  2714. if (itemIndex >= length)
  2715. {
  2716. return true;
  2717. }
  2718. SparseArraySegment<T>* next = (SparseArraySegment<T>*)GetBeginLookupSegment(itemIndex);
  2719. while(next != nullptr && next->left <= itemIndex)
  2720. {
  2721. uint32 limit = next->left + next->length;
  2722. if (itemIndex < limit)
  2723. {
  2724. next->SetElement(GetRecycler(), itemIndex, SparseArraySegment<T>::GetMissingItem());
  2725. if(itemIndex - next->left == next->length - 1)
  2726. {
  2727. --next->length;
  2728. next->CheckLengthvsSize();
  2729. }
  2730. else if(next == head)
  2731. {
  2732. SetHasNoMissingValues(false);
  2733. }
  2734. break;
  2735. }
  2736. next = SparseArraySegment<T>::From(next->next);
  2737. }
  2738. #ifdef VALIDATE_ARRAY
  2739. ValidateArray();
  2740. #endif
  2741. return true;
  2742. }
  2743. template <> Var JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2744. {
  2745. return idxDest.ToNumber(scriptContext);
  2746. }
  2747. template <> uint32 JavascriptArray::ConvertToIndex(BigIndex idxDest, ScriptContext* scriptContext)
  2748. {
  2749. // Note this is only for setting Array length which is a uint32
  2750. return idxDest.IsSmallIndex() ? idxDest.GetSmallIndex() : UINT_MAX;
  2751. }
  2752. template <> Var JavascriptArray::ConvertToIndex(uint32 idxDest, ScriptContext* scriptContext)
  2753. {
  2754. return JavascriptNumber::ToVar(idxDest, scriptContext);
  2755. }
  2756. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, uint32 index)
  2757. {
  2758. if (!succeeded)
  2759. {
  2760. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(index, scriptContext), scriptContext)->GetSz());
  2761. }
  2762. }
  2763. void JavascriptArray::ThrowErrorOnFailure(BOOL succeeded, ScriptContext* scriptContext, BigIndex index)
  2764. {
  2765. if (!succeeded)
  2766. {
  2767. uint64 i = (uint64)(index.IsSmallIndex() ? index.GetSmallIndex() : index.GetBigIndex());
  2768. JavascriptError::ThrowTypeError(scriptContext, JSERR_CantRedefineProp, JavascriptConversion::ToString(JavascriptNumber::ToVar(i, scriptContext), scriptContext)->GetSz());
  2769. }
  2770. }
  2771. void JavascriptArray::CreateDataPropertyOrThrow(RecyclableObject * obj, BigIndex index, Var item, ScriptContext * scriptContext)
  2772. {
  2773. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2774. JavascriptArray * arr = JavascriptArray::TryVarToNonES5Array(obj);
  2775. if (arr != nullptr)
  2776. {
  2777. arr->GenericDirectSetItemAt(index, item);
  2778. }
  2779. else
  2780. {
  2781. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(obj, index, item), scriptContext, index));
  2782. }
  2783. }
  2784. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, uint32 idxDest, Var aItem)
  2785. {
  2786. return pDestObj->SetItem(idxDest, aItem, Js::PropertyOperation_ThrowIfNotExtensible);
  2787. }
  2788. uint64 JavascriptArray::OP_GetLength(Var obj, ScriptContext *scriptContext)
  2789. {
  2790. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  2791. {
  2792. // Casting to uint64 is okay as ToLength will always be >= 0.
  2793. return (uint64)JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2794. }
  2795. else
  2796. {
  2797. return (uint64)JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  2798. }
  2799. }
  2800. template<typename T>
  2801. void JavascriptArray::TryGetArrayAndLength(Var arg,
  2802. ScriptContext *scriptContext,
  2803. PCWSTR methodName,
  2804. __out JavascriptArray** array,
  2805. __out RecyclableObject** obj,
  2806. __out T * length)
  2807. {
  2808. Assert(array != nullptr);
  2809. Assert(obj != nullptr);
  2810. Assert(length != nullptr);
  2811. *array = JavascriptArray::TryVarToNonES5Array(arg);
  2812. if (*array && !(*array)->IsCrossSiteObject())
  2813. {
  2814. #if ENABLE_COPYONACCESS_ARRAY
  2815. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(*array);
  2816. #endif
  2817. *obj = *array;
  2818. *length = (*array)->length;
  2819. }
  2820. else
  2821. {
  2822. if (!JavascriptConversion::ToObject(arg, scriptContext, obj))
  2823. {
  2824. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, methodName);
  2825. }
  2826. *length = OP_GetLength(*obj, scriptContext);
  2827. *array = nullptr;
  2828. }
  2829. }
  2830. BOOL JavascriptArray::SetArrayLikeObjects(RecyclableObject* pDestObj, BigIndex idxDest, Var aItem)
  2831. {
  2832. ScriptContext* scriptContext = pDestObj->GetScriptContext();
  2833. PropertyRecord const * propertyRecord;
  2834. if (idxDest.IsSmallIndex())
  2835. {
  2836. JavascriptOperators::GetPropertyIdForInt(idxDest.GetSmallIndex(), scriptContext, &propertyRecord);
  2837. }
  2838. else
  2839. {
  2840. JavascriptOperators::GetPropertyIdForInt(idxDest.GetBigIndex(), scriptContext, &propertyRecord);
  2841. }
  2842. PropertyDescriptor propertyDescriptor;
  2843. propertyDescriptor.SetConfigurable(true);
  2844. propertyDescriptor.SetEnumerable(true);
  2845. propertyDescriptor.SetWritable(true);
  2846. propertyDescriptor.SetValue(aItem);
  2847. return JavascriptObject::DefineOwnPropertyHelper(pDestObj, propertyRecord->GetPropertyId(), propertyDescriptor, scriptContext, false);
  2848. }
  2849. template<typename T>
  2850. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2851. Js::Arguments& args, ScriptContext* scriptContext, uint start, BigIndex startIdxDest,
  2852. ConcatSpreadableState previousItemSpreadableState /*= ConcatSpreadableState_NotChecked*/, BigIndex *firstPromotedItemLength /* = nullptr */)
  2853. {
  2854. // This never gets called.
  2855. Throw::InternalError();
  2856. }
  2857. //
  2858. // Helper for EntryConcat. Concat args or elements of arg arrays into dest array.
  2859. //
  2860. template<typename T>
  2861. void JavascriptArray::ConcatArgs(RecyclableObject* pDestObj, TypeId* remoteTypeIds,
  2862. Js::Arguments& args, ScriptContext* scriptContext, uint start, uint startIdxDest,
  2863. ConcatSpreadableState previousItemSpreadableState /*= ConcatSpreadableState_NotChecked*/, BigIndex *firstPromotedItemLength /* = nullptr */)
  2864. {
  2865. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  2866. JavascriptArray* pDestArray = JavascriptArray::TryVarToNonES5Array(pDestObj);
  2867. if (pDestArray)
  2868. {
  2869. // ConcatArgs function expects to work on the Var array so we are ensuring it.
  2870. pDestArray = EnsureNonNativeArray(pDestArray);
  2871. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  2872. }
  2873. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled()); // ConcatSpreadable is enabled already - not going back.
  2874. T idxDest = startIdxDest;
  2875. for (uint idxArg = start; idxArg < args.Info.Count; idxArg++)
  2876. {
  2877. Var aItem = args[idxArg];
  2878. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  2879. bool spreadable = previousItemSpreadableState == ConcatSpreadableState_CheckedAndTrue;
  2880. if (previousItemSpreadableState == ConcatSpreadableState_NotChecked)
  2881. {
  2882. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  2883. }
  2884. // Reset the state for the next item in the array
  2885. previousItemSpreadableState = ConcatSpreadableState_NotChecked;
  2886. if (!spreadable)
  2887. {
  2888. JS_REENTRANT(jsReentLock, JavascriptArray::SetConcatItem<T>(aItem, idxArg, pDestArray, pDestObj, idxDest, scriptContext));
  2889. ++idxDest;
  2890. continue;
  2891. }
  2892. if (pDestArray && JavascriptArray::IsDirectAccessArray(aItem) && JavascriptArray::IsDirectAccessArray(pDestArray)
  2893. && BigIndex(idxDest + UnsafeVarTo<JavascriptArray>(aItem)->length).IsSmallIndex() && !UnsafeVarTo<JavascriptArray>(aItem)->IsFillFromPrototypes()) // Fast path
  2894. {
  2895. JavascriptNativeIntArray *pIntItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  2896. if (pIntItemArray)
  2897. {
  2898. JS_REENTRANT_NO_MUTATE(jsReentLock, CopyNativeIntArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pIntItemArray));
  2899. idxDest = idxDest + pIntItemArray->length;
  2900. }
  2901. else
  2902. {
  2903. JavascriptNativeFloatArray *pFloatItemArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(aItem);
  2904. if (pFloatItemArray)
  2905. {
  2906. JS_REENTRANT_NO_MUTATE(jsReentLock, CopyNativeFloatArrayElementsToVar(pDestArray, BigIndex(idxDest).GetSmallIndex(), pFloatItemArray));
  2907. idxDest = idxDest + pFloatItemArray->length;
  2908. }
  2909. else
  2910. {
  2911. JavascriptArray* pItemArray = UnsafeVarTo<JavascriptArray>(aItem);
  2912. JS_REENTRANT(jsReentLock, CopyArrayElements(pDestArray, BigIndex(idxDest).GetSmallIndex(), pItemArray));
  2913. idxDest = idxDest + pItemArray->length;
  2914. }
  2915. }
  2916. }
  2917. else
  2918. {
  2919. AssertOrFailFast(VarIs<RecyclableObject>(aItem));
  2920. //CONSIDER: enumerating remote array instead of walking all indices
  2921. BigIndex length;
  2922. if (firstPromotedItemLength != nullptr)
  2923. {
  2924. length = *firstPromotedItemLength;
  2925. }
  2926. else
  2927. {
  2928. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext));
  2929. }
  2930. if (PromoteToBigIndex(length, idxDest))
  2931. {
  2932. // This is a special case for spreadable objects. We do not pre-calculate the length
  2933. // in EntryConcat like we do with Arrays because a getProperty on an object Length
  2934. // is observable. The result is we have to check for overflows separately for
  2935. // spreadable objects and promote to a bigger index type when we find them.
  2936. JS_REENTRANT(jsReentLock, ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  2937. return;
  2938. }
  2939. if (length + idxDest > FiftyThirdPowerOfTwoMinusOne) // 2^53-1: from ECMA 22.1.3.1 Array.prototype.concat(...arguments)
  2940. {
  2941. JavascriptError::ThrowTypeError(scriptContext, JSERR_IllegalArraySizeAndLength);
  2942. }
  2943. RecyclableObject* itemObject = VarTo<RecyclableObject>(aItem);
  2944. Var subItem;
  2945. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  2946. for (uint32 idxSubItem = 0u; idxSubItem < lengthToUin32Max; ++idxSubItem)
  2947. {
  2948. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(itemObject, idxSubItem));
  2949. if (hasItem)
  2950. {
  2951. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetItem(itemObject, idxSubItem, scriptContext));
  2952. if (pDestArray)
  2953. {
  2954. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2955. }
  2956. else
  2957. {
  2958. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxDest));
  2959. }
  2960. }
  2961. ++idxDest;
  2962. }
  2963. for (BigIndex idxSubItem = MaxArrayLength; idxSubItem < length; ++idxSubItem)
  2964. {
  2965. PropertyRecord const * propertyRecord;
  2966. JavascriptOperators::GetPropertyIdForInt(idxSubItem.GetBigIndex(), scriptContext, &propertyRecord);
  2967. JS_REENTRANT(jsReentLock, BOOL hasProp = JavascriptOperators::HasProperty(itemObject, propertyRecord->GetPropertyId()));
  2968. if (hasProp)
  2969. {
  2970. JS_REENTRANT(jsReentLock, subItem = JavascriptOperators::GetProperty(itemObject, propertyRecord->GetPropertyId(), scriptContext));
  2971. if (pDestArray)
  2972. {
  2973. pDestArray->GenericDirectSetItemAt(idxDest, subItem);
  2974. }
  2975. else
  2976. {
  2977. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(SetArrayLikeObjects(pDestObj, idxDest, subItem), scriptContext, idxSubItem));
  2978. }
  2979. }
  2980. ++idxDest;
  2981. }
  2982. }
  2983. firstPromotedItemLength = nullptr;
  2984. }
  2985. if (!pDestArray)
  2986. {
  2987. JS_REENTRANT(jsReentLock, pDestObj->SetProperty(PropertyIds::length, ConvertToIndex<T, Var>(idxDest, scriptContext), Js::PropertyOperation_None, nullptr));
  2988. }
  2989. else if (pDestArray->GetLength() != ConvertToIndex<T, uint32>(idxDest, scriptContext))
  2990. {
  2991. pDestArray->SetLength(ConvertToIndex<T, uint32>(idxDest, scriptContext));
  2992. }
  2993. }
  2994. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, BigIndex rhs)
  2995. {
  2996. return false; // already a big index
  2997. }
  2998. bool JavascriptArray::PromoteToBigIndex(BigIndex lhs, uint32 rhs)
  2999. {
  3000. ::Math::RecordOverflowPolicy destLengthOverflow;
  3001. if (lhs.IsSmallIndex())
  3002. {
  3003. UInt32Math::Add(lhs.GetSmallIndex(), rhs, destLengthOverflow);
  3004. return destLengthOverflow.HasOverflowed();
  3005. }
  3006. return true;
  3007. }
  3008. JavascriptArray* JavascriptArray::ConcatIntArgs(JavascriptNativeIntArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  3009. {
  3010. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3011. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  3012. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled());
  3013. Assert(pDestArray->GetTypeId() == TypeIds_NativeIntArray);
  3014. uint idxDest = 0u;
  3015. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3016. {
  3017. Var aItem = args[idxArg];
  3018. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  3019. bool spreadable = false;
  3020. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  3021. if (!VarIsCorrectType(pDestArray))
  3022. {
  3023. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest,
  3024. spreadable ? ConcatSpreadableState_CheckedAndTrue : ConcatSpreadableState_CheckedAndFalse));
  3025. return pDestArray;
  3026. }
  3027. if (!spreadable)
  3028. {
  3029. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  3030. idxDest++;
  3031. if (!VarIsCorrectType(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  3032. {
  3033. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  3034. return pDestArray;
  3035. }
  3036. continue;
  3037. }
  3038. JavascriptNativeIntArray * pItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  3039. if (pItemArray && !pItemArray->IsFillFromPrototypes()) // Fast path
  3040. {
  3041. JS_REENTRANT_NO_MUTATE(jsReentLock, bool converted = CopyNativeIntArrayElements(pDestArray, idxDest, pItemArray));
  3042. idxDest = idxDest + pItemArray->length;
  3043. if (converted)
  3044. {
  3045. // Copying the last array forced a conversion, so switch over to the var version
  3046. // to finish.
  3047. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  3048. return pDestArray;
  3049. }
  3050. }
  3051. else if (!JavascriptArray::IsAnyArray(aItem) && remoteTypeIds[idxArg] != TypeIds_Array)
  3052. {
  3053. if (TaggedInt::Is(aItem))
  3054. {
  3055. int32 int32Value = TaggedInt::ToInt32(aItem);
  3056. Assert(!SparseArraySegment<int32>::IsMissingItem(&int32Value));
  3057. pDestArray->DirectSetItemAt(idxDest, int32Value);
  3058. }
  3059. else
  3060. {
  3061. pDestArray->DirectSetItemAt(idxDest, static_cast<int32>(JavascriptNumber::GetValue(aItem)));
  3062. }
  3063. ++idxDest;
  3064. }
  3065. else
  3066. {
  3067. JavascriptArray *pVarDestArray = JavascriptNativeIntArray::ConvertToVarArray(pDestArray);
  3068. BigIndex length;
  3069. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  3070. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  3071. return pVarDestArray;
  3072. }
  3073. }
  3074. if (pDestArray->GetLength() != idxDest)
  3075. {
  3076. pDestArray->SetLength(idxDest);
  3077. }
  3078. return pDestArray;
  3079. }
  3080. JavascriptArray* JavascriptArray::ConcatFloatArgs(JavascriptNativeFloatArray* pDestArray, TypeId *remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext)
  3081. {
  3082. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3083. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pDestArray);
  3084. AssertOrFailFast(scriptContext->GetConfig()->IsES6IsConcatSpreadableEnabled());
  3085. uint idxDest = 0u;
  3086. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3087. {
  3088. Var aItem = args[idxArg];
  3089. SETOBJECT_FOR_MUTATION(jsReentLock, aItem);
  3090. bool spreadable = false;
  3091. JS_REENTRANT(jsReentLock, spreadable = !!JavascriptOperators::IsConcatSpreadable(aItem));
  3092. if (!VarIsCorrectType(pDestArray))
  3093. {
  3094. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest,
  3095. spreadable ? ConcatSpreadableState_CheckedAndTrue : ConcatSpreadableState_CheckedAndFalse));
  3096. return pDestArray;
  3097. }
  3098. if (!spreadable)
  3099. {
  3100. JS_REENTRANT(jsReentLock, pDestArray->SetItem(idxDest, aItem, PropertyOperation_ThrowIfNotExtensible));
  3101. idxDest = idxDest + 1;
  3102. if (!VarIsCorrectType(pDestArray)) // SetItem could convert pDestArray to a var array if aItem is not an integer if so fall back
  3103. {
  3104. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  3105. return pDestArray;
  3106. }
  3107. continue;
  3108. }
  3109. bool converted = false;
  3110. if (JavascriptArray::IsAnyArray(aItem) || remoteTypeIds[idxArg] == TypeIds_Array)
  3111. {
  3112. bool isFillFromPrototypes = UnsafeVarTo<JavascriptArray>(aItem)->IsFillFromPrototypes();
  3113. JavascriptNativeIntArray * pIntItemArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(aItem);
  3114. if (pIntItemArray && !isFillFromPrototypes) // Fast path
  3115. {
  3116. JS_REENTRANT_NO_MUTATE(jsReentLock, converted = CopyNativeIntArrayElementsToFloat(pDestArray, idxDest, pIntItemArray));
  3117. idxDest = idxDest + pIntItemArray->length;
  3118. }
  3119. else
  3120. {
  3121. JavascriptNativeFloatArray * pFloatItemArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(aItem);
  3122. if (pFloatItemArray && !isFillFromPrototypes)
  3123. {
  3124. JS_REENTRANT_NO_MUTATE(jsReentLock, converted = CopyNativeFloatArrayElements(pDestArray, idxDest, pFloatItemArray));
  3125. idxDest = idxDest + pFloatItemArray->length;
  3126. }
  3127. else
  3128. {
  3129. JavascriptArray *pVarDestArray = JavascriptNativeFloatArray::ConvertToVarArray(pDestArray);
  3130. BigIndex length;
  3131. JS_REENTRANT(jsReentLock, length = OP_GetLength(aItem, scriptContext),
  3132. ConcatArgs<uint>(pVarDestArray, remoteTypeIds, args, scriptContext, idxArg, idxDest, ConcatSpreadableState_CheckedAndTrue, &length));
  3133. return pVarDestArray;
  3134. }
  3135. }
  3136. if (converted)
  3137. {
  3138. // Copying the last array forced a conversion, so switch over to the var version
  3139. // to finish.
  3140. JS_REENTRANT(jsReentLock, ConcatArgs<uint>(pDestArray, remoteTypeIds, args, scriptContext, idxArg + 1, idxDest, ConcatSpreadableState_NotChecked));
  3141. return pDestArray;
  3142. }
  3143. }
  3144. else
  3145. {
  3146. if (TaggedInt::Is(aItem))
  3147. {
  3148. pDestArray->DirectSetItemAt(idxDest, (double)TaggedInt::ToInt32(aItem));
  3149. }
  3150. else
  3151. {
  3152. Assert(JavascriptNumber::Is(aItem));
  3153. pDestArray->DirectSetItemAt(idxDest, JavascriptNumber::GetValue(aItem));
  3154. }
  3155. ++idxDest;
  3156. }
  3157. }
  3158. if (pDestArray->GetLength() != idxDest)
  3159. {
  3160. pDestArray->SetLength(idxDest);
  3161. }
  3162. return pDestArray;
  3163. }
  3164. bool JavascriptArray::BoxConcatItem(Var aItem, uint idxArg, ScriptContext *scriptContext)
  3165. {
  3166. return idxArg == 0 && !JavascriptOperators::IsObject(aItem);
  3167. }
  3168. Var JavascriptArray::EntryConcat(RecyclableObject* function, CallInfo callInfo, ...)
  3169. {
  3170. JIT_HELPER_REENTRANT_HEADER(Array_Concat);
  3171. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3172. ARGUMENTS(args, callInfo);
  3173. ScriptContext* scriptContext = function->GetScriptContext();
  3174. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3175. Assert(!(callInfo.Flags & CallFlags_New));
  3176. if (args.Info.Count == 0)
  3177. {
  3178. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3179. }
  3180. //
  3181. // Compute the destination ScriptArray size:
  3182. // - Each item, flattening only one level if a ScriptArray.
  3183. //
  3184. uint32 cDestLength = 0;
  3185. JavascriptArray * pDestArray = NULL;
  3186. PROBE_STACK_NO_DISPOSE(function->GetScriptContext(), Js::Constants::MinStackDefault + (args.Info.Count * sizeof(TypeId*)));
  3187. TypeId* remoteTypeIds = (TypeId*)_alloca(args.Info.Count * sizeof(TypeId*));
  3188. bool isInt = true;
  3189. bool isFloat = true;
  3190. ::Math::RecordOverflowPolicy destLengthOverflow;
  3191. for (uint idxArg = 0; idxArg < args.Info.Count; idxArg++)
  3192. {
  3193. Var aItem = args[idxArg];
  3194. #if ENABLE_COPYONACCESS_ARRAY
  3195. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(aItem);
  3196. #endif
  3197. if (DynamicObject::IsAnyArray(aItem)) // Get JavascriptArray or ES5Array length
  3198. {
  3199. JavascriptArray * pItemArray = JavascriptArray::FromAnyArray(aItem);
  3200. if (isFloat)
  3201. {
  3202. if (!VarIs<JavascriptNativeIntArray>(pItemArray))
  3203. {
  3204. isInt = false;
  3205. if (!VarIs<JavascriptNativeFloatArray>(pItemArray))
  3206. {
  3207. isFloat = false;
  3208. }
  3209. }
  3210. }
  3211. cDestLength = UInt32Math::Add(cDestLength, pItemArray->GetLength(), destLengthOverflow);
  3212. }
  3213. else // Get remote array or object length
  3214. {
  3215. // We already checked for types derived from JavascriptArray. These are types that should behave like array
  3216. // i.e. proxy to array and remote array.
  3217. JS_REENTRANT(jsReentLock, BOOL isArray = JavascriptOperators::IsArray(aItem));
  3218. if (isArray)
  3219. {
  3220. // Don't try to preserve nativeness of remote arrays. The extra complexity is probably not
  3221. // worth it.
  3222. isInt = false;
  3223. isFloat = false;
  3224. if (!VarIs<JavascriptProxy>(aItem))
  3225. {
  3226. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  3227. {
  3228. JS_REENTRANT(jsReentLock,
  3229. int64 len = JavascriptConversion::ToLength(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3230. // clipping to MaxArrayLength will overflow when added to cDestLength which we catch below
  3231. cDestLength = UInt32Math::Add(cDestLength, len < MaxArrayLength ? (uint32)len : MaxArrayLength, destLengthOverflow);
  3232. }
  3233. else
  3234. {
  3235. JS_REENTRANT(jsReentLock,
  3236. uint len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(aItem, scriptContext), scriptContext));
  3237. cDestLength = UInt32Math::Add(cDestLength, len, destLengthOverflow);
  3238. }
  3239. }
  3240. remoteTypeIds[idxArg] = TypeIds_Array; // Mark remote array, no matter remote JavascriptArray or ES5Array.
  3241. }
  3242. else
  3243. {
  3244. if (isFloat)
  3245. {
  3246. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3247. {
  3248. // A primitive will be boxed, so we have to create a var array for the result.
  3249. isInt = false;
  3250. isFloat = false;
  3251. }
  3252. else if (!TaggedInt::Is(aItem))
  3253. {
  3254. if (!JavascriptNumber::Is(aItem))
  3255. {
  3256. isInt = false;
  3257. isFloat = false;
  3258. }
  3259. else if (isInt)
  3260. {
  3261. int32 int32Value;
  3262. if(!JavascriptNumber::TryGetInt32Value(JavascriptNumber::GetValue(aItem), &int32Value) ||
  3263. SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3264. {
  3265. isInt = false;
  3266. }
  3267. }
  3268. }
  3269. else if(isInt)
  3270. {
  3271. int32 int32Value = TaggedInt::ToInt32(aItem);
  3272. if(SparseArraySegment<int32>::IsMissingItem(&int32Value))
  3273. {
  3274. isInt = false;
  3275. }
  3276. }
  3277. }
  3278. remoteTypeIds[idxArg] = TypeIds_Limit;
  3279. cDestLength = UInt32Math::Add(cDestLength, 1, destLengthOverflow);
  3280. }
  3281. }
  3282. }
  3283. if (destLengthOverflow.HasOverflowed())
  3284. {
  3285. cDestLength = MaxArrayLength;
  3286. isInt = false;
  3287. isFloat = false;
  3288. }
  3289. //
  3290. // Create the destination array
  3291. //
  3292. RecyclableObject* pDestObj = nullptr;
  3293. bool isArray = false;
  3294. JS_REENTRANT_NO_MUTATE(jsReentLock, pDestObj = ArraySpeciesCreate(args[0], 0, scriptContext));
  3295. if (pDestObj)
  3296. {
  3297. #if ENABLE_COPYONACCESS_ARRAY
  3298. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pDestObj);
  3299. #endif
  3300. // Check the thing that species create made. If it's a native array that can't handle the source
  3301. // data, convert it. If it's a more conservative kind of array than the source data, indicate that
  3302. // so that the data will be converted on copy.
  3303. if (isInt)
  3304. {
  3305. if (VarIs<JavascriptNativeIntArray>(pDestObj))
  3306. {
  3307. isArray = true;
  3308. }
  3309. else
  3310. {
  3311. isInt = false;
  3312. isFloat = VarIs<JavascriptNativeFloatArray>(pDestObj);
  3313. isArray = JavascriptArray::IsNonES5Array(pDestObj);
  3314. }
  3315. }
  3316. else if (isFloat)
  3317. {
  3318. JavascriptNativeIntArray *nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(pDestObj);
  3319. if (nativeIntArray)
  3320. {
  3321. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  3322. isArray = true;
  3323. }
  3324. else
  3325. {
  3326. isFloat = VarIs<JavascriptNativeFloatArray>(pDestObj);
  3327. isArray = JavascriptArray::IsNonES5Array(pDestObj);
  3328. }
  3329. }
  3330. else
  3331. {
  3332. JavascriptNativeIntArray *nativeIntArray = JavascriptOperators::TryFromVar<Js::JavascriptNativeIntArray>(pDestObj);
  3333. if (nativeIntArray)
  3334. {
  3335. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  3336. isArray = true;
  3337. }
  3338. else
  3339. {
  3340. JavascriptNativeFloatArray *nativeFloatArray = JavascriptOperators::TryFromVar<Js::JavascriptNativeFloatArray>(pDestObj);
  3341. if (nativeFloatArray)
  3342. {
  3343. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  3344. isArray = true;
  3345. }
  3346. else
  3347. {
  3348. isArray = JavascriptArray::IsNonES5Array(pDestObj);
  3349. }
  3350. }
  3351. }
  3352. }
  3353. if (pDestObj == nullptr || isArray)
  3354. {
  3355. if (isInt)
  3356. {
  3357. JavascriptNativeIntArray *pIntArray = isArray ? VarTo<JavascriptNativeIntArray>(pDestObj) : scriptContext->GetLibrary()->CreateNativeIntArray(cDestLength);
  3358. pIntArray->EnsureHead<int32>();
  3359. JS_REENTRANT(jsReentLock, pDestArray = ConcatIntArgs(pIntArray, remoteTypeIds, args, scriptContext));
  3360. }
  3361. else if (isFloat)
  3362. {
  3363. JavascriptNativeFloatArray *pFArray = isArray ? VarTo<JavascriptNativeFloatArray>(pDestObj) : scriptContext->GetLibrary()->CreateNativeFloatArray(cDestLength);
  3364. pFArray->EnsureHead<double>();
  3365. JS_REENTRANT(jsReentLock, pDestArray = ConcatFloatArgs(pFArray, remoteTypeIds, args, scriptContext));
  3366. }
  3367. else
  3368. {
  3369. pDestArray = isArray ? VarTo<JavascriptArray>(pDestObj) : scriptContext->GetLibrary()->CreateArray(cDestLength);
  3370. // if the constructor has changed then we no longer specialize for ints and floats
  3371. pDestArray->EnsureHead<Var>();
  3372. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestArray, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3373. }
  3374. //
  3375. // Return the new array instance.
  3376. //
  3377. #ifdef VALIDATE_ARRAY
  3378. pDestArray->ValidateArray();
  3379. #endif
  3380. return pDestArray;
  3381. }
  3382. Assert(pDestObj);
  3383. JS_REENTRANT(jsReentLock, ConcatArgsCallingHelper(pDestObj, remoteTypeIds, args, scriptContext, destLengthOverflow));
  3384. return pDestObj;
  3385. JIT_HELPER_END(Array_Concat);
  3386. }
  3387. void JavascriptArray::ConcatArgsCallingHelper(RecyclableObject* pDestObj, TypeId* remoteTypeIds, Js::Arguments& args, ScriptContext* scriptContext, ::Math::RecordOverflowPolicy &destLengthOverflow)
  3388. {
  3389. if (destLengthOverflow.HasOverflowed())
  3390. {
  3391. ConcatArgs<BigIndex>(pDestObj, remoteTypeIds, args, scriptContext);
  3392. }
  3393. else
  3394. {
  3395. // Use faster uint32 version if no overflow
  3396. ConcatArgs<uint32>(pDestObj, remoteTypeIds, args, scriptContext);
  3397. }
  3398. }
  3399. template<typename T>
  3400. /* static */ void JavascriptArray::SetConcatItem(Var aItem, uint idxArg, JavascriptArray* pDestArray, RecyclableObject* pDestObj, T idxDest, ScriptContext *scriptContext)
  3401. {
  3402. if (BoxConcatItem(aItem, idxArg, scriptContext))
  3403. {
  3404. // bug# 725784: ES5: not calling ToObject in Step 1 of 15.4.4.4
  3405. RecyclableObject* pObj = nullptr;
  3406. if (FALSE == JavascriptConversion::ToObject(aItem, scriptContext, &pObj))
  3407. {
  3408. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.concat"));
  3409. }
  3410. if (pDestArray)
  3411. {
  3412. pDestArray->GenericDirectSetItemAt(idxDest, pObj);
  3413. }
  3414. else
  3415. {
  3416. SetArrayLikeObjects(pDestObj, idxDest, pObj);
  3417. }
  3418. }
  3419. else
  3420. {
  3421. if (pDestArray)
  3422. {
  3423. pDestArray->GenericDirectSetItemAt(idxDest, aItem);
  3424. }
  3425. else
  3426. {
  3427. SetArrayLikeObjects(pDestObj, idxDest, aItem);
  3428. }
  3429. }
  3430. }
  3431. int64 JavascriptArray::GetFromLastIndex(Var arg, int64 length, ScriptContext *scriptContext)
  3432. {
  3433. int64 fromIndex;
  3434. if (TaggedInt::Is(arg))
  3435. {
  3436. int intValue = TaggedInt::ToInt32(arg);
  3437. if (intValue >= 0)
  3438. {
  3439. fromIndex = min<int64>(intValue, length - 1);
  3440. }
  3441. else if ((uint32)-intValue > length)
  3442. {
  3443. return length;
  3444. }
  3445. else
  3446. {
  3447. fromIndex = intValue + length;
  3448. }
  3449. }
  3450. else
  3451. {
  3452. double value = JavascriptConversion::ToInteger(arg, scriptContext);
  3453. if (value >= 0)
  3454. {
  3455. fromIndex = (int64)min(value, (double)(length - 1));
  3456. }
  3457. else if (value + length < 0)
  3458. {
  3459. return length;
  3460. }
  3461. else
  3462. {
  3463. fromIndex = (int64)(value + length);
  3464. }
  3465. }
  3466. return fromIndex;
  3467. }
  3468. // includesAlgorithm specifies to follow ES7 Array.prototype.includes semantics instead of Array.prototype.indexOf
  3469. // Differences
  3470. // 1. Returns boolean true or false value instead of the search hit index
  3471. // 2. Follows SameValueZero algorithm instead of StrictEquals
  3472. // 3. Missing values are scanned if the search value is undefined
  3473. template <bool includesAlgorithm>
  3474. Var JavascriptArray::IndexOfHelper(Arguments const & args, ScriptContext *scriptContext)
  3475. {
  3476. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3477. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  3478. RecyclableObject* obj = nullptr;
  3479. JavascriptArray* pArr = nullptr;
  3480. BigIndex length;
  3481. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3482. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3483. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.indexOf"), &pArr, &obj, &length));
  3484. Var search;
  3485. uint32 fromIndex = 0;
  3486. uint64 fromIndex64 = 0;
  3487. // The evaluation of method arguments may change the type of the array. Hence, we do that prior to the actual helper method calls.
  3488. // The if clause of the conditional statement below applies to an JavascriptArray or TypedArray instances. The rest of the conditional
  3489. // clauses apply to an ES5Array or other valid Javascript objects.
  3490. if ((pArr || VarIs<TypedArrayBase>(obj)) && (length.IsSmallIndex() || length.IsUint32Max()))
  3491. {
  3492. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3493. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(len, args, search, fromIndex, scriptContext));
  3494. if (!gotParam)
  3495. {
  3496. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3497. }
  3498. }
  3499. else if (length.IsSmallIndex())
  3500. {
  3501. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetSmallIndex(), args, search, fromIndex, scriptContext));
  3502. if (!gotParam)
  3503. {
  3504. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3505. }
  3506. }
  3507. else
  3508. {
  3509. JS_REENTRANT(jsReentLock, BOOL gotParam = GetParamForIndexOf(length.GetBigIndex(), args, search, fromIndex64, scriptContext));
  3510. if (!gotParam)
  3511. {
  3512. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3513. }
  3514. }
  3515. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  3516. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  3517. {
  3518. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  3519. pArr = nullptr;
  3520. }
  3521. if (pArr)
  3522. {
  3523. if (length.IsSmallIndex() || length.IsUint32Max())
  3524. {
  3525. uint32 len = length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex();
  3526. JS_REENTRANT(jsReentLock, int32 index = pArr->HeadSegmentIndexOfHelper(search, fromIndex, len, includesAlgorithm, scriptContext));
  3527. // If we found the search value in the head segment, or if we determined there is no need to search other segments,
  3528. // we stop right here.
  3529. if (index != -1 || fromIndex == -1)
  3530. {
  3531. if (includesAlgorithm)
  3532. {
  3533. //Array.prototype.includes
  3534. return (index == -1) ? falseValue : trueValue;
  3535. }
  3536. else
  3537. {
  3538. //Array.prototype.indexOf
  3539. return JavascriptNumber::ToVar(index, scriptContext);
  3540. }
  3541. }
  3542. // If we really must search other segments, let's do it now. We'll have to search the slow way (dealing with holes, etc.).
  3543. switch (pArr->GetTypeId())
  3544. {
  3545. case Js::TypeIds_Array:
  3546. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3547. case Js::TypeIds_NativeIntArray:
  3548. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(UnsafeVarTo<JavascriptNativeIntArray>(pArr), search, fromIndex, len, scriptContext));
  3549. case Js::TypeIds_NativeFloatArray:
  3550. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(UnsafeVarTo<JavascriptNativeFloatArray>(pArr), search, fromIndex, len, scriptContext));
  3551. default:
  3552. AssertMsg(FALSE, "invalid array typeid");
  3553. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(pArr, search, fromIndex, len, scriptContext));
  3554. }
  3555. }
  3556. }
  3557. // source object is not a JavascriptArray but source could be a TypedArray
  3558. TypedArrayBase * typedArrayObj = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(obj);
  3559. if (typedArrayObj)
  3560. {
  3561. if (length.IsSmallIndex() || length.IsUint32Max())
  3562. {
  3563. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(typedArrayObj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3564. }
  3565. }
  3566. if (length.IsSmallIndex())
  3567. {
  3568. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex, length.GetSmallIndex(), scriptContext));
  3569. }
  3570. else
  3571. {
  3572. JS_REENTRANT_UNLOCK(jsReentLock, return TemplatedIndexOfHelper<includesAlgorithm>(obj, search, fromIndex64, length.GetBigIndex(), scriptContext));
  3573. }
  3574. }
  3575. // Array.prototype.indexOf as defined in ES6.0 (final) Section 22.1.3.11
  3576. Var JavascriptArray::EntryIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  3577. {
  3578. JIT_HELPER_REENTRANT_HEADER(Array_IndexOf);
  3579. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3580. ARGUMENTS(args, callInfo);
  3581. ScriptContext* scriptContext = function->GetScriptContext();
  3582. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3583. Assert(!(callInfo.Flags & CallFlags_New));
  3584. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_indexOf);
  3585. JS_REENTRANT_UNLOCK(jsReentLock, Var returnValue = IndexOfHelper<false>(args, scriptContext));
  3586. //IndexOfHelper code is reused for array.prototype.includes as well. Let us assert here we didn't get a true or false instead of index
  3587. Assert(returnValue != scriptContext->GetLibrary()->GetTrue() && returnValue != scriptContext->GetLibrary()->GetFalse());
  3588. return returnValue;
  3589. JIT_HELPER_END(Array_IndexOf);
  3590. }
  3591. Var JavascriptArray::EntryIncludes(RecyclableObject* function, CallInfo callInfo, ...)
  3592. {
  3593. JIT_HELPER_REENTRANT_HEADER(Array_Includes);
  3594. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3595. ARGUMENTS(args, callInfo);
  3596. ScriptContext* scriptContext = function->GetScriptContext();
  3597. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3598. Assert(!(callInfo.Flags & CallFlags_New));
  3599. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_includes);
  3600. JS_REENTRANT(jsReentLock, Var returnValue = IndexOfHelper<true>(args, scriptContext));
  3601. Assert(returnValue == scriptContext->GetLibrary()->GetTrue() || returnValue == scriptContext->GetLibrary()->GetFalse());
  3602. return returnValue;
  3603. JIT_HELPER_END(Array_Includes);
  3604. }
  3605. template<typename T>
  3606. BOOL JavascriptArray::GetParamForIndexOf(T length, Arguments const& args, Var& search, T& fromIndex, ScriptContext * scriptContext)
  3607. {
  3608. if (length == 0)
  3609. {
  3610. return false;
  3611. }
  3612. if (args.Info.Count > 2)
  3613. {
  3614. fromIndex = GetFromIndex(args[2], length, scriptContext);
  3615. if (fromIndex >= length)
  3616. {
  3617. return false;
  3618. }
  3619. search = args[1];
  3620. }
  3621. else
  3622. {
  3623. fromIndex = 0;
  3624. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  3625. }
  3626. return true;
  3627. }
  3628. template <>
  3629. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3630. {
  3631. // Note: Sometime cross site array go down this path to get the marshalling
  3632. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3633. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3634. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3635. if (checkHasItem && !JavascriptOperators::HasItem(obj, index))
  3636. {
  3637. return FALSE;
  3638. }
  3639. return JavascriptOperators::GetItem(obj, index, element, scriptContext);
  3640. }
  3641. template <>
  3642. BOOL JavascriptArray::TemplatedGetItem(RecyclableObject * obj, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3643. {
  3644. // Note: Sometime cross site array go down this path to get the marshalling
  3645. Assert(!VirtualTableInfo<JavascriptArray>::HasVirtualTable(obj)
  3646. && !VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(obj)
  3647. && !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(obj));
  3648. PropertyRecord const * propertyRecord;
  3649. JavascriptOperators::GetPropertyIdForInt(index, scriptContext, &propertyRecord);
  3650. if (checkHasItem && !JavascriptOperators::HasProperty(obj, propertyRecord->GetPropertyId()))
  3651. {
  3652. return FALSE;
  3653. }
  3654. *element = JavascriptOperators::GetProperty(obj, propertyRecord->GetPropertyId(), scriptContext);
  3655. return *element != scriptContext->GetLibrary()->GetUndefined();
  3656. }
  3657. template <>
  3658. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3659. {
  3660. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(pArr)
  3661. || VirtualTableInfo<CrossSiteObject<JavascriptArray>>::HasVirtualTable(pArr));
  3662. return pArr->JavascriptArray::DirectGetItemAtFull(index, element);
  3663. }
  3664. template <>
  3665. BOOL JavascriptArray::TemplatedGetItem(JavascriptArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3666. {
  3667. // This should never get called.
  3668. Assert(false);
  3669. Throw::InternalError();
  3670. }
  3671. template <>
  3672. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3673. {
  3674. Assert(VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pArr)
  3675. || VirtualTableInfo<CrossSiteObject<JavascriptNativeIntArray>>::HasVirtualTable(pArr));
  3676. return pArr->JavascriptNativeIntArray::DirectGetItemAtFull(index, element);
  3677. }
  3678. template <>
  3679. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeIntArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3680. {
  3681. // This should never get called.
  3682. Assert(false);
  3683. Throw::InternalError();
  3684. }
  3685. template <>
  3686. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3687. {
  3688. Assert(VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pArr)
  3689. || VirtualTableInfo<CrossSiteObject<JavascriptNativeFloatArray>>::HasVirtualTable(pArr));
  3690. return pArr->JavascriptNativeFloatArray::DirectGetItemAtFull(index, element);
  3691. }
  3692. template <>
  3693. BOOL JavascriptArray::TemplatedGetItem(JavascriptNativeFloatArray *pArr, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3694. {
  3695. // This should never get called.
  3696. Assert(false);
  3697. Throw::InternalError();
  3698. }
  3699. template <>
  3700. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint32 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3701. {
  3702. // We need to do explicit check for items since length value may not actually match the actual TypedArray length.
  3703. // User could add a length property to a TypedArray instance which lies and returns a different value from the underlying length.
  3704. // Since this method can be called via Array.prototype.indexOf with .apply or .call passing a TypedArray as this parameter
  3705. // we don't know whether or not length == typedArrayBase->GetLength().
  3706. if (checkHasItem && !typedArrayBase->HasItem(index))
  3707. {
  3708. return false;
  3709. }
  3710. *element = typedArrayBase->DirectGetItem(index);
  3711. return true;
  3712. }
  3713. template <>
  3714. BOOL JavascriptArray::TemplatedGetItem(TypedArrayBase * typedArrayBase, uint64 index, Var * element, ScriptContext * scriptContext, bool checkHasItem)
  3715. {
  3716. // This should never get called.
  3717. Assert(false);
  3718. Throw::InternalError();
  3719. }
  3720. template <bool includesAlgorithm, typename T, typename P>
  3721. Var JavascriptArray::TemplatedIndexOfHelper(T * pArr, Var search, P fromIndex, P toIndex, ScriptContext * scriptContext)
  3722. {
  3723. Var element = nullptr;
  3724. bool isSearchTaggedInt = TaggedInt::Is(search);
  3725. bool doUndefinedSearch = includesAlgorithm && JavascriptOperators::GetTypeId(search) == TypeIds_Undefined;
  3726. Var trueValue = scriptContext->GetLibrary()->GetTrue();
  3727. Var falseValue = scriptContext->GetLibrary()->GetFalse();
  3728. //Consider: enumerating instead of walking all indices
  3729. for (P i = fromIndex; i < toIndex; i++)
  3730. {
  3731. if (!TryTemplatedGetItem<T>(pArr, i, &element, scriptContext, !includesAlgorithm))
  3732. {
  3733. if (doUndefinedSearch)
  3734. {
  3735. return trueValue;
  3736. }
  3737. continue;
  3738. }
  3739. if (isSearchTaggedInt && TaggedInt::Is(element))
  3740. {
  3741. if (element == search)
  3742. {
  3743. return includesAlgorithm? trueValue : JavascriptNumber::ToVar(i, scriptContext);
  3744. }
  3745. continue;
  3746. }
  3747. if (includesAlgorithm)
  3748. {
  3749. //Array.prototype.includes
  3750. if (JavascriptConversion::SameValueZero(element, search))
  3751. {
  3752. return trueValue;
  3753. }
  3754. }
  3755. else
  3756. {
  3757. //Array.prototype.indexOf
  3758. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3759. {
  3760. return JavascriptNumber::ToVar(i, scriptContext);
  3761. }
  3762. }
  3763. }
  3764. return includesAlgorithm ? falseValue : TaggedInt::ToVarUnchecked(-1);
  3765. }
  3766. int32 JavascriptArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3767. {
  3768. Assert(IsNonES5Array(GetTypeId()) && !JavascriptNativeArray::Is(GetTypeId()));
  3769. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3770. {
  3771. return -1;
  3772. }
  3773. bool isSearchTaggedInt = TaggedInt::Is(search);
  3774. // We need to cast head segment to SparseArraySegment<Var> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3775. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptArray, and not for
  3776. // either of the derived native arrays, so the elements of each segment used here must be Vars. Hence, the cast is safe.
  3777. SparseArraySegment<Var>* head = static_cast<SparseArraySegment<Var>*>(GetHead());
  3778. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3779. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3780. {
  3781. Var element = head->GetElement(i);
  3782. if (isSearchTaggedInt && TaggedInt::Is(element))
  3783. {
  3784. if (search == element)
  3785. {
  3786. return i;
  3787. }
  3788. }
  3789. else if (SparseArraySegment<Var>::IsMissingItem(&element))
  3790. {
  3791. AssertOrFailFast(false);
  3792. }
  3793. else if (includesAlgorithm && JavascriptConversion::SameValueZero(element, search))
  3794. {
  3795. //Array.prototype.includes
  3796. return i;
  3797. }
  3798. else if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  3799. {
  3800. //Array.prototype.indexOf
  3801. return i;
  3802. }
  3803. }
  3804. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3805. // the head segment.
  3806. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3807. return -1;
  3808. }
  3809. template<typename T>
  3810. bool AreAllBytesEqual(T value)
  3811. {
  3812. byte* bValue = (byte*)&value;
  3813. byte firstByte = *bValue++;
  3814. for (int i = 1; i < sizeof(T); ++i)
  3815. {
  3816. if (*bValue++ != firstByte)
  3817. {
  3818. return false;
  3819. }
  3820. }
  3821. return true;
  3822. }
  3823. template<>
  3824. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(double)* buffer, uint32 length, double value)
  3825. {
  3826. if (JavascriptNumber::IsZero(value) && !JavascriptNumber::IsNegZero(value))
  3827. {
  3828. memset(buffer, 0, sizeof(double) * length);
  3829. }
  3830. else
  3831. {
  3832. for (uint32 i = 0; i < length; i++)
  3833. {
  3834. buffer[i] = value;
  3835. }
  3836. }
  3837. }
  3838. template<>
  3839. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(int32)* buffer, uint32 length, int32 value)
  3840. {
  3841. if (value == 0 || AreAllBytesEqual(value))
  3842. {
  3843. memset(buffer, *(byte*)&value, sizeof(int32)* length);
  3844. }
  3845. else
  3846. {
  3847. for (uint32 i = 0; i < length; i++)
  3848. {
  3849. buffer[i] = value;
  3850. }
  3851. }
  3852. }
  3853. template<>
  3854. void JavascriptArray::CopyValueToSegmentBuferNoCheck(Field(Js::Var)* buffer, uint32 length, Js::Var value)
  3855. {
  3856. for (uint32 i = 0; i < length; i++)
  3857. {
  3858. buffer[i] = value;
  3859. }
  3860. }
  3861. int32 JavascriptNativeIntArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3862. {
  3863. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3864. // except when we can further optimize thanks to the knowledge that all elements in the array are int32's. This allows for two additional optimizations:
  3865. // 1. Only tagged ints or JavascriptNumbers that can be represented as int32 can be strict equal to some element in the array (all int32). Thus, if
  3866. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3867. // 2. If the search value is a number that can be represented as int32, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
  3868. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3869. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3870. {
  3871. return -1;
  3872. }
  3873. bool isSearchTaggedInt = TaggedInt::Is(search);
  3874. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3875. {
  3876. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3877. // the head segment has no gaps.
  3878. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3879. return -1;
  3880. }
  3881. int32 searchAsInt32;
  3882. if (isSearchTaggedInt)
  3883. {
  3884. searchAsInt32 = TaggedInt::ToInt32(search);
  3885. }
  3886. else if (!JavascriptNumber::TryGetInt32Value<true>(JavascriptNumber::GetValue(search), &searchAsInt32))
  3887. {
  3888. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3889. // the head segment has no gaps.
  3890. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3891. return -1;
  3892. }
  3893. // We need to cast head segment to SparseArraySegment<int32> to have access to GetElement (onSparseArraySegment<T>). Because there are separate overloads of this
  3894. // virtual method on JavascriptNativeIntArray and JavascriptNativeFloatArray, we know this version of this method will only be called for true JavascriptNativeIntArray, and not for
  3895. // the other two, so the elements of each segment used here must be int32's. Hence, the cast is safe.
  3896. SparseArraySegment<int32> * head = static_cast<SparseArraySegment<int32>*>(GetHead());
  3897. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3898. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3899. {
  3900. int32 element = head->GetElement(i);
  3901. if (searchAsInt32 == element)
  3902. {
  3903. return i;
  3904. }
  3905. }
  3906. // Element not found in the head segment. Keep looking only if the range of indices extends past
  3907. // the head segment.
  3908. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3909. return -1;
  3910. }
  3911. int32 JavascriptNativeFloatArray::HeadSegmentIndexOfHelper(Var search, uint32 &fromIndex, uint32 toIndex, bool includesAlgorithm, ScriptContext * scriptContext)
  3912. {
  3913. // We proceed largely in the same manner as in JavascriptArray's version of this method (see comments there for more information),
  3914. // except when we can further optimize thanks to the knowledge that all elements in the array are doubles. This allows for two additional optimizations:
  3915. // 1. Only tagged ints or JavascriptNumbers can be strict equal to some element in the array (all doubles). Thus, if
  3916. // the search value is some other kind of Var, we can return -1 without ever iterating over the elements.
  3917. // 2. If the search value is a number, then we inspect the elements, but we don't need to perform the full strict equality algorithm.
  3918. // Instead we can use simple C++ equality (which in case of such values is equivalent to strict equality in JavaScript).
  3919. if (!HasNoMissingValues() || fromIndex >= GetHead()->length)
  3920. {
  3921. return -1;
  3922. }
  3923. bool isSearchTaggedInt = TaggedInt::Is(search);
  3924. if (!isSearchTaggedInt && !JavascriptNumber::Is_NoTaggedIntCheck(search))
  3925. {
  3926. // The value can't be in the array, but it could be in a prototype, and we can only guarantee that
  3927. // the head segment has no gaps.
  3928. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3929. return -1;
  3930. }
  3931. double searchAsDouble = isSearchTaggedInt ? TaggedInt::ToDouble(search) : JavascriptNumber::GetValue(search);
  3932. // We need to cast head segment to SparseArraySegment<double> to have access to GetElement (SparseArraySegment). We know the
  3933. // segment's elements are all Vars so the cast is safe. It would have been more convenient here if JavascriptArray
  3934. // used SparseArraySegment<Var>, instead of SparseArraySegmentBase.
  3935. SparseArraySegment<double> * head = static_cast<SparseArraySegment<double>*>(GetHead());
  3936. uint32 toIndexTrimmed = toIndex <= head->length ? toIndex : head->length;
  3937. bool matchNaN = includesAlgorithm && JavascriptNumber::IsNan(searchAsDouble);
  3938. for (uint32 i = fromIndex; i < toIndexTrimmed; i++)
  3939. {
  3940. double element = head->GetElement(i);
  3941. if (element == searchAsDouble)
  3942. {
  3943. return i;
  3944. }
  3945. //NaN != NaN we expect to match for NaN in Array.prototype.includes algorithm
  3946. if (matchNaN && JavascriptNumber::IsNan(element))
  3947. {
  3948. return i;
  3949. }
  3950. }
  3951. fromIndex = toIndex > GetHead()->length ? GetHead()->length : -1;
  3952. return -1;
  3953. }
  3954. Var JavascriptArray::EntryJoin(RecyclableObject* function, CallInfo callInfo, ...)
  3955. {
  3956. JIT_HELPER_REENTRANT_HEADER(Array_Join);
  3957. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  3958. ARGUMENTS(args, callInfo);
  3959. ScriptContext* scriptContext = function->GetScriptContext();
  3960. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  3961. Assert(!(callInfo.Flags & CallFlags_New));
  3962. if (args.Info.Count == 0)
  3963. {
  3964. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.join"));
  3965. }
  3966. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  3967. JavascriptString* separator;
  3968. if (args.Info.Count >= 2)
  3969. {
  3970. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  3971. //ES5 15.4.4.5 If separator is undefined, let separator be the single-character String ",".
  3972. if (TypeIds_Undefined != typeId)
  3973. {
  3974. JS_REENTRANT(jsReentLock, separator = JavascriptConversion::ToString(args[1], scriptContext));
  3975. }
  3976. else
  3977. {
  3978. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3979. }
  3980. }
  3981. else
  3982. {
  3983. separator = scriptContext->GetLibrary()->GetCommaDisplayString();
  3984. }
  3985. JS_REENTRANT_UNLOCK(jsReentLock, return JoinHelper(args[0], separator, scriptContext));
  3986. JIT_HELPER_END(Array_Join);
  3987. }
  3988. JavascriptString* JavascriptArray::JoinToString(Var value, ScriptContext* scriptContext)
  3989. {
  3990. TypeId typeId = JavascriptOperators::GetTypeId(value);
  3991. if (typeId <= TypeIds_UndefinedOrNull)
  3992. {
  3993. return scriptContext->GetLibrary()->GetEmptyString();
  3994. }
  3995. else
  3996. {
  3997. return JavascriptConversion::ToString(value, scriptContext);
  3998. }
  3999. }
  4000. JavascriptString* JavascriptArray::JoinHelper(Var thisArg, JavascriptString* separator, ScriptContext* scriptContext)
  4001. {
  4002. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4003. SETOBJECT_FOR_MUTATION(jsReentLock, thisArg);
  4004. JavascriptArray * arr = JavascriptArray::TryVarToNonES5Array(thisArg);
  4005. JavascriptProxy * proxy = JavascriptOperators::TryFromVar<JavascriptProxy>(thisArg);
  4006. bool isArray = arr && (scriptContext == arr->GetScriptContext());
  4007. bool isProxy = proxy && (scriptContext == proxy->GetScriptContext());
  4008. Var target = NULL;
  4009. bool isTargetObjectPushed = false;
  4010. // if we are visiting a proxy object, track that we have visited the target object as well so the next time w
  4011. // call the join helper for the target of this proxy, we will return above.
  4012. if (isProxy)
  4013. {
  4014. Assert(proxy);
  4015. target = proxy->GetTarget();
  4016. if (target != nullptr)
  4017. {
  4018. // If we end up joining same array, instead of going in infinite loop, return the empty string
  4019. if (scriptContext->CheckObject(target))
  4020. {
  4021. return scriptContext->GetLibrary()->GetEmptyString();
  4022. }
  4023. else
  4024. {
  4025. scriptContext->PushObject(target);
  4026. isTargetObjectPushed = true;
  4027. }
  4028. }
  4029. }
  4030. // If we end up joining same array, instead of going in infinite loop, return the empty string
  4031. else if (scriptContext->CheckObject(thisArg))
  4032. {
  4033. return scriptContext->GetLibrary()->GetEmptyString();
  4034. }
  4035. if (!isTargetObjectPushed)
  4036. {
  4037. scriptContext->PushObject(thisArg);
  4038. }
  4039. JavascriptString* res = nullptr;
  4040. TryFinally([&]()
  4041. {
  4042. if (isArray)
  4043. {
  4044. #if ENABLE_COPYONACCESS_ARRAY
  4045. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray(thisArg);
  4046. #endif
  4047. switch (arr->GetTypeId())
  4048. {
  4049. case Js::TypeIds_Array:
  4050. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(arr, separator, scriptContext));
  4051. break;
  4052. case Js::TypeIds_NativeIntArray:
  4053. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(UnsafeVarTo<JavascriptNativeIntArray>(arr), separator, scriptContext));
  4054. break;
  4055. case Js::TypeIds_NativeFloatArray:
  4056. JS_REENTRANT(jsReentLock, res = JoinArrayHelper(UnsafeVarTo<JavascriptNativeFloatArray>(arr), separator, scriptContext));
  4057. break;
  4058. }
  4059. }
  4060. else if (VarIs<RecyclableObject>(thisArg))
  4061. {
  4062. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(VarTo<RecyclableObject>(thisArg), separator, scriptContext));
  4063. }
  4064. else
  4065. {
  4066. JS_REENTRANT(jsReentLock, res = JoinOtherHelper(scriptContext->GetLibrary()->CreateNumberObject(thisArg), separator, scriptContext));
  4067. }
  4068. },
  4069. [&](bool/*hasException*/)
  4070. {
  4071. Var top = scriptContext->PopObject();
  4072. if (isProxy)
  4073. {
  4074. AssertMsg(top == target, "Unmatched operation stack");
  4075. }
  4076. else
  4077. {
  4078. AssertMsg(top == thisArg, "Unmatched operation stack");
  4079. }
  4080. });
  4081. if (res == nullptr)
  4082. {
  4083. res = scriptContext->GetLibrary()->GetEmptyString();
  4084. }
  4085. return res;
  4086. }
  4087. static const charcount_t Join_MaxEstimatedAppendCount = static_cast<charcount_t>((64 << 20) / sizeof(void *)); // 64 MB worth of pointers
  4088. template <typename T>
  4089. JavascriptString* JavascriptArray::JoinArrayHelper(T * arr, JavascriptString* separator, ScriptContext* scriptContext)
  4090. {
  4091. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4092. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4093. Assert(VirtualTableInfo<T>::HasVirtualTable(arr) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(arr));
  4094. const uint32 arrLength = arr->length;
  4095. switch(arrLength)
  4096. {
  4097. default:
  4098. {
  4099. CaseDefault:
  4100. bool hasSeparator = (separator->GetLength() != 0);
  4101. const charcount_t estimatedAppendCount =
  4102. min(
  4103. Join_MaxEstimatedAppendCount,
  4104. static_cast<charcount_t>(arrLength + (hasSeparator ? arrLength - 1 : 0)));
  4105. CompoundString *const cs =
  4106. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4107. Var item;
  4108. BOOL gotItem;
  4109. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4110. if (gotItem)
  4111. {
  4112. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  4113. }
  4114. for (uint32 i = 1; i < arrLength; i++)
  4115. {
  4116. if (hasSeparator)
  4117. {
  4118. cs->Append(separator);
  4119. }
  4120. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem<T>(arr, i, &item, scriptContext));
  4121. if (gotItem)
  4122. {
  4123. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(item, scriptContext)));
  4124. }
  4125. }
  4126. return cs;
  4127. }
  4128. case 2:
  4129. {
  4130. bool hasSeparator = (separator->GetLength() != 0);
  4131. BOOL gotItem;
  4132. if(hasSeparator)
  4133. {
  4134. goto CaseDefault;
  4135. }
  4136. JavascriptString *res = nullptr;
  4137. Var item;
  4138. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4139. if (gotItem)
  4140. {
  4141. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(item, scriptContext));
  4142. }
  4143. JS_REENTRANT(jsReentLock, gotItem = TryTemplatedGetItem<T>(arr, 1u, &item, scriptContext));
  4144. if (gotItem)
  4145. {
  4146. JS_REENTRANT(jsReentLock, JavascriptString *const itemString = JavascriptArray::JoinToString(item, scriptContext));
  4147. return res ? ConcatString::New(res, itemString) : itemString;
  4148. }
  4149. if(res)
  4150. {
  4151. return res;
  4152. }
  4153. goto Case0;
  4154. }
  4155. case 1:
  4156. {
  4157. Var item;
  4158. BOOL gotItem;
  4159. JS_REENTRANT(jsReentLock, gotItem = TemplatedGetItem(arr, 0u, &item, scriptContext));
  4160. if (gotItem)
  4161. {
  4162. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(item, scriptContext));
  4163. }
  4164. // fall through
  4165. }
  4166. case 0:
  4167. Case0:
  4168. return scriptContext->GetLibrary()->GetEmptyString();
  4169. }
  4170. }
  4171. JavascriptString* JavascriptArray::JoinOtherHelper(RecyclableObject* object, JavascriptString* separator, ScriptContext* scriptContext)
  4172. {
  4173. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4174. SETOBJECT_FOR_MUTATION(jsReentLock, object);
  4175. // In ES6-mode, we always load the length property from the object instead of using the internal slot.
  4176. // Even for arrays, this is now observable via proxies.
  4177. // If source object is not an array, we fall back to this behavior anyway.
  4178. JS_REENTRANT(jsReentLock,
  4179. int64 cSrcLength = (int64)OP_GetLength(object, scriptContext));
  4180. switch (cSrcLength)
  4181. {
  4182. default:
  4183. {
  4184. CaseDefault:
  4185. bool hasSeparator = (separator->GetLength() != 0);
  4186. BOOL gotItem;
  4187. const charcount_t estimatedAppendCount =
  4188. min(
  4189. Join_MaxEstimatedAppendCount,
  4190. static_cast<charcount_t>(cSrcLength + (hasSeparator ? cSrcLength - 1 : 0)));
  4191. CompoundString *const cs =
  4192. CompoundString::NewWithPointerCapacity(estimatedAppendCount, scriptContext->GetLibrary());
  4193. Var value;
  4194. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4195. if (gotItem)
  4196. {
  4197. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4198. }
  4199. for (uint32 i = 1; i < cSrcLength; i++)
  4200. {
  4201. if (hasSeparator)
  4202. {
  4203. cs->Append(separator);
  4204. }
  4205. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, i, &value, scriptContext));
  4206. if (gotItem)
  4207. {
  4208. JS_REENTRANT(jsReentLock, cs->Append(JavascriptArray::JoinToString(value, scriptContext)));
  4209. }
  4210. }
  4211. return cs;
  4212. }
  4213. case 2:
  4214. {
  4215. bool hasSeparator = (separator->GetLength() != 0);
  4216. BOOL gotItem;
  4217. if(hasSeparator)
  4218. {
  4219. goto CaseDefault;
  4220. }
  4221. JavascriptString *res = nullptr;
  4222. Var value;
  4223. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4224. if (gotItem)
  4225. {
  4226. JS_REENTRANT(jsReentLock, res = JavascriptArray::JoinToString(value, scriptContext));
  4227. }
  4228. JS_REENTRANT(jsReentLock, gotItem = JavascriptOperators::GetItem(object, 1u, &value, scriptContext));
  4229. if (gotItem)
  4230. {
  4231. JS_REENTRANT(jsReentLock, JavascriptString *const valueString = JavascriptArray::JoinToString(value, scriptContext));
  4232. return res ? ConcatString::New(res, valueString) : valueString;
  4233. }
  4234. if(res)
  4235. {
  4236. return res;
  4237. }
  4238. goto Case0;
  4239. }
  4240. case 1:
  4241. {
  4242. Var value;
  4243. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(object, 0u, &value, scriptContext));
  4244. if (gotItem)
  4245. {
  4246. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::JoinToString(value, scriptContext));
  4247. }
  4248. // fall through
  4249. }
  4250. case 0:
  4251. Case0:
  4252. return scriptContext->GetLibrary()->GetEmptyString();
  4253. }
  4254. }
  4255. Var JavascriptArray::EntryLastIndexOf(RecyclableObject* function, CallInfo callInfo, ...)
  4256. {
  4257. JIT_HELPER_REENTRANT_HEADER(Array_LastIndexOf);
  4258. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4259. ARGUMENTS(args, callInfo);
  4260. ScriptContext* scriptContext = function->GetScriptContext();
  4261. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4262. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  4263. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_lastIndexOf);
  4264. Assert(!(callInfo.Flags & CallFlags_New));
  4265. int64 length;
  4266. JavascriptArray * pArr = nullptr;
  4267. RecyclableObject* obj = nullptr;
  4268. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.lastIndexOf"), &pArr, &obj, &length));
  4269. Var search;
  4270. int64 fromIndex;
  4271. JS_REENTRANT(jsReentLock,
  4272. BOOL gotParam = GetParamForLastIndexOf(length, args, search, fromIndex, scriptContext));
  4273. if (!gotParam)
  4274. {
  4275. return TaggedInt::ToVarUnchecked(-1);
  4276. }
  4277. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of fromIndex argument may convert the array to an ES5 array.
  4278. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  4279. {
  4280. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  4281. pArr = nullptr;
  4282. }
  4283. if (pArr)
  4284. {
  4285. switch (pArr->GetTypeId())
  4286. {
  4287. case Js::TypeIds_Array:
  4288. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4289. case Js::TypeIds_NativeIntArray:
  4290. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(UnsafeVarTo<JavascriptNativeIntArray>(pArr), search, fromIndex, scriptContext));
  4291. case Js::TypeIds_NativeFloatArray:
  4292. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(UnsafeVarTo<JavascriptNativeFloatArray>(pArr), search, fromIndex, scriptContext));
  4293. default:
  4294. AssertMsg(FALSE, "invalid array typeid");
  4295. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(pArr, search, fromIndex, scriptContext));
  4296. }
  4297. }
  4298. // source object is not a JavascriptArray but source could be a TypedArray
  4299. TypedArrayBase * typedArrayObj = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(obj);
  4300. if (typedArrayObj)
  4301. {
  4302. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(typedArrayObj, search, fromIndex, scriptContext));
  4303. }
  4304. JS_REENTRANT_UNLOCK(jsReentLock, return LastIndexOfHelper(obj, search, fromIndex, scriptContext));
  4305. JIT_HELPER_END(Array_LastIndexOf);
  4306. }
  4307. // Array.prototype.lastIndexOf as described in ES6.0 (draft 22) Section 22.1.3.14
  4308. BOOL JavascriptArray::GetParamForLastIndexOf(int64 length, Arguments const & args, Var& search, int64& fromIndex, ScriptContext * scriptContext)
  4309. {
  4310. if (length == 0)
  4311. {
  4312. return false;
  4313. }
  4314. if (args.Info.Count > 2)
  4315. {
  4316. fromIndex = GetFromLastIndex(args[2], length, scriptContext);
  4317. if (fromIndex >= length)
  4318. {
  4319. return false;
  4320. }
  4321. search = args[1];
  4322. }
  4323. else
  4324. {
  4325. search = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  4326. fromIndex = length - 1;
  4327. }
  4328. return true;
  4329. }
  4330. template <typename T>
  4331. Var JavascriptArray::LastIndexOfHelper(T* pArr, Var search, int64 fromIndex, ScriptContext * scriptContext)
  4332. {
  4333. Var element = nullptr;
  4334. bool isSearchTaggedInt = TaggedInt::Is(search);
  4335. // First handle the indices > 2^32
  4336. while (fromIndex >= MaxArrayLength)
  4337. {
  4338. Var index = JavascriptNumber::ToVar(fromIndex, scriptContext);
  4339. if (JavascriptOperators::OP_HasItem(pArr, index, scriptContext))
  4340. {
  4341. element = JavascriptOperators::OP_GetElementI(pArr, index, scriptContext);
  4342. if (isSearchTaggedInt && TaggedInt::Is(element))
  4343. {
  4344. if (element == search)
  4345. {
  4346. return index;
  4347. }
  4348. fromIndex--;
  4349. continue;
  4350. }
  4351. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4352. {
  4353. return index;
  4354. }
  4355. }
  4356. fromIndex--;
  4357. }
  4358. Assert(fromIndex < MaxArrayLength);
  4359. // fromIndex now has to be < MaxArrayLength so casting to uint32 is safe
  4360. uint32 end = static_cast<uint32>(fromIndex);
  4361. for (uint32 i = 0; i <= end; i++)
  4362. {
  4363. uint32 index = end - i;
  4364. if (!TryTemplatedGetItem<T>(pArr, index, &element, scriptContext))
  4365. {
  4366. continue;
  4367. }
  4368. if (isSearchTaggedInt && TaggedInt::Is(element))
  4369. {
  4370. if (element == search)
  4371. {
  4372. return JavascriptNumber::ToVar(index, scriptContext);
  4373. }
  4374. continue;
  4375. }
  4376. if (JavascriptOperators::StrictEqual(element, search, scriptContext))
  4377. {
  4378. return JavascriptNumber::ToVar(index, scriptContext);
  4379. }
  4380. }
  4381. return TaggedInt::ToVarUnchecked(-1);
  4382. }
  4383. /*
  4384. * PopWithNoDst
  4385. * - For pop calls that do not return a value, we only need to decrement the length of the array.
  4386. */
  4387. void JavascriptNativeArray::PopWithNoDst(Var nativeArray)
  4388. {
  4389. JIT_HELPER_NOT_REENTRANT_NOLOCK_HEADER(Array_NativePopWithNoDst);
  4390. Assert(VarIs<JavascriptNativeArray>(nativeArray));
  4391. JavascriptArray * arr = VarTo<JavascriptArray>(nativeArray);
  4392. // we will bailout on length 0
  4393. Assert(arr->GetLength() != 0);
  4394. uint32 index = arr->GetLength() - 1;
  4395. arr->SetLength(index);
  4396. JIT_HELPER_END(Array_NativePopWithNoDst);
  4397. }
  4398. /*
  4399. * JavascriptNativeIntArray::Pop
  4400. * - Returns int32 value from the array.
  4401. * - Returns missing item when the element is not available in the array object.
  4402. * - It doesn't walk up the prototype chain.
  4403. * - Length is decremented only if it pops an int32 element, in all other cases - we bail out from the jitted code.
  4404. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4405. */
  4406. int32 JavascriptNativeIntArray::Pop(ScriptContext * scriptContext, Var object)
  4407. {
  4408. JIT_HELPER_NOT_REENTRANT_HEADER(Array_NativeIntPop, reentrancylock, scriptContext->GetThreadContext());
  4409. Assert(VarIs<JavascriptNativeIntArray>(object));
  4410. JavascriptNativeIntArray * arr = VarTo<JavascriptNativeIntArray>(object);
  4411. Assert(arr->GetLength() != 0);
  4412. uint32 index = arr->length - 1;
  4413. int32 element = Js::JavascriptOperators::OP_GetNativeIntElementI_UInt32(object, index, scriptContext);
  4414. //If it is a missing item, then don't update the length - Pre-op Bail out will happen.
  4415. if(!SparseArraySegment<int32>::IsMissingItem(&element))
  4416. {
  4417. arr->SetLength(index);
  4418. }
  4419. return element;
  4420. JIT_HELPER_END(Array_NativeIntPop);
  4421. }
  4422. /*
  4423. * JavascriptNativeFloatArray::Pop
  4424. * - Returns double value from the array.
  4425. * - Returns missing item when the element is not available in the array object.
  4426. * - It doesn't walk up the prototype chain.
  4427. * - Length is decremented only if it pops a double element, in all other cases - we bail out from the jitted code.
  4428. * - This api cannot cause any implicit call and hence do not need implicit call bailout test around this api
  4429. */
  4430. double JavascriptNativeFloatArray::Pop(ScriptContext * scriptContext, Var object)
  4431. {
  4432. JIT_HELPER_NOT_REENTRANT_HEADER(Array_NativeFloatPop, reentrancylock, scriptContext->GetThreadContext());
  4433. Assert(VarIs<JavascriptNativeFloatArray>(object));
  4434. JavascriptNativeFloatArray * arr = VarTo<JavascriptNativeFloatArray>(object);
  4435. Assert(arr->GetLength() != 0);
  4436. uint32 index = arr->length - 1;
  4437. double element = Js::JavascriptOperators::OP_GetNativeFloatElementI_UInt32(object, index, scriptContext);
  4438. // If it is a missing item then don't update the length - Pre-op Bail out will happen.
  4439. if(!SparseArraySegment<double>::IsMissingItem(&element))
  4440. {
  4441. arr->SetLength(index);
  4442. }
  4443. return element;
  4444. JIT_HELPER_END(Array_NativeFloatPop);
  4445. }
  4446. /*
  4447. * JavascriptArray::Pop
  4448. * - Calls the generic Pop API, which can find elements from the prototype chain, when it is not available in the array object.
  4449. * - This API may cause implicit calls. Handles Array and non-array objects
  4450. */
  4451. Var JavascriptArray::Pop(ScriptContext * scriptContext, Var object)
  4452. {
  4453. JIT_HELPER_REENTRANT_HEADER(Array_VarPop);
  4454. if (JavascriptArray::IsNonES5Array(object))
  4455. {
  4456. return EntryPopJavascriptArray(scriptContext, VarTo<JavascriptArray>(object));
  4457. }
  4458. else
  4459. {
  4460. return EntryPopNonJavascriptArray(scriptContext, object);
  4461. }
  4462. JIT_HELPER_END(Array_VarPop);
  4463. }
  4464. Var JavascriptArray::EntryPopJavascriptArray(ScriptContext * scriptContext, JavascriptArray* arr)
  4465. {
  4466. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4467. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4468. uint32 length = arr->length;
  4469. if (length == 0)
  4470. {
  4471. // If length is 0, return 'undefined'
  4472. return scriptContext->GetLibrary()->GetUndefined();
  4473. }
  4474. uint32 index = length - 1;
  4475. Var element;
  4476. JS_REENTRANT(jsReentLock, BOOL gotItem = arr->DirectGetItemAtFull(index, &element));
  4477. if (!gotItem)
  4478. {
  4479. element = scriptContext->GetLibrary()->GetUndefined();
  4480. }
  4481. else
  4482. {
  4483. element = CrossSite::MarshalVar(scriptContext, element, arr->GetScriptContext());
  4484. }
  4485. arr->SetLength(index); // SetLength will clear element at index
  4486. #ifdef VALIDATE_ARRAY
  4487. arr->ValidateArray();
  4488. #endif
  4489. return element;
  4490. }
  4491. Var JavascriptArray::EntryPopNonJavascriptArray(ScriptContext * scriptContext, Var object)
  4492. {
  4493. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4494. RecyclableObject* dynamicObject = nullptr;
  4495. if (FALSE == JavascriptConversion::ToObject(object, scriptContext, &dynamicObject))
  4496. {
  4497. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4498. }
  4499. SETOBJECT_FOR_MUTATION(jsReentLock, dynamicObject);
  4500. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  4501. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.pop"));
  4502. if (length == 0u)
  4503. {
  4504. // Set length = 0
  4505. JS_REENTRANT(jsReentLock,
  4506. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4507. return scriptContext->GetLibrary()->GetUndefined();
  4508. }
  4509. BigIndex index = length;
  4510. --index;
  4511. Var element;
  4512. if (index.IsSmallIndex())
  4513. {
  4514. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetSmallIndex(), &element, scriptContext));
  4515. if (!gotItem)
  4516. {
  4517. element = scriptContext->GetLibrary()->GetUndefined();
  4518. }
  4519. JS_REENTRANT(jsReentLock,
  4520. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4521. // Set the new length
  4522. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4523. }
  4524. else
  4525. {
  4526. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, index.GetBigIndex(), &element, scriptContext));
  4527. if (!gotItem)
  4528. {
  4529. element = scriptContext->GetLibrary()->GetUndefined();
  4530. }
  4531. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, index.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  4532. // Set the new length
  4533. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(index.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  4534. }
  4535. return element;
  4536. }
  4537. Var JavascriptArray::EntryPop(RecyclableObject* function, CallInfo callInfo, ...)
  4538. {
  4539. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4540. ARGUMENTS(args, callInfo);
  4541. ScriptContext* scriptContext = function->GetScriptContext();
  4542. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4543. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  4544. Assert(!(callInfo.Flags & CallFlags_New));
  4545. if (args.Info.Count == 0)
  4546. {
  4547. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.pop"));
  4548. }
  4549. if (JavascriptArray::IsNonES5Array(args[0]))
  4550. {
  4551. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopJavascriptArray(scriptContext, VarTo<JavascriptArray>(args.Values[0])));
  4552. }
  4553. else
  4554. {
  4555. JS_REENTRANT_UNLOCK(jsReentLock, return EntryPopNonJavascriptArray(scriptContext, args.Values[0]));
  4556. }
  4557. }
  4558. /*
  4559. * JavascriptNativeIntArray::Push
  4560. * Pushes Int element in a native Int Array.
  4561. * We call the generic Push, if the array is not native Int or we have a really big array.
  4562. */
  4563. Var JavascriptNativeIntArray::Push(ScriptContext * scriptContext, Var array, int value)
  4564. {
  4565. JIT_HELPER_REENTRANT_HEADER(Array_NativeIntPush);
  4566. JIT_HELPER_SAME_ATTRIBUTES(Array_NativeIntPush, Array_VarPush);
  4567. // Fast path for case where `array` is a same-site JavascriptNativeIntArray
  4568. // instance with a length less than MaxArrayLength
  4569. if (VarIs<JavascriptNativeIntArray>(array) &&
  4570. VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(array))
  4571. {
  4572. auto* nativeIntArray = UnsafeVarTo<JavascriptNativeIntArray>(array);
  4573. Assert(!nativeIntArray->IsCrossSiteObject());
  4574. uint32 n = nativeIntArray->length;
  4575. if (n < JavascriptArray::MaxArrayLength)
  4576. {
  4577. nativeIntArray->SetItem(n, value);
  4578. n++;
  4579. AssertMsg(n == nativeIntArray->length, "Wrong update to the length of the native Int array");
  4580. return JavascriptNumber::ToVar(n, scriptContext);
  4581. }
  4582. }
  4583. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVar(value, scriptContext));
  4584. JIT_HELPER_END(Array_NativeIntPush);
  4585. }
  4586. /*
  4587. * JavascriptNativeFloatArray::Push
  4588. * Pushes Float element in a native Int Array.
  4589. * We call the generic Push, if the array is not native Float or we have a really big array.
  4590. */
  4591. Var JavascriptNativeFloatArray::Push(ScriptContext * scriptContext, Var array, double value)
  4592. {
  4593. JIT_HELPER_REENTRANT_HEADER(Array_NativeFloatPush);
  4594. JIT_HELPER_SAME_ATTRIBUTES(Array_NativeFloatPush, Array_VarPush);
  4595. // Fast path for case where `array` is a same-site JavascriptNativeFloatArray
  4596. // instance with a length less than MaxArrayLength
  4597. if (VarIs<JavascriptNativeFloatArray>(array) &&
  4598. VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(array))
  4599. {
  4600. auto* nativeFloatArray = UnsafeVarTo<JavascriptNativeFloatArray>(array);
  4601. Assert(!nativeFloatArray->IsCrossSiteObject());
  4602. uint32 n = nativeFloatArray->length;
  4603. if( n < JavascriptArray::MaxArrayLength)
  4604. {
  4605. nativeFloatArray->SetItem(n, value);
  4606. n++;
  4607. AssertMsg(n == nativeFloatArray->length, "Wrong update to the length of the native Float array");
  4608. return JavascriptNumber::ToVar(n, scriptContext);
  4609. }
  4610. }
  4611. return JavascriptArray::Push(scriptContext, array, JavascriptNumber::ToVarNoCheck(value, scriptContext));
  4612. JIT_HELPER_END(Array_NativeFloatPush);
  4613. }
  4614. /*
  4615. * JavascriptArray::Push
  4616. * Pushes Var element in a Var Array.
  4617. */
  4618. Var JavascriptArray::Push(ScriptContext * scriptContext, Var object, Var value)
  4619. {
  4620. JIT_HELPER_REENTRANT_HEADER(Array_VarPush);
  4621. Var args[2];
  4622. args[0] = object;
  4623. args[1] = value;
  4624. if (JavascriptArray::IsNonES5Array(object))
  4625. {
  4626. return EntryPushJavascriptArray(scriptContext, args, 2);
  4627. }
  4628. else
  4629. {
  4630. return EntryPushNonJavascriptArray(scriptContext, args, 2);
  4631. }
  4632. JIT_HELPER_END(Array_VarPush);
  4633. }
  4634. /*
  4635. * EntryPushNonJavascriptArray
  4636. * - Handles Entry push calls, when Objects are not javascript arrays
  4637. */
  4638. Var JavascriptArray::EntryPushNonJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4639. {
  4640. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4641. RecyclableObject* obj = nullptr;
  4642. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  4643. {
  4644. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4645. }
  4646. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  4647. JS_REENTRANT_UNLOCK(jsReentLock, Var length = JavascriptOperators::OP_GetLength(obj, scriptContext));
  4648. if(JavascriptOperators::GetTypeId(length) == TypeIds_Undefined && scriptContext->GetThreadContext()->IsDisableImplicitCall() &&
  4649. scriptContext->GetThreadContext()->GetImplicitCallFlags() != Js::ImplicitCall_None)
  4650. {
  4651. return length;
  4652. }
  4653. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4654. BigIndex n;
  4655. if (scriptContext->GetConfig()->IsES6ToLengthEnabled())
  4656. {
  4657. n = (uint64) JavascriptConversion::ToLength(length, scriptContext);
  4658. }
  4659. else
  4660. {
  4661. n = JavascriptConversion::ToUInt32(length, scriptContext);
  4662. }
  4663. // First handle "small" indices.
  4664. uint index;
  4665. for (index=1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4666. {
  4667. JS_REENTRANT(jsReentLock,
  4668. BOOL setItem = JavascriptOperators::SetItem(obj, obj, n.GetSmallIndex(), args[index], scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4669. if (h.IsThrowTypeError(setItem))
  4670. {
  4671. if (scriptContext->GetThreadContext()->RecordImplicitException())
  4672. {
  4673. h.ThrowTypeErrorOnFailure();
  4674. }
  4675. else
  4676. {
  4677. return nullptr;
  4678. }
  4679. }
  4680. }
  4681. // Use BigIndex if we need to push indices >= MaxArrayLength
  4682. if (index < argCount)
  4683. {
  4684. BigIndex big = n;
  4685. for (; index < argCount; ++index, ++big)
  4686. {
  4687. JS_REENTRANT(jsReentLock, BOOL setItem = big.SetItem(obj, args[index], PropertyOperation_ThrowIfNotExtensible));
  4688. if (h.IsThrowTypeError(setItem))
  4689. {
  4690. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4691. {
  4692. h.ThrowTypeErrorOnFailure();
  4693. }
  4694. else
  4695. {
  4696. return nullptr;
  4697. }
  4698. }
  4699. }
  4700. // Set the new length; for objects it is all right for this to be >= MaxArrayLength
  4701. JS_REENTRANT(jsReentLock,
  4702. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, big.ToNumber(scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4703. if (h.IsThrowTypeError(setLength))
  4704. {
  4705. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4706. {
  4707. h.ThrowTypeErrorOnFailure();
  4708. }
  4709. else
  4710. {
  4711. return nullptr;
  4712. }
  4713. }
  4714. return big.ToNumber(scriptContext);
  4715. }
  4716. else
  4717. {
  4718. // Set the new length
  4719. Var lengthAsNUmberVar = JavascriptNumber::ToVar(n.IsSmallIndex() ? n.GetSmallIndex() : n.GetBigIndex(), scriptContext);
  4720. JS_REENTRANT(jsReentLock,
  4721. BOOL setLength = JavascriptOperators::SetProperty(obj, obj, PropertyIds::length, lengthAsNUmberVar, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  4722. if (h.IsThrowTypeError(setLength))
  4723. {
  4724. if(scriptContext->GetThreadContext()->RecordImplicitException())
  4725. {
  4726. h.ThrowTypeErrorOnFailure();
  4727. }
  4728. else
  4729. {
  4730. return nullptr;
  4731. }
  4732. }
  4733. return lengthAsNUmberVar;
  4734. }
  4735. }
  4736. /*
  4737. * JavascriptArray::EntryPushJavascriptArray
  4738. * Pushes Var element in a Var Array.
  4739. * Returns the length of the array.
  4740. */
  4741. Var JavascriptArray::EntryPushJavascriptArray(ScriptContext * scriptContext, Var * args, uint argCount)
  4742. {
  4743. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4744. #if ENABLE_COPYONACCESS_ARRAY
  4745. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  4746. #endif
  4747. uint n = arr->length;
  4748. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4749. // Fast Path for one push for small indexes
  4750. if (argCount == 2 && n < JavascriptArray::MaxArrayLength)
  4751. {
  4752. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4753. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[1], PropertyOperation_None));
  4754. return JavascriptNumber::ToVar(n + 1, scriptContext);
  4755. }
  4756. // Fast Path for multiple push for small indexes
  4757. if (JavascriptArray::MaxArrayLength - argCount + 1 > n && JavascriptArray::IsVarArray(arr) && scriptContext == arr->GetScriptContext())
  4758. {
  4759. uint index;
  4760. for (index = 1; index < argCount; ++index, ++n)
  4761. {
  4762. Assert(n != JavascriptArray::MaxArrayLength);
  4763. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4764. arr->JavascriptArray::DirectSetItemAt(n, args[index]);
  4765. }
  4766. return JavascriptNumber::ToVar(n, scriptContext);
  4767. }
  4768. return EntryPushJavascriptArrayNoFastPath(scriptContext, args, argCount);
  4769. }
  4770. Var JavascriptArray::EntryPushJavascriptArrayNoFastPath(ScriptContext * scriptContext, Var * args, uint argCount)
  4771. {
  4772. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4773. JavascriptArray * arr = JavascriptArray::FromAnyArray(args[0]);
  4774. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  4775. uint n = arr->length;
  4776. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.push"));
  4777. // First handle "small" indices.
  4778. uint index;
  4779. for (index = 1; index < argCount && n < JavascriptArray::MaxArrayLength; ++index, ++n)
  4780. {
  4781. // Set Item is overridden by CrossSiteObject, so no need to check for IsCrossSiteObject()
  4782. h.ThrowTypeErrorOnFailure(arr->SetItem(n, args[index], PropertyOperation_None));
  4783. }
  4784. // Use BigIndex if we need to push indices >= MaxArrayLength
  4785. if (index < argCount)
  4786. {
  4787. // Not supporting native array with BigIndex.
  4788. arr = EnsureNonNativeArray(arr);
  4789. Assert(n == JavascriptArray::MaxArrayLength);
  4790. for (BigIndex big = n; index < argCount; ++index, ++big)
  4791. {
  4792. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(big.SetItem(arr, args[index])));
  4793. }
  4794. #ifdef VALIDATE_ARRAY
  4795. arr->ValidateArray();
  4796. #endif
  4797. // This is where we should set the length, but for arrays it cannot be >= MaxArrayLength
  4798. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  4799. }
  4800. #ifdef VALIDATE_ARRAY
  4801. arr->ValidateArray();
  4802. #endif
  4803. return JavascriptNumber::ToVar(n, scriptContext);
  4804. }
  4805. /*
  4806. * JavascriptArray::EntryPush
  4807. * Handles Push calls(Script Function)
  4808. */
  4809. Var JavascriptArray::EntryPush(RecyclableObject* function, CallInfo callInfo, ...)
  4810. {
  4811. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4812. ARGUMENTS(args, callInfo);
  4813. ScriptContext* scriptContext = function->GetScriptContext();
  4814. Assert(!(callInfo.Flags & CallFlags_New));
  4815. if (args.Info.Count == 0)
  4816. {
  4817. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.push"));
  4818. }
  4819. if (JavascriptArray::IsNonES5Array(args[0]))
  4820. {
  4821. return EntryPushJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4822. }
  4823. else
  4824. {
  4825. return EntryPushNonJavascriptArray(scriptContext, args.Values, args.Info.Count);
  4826. }
  4827. }
  4828. template <typename T>
  4829. void JavascriptArray::CopyHeadIfInlinedHeadSegment(JavascriptArray *array, Recycler *recycler)
  4830. {
  4831. if (JavascriptArray::IsInlineSegment(array->head, array))
  4832. {
  4833. AnalysisAssert(array->head);
  4834. SparseArraySegment<T>* newHeadSeg = array->ReallocNonLeafSegment((SparseArraySegment<T>*)PointerValue(array->head), array->head->next);
  4835. array->head = newHeadSeg;
  4836. array->InvalidateLastUsedSegment();
  4837. array->ClearSegmentMap();
  4838. }
  4839. }
  4840. template <typename T>
  4841. void JavascriptArray::ReallocateNonLeafLastSegmentIfLeaf(JavascriptArray * arr, Recycler * recycler)
  4842. {
  4843. Assert(arr->head && arr->head->next); // Doesn't make sense to reallocate a leaf last segment as a non-leaf if its not going to point to any other segments.
  4844. // TODO: Consider utilizing lastUsedSegment once we fix CopyHeadIfInlinedHeadSegment in that respect.
  4845. SparseArraySegmentBase *lastSeg = nullptr;
  4846. SparseArraySegmentBase *seg = arr->head;
  4847. while (seg)
  4848. {
  4849. lastSeg = seg;
  4850. seg = seg->next;
  4851. }
  4852. if (SparseArraySegmentBase::IsLeafSegment(lastSeg, recycler))
  4853. {
  4854. AnalysisAssert(lastSeg);
  4855. arr->ReallocNonLeafSegment((SparseArraySegment<T>*)lastSeg, lastSeg->next, true /*forceNonLeaf*/);
  4856. }
  4857. }
  4858. Var JavascriptArray::EntryReverse(RecyclableObject* function, CallInfo callInfo, ...)
  4859. {
  4860. JIT_HELPER_REENTRANT_HEADER(Array_Reverse);
  4861. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  4862. ARGUMENTS(args, callInfo);
  4863. ScriptContext* scriptContext = function->GetScriptContext();
  4864. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4865. Assert(!(callInfo.Flags & CallFlags_New));
  4866. if (args.Info.Count == 0)
  4867. {
  4868. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reverse"));
  4869. }
  4870. BigIndex length = 0u;
  4871. JavascriptArray* pArr = nullptr;
  4872. RecyclableObject* obj = nullptr;
  4873. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reverse"), &pArr, &obj, &length));
  4874. if (length.IsSmallIndex())
  4875. {
  4876. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetSmallIndex(), scriptContext));
  4877. }
  4878. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReverseHelper(pArr, nullptr, obj, length.GetBigIndex(), scriptContext));
  4879. JIT_HELPER_END(Array_Reverse);
  4880. }
  4881. bool JavascriptArray::HasAnyES5ArrayInPrototypeChain(JavascriptArray *arr, bool forceCheckProtoChain)
  4882. {
  4883. Assert(arr != nullptr);
  4884. #if ENABLE_COPYONACCESS_ARRAY
  4885. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  4886. #endif
  4887. bool hasAnyES5Array = false;
  4888. // If there is no gap (unless forced) we are not filling from the prototype - so no point checking for ES5Array.
  4889. if (forceCheckProtoChain || arr->IsFillFromPrototypes())
  4890. {
  4891. RecyclableObject* prototype = arr->GetPrototype();
  4892. while (!JavascriptOperators::IsNull(prototype))
  4893. {
  4894. RecyclableObject* protoObj = prototype;
  4895. if (!(DynamicObject::IsAnyArray(protoObj) || JavascriptOperators::IsObject(protoObj))
  4896. || VarIs<JavascriptProxy>(protoObj)
  4897. || protoObj->IsExternal())
  4898. {
  4899. hasAnyES5Array = true;
  4900. break;
  4901. }
  4902. if (DynamicObject::IsAnyArray(protoObj))
  4903. {
  4904. if (VarIs<ES5Array>(protoObj))
  4905. {
  4906. hasAnyES5Array = true;
  4907. break;
  4908. }
  4909. }
  4910. else if (DynamicType::Is(protoObj->GetTypeId()))
  4911. {
  4912. DynamicObject* dynobj = UnsafeVarTo<DynamicObject>(protoObj);
  4913. ArrayObject* objectArray = dynobj->GetObjectArray();
  4914. if (objectArray != nullptr && VarIs<ES5Array>(objectArray))
  4915. {
  4916. hasAnyES5Array = true;
  4917. break;
  4918. }
  4919. }
  4920. prototype = prototype->GetPrototype();
  4921. }
  4922. }
  4923. return hasAnyES5Array;
  4924. }
  4925. // Array.prototype.reverse as described in ES6.0 (draft 22) Section 22.1.3.20
  4926. template <typename T>
  4927. Var JavascriptArray::ReverseHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, ScriptContext* scriptContext)
  4928. {
  4929. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  4930. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  4931. T middle = length / 2;
  4932. Var lowerValue = nullptr, upperValue = nullptr;
  4933. T lowerExists, upperExists;
  4934. const char16* methodName;
  4935. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  4936. if (isTypedArrayEntryPoint)
  4937. {
  4938. methodName = _u("[TypedArray].prototype.reverse");
  4939. }
  4940. else
  4941. {
  4942. methodName = _u("Array.prototype.reverse");
  4943. }
  4944. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  4945. if (!isTypedArrayEntryPoint && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  4946. {
  4947. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  4948. }
  4949. ThrowTypeErrorOnFailureHelper h(scriptContext, methodName);
  4950. bool useNoSideEffectReverse = pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr);
  4951. if (useNoSideEffectReverse)
  4952. {
  4953. Assert(length <= JavascriptArray::MaxArrayLength);
  4954. Recycler * recycler = scriptContext->GetRecycler();
  4955. if (length <= 1)
  4956. {
  4957. return pArr;
  4958. }
  4959. if (pArr->IsFillFromPrototypes())
  4960. {
  4961. // For odd-length arrays, the middle element is unchanged,
  4962. // so we cannot fill it from the prototypes.
  4963. if (length % 2 == 0)
  4964. {
  4965. pArr->FillFromPrototypes(0, (uint32)length);
  4966. }
  4967. else
  4968. {
  4969. middle = length / 2;
  4970. pArr->FillFromPrototypes(0, (uint32)middle);
  4971. pArr->FillFromPrototypes(1 + (uint32)middle, (uint32)length);
  4972. }
  4973. }
  4974. // As we have already established that the FillFromPrototype should not change the bound of the array.
  4975. if (length != (T)pArr->length)
  4976. {
  4977. Js::Throw::FatalInternalError();
  4978. }
  4979. if (pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  4980. {
  4981. // This function currently does not track missing values in the head segment if there are multiple segments
  4982. pArr->SetHasNoMissingValues(false);
  4983. }
  4984. // Above FillFromPrototypes call can change the length of the array. Our segment calculation below will
  4985. // not work with the stale length. Update the length.
  4986. // Note : since we are reversing the whole segment below - the functionality is not spec compliant already.
  4987. length = pArr->length;
  4988. SparseArraySegmentBase *prevSeg = nullptr;
  4989. SparseArraySegmentBase *nextSeg = nullptr;
  4990. bool isIntArray = false;
  4991. bool isFloatArray = false;
  4992. pArr->ClearSegmentMap(); // Just dump the segment map on reverse
  4993. if (VarIs<JavascriptNativeIntArray>(pArr))
  4994. {
  4995. isIntArray = true;
  4996. }
  4997. else if (VarIs<JavascriptNativeFloatArray>(pArr))
  4998. {
  4999. isFloatArray = true;
  5000. }
  5001. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  5002. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  5003. // During the loop below we are going to reverse the segments list. The head segment will become the last segment.
  5004. // We have to verify that the current head segment is not the inilined segement, otherwise due to shuffling below (of EnsureHeadStartsFromZero call below), the inlined segment will no longer
  5005. // be the head and that can create issue down the line. Create new segment if it is an inilined segment.
  5006. if (pArr->head && (pArr->head->next || (pArr->head->left + pArr->head->length) < length))
  5007. {
  5008. if (isIntArray)
  5009. {
  5010. CopyHeadIfInlinedHeadSegment<int32>(pArr, recycler);
  5011. if (pArr->head->next)
  5012. {
  5013. ReallocateNonLeafLastSegmentIfLeaf<int32>(pArr, recycler);
  5014. }
  5015. }
  5016. else if (isFloatArray)
  5017. {
  5018. CopyHeadIfInlinedHeadSegment<double>(pArr, recycler);
  5019. if (pArr->head->next)
  5020. {
  5021. ReallocateNonLeafLastSegmentIfLeaf<double>(pArr, recycler);
  5022. }
  5023. }
  5024. else
  5025. {
  5026. CopyHeadIfInlinedHeadSegment<Var>(pArr, recycler);
  5027. }
  5028. }
  5029. SparseArraySegmentBase* seg = pArr->head;
  5030. while (seg)
  5031. {
  5032. nextSeg = seg->next;
  5033. // If seg.length == 0, it is possible that (seg.left + seg.length == prev.left + prev.length),
  5034. // resulting in 2 segments sharing the same "left".
  5035. if (seg->length > 0)
  5036. {
  5037. if (isIntArray)
  5038. {
  5039. ((SparseArraySegment<int32>*)seg)->ReverseSegment(recycler);
  5040. }
  5041. else if (isFloatArray)
  5042. {
  5043. ((SparseArraySegment<double>*)seg)->ReverseSegment(recycler);
  5044. }
  5045. else
  5046. {
  5047. ((SparseArraySegment<Var>*)seg)->ReverseSegment(recycler);
  5048. }
  5049. if (((uint32)length) < (seg->left + seg->length))
  5050. {
  5051. Js::Throw::FatalInternalError();
  5052. }
  5053. seg->left = ((uint32)length) - (seg->left + seg->length);
  5054. seg->next = prevSeg;
  5055. // Make sure size doesn't overlap with next segment.
  5056. // An easy fix is to just truncate the size...
  5057. seg->EnsureSizeInBound();
  5058. prevSeg = seg;
  5059. }
  5060. seg = nextSeg;
  5061. }
  5062. pArr->head = prevSeg;
  5063. if (isIntArray)
  5064. {
  5065. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  5066. }
  5067. else if (isFloatArray)
  5068. {
  5069. pArr->EnsureHeadStartsFromZero<double>(recycler);
  5070. }
  5071. else
  5072. {
  5073. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  5074. }
  5075. pArr->InvalidateLastUsedSegment(); // lastUsedSegment might be 0-length and discarded above
  5076. pArr->ClearSegmentMap();
  5077. #ifdef VALIDATE_ARRAY
  5078. pArr->ValidateArray();
  5079. #endif
  5080. failFastOnError.Completed();
  5081. }
  5082. else if (typedArrayBase && length <= JavascriptArray::MaxArrayLength)
  5083. {
  5084. if (typedArrayBase->GetLength() == length)
  5085. {
  5086. // If typedArrayBase->length == length then we know that the TypedArray will have all items < length
  5087. // and we won't have to check that the elements exist or not.
  5088. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  5089. {
  5090. uint32 upper = (uint32)length - lower - 1;
  5091. lowerValue = typedArrayBase->DirectGetItem(lower);
  5092. upperValue = typedArrayBase->DirectGetItem(upper);
  5093. // We still have to call HasItem even though we know the TypedArray has both lower and upper because
  5094. // there may be a proxy handler trapping HasProperty.
  5095. lowerExists = typedArrayBase->HasItem(lower);
  5096. upperExists = typedArrayBase->HasItem(upper);
  5097. JS_REENTRANT(jsReentLock,
  5098. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  5099. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  5100. }
  5101. }
  5102. else
  5103. {
  5104. Assert(middle <= UINT_MAX);
  5105. for (uint32 lower = 0; lower < (uint32)middle; lower++)
  5106. {
  5107. uint32 upper = (uint32)length - lower - 1;
  5108. lowerValue = typedArrayBase->DirectGetItem(lower);
  5109. upperValue = typedArrayBase->DirectGetItem(upper);
  5110. lowerExists = typedArrayBase->HasItem(lower);
  5111. upperExists = typedArrayBase->HasItem(upper);
  5112. if (lowerExists)
  5113. {
  5114. if (upperExists)
  5115. {
  5116. JS_REENTRANT(jsReentLock,
  5117. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)),
  5118. h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  5119. }
  5120. else
  5121. {
  5122. // This will always fail for a TypedArray if lower < length
  5123. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(lower, PropertyOperation_ThrowOnDeleteIfNotConfig));
  5124. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(upper, lowerValue)));
  5125. }
  5126. }
  5127. else
  5128. {
  5129. if (upperExists)
  5130. {
  5131. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(typedArrayBase->DirectSetItem(lower, upperValue)));
  5132. // This will always fail for a TypedArray if upper < length
  5133. h.ThrowTypeErrorOnFailure(typedArrayBase->DeleteItem(upper, PropertyOperation_ThrowOnDeleteIfNotConfig));
  5134. }
  5135. }
  5136. }
  5137. }
  5138. }
  5139. else
  5140. {
  5141. for (T lower = 0; lower < middle; lower++)
  5142. {
  5143. T upper = length - lower - 1;
  5144. JS_REENTRANT(jsReentLock,
  5145. lowerExists = JavascriptOperators::HasItem(obj, lower) && JavascriptOperators::GetItem(obj, lower, &lowerValue, scriptContext),
  5146. upperExists = JavascriptOperators::HasItem(obj, upper) && JavascriptOperators::GetItem(obj, upper, &upperValue, scriptContext));
  5147. if (lowerExists)
  5148. {
  5149. if (upperExists)
  5150. {
  5151. JS_REENTRANT(jsReentLock,
  5152. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  5153. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5154. }
  5155. else
  5156. {
  5157. JS_REENTRANT(jsReentLock,
  5158. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, lower, PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5159. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, upper, lowerValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5160. }
  5161. }
  5162. else
  5163. {
  5164. if (upperExists)
  5165. {
  5166. JS_REENTRANT(jsReentLock,
  5167. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(obj, obj, lower, upperValue, scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  5168. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(obj, upper, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5169. }
  5170. }
  5171. }
  5172. }
  5173. return obj;
  5174. }
  5175. template<typename T>
  5176. void JavascriptArray::ShiftHelper(JavascriptArray* pArr, ScriptContext * scriptContext)
  5177. {
  5178. Recycler * recycler = scriptContext->GetRecycler();
  5179. SparseArraySegment<T>* next = SparseArraySegment<T>::From(pArr->head->next);
  5180. while (next)
  5181. {
  5182. next->left--;
  5183. next = SparseArraySegment<T>::From(next->next);
  5184. }
  5185. // head and next might overlap as the next segment left is decremented
  5186. next = SparseArraySegment<T>::From(pArr->head->next);
  5187. if (next && (pArr->head->size > next->left))
  5188. {
  5189. AssertMsg(pArr->head->left == 0, "Array always points to a head starting at index 0");
  5190. AssertMsg(pArr->head->size == next->left + 1, "Shift next->left overlaps current segment by more than 1 element");
  5191. SparseArraySegment<T> *head = SparseArraySegment<T>::From(pArr->head);
  5192. SparseArraySegment<T> *oldHead = head;
  5193. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, pArr);
  5194. bool nextIsInlineSegment = JavascriptArray::IsInlineSegment(next, pArr);
  5195. // Merge the two adjacent segments
  5196. if (next->length != 0)
  5197. {
  5198. uint32 offset = head->size - 1;
  5199. // There is room for one unshifted element in head segment.
  5200. // Hence it's enough if we grow the head segment by next->length - 1
  5201. if (next->next)
  5202. {
  5203. // If we have a next->next, we can't grow pass the left of that
  5204. // If the array had a segment map before, the next->next might just be right after next as well.
  5205. // So we just need to grow to the end of the next segment
  5206. // TODO: merge that segment too?
  5207. Assert(next->next->left >= head->size);
  5208. uint32 maxGrowSize = next->next->left - head->size;
  5209. if (maxGrowSize != 0)
  5210. {
  5211. head = head->GrowByMinMax(recycler, next->length - 1, maxGrowSize); //-1 is to account for unshift
  5212. }
  5213. else
  5214. {
  5215. // The next segment is only of length one, so we already have space in the header to copy that
  5216. Assert(next->length == 1);
  5217. }
  5218. }
  5219. else
  5220. {
  5221. head = head->GrowByMin(recycler, next->length - 1); //-1 is to account for unshift
  5222. }
  5223. MoveArray(head->elements + offset, next->elements, next->length);
  5224. head->length = offset + next->length;
  5225. head->CheckLengthvsSize();
  5226. pArr->head = head;
  5227. if (isInlineSegment && oldHead != head)
  5228. {
  5229. pArr->ClearElements(oldHead, 0);
  5230. }
  5231. }
  5232. head->next = next->next;
  5233. if (nextIsInlineSegment)
  5234. {
  5235. pArr->ClearElements(next, 0);
  5236. }
  5237. pArr->InvalidateLastUsedSegment();
  5238. pArr->ClearSegmentMap();
  5239. }
  5240. #ifdef VALIDATE_ARRAY
  5241. pArr->ValidateArray();
  5242. #endif
  5243. }
  5244. Var JavascriptArray::EntryShift(RecyclableObject* function, CallInfo callInfo, ...)
  5245. {
  5246. JIT_HELPER_REENTRANT_HEADER(Array_Shift);
  5247. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5248. ARGUMENTS(args, callInfo);
  5249. ScriptContext* scriptContext = function->GetScriptContext();
  5250. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5251. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  5252. Assert(!(callInfo.Flags & CallFlags_New));
  5253. Var res = scriptContext->GetLibrary()->GetUndefined();
  5254. if (args.Info.Count == 0)
  5255. {
  5256. return res;
  5257. }
  5258. bool useNoSideEffectShift = JavascriptArray::IsNonES5Array(args[0])
  5259. && !VarTo<JavascriptArray>(args[0])->IsCrossSiteObject()
  5260. && !HasAnyES5ArrayInPrototypeChain(UnsafeVarTo<JavascriptArray>(args[0]));
  5261. if (useNoSideEffectShift)
  5262. {
  5263. JavascriptArray * pArr = UnsafeVarTo<JavascriptArray>(args[0]);
  5264. if (pArr->length == 0)
  5265. {
  5266. return res;
  5267. }
  5268. uint32 length = pArr->length;
  5269. if(pArr->IsFillFromPrototypes())
  5270. {
  5271. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  5272. }
  5273. // As we have already established that the FillFromPrototype should not change the bound of the array.
  5274. if (length != pArr->length)
  5275. {
  5276. Js::Throw::FatalInternalError();
  5277. }
  5278. if(pArr->HasNoMissingValues() && pArr->head && pArr->head->next)
  5279. {
  5280. // This function currently does not track missing values in the head segment if there are multiple segments
  5281. pArr->SetHasNoMissingValues(false);
  5282. }
  5283. pArr->length--;
  5284. pArr->ClearSegmentMap(); // Dump segmentMap on shift (before any allocation)
  5285. Recycler * recycler = scriptContext->GetRecycler();
  5286. bool isIntArray = false;
  5287. bool isFloatArray = false;
  5288. if(VarIs<JavascriptNativeIntArray>(pArr))
  5289. {
  5290. isIntArray = true;
  5291. }
  5292. else if(VarIs<JavascriptNativeFloatArray>(pArr))
  5293. {
  5294. isFloatArray = true;
  5295. }
  5296. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  5297. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  5298. if (pArr->head->length != 0)
  5299. {
  5300. if(isIntArray)
  5301. {
  5302. int32 nativeResult = SparseArraySegment<int32>::From(pArr->head)->GetElement(0);
  5303. if(SparseArraySegment<int32>::IsMissingItem(&nativeResult))
  5304. {
  5305. res = scriptContext->GetLibrary()->GetUndefined();
  5306. }
  5307. else
  5308. {
  5309. res = Js::JavascriptNumber::ToVar(nativeResult, scriptContext);
  5310. }
  5311. SparseArraySegment<int32>::From(pArr->head)->RemoveElement(recycler, 0);
  5312. }
  5313. else if (isFloatArray)
  5314. {
  5315. double nativeResult = SparseArraySegment<double>::From(pArr->head)->GetElement(0);
  5316. if(SparseArraySegment<double>::IsMissingItem(&nativeResult))
  5317. {
  5318. res = scriptContext->GetLibrary()->GetUndefined();
  5319. }
  5320. else
  5321. {
  5322. res = Js::JavascriptNumber::ToVarNoCheck(nativeResult, scriptContext);
  5323. }
  5324. SparseArraySegment<double>::From(pArr->head)->RemoveElement(recycler, 0);
  5325. }
  5326. else
  5327. {
  5328. res = SparseArraySegment<Var>::From(pArr->head)->GetElement(0);
  5329. if(SparseArraySegment<Var>::IsMissingItem(&res))
  5330. {
  5331. res = scriptContext->GetLibrary()->GetUndefined();
  5332. }
  5333. else
  5334. {
  5335. res = CrossSite::MarshalVar(scriptContext, res);
  5336. }
  5337. SparseArraySegment<Var>::From(pArr->head)->RemoveElement(recycler, 0);
  5338. }
  5339. }
  5340. if(isIntArray)
  5341. {
  5342. ShiftHelper<int32>(pArr, scriptContext);
  5343. }
  5344. else if (isFloatArray)
  5345. {
  5346. ShiftHelper<double>(pArr, scriptContext);
  5347. }
  5348. else
  5349. {
  5350. ShiftHelper<Var>(pArr, scriptContext);
  5351. }
  5352. failFastOnError.Completed();
  5353. }
  5354. else
  5355. {
  5356. RecyclableObject* dynamicObject = nullptr;
  5357. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  5358. {
  5359. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.shift"));
  5360. }
  5361. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.shift"));
  5362. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  5363. if (length == 0u)
  5364. {
  5365. // If length is 0, return 'undefined'
  5366. JS_REENTRANT(jsReentLock,
  5367. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, TaggedInt::ToVarUnchecked(0), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5368. return scriptContext->GetLibrary()->GetUndefined();
  5369. }
  5370. JS_REENTRANT(jsReentLock,
  5371. BOOL gotItem = JavascriptOperators::GetItem(dynamicObject, 0u, &res, scriptContext));
  5372. if (!gotItem)
  5373. {
  5374. res = scriptContext->GetLibrary()->GetUndefined();
  5375. }
  5376. --length;
  5377. uint32 lengthToUin32Max = length.IsSmallIndex() ? length.GetSmallIndex() : MaxArrayLength;
  5378. for (uint32 i = 0u; i < lengthToUin32Max; i++)
  5379. {
  5380. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5381. if (hasItem)
  5382. {
  5383. Var element = nullptr;
  5384. JS_REENTRANT(jsReentLock,
  5385. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5386. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible, /*skipPrototypeCheck*/ true)));
  5387. }
  5388. else
  5389. {
  5390. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5391. }
  5392. }
  5393. for (uint64 i = MaxArrayLength; length > i; i++)
  5394. {
  5395. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(dynamicObject, i + 1));
  5396. if (hasItem)
  5397. {
  5398. Var element = nullptr;
  5399. JS_REENTRANT(jsReentLock,
  5400. element = JavascriptOperators::GetItem(dynamicObject, i + 1, scriptContext),
  5401. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5402. }
  5403. else
  5404. {
  5405. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, i, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  5406. }
  5407. }
  5408. if (length.IsSmallIndex())
  5409. {
  5410. JS_REENTRANT(jsReentLock,
  5411. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetSmallIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5412. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetSmallIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5413. }
  5414. else
  5415. {
  5416. JS_REENTRANT(jsReentLock,
  5417. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(dynamicObject, length.GetBigIndex(), PropertyOperation_ThrowOnDeleteIfNotConfig)),
  5418. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, JavascriptNumber::ToVar(length.GetBigIndex(), scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  5419. }
  5420. }
  5421. return res;
  5422. JIT_HELPER_END(Array_Shift);
  5423. }
  5424. Js::JavascriptArray* JavascriptArray::CreateNewArrayHelper(uint32 len, bool isIntArray, bool isFloatArray, Js::JavascriptArray* baseArray, ScriptContext* scriptContext)
  5425. {
  5426. if (isIntArray)
  5427. {
  5428. Js::JavascriptNativeIntArray *pnewArr = scriptContext->GetLibrary()->CreateNativeIntArray(len);
  5429. pnewArr->EnsureHead<int32>();
  5430. #if ENABLE_PROFILE_INFO
  5431. pnewArr->CopyArrayProfileInfo(Js::UnsafeVarTo<Js::JavascriptNativeIntArray>(baseArray));
  5432. #endif
  5433. return pnewArr;
  5434. }
  5435. else if (isFloatArray)
  5436. {
  5437. Js::JavascriptNativeFloatArray *pnewArr = scriptContext->GetLibrary()->CreateNativeFloatArray(len);
  5438. pnewArr->EnsureHead<double>();
  5439. #if ENABLE_PROFILE_INFO
  5440. pnewArr->CopyArrayProfileInfo(Js::UnsafeVarTo<Js::JavascriptNativeFloatArray>(baseArray));
  5441. #endif
  5442. return pnewArr;
  5443. }
  5444. else
  5445. {
  5446. JavascriptArray *pnewArr = pnewArr = scriptContext->GetLibrary()->CreateArray(len);
  5447. pnewArr->EnsureHead<Var>();
  5448. return pnewArr;
  5449. }
  5450. }
  5451. template<typename T>
  5452. void JavascriptArray::SliceHelper(JavascriptArray* pArr, JavascriptArray* pnewArr, uint32 start, uint32 newLen)
  5453. {
  5454. JS_REENTRANCY_LOCK(jsReentLock, pArr->GetScriptContext()->GetThreadContext());
  5455. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  5456. SparseArraySegment<T>* headSeg = SparseArraySegment<T>::From(pArr->head);
  5457. SparseArraySegment<T>* pnewHeadSeg = SparseArraySegment<T>::From(pnewArr->head);
  5458. // Fill the newly created sliced array
  5459. CopyArray(pnewHeadSeg->elements, newLen, headSeg->elements + start, newLen);
  5460. pnewHeadSeg->length = newLen;
  5461. pnewHeadSeg->CheckLengthvsSize();
  5462. Assert(pnewHeadSeg->length <= pnewHeadSeg->size);
  5463. // Prototype lookup for missing elements
  5464. if (!pArr->HasNoMissingValues())
  5465. {
  5466. for (uint32 i = 0; i < newLen; i++)
  5467. {
  5468. if (!(pArr->head->left <= (i + start) && (i + start) < (pArr->head->left + pArr->head->length)))
  5469. {
  5470. break;
  5471. }
  5472. // array type might be changed in the below call to DirectGetItemAtFull
  5473. // need recheck array type before checking array item [i + start]
  5474. if (pArr->IsMissingItem(i + start))
  5475. {
  5476. Var element;
  5477. pnewArr->SetHasNoMissingValues(false);
  5478. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5479. if (gotItem)
  5480. {
  5481. JS_REENTRANT(jsReentLock, pnewArr->SetItem(i, element, PropertyOperation_None));
  5482. }
  5483. }
  5484. }
  5485. }
  5486. #ifdef DBG
  5487. else
  5488. {
  5489. for (uint32 i = 0; i < newLen; i++)
  5490. {
  5491. AssertMsg(!SparseArraySegment<T>::IsMissingItem(&headSeg->elements[i+start]), "Array marked incorrectly as having missing value");
  5492. }
  5493. }
  5494. #endif
  5495. }
  5496. // If the creating profile data has changed, convert it to the type of array indicated
  5497. // in the profile
  5498. void JavascriptArray::GetArrayTypeAndConvert(bool* isIntArray, bool* isFloatArray)
  5499. {
  5500. JavascriptNativeIntArray* nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(this);
  5501. if (nativeIntArray)
  5502. {
  5503. #if ENABLE_PROFILE_INFO
  5504. ArrayCallSiteInfo* info = nativeIntArray->GetArrayCallSiteInfo();
  5505. if(!info || info->IsNativeIntArray())
  5506. {
  5507. *isIntArray = true;
  5508. }
  5509. else if(info->IsNativeFloatArray())
  5510. {
  5511. JavascriptNativeIntArray::ToNativeFloatArray(nativeIntArray);
  5512. *isFloatArray = true;
  5513. }
  5514. else
  5515. {
  5516. JavascriptNativeIntArray::ToVarArray(nativeIntArray);
  5517. }
  5518. #else
  5519. *isIntArray = true;
  5520. #endif
  5521. }
  5522. else
  5523. {
  5524. JavascriptNativeFloatArray* nativeFloatArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(this);
  5525. if (nativeFloatArray)
  5526. {
  5527. #if ENABLE_PROFILE_INFO
  5528. ArrayCallSiteInfo* info = nativeFloatArray->GetArrayCallSiteInfo();
  5529. if (info && !info->IsNativeArray())
  5530. {
  5531. JavascriptNativeFloatArray::ToVarArray(nativeFloatArray);
  5532. }
  5533. else
  5534. {
  5535. *isFloatArray = true;
  5536. }
  5537. #else
  5538. *isFloatArray = true;
  5539. #endif
  5540. }
  5541. }
  5542. }
  5543. Var JavascriptArray::EntrySlice(RecyclableObject* function, CallInfo callInfo, ...)
  5544. {
  5545. JIT_HELPER_REENTRANT_HEADER(Array_Slice);
  5546. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  5547. ARGUMENTS(args, callInfo);
  5548. ScriptContext* scriptContext = function->GetScriptContext();
  5549. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5550. Assert(!(callInfo.Flags & CallFlags_New));
  5551. Var res = scriptContext->GetLibrary()->GetUndefined();
  5552. if (args.Info.Count == 0)
  5553. {
  5554. return res;
  5555. }
  5556. BigIndex length;
  5557. JavascriptArray* pArr = nullptr;
  5558. RecyclableObject* obj = nullptr;
  5559. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.slice"), &pArr, &obj, &length));
  5560. if (length.IsSmallIndex())
  5561. {
  5562. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  5563. }
  5564. Assert(pArr == nullptr || length.IsUint32Max());
  5565. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  5566. JIT_HELPER_END(Array_Slice);
  5567. }
  5568. // Array.prototype.slice as described in ES6.0 (draft 22) Section 22.1.3.22
  5569. template <typename T>
  5570. Var JavascriptArray::SliceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  5571. {
  5572. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5573. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  5574. JavascriptArray* newArr = nullptr;
  5575. RecyclableObject* newObj = nullptr;
  5576. bool isIntArray = false;
  5577. bool isFloatArray = false;
  5578. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  5579. bool isBuiltinArrayCtor = true;
  5580. T startT = 0;
  5581. T newLenT = length;
  5582. T endT = length;
  5583. #if ENABLE_COPYONACCESS_ARRAY
  5584. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pArr);
  5585. #endif
  5586. if (args.Info.Count > 1)
  5587. {
  5588. JS_REENTRANT(jsReentLock, startT = GetFromIndex(args[1], length, scriptContext));
  5589. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  5590. {
  5591. JS_REENTRANT(jsReentLock, endT = GetFromIndex(args[2], length, scriptContext));
  5592. }
  5593. newLenT = endT > startT ? endT - startT : 0;
  5594. }
  5595. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments start or end may convert the array to an ES5 array.
  5596. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  5597. {
  5598. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  5599. pArr = nullptr;
  5600. }
  5601. if (TypedArrayBase::IsDetachedTypedArray(obj))
  5602. {
  5603. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.slice"));
  5604. }
  5605. // If we came from Array.prototype.slice and source object is not a JavascriptArray, source could be a TypedArray
  5606. if (!isTypedArrayEntryPoint && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  5607. {
  5608. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  5609. }
  5610. // If the entry point is %TypedArray%.prototype.slice or the source object is an Array exotic object we should try to load the constructor property
  5611. // and use it to construct the return object.
  5612. if (isTypedArrayEntryPoint)
  5613. {
  5614. JavascriptFunction* defaultConstructor = TypedArrayBase::GetDefaultConstructor(args[0], scriptContext);
  5615. JS_REENTRANT(jsReentLock,
  5616. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, defaultConstructor, scriptContext));
  5617. isBuiltinArrayCtor = false;
  5618. AssertAndFailFast(pArr == nullptr);
  5619. AssertOrFailFast(JavascriptOperators::IsConstructor(constructor));
  5620. bool isDefaultConstructor = constructor == defaultConstructor;
  5621. JS_REENTRANT(jsReentLock,
  5622. newObj = VarTo<RecyclableObject>(
  5623. JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var
  5624. {
  5625. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(newLenT, scriptContext) };
  5626. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  5627. return TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)newLenT, scriptContext);
  5628. }));
  5629. );
  5630. }
  5631. else if (pArr != nullptr)
  5632. {
  5633. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(pArr, newLenT, scriptContext, &isIntArray, &isFloatArray, &isBuiltinArrayCtor));
  5634. }
  5635. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  5636. else
  5637. {
  5638. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(obj, newLenT, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  5639. }
  5640. // If we didn't create a new object above we will create a new array here.
  5641. // This is the pre-ES6 behavior or the case of calling Array.prototype.slice with a constructor argument that is not a constructor function.
  5642. if (newObj == nullptr)
  5643. {
  5644. if (pArr)
  5645. {
  5646. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  5647. }
  5648. if (newLenT > JavascriptArray::MaxArrayLength)
  5649. {
  5650. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  5651. }
  5652. newArr = CreateNewArrayHelper(static_cast<uint32>(newLenT), isIntArray, isFloatArray, pArr, scriptContext);
  5653. #if ENABLE_COPYONACCESS_ARRAY
  5654. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5655. #endif
  5656. newObj = newArr;
  5657. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  5658. }
  5659. else
  5660. {
  5661. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  5662. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  5663. if (newArr)
  5664. {
  5665. #if ENABLE_COPYONACCESS_ARRAY
  5666. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  5667. #endif
  5668. }
  5669. }
  5670. uint32 start = (uint32) startT;
  5671. uint32 newLen = (uint32) newLenT;
  5672. // We at least have to have newObj as a valid object
  5673. Assert(newObj);
  5674. // Bail out early if the new object will have zero length.
  5675. if (newLen == 0)
  5676. {
  5677. return newObj;
  5678. }
  5679. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  5680. // we will process the array elements like an ES5Array.
  5681. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  5682. {
  5683. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  5684. pArr = nullptr;
  5685. }
  5686. if (pArr)
  5687. {
  5688. if (HasAnyES5ArrayInPrototypeChain(pArr))
  5689. {
  5690. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));
  5691. }
  5692. // If we constructed a new Array object, we have some nice helpers here
  5693. if (newArr && isBuiltinArrayCtor)
  5694. {
  5695. if (JavascriptArray::IsDirectAccessArray(newArr))
  5696. {
  5697. if (((start + newLen) <= pArr->head->length) && newLen <= newArr->head->size) //Fast Path
  5698. {
  5699. if (isIntArray)
  5700. {
  5701. JS_REENTRANT(jsReentLock, SliceHelper<int32>(pArr, newArr, start, newLen));
  5702. }
  5703. else if (isFloatArray)
  5704. {
  5705. JS_REENTRANT(jsReentLock, SliceHelper<double>(pArr, newArr, start, newLen));
  5706. }
  5707. else
  5708. {
  5709. JS_REENTRANT(jsReentLock, SliceHelper<Var>(pArr, newArr, start, newLen));
  5710. }
  5711. }
  5712. else
  5713. {
  5714. if (isIntArray)
  5715. {
  5716. JS_REENTRANT(jsReentLock, CopyNativeIntArrayElements(VarTo<JavascriptNativeIntArray>(newArr), 0, VarTo<JavascriptNativeIntArray>(pArr), start, start + newLen));
  5717. }
  5718. else if (isFloatArray)
  5719. {
  5720. JS_REENTRANT(jsReentLock, CopyNativeFloatArrayElements(VarTo<JavascriptNativeFloatArray>(newArr), 0, VarTo<JavascriptNativeFloatArray>(pArr), start, start + newLen));
  5721. }
  5722. else
  5723. {
  5724. JS_REENTRANT(jsReentLock, CopyArrayElements(newArr, 0u, pArr, start, start + newLen));
  5725. }
  5726. }
  5727. }
  5728. else
  5729. {
  5730. AssertMsg(CONFIG_FLAG(ForceES5Array), "newArr can only be ES5Array when it is forced");
  5731. Var element;
  5732. for (uint32 i = 0; i < newLen; i++)
  5733. {
  5734. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5735. if (!gotItem)
  5736. {
  5737. continue;
  5738. }
  5739. newArr->SetItem(i, element, PropertyOperation_None);
  5740. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5741. // we will process the rest of the array elements like an ES5Array.
  5742. if (!JavascriptArray::IsNonES5Array(obj))
  5743. {
  5744. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  5745. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5746. }
  5747. }
  5748. }
  5749. }
  5750. else
  5751. {
  5752. // The constructed object isn't an array, we'll need to use normal object manipulation
  5753. Var element;
  5754. for (uint32 i = 0; i < newLen; i++)
  5755. {
  5756. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(i + start, &element));
  5757. if (!gotItem)
  5758. {
  5759. continue;
  5760. }
  5761. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5762. // Side-effects in the prototype lookup may have changed the source array into an ES5Array. If this happens
  5763. // we will process the rest of the array elements like an ES5Array.
  5764. if (!JavascriptArray::IsNonES5Array(obj))
  5765. {
  5766. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  5767. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, i + 1, newArr, newObj, newLen, scriptContext));
  5768. }
  5769. }
  5770. }
  5771. }
  5772. else if (typedArrayBase)
  5773. {
  5774. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  5775. // Source is a TypedArray, we must have created the return object via a call to constructor, but newObj may not be a TypedArray (or an array either)
  5776. TypedArrayBase* newTypedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj);
  5777. if (!newTypedArray)
  5778. {
  5779. AssertAndFailFast(newArr != nullptr);
  5780. }
  5781. Var element;
  5782. for (uint32 i = 0; i < newLen; i++)
  5783. {
  5784. // We only need to call HasItem in the case that we are called from Array.prototype.slice
  5785. if (!isTypedArrayEntryPoint && !typedArrayBase->HasItem(i + start))
  5786. {
  5787. continue;
  5788. }
  5789. element = typedArrayBase->DirectGetItem(i + start);
  5790. // The object we got back from the constructor might not be a TypedArray. In fact, it could be any object.
  5791. if (newTypedArray)
  5792. {
  5793. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(i, element));
  5794. }
  5795. else
  5796. {
  5797. newArr->SetItem(i, element, PropertyOperation_None);
  5798. }
  5799. }
  5800. }
  5801. else
  5802. {
  5803. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SliceObjectHelper(obj, start, 0u, newArr, newObj, newLen, scriptContext));;
  5804. }
  5805. if (!isTypedArrayEntryPoint)
  5806. {
  5807. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5808. }
  5809. #ifdef VALIDATE_ARRAY
  5810. JavascriptArray * jsArr = JavascriptArray::TryVarToNonES5Array(newObj);
  5811. if (jsArr)
  5812. {
  5813. jsArr->ValidateArray();
  5814. }
  5815. #endif
  5816. return newObj;
  5817. }
  5818. Var JavascriptArray::SliceObjectHelper(RecyclableObject* obj, uint32 sliceStart, uint32 start, JavascriptArray* newArr, RecyclableObject* newObj, uint32 newLen, ScriptContext* scriptContext)
  5819. {
  5820. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  5821. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  5822. for (uint32 i = start; i < newLen; i++)
  5823. {
  5824. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i + sliceStart));
  5825. if (hasItem)
  5826. {
  5827. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(obj, i + sliceStart, scriptContext));
  5828. if (newArr != nullptr)
  5829. {
  5830. newArr->SetItem(i, element, PropertyOperation_None);
  5831. }
  5832. else
  5833. {
  5834. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  5835. }
  5836. }
  5837. }
  5838. JS_REENTRANT(jsReentLock,
  5839. JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  5840. #ifdef VALIDATE_ARRAY
  5841. JavascriptArray * jsArr = JavascriptArray::TryVarToNonES5Array(newObj);
  5842. if (jsArr)
  5843. {
  5844. jsArr->ValidateArray();
  5845. }
  5846. #endif
  5847. return newObj;
  5848. }
  5849. struct CompareVarsInfo
  5850. {
  5851. ScriptContext* scriptContext;
  5852. RecyclableObject* compFn;
  5853. };
  5854. int __cdecl compareVars(void* cvInfoV, const void* aRef, const void* bRef)
  5855. {
  5856. CompareVarsInfo* cvInfo=(CompareVarsInfo*)cvInfoV;
  5857. ScriptContext* requestContext=cvInfo->scriptContext;
  5858. RecyclableObject* compFn=cvInfo->compFn;
  5859. AssertMsg(*(Var*)aRef, "No null expected in sort");
  5860. AssertMsg(*(Var*)bRef, "No null expected in sort");
  5861. if (compFn != nullptr)
  5862. {
  5863. ScriptContext* scriptContext = compFn->GetScriptContext();
  5864. ThreadContext* threadContext = scriptContext->GetThreadContext();
  5865. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  5866. CallFlags flags = CallFlags_Value;
  5867. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  5868. Var retVal;
  5869. if (requestContext != scriptContext)
  5870. {
  5871. Var leftVar = CrossSite::MarshalVar(scriptContext, *(Var*)aRef);
  5872. Var rightVar = CrossSite::MarshalVar(scriptContext, *(Var*)bRef);
  5873. BEGIN_SAFE_REENTRANT_CALL(threadContext)
  5874. {
  5875. retVal = CALL_FUNCTION(threadContext, compFn, CallInfo(flags, 3), undefined, leftVar, rightVar);
  5876. }
  5877. END_SAFE_REENTRANT_CALL
  5878. }
  5879. else
  5880. {
  5881. BEGIN_SAFE_REENTRANT_CALL(threadContext)
  5882. {
  5883. retVal = CALL_FUNCTION(scriptContext->GetThreadContext(), compFn, CallInfo(flags, 3), undefined, *(Var*)aRef, *(Var*)bRef);
  5884. }
  5885. END_SAFE_REENTRANT_CALL
  5886. }
  5887. if (TaggedInt::Is(retVal))
  5888. {
  5889. return TaggedInt::ToInt32(retVal);
  5890. }
  5891. double dblResult;
  5892. if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
  5893. {
  5894. dblResult = JavascriptNumber::GetValue(retVal);
  5895. }
  5896. else
  5897. {
  5898. dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
  5899. }
  5900. if (dblResult < 0)
  5901. {
  5902. return -1;
  5903. }
  5904. return (dblResult > 0) ? 1 : 0;
  5905. }
  5906. else
  5907. {
  5908. JavascriptString* pStr1 = JavascriptConversion::ToString(*(Var*)aRef, requestContext);
  5909. JavascriptString* pStr2 = JavascriptConversion::ToString(*(Var*)bRef, requestContext);
  5910. return JavascriptString::strcmp(pStr1, pStr2);
  5911. }
  5912. }
  5913. static void hybridSort(__inout_ecount(length) Field(Var) *elements, uint32 length, CompareVarsInfo* compareInfo)
  5914. {
  5915. // The cost of memory moves starts to be more expensive than additional comparer calls (given a simple comparer)
  5916. // for arrays of more than 512 elements.
  5917. if (length > 512)
  5918. {
  5919. qsort_s(elements, length, compareVars, compareInfo);
  5920. return;
  5921. }
  5922. for (int i = 1; i < (int)length; i++)
  5923. {
  5924. if (compareVars(compareInfo, elements + i, elements + i - 1) < 0) {
  5925. // binary search for the left-most element greater than value:
  5926. int first = 0;
  5927. int last = i - 1;
  5928. while (first <= last)
  5929. {
  5930. int middle = (first + last) / 2;
  5931. if (compareVars(compareInfo, elements + i, elements + middle) < 0)
  5932. {
  5933. last = middle - 1;
  5934. }
  5935. else
  5936. {
  5937. first = middle + 1;
  5938. }
  5939. }
  5940. // insert value right before first:
  5941. Var value = elements[i];
  5942. MoveArray(elements + first + 1, elements + first, (i - first));
  5943. elements[first] = value;
  5944. }
  5945. }
  5946. }
  5947. void JavascriptArray::Sort(RecyclableObject* compFn)
  5948. {
  5949. JS_REENTRANCY_LOCK(jsReentLock, this->GetScriptContext()->GetThreadContext());
  5950. if (length <= 1)
  5951. {
  5952. return;
  5953. }
  5954. SETOBJECT_FOR_MUTATION(jsReentLock, this);
  5955. this->EnsureHead<Var>();
  5956. ScriptContext* scriptContext = this->GetScriptContext();
  5957. Recycler* recycler = scriptContext->GetRecycler();
  5958. CompareVarsInfo cvInfo;
  5959. cvInfo.scriptContext = scriptContext;
  5960. cvInfo.compFn = compFn;
  5961. Assert(head != nullptr);
  5962. // Just dump the segment map on sort
  5963. ClearSegmentMap();
  5964. uint32 countUndefined = 0;
  5965. SparseArraySegment<Var>* startSeg = SparseArraySegment<Var>::From(head);
  5966. // Sort may have side effects on the array. Setting a dummy head so that original array is not affected
  5967. uint32 saveLength = length;
  5968. // that if compare function tries to modify the array it won't AV.
  5969. head = const_cast<SparseArraySegmentBase*>(EmptySegment);
  5970. SetFlags(DynamicObjectFlags::None);
  5971. this->InvalidateLastUsedSegment();
  5972. length = 0;
  5973. TryFinally([&]()
  5974. {
  5975. //The array is a continuous array if there is only one segment
  5976. if (startSeg->next == nullptr
  5977. // If this flag is specified, we want to improve the consistency of our array sorts
  5978. // by removing missing values from all kinds of arrays before sorting (done here by
  5979. // using the copy-to-one-segment path for array sorts) and by using a stronger sort
  5980. // comparer than the spec requires (done in CompareElements).
  5981. && !CONFIG_FLAG(StrongArraySort)
  5982. ) // Single segment fast path
  5983. {
  5984. if (compFn != nullptr)
  5985. {
  5986. countUndefined = startSeg->RemoveUndefined(scriptContext);
  5987. #ifdef VALIDATE_ARRAY
  5988. ValidateSegment(startSeg);
  5989. #endif
  5990. JS_REENTRANT(jsReentLock, hybridSort(startSeg->elements, startSeg->length, &cvInfo));
  5991. startSeg->CheckLengthvsSize();
  5992. }
  5993. else
  5994. {
  5995. JS_REENTRANT(jsReentLock, countUndefined = sort(startSeg->elements, &startSeg->length, scriptContext));
  5996. }
  5997. head = startSeg;
  5998. }
  5999. else
  6000. {
  6001. SparseArraySegment<Var>* allElements = SparseArraySegment<Var>::AllocateSegment(recycler, 0, 0, nullptr);
  6002. SparseArraySegment<Var>* next = startSeg;
  6003. uint32 nextIndex = 0;
  6004. // copy all the elements to single segment
  6005. while (next)
  6006. {
  6007. countUndefined += next->RemoveUndefined(scriptContext);
  6008. if (next->length != 0)
  6009. {
  6010. allElements = SparseArraySegment<Var>::CopySegment(recycler, allElements, nextIndex, next, next->left, next->length);
  6011. }
  6012. next = SparseArraySegment<Var>::From(next->next);
  6013. nextIndex = allElements->length;
  6014. #ifdef VALIDATE_ARRAY
  6015. ValidateSegment(allElements);
  6016. #endif
  6017. }
  6018. if (compFn != nullptr)
  6019. {
  6020. JS_REENTRANT(jsReentLock, hybridSort(allElements->elements, allElements->length, &cvInfo));
  6021. }
  6022. else
  6023. {
  6024. JS_REENTRANT(jsReentLock, sort(allElements->elements, &allElements->length, scriptContext));
  6025. allElements->CheckLengthvsSize();
  6026. }
  6027. head = allElements;
  6028. head->next = nullptr;
  6029. }
  6030. },
  6031. [&](bool hasException)
  6032. {
  6033. length = saveLength;
  6034. ClearSegmentMap(); // Dump the segmentMap again in case user compare function rebuilds it
  6035. if (hasException)
  6036. {
  6037. // The current array might have affected due to callbacks. As we have got the exception we should be resetting the missing value.
  6038. SetHasNoMissingValues(false);
  6039. head = startSeg;
  6040. this->InvalidateLastUsedSegment();
  6041. }
  6042. });
  6043. #if DEBUG
  6044. {
  6045. uint32 countNull = 0;
  6046. uint32 index = head->length - 1;
  6047. while (countNull < head->length)
  6048. {
  6049. if (SparseArraySegment<Var>::From(head)->elements[index] != NULL)
  6050. {
  6051. break;
  6052. }
  6053. index--;
  6054. countNull++;
  6055. }
  6056. AssertMsg(countNull == 0, "No null expected at the end");
  6057. }
  6058. #endif
  6059. if (countUndefined != 0)
  6060. {
  6061. // fill undefined at the end
  6062. uint32 newLength = head->length + countUndefined;
  6063. if (newLength > head->size)
  6064. {
  6065. SparseArraySegmentBase *oldHead = head;
  6066. bool isInlineSegment = JavascriptArray::IsInlineSegment(head, this);
  6067. head = SparseArraySegment<Var>::From(head)->GrowByMin(recycler, newLength - head->size);
  6068. if (isInlineSegment)
  6069. {
  6070. this->ClearElements(oldHead, 0);
  6071. }
  6072. }
  6073. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  6074. for (uint32 i = head->length; i < newLength; i++)
  6075. {
  6076. SparseArraySegment<Var>::From(head)->elements[i] = undefined;
  6077. }
  6078. head->length = newLength;
  6079. head->CheckLengthvsSize();
  6080. }
  6081. SetHasNoMissingValues();
  6082. this->InvalidateLastUsedSegment();
  6083. this->ClearSegmentMap();
  6084. #ifdef VALIDATE_ARRAY
  6085. ValidateArray();
  6086. #endif
  6087. return;
  6088. }
  6089. uint32 JavascriptArray::sort(__inout_ecount(*len) Field(Var) *orig, uint32 *len, ScriptContext *scriptContext)
  6090. {
  6091. uint32 count = 0, countUndefined = 0;
  6092. Element *elements = RecyclerNewArrayZ(scriptContext->GetRecycler(), Element, *len);
  6093. RecyclableObject *undefined = scriptContext->GetLibrary()->GetUndefined();
  6094. //
  6095. // Create the Elements array
  6096. //
  6097. for (uint32 i = 0; i < *len; ++i)
  6098. {
  6099. if (!SparseArraySegment<Var>::IsMissingItem(&orig[i]))
  6100. {
  6101. if (!JavascriptOperators::IsUndefinedObject(orig[i], undefined))
  6102. {
  6103. elements[count].Value = orig[i];
  6104. elements[count].StringValue = JavascriptConversion::ToString(orig[i], scriptContext);
  6105. count++;
  6106. }
  6107. else
  6108. {
  6109. countUndefined++;
  6110. }
  6111. }
  6112. }
  6113. if (count > 0)
  6114. {
  6115. SortElements(elements, 0, count - 1);
  6116. for (uint32 i = 0; i < count; ++i)
  6117. {
  6118. orig[i] = elements[i].Value;
  6119. }
  6120. }
  6121. for (uint32 i = count + countUndefined; i < *len; ++i)
  6122. {
  6123. orig[i] = SparseArraySegment<Var>::GetMissingItem();
  6124. }
  6125. *len = count; // set the correct length
  6126. return countUndefined;
  6127. }
  6128. int __cdecl JavascriptArray::CompareElements(void* context, const void* elem1, const void* elem2)
  6129. {
  6130. const Element* element1 = static_cast<const Element*>(elem1);
  6131. const Element* element2 = static_cast<const Element*>(elem2);
  6132. Assert(element1 != NULL);
  6133. Assert(element2 != NULL);
  6134. if (!CONFIG_FLAG(StrongArraySort))
  6135. {
  6136. return JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  6137. }
  6138. else
  6139. {
  6140. int str_cmp = JavascriptString::strcmp(element1->StringValue, element2->StringValue);
  6141. if (str_cmp != 0)
  6142. {
  6143. return str_cmp;
  6144. }
  6145. // If they are equal, we get to a slightly more complex problem. We want to make a very
  6146. // predictable sort here, regardless of the structure of the array. To achieve this, we
  6147. // need to get an order for every pair of non-identical elements, else there will be an
  6148. // identifiable difference between sparse and dense array sorts in some cases.
  6149. // Handle a common set of equivalent nodes first for speed/convenience
  6150. if (element1->Value == element2->Value)
  6151. {
  6152. return 0;
  6153. }
  6154. // Easy way to do most remaining cases is to just compare the type ids if they differ.
  6155. if (JavascriptOperators::GetTypeId(element1->Value) != JavascriptOperators::GetTypeId(element2->Value))
  6156. {
  6157. return JavascriptOperators::GetTypeId(element1->Value) - JavascriptOperators::GetTypeId(element2->Value);
  6158. }
  6159. // Further comparisons are possible, but get increasingly complex, and aren't necessary
  6160. // for the cases on hand.
  6161. return 0;
  6162. }
  6163. }
  6164. void JavascriptArray::SortElements(Element* elements, uint32 left, uint32 right)
  6165. {
  6166. // Note: use write barrier policy of Field(Var)
  6167. qsort_s<Element, Field(Var)>(elements, right - left + 1, CompareElements, this);
  6168. }
  6169. Var JavascriptArray::EntrySort(RecyclableObject* function, CallInfo callInfo, ...)
  6170. {
  6171. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6172. ARGUMENTS(args, callInfo);
  6173. ScriptContext* scriptContext = function->GetScriptContext();
  6174. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6175. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.sort"));
  6176. Assert(!(callInfo.Flags & CallFlags_New));
  6177. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  6178. RecyclableObject* compFn = NULL;
  6179. if (args.Info.Count > 1)
  6180. {
  6181. if (JavascriptConversion::IsCallable(args[1]))
  6182. {
  6183. compFn = VarTo<RecyclableObject>(args[1]);
  6184. }
  6185. else
  6186. {
  6187. TypeId typeId = JavascriptOperators::GetTypeId(args[1]);
  6188. // Use default comparer:
  6189. // - In ES5 mode if the argument is undefined.
  6190. bool useDefaultComparer = typeId == TypeIds_Undefined;
  6191. if (!useDefaultComparer)
  6192. {
  6193. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.sort"));
  6194. }
  6195. }
  6196. }
  6197. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6198. bool useNoSideEffectSort = JavascriptArray::IsNonES5Array(args[0])
  6199. && !VarTo<JavascriptArray>(args[0])->IsCrossSiteObject()
  6200. && !HasAnyES5ArrayInPrototypeChain(UnsafeVarTo<JavascriptArray>(args[0]));
  6201. if (useNoSideEffectSort)
  6202. {
  6203. JavascriptArray *arr = UnsafeVarTo<JavascriptArray>(args[0]);
  6204. if (arr->length <= 1)
  6205. {
  6206. return args[0];
  6207. }
  6208. uint32 length = arr->length;
  6209. if(arr->IsFillFromPrototypes())
  6210. {
  6211. arr->FillFromPrototypes(0, arr->length); // We need find all missing value from [[proto]] object
  6212. }
  6213. // As we have already established that the FillFromPrototype should not change the bound of the array.
  6214. if (length != arr->length)
  6215. {
  6216. Js::Throw::FatalInternalError();
  6217. }
  6218. EnsureNonNativeArray(arr);
  6219. JS_REENTRANT(jsReentLock, arr->Sort(compFn));
  6220. }
  6221. else
  6222. {
  6223. RecyclableObject* pObj = nullptr;
  6224. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &pObj))
  6225. {
  6226. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.sort"));
  6227. }
  6228. JS_REENTRANT(jsReentLock,
  6229. uint32 len = JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(pObj, scriptContext), scriptContext));
  6230. JavascriptArray* sortArray = scriptContext->GetLibrary()->CreateArray(len);
  6231. sortArray->EnsureHead<Var>();
  6232. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.sort"));
  6233. BEGIN_TEMP_ALLOCATOR(tempAlloc, scriptContext, _u("Runtime"))
  6234. {
  6235. JsUtil::List<uint32, ArenaAllocator>* indexList = JsUtil::List<uint32, ArenaAllocator>::New(tempAlloc);
  6236. for (uint32 i = 0; i < len; i++)
  6237. {
  6238. Var item;
  6239. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(pObj, i, &item, scriptContext));
  6240. if (gotItem)
  6241. {
  6242. indexList->Add(i);
  6243. sortArray->DirectSetItemAt(i, item);
  6244. }
  6245. }
  6246. if (indexList->Count() > 0)
  6247. {
  6248. if (sortArray->length > 1)
  6249. {
  6250. JS_REENTRANT(jsReentLock, sortArray->FillFromPrototypes(0, sortArray->length)); // We need find all missing value from [[proto]] object
  6251. }
  6252. JS_REENTRANT(jsReentLock, sortArray->Sort(compFn));
  6253. uint32 removeIndex = sortArray->head->length;
  6254. for (uint32 i = 0; i < removeIndex; i++)
  6255. {
  6256. AssertMsg(!SparseArraySegment<Var>::IsMissingItem(&SparseArraySegment<Var>::From(sortArray->head)->elements[i]), "No gaps expected in sorted array");
  6257. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, i, SparseArraySegment<Var>::From(sortArray->head)->elements[i], scriptContext)));
  6258. }
  6259. for (int i = 0; i < indexList->Count(); i++)
  6260. {
  6261. uint32 value = indexList->Item(i);
  6262. if (value >= removeIndex)
  6263. {
  6264. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure((JavascriptOperators::DeleteItem(pObj, value))));
  6265. }
  6266. }
  6267. }
  6268. }
  6269. END_TEMP_ALLOCATOR(tempAlloc, scriptContext);
  6270. }
  6271. return args[0];
  6272. }
  6273. Var JavascriptArray::EntrySplice(RecyclableObject* function, CallInfo callInfo, ...)
  6274. {
  6275. JIT_HELPER_REENTRANT_HEADER(Array_Splice);
  6276. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6277. ARGUMENTS(args, callInfo);
  6278. ScriptContext* scriptContext = function->GetScriptContext();
  6279. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6280. Assert(!(callInfo.Flags & CallFlags_New));
  6281. AssertMsg(args.Info.Count >= 1, "Should have at least one argument");
  6282. JavascriptArray* pArr = 0;
  6283. RecyclableObject* pObj = 0;
  6284. uint64 start = 0u;
  6285. uint64 deleteLen = 0u;
  6286. uint64 length = 0u;
  6287. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.splice"), &pArr, &pObj, &length));
  6288. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  6289. switch (args.Info.Count)
  6290. {
  6291. case 1:
  6292. start = length;
  6293. deleteLen = 0u;
  6294. break;
  6295. case 2:
  6296. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext));
  6297. deleteLen = length - start;
  6298. break;
  6299. default:
  6300. JS_REENTRANT(jsReentLock, start = GetFromIndex(args[1], length, scriptContext),
  6301. deleteLen = GetFromIndex(args[2], (length - start), scriptContext, false));
  6302. break;
  6303. }
  6304. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments start or deleteCount may convert the array to an ES5 array.
  6305. if (pArr && !JavascriptArray::IsNonES5Array(pObj))
  6306. {
  6307. AssertOrFailFastMsg(VarIs<ES5Array>(pObj), "The array should have been converted to an ES5Array");
  6308. pArr = nullptr;
  6309. }
  6310. Var* insertArgs = args.Info.Count > 3 ? &args.Values[3] : nullptr;
  6311. uint32 insertLen = args.Info.Count > 3 ? args.Info.Count - 3 : 0;
  6312. // Force check the prototype as we may insert values more than current elements
  6313. if (pArr != nullptr && !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/))
  6314. {
  6315. // Since we get the length from an array and that cannot be more than uint32.
  6316. _Analysis_assume_(length <= UINT_MAX);
  6317. JS_REENTRANT_UNLOCK(jsReentLock,
  6318. return TryArraySplice(pArr, (uint32)start, (uint32)length, (uint32)deleteLen, insertArgs, insertLen, scriptContext));
  6319. }
  6320. uint64 newLen = (length - deleteLen) + insertLen;
  6321. if (newLen > UINT_MAX || length > UINT_MAX || (length + insertLen) > UINT_MAX)
  6322. {
  6323. JS_REENTRANT_UNLOCK(jsReentLock,
  6324. return ObjectSpliceHelper<uint64>(pObj, length, start, deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6325. }
  6326. else
  6327. {
  6328. JS_REENTRANT_UNLOCK(jsReentLock,
  6329. return ObjectSpliceHelper<uint32>(pObj, (uint32)length, (uint32)start, (uint32)deleteLen, (Var*)insertArgs, insertLen, scriptContext, nullptr));
  6330. }
  6331. JIT_HELPER_END(Array_Splice);
  6332. }
  6333. inline BOOL JavascriptArray::IsSingleSegmentArray() const
  6334. {
  6335. return nullptr == head->next;
  6336. }
  6337. template<typename T>
  6338. void JavascriptArray::ArraySegmentSpliceHelper(
  6339. JavascriptArray *pnewArr, SparseArraySegment<T> *seg, Field(SparseArraySegment<T>*) *prev,
  6340. uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, Recycler *recycler)
  6341. {
  6342. // book keeping variables
  6343. uint32 relativeStart = start - seg->left; // This will be different from start when head->left is non zero -
  6344. //(Missing elements at the beginning)
  6345. uint32 headDeleteLen = min(start + deleteLen , seg->left + seg->length) - start; // actual number of elements to delete in
  6346. // head if deleteLen overflows the length of head
  6347. uint32 newHeadLen = seg->length - headDeleteLen + insertLen; // new length of the head after splice
  6348. // Save the deleted elements
  6349. if (headDeleteLen != 0)
  6350. {
  6351. SparseArraySegmentBase *oldHead = pnewArr->head;
  6352. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pnewArr);
  6353. pnewArr->InvalidateLastUsedSegment();
  6354. pnewArr->head = SparseArraySegment<T>::CopySegment(recycler, SparseArraySegment<T>::From(pnewArr->head), 0, seg, start, headDeleteLen);
  6355. if (isInlineSegment && oldHead != pnewArr->head)
  6356. {
  6357. pnewArr->ClearElements(oldHead, 0);
  6358. }
  6359. }
  6360. if (newHeadLen != 0)
  6361. {
  6362. if (seg->size < newHeadLen)
  6363. {
  6364. if (seg->next)
  6365. {
  6366. // If we have "next", require that we haven't adjusted next segments left yet.
  6367. seg = seg->GrowByMinMax(recycler, newHeadLen - seg->size, seg->next->left - deleteLen + insertLen - seg->left - seg->size);
  6368. }
  6369. else
  6370. {
  6371. seg = seg->GrowByMin(recycler, newHeadLen - seg->size);
  6372. }
  6373. #ifdef VALIDATE_ARRAY
  6374. ValidateSegment(seg);
  6375. #endif
  6376. }
  6377. // Move the elements if necessary
  6378. if (headDeleteLen != insertLen)
  6379. {
  6380. uint32 noElementsToMove = seg->length - (relativeStart + headDeleteLen);
  6381. MoveArray(seg->elements + relativeStart + insertLen,
  6382. seg->elements + relativeStart + headDeleteLen,
  6383. noElementsToMove);
  6384. if (newHeadLen < seg->length) // truncate if necessary
  6385. {
  6386. seg->Truncate(seg->left + newHeadLen); // set end elements to null so that when we introduce null elements we are safe
  6387. }
  6388. seg->length = newHeadLen;
  6389. seg->CheckLengthvsSize();
  6390. }
  6391. // Copy the new elements
  6392. if (insertLen > 0)
  6393. {
  6394. Assert(!VirtualTableInfo<JavascriptNativeIntArray>::HasVirtualTable(pnewArr) &&
  6395. !VirtualTableInfo<JavascriptNativeFloatArray>::HasVirtualTable(pnewArr));
  6396. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6397. CopyArray(seg->elements + relativeStart, insertLen,
  6398. reinterpret_cast<const T*>(insertArgs), insertLen);
  6399. }
  6400. *prev = seg;
  6401. }
  6402. else
  6403. {
  6404. *prev = SparseArraySegment<T>::From(seg->next);
  6405. }
  6406. }
  6407. template<typename T>
  6408. void JavascriptArray::ArraySpliceHelper(JavascriptArray* pnewArr, JavascriptArray* pArr, uint32 start, uint32 deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6409. {
  6410. // Skip pnewArr->EnsureHead(): we don't use existing segment at all.
  6411. Recycler *recycler = scriptContext->GetRecycler();
  6412. Field(SparseArraySegmentBase*)* prevSeg = &pArr->head; // holds the next pointer of previous
  6413. Field(SparseArraySegmentBase*)* prevPrevSeg = &pArr->head; // this holds the previous pointer to prevSeg dirty trick.
  6414. SparseArraySegmentBase* savePrev = nullptr;
  6415. Assert(pArr->head); // We should never have a null head.
  6416. pArr->EnsureHead<T>();
  6417. SparseArraySegment<T>* startSeg = SparseArraySegment<T>::From(pArr->head);
  6418. const uint32 limit = start + deleteLen;
  6419. uint32 rightLimit;
  6420. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6421. {
  6422. rightLimit = JavascriptArray::MaxArrayLength;
  6423. }
  6424. // Find out the segment to start delete
  6425. while (startSeg && (rightLimit <= start))
  6426. {
  6427. savePrev = startSeg;
  6428. prevPrevSeg = prevSeg;
  6429. prevSeg = &startSeg->next;
  6430. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6431. if (startSeg)
  6432. {
  6433. if (UInt32Math::Add(startSeg->left, startSeg->size, &rightLimit))
  6434. {
  6435. rightLimit = JavascriptArray::MaxArrayLength;
  6436. }
  6437. }
  6438. }
  6439. bool hasInlineSegment = JavascriptArray::IsInlineSegment(startSeg, pArr);
  6440. if (startSeg)
  6441. {
  6442. // Delete Phase
  6443. if (startSeg->left <= start && (startSeg->left + startSeg->length) >= limit)
  6444. {
  6445. // All splice happens in one segment.
  6446. SparseArraySegmentBase *nextSeg = startSeg->next;
  6447. // Splice the segment first, which might OOM throw but the array would be intact.
  6448. JavascriptArray::ArraySegmentSpliceHelper(
  6449. pnewArr, startSeg, SparseArraySegment<T>::AddressFrom(prevSeg),
  6450. start, deleteLen, insertArgs, insertLen, recycler);
  6451. while (nextSeg)
  6452. {
  6453. // adjust next segments left
  6454. nextSeg->left = nextSeg->left - deleteLen + insertLen;
  6455. if (nextSeg->next == nullptr)
  6456. {
  6457. nextSeg->EnsureSizeInBound();
  6458. }
  6459. nextSeg = nextSeg->next;
  6460. }
  6461. if (*prevSeg)
  6462. {
  6463. (*prevSeg)->EnsureSizeInBound();
  6464. }
  6465. return;
  6466. }
  6467. else
  6468. {
  6469. SparseArraySegment<T>* newHeadSeg = nullptr; // pnewArr->head is null
  6470. Field(SparseArraySegmentBase*)* prevNewHeadSeg = &pnewArr->head;
  6471. // delete till deleteLen and reuse segments for new array if it is possible.
  6472. // 3 steps -
  6473. //1. delete 1st segment (which may be partial delete)
  6474. // 2. delete next n complete segments
  6475. // 3. delete last segment (which again may be partial delete)
  6476. // Step (1) -- WOOB 1116297: When left >= start, step (1) is skipped, resulting in pNewArr->head->left != 0. We need to touch up pNewArr.
  6477. if (startSeg->left < start)
  6478. {
  6479. if (start < startSeg->left + startSeg->length)
  6480. {
  6481. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6482. if (startSeg->next)
  6483. {
  6484. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6485. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6486. }
  6487. else
  6488. {
  6489. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6490. }
  6491. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6492. newHeadSeg->next = nullptr;
  6493. *prevNewHeadSeg = newHeadSeg;
  6494. prevNewHeadSeg = &newHeadSeg->next;
  6495. startSeg->Truncate(start);
  6496. }
  6497. savePrev = startSeg;
  6498. prevPrevSeg = prevSeg;
  6499. prevSeg = &startSeg->next;
  6500. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6501. }
  6502. // Step (2) first we should do a hard copy if we have an inline head Segment
  6503. else if (hasInlineSegment && nullptr != startSeg)
  6504. {
  6505. // start should be in between left and left + length
  6506. if (startSeg->left <= start && start < startSeg->left + startSeg->length)
  6507. {
  6508. uint32 headDeleteLen = startSeg->left + startSeg->length - start;
  6509. if (startSeg->next)
  6510. {
  6511. // We know the new segment will have a next segment, so allocate it as non-leaf.
  6512. newHeadSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6513. }
  6514. else
  6515. {
  6516. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, headDeleteLen, headDeleteLen, nullptr);
  6517. }
  6518. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, 0, startSeg, start, headDeleteLen);
  6519. *prevNewHeadSeg = newHeadSeg;
  6520. prevNewHeadSeg = &newHeadSeg->next;
  6521. // Remove the entire segment from the original array
  6522. *prevSeg = startSeg->next;
  6523. pArr->ClearElements(startSeg, 0);
  6524. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6525. }
  6526. // if we have an inline head segment with 0 elements, remove it
  6527. else if (startSeg->left == 0 && startSeg->length == 0)
  6528. {
  6529. Assert(startSeg->size != 0);
  6530. *prevSeg = startSeg->next;
  6531. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6532. }
  6533. }
  6534. // Step (2) proper
  6535. SparseArraySegmentBase *temp = nullptr;
  6536. while (startSeg && (startSeg->left + startSeg->length) <= limit)
  6537. {
  6538. temp = startSeg->next;
  6539. // move that entire segment to new array
  6540. startSeg->left = startSeg->left - start;
  6541. startSeg->next = nullptr;
  6542. *prevNewHeadSeg = startSeg;
  6543. prevNewHeadSeg = &startSeg->next;
  6544. // Remove the entire segment from the original array
  6545. *prevSeg = temp;
  6546. startSeg = (SparseArraySegment<T>*)temp;
  6547. }
  6548. // Step(2) above could delete the original head segment entirely, causing current head not
  6549. // starting from 0. Then if any of the following throw, we have a corrupted array. Need
  6550. // protection here.
  6551. bool dummyHeadNodeInserted = false;
  6552. if (!savePrev && (!startSeg || startSeg->left != 0))
  6553. {
  6554. Assert(pArr->head == startSeg);
  6555. pArr->EnsureHeadStartsFromZero<T>(recycler);
  6556. Assert(pArr->head && pArr->head->next == startSeg);
  6557. savePrev = pArr->head;
  6558. prevPrevSeg = prevSeg;
  6559. prevSeg = &pArr->head->next;
  6560. dummyHeadNodeInserted = true;
  6561. }
  6562. // Step (3)
  6563. if (startSeg && (startSeg->left < limit))
  6564. {
  6565. // copy the first part of the last segment to be deleted to new array
  6566. uint32 headDeleteLen = start + deleteLen - startSeg->left ;
  6567. newHeadSeg = SparseArraySegment<T>::AllocateSegment(recycler, startSeg->left - start, headDeleteLen, (SparseArraySegmentBase *)nullptr);
  6568. newHeadSeg = SparseArraySegment<T>::CopySegment(recycler, newHeadSeg, startSeg->left - start, startSeg, startSeg->left, headDeleteLen);
  6569. newHeadSeg->next = nullptr;
  6570. *prevNewHeadSeg = newHeadSeg;
  6571. prevNewHeadSeg = &newHeadSeg->next;
  6572. // move the last segment
  6573. MoveArray(startSeg->elements, startSeg->elements + headDeleteLen, startSeg->length - headDeleteLen);
  6574. startSeg->left = startSeg->left + headDeleteLen; // We are moving the left ahead to point to the right index
  6575. startSeg->length = startSeg->length - headDeleteLen;
  6576. startSeg->CheckLengthvsSize();
  6577. startSeg->Truncate(startSeg->left + startSeg->length);
  6578. startSeg->EnsureSizeInBound(); // Just truncated, size might exceed next.left
  6579. }
  6580. if (startSeg && ((startSeg->left - deleteLen + insertLen) == 0) && dummyHeadNodeInserted)
  6581. {
  6582. Assert(start + insertLen == 0);
  6583. // Remove the dummy head node to preserve array consistency.
  6584. pArr->head = startSeg;
  6585. savePrev = nullptr;
  6586. prevSeg = &pArr->head;
  6587. }
  6588. while (startSeg)
  6589. {
  6590. startSeg->left = startSeg->left - deleteLen + insertLen ;
  6591. if (startSeg->next == nullptr)
  6592. {
  6593. startSeg->EnsureSizeInBound();
  6594. }
  6595. startSeg = SparseArraySegment<T>::From(startSeg->next);
  6596. }
  6597. }
  6598. }
  6599. // The size of pnewArr head allocated in above step 1 might exceed next.left concatenated in step 2/3.
  6600. pnewArr->head->EnsureSizeInBound();
  6601. if (savePrev)
  6602. {
  6603. savePrev->EnsureSizeInBound();
  6604. }
  6605. // insert elements
  6606. if (insertLen > 0)
  6607. {
  6608. Assert(!VarIs<JavascriptNativeIntArray>(pArr) && !VarIs<JavascriptNativeFloatArray>(pArr));
  6609. // InsertPhase
  6610. SparseArraySegment<T> *segInsert = nullptr;
  6611. // see if we are just about the right of the previous segment
  6612. Assert(!savePrev || savePrev->left <= start);
  6613. if (savePrev && (start - savePrev->left < savePrev->size))
  6614. {
  6615. segInsert = (SparseArraySegment<T>*)savePrev;
  6616. uint32 spaceLeft = segInsert->size - (start - segInsert->left);
  6617. if(spaceLeft < insertLen)
  6618. {
  6619. SparseArraySegment<T> *oldSegInsert = segInsert;
  6620. bool isInlineSegment = JavascriptArray::IsInlineSegment(segInsert, pArr);
  6621. if (!segInsert->next)
  6622. {
  6623. segInsert = segInsert->GrowByMin(recycler, insertLen - spaceLeft);
  6624. }
  6625. else
  6626. {
  6627. segInsert = segInsert->GrowByMinMax(recycler, insertLen - spaceLeft, segInsert->next->left - segInsert->left - segInsert->size);
  6628. }
  6629. if (isInlineSegment)
  6630. {
  6631. pArr->ClearElements(oldSegInsert, 0);
  6632. }
  6633. }
  6634. *prevPrevSeg = segInsert;
  6635. segInsert->length = start + insertLen - segInsert->left;
  6636. segInsert->CheckLengthvsSize();
  6637. }
  6638. else
  6639. {
  6640. segInsert = SparseArraySegment<T>::AllocateSegment(recycler, start, insertLen, *prevSeg);
  6641. segInsert->next = *prevSeg;
  6642. *prevSeg = segInsert;
  6643. savePrev = segInsert;
  6644. }
  6645. uint32 relativeStart = start - segInsert->left;
  6646. // inserted elements starts at argument 3 of splice(start, deleteNumber, insertelem1, insertelem2, insertelem3, ...);
  6647. CopyArray(segInsert->elements + relativeStart, insertLen,
  6648. reinterpret_cast<const T*>(insertArgs), insertLen);
  6649. }
  6650. }
  6651. Var JavascriptArray::TryArraySplice(JavascriptArray* pArr, uint32 start, uint32 len, uint32 deleteLen,
  6652. Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext)
  6653. {
  6654. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6655. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  6656. Assert(pArr != nullptr);
  6657. RecyclableObject* newObj = nullptr;
  6658. Recycler *recycler = scriptContext->GetRecycler();
  6659. ::Math::RecordOverflowPolicy newLenOverflow;
  6660. uint32 newLen = UInt32Math::Add(len - deleteLen, insertLen, newLenOverflow); // new length of the array after splice
  6661. // If newLen overflowed, take the slower path to do splicing.
  6662. if (newLenOverflow.HasOverflowed())
  6663. {
  6664. pArr = EnsureNonNativeArray(pArr);
  6665. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint64>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6666. }
  6667. // If we have missing values then convert to not native array for now
  6668. // In future, we could support this scenario.
  6669. if (deleteLen == insertLen)
  6670. {
  6671. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, start + deleteLen));
  6672. }
  6673. else if (len)
  6674. {
  6675. JS_REENTRANT(jsReentLock, pArr->FillFromPrototypes(start, len));
  6676. }
  6677. if (insertArgs)
  6678. {
  6679. pArr = EnsureNonNativeArray(pArr);
  6680. }
  6681. bool isIntArray = false;
  6682. bool isFloatArray = false;
  6683. bool isBuiltinArrayCtor = true;
  6684. JavascriptArray *newArr = nullptr;
  6685. // Just dump the segment map on splice (before any possible allocation and throw)
  6686. pArr->ClearSegmentMap();
  6687. // If the source object is an Array exotic object (Array.isArray) we should try to load the constructor property
  6688. // and use it to construct the return object.
  6689. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(pArr, deleteLen, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  6690. if (newObj != nullptr)
  6691. {
  6692. pArr = EnsureNonNativeArray(pArr);
  6693. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  6694. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  6695. if (newArr)
  6696. {
  6697. #if ENABLE_COPYONACCESS_ARRAY
  6698. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6699. #endif
  6700. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  6701. }
  6702. }
  6703. else
  6704. // This is the ES5 case, pArr['constructor'] doesn't exist, or pArr['constructor'] is the builtin Array constructor
  6705. {
  6706. pArr->GetArrayTypeAndConvert(&isIntArray, &isFloatArray);
  6707. newArr = CreateNewArrayHelper(deleteLen, isIntArray, isFloatArray, pArr, scriptContext);
  6708. #if ENABLE_COPYONACCESS_ARRAY
  6709. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  6710. #endif
  6711. }
  6712. // If return object is a JavascriptArray, we can use all the array splice helpers
  6713. if (newArr && isBuiltinArrayCtor && len == pArr->length)
  6714. {
  6715. // Code below has potential to throw due to OOM or SO. Just FailFast on those cases
  6716. AutoDisableInterrupt failFastOnError(scriptContext->GetThreadContext());
  6717. // Array has a single segment (need not start at 0) and splice start lies in the range
  6718. // of that segment we optimize splice - Fast path.
  6719. if (pArr->IsSingleSegmentArray() && pArr->head->HasIndex(start))
  6720. {
  6721. SparseArraySegmentBase *oldHead = pArr->head;
  6722. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  6723. if (isIntArray)
  6724. {
  6725. ArraySegmentSpliceHelper<int32>(newArr,
  6726. SparseArraySegment<int32>::From(pArr->head),
  6727. SparseArraySegment<int32>::AddressFrom(&pArr->head),
  6728. start, deleteLen, insertArgs, insertLen, recycler);
  6729. }
  6730. else if (isFloatArray)
  6731. {
  6732. ArraySegmentSpliceHelper<double>(newArr,
  6733. SparseArraySegment<double>::From(pArr->head),
  6734. SparseArraySegment<double>::AddressFrom(&pArr->head),
  6735. start, deleteLen, insertArgs, insertLen, recycler);
  6736. }
  6737. else
  6738. {
  6739. ArraySegmentSpliceHelper<Var>(newArr,
  6740. SparseArraySegment<Var>::From(pArr->head),
  6741. SparseArraySegment<Var>::AddressFrom(&pArr->head),
  6742. start, deleteLen, insertArgs, insertLen, recycler);
  6743. }
  6744. if (isInlineSegment && oldHead != pArr->head)
  6745. {
  6746. pArr->ClearElements(oldHead, 0);
  6747. }
  6748. // Since the start index is within the bounds of the original array's head segment, it will not acquire any new
  6749. // missing values. If the original array had missing values in the head segment, some of them may have been
  6750. // copied into the array that will be returned; otherwise, the array that is returned will also not have any
  6751. // missing values.
  6752. newArr->SetHasNoMissingValues(pArr->HasNoMissingValues());
  6753. }
  6754. else
  6755. {
  6756. if (isIntArray)
  6757. {
  6758. ArraySpliceHelper<int32>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6759. }
  6760. else if (isFloatArray)
  6761. {
  6762. ArraySpliceHelper<double>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6763. }
  6764. else
  6765. {
  6766. ArraySpliceHelper<Var>(newArr, pArr, start, deleteLen, insertArgs, insertLen, scriptContext);
  6767. }
  6768. // This function currently does not track missing values in the head segment if there are multiple segments
  6769. pArr->SetHasNoMissingValues(false);
  6770. newArr->SetHasNoMissingValues(false);
  6771. }
  6772. if (isIntArray)
  6773. {
  6774. pArr->EnsureHeadStartsFromZero<int32>(recycler);
  6775. newArr->EnsureHeadStartsFromZero<int32>(recycler);
  6776. }
  6777. else if (isFloatArray)
  6778. {
  6779. pArr->EnsureHeadStartsFromZero<double>(recycler);
  6780. newArr->EnsureHeadStartsFromZero<double>(recycler);
  6781. }
  6782. else
  6783. {
  6784. pArr->EnsureHeadStartsFromZero<Var>(recycler);
  6785. newArr->EnsureHeadStartsFromZero<Var>(recycler);
  6786. }
  6787. pArr->InvalidateLastUsedSegment();
  6788. pArr->ClearSegmentMap();
  6789. // it is possible for valueOf accessors for the start or deleteLen
  6790. // arguments to modify the size of the array. Since the resulting size of the array
  6791. // is based on the cached value of length, this might lead to us having to trim
  6792. // excess array segments at the end of the splice operation, which SetLength() will do.
  6793. // However, this is also slower than performing the simple length assignment, so we only
  6794. // do it if we can detect the array length changing.
  6795. if (pArr->length != len)
  6796. {
  6797. pArr->SetLength(newLen);
  6798. }
  6799. else
  6800. {
  6801. pArr->length = newLen;
  6802. }
  6803. if (newArr->length != deleteLen)
  6804. {
  6805. newArr->SetLength(deleteLen);
  6806. }
  6807. else
  6808. {
  6809. newArr->length = deleteLen;
  6810. }
  6811. failFastOnError.Completed();
  6812. newArr->InvalidateLastUsedSegment();
  6813. newArr->ClearSegmentMap();
  6814. #ifdef VALIDATE_ARRAY
  6815. newArr->ValidateArray();
  6816. pArr->ValidateArray();
  6817. #endif
  6818. return newArr;
  6819. }
  6820. JS_REENTRANT_UNLOCK(jsReentLock, return ObjectSpliceHelper<uint32>(pArr, len, start, deleteLen, insertArgs, insertLen, scriptContext, newObj));
  6821. }
  6822. template<typename T>
  6823. RecyclableObject* JavascriptArray::ObjectSpliceHelper(RecyclableObject* pObj, T len, T start,
  6824. T deleteLen, Var* insertArgs, uint32 insertLen, ScriptContext *scriptContext, RecyclableObject* pNewObj)
  6825. {
  6826. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6827. SETOBJECT_FOR_MUTATION(jsReentLock, pObj);
  6828. JavascriptArray *pnewArr = nullptr;
  6829. if (pNewObj == nullptr)
  6830. {
  6831. JS_REENTRANT_NO_MUTATE(jsReentLock, pNewObj = ArraySpeciesCreate(pObj, deleteLen, scriptContext));
  6832. if (pNewObj == nullptr)
  6833. {
  6834. if (deleteLen > UINT_MAX)
  6835. {
  6836. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  6837. }
  6838. pnewArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(deleteLen));
  6839. pnewArr->EnsureHead<Var>();
  6840. pNewObj = pnewArr;
  6841. }
  6842. }
  6843. pnewArr = JavascriptArray::TryVarToNonES5Array(pNewObj);
  6844. if (pnewArr)
  6845. {
  6846. #if ENABLE_COPYONACCESS_ARRAY
  6847. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(pnewArr);
  6848. #endif
  6849. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, pnewArr);
  6850. }
  6851. // copy elements to delete to new array
  6852. if (pnewArr != nullptr)
  6853. {
  6854. for (uint32 i = 0; i < deleteLen; i++)
  6855. {
  6856. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6857. if (hasItem)
  6858. {
  6859. JS_REENTRANT(jsReentLock, Var element = JavascriptOperators::GetItem(pObj, start + i, scriptContext));
  6860. pnewArr->SetItem(i, element, PropertyOperation_None);
  6861. }
  6862. }
  6863. }
  6864. else
  6865. {
  6866. BigIndex k = 0u;
  6867. for (T i = 0u; i < deleteLen; i++)
  6868. {
  6869. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, start + i));
  6870. if (hasItem)
  6871. {
  6872. Var element = nullptr;
  6873. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, start + i, scriptContext),
  6874. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(pNewObj, k, element), scriptContext, k));
  6875. }
  6876. ++k;
  6877. }
  6878. }
  6879. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.splice"));
  6880. // Now we need reserve room if it is necessary
  6881. if (insertLen > deleteLen) // Might overflow max array length
  6882. {
  6883. // Unshift [start + deleteLen, len) to start + insertLen
  6884. JS_REENTRANT(jsReentLock, Unshift<BigIndex, T>(pObj, start + insertLen, start + deleteLen, len, scriptContext));
  6885. }
  6886. else if (insertLen < deleteLen) // Won't overflow max array length
  6887. {
  6888. T j = 0;
  6889. for (T i = start + deleteLen; i < len; i++)
  6890. {
  6891. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(pObj, i));
  6892. if (hasItem)
  6893. {
  6894. Var element = nullptr;
  6895. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(pObj, i, scriptContext),
  6896. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetItem(pObj, pObj, start + insertLen + j, element, scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6897. }
  6898. else
  6899. {
  6900. JS_REENTRANT(jsReentLock,
  6901. h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, start + insertLen + j, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6902. }
  6903. j++;
  6904. }
  6905. // Clean up the rest
  6906. for (T i = len; i > len - deleteLen + insertLen; i--)
  6907. {
  6908. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(JavascriptOperators::DeleteItem(pObj, i - 1, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6909. }
  6910. }
  6911. if (insertLen > 0)
  6912. {
  6913. T dstIndex = start; // insert index might overflow max array length
  6914. for (uint32 i = 0; i < insertLen; i++)
  6915. {
  6916. JS_REENTRANT(jsReentLock,
  6917. h.ThrowTypeErrorOnFailure(IndexTrace<BigIndex>::SetItem(pObj, dstIndex, insertArgs[i], PropertyOperation_ThrowIfNotExtensible)));
  6918. ++dstIndex;
  6919. }
  6920. }
  6921. // Set up new length
  6922. T newLen = T(len - deleteLen) + insertLen;
  6923. JS_REENTRANT(jsReentLock,
  6924. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pObj, pObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(newLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)),
  6925. h.ThrowTypeErrorOnFailure(JavascriptOperators::SetProperty(pNewObj, pNewObj, PropertyIds::length, IndexTrace<BigIndex>::ToNumber(deleteLen, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible)));
  6926. #ifdef VALIDATE_ARRAY
  6927. if (pnewArr)
  6928. {
  6929. pnewArr->ValidateArray();
  6930. }
  6931. #endif
  6932. return pNewObj;
  6933. }
  6934. Var JavascriptArray::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  6935. {
  6936. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  6937. ARGUMENTS(args, callInfo);
  6938. ScriptContext* scriptContext = function->GetScriptContext();
  6939. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6940. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  6941. Assert(!(callInfo.Flags & CallFlags_New));
  6942. if (args.Info.Count == 0)
  6943. {
  6944. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedObject, _u("Array.prototype.toLocaleString"));
  6945. }
  6946. if (JavascriptArray::IsDirectAccessArray(args[0]))
  6947. {
  6948. JavascriptArray* arr = UnsafeVarTo<JavascriptArray>(args[0]);
  6949. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(arr, scriptContext));
  6950. }
  6951. else
  6952. {
  6953. if (TypedArrayBase::IsDetachedTypedArray(args[0]))
  6954. {
  6955. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("Array.prototype.toLocalString"));
  6956. }
  6957. RecyclableObject* obj = nullptr;
  6958. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  6959. {
  6960. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toLocaleString"));
  6961. }
  6962. JS_REENTRANT_UNLOCK(jsReentLock, return ToLocaleString(obj, scriptContext));
  6963. }
  6964. }
  6965. //
  6966. // Unshift object elements [start, end) to toIndex, asserting toIndex > start.
  6967. //
  6968. template<typename T, typename P>
  6969. void JavascriptArray::Unshift(RecyclableObject* obj, const T& toIndex, P start, P end, ScriptContext* scriptContext)
  6970. {
  6971. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  6972. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  6973. typedef IndexTrace<T> index_trace;
  6974. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  6975. if (start < end)
  6976. {
  6977. T newEnd = (end - start - 1);// newEnd - 1
  6978. T dst = toIndex + newEnd;
  6979. for (P i = end; i > start; --i)
  6980. {
  6981. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, i - 1));
  6982. if (hasItem)
  6983. {
  6984. Var element = nullptr;
  6985. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, i - 1, scriptContext),
  6986. h.ThrowTypeErrorOnFailure(index_trace::SetItem(obj, dst, element, PropertyOperation_ThrowIfNotExtensible)));
  6987. }
  6988. else
  6989. {
  6990. JS_REENTRANT(jsReentLock, h.ThrowTypeErrorOnFailure(index_trace::DeleteItem(obj, dst, PropertyOperation_ThrowOnDeleteIfNotConfig)));
  6991. }
  6992. --dst;
  6993. }
  6994. }
  6995. }
  6996. template<typename T>
  6997. void JavascriptArray::GrowArrayHeadHelperForUnshift(JavascriptArray* pArr, uint32 unshiftElements, ScriptContext * scriptContext)
  6998. {
  6999. SparseArraySegmentBase* nextToHeadSeg = pArr->head->next;
  7000. Recycler* recycler = scriptContext->GetRecycler();
  7001. SparseArraySegmentBase *oldHead = pArr->head;
  7002. bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, pArr);
  7003. if (nextToHeadSeg == nullptr)
  7004. {
  7005. pArr->EnsureHead<T>();
  7006. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMin(recycler, unshiftElements);
  7007. }
  7008. else
  7009. {
  7010. pArr->head = SparseArraySegment<T>::From(pArr->head)->GrowByMinMax(recycler, unshiftElements, ((nextToHeadSeg->left + unshiftElements) - pArr->head->left - pArr->head->size));
  7011. }
  7012. if (isInlineSegment)
  7013. {
  7014. pArr->ClearElements(oldHead, 0);
  7015. }
  7016. }
  7017. template<typename T>
  7018. void JavascriptArray::UnshiftHelper(JavascriptArray* pArr, uint32 unshiftElements, Js::Var * elements)
  7019. {
  7020. SparseArraySegment<T>* head = SparseArraySegment<T>::From(pArr->head);
  7021. // Make enough room in the head segment to insert new elements at the front
  7022. MoveArray(head->elements + unshiftElements, head->elements, pArr->head->length);
  7023. uint32 oldHeadLength = head->length;
  7024. head->length += unshiftElements;
  7025. head->CheckLengthvsSize();
  7026. /* Set head segment as the last used segment */
  7027. pArr->InvalidateLastUsedSegment();
  7028. bool hasNoMissingValues = pArr->HasNoMissingValues();
  7029. /* Set HasNoMissingValues to false -> Since we shifted elements right, we might have missing values after the memmove */
  7030. if(unshiftElements > oldHeadLength)
  7031. {
  7032. pArr->SetHasNoMissingValues(false);
  7033. }
  7034. #if ENABLE_PROFILE_INFO
  7035. pArr->FillFromArgs(unshiftElements, 0, elements, nullptr, true/*dontCreateNewArray*/);
  7036. #else
  7037. pArr->FillFromArgs(unshiftElements, 0, elements, true/*dontCreateNewArray*/);
  7038. #endif
  7039. // Setting back to the old value
  7040. pArr->SetHasNoMissingValues(hasNoMissingValues);
  7041. }
  7042. Var JavascriptArray::UnshiftObjectHelper(Js::Arguments& args, ScriptContext * scriptContext)
  7043. {
  7044. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7045. Assert(args.Info.Count >= 1);
  7046. RecyclableObject* dynamicObject = nullptr;
  7047. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  7048. {
  7049. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.unshift"));
  7050. }
  7051. uint32 unshiftElements = args.Info.Count - 1;
  7052. JS_REENTRANT(jsReentLock, BigIndex length = OP_GetLength(dynamicObject, scriptContext));
  7053. if (unshiftElements > 0)
  7054. {
  7055. uint32 MaxSpaceUint32 = MaxArrayLength - unshiftElements;
  7056. // Note: end will always be a smallIndex either it is less than length in which case it is MaxSpaceUint32
  7057. // or MaxSpaceUint32 is greater than length meaning length is a uint32 number
  7058. BigIndex end = length > MaxSpaceUint32 ? MaxSpaceUint32 : length;
  7059. if (end < length)
  7060. {
  7061. // Unshift [end, length) to MaxArrayLength
  7062. // MaxArrayLength + (length - MaxSpaceUint32 - 1) = length + unshiftElements -1
  7063. if (length.IsSmallIndex())
  7064. {
  7065. JS_REENTRANT(jsReentLock, Unshift<BigIndex>(dynamicObject, MaxArrayLength, end.GetSmallIndex(), length.GetSmallIndex(), scriptContext));
  7066. }
  7067. else
  7068. {
  7069. JS_REENTRANT(jsReentLock, Unshift<BigIndex, uint64>(dynamicObject, MaxArrayLength, (uint64)end.GetSmallIndex(), length.GetBigIndex(), scriptContext));
  7070. }
  7071. }
  7072. // Unshift [0, end) to unshiftElements
  7073. // unshiftElements + (MaxSpaceUint32 - 0 - 1) = MaxArrayLength -1 therefore this unshift covers up to MaxArrayLength - 1
  7074. JS_REENTRANT(jsReentLock, Unshift<uint32>(dynamicObject, unshiftElements, (uint32)0, end.GetSmallIndex(), scriptContext));
  7075. for (uint32 i = 0; i < unshiftElements; i++)
  7076. {
  7077. JS_REENTRANT(jsReentLock,
  7078. JavascriptOperators::SetItem(dynamicObject, dynamicObject, i, args[i + 1], scriptContext, PropertyOperation_ThrowIfNotExtensible, true));
  7079. }
  7080. }
  7081. ThrowTypeErrorOnFailureHelper h(scriptContext, _u("Array.prototype.unshift"));
  7082. //ES6 - update 'length' even if unshiftElements == 0;
  7083. BigIndex newLen = length + unshiftElements;
  7084. Var res = JavascriptNumber::ToVar(newLen.IsSmallIndex() ? newLen.GetSmallIndex() : newLen.GetBigIndex(), scriptContext);
  7085. JS_REENTRANT(jsReentLock,
  7086. BOOL setLength = JavascriptOperators::SetProperty(dynamicObject, dynamicObject, PropertyIds::length, res, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  7087. h.ThrowTypeErrorOnFailure(setLength);
  7088. return res;
  7089. }
  7090. Var JavascriptArray::EntryUnshift(RecyclableObject* function, CallInfo callInfo, ...)
  7091. {
  7092. JIT_HELPER_REENTRANT_HEADER(Array_Unshift);
  7093. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7094. ARGUMENTS(args, callInfo);
  7095. ScriptContext* scriptContext = function->GetScriptContext();
  7096. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7097. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  7098. Assert(!(callInfo.Flags & CallFlags_New));
  7099. Var res = scriptContext->GetLibrary()->GetUndefined();
  7100. if (args.Info.Count == 0)
  7101. {
  7102. return res;
  7103. }
  7104. JavascriptArray * pArr = nullptr;
  7105. if (JavascriptArray::IsNonES5Array(args[0])
  7106. && !VarTo<JavascriptArray>(args[0])->IsCrossSiteObject())
  7107. {
  7108. #if ENABLE_COPYONACCESS_ARRAY
  7109. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  7110. #endif
  7111. pArr = VarTo<JavascriptArray>(args[0]);
  7112. }
  7113. uint32 unshiftElements = args.Info.Count - 1;
  7114. // forceCheckProtoChain - since the array expand to accommodate new items thus we have to check if we have accessor on the proto chain.
  7115. bool useNoSideEffectUnshift = pArr != nullptr && (unshiftElements == 0 || !HasAnyES5ArrayInPrototypeChain(pArr, true /*forceCheckProtoChain*/));
  7116. if (useNoSideEffectUnshift)
  7117. {
  7118. if (unshiftElements > 0)
  7119. {
  7120. uint32 length = pArr->length;
  7121. if (pArr->IsFillFromPrototypes())
  7122. {
  7123. pArr->FillFromPrototypes(0, pArr->length); // We need find all missing value from [[proto]] object
  7124. }
  7125. // As we have already established that the FillFromPrototype should not change the bound of the array.
  7126. if (length != pArr->length)
  7127. {
  7128. Js::Throw::FatalInternalError();
  7129. }
  7130. // Pre-process: truncate overflowing elements to properties
  7131. bool newLenOverflowed = false;
  7132. uint32 maxLen = MaxArrayLength - unshiftElements;
  7133. if (pArr->length > maxLen)
  7134. {
  7135. newLenOverflowed = true;
  7136. // Ensure the array is non-native when overflow happens
  7137. EnsureNonNativeArray(pArr);
  7138. JS_REENTRANT(jsReentLock, pArr->TruncateToProperties(MaxArrayLength, maxLen));
  7139. Assert(pArr->length + unshiftElements == MaxArrayLength);
  7140. if (VarIs<ES5Array>(pArr))
  7141. {
  7142. JS_REENTRANT_UNLOCK(jsReentLock, return UnshiftObjectHelper(args, scriptContext));
  7143. }
  7144. }
  7145. pArr->ClearSegmentMap(); // Dump segmentMap on unshift (before any possible allocation and throw)
  7146. Assert(pArr->length <= MaxArrayLength - unshiftElements);
  7147. bool isIntArray = false;
  7148. bool isFloatArray = false;
  7149. if (VarIs<JavascriptNativeIntArray>(pArr))
  7150. {
  7151. isIntArray = true;
  7152. }
  7153. else if (VarIs<JavascriptNativeFloatArray>(pArr))
  7154. {
  7155. isFloatArray = true;
  7156. }
  7157. // If we need to grow head segment and there is already a next segment, then allocate the new head segment upfront
  7158. // If there is OOM in array allocation, then array consistency is maintained.
  7159. if (pArr->head->size < pArr->head->length + unshiftElements)
  7160. {
  7161. if (isIntArray)
  7162. {
  7163. GrowArrayHeadHelperForUnshift<int32>(pArr, unshiftElements, scriptContext);
  7164. }
  7165. else if (isFloatArray)
  7166. {
  7167. GrowArrayHeadHelperForUnshift<double>(pArr, unshiftElements, scriptContext);
  7168. }
  7169. else
  7170. {
  7171. GrowArrayHeadHelperForUnshift<Var>(pArr, unshiftElements, scriptContext);
  7172. }
  7173. }
  7174. SparseArraySegmentBase* renumberSeg = pArr->head->next;
  7175. while (renumberSeg)
  7176. {
  7177. renumberSeg->left += unshiftElements;
  7178. if (renumberSeg->next == nullptr)
  7179. {
  7180. // last segment can shift its left + size beyond MaxArrayLength, so truncate if so
  7181. renumberSeg->EnsureSizeInBound();
  7182. }
  7183. renumberSeg = renumberSeg->next;
  7184. }
  7185. try
  7186. {
  7187. if (isIntArray)
  7188. {
  7189. UnshiftHelper<int32>(pArr, unshiftElements, args.Values);
  7190. }
  7191. else if (isFloatArray)
  7192. {
  7193. UnshiftHelper<double>(pArr, unshiftElements, args.Values);
  7194. }
  7195. else
  7196. {
  7197. UnshiftHelper<Var>(pArr, unshiftElements, args.Values);
  7198. }
  7199. }
  7200. catch (...)
  7201. {
  7202. Js::Throw::FatalInternalError();
  7203. }
  7204. pArr->InvalidateLastUsedSegment();
  7205. pArr->length += unshiftElements;
  7206. pArr->ClearSegmentMap();
  7207. #ifdef VALIDATE_ARRAY
  7208. pArr->ValidateArray();
  7209. #endif
  7210. if (newLenOverflowed) // ES5: throw if new "length" exceeds max array length
  7211. {
  7212. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect);
  7213. }
  7214. }
  7215. res = JavascriptNumber::ToVar(pArr->length, scriptContext);
  7216. }
  7217. else
  7218. {
  7219. JS_REENTRANT_UNLOCK(jsReentLock, res = UnshiftObjectHelper(args, scriptContext));
  7220. }
  7221. return res;
  7222. JIT_HELPER_END(Array_Unshift);
  7223. }
  7224. Var JavascriptArray::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  7225. {
  7226. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7227. ARGUMENTS(args, callInfo);
  7228. ScriptContext* scriptContext = function->GetScriptContext();
  7229. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7230. Assert(!(callInfo.Flags & CallFlags_New));
  7231. if (args.Info.Count == 0)
  7232. {
  7233. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject);
  7234. }
  7235. // ES5 15.4.4.2: call join, or built-in Object.prototype.toString
  7236. RecyclableObject* obj = nullptr;
  7237. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  7238. {
  7239. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.toString"));
  7240. }
  7241. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7242. // In ES5 we could be calling a user defined join, even on array. We must [[Get]] join at runtime.
  7243. JS_REENTRANT(jsReentLock, Var join = JavascriptOperators::GetPropertyNoCache(obj, PropertyIds::join, scriptContext));
  7244. if (JavascriptConversion::IsCallable(join))
  7245. {
  7246. RecyclableObject* func = VarTo<RecyclableObject>(join);
  7247. // We need to record implicit call here, because marked the Array.toString as no side effect,
  7248. // but if we call user code here which may have side effect
  7249. ThreadContext * threadContext = scriptContext->GetThreadContext();
  7250. JS_REENTRANT(jsReentLock,
  7251. Var result = threadContext->ExecuteImplicitCall(func, ImplicitCall_ToPrimitive, [=]() -> Js::Var
  7252. {
  7253. // Stack object should have a pre-op bail on implicit call. We shouldn't see them here.
  7254. Assert(!ThreadContext::IsOnStack(obj));
  7255. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7256. CallFlags flags = CallFlags_Value;
  7257. return CALL_FUNCTION(threadContext, func, CallInfo(flags, 1), obj);
  7258. }));
  7259. if(!result)
  7260. {
  7261. // There was an implicit call and implicit calls are disabled. This would typically cause a bailout.
  7262. Assert(threadContext->IsDisableImplicitCall());
  7263. result = scriptContext->GetLibrary()->GetNull();
  7264. }
  7265. return result;
  7266. }
  7267. else
  7268. {
  7269. JS_REENTRANT_UNLOCK(jsReentLock,
  7270. // If we're working with a HostDispatch object, we may have re-entrancy. Otherwise, it should be safe.
  7271. if (obj->GetTypeId() == TypeIds_HostDispatch)
  7272. {
  7273. return scriptContext->GetThreadContext()->ExecuteImplicitCall(scriptContext->GetLibrary()->GetObjectToStringFunction(), Js::ImplicitCall_External, [=]()->Js::Var
  7274. {
  7275. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj);
  7276. });
  7277. }
  7278. else
  7279. {
  7280. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext()) {
  7281. // call built-in Object.prototype.toString
  7282. return CALL_ENTRYPOINT(scriptContext->GetThreadContext(), JavascriptObject::EntryToString, function, CallInfo(1), obj);
  7283. } END_SAFE_REENTRANT_CALL
  7284. }
  7285. );
  7286. }
  7287. }
  7288. #if DEBUG
  7289. BOOL JavascriptArray::GetIndex(const char16* propName, uint32 *pIndex)
  7290. {
  7291. uint32 lu, luDig;
  7292. int32 cch = (int32)wcslen(propName);
  7293. char16* pch = const_cast<char16 *>(propName);
  7294. lu = *pch - '0';
  7295. if (lu > 9)
  7296. return FALSE;
  7297. if (0 == lu)
  7298. {
  7299. *pIndex = 0;
  7300. return 1 == cch;
  7301. }
  7302. while ((luDig = *++pch - '0') < 10)
  7303. {
  7304. // If we overflow 32 bits, ignore the item
  7305. if (lu > 0x19999999)
  7306. return FALSE;
  7307. lu *= 10;
  7308. if(lu > (ULONG_MAX - luDig))
  7309. return FALSE;
  7310. lu += luDig;
  7311. }
  7312. if (pch - propName != cch)
  7313. return FALSE;
  7314. if (lu == JavascriptArray::InvalidIndex)
  7315. {
  7316. // 0xFFFFFFFF is not treated as an array index so that the length can be
  7317. // capped at 32 bits.
  7318. return FALSE;
  7319. }
  7320. *pIndex = lu;
  7321. return TRUE;
  7322. }
  7323. #endif
  7324. template <typename T>
  7325. JavascriptString* JavascriptArray::ToLocaleString(T* arr, ScriptContext* scriptContext)
  7326. {
  7327. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7328. SETOBJECT_FOR_MUTATION(jsReentLock, arr);
  7329. uint32 length = 0;
  7330. TypedArrayBase * typedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(static_cast<RecyclableObject*>(arr));
  7331. if (typedArray)
  7332. {
  7333. // For a TypedArray use the actual length of the array.
  7334. length = typedArray->GetLength();
  7335. }
  7336. else
  7337. {
  7338. //For anything else, use the "length" property if present.
  7339. JS_REENTRANT(jsReentLock, length = ItemTrace<T>::GetLength(arr, scriptContext));
  7340. }
  7341. if (length == 0 || scriptContext->CheckObject(arr))
  7342. {
  7343. return scriptContext->GetLibrary()->GetEmptyString();
  7344. }
  7345. JavascriptString* res = scriptContext->GetLibrary()->GetEmptyString();
  7346. bool pushedObject = false;
  7347. TryFinally([&]()
  7348. {
  7349. scriptContext->PushObject(arr);
  7350. pushedObject = true;
  7351. Var element;
  7352. JS_REENTRANT(jsReentLock, BOOL gotItem = ItemTrace<T>::GetItem(arr, 0, &element, scriptContext));
  7353. if (gotItem)
  7354. {
  7355. JS_REENTRANT(jsReentLock, res = JavascriptArray::ToLocaleStringHelper(element, scriptContext));
  7356. }
  7357. if (length > 1)
  7358. {
  7359. uint32 sepSize = 0;
  7360. char16 szSeparator[Arrays::SeparatorBufferSize];
  7361. bool hasLocaleSeparator = Arrays::GetLocaleSeparator(szSeparator, &sepSize, Arrays::SeparatorBufferSize);
  7362. JavascriptString* separator = nullptr;
  7363. if (hasLocaleSeparator)
  7364. {
  7365. separator = JavascriptString::NewCopyBuffer(szSeparator, static_cast<charcount_t>(sepSize), scriptContext);
  7366. }
  7367. else
  7368. {
  7369. separator = scriptContext->GetLibrary()->GetCommaSpaceDisplayString();
  7370. }
  7371. for (uint32 i = 1; i < length; i++)
  7372. {
  7373. res = JavascriptString::Concat(res, separator);
  7374. JS_REENTRANT(jsReentLock, gotItem = ItemTrace<T>::GetItem(arr, i, &element, scriptContext));
  7375. if (gotItem)
  7376. {
  7377. JS_REENTRANT(jsReentLock, res = JavascriptString::Concat(res, JavascriptArray::ToLocaleStringHelper(element, scriptContext)));
  7378. }
  7379. }
  7380. }
  7381. },
  7382. [&](bool/*hasException*/)
  7383. {
  7384. if (pushedObject)
  7385. {
  7386. Var top = scriptContext->PopObject();
  7387. AssertMsg(top == arr, "Unmatched operation stack");
  7388. }
  7389. });
  7390. if (res == nullptr)
  7391. {
  7392. res = scriptContext->GetLibrary()->GetEmptyString();
  7393. }
  7394. return res;
  7395. }
  7396. Var JavascriptArray::EntryIsArray(RecyclableObject* function, CallInfo callInfo, ...)
  7397. {
  7398. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7399. ARGUMENTS(args, callInfo);
  7400. ScriptContext* scriptContext = function->GetScriptContext();
  7401. JIT_HELPER_REENTRANT_HEADER(Array_IsArray);
  7402. Assert(!(callInfo.Flags & CallFlags_New));
  7403. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Constructor_isArray);
  7404. if (args.Info.Count < 2)
  7405. {
  7406. return scriptContext->GetLibrary()->GetFalse();
  7407. }
  7408. #if ENABLE_COPYONACCESS_ARRAY
  7409. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  7410. #endif
  7411. if (JavascriptOperators::IsArray(args[1]))
  7412. {
  7413. return scriptContext->GetLibrary()->GetTrue();
  7414. }
  7415. return scriptContext->GetLibrary()->GetFalse();
  7416. JIT_HELPER_END(Array_IsArray);
  7417. }
  7418. ///----------------------------------------------------------------------------
  7419. /// Find() calls the given predicate callback on each element of the array, in
  7420. /// order, and returns the first element that makes the predicate return true,
  7421. /// as described in (ES6.0: S22.1.3.8).
  7422. ///----------------------------------------------------------------------------
  7423. Var JavascriptArray::EntryFind(RecyclableObject* function, CallInfo callInfo, ...)
  7424. {
  7425. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7426. ARGUMENTS(args, callInfo);
  7427. ScriptContext* scriptContext = function->GetScriptContext();
  7428. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7429. Assert(!(callInfo.Flags & CallFlags_New));
  7430. if (args.Info.Count == 0)
  7431. {
  7432. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.find"));
  7433. }
  7434. int64 length;
  7435. JavascriptArray * pArr = nullptr;
  7436. RecyclableObject* obj = nullptr;
  7437. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.find"), &pArr, &obj, &length));
  7438. return JavascriptArray::FindHelper<false>(pArr, nullptr, obj, length, args, scriptContext);
  7439. }
  7440. template <bool findIndex>
  7441. Var JavascriptArray::FindHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  7442. {
  7443. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7444. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7445. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7446. {
  7447. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7448. if (typedArrayBase != nullptr)
  7449. {
  7450. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("[TypedArray].prototype.findIndex") : _u("[TypedArray].prototype.find"));
  7451. }
  7452. else
  7453. {
  7454. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, findIndex ? _u("Array.prototype.findIndex") : _u("Array.prototype.find"));
  7455. }
  7456. }
  7457. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  7458. Var thisArg;
  7459. if (args.Info.Count > 2)
  7460. {
  7461. thisArg = args[2];
  7462. }
  7463. else
  7464. {
  7465. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7466. }
  7467. // If we came from Array.prototype.find/findIndex and source object is not a JavascriptArray, source could be a TypedArray
  7468. if (typedArrayBase == nullptr && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  7469. {
  7470. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  7471. }
  7472. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7473. CallFlags flags = CallFlags_Value;
  7474. Var element = nullptr;
  7475. Var testResult = nullptr;
  7476. if (pArr)
  7477. {
  7478. Var undefined = scriptContext->GetLibrary()->GetUndefined();
  7479. Assert(length <= UINT_MAX);
  7480. for (uint32 k = 0; k < (uint32)length; k++)
  7481. {
  7482. element = undefined;
  7483. JS_REENTRANT(jsReentLock, pArr->DirectGetItemAtFull(k, &element));
  7484. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7485. JS_REENTRANT(jsReentLock,
  7486. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7487. {
  7488. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7489. element,
  7490. index,
  7491. pArr);
  7492. }
  7493. END_SAFE_REENTRANT_CALL
  7494. );
  7495. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7496. {
  7497. return findIndex ? index : element;
  7498. }
  7499. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  7500. // we will process the rest of the array elements like an ES5Array.
  7501. if (!JavascriptArray::IsNonES5Array(obj))
  7502. {
  7503. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  7504. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, k + 1, callBackFn, thisArg, scriptContext));
  7505. }
  7506. }
  7507. }
  7508. else if (typedArrayBase)
  7509. {
  7510. Assert(length <= UINT_MAX);
  7511. for (uint32 k = 0; k < (uint32)length; k++)
  7512. {
  7513. // Spec does not ask to call HasItem, so we need to go to visit the whole length
  7514. element = typedArrayBase->DirectGetItem(k);
  7515. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7516. JS_REENTRANT(jsReentLock,
  7517. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7518. {
  7519. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7520. element,
  7521. index,
  7522. typedArrayBase);
  7523. }
  7524. END_SAFE_REENTRANT_CALL
  7525. );
  7526. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7527. {
  7528. return findIndex ? index : element;
  7529. }
  7530. }
  7531. }
  7532. else
  7533. {
  7534. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FindObjectHelper<findIndex>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7535. }
  7536. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7537. }
  7538. template <bool findIndex>
  7539. Var JavascriptArray::FindObjectHelper(RecyclableObject* obj, int64 length, int64 start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7540. {
  7541. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7542. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7543. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7544. CallFlags flags = CallFlags_Value;
  7545. Var element = nullptr;
  7546. Var testResult = nullptr;
  7547. for (int64 k = start; k < length; k++)
  7548. {
  7549. JS_REENTRANT(jsReentLock, element = JavascriptOperators::GetItem(obj, (uint64)k, scriptContext));
  7550. Var index = JavascriptNumber::ToVar(k, scriptContext);
  7551. JS_REENTRANT(jsReentLock,
  7552. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7553. {
  7554. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7555. element,
  7556. index,
  7557. obj);
  7558. }
  7559. END_SAFE_REENTRANT_CALL
  7560. );
  7561. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7562. {
  7563. return findIndex ? index : element;
  7564. }
  7565. }
  7566. return findIndex ? JavascriptNumber::ToVar(-1, scriptContext) : scriptContext->GetLibrary()->GetUndefined();
  7567. }
  7568. ///----------------------------------------------------------------------------
  7569. /// FindIndex() calls the given predicate callback on each element of the
  7570. /// array, in order, and returns the index of the first element that makes the
  7571. /// predicate return true, as described in (ES6.0: S22.1.3.9).
  7572. ///----------------------------------------------------------------------------
  7573. Var JavascriptArray::EntryFindIndex(RecyclableObject* function, CallInfo callInfo, ...)
  7574. {
  7575. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7576. ARGUMENTS(args, callInfo);
  7577. ScriptContext* scriptContext = function->GetScriptContext();
  7578. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7579. Assert(!(callInfo.Flags & CallFlags_New));
  7580. if (args.Info.Count == 0)
  7581. {
  7582. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.findIndex"));
  7583. }
  7584. int64 length;
  7585. JavascriptArray * pArr = nullptr;
  7586. RecyclableObject* obj = nullptr;
  7587. JS_REENTRANT_UNLOCK(jsReentLock,
  7588. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.findIndex"), &pArr, &obj, &length));
  7589. return JavascriptArray::FindHelper<true>(pArr, nullptr, obj, length, args, scriptContext);
  7590. }
  7591. ///----------------------------------------------------------------------------
  7592. /// Entries() returns a new ArrayIterator object configured to return key-
  7593. /// value pairs matching the elements of the this array/array-like object,
  7594. /// as described in (ES6.0: S22.1.3.4).
  7595. ///----------------------------------------------------------------------------
  7596. Var JavascriptArray::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  7597. {
  7598. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7599. ARGUMENTS(args, callInfo);
  7600. ScriptContext* scriptContext = function->GetScriptContext();
  7601. #ifdef ENABLE_JS_BUILTINS
  7602. Assert(!scriptContext->IsJsBuiltInEnabled());
  7603. #endif
  7604. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7605. Assert(!(callInfo.Flags & CallFlags_New));
  7606. if (args.Info.Count == 0)
  7607. {
  7608. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7609. }
  7610. RecyclableObject* thisObj = nullptr;
  7611. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7612. {
  7613. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.entries"));
  7614. }
  7615. #if ENABLE_COPYONACCESS_ARRAY
  7616. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7617. #endif
  7618. JS_REENTRANT_UNLOCK(jsReentLock,
  7619. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::KeyAndValue));
  7620. }
  7621. ///----------------------------------------------------------------------------
  7622. /// Keys() returns a new ArrayIterator object configured to return the keys
  7623. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.13).
  7624. ///----------------------------------------------------------------------------
  7625. Var JavascriptArray::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  7626. {
  7627. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7628. ARGUMENTS(args, callInfo);
  7629. ScriptContext* scriptContext = function->GetScriptContext();
  7630. #ifdef ENABLE_JS_BUILTINS
  7631. Assert(!scriptContext->IsJsBuiltInEnabled());
  7632. #endif
  7633. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7634. Assert(!(callInfo.Flags & CallFlags_New));
  7635. if (args.Info.Count == 0)
  7636. {
  7637. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7638. }
  7639. RecyclableObject* thisObj = nullptr;
  7640. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7641. {
  7642. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.keys"));
  7643. }
  7644. #if ENABLE_COPYONACCESS_ARRAY
  7645. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7646. #endif
  7647. JS_REENTRANT_UNLOCK(jsReentLock,
  7648. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Key));
  7649. }
  7650. ///----------------------------------------------------------------------------
  7651. /// Values() returns a new ArrayIterator object configured to return the values
  7652. /// of the this array/array-like object, as described in (ES6.0: S22.1.3.29).
  7653. ///----------------------------------------------------------------------------
  7654. Var JavascriptArray::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  7655. {
  7656. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7657. ARGUMENTS(args, callInfo);
  7658. ScriptContext* scriptContext = function->GetScriptContext();
  7659. #ifdef ENABLE_JS_BUILTINS
  7660. Assert(!scriptContext->IsJsBuiltInEnabled());
  7661. #endif
  7662. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7663. Assert(!(callInfo.Flags & CallFlags_New));
  7664. if (args.Info.Count == 0)
  7665. {
  7666. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7667. }
  7668. RecyclableObject* thisObj = nullptr;
  7669. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &thisObj))
  7670. {
  7671. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.values"));
  7672. }
  7673. #if ENABLE_COPYONACCESS_ARRAY
  7674. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(thisObj);
  7675. #endif
  7676. JS_REENTRANT_UNLOCK(jsReentLock,
  7677. return scriptContext->GetLibrary()->CreateArrayIterator(thisObj, JavascriptArrayIteratorKind::Value));
  7678. }
  7679. Var JavascriptArray::EntryEvery(RecyclableObject* function, CallInfo callInfo, ...)
  7680. {
  7681. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7682. ARGUMENTS(args, callInfo);
  7683. ScriptContext* scriptContext = function->GetScriptContext();
  7684. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7685. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.every"));
  7686. Assert(!(callInfo.Flags & CallFlags_New));
  7687. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_every);
  7688. if (args.Info.Count == 0)
  7689. {
  7690. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.every"));
  7691. }
  7692. BigIndex length;
  7693. JavascriptArray* pArr = nullptr;
  7694. RecyclableObject* obj = nullptr;
  7695. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.every"), &pArr, &obj, &length));
  7696. if (length.IsSmallIndex())
  7697. {
  7698. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7699. }
  7700. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7701. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7702. }
  7703. // Array.prototype.every as described by ES6.0 (draft 22) Section 22.1.3.5
  7704. template <typename T>
  7705. Var JavascriptArray::EveryHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7706. {
  7707. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7708. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7709. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7710. {
  7711. // typedArrayBase is only non-null if and only if we came here via the TypedArray entrypoint
  7712. if (typedArrayBase != nullptr)
  7713. {
  7714. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.every"));
  7715. }
  7716. else
  7717. {
  7718. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.every"));
  7719. }
  7720. }
  7721. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  7722. Var thisArg = nullptr;
  7723. if (args.Info.Count > 2)
  7724. {
  7725. thisArg = args[2];
  7726. }
  7727. else
  7728. {
  7729. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7730. }
  7731. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  7732. if (typedArrayBase == nullptr && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  7733. {
  7734. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  7735. }
  7736. Var element = nullptr;
  7737. Var testResult = nullptr;
  7738. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7739. CallFlags flags = CallFlags_Value;
  7740. if (typedArrayBase)
  7741. {
  7742. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  7743. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7744. for (uint32 k = 0; k < end; k++)
  7745. {
  7746. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7747. element = typedArrayBase->DirectGetItem(k);
  7748. JS_REENTRANT(jsReentLock,
  7749. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7750. {
  7751. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7752. element,
  7753. JavascriptNumber::ToVar(k, scriptContext),
  7754. typedArrayBase);
  7755. }
  7756. END_SAFE_REENTRANT_CALL
  7757. );
  7758. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7759. {
  7760. return scriptContext->GetLibrary()->GetFalse();
  7761. }
  7762. }
  7763. }
  7764. else
  7765. {
  7766. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::EveryObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7767. }
  7768. return scriptContext->GetLibrary()->GetTrue();
  7769. }
  7770. template <typename T>
  7771. Var JavascriptArray::EveryObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7772. {
  7773. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7774. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7775. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7776. CallFlags flags = CallFlags_Value;
  7777. Var element = nullptr;
  7778. Var testResult = nullptr;
  7779. for (T k = start; k < length; k++)
  7780. {
  7781. // According to es6 spec, we need to call Has first before calling Get
  7782. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7783. if (hasItem)
  7784. {
  7785. JS_REENTRANT(jsReentLock,
  7786. element = JavascriptOperators::GetItem(obj, k, scriptContext);
  7787. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7788. {
  7789. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7790. element,
  7791. JavascriptNumber::ToVar(k, scriptContext),
  7792. obj);
  7793. }
  7794. END_SAFE_REENTRANT_CALL
  7795. );
  7796. if (!JavascriptConversion::ToBoolean(testResult, scriptContext))
  7797. {
  7798. return scriptContext->GetLibrary()->GetFalse();
  7799. }
  7800. }
  7801. }
  7802. return scriptContext->GetLibrary()->GetTrue();
  7803. }
  7804. Var JavascriptArray::EntrySome(RecyclableObject* function, CallInfo callInfo, ...)
  7805. {
  7806. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7807. ARGUMENTS(args, callInfo);
  7808. ScriptContext* scriptContext = function->GetScriptContext();
  7809. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7810. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.some"));
  7811. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_some);
  7812. Assert(!(callInfo.Flags & CallFlags_New));
  7813. if (args.Info.Count == 0)
  7814. {
  7815. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.some"));
  7816. }
  7817. BigIndex length;
  7818. JavascriptArray* pArr = nullptr;
  7819. RecyclableObject* obj = nullptr;
  7820. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.some"), &pArr, &obj, &length));
  7821. if (length.IsSmallIndex())
  7822. {
  7823. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  7824. }
  7825. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  7826. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  7827. }
  7828. // Array.prototype.some as described in ES6.0 (draft 22) Section 22.1.3.23
  7829. template <typename T>
  7830. Var JavascriptArray::SomeHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  7831. {
  7832. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7833. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  7834. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7835. {
  7836. // We are in the TypedArray version of this API if and only if typedArrayBase != nullptr
  7837. if (typedArrayBase != nullptr)
  7838. {
  7839. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.some"));
  7840. }
  7841. else
  7842. {
  7843. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.some"));
  7844. }
  7845. }
  7846. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  7847. Var thisArg = nullptr;
  7848. if (args.Info.Count > 2)
  7849. {
  7850. thisArg = args[2];
  7851. }
  7852. else
  7853. {
  7854. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7855. }
  7856. // If we came from Array.prototype.some and source object is not a JavascriptArray, source could be a TypedArray
  7857. if (typedArrayBase == nullptr && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  7858. {
  7859. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  7860. }
  7861. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7862. CallFlags flags = CallFlags_Value;
  7863. Var element = nullptr;
  7864. Var testResult = nullptr;
  7865. if (typedArrayBase)
  7866. {
  7867. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  7868. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  7869. for (uint32 k = 0; k < end; k++)
  7870. {
  7871. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  7872. element = typedArrayBase->DirectGetItem(k);
  7873. JS_REENTRANT_UNLOCK(jsReentLock,
  7874. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7875. {
  7876. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7877. element,
  7878. JavascriptNumber::ToVar(k, scriptContext),
  7879. typedArrayBase);
  7880. }
  7881. END_SAFE_REENTRANT_CALL
  7882. );
  7883. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7884. {
  7885. return scriptContext->GetLibrary()->GetTrue();
  7886. }
  7887. }
  7888. }
  7889. else
  7890. {
  7891. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::SomeObjectHelper<T>(obj, length, 0u, callBackFn, thisArg, scriptContext));
  7892. }
  7893. return scriptContext->GetLibrary()->GetFalse();
  7894. }
  7895. template <typename T>
  7896. Var JavascriptArray::SomeObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  7897. {
  7898. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7899. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  7900. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7901. CallFlags flags = CallFlags_Value;
  7902. Var element = nullptr;
  7903. Var testResult = nullptr;
  7904. for (T k = start; k < length; k++)
  7905. {
  7906. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  7907. if (hasItem)
  7908. {
  7909. JS_REENTRANT_UNLOCK(jsReentLock,
  7910. element = JavascriptOperators::GetItem(obj, k, scriptContext);
  7911. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7912. {
  7913. testResult = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7914. element,
  7915. JavascriptNumber::ToVar(k, scriptContext),
  7916. obj);
  7917. }
  7918. END_SAFE_REENTRANT_CALL
  7919. );
  7920. if (JavascriptConversion::ToBoolean(testResult, scriptContext))
  7921. {
  7922. return scriptContext->GetLibrary()->GetTrue();
  7923. }
  7924. }
  7925. }
  7926. return scriptContext->GetLibrary()->GetFalse();
  7927. }
  7928. // There is a Javascript built-in for forEach
  7929. Var JavascriptArray::EntryForEach(RecyclableObject* function, CallInfo callInfo, ...)
  7930. {
  7931. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  7932. ARGUMENTS(args, callInfo);
  7933. ScriptContext* scriptContext = function->GetScriptContext();
  7934. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  7935. SETOBJECT_FOR_MUTATION(jsReentLock, args[0]);
  7936. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.forEach"));
  7937. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_forEach)
  7938. Assert(!(callInfo.Flags & CallFlags_New));
  7939. if (args.Info.Count == 0)
  7940. {
  7941. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.forEach"));
  7942. }
  7943. BigIndex length;
  7944. JavascriptArray* pArr = nullptr;
  7945. RecyclableObject* dynamicObject = nullptr;
  7946. RecyclableObject* callBackFn = nullptr;
  7947. Var thisArg = nullptr;
  7948. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.forEach"), &pArr, &dynamicObject, &length));
  7949. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  7950. {
  7951. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.forEach"));
  7952. }
  7953. callBackFn = VarTo<RecyclableObject>(args[1]);
  7954. if (args.Info.Count > 2)
  7955. {
  7956. thisArg = args[2];
  7957. }
  7958. else
  7959. {
  7960. thisArg = scriptContext->GetLibrary()->GetUndefined();
  7961. }
  7962. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  7963. CallFlags flags = CallFlags_Value;
  7964. auto fn32 = [dynamicObject, callBackFn, flags, thisArg,
  7965. scriptContext](uint32 k, Var element)
  7966. {
  7967. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7968. {
  7969. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7970. element,
  7971. JavascriptNumber::ToVar(k, scriptContext),
  7972. dynamicObject);
  7973. }
  7974. END_SAFE_REENTRANT_CALL;
  7975. };
  7976. auto fn64 = [dynamicObject, callBackFn, flags, thisArg,
  7977. scriptContext](uint64 k, Var element)
  7978. {
  7979. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  7980. {
  7981. CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 4), thisArg,
  7982. element,
  7983. JavascriptNumber::ToVar(k, scriptContext),
  7984. dynamicObject);
  7985. }
  7986. END_SAFE_REENTRANT_CALL
  7987. };
  7988. if (pArr)
  7989. {
  7990. Assert(pArr == dynamicObject);
  7991. JS_REENTRANT(jsReentLock, pArr->ForEachItemInRange<true>(0, length.IsUint32Max() ? MaxArrayLength : length.GetSmallIndex(), scriptContext, fn32));
  7992. }
  7993. else
  7994. {
  7995. if (length.IsSmallIndex())
  7996. {
  7997. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0u, length.GetSmallIndex(), scriptContext, fn32));
  7998. }
  7999. else
  8000. {
  8001. JS_REENTRANT(jsReentLock, TemplatedForEachItemInRange<true>(dynamicObject, 0ui64, length.GetBigIndex(), scriptContext, fn64));
  8002. }
  8003. }
  8004. return scriptContext->GetLibrary()->GetUndefined();
  8005. }
  8006. Var JavascriptArray::EntryCopyWithin(RecyclableObject* function, CallInfo callInfo, ...)
  8007. {
  8008. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8009. ARGUMENTS(args, callInfo);
  8010. ScriptContext* scriptContext = function->GetScriptContext();
  8011. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8012. Assert(!(callInfo.Flags & CallFlags_New));
  8013. RecyclableObject* obj = nullptr;
  8014. JavascriptArray* pArr = nullptr;
  8015. int64 length;
  8016. JS_REENTRANT_UNLOCK(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.copyWithin"), &pArr, &obj, &length));
  8017. return JavascriptArray::CopyWithinHelper(pArr, nullptr, obj, length, args, scriptContext);
  8018. }
  8019. // Array.prototype.copyWithin as defined in ES6.0 (draft 22) Section 22.1.3.3
  8020. Var JavascriptArray::CopyWithinHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  8021. {
  8022. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8023. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8024. Assert(args.Info.Count > 0);
  8025. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8026. JavascriptLibrary* library = scriptContext->GetLibrary();
  8027. int64 fromVal = 0;
  8028. int64 toVal = 0;
  8029. int64 finalVal = length;
  8030. // If we came from Array.prototype.copyWithin and source object is not a JavascriptArray, source could be a TypedArray
  8031. if (typedArrayBase == nullptr && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  8032. {
  8033. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  8034. }
  8035. if (args.Info.Count > 1)
  8036. {
  8037. JS_REENTRANT(jsReentLock, toVal = JavascriptArray::GetIndexFromVar(args[1], length, scriptContext));
  8038. if (args.Info.Count > 2)
  8039. {
  8040. JS_REENTRANT(jsReentLock, fromVal = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  8041. if (args.Info.Count > 3 && args[3] != library->GetUndefined())
  8042. {
  8043. JS_REENTRANT(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  8044. }
  8045. }
  8046. }
  8047. // If count would be negative or zero, we won't do anything so go ahead and return early.
  8048. if (finalVal <= fromVal || length <= toVal)
  8049. {
  8050. return obj;
  8051. }
  8052. // Make sure we won't underflow during the count calculation
  8053. Assert(finalVal > fromVal && length > toVal);
  8054. int64 count = min(finalVal - fromVal, length - toVal);
  8055. // We shouldn't have made it here if the count was going to be zero
  8056. Assert(count > 0);
  8057. // If we entered via TypedArray.prototype.copyWithin, then we can copy by bytes. Otherwise, if the user called
  8058. // Array.prototype.copyWithin on a typed array instance, then the typed array might be responsible for not
  8059. // writing torn values, which memmove does not guarantee.
  8060. if (isTypedArrayEntryPoint)
  8061. {
  8062. Assert(typedArrayBase);
  8063. // Re-validate the typed array, which could have become detached due to reentrant script.
  8064. if (typedArrayBase->IsDetachedBuffer())
  8065. {
  8066. JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.copyWithin"));
  8067. }
  8068. AssertOrFailFast(length == typedArrayBase->GetLength());
  8069. uint32 bytesPerElement = typedArrayBase->GetBytesPerElement();
  8070. byte *buffer = typedArrayBase->GetByteBuffer();
  8071. size_t fromByteIndex = static_cast<size_t>(fromVal) * bytesPerElement;
  8072. size_t toByteIndex = static_cast<size_t>(toVal) * bytesPerElement;
  8073. size_t byteCount = static_cast<size_t>(count) * bytesPerElement;
  8074. Assert(typedArrayBase->GetByteLength() >= byteCount);
  8075. Assert(fromByteIndex <= typedArrayBase->GetByteLength() - byteCount);
  8076. Assert(toByteIndex <= typedArrayBase->GetByteLength() - byteCount);
  8077. memmove(&buffer[toByteIndex], &buffer[fromByteIndex], byteCount);
  8078. return obj;
  8079. }
  8080. int direction;
  8081. if (fromVal < toVal && toVal < (fromVal + count))
  8082. {
  8083. direction = -1;
  8084. fromVal += count - 1;
  8085. toVal += count - 1;
  8086. }
  8087. else
  8088. {
  8089. direction = 1;
  8090. }
  8091. // Side effects (such as defining a property in a ToPrimitive call) during evaluation of arguments may convert the array to an ES5 array.
  8092. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  8093. {
  8094. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  8095. pArr = nullptr;
  8096. }
  8097. // If we are going to copy elements from or to indices > 2^32-1 we'll execute this (slightly slower path)
  8098. // It's possible to optimize here so that we use the normal code below except for the > 2^32-1 indices
  8099. if ((direction == -1 && (fromVal >= MaxArrayLength || toVal >= MaxArrayLength))
  8100. || (((fromVal + count) > MaxArrayLength) || ((toVal + count) > MaxArrayLength)))
  8101. {
  8102. while (count > 0)
  8103. {
  8104. Var index = JavascriptNumber::ToVar(fromVal, scriptContext);
  8105. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::OP_HasItem(obj, index, scriptContext));
  8106. if (hasItem)
  8107. {
  8108. Var val = nullptr;
  8109. JS_REENTRANT(jsReentLock,
  8110. val = JavascriptOperators::OP_GetElementI(obj, index, scriptContext),
  8111. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8112. }
  8113. else
  8114. {
  8115. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_DeleteElementI(obj, JavascriptNumber::ToVar(toVal, scriptContext), scriptContext, PropertyOperation_ThrowOnDeleteIfNotConfig));
  8116. }
  8117. fromVal += direction;
  8118. toVal += direction;
  8119. count--;
  8120. }
  8121. }
  8122. else
  8123. {
  8124. Assert(fromVal < MaxArrayLength);
  8125. Assert(toVal < MaxArrayLength);
  8126. Assert(direction == -1 || (fromVal + count < MaxArrayLength && toVal + count < MaxArrayLength));
  8127. uint32 fromIndex = static_cast<uint32>(fromVal);
  8128. uint32 toIndex = static_cast<uint32>(toVal);
  8129. while (count > 0)
  8130. {
  8131. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, fromIndex));
  8132. if (hasItem)
  8133. {
  8134. if (typedArrayBase)
  8135. {
  8136. Var val = typedArrayBase->DirectGetItem(fromIndex);
  8137. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(toIndex, val));
  8138. }
  8139. else if (pArr)
  8140. {
  8141. Var val = nullptr;
  8142. JS_REENTRANT(jsReentLock,
  8143. val = pArr->DirectGetItem(fromIndex),
  8144. pArr->SetItem(toIndex, val, Js::PropertyOperation_ThrowIfNotExtensible));
  8145. if (!JavascriptArray::IsNonES5Array(obj))
  8146. {
  8147. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  8148. pArr = nullptr;
  8149. }
  8150. }
  8151. else
  8152. {
  8153. Var val = nullptr;
  8154. JS_REENTRANT(jsReentLock,
  8155. val = JavascriptOperators::OP_GetElementI_UInt32(obj, fromIndex, scriptContext),
  8156. JavascriptOperators::OP_SetElementI_UInt32(obj, toIndex, val, scriptContext, PropertyOperation_ThrowIfNotExtensible));
  8157. }
  8158. }
  8159. else
  8160. {
  8161. JS_REENTRANT(jsReentLock, obj->DeleteItem(toIndex, PropertyOperation_ThrowOnDeleteIfNotConfig));
  8162. }
  8163. fromIndex += direction;
  8164. toIndex += direction;
  8165. count--;
  8166. }
  8167. }
  8168. return obj;
  8169. }
  8170. Var JavascriptArray::EntryFill(RecyclableObject* function, CallInfo callInfo, ...)
  8171. {
  8172. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8173. ARGUMENTS(args, callInfo);
  8174. ScriptContext* scriptContext = function->GetScriptContext();
  8175. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8176. Assert(!(callInfo.Flags & CallFlags_New));
  8177. RecyclableObject* obj = nullptr;
  8178. JavascriptArray* pArr = nullptr;
  8179. int64 length;
  8180. JS_REENTRANT_UNLOCK(jsReentLock,
  8181. TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.fill"), &pArr, &obj, &length));
  8182. return JavascriptArray::FillHelper(pArr, nullptr, obj, length, args, scriptContext);
  8183. }
  8184. // Array.prototype.fill as defined in ES6.0 (draft 22) Section 22.1.3.6
  8185. Var JavascriptArray::FillHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, int64 length, Arguments& args, ScriptContext* scriptContext)
  8186. {
  8187. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8188. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8189. Assert(args.Info.Count > 0);
  8190. JavascriptLibrary* library = scriptContext->GetLibrary();
  8191. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8192. // If we came from Array.prototype.fill and source object is not a JavascriptArray, source could be a TypedArray
  8193. if (!isTypedArrayEntryPoint && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  8194. {
  8195. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  8196. }
  8197. Var fillValue;
  8198. if (args.Info.Count > 1)
  8199. {
  8200. fillValue = args[1];
  8201. if (isTypedArrayEntryPoint)
  8202. {
  8203. JS_REENTRANT_UNLOCK(jsReentLock, fillValue = JavascriptNumber::ToVarNoCheck(JavascriptConversion::ToNumber(fillValue, scriptContext), scriptContext));
  8204. }
  8205. }
  8206. else
  8207. {
  8208. fillValue = library->GetUndefined();
  8209. }
  8210. int64 k = 0;
  8211. int64 finalVal = length;
  8212. if (args.Info.Count > 2)
  8213. {
  8214. JS_REENTRANT_UNLOCK(jsReentLock, k = JavascriptArray::GetIndexFromVar(args[2], length, scriptContext));
  8215. if (args.Info.Count > 3 && !JavascriptOperators::IsUndefinedObject(args[3]))
  8216. {
  8217. JS_REENTRANT_UNLOCK(jsReentLock, finalVal = JavascriptArray::GetIndexFromVar(args[3], length, scriptContext));
  8218. }
  8219. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8220. // we will process the array elements like an ES5Array.
  8221. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  8222. {
  8223. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  8224. pArr = nullptr;
  8225. }
  8226. }
  8227. if (k < MaxArrayLength)
  8228. {
  8229. int64 end = min<int64>(finalVal, MaxArrayLength);
  8230. uint32 u32k = static_cast<uint32>(k);
  8231. while (u32k < end)
  8232. {
  8233. if (typedArrayBase)
  8234. {
  8235. JS_REENTRANT(jsReentLock, typedArrayBase->DirectSetItem(u32k, fillValue));
  8236. }
  8237. else if (pArr)
  8238. {
  8239. pArr->SetItem(u32k, fillValue, PropertyOperation_ThrowIfNotExtensible);
  8240. }
  8241. else
  8242. {
  8243. JS_REENTRANT(jsReentLock,
  8244. JavascriptOperators::OP_SetElementI_UInt32(obj, u32k, fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8245. }
  8246. u32k++;
  8247. }
  8248. BigIndex dstIndex = MaxArrayLength;
  8249. for (int64 i = end; i < finalVal; ++i)
  8250. {
  8251. if (pArr)
  8252. {
  8253. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  8254. ++dstIndex;
  8255. }
  8256. else
  8257. {
  8258. JS_REENTRANT(jsReentLock,
  8259. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8260. }
  8261. }
  8262. }
  8263. else
  8264. {
  8265. BigIndex dstIndex = static_cast<uint64>(k);
  8266. for (int64 i = k; i < finalVal; i++)
  8267. {
  8268. if (pArr)
  8269. {
  8270. pArr->GenericDirectSetItemAt(dstIndex, fillValue);
  8271. ++dstIndex;
  8272. }
  8273. else
  8274. {
  8275. JS_REENTRANT(jsReentLock,
  8276. JavascriptOperators::OP_SetElementI(obj, JavascriptNumber::ToVar(i, scriptContext), fillValue, scriptContext, Js::PropertyOperation_ThrowIfNotExtensible));
  8277. }
  8278. }
  8279. }
  8280. return obj;
  8281. }
  8282. // Array.prototype.map as defined by ES6.0 (Final) 22.1.3.15
  8283. Var JavascriptArray::EntryMap(RecyclableObject* function, CallInfo callInfo, ...)
  8284. {
  8285. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8286. ARGUMENTS(args, callInfo);
  8287. ScriptContext* scriptContext = function->GetScriptContext();
  8288. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8289. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.map"));
  8290. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_map);
  8291. Assert(!(callInfo.Flags & CallFlags_New));
  8292. if (args.Info.Count == 0)
  8293. {
  8294. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.map"));
  8295. }
  8296. BigIndex length;
  8297. JavascriptArray* pArr = nullptr;
  8298. RecyclableObject* obj = nullptr;
  8299. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.map"), &pArr, &obj, &length));
  8300. if (length.IsSmallIndex())
  8301. {
  8302. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8303. }
  8304. Assert(pArr == nullptr || length.IsUint32Max()); // if pArr is not null lets make sure length is safe to cast, which will only happen if length is a uint32max
  8305. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8306. }
  8307. template<typename T>
  8308. Var JavascriptArray::MapHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8309. {
  8310. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8311. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8312. RecyclableObject* newObj = nullptr;
  8313. JavascriptArray* newArr = nullptr;
  8314. bool isTypedArrayEntryPoint = typedArrayBase != nullptr;
  8315. bool isBuiltinArrayCtor = true;
  8316. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8317. {
  8318. if (isTypedArrayEntryPoint)
  8319. {
  8320. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.map"));
  8321. }
  8322. else
  8323. {
  8324. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.map"));
  8325. }
  8326. }
  8327. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  8328. Var thisArg;
  8329. if (args.Info.Count > 2)
  8330. {
  8331. thisArg = args[2];
  8332. }
  8333. else
  8334. {
  8335. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8336. }
  8337. // If we came from Array.prototype.map and source object is not a JavascriptArray, source could be a TypedArray
  8338. if (!isTypedArrayEntryPoint && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  8339. {
  8340. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  8341. }
  8342. // If the entry point is %TypedArray%.prototype.map or the source object is an Array exotic object we should try to load the constructor property
  8343. // and use it to construct the return object.
  8344. if (isTypedArrayEntryPoint)
  8345. {
  8346. JavascriptFunction* defaultConstructor = TypedArrayBase::GetDefaultConstructor(args[0], scriptContext);
  8347. JS_REENTRANT(jsReentLock,
  8348. RecyclableObject* constructor = JavascriptOperators::SpeciesConstructor(typedArrayBase, defaultConstructor, scriptContext));
  8349. isBuiltinArrayCtor = false;
  8350. AssertOrFailFast(JavascriptOperators::IsConstructor(constructor));
  8351. bool isDefaultConstructor = constructor == defaultConstructor;
  8352. JS_REENTRANT(jsReentLock,
  8353. newObj = VarTo<RecyclableObject>(
  8354. JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var
  8355. {
  8356. Js::Var constructorArgs[] = {constructor, JavascriptNumber::ToVar(length, scriptContext) };
  8357. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  8358. return TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), (uint32)length, scriptContext);
  8359. }));
  8360. )
  8361. }
  8362. // skip the typed array and "pure" array case, we still need to handle special arrays like es5array, remote array, and proxy of array.
  8363. else if (pArr == nullptr || scriptContext->GetConfig()->IsES6SpeciesEnabled())
  8364. {
  8365. JS_REENTRANT_NO_MUTATE(jsReentLock, newObj = ArraySpeciesCreate(obj, length, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8366. }
  8367. if (newObj == nullptr)
  8368. {
  8369. if (length > UINT_MAX)
  8370. {
  8371. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  8372. }
  8373. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(length));
  8374. newArr->EnsureHead<Var>();
  8375. newObj = newArr;
  8376. }
  8377. else
  8378. {
  8379. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8380. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  8381. if (newArr)
  8382. {
  8383. #if ENABLE_COPYONACCESS_ARRAY
  8384. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8385. #endif
  8386. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  8387. }
  8388. }
  8389. Var element = nullptr;
  8390. Var mappedValue = nullptr;
  8391. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8392. CallFlags callBackFnflags = CallFlags_Value;
  8393. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8394. // We at least have to have newObj as a valid object
  8395. Assert(newObj);
  8396. // The ArraySpeciesCreate call above could have converted the source array into an ES5Array. If this happens
  8397. // we will process the array elements like an ES5Array.
  8398. if (pArr && !JavascriptArray::IsNonES5Array(obj))
  8399. {
  8400. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  8401. pArr = nullptr;
  8402. }
  8403. if (pArr != nullptr)
  8404. {
  8405. // If source is a JavascriptArray, newObj may or may not be an array based on what was in source's constructor property
  8406. Assert(length <= UINT_MAX);
  8407. for (uint32 k = 0; k < (uint32)length; k++)
  8408. {
  8409. JS_REENTRANT(jsReentLock, BOOL gotItem = pArr->DirectGetItemAtFull(k, &element));
  8410. if (!gotItem)
  8411. {
  8412. continue;
  8413. }
  8414. JS_REENTRANT(jsReentLock,
  8415. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8416. {
  8417. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8418. element,
  8419. JavascriptNumber::ToVar(k, scriptContext),
  8420. pArr);
  8421. }
  8422. END_SAFE_REENTRANT_CALL
  8423. );
  8424. // If newArr is a valid pointer, then we constructed an array to return. Otherwise we need to do generic object operations
  8425. if (newArr && isBuiltinArrayCtor)
  8426. {
  8427. newArr->DirectSetItemAt(k, mappedValue);
  8428. }
  8429. else
  8430. {
  8431. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, mappedValue), scriptContext, k));
  8432. }
  8433. // Side-effects in the callback function may have changed the source array into an ES5Array. If this happens
  8434. // we will process the rest of the array elements like an ES5Array.
  8435. if (!JavascriptArray::IsNonES5Array(obj))
  8436. {
  8437. AssertOrFailFastMsg(VarIs<ES5Array>(obj), "The array should have been converted to an ES5Array");
  8438. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, k + 1, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8439. }
  8440. }
  8441. }
  8442. else if (typedArrayBase != nullptr)
  8443. {
  8444. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  8445. // Source is a TypedArray, we may have tried to call a constructor, but newObj may not be a TypedArray (or an array either)
  8446. TypedArrayBase* newTypedArray = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(newObj);
  8447. if (!newTypedArray)
  8448. {
  8449. AssertAndFailFast(newArr != nullptr);
  8450. }
  8451. Assert(length <= UINT_MAX);
  8452. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8453. for (uint32 k = 0; k < end; k++)
  8454. {
  8455. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8456. element = typedArrayBase->DirectGetItem(k);
  8457. JS_REENTRANT(jsReentLock,
  8458. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8459. {
  8460. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8461. element,
  8462. JavascriptNumber::ToVar(k, scriptContext),
  8463. obj);
  8464. }
  8465. END_SAFE_REENTRANT_CALL
  8466. );
  8467. // If newObj is a TypedArray, set the mappedValue directly, otherwise it should be an array, set that item to that array
  8468. if (newTypedArray)
  8469. {
  8470. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, mappedValue));
  8471. }
  8472. else
  8473. {
  8474. newArr->SetItem(k, mappedValue, PropertyOperation_None);
  8475. }
  8476. }
  8477. }
  8478. else
  8479. {
  8480. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::MapObjectHelper<T>(obj, length, 0u, newObj, newArr, isBuiltinArrayCtor, callBackFn, thisArg, scriptContext));
  8481. }
  8482. #ifdef VALIDATE_ARRAY
  8483. if (JavascriptArray::IsNonES5Array(newObj))
  8484. {
  8485. newArr->ValidateArray();
  8486. }
  8487. #endif
  8488. return newObj;
  8489. }
  8490. template<typename T>
  8491. Var JavascriptArray::MapObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* newObj, JavascriptArray* newArr,
  8492. bool isBuiltinArrayCtor, RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8493. {
  8494. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8495. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8496. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8497. CallFlags callBackFnflags = CallFlags_Value;
  8498. CallInfo callBackFnInfo = CallInfo(callBackFnflags, 4);
  8499. Var element = nullptr;
  8500. Var mappedValue = nullptr;
  8501. for (T k = start; k < length; k++)
  8502. {
  8503. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8504. if (hasItem)
  8505. {
  8506. JS_REENTRANT(jsReentLock,
  8507. element = JavascriptOperators::GetItem(obj, k, scriptContext);
  8508. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8509. {
  8510. mappedValue = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, callBackFnInfo, thisArg,
  8511. element,
  8512. JavascriptNumber::ToVar(k, scriptContext),
  8513. obj);
  8514. }
  8515. END_SAFE_REENTRANT_CALL
  8516. );
  8517. if (newArr && isBuiltinArrayCtor)
  8518. {
  8519. newArr->SetItem((uint32)k, mappedValue, PropertyOperation_None);
  8520. }
  8521. else
  8522. {
  8523. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, BigIndex(k), mappedValue), scriptContext, BigIndex(k)));
  8524. }
  8525. }
  8526. }
  8527. #ifdef VALIDATE_ARRAY
  8528. if (JavascriptArray::IsNonES5Array(newObj))
  8529. {
  8530. newArr->ValidateArray();
  8531. }
  8532. #endif
  8533. return newObj;
  8534. }
  8535. Var JavascriptArray::EntryFilter(RecyclableObject* function, CallInfo callInfo, ...)
  8536. {
  8537. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8538. ARGUMENTS(args, callInfo);
  8539. ScriptContext* scriptContext = function->GetScriptContext();
  8540. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8541. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.filter"));
  8542. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_filter);
  8543. Assert(!(callInfo.Flags & CallFlags_New));
  8544. if (args.Info.Count == 0)
  8545. {
  8546. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.filter"));
  8547. }
  8548. BigIndex length;
  8549. JavascriptArray* pArr = nullptr;
  8550. RecyclableObject* obj = nullptr;
  8551. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.filter"), &pArr, &obj, &length));
  8552. if (length.IsSmallIndex())
  8553. {
  8554. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetSmallIndex(), args, scriptContext));
  8555. }
  8556. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterHelper(pArr, obj, length.GetBigIndex(), args, scriptContext));
  8557. }
  8558. template <typename T>
  8559. Var JavascriptArray::FilterHelper(JavascriptArray* pArr, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8560. {
  8561. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8562. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8563. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8564. {
  8565. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.filter"));
  8566. }
  8567. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  8568. Var thisArg = nullptr;
  8569. if (args.Info.Count > 2)
  8570. {
  8571. thisArg = args[2];
  8572. }
  8573. else
  8574. {
  8575. thisArg = scriptContext->GetLibrary()->GetUndefined();
  8576. }
  8577. // If the source object is an Array exotic object we should try to load the constructor property and use it to construct the return object.
  8578. bool isBuiltinArrayCtor = true;
  8579. JS_REENTRANT_NO_MUTATE(jsReentLock, RecyclableObject* newObj = ArraySpeciesCreate(obj, 0, scriptContext, nullptr, nullptr, &isBuiltinArrayCtor));
  8580. JavascriptArray* newArr = nullptr;
  8581. if (newObj == nullptr)
  8582. {
  8583. newArr = scriptContext->GetLibrary()->CreateArray(0);
  8584. newArr->EnsureHead<Var>();
  8585. newObj = newArr;
  8586. }
  8587. else
  8588. {
  8589. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  8590. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  8591. if (newArr)
  8592. {
  8593. #if ENABLE_COPYONACCESS_ARRAY
  8594. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  8595. #endif
  8596. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, newArr);
  8597. }
  8598. }
  8599. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::FilterObjectHelper<T>(obj, length, 0u, newArr, newObj, 0u, callBackFn, thisArg, scriptContext));
  8600. }
  8601. template <typename T>
  8602. Var JavascriptArray::FilterObjectHelper(RecyclableObject* obj, T length, T start, JavascriptArray* newArr, RecyclableObject* newObj, T newStart,
  8603. RecyclableObject* callBackFn, Var thisArg, ScriptContext* scriptContext)
  8604. {
  8605. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8606. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8607. Var element = nullptr;
  8608. Var selected = nullptr;
  8609. BigIndex i = BigIndex(newStart);
  8610. for (T k = start; k < length; k++)
  8611. {
  8612. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8613. if (hasItem)
  8614. {
  8615. JS_REENTRANT(jsReentLock,
  8616. element = JavascriptOperators::GetItem(obj, k, scriptContext);
  8617. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8618. {
  8619. selected = CALL_ENTRYPOINT(scriptContext->GetThreadContext(),
  8620. callBackFn->GetEntryPoint(), callBackFn, CallInfo(CallFlags_Value, 4),
  8621. thisArg,
  8622. element,
  8623. JavascriptNumber::ToVar(k, scriptContext),
  8624. obj);
  8625. }
  8626. END_SAFE_REENTRANT_CALL
  8627. );
  8628. if (JavascriptConversion::ToBoolean(selected, scriptContext))
  8629. {
  8630. if (newArr)
  8631. {
  8632. newArr->GenericDirectSetItemAt(i, element);
  8633. }
  8634. else
  8635. {
  8636. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, i, element), scriptContext, i));
  8637. }
  8638. ++i;
  8639. }
  8640. }
  8641. }
  8642. #ifdef VALIDATE_ARRAY
  8643. if (newArr)
  8644. {
  8645. newArr->ValidateArray();
  8646. }
  8647. #endif
  8648. return newObj;
  8649. }
  8650. Var JavascriptArray::EntryReduce(RecyclableObject* function, CallInfo callInfo, ...)
  8651. {
  8652. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8653. ARGUMENTS(args, callInfo);
  8654. ScriptContext* scriptContext = function->GetScriptContext();
  8655. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8656. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduce"));
  8657. #ifdef ENABLE_JS_BUILTINS
  8658. Assert(!scriptContext->IsJsBuiltInEnabled());
  8659. #endif
  8660. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduce);
  8661. Assert(!(callInfo.Flags & CallFlags_New));
  8662. if (args.Info.Count == 0)
  8663. {
  8664. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduce"));
  8665. }
  8666. BigIndex length;
  8667. JavascriptArray * pArr = nullptr;
  8668. RecyclableObject* obj = nullptr;
  8669. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduce"), &pArr, &obj, &length));
  8670. if (length.IsSmallIndex())
  8671. {
  8672. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8673. }
  8674. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8675. }
  8676. // Array.prototype.reduce as described in ES6.0 (draft 22) Section 22.1.3.18
  8677. template <typename T>
  8678. Var JavascriptArray::ReduceHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8679. {
  8680. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8681. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8682. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8683. {
  8684. if (typedArrayBase != nullptr)
  8685. {
  8686. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduce"));
  8687. }
  8688. else
  8689. {
  8690. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduce"));
  8691. }
  8692. }
  8693. // If we came from Array.prototype.reduce and source object is not a JavascriptArray, source could be a TypedArray
  8694. if (typedArrayBase == nullptr && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  8695. {
  8696. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  8697. }
  8698. T k = 0;
  8699. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  8700. Var accumulator = nullptr;
  8701. Var element = nullptr;
  8702. if (args.Info.Count > 2)
  8703. {
  8704. accumulator = args[2];
  8705. }
  8706. else
  8707. {
  8708. if (length == 0)
  8709. {
  8710. if (typedArrayBase)
  8711. {
  8712. JavascriptError::ThrowTypeError(scriptContext, JSERR_EmptyArrayAndInitValueNotPresent, _u("TypedArray.prototype.reduce"));
  8713. }
  8714. else
  8715. {
  8716. JavascriptError::ThrowTypeError(scriptContext, JSERR_EmptyArrayAndInitValueNotPresent, _u("Array.prototype.reduce"));
  8717. }
  8718. }
  8719. bool bPresent = false;
  8720. if (typedArrayBase)
  8721. {
  8722. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  8723. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8724. for (; k < end && bPresent == false; k++)
  8725. {
  8726. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8727. element = typedArrayBase->DirectGetItem((uint32)k);
  8728. bPresent = true;
  8729. accumulator = element;
  8730. }
  8731. }
  8732. else
  8733. {
  8734. for (; k < length && bPresent == false; k++)
  8735. {
  8736. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8737. if (hasItem)
  8738. {
  8739. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, k, scriptContext));
  8740. bPresent = true;
  8741. }
  8742. }
  8743. }
  8744. if (bPresent == false)
  8745. {
  8746. if (typedArrayBase)
  8747. {
  8748. JavascriptError::ThrowTypeError(scriptContext, JSERR_EmptyArrayAndInitValueNotPresent, _u("TypedArray.prototype.reduce"));
  8749. }
  8750. else
  8751. {
  8752. JavascriptError::ThrowTypeError(scriptContext, JSERR_EmptyArrayAndInitValueNotPresent, _u("Array.prototype.reduce"));
  8753. }
  8754. }
  8755. }
  8756. Assert(accumulator);
  8757. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8758. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8759. CallFlags flags = CallFlags_Value;
  8760. if (typedArrayBase)
  8761. {
  8762. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  8763. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8764. for (; k < end; k++)
  8765. {
  8766. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8767. element = typedArrayBase->DirectGetItem((uint32)k);
  8768. JS_REENTRANT(jsReentLock,
  8769. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8770. {
  8771. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8772. accumulator,
  8773. element,
  8774. JavascriptNumber::ToVar(k, scriptContext),
  8775. typedArrayBase);
  8776. }
  8777. END_SAFE_REENTRANT_CALL
  8778. );
  8779. }
  8780. }
  8781. else
  8782. {
  8783. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8784. }
  8785. return accumulator;
  8786. }
  8787. template <typename T>
  8788. Var JavascriptArray::ReduceObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8789. {
  8790. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8791. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8792. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8793. CallFlags flags = CallFlags_Value;
  8794. Var element = nullptr;
  8795. for (T k = start; k < length; k++)
  8796. {
  8797. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, k));
  8798. if (hasItem)
  8799. {
  8800. JS_REENTRANT(jsReentLock,
  8801. element = JavascriptOperators::GetItem(obj, k, scriptContext);
  8802. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8803. {
  8804. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8805. accumulator,
  8806. element,
  8807. JavascriptNumber::ToVar(k, scriptContext),
  8808. obj);
  8809. }
  8810. END_SAFE_REENTRANT_CALL
  8811. );
  8812. }
  8813. }
  8814. return accumulator;
  8815. }
  8816. Var JavascriptArray::EntryReduceRight(RecyclableObject* function, CallInfo callInfo, ...)
  8817. {
  8818. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8819. ARGUMENTS(args, callInfo);
  8820. ScriptContext* scriptContext = function->GetScriptContext();
  8821. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8822. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.prototype.reduceRight"));
  8823. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Array_Prototype_reduceRight);
  8824. Assert(!(callInfo.Flags & CallFlags_New));
  8825. if (args.Info.Count == 0)
  8826. {
  8827. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.prototype.reduceRight"));
  8828. }
  8829. BigIndex length;
  8830. JavascriptArray * pArr = nullptr;
  8831. RecyclableObject* obj = nullptr;
  8832. JS_REENTRANT(jsReentLock, TryGetArrayAndLength(args[0], scriptContext, _u("Array.prototype.reduceRight"), &pArr, &obj, &length));
  8833. if (length.IsSmallIndex())
  8834. {
  8835. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetSmallIndex(), args, scriptContext));
  8836. }
  8837. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightHelper(pArr, nullptr, obj, length.GetBigIndex(), args, scriptContext));
  8838. }
  8839. // Array.prototype.reduceRight as described in ES6.0 (draft 22) Section 22.1.3.19
  8840. template <typename T>
  8841. Var JavascriptArray::ReduceRightHelper(JavascriptArray* pArr, Js::TypedArrayBase* typedArrayBase, RecyclableObject* obj, T length, Arguments& args, ScriptContext* scriptContext)
  8842. {
  8843. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8844. SETOBJECT_FOR_MUTATION(jsReentLock, pArr);
  8845. if (args.Info.Count < 2 || !JavascriptConversion::IsCallable(args[1]))
  8846. {
  8847. if (typedArrayBase != nullptr)
  8848. {
  8849. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("[TypedArray].prototype.reduceRight"));
  8850. }
  8851. else
  8852. {
  8853. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.prototype.reduceRight"));
  8854. }
  8855. }
  8856. // If we came from Array.prototype.reduceRight and source object is not a JavascriptArray, source could be a TypedArray
  8857. if (typedArrayBase == nullptr && pArr == nullptr && VarIs<TypedArrayBase>(obj))
  8858. {
  8859. typedArrayBase = UnsafeVarTo<TypedArrayBase>(obj);
  8860. }
  8861. RecyclableObject* callBackFn = VarTo<RecyclableObject>(args[1]);
  8862. Var accumulator = nullptr;
  8863. Var element = nullptr;
  8864. T k = 0;
  8865. T index = 0;
  8866. if (args.Info.Count > 2)
  8867. {
  8868. accumulator = args[2];
  8869. }
  8870. else
  8871. {
  8872. if (length == 0)
  8873. {
  8874. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8875. }
  8876. bool bPresent = false;
  8877. if (typedArrayBase)
  8878. {
  8879. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  8880. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8881. for (; k < end && bPresent == false; k++)
  8882. {
  8883. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8884. index = length - k - 1;
  8885. element = typedArrayBase->DirectGetItem((uint32)index);
  8886. bPresent = true;
  8887. accumulator = element;
  8888. }
  8889. }
  8890. else
  8891. {
  8892. for (; k < length && bPresent == false; k++)
  8893. {
  8894. index = length - k - 1;
  8895. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8896. if (hasItem)
  8897. {
  8898. JS_REENTRANT(jsReentLock, accumulator = JavascriptOperators::GetItem(obj, index, scriptContext));
  8899. bPresent = true;
  8900. }
  8901. }
  8902. }
  8903. if (bPresent == false)
  8904. {
  8905. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  8906. }
  8907. }
  8908. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8909. CallFlags flags = CallFlags_Value;
  8910. Var undefinedValue = scriptContext->GetLibrary()->GetUndefined();
  8911. if (typedArrayBase)
  8912. {
  8913. AssertAndFailFast(VarIsCorrectType(typedArrayBase));
  8914. uint32 end = (uint32)min(length, (T)typedArrayBase->GetLength());
  8915. for (; k < end; k++)
  8916. {
  8917. // No need to do HasItem, as it cannot be observable unless 'typedArrayBase' is proxy. And we have established that it is indeed typedarray.
  8918. index = length - k - 1;
  8919. element = typedArrayBase->DirectGetItem((uint32)index);
  8920. JS_REENTRANT(jsReentLock,
  8921. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8922. {
  8923. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(), callBackFn, CallInfo(flags, 5), undefinedValue,
  8924. accumulator,
  8925. element,
  8926. JavascriptNumber::ToVar(index, scriptContext),
  8927. typedArrayBase);
  8928. }
  8929. END_SAFE_REENTRANT_CALL
  8930. );
  8931. }
  8932. }
  8933. else
  8934. {
  8935. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::ReduceRightObjectHelper<T>(obj, length, k, callBackFn, accumulator, scriptContext));
  8936. }
  8937. return accumulator;
  8938. }
  8939. template <typename T>
  8940. Var JavascriptArray::ReduceRightObjectHelper(RecyclableObject* obj, T length, T start, RecyclableObject* callBackFn, Var accumulator, ScriptContext* scriptContext)
  8941. {
  8942. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8943. SETOBJECT_FOR_MUTATION(jsReentLock, obj);
  8944. // The correct flag value is CallFlags_Value but we pass CallFlags_None in compat modes
  8945. CallFlags flags = CallFlags_Value;
  8946. Var element = nullptr;
  8947. T index = 0;
  8948. for (T k = start; k < length; k++)
  8949. {
  8950. index = length - k - 1;
  8951. JS_REENTRANT(jsReentLock, BOOL hasItem = JavascriptOperators::HasItem(obj, index));
  8952. if (hasItem)
  8953. {
  8954. JS_REENTRANT(jsReentLock,
  8955. element = JavascriptOperators::GetItem(obj, index, scriptContext);
  8956. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  8957. {
  8958. accumulator = CALL_FUNCTION(scriptContext->GetThreadContext(),
  8959. callBackFn, CallInfo(flags, 5), scriptContext->GetLibrary()->GetUndefined(),
  8960. accumulator,
  8961. element,
  8962. JavascriptNumber::ToVar(index, scriptContext),
  8963. obj);
  8964. }
  8965. END_SAFE_REENTRANT_CALL
  8966. );
  8967. }
  8968. }
  8969. return accumulator;
  8970. }
  8971. Var JavascriptArray::EntryFrom(RecyclableObject* function, CallInfo callInfo, ...)
  8972. {
  8973. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  8974. ARGUMENTS(args, callInfo);
  8975. ScriptContext* scriptContext = function->GetScriptContext();
  8976. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  8977. AUTO_TAG_NATIVE_LIBRARY_ENTRY(function, callInfo, _u("Array.from"));
  8978. Assert(!(callInfo.Flags & CallFlags_New));
  8979. JavascriptLibrary* library = scriptContext->GetLibrary();
  8980. RecyclableObject* constructor = nullptr;
  8981. if (JavascriptOperators::IsConstructor(args[0]))
  8982. {
  8983. constructor = VarTo<RecyclableObject>(args[0]);
  8984. }
  8985. RecyclableObject* items = nullptr;
  8986. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &items))
  8987. {
  8988. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Array.from"));
  8989. }
  8990. JavascriptArray* itemsArr = JavascriptArray::TryVarToNonES5Array(items);
  8991. if (itemsArr)
  8992. {
  8993. #if ENABLE_COPYONACCESS_ARRAY
  8994. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(itemsArr);
  8995. #endif
  8996. }
  8997. SETOBJECT_FOR_MUTATION(jsReentLock, itemsArr);
  8998. bool mapping = false;
  8999. RecyclableObject* mapFn = nullptr;
  9000. Var mapFnThisArg = nullptr;
  9001. if (args.Info.Count >= 3 && !JavascriptOperators::IsUndefinedObject(args[2]))
  9002. {
  9003. if (!JavascriptConversion::IsCallable(args[2]))
  9004. {
  9005. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Array.from"));
  9006. }
  9007. mapFn = VarTo<RecyclableObject>(args[2]);
  9008. if (args.Info.Count >= 4)
  9009. {
  9010. mapFnThisArg = args[3];
  9011. }
  9012. else
  9013. {
  9014. mapFnThisArg = library->GetUndefined();
  9015. }
  9016. mapping = true;
  9017. }
  9018. RecyclableObject* newObj = nullptr;
  9019. JavascriptArray* newArr = nullptr;
  9020. JS_REENTRANT(jsReentLock, RecyclableObject* iterator = JavascriptOperators::GetIterator(items, scriptContext, true /* optional */));
  9021. if (iterator != nullptr)
  9022. {
  9023. if (constructor)
  9024. {
  9025. Js::Var constructorArgs[] = { constructor };
  9026. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  9027. Js::Arguments arguments(constructorCallInfo, constructorArgs);
  9028. bool isDefaultConstructor = constructor == scriptContext->GetLibrary()->GetArrayConstructor();
  9029. JS_REENTRANT(jsReentLock,
  9030. newObj = VarTo<RecyclableObject>(JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var
  9031. {
  9032. return JavascriptOperators::NewScObject(constructor, arguments, scriptContext);
  9033. }))
  9034. );
  9035. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  9036. if (newArr)
  9037. {
  9038. #if ENABLE_COPYONACCESS_ARRAY
  9039. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  9040. #endif
  9041. }
  9042. }
  9043. else
  9044. {
  9045. newArr = scriptContext->GetLibrary()->CreateArray(0);
  9046. newArr->EnsureHead<Var>();
  9047. newObj = newArr;
  9048. }
  9049. uint32 k = 0;
  9050. JS_REENTRANT(jsReentLock, JavascriptOperators::DoIteratorStepAndValue(iterator, scriptContext, [&](Var nextValue) {
  9051. if (mapping)
  9052. {
  9053. Assert(mapFn != nullptr);
  9054. Assert(mapFnThisArg != nullptr);
  9055. Var kVar = JavascriptNumber::ToVar(k, scriptContext);
  9056. nextValue = scriptContext->GetThreadContext()->ExecuteImplicitCall(mapFn, Js::ImplicitCall_Accessor, [=]()->Js::Var
  9057. {
  9058. return CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, nextValue, kVar);
  9059. });
  9060. }
  9061. if (newArr)
  9062. {
  9063. newArr->SetItem(k, nextValue, PropertyOperation_None);
  9064. }
  9065. else
  9066. {
  9067. ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, nextValue), scriptContext, k);
  9068. }
  9069. k++;
  9070. }));
  9071. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(k, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  9072. }
  9073. else
  9074. {
  9075. JS_REENTRANT(jsReentLock, int64 len = (int64)OP_GetLength(items, scriptContext));
  9076. if (constructor)
  9077. {
  9078. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  9079. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  9080. Js::Arguments arguments(constructorCallInfo, constructorArgs);
  9081. bool isDefaultConstructor = constructor == scriptContext->GetLibrary()->GetArrayConstructor();
  9082. JS_REENTRANT(jsReentLock,
  9083. newObj = VarTo<RecyclableObject>(JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isDefaultConstructor, scriptContext->GetThreadContext(), [=]()->Js::Var
  9084. {
  9085. return JavascriptOperators::NewScObject(constructor, arguments, scriptContext);
  9086. }))
  9087. );
  9088. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  9089. if (newArr)
  9090. {
  9091. #if ENABLE_COPYONACCESS_ARRAY
  9092. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  9093. #endif
  9094. }
  9095. }
  9096. else
  9097. {
  9098. // Abstract operation ArrayCreate throws RangeError if length argument is > 2^32 -1
  9099. if (len > MaxArrayLength)
  9100. {
  9101. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthAssignIncorrect, _u("Array.from"));
  9102. }
  9103. // Static cast len should be valid (len < 2^32) or we would throw above
  9104. newArr = scriptContext->GetLibrary()->CreateArray(static_cast<uint32>(len));
  9105. newArr->EnsureHead<Var>();
  9106. newObj = newArr;
  9107. }
  9108. uint32 k = 0;
  9109. for ( ; k < len; k++)
  9110. {
  9111. Var kValue;
  9112. if (itemsArr)
  9113. {
  9114. JS_REENTRANT(jsReentLock, kValue = itemsArr->DirectGetItem(k));
  9115. }
  9116. else
  9117. {
  9118. JS_REENTRANT(jsReentLock, kValue = JavascriptOperators::OP_GetElementI_UInt32(items, k, scriptContext));
  9119. }
  9120. if (mapping)
  9121. {
  9122. Assert(mapFn != nullptr);
  9123. Assert(mapFnThisArg != nullptr);
  9124. Var kVar = JavascriptNumber::ToVar(k, scriptContext);
  9125. JS_REENTRANT(jsReentLock,
  9126. kValue = scriptContext->GetThreadContext()->ExecuteImplicitCall(mapFn, Js::ImplicitCall_Accessor, [=]()->Js::Var
  9127. {
  9128. return CALL_FUNCTION(scriptContext->GetThreadContext(), mapFn, CallInfo(CallFlags_Value, 3), mapFnThisArg, kValue, kVar)
  9129. })
  9130. );
  9131. }
  9132. if (newArr)
  9133. {
  9134. newArr->SetItem(k, kValue, PropertyOperation_None);
  9135. }
  9136. else
  9137. {
  9138. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(newObj, k, kValue), scriptContext, k));
  9139. }
  9140. }
  9141. JS_REENTRANT(jsReentLock, JavascriptOperators::SetProperty(newObj, newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, PropertyOperation_ThrowIfNotExtensible));
  9142. }
  9143. return newObj;
  9144. }
  9145. Var JavascriptArray::EntryOf(RecyclableObject* function, CallInfo callInfo, ...)
  9146. {
  9147. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  9148. ARGUMENTS(args, callInfo);
  9149. ScriptContext* scriptContext = function->GetScriptContext();
  9150. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9151. Assert(!(callInfo.Flags & CallFlags_New));
  9152. if (args.Info.Count == 0)
  9153. {
  9154. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Array.of"));
  9155. }
  9156. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptArray::OfHelper(false, args, scriptContext));
  9157. }
  9158. Var JavascriptArray::EntryGetterSymbolSpecies(RecyclableObject* function, CallInfo callInfo, ...)
  9159. {
  9160. ARGUMENTS(args, callInfo);
  9161. Assert(args.Info.Count > 0);
  9162. return args[0];
  9163. }
  9164. // Array.of and %TypedArray%.of as described in ES6.0 (draft 22) Section 22.1.2.2 and 22.2.2.2
  9165. Var JavascriptArray::OfHelper(bool isTypedArrayEntryPoint, Arguments& args, ScriptContext* scriptContext)
  9166. {
  9167. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  9168. Assert(args.Info.Count > 0);
  9169. // args.Info.Count cannot equal zero or we would have thrown above so no chance of underflowing
  9170. uint32 len = args.Info.Count - 1;
  9171. Var newObj = nullptr;
  9172. JavascriptArray* newArr = nullptr;
  9173. TypedArrayBase* newTypedArray = nullptr;
  9174. bool isBuiltinArrayCtor = true;
  9175. if (JavascriptOperators::IsConstructor(args[0]))
  9176. {
  9177. RecyclableObject* constructor = VarTo<RecyclableObject>(args[0]);
  9178. isBuiltinArrayCtor = (constructor == scriptContext->GetLibrary()->GetArrayConstructor());
  9179. bool isBuiltInTypedArrayCtor = JavascriptLibrary::IsTypedArrayConstructor(constructor, scriptContext);
  9180. JS_REENTRANT
  9181. (
  9182. jsReentLock,
  9183. newObj = JavascriptOperators::NewObjectCreationHelper_ReentrancySafe(constructor, isBuiltinArrayCtor || isBuiltInTypedArrayCtor, scriptContext->GetThreadContext(), [=]()->Js::Var
  9184. {
  9185. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(len, scriptContext) };
  9186. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  9187. if (isTypedArrayEntryPoint)
  9188. {
  9189. return TypedArrayBase::TypedArrayCreate(constructor, &Js::Arguments(constructorCallInfo, constructorArgs), len, scriptContext);
  9190. }
  9191. else
  9192. {
  9193. return JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext);
  9194. }
  9195. });
  9196. )
  9197. // If the new object we created is an array, remember that as it will save us time setting properties in the object below
  9198. newArr = JavascriptArray::TryVarToNonES5Array(newObj);
  9199. if (newArr)
  9200. {
  9201. #if ENABLE_COPYONACCESS_ARRAY
  9202. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(newArr);
  9203. #endif
  9204. SETOBJECT_FOR_MUTATION(jsReentLock, newArr);
  9205. }
  9206. else if (VarIs<TypedArrayBase>(newObj))
  9207. {
  9208. newTypedArray = UnsafeVarTo<TypedArrayBase>(newObj);
  9209. }
  9210. }
  9211. else
  9212. {
  9213. // We only throw when the constructor property is not a constructor function in the TypedArray version
  9214. if (isTypedArrayEntryPoint)
  9215. {
  9216. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("[TypedArray].of"));
  9217. }
  9218. newArr = scriptContext->GetLibrary()->CreateArray(len);
  9219. newArr->EnsureHead<Var>();
  9220. newObj = newArr;
  9221. }
  9222. // At least we have a new object of some kind
  9223. Assert(newObj);
  9224. if (isBuiltinArrayCtor)
  9225. {
  9226. for (uint32 k = 0; k < len; k++)
  9227. {
  9228. Var kValue = args[k + 1];
  9229. newArr->DirectSetItemAt(k, kValue);
  9230. }
  9231. }
  9232. else if (newTypedArray)
  9233. {
  9234. for (uint32 k = 0; k < len; k++)
  9235. {
  9236. Var kValue = args[k + 1];
  9237. JS_REENTRANT(jsReentLock, newTypedArray->DirectSetItem(k, kValue));
  9238. }
  9239. }
  9240. else
  9241. {
  9242. for (uint32 k = 0; k < len; k++)
  9243. {
  9244. Var kValue = args[k + 1];
  9245. JS_REENTRANT(jsReentLock, ThrowErrorOnFailure(JavascriptArray::SetArrayLikeObjects(VarTo<RecyclableObject>(newObj), k, kValue), scriptContext, k));
  9246. }
  9247. }
  9248. if (!isTypedArrayEntryPoint)
  9249. {
  9250. // Set length if we are in the Array version of the function
  9251. JS_REENTRANT(jsReentLock, JavascriptOperators::OP_SetProperty(newObj, Js::PropertyIds::length, JavascriptNumber::ToVar(len, scriptContext), scriptContext, nullptr, PropertyOperation_ThrowIfNotExtensible));
  9252. }
  9253. return newObj;
  9254. }
  9255. JavascriptString* JavascriptArray::ToLocaleStringHelper(Var value, ScriptContext* scriptContext)
  9256. {
  9257. TypeId typeId = JavascriptOperators::GetTypeId(value);
  9258. if (typeId <= TypeIds_UndefinedOrNull)
  9259. {
  9260. return scriptContext->GetLibrary()->GetEmptyString();
  9261. }
  9262. else
  9263. {
  9264. return JavascriptConversion::ToLocaleString(value, scriptContext);
  9265. }
  9266. }
  9267. inline BOOL JavascriptArray::IsFullArray() const
  9268. {
  9269. if (head && head->length == length)
  9270. {
  9271. AssertMsg(head->next == 0 && head->left == 0, "Invalid Array");
  9272. return true;
  9273. }
  9274. return (0 == length);
  9275. }
  9276. /*
  9277. * IsFillFromPrototypes
  9278. * - Check the array has no missing values and only head segment.
  9279. * - Also ensure if the lengths match.
  9280. */
  9281. bool JavascriptArray::IsFillFromPrototypes()
  9282. {
  9283. return !(this->head->next == nullptr && this->HasNoMissingValues() && this->length == this->head->length);
  9284. }
  9285. // Fill all missing value in the array and fill it from prototype between startIndex and limitIndex
  9286. // typically startIndex = 0 and limitIndex = length. From start of the array till end of the array.
  9287. void JavascriptArray::FillFromPrototypes(uint32 startIndex, uint32 limitIndex)
  9288. {
  9289. if (startIndex >= limitIndex)
  9290. {
  9291. return;
  9292. }
  9293. RecyclableObject* prototype = this->GetPrototype();
  9294. // Fill all missing values by walking through prototype
  9295. while (!JavascriptOperators::IsNull(prototype))
  9296. {
  9297. ForEachOwnMissingArrayIndexOfObject(this, nullptr, prototype, startIndex, limitIndex,0, [this](uint32 index, Var value) {
  9298. this->SetItem(index, value, PropertyOperation_None);
  9299. });
  9300. prototype = prototype->GetPrototype();
  9301. }
  9302. #ifdef VALIDATE_ARRAY
  9303. ValidateArray();
  9304. #endif
  9305. }
  9306. //
  9307. // JavascriptArray requires head->left == 0 for fast path Get.
  9308. //
  9309. template<typename T>
  9310. void JavascriptArray::EnsureHeadStartsFromZero(Recycler * recycler)
  9311. {
  9312. if (head == nullptr || head->left != 0)
  9313. {
  9314. // This is used to fix up altered arrays.
  9315. // any SegmentMap would be invalid at this point.
  9316. ClearSegmentMap();
  9317. //
  9318. // We could OOM and throw when allocating new empty head, resulting in a corrupted array. Need
  9319. // some protection here. Save the head and switch this array to EmptySegment. Will be restored
  9320. // correctly if allocating new segment succeeds.
  9321. //
  9322. SparseArraySegment<T>* savedHead = SparseArraySegment<T>::From(this->head);
  9323. SparseArraySegment<T>* savedLastUsedSegment = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  9324. SetHeadAndLastUsedSegment(const_cast<SparseArraySegmentBase*>(EmptySegment));
  9325. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, savedHead);
  9326. newSeg->next = savedHead;
  9327. this->head = newSeg;
  9328. SetHasNoMissingValues();
  9329. this->SetLastUsedSegment(savedLastUsedSegment);
  9330. }
  9331. }
  9332. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  9333. void JavascriptArray::CheckForceES5Array()
  9334. {
  9335. if (Configuration::Global.flags.ForceES5Array)
  9336. {
  9337. // There's a bad interaction with the jitted code for native array creation here.
  9338. // ForceES5Array doesn't interact well with native arrays
  9339. if (PHASE_OFF1(NativeArrayPhase))
  9340. {
  9341. GetTypeHandler()->ConvertToTypeWithItemAttributes(this);
  9342. }
  9343. }
  9344. }
  9345. #endif
  9346. #if DBG
  9347. void JavascriptArray::DoTypeMutation()
  9348. {
  9349. // Type transition
  9350. uint32 random1 = static_cast<uint32>(rand());
  9351. if (random1 % 2 == 0)
  9352. {
  9353. if (VarIs<JavascriptNativeIntArray>(this))
  9354. {
  9355. uint32 random2 = static_cast<uint32>(rand());
  9356. if (random2 % 2 == 0)
  9357. {
  9358. JavascriptNativeIntArray::ToNativeFloatArray(static_cast<JavascriptNativeIntArray*>(this));
  9359. }
  9360. else
  9361. {
  9362. JavascriptNativeIntArray::ToVarArray(static_cast<JavascriptNativeIntArray*>(this));
  9363. }
  9364. }
  9365. else if (VarIs<JavascriptNativeFloatArray>(this))
  9366. {
  9367. JavascriptNativeFloatArray::ToVarArray(static_cast<JavascriptNativeFloatArray*>(this));
  9368. }
  9369. }
  9370. }
  9371. #endif
  9372. template <typename Fn>
  9373. void JavascriptArray::ForEachOwnMissingArrayIndexOfObject(JavascriptArray *baseArray, JavascriptArray *destArray, RecyclableObject* obj, uint32 startIndex, uint32 limitIndex, uint32 destIndex, Fn fn)
  9374. {
  9375. JS_REENTRANCY_LOCK(jsReentLock, baseArray->GetScriptContext()->GetThreadContext());
  9376. SETOBJECT_FOR_MUTATION(jsReentLock, baseArray);
  9377. SET_SECOND_OBJECT_FOR_MUTATION(jsReentLock, destArray);
  9378. Assert(DynamicObject::IsAnyArray(obj) || JavascriptOperators::IsObject(obj));
  9379. Var oldValue;
  9380. JavascriptArray* arr = nullptr;
  9381. if (DynamicObject::IsAnyArray(obj))
  9382. {
  9383. arr = JavascriptArray::UnsafeFromAnyArray(obj);
  9384. }
  9385. else if (DynamicType::Is(obj->GetTypeId()))
  9386. {
  9387. DynamicObject* dynobj = UnsafeVarTo<DynamicObject>(obj);
  9388. ArrayObject* objectArray = dynobj->GetObjectArray();
  9389. arr = (objectArray && JavascriptArray::IsAnyArray(objectArray)) ? JavascriptArray::UnsafeFromAnyArray(objectArray) : nullptr;
  9390. }
  9391. if (arr != nullptr)
  9392. {
  9393. if (JavascriptArray::IsNonES5Array(arr))
  9394. {
  9395. arr = EnsureNonNativeArray(arr);
  9396. ArrayElementEnumerator e(arr, startIndex, limitIndex);
  9397. while(e.MoveNext<Var>())
  9398. {
  9399. uint32 index = e.GetIndex();
  9400. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9401. {
  9402. uint32 n = destIndex + (index - startIndex);
  9403. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9404. {
  9405. JS_REENTRANT(jsReentLock, fn(index, e.GetItem<Var>()));
  9406. }
  9407. }
  9408. }
  9409. }
  9410. else
  9411. {
  9412. ScriptContext* scriptContext = obj->GetScriptContext();
  9413. Assert(VarIs<ES5Array>(arr));
  9414. ES5Array* es5Array = VarTo<ES5Array>(arr);
  9415. ES5ArrayIndexStaticEnumerator<true> e(es5Array);
  9416. while (e.MoveNext())
  9417. {
  9418. uint32 index = e.GetIndex();
  9419. if (index < startIndex) continue;
  9420. else if (index >= limitIndex) break;
  9421. if (!baseArray->DirectGetVarItemAt(index, &oldValue, baseArray->GetScriptContext()))
  9422. {
  9423. uint32 n = destIndex + (index - startIndex);
  9424. if (destArray == nullptr || !destArray->DirectGetItemAt(n, &oldValue))
  9425. {
  9426. Var value = nullptr;
  9427. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetOwnItem(obj, index, &value, scriptContext));
  9428. if (gotItem)
  9429. {
  9430. JS_REENTRANT(jsReentLock, fn(index, value));
  9431. }
  9432. }
  9433. }
  9434. }
  9435. }
  9436. }
  9437. }
  9438. //
  9439. // ArrayElementEnumerator to enumerate array elements (not including elements from prototypes).
  9440. //
  9441. JavascriptArray::ArrayElementEnumerator::ArrayElementEnumerator(JavascriptArray* arr, uint32 start, uint32 end)
  9442. : start(start), end(min(end, arr->length))
  9443. {
  9444. Init(arr);
  9445. }
  9446. //
  9447. // Initialize this enumerator and prepare for the first MoveNext.
  9448. //
  9449. void JavascriptArray::ArrayElementEnumerator::Init(JavascriptArray* arr)
  9450. {
  9451. // Find start segment
  9452. seg = (arr ? arr->GetBeginLookupSegment(start) : nullptr);
  9453. while (seg && (seg->left + seg->length <= start))
  9454. {
  9455. seg = seg->next;
  9456. }
  9457. // Set start index and endIndex
  9458. if (seg)
  9459. {
  9460. if (seg->left >= end)
  9461. {
  9462. seg = nullptr;
  9463. }
  9464. else
  9465. {
  9466. // set index to be at target index - 1, so MoveNext will move to target
  9467. index = max(seg->left, start) - seg->left - 1;
  9468. endIndex = min(end - seg->left, seg->length);
  9469. }
  9470. }
  9471. }
  9472. //
  9473. // Move to the next element if available.
  9474. //
  9475. template<typename T>
  9476. inline bool JavascriptArray::ArrayElementEnumerator::MoveNext()
  9477. {
  9478. while (seg)
  9479. {
  9480. // Look for next non-null item in current segment
  9481. while (++index < endIndex)
  9482. {
  9483. if (!SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]))
  9484. {
  9485. return true;
  9486. }
  9487. }
  9488. // Move to next segment
  9489. seg = seg->next;
  9490. if (seg)
  9491. {
  9492. if (seg->left >= end)
  9493. {
  9494. seg = nullptr;
  9495. break;
  9496. }
  9497. else
  9498. {
  9499. index = static_cast<uint32>(-1);
  9500. endIndex = min(end - seg->left, seg->length);
  9501. }
  9502. }
  9503. }
  9504. return false;
  9505. }
  9506. //
  9507. // Get current array element index.
  9508. //
  9509. uint32 JavascriptArray::ArrayElementEnumerator::GetIndex() const
  9510. {
  9511. Assert(seg && index < seg->length && index < endIndex);
  9512. return seg->left + index;
  9513. }
  9514. //
  9515. // Get current array element value.
  9516. //
  9517. template<typename T>
  9518. T JavascriptArray::ArrayElementEnumerator::GetItem() const
  9519. {
  9520. Assert(seg && index < seg->length && index < endIndex &&
  9521. !SparseArraySegment<T>::IsMissingItem(&((SparseArraySegment<T>*)seg)->elements[index]));
  9522. return ((SparseArraySegment<T>*)seg)->elements[index];
  9523. }
  9524. //
  9525. // Construct a BigIndex initialized to a given uint32 (small index).
  9526. //
  9527. JavascriptArray::BigIndex::BigIndex(uint32 initIndex)
  9528. : index(initIndex), bigIndex(InvalidIndex)
  9529. {
  9530. //ok if initIndex == InvalidIndex
  9531. }
  9532. //
  9533. // Construct a BigIndex initialized to a given uint64 (large or small index).
  9534. //
  9535. JavascriptArray::BigIndex::BigIndex(uint64 initIndex)
  9536. : index(InvalidIndex), bigIndex(initIndex)
  9537. {
  9538. if (bigIndex < InvalidIndex) // if it's actually small index
  9539. {
  9540. index = static_cast<uint32>(bigIndex);
  9541. bigIndex = InvalidIndex;
  9542. }
  9543. }
  9544. bool JavascriptArray::BigIndex::IsUint32Max() const
  9545. {
  9546. return index == InvalidIndex && bigIndex == InvalidIndex;
  9547. }
  9548. bool JavascriptArray::BigIndex::IsSmallIndex() const
  9549. {
  9550. return index < InvalidIndex;
  9551. }
  9552. uint32 JavascriptArray::BigIndex::GetSmallIndex() const
  9553. {
  9554. Assert(IsSmallIndex());
  9555. return index;
  9556. }
  9557. uint64 JavascriptArray::BigIndex::GetBigIndex() const
  9558. {
  9559. Assert(!IsSmallIndex());
  9560. return bigIndex;
  9561. }
  9562. //
  9563. // Convert this index value to a JS number
  9564. //
  9565. Var JavascriptArray::BigIndex::ToNumber(ScriptContext* scriptContext) const
  9566. {
  9567. if (IsSmallIndex())
  9568. {
  9569. return small_index::ToNumber(index, scriptContext);
  9570. }
  9571. else
  9572. {
  9573. return JavascriptNumber::ToVar(bigIndex, scriptContext);
  9574. }
  9575. }
  9576. //
  9577. // Increment this index by 1.
  9578. //
  9579. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator++()
  9580. {
  9581. if (IsSmallIndex())
  9582. {
  9583. ++index;
  9584. // If index reaches InvalidIndex, we will start to use bigIndex which is initially InvalidIndex.
  9585. }
  9586. else
  9587. {
  9588. bigIndex = bigIndex + 1;
  9589. }
  9590. return *this;
  9591. }
  9592. //
  9593. // Decrement this index by 1.
  9594. //
  9595. const JavascriptArray::BigIndex& JavascriptArray::BigIndex::operator--()
  9596. {
  9597. if (IsSmallIndex())
  9598. {
  9599. --index;
  9600. }
  9601. else
  9602. {
  9603. Assert(index == InvalidIndex && bigIndex >= InvalidIndex);
  9604. --bigIndex;
  9605. if (bigIndex < InvalidIndex)
  9606. {
  9607. index = InvalidIndex - 1;
  9608. bigIndex = InvalidIndex;
  9609. }
  9610. }
  9611. return *this;
  9612. }
  9613. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(const BigIndex& delta) const
  9614. {
  9615. if (delta.IsSmallIndex())
  9616. {
  9617. return operator+(delta.GetSmallIndex());
  9618. }
  9619. if (IsSmallIndex())
  9620. {
  9621. return index + delta.GetBigIndex();
  9622. }
  9623. return bigIndex + delta.GetBigIndex();
  9624. }
  9625. //
  9626. // Get a new BigIndex representing this + delta.
  9627. //
  9628. JavascriptArray::BigIndex JavascriptArray::BigIndex::operator+(uint32 delta) const
  9629. {
  9630. if (IsSmallIndex())
  9631. {
  9632. uint32 newIndex;
  9633. if (UInt32Math::Add(index, delta, &newIndex))
  9634. {
  9635. return static_cast<uint64>(index) + static_cast<uint64>(delta);
  9636. }
  9637. else
  9638. {
  9639. return newIndex; // ok if newIndex == InvalidIndex
  9640. }
  9641. }
  9642. else
  9643. {
  9644. return bigIndex + static_cast<uint64>(delta);
  9645. }
  9646. }
  9647. bool JavascriptArray::BigIndex::operator==(const BigIndex& rhs) const
  9648. {
  9649. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9650. {
  9651. return this->GetSmallIndex() == rhs.GetSmallIndex();
  9652. }
  9653. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9654. {
  9655. // if lhs is big promote rhs
  9656. return this->GetBigIndex() == (uint64) rhs.GetSmallIndex();
  9657. }
  9658. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9659. {
  9660. // if rhs is big promote lhs
  9661. return ((uint64)this->GetSmallIndex()) == rhs.GetBigIndex();
  9662. }
  9663. return this->GetBigIndex() == rhs.GetBigIndex();
  9664. }
  9665. bool JavascriptArray::BigIndex::operator> (const BigIndex& rhs) const
  9666. {
  9667. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9668. {
  9669. return this->GetSmallIndex() > rhs.GetSmallIndex();
  9670. }
  9671. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9672. {
  9673. // if lhs is big promote rhs
  9674. return this->GetBigIndex() > (uint64)rhs.GetSmallIndex();
  9675. }
  9676. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9677. {
  9678. // if rhs is big promote lhs
  9679. return ((uint64)this->GetSmallIndex()) > rhs.GetBigIndex();
  9680. }
  9681. return this->GetBigIndex() > rhs.GetBigIndex();
  9682. }
  9683. bool JavascriptArray::BigIndex::operator< (const BigIndex& rhs) const
  9684. {
  9685. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9686. {
  9687. return this->GetSmallIndex() < rhs.GetSmallIndex();
  9688. }
  9689. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9690. {
  9691. // if lhs is big promote rhs
  9692. return this->GetBigIndex() < (uint64)rhs.GetSmallIndex();
  9693. }
  9694. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9695. {
  9696. // if rhs is big promote lhs
  9697. return ((uint64)this->GetSmallIndex()) < rhs.GetBigIndex();
  9698. }
  9699. return this->GetBigIndex() < rhs.GetBigIndex();
  9700. }
  9701. bool JavascriptArray::BigIndex::operator<=(const BigIndex& rhs) const
  9702. {
  9703. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9704. {
  9705. return this->GetSmallIndex() <= rhs.GetSmallIndex();
  9706. }
  9707. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9708. {
  9709. // if lhs is big promote rhs
  9710. return this->GetBigIndex() <= (uint64)rhs.GetSmallIndex();
  9711. }
  9712. else if (!rhs.IsSmallIndex() && !this->IsSmallIndex())
  9713. {
  9714. // if rhs is big promote lhs
  9715. return ((uint64)this->GetSmallIndex()) <= rhs.GetBigIndex();
  9716. }
  9717. return this->GetBigIndex() <= rhs.GetBigIndex();
  9718. }
  9719. bool JavascriptArray::BigIndex::operator>=(const BigIndex& rhs) const
  9720. {
  9721. if (rhs.IsSmallIndex() && this->IsSmallIndex())
  9722. {
  9723. return this->GetSmallIndex() >= rhs.GetSmallIndex();
  9724. }
  9725. else if (rhs.IsSmallIndex() && !this->IsSmallIndex())
  9726. {
  9727. // if lhs is big promote rhs
  9728. return this->GetBigIndex() >= (uint64)rhs.GetSmallIndex();
  9729. }
  9730. else if (!rhs.IsSmallIndex() && this->IsSmallIndex())
  9731. {
  9732. // if rhs is big promote lhs
  9733. return ((uint64)this->GetSmallIndex()) >= rhs.GetBigIndex();
  9734. }
  9735. return this->GetBigIndex() >= rhs.GetBigIndex();
  9736. }
  9737. BOOL JavascriptArray::BigIndex::GetItem(JavascriptArray* arr, Var* outVal) const
  9738. {
  9739. if (IsSmallIndex())
  9740. {
  9741. return small_index::GetItem(arr, index, outVal);
  9742. }
  9743. else
  9744. {
  9745. ScriptContext* scriptContext = arr->GetScriptContext();
  9746. PropertyRecord const * propertyRecord;
  9747. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9748. return arr->GetProperty(arr, propertyRecord->GetPropertyId(), outVal, NULL, scriptContext);
  9749. }
  9750. }
  9751. BOOL JavascriptArray::BigIndex::SetItem(JavascriptArray* arr, Var newValue) const
  9752. {
  9753. if (IsSmallIndex())
  9754. {
  9755. return small_index::SetItem(arr, index, newValue);
  9756. }
  9757. else
  9758. {
  9759. ScriptContext* scriptContext = arr->GetScriptContext();
  9760. PropertyRecord const * propertyRecord;
  9761. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9762. return arr->SetProperty(propertyRecord->GetPropertyId(), newValue, PropertyOperation_None, NULL);
  9763. }
  9764. }
  9765. void JavascriptArray::BigIndex::SetItemIfNotExist(JavascriptArray* arr, Var newValue) const
  9766. {
  9767. if (IsSmallIndex())
  9768. {
  9769. small_index::SetItemIfNotExist(arr, index, newValue);
  9770. }
  9771. else
  9772. {
  9773. ScriptContext* scriptContext = arr->GetScriptContext();
  9774. PropertyRecord const * propertyRecord;
  9775. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9776. Var oldValue;
  9777. PropertyId propertyId = propertyRecord->GetPropertyId();
  9778. if (!arr->GetProperty(arr, propertyId, &oldValue, NULL, scriptContext))
  9779. {
  9780. arr->SetProperty(propertyId, newValue, PropertyOperation_None, NULL);
  9781. }
  9782. }
  9783. }
  9784. BOOL JavascriptArray::BigIndex::DeleteItem(JavascriptArray* arr) const
  9785. {
  9786. if (IsSmallIndex())
  9787. {
  9788. return small_index::DeleteItem(arr, index);
  9789. }
  9790. else
  9791. {
  9792. ScriptContext* scriptContext = arr->GetScriptContext();
  9793. PropertyRecord const * propertyRecord;
  9794. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9795. return arr->DeleteProperty(propertyRecord->GetPropertyId(), PropertyOperation_None);
  9796. }
  9797. }
  9798. BOOL JavascriptArray::BigIndex::SetItem(RecyclableObject* obj, Var newValue, PropertyOperationFlags flags) const
  9799. {
  9800. if (IsSmallIndex())
  9801. {
  9802. return small_index::SetItem(obj, index, newValue, flags);
  9803. }
  9804. else
  9805. {
  9806. ScriptContext* scriptContext = obj->GetScriptContext();
  9807. PropertyRecord const * propertyRecord;
  9808. JavascriptOperators::GetPropertyIdForInt(bigIndex, scriptContext, &propertyRecord);
  9809. return JavascriptOperators::SetProperty(obj, obj, propertyRecord->GetPropertyId(), newValue, scriptContext, flags);
  9810. }
  9811. }
  9812. BOOL JavascriptArray::BigIndex::DeleteItem(RecyclableObject* obj, PropertyOperationFlags flags) const
  9813. {
  9814. if (IsSmallIndex())
  9815. {
  9816. return small_index::DeleteItem(obj, index, flags);
  9817. }
  9818. else
  9819. {
  9820. PropertyRecord const * propertyRecord;
  9821. JavascriptOperators::GetPropertyIdForInt(bigIndex, obj->GetScriptContext(), &propertyRecord);
  9822. return JavascriptOperators::DeleteProperty(obj, propertyRecord->GetPropertyId(), flags);
  9823. }
  9824. }
  9825. //
  9826. // Truncate the array at start and clone the truncated span as properties starting at dstIndex (asserting dstIndex >= MaxArrayLength).
  9827. //
  9828. void JavascriptArray::TruncateToProperties(const BigIndex& dstIndex, uint32 start)
  9829. {
  9830. Assert(!dstIndex.IsSmallIndex());
  9831. typedef IndexTrace<BigIndex> index_trace;
  9832. BigIndex dst = dstIndex;
  9833. uint32 i = start;
  9834. ArrayElementEnumerator e(this, start);
  9835. while(e.MoveNext<Var>())
  9836. {
  9837. // delete all items not enumerated
  9838. while (i < e.GetIndex())
  9839. {
  9840. index_trace::DeleteItem(this, dst);
  9841. ++i;
  9842. ++dst;
  9843. }
  9844. // Copy over the item
  9845. index_trace::SetItem(this, dst, e.GetItem<Var>());
  9846. ++i;
  9847. ++dst;
  9848. }
  9849. // Delete the rest till length
  9850. while (i < this->length)
  9851. {
  9852. index_trace::DeleteItem(this, dst);
  9853. ++i;
  9854. ++dst;
  9855. }
  9856. // Elements moved, truncate the array at start
  9857. SetLength(start);
  9858. }
  9859. //
  9860. // Copy a srcArray elements (including elements from prototypes) to a dstArray starting from an index.
  9861. //
  9862. void JavascriptArray::InternalCopyArrayElements(JavascriptArray* dstArray, const uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9863. {
  9864. Assert(start < end && end <= srcArray->length);
  9865. uint32 count = 0;
  9866. // iterate on the array itself
  9867. ArrayElementEnumerator e(srcArray, start, end);
  9868. while(e.MoveNext<Var>())
  9869. {
  9870. uint32 n = dstIndex + (e.GetIndex() - start);
  9871. dstArray->DirectSetItemAt(n, e.GetItem<Var>());
  9872. count++;
  9873. }
  9874. // iterate on the array's prototypes only if not all elements found
  9875. if (start + count != end)
  9876. {
  9877. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  9878. }
  9879. }
  9880. //
  9881. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9882. //
  9883. void JavascriptArray::CopyArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9884. {
  9885. end = min(end, srcArray->length);
  9886. if (start < end)
  9887. {
  9888. Assert(end - start <= MaxArrayLength - dstIndex);
  9889. InternalCopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9890. }
  9891. }
  9892. template <typename T>
  9893. void JavascriptArray::CopyAnyArrayElementsToVar(JavascriptArray* dstArray, T dstIndex, JavascriptArray* srcArray, uint32 start, uint32 end)
  9894. {
  9895. #if ENABLE_COPYONACCESS_ARRAY
  9896. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(srcArray);
  9897. #endif
  9898. #if ENABLE_COPYONACCESS_ARRAY
  9899. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(dstArray);
  9900. #endif
  9901. JavascriptNativeIntArray * nativeIntArray = JavascriptOperators::TryFromVar<JavascriptNativeIntArray>(srcArray);
  9902. if (nativeIntArray)
  9903. {
  9904. CopyNativeIntArrayElementsToVar(dstArray, dstIndex, nativeIntArray, start, end);
  9905. }
  9906. else
  9907. {
  9908. JavascriptNativeFloatArray * nativeFloatArray = JavascriptOperators::TryFromVar<JavascriptNativeFloatArray>(srcArray);
  9909. if (nativeFloatArray)
  9910. {
  9911. CopyNativeFloatArrayElementsToVar(dstArray, dstIndex, nativeFloatArray, start, end);
  9912. }
  9913. else
  9914. {
  9915. CopyArrayElements(dstArray, dstIndex, srcArray, start, end);
  9916. }
  9917. }
  9918. }
  9919. //
  9920. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9921. //
  9922. void JavascriptArray::CopyNativeIntArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9923. {
  9924. end = min(end, srcArray->length);
  9925. if (start < end)
  9926. {
  9927. Assert(end - start <= MaxArrayLength - dstIndex);
  9928. InternalCopyNativeIntArrayElements(dstArray, dstIndex, srcArray, start, end);
  9929. }
  9930. }
  9931. bool JavascriptArray::CopyNativeIntArrayElements(JavascriptNativeIntArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9932. {
  9933. end = min(end, srcArray->length);
  9934. if (start >= end)
  9935. {
  9936. return false;
  9937. }
  9938. Assert(end - start <= MaxArrayLength - dstIndex);
  9939. Assert(start < end && end <= srcArray->length);
  9940. uint32 count = 0;
  9941. // iterate on the array itself
  9942. ArrayElementEnumerator e(srcArray, start, end);
  9943. while(e.MoveNext<int32>())
  9944. {
  9945. uint n = dstIndex + (e.GetIndex() - start);
  9946. dstArray->DirectSetItemAt(n, e.GetItem<int32>());
  9947. count++;
  9948. }
  9949. // iterate on the array's prototypes only if not all elements found
  9950. if (start + count != end)
  9951. {
  9952. JavascriptArray *varArray = JavascriptNativeIntArray::ToVarArray(dstArray);
  9953. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9954. return true;
  9955. }
  9956. return false;
  9957. }
  9958. bool JavascriptArray::CopyNativeIntArrayElementsToFloat(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  9959. {
  9960. end = min(end, srcArray->length);
  9961. if (start >= end)
  9962. {
  9963. return false;
  9964. }
  9965. Assert(end - start <= MaxArrayLength - dstIndex);
  9966. Assert(start < end && end <= srcArray->length);
  9967. uint32 count = 0;
  9968. // iterate on the array itself
  9969. ArrayElementEnumerator e(srcArray, start, end);
  9970. while(e.MoveNext<int32>())
  9971. {
  9972. uint n = dstIndex + (e.GetIndex() - start);
  9973. dstArray->DirectSetItemAt(n, (double)e.GetItem<int32>());
  9974. count++;
  9975. }
  9976. // iterate on the array's prototypes only if not all elements found
  9977. if (start + count != end)
  9978. {
  9979. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  9980. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  9981. return true;
  9982. }
  9983. return false;
  9984. }
  9985. //
  9986. // Faster small_index overload of CopyArrayElements, asserting the uint32 dstIndex won't overflow.
  9987. //
  9988. void JavascriptArray::CopyNativeFloatArrayElementsToVar(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9989. {
  9990. end = min(end, srcArray->length);
  9991. if (start < end)
  9992. {
  9993. Assert(end - start <= MaxArrayLength - dstIndex);
  9994. InternalCopyNativeFloatArrayElements(dstArray, dstIndex, srcArray, start, end);
  9995. }
  9996. }
  9997. bool JavascriptArray::CopyNativeFloatArrayElements(JavascriptNativeFloatArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  9998. {
  9999. end = min(end, srcArray->length);
  10000. if (start >= end)
  10001. {
  10002. return false;
  10003. }
  10004. Assert(end - start <= MaxArrayLength - dstIndex);
  10005. Assert(start < end && end <= srcArray->length);
  10006. uint32 count = 0;
  10007. // iterate on the array itself
  10008. ArrayElementEnumerator e(srcArray, start, end);
  10009. while(e.MoveNext<double>())
  10010. {
  10011. uint n = dstIndex + (e.GetIndex() - start);
  10012. dstArray->DirectSetItemAt(n, e.GetItem<double>());
  10013. count++;
  10014. }
  10015. // iterate on the array's prototypes only if not all elements found
  10016. if (start + count != end)
  10017. {
  10018. JavascriptArray *varArray = JavascriptNativeFloatArray::ToVarArray(dstArray);
  10019. InternalFillFromPrototype(varArray, dstIndex, srcArray, start, end, count);
  10020. return true;
  10021. }
  10022. return false;
  10023. }
  10024. JavascriptArray *JavascriptArray::EnsureNonNativeArray(JavascriptArray *arr)
  10025. {
  10026. #if ENABLE_COPYONACCESS_ARRAY
  10027. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arr);
  10028. #endif
  10029. if (VarIs<JavascriptNativeIntArray>(arr))
  10030. {
  10031. arr = JavascriptNativeIntArray::ToVarArray((JavascriptNativeIntArray*)arr);
  10032. }
  10033. else if (VarIs<JavascriptNativeFloatArray>(arr))
  10034. {
  10035. arr = JavascriptNativeFloatArray::ToVarArray((JavascriptNativeFloatArray*)arr);
  10036. }
  10037. return arr;
  10038. }
  10039. BOOL JavascriptNativeIntArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  10040. {
  10041. ScriptContext* requestContext = type->GetScriptContext();
  10042. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeIntArray::GetItemQuery(this, index, outVal, requestContext)))
  10043. {
  10044. return TRUE;
  10045. }
  10046. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  10047. }
  10048. BOOL JavascriptNativeFloatArray::DirectGetItemAtFull(uint32 index, Var* outVal)
  10049. {
  10050. ScriptContext* requestContext = type->GetScriptContext();
  10051. if (JavascriptConversion::PropertyQueryFlagsToBoolean(JavascriptNativeFloatArray::GetItemQuery(this, index, outVal, requestContext)))
  10052. {
  10053. return TRUE;
  10054. }
  10055. return JavascriptOperators::GetItem(this, this->GetPrototype(), index, outVal, requestContext);
  10056. }
  10057. void JavascriptArray::InternalCopyNativeIntArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeIntArray* srcArray, uint32 start, uint32 end)
  10058. {
  10059. Assert(start < end && end <= srcArray->length);
  10060. uint32 count = 0;
  10061. // iterate on the array itself
  10062. ScriptContext *scriptContext = dstArray->GetScriptContext();
  10063. ArrayElementEnumerator e(srcArray, start, end);
  10064. while(e.MoveNext<int32>())
  10065. {
  10066. uint32 n = dstIndex + (e.GetIndex() - start);
  10067. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVar(e.GetItem<int32>(), scriptContext));
  10068. count++;
  10069. }
  10070. // iterate on the array's prototypes only if not all elements found
  10071. if (start + count != end)
  10072. {
  10073. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  10074. }
  10075. }
  10076. void JavascriptArray::InternalCopyNativeFloatArrayElements(JavascriptArray* dstArray, uint32 dstIndex, JavascriptNativeFloatArray* srcArray, uint32 start, uint32 end)
  10077. {
  10078. Assert(start < end && end <= srcArray->length);
  10079. uint32 count = 0;
  10080. // iterate on the array itself
  10081. ScriptContext *scriptContext = dstArray->GetScriptContext();
  10082. ArrayElementEnumerator e(srcArray, start, end);
  10083. while(e.MoveNext<double>())
  10084. {
  10085. uint32 n = dstIndex + (e.GetIndex() - start);
  10086. dstArray->DirectSetItemAt(n, JavascriptNumber::ToVarWithCheck(e.GetItem<double>(), scriptContext));
  10087. count++;
  10088. }
  10089. // iterate on the array's prototypes only if not all elements found
  10090. if (start + count != end)
  10091. {
  10092. InternalFillFromPrototype(dstArray, dstIndex, srcArray, start, end, count);
  10093. }
  10094. }
  10095. Var JavascriptArray::SpreadArrayArgs(Var arrayToSpread, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  10096. {
  10097. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  10098. SETOBJECT_FOR_MUTATION(jsReentLock, arrayToSpread);
  10099. // At this stage we have an array literal with some arguments to be spread.
  10100. // First we need to calculate the real size of the final literal.
  10101. #if ENABLE_COPYONACCESS_ARRAY
  10102. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(arrayToSpread);
  10103. #endif
  10104. JavascriptArray *array = VarTo<JavascriptArray>(arrayToSpread);
  10105. uint32 arrayLength = array->GetLength();
  10106. uint32 actualLength = arrayLength;
  10107. for (unsigned i = 0; i < spreadIndices->count; ++i)
  10108. {
  10109. JS_REENTRANT(jsReentLock,
  10110. actualLength = UInt32Math::Add(actualLength - 1, GetSpreadArgLen(array->DirectGetItem(spreadIndices->elements[i]), scriptContext)));
  10111. }
  10112. JavascriptArray *result = VarTo<JavascriptArray>(OP_NewScArrayWithMissingValues(actualLength, scriptContext));
  10113. // Now we copy each element and expand the spread parameters inline.
  10114. for (unsigned i = 0, spreadArrIndex = 0, resultIndex = 0; i < arrayLength && resultIndex < actualLength; ++i)
  10115. {
  10116. uint32 spreadIndex = spreadIndices->elements[spreadArrIndex]; // The index of the next element to be spread.
  10117. // An array needs a slow copy if it is a cross-site object or we have missing values that need to be set to undefined.
  10118. auto needArraySlowCopy = [&](Var instance) {
  10119. JavascriptArray *arr = JavascriptArray::TryVarToNonES5Array(instance);
  10120. if (arr)
  10121. {
  10122. JS_REENTRANT_UNLOCK(jsReentLock, return arr->IsCrossSiteObject() || arr->IsFillFromPrototypes());
  10123. }
  10124. return false;
  10125. };
  10126. // Designed to have interchangeable arguments with CopyAnyArrayElementsToVar.
  10127. auto slowCopy = [&scriptContext, &needArraySlowCopy
  10128. ](JavascriptArray *dstArray, unsigned dstIndex, Var srcArray, uint32 start, uint32 end) {
  10129. Assert(needArraySlowCopy(srcArray) || VarIs<ArgumentsObject>(srcArray) || VarIs<TypedArrayBase>(srcArray) || VarIs<JavascriptString>(srcArray));
  10130. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  10131. RecyclableObject *propertyObject;
  10132. if (!JavascriptOperators::GetPropertyObject(srcArray, scriptContext, &propertyObject))
  10133. {
  10134. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidSpreadArgument);
  10135. }
  10136. for (uint32 j = start; j < end; j++)
  10137. {
  10138. Var element;
  10139. JS_REENTRANT(jsReentLock, BOOL gotItem = JavascriptOperators::GetItem(srcArray, propertyObject, j, &element, scriptContext));
  10140. if (!gotItem)
  10141. {
  10142. // skip elided elements
  10143. dstIndex++;
  10144. }
  10145. else
  10146. {
  10147. dstArray->DirectSetItemAt(dstIndex++, element);
  10148. }
  10149. }
  10150. };
  10151. if (i < spreadIndex)
  10152. {
  10153. // Any non-spread elements can be copied in bulk.
  10154. if (needArraySlowCopy(array))
  10155. {
  10156. slowCopy(result, resultIndex, (Var)array, i, spreadIndex);
  10157. }
  10158. else
  10159. {
  10160. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, spreadIndex));
  10161. }
  10162. resultIndex += spreadIndex - i;
  10163. i = spreadIndex - 1;
  10164. continue;
  10165. }
  10166. else if (i > spreadIndex)
  10167. {
  10168. // Any non-spread elements terminating the array can also be copied in bulk.
  10169. Assert(spreadArrIndex == spreadIndices->count - 1);
  10170. if (needArraySlowCopy(array))
  10171. {
  10172. slowCopy(result, resultIndex, array, i, arrayLength);
  10173. }
  10174. else
  10175. {
  10176. JS_REENTRANT(jsReentLock, CopyAnyArrayElementsToVar(result, resultIndex, array, i, arrayLength));
  10177. }
  10178. break;
  10179. }
  10180. else
  10181. {
  10182. JS_REENTRANT(jsReentLock, Var instance = array->DirectGetItem(i));
  10183. if (VarIs<SpreadArgument>(instance))
  10184. {
  10185. SpreadArgument* spreadArgument = VarTo<SpreadArgument>(instance);
  10186. uint32 len = spreadArgument->GetArgumentSpreadCount();
  10187. const Var* spreadItems = spreadArgument->GetArgumentSpread();
  10188. for (uint32 j = 0; j < len; j++)
  10189. {
  10190. result->DirectSetItemAt(resultIndex++, spreadItems[j]);
  10191. }
  10192. }
  10193. else
  10194. {
  10195. Assert(JavascriptOperators::IsUndefinedObject(instance));
  10196. result->DirectSetItemAt(resultIndex++, instance);
  10197. }
  10198. if (spreadArrIndex < spreadIndices->count - 1)
  10199. {
  10200. spreadArrIndex++;
  10201. }
  10202. }
  10203. }
  10204. AssertMsg(arrayLength == array->GetLength(), "Array's length should not have changed");
  10205. return result;
  10206. }
  10207. uint32 JavascriptArray::GetSpreadArgLen(Var spreadArg, ScriptContext *scriptContext)
  10208. {
  10209. // A spread argument can be anything that returns a 'length' property, even if that
  10210. // property is null or undefined.
  10211. spreadArg = CrossSite::MarshalVar(scriptContext, spreadArg);
  10212. JavascriptArray *arr = JavascriptArray::TryVarToNonES5Array(spreadArg);
  10213. if (arr)
  10214. {
  10215. return arr->GetLength();
  10216. }
  10217. TypedArrayBase *tarr = JavascriptOperators::TryFromVar<Js::TypedArrayBase>(spreadArg);
  10218. if (tarr)
  10219. {
  10220. return tarr->GetLength();
  10221. }
  10222. if (VarIs<SpreadArgument>(spreadArg))
  10223. {
  10224. SpreadArgument *spreadFunctionArgs = VarTo<SpreadArgument>(spreadArg);
  10225. return spreadFunctionArgs->GetArgumentSpreadCount();
  10226. }
  10227. AssertMsg(false, "LdCustomSpreadIteratorList should have converted the arg to one of the above types");
  10228. Throw::FatalInternalError();
  10229. }
  10230. #ifdef VALIDATE_ARRAY
  10231. class ArraySegmentsVisitor
  10232. {
  10233. private:
  10234. SparseArraySegmentBase* seg;
  10235. public:
  10236. ArraySegmentsVisitor(SparseArraySegmentBase* head)
  10237. : seg(head)
  10238. {
  10239. }
  10240. void operator()(SparseArraySegmentBase* s)
  10241. {
  10242. Assert(seg == s);
  10243. if (seg)
  10244. {
  10245. seg = seg->next;
  10246. }
  10247. }
  10248. };
  10249. void JavascriptArray::ValidateArrayCommon()
  10250. {
  10251. SparseArraySegmentBase * lastUsedSegment = this->GetLastUsedSegment();
  10252. AssertMsg(this != nullptr && head && lastUsedSegment, "Array should not be null");
  10253. AssertMsg(head->left == 0, "Array always should have a segment starting at zero");
  10254. // Simple segments validation
  10255. bool foundLastUsedSegment = false;
  10256. SparseArraySegmentBase *seg = head;
  10257. while(seg != nullptr)
  10258. {
  10259. if (seg == lastUsedSegment)
  10260. {
  10261. foundLastUsedSegment = true;
  10262. }
  10263. AssertMsg(seg->length <= seg->size , "Length greater than size not possible");
  10264. SparseArraySegmentBase* next = seg->next;
  10265. if (next != nullptr)
  10266. {
  10267. AssertMsg(seg->left < next->left, "Segment is adjacent to or overlaps with next segment");
  10268. AssertMsg(seg->size <= (next->left - seg->left), "Segment is adjacent to or overlaps with next segment");
  10269. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10270. }
  10271. else
  10272. {
  10273. AssertMsg(seg->length <= MaxArrayLength - seg->left, "Segment index range overflow");
  10274. AssertMsg(seg->left + seg->length <= this->length, "Segment index range exceeds array length");
  10275. }
  10276. seg = next;
  10277. }
  10278. AssertMsg(foundLastUsedSegment || HasSegmentMap(), "Corrupt lastUsedSegment in array header");
  10279. // Validate segmentMap if present
  10280. if (HasSegmentMap())
  10281. {
  10282. ArraySegmentsVisitor visitor(head);
  10283. GetSegmentMap()->Walk(visitor);
  10284. }
  10285. }
  10286. void JavascriptArray::ValidateArray()
  10287. {
  10288. if (!Js::Configuration::Global.flags.ArrayValidate)
  10289. {
  10290. return;
  10291. }
  10292. ValidateArrayCommon();
  10293. // Detailed segments validation
  10294. JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>::From(head));
  10295. }
  10296. void JavascriptNativeIntArray::ValidateArray()
  10297. {
  10298. if (!Js::Configuration::Global.flags.ArrayValidate)
  10299. {
  10300. #if DBG
  10301. SparseArraySegmentBase *seg = head;
  10302. while (seg)
  10303. {
  10304. if (seg->next != nullptr)
  10305. {
  10306. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10307. }
  10308. seg = seg->next;
  10309. }
  10310. #endif
  10311. return;
  10312. }
  10313. ValidateArrayCommon();
  10314. // Detailed segments validation
  10315. JavascriptArray::ValidateSegment<int32>(SparseArraySegment<int32>::From(head));
  10316. }
  10317. void JavascriptNativeFloatArray::ValidateArray()
  10318. {
  10319. if (!Js::Configuration::Global.flags.ArrayValidate)
  10320. {
  10321. #if DBG
  10322. SparseArraySegmentBase *seg = head;
  10323. while (seg)
  10324. {
  10325. if (seg->next != nullptr)
  10326. {
  10327. AssertMsg(!SparseArraySegmentBase::IsLeafSegment(seg, this->GetScriptContext()->GetRecycler()), "Leaf segment with a next pointer");
  10328. }
  10329. seg = seg->next;
  10330. }
  10331. #endif
  10332. return;
  10333. }
  10334. ValidateArrayCommon();
  10335. // Detailed segments validation
  10336. JavascriptArray::ValidateSegment<double>(SparseArraySegment<double>::From(head));
  10337. }
  10338. void JavascriptArray::ValidateVarSegment(SparseArraySegment<Var>* seg)
  10339. {
  10340. if (!Js::Configuration::Global.flags.ArrayValidate)
  10341. {
  10342. return;
  10343. }
  10344. int32 inspect;
  10345. double inspectDouble;
  10346. while (seg)
  10347. {
  10348. uint32 i = 0;
  10349. for (i = 0; i < seg->length; i++)
  10350. {
  10351. if (SparseArraySegment<Var>::IsMissingItem(&seg->elements[i]))
  10352. {
  10353. continue;
  10354. }
  10355. if (TaggedInt::Is(seg->elements[i]))
  10356. {
  10357. inspect = TaggedInt::ToInt32(seg->elements[i]);
  10358. }
  10359. else if (JavascriptNumber::Is_NoTaggedIntCheck(seg->elements[i]))
  10360. {
  10361. inspectDouble = JavascriptNumber::GetValue(seg->elements[i]);
  10362. }
  10363. else
  10364. {
  10365. AssertMsg(VarIs<RecyclableObject>(seg->elements[i]), "Invalid entry in segment");
  10366. }
  10367. }
  10368. ValidateSegment(seg);
  10369. seg = SparseArraySegment<Var>::From(seg->next);
  10370. }
  10371. }
  10372. template<typename T>
  10373. void JavascriptArray::ValidateSegment(SparseArraySegment<T>* seg)
  10374. {
  10375. if (!Js::Configuration::Global.flags.ArrayValidate)
  10376. {
  10377. return;
  10378. }
  10379. while (seg)
  10380. {
  10381. uint32 i = seg->length;
  10382. while (i < seg->size)
  10383. {
  10384. AssertMsg(SparseArraySegment<T>::IsMissingItem(&seg->elements[i]), "Non missing value the end of the segment");
  10385. i++;
  10386. }
  10387. seg = SparseArraySegment<T>::From(seg->next);
  10388. }
  10389. }
  10390. #endif
  10391. template <typename T>
  10392. void JavascriptArray::InitBoxedInlineSegments(T * instance, bool deepCopy)
  10393. {
  10394. // Don't copy the segment map, we will build it again
  10395. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10396. SparseArraySegment<typename T::TElement>* src = SparseArraySegment<typename T::TElement>::From(instance->head);
  10397. SparseArraySegment<typename T::TElement>* dst;
  10398. uint32 sourceSize = src->size;
  10399. if (IsInlineSegment(src, instance))
  10400. {
  10401. // Copy head segment data between inlined head segments
  10402. dst = DetermineInlineHeadSegmentPointer<T, 0, true>(static_cast<T*>(this));
  10403. dst->left = src->left;
  10404. dst->length = src->length;
  10405. uint inlineChunkSize = SparseArraySegmentBase::INLINE_CHUNK_SIZE;
  10406. dst->size = min(src->size, inlineChunkSize);
  10407. sourceSize = dst->size;
  10408. }
  10409. else
  10410. {
  10411. // Otherwise, ensure that the new head segment is allocated now in the recycler so that the data can be copied.
  10412. // Note: src->next is provided to control whether a leaf segment is allocated just as it is with instance. If
  10413. // src->next is non-null, the appropriate update to dst->next will continue below.
  10414. dst = SparseArraySegment<typename T::TElement>::AllocateSegment(GetRecycler(), src->left, src->length, src->size, src->next);
  10415. }
  10416. SetHeadAndLastUsedSegment(dst);
  10417. dst->CheckLengthvsSize();
  10418. Assert(!IsInlineSegment(src, instance) || IsInlineSegment(dst, static_cast<T*>(this)));
  10419. CopyArray(dst->elements, dst->size, src->elements, sourceSize);
  10420. if (!deepCopy)
  10421. {
  10422. // Without a deep copy, point to the existing next segment from the original instance
  10423. dst->next = src->next;
  10424. }
  10425. else
  10426. {
  10427. // When deepCopy is true, make a separate copy of each segment. While this involves data
  10428. // duplication, it allows the new object to have a separate lifetime without sharing data.
  10429. AutoDisableInterrupt failFastError(GetScriptContext()->GetThreadContext());
  10430. do
  10431. {
  10432. if (src->next != nullptr)
  10433. {
  10434. // Allocate a new segment in the destination and copy from src
  10435. // note: PointerValue is to strip SWB wrapping before static_cast
  10436. src = static_cast<SparseArraySegment<typename T::TElement>*>(PointerValue(src->next));
  10437. dst->next = dst->AllocateSegment(GetRecycler(), src->left, src->length, src->size, src->next);
  10438. dst = static_cast<SparseArraySegment<typename T::TElement>*>(PointerValue(dst->next));
  10439. CopyArray(dst->elements, dst->size, src->elements, src->size);
  10440. }
  10441. else
  10442. {
  10443. // Terminate the loop
  10444. dst->next = nullptr;
  10445. dst = nullptr;
  10446. }
  10447. } while (dst != nullptr);
  10448. failFastError.Completed();
  10449. }
  10450. // Assert either
  10451. // - there is only the head segment
  10452. // - the new head segment points to a new next segment
  10453. // - the new head segment points to the existing next segment because this is not a deepCopy
  10454. Assert(this->head->next == nullptr || this->head->next != src->next || !deepCopy);
  10455. }
  10456. JavascriptArray::JavascriptArray(JavascriptArray * instance, bool boxHead, bool deepCopy)
  10457. : ArrayObject(instance, deepCopy)
  10458. {
  10459. if (boxHead)
  10460. {
  10461. InitBoxedInlineSegments(instance, deepCopy);
  10462. }
  10463. else
  10464. {
  10465. SetFlags(GetFlags() & ~DynamicObjectFlags::HasSegmentMap);
  10466. head = instance->head;
  10467. SetLastUsedSegment(instance->GetLastUsedSegment());
  10468. }
  10469. }
  10470. // Allocate a new Array with its own segments and copy the data in instance
  10471. // into the new Array. If the instance being deepCopy'd has an inline head
  10472. // segment, then make sure the new instance also has allocation for an inline
  10473. // head segment.
  10474. template <typename T>
  10475. T * JavascriptArray::DeepCopyInstance(T * instance)
  10476. {
  10477. size_t allocSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10478. if (IsInlineSegment(instance->head, instance))
  10479. {
  10480. allocSize += sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement);
  10481. }
  10482. return RecyclerNewPlusZ(instance->GetRecycler(), allocSize, T, instance, true /*boxHead*/, true /*deepCopy*/);
  10483. }
  10484. ArrayObject* JavascriptArray::DeepCopyInstance(ArrayObject* arrayObject)
  10485. {
  10486. ArrayObject* arrayCopy;
  10487. TypeId typeId = JavascriptOperators::GetTypeId(arrayObject);
  10488. switch (typeId)
  10489. {
  10490. case Js::TypeIds_Array:
  10491. arrayCopy = JavascriptArray::DeepCopyInstance<JavascriptArray>(UnsafeVarTo<JavascriptArray>(arrayObject));
  10492. break;
  10493. case Js::TypeIds_NativeIntArray:
  10494. arrayCopy = JavascriptArray::DeepCopyInstance<JavascriptNativeIntArray>(UnsafeVarTo<JavascriptNativeIntArray>(arrayObject));
  10495. break;
  10496. case Js::TypeIds_NativeFloatArray:
  10497. arrayCopy = JavascriptArray::DeepCopyInstance<JavascriptNativeFloatArray>(UnsafeVarTo<JavascriptNativeFloatArray>(arrayObject));
  10498. break;
  10499. default:
  10500. AssertAndFailFast(!"Unexpected objectArray type while boxing stack instance");
  10501. arrayCopy = nullptr;
  10502. };
  10503. return arrayCopy;
  10504. }
  10505. template <typename T>
  10506. T * JavascriptArray::BoxStackInstance(T * instance, bool deepCopy)
  10507. {
  10508. Assert(ThreadContext::IsOnStack(instance));
  10509. T * boxedInstance;
  10510. T ** boxedInstanceRef;
  10511. if (!deepCopy)
  10512. {
  10513. // On the stack, the we reserved a pointer before the object as to store the boxed value
  10514. boxedInstanceRef = ((T **)instance) - 1;
  10515. boxedInstance = *boxedInstanceRef;
  10516. if (boxedInstance)
  10517. {
  10518. return boxedInstance;
  10519. }
  10520. }
  10521. else
  10522. {
  10523. // When doing a deep copy, do not cache the boxed value to ensure that only shallow copies
  10524. // are reused
  10525. boxedInstance = nullptr;
  10526. boxedInstanceRef = nullptr;
  10527. }
  10528. const size_t inlineSlotsSize = instance->GetTypeHandler()->GetInlineSlotsSize();
  10529. if (ThreadContext::IsOnStack(instance->head) || deepCopy)
  10530. {
  10531. // Reallocate both the object as well as the head segment when the head is on the stack or
  10532. // when a deep copy is needed. This is to prevent a scenario where box may leave either one
  10533. // on the stack when both must be on the heap.
  10534. if (deepCopy)
  10535. {
  10536. boxedInstance = DeepCopyInstance(instance);
  10537. }
  10538. else
  10539. {
  10540. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(),
  10541. inlineSlotsSize + sizeof(Js::SparseArraySegmentBase) + instance->head->size * sizeof(typename T::TElement),
  10542. T, instance, true /*boxHead*/, false /*deepCopy*/);
  10543. }
  10544. }
  10545. else if(inlineSlotsSize)
  10546. {
  10547. boxedInstance = RecyclerNewPlusZ(instance->GetRecycler(), inlineSlotsSize, T, instance, false, false);
  10548. }
  10549. else
  10550. {
  10551. boxedInstance = RecyclerNew(instance->GetRecycler(), T, instance, false, false);
  10552. }
  10553. if (boxedInstanceRef != nullptr)
  10554. {
  10555. *boxedInstanceRef = boxedInstance;
  10556. }
  10557. return boxedInstance;
  10558. }
  10559. JavascriptArray *
  10560. JavascriptArray::BoxStackInstance(JavascriptArray * instance, bool deepCopy)
  10561. {
  10562. return BoxStackInstance<JavascriptArray>(instance, deepCopy);
  10563. }
  10564. #if ENABLE_TTD
  10565. void JavascriptArray::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  10566. {
  10567. TTDAssert(this->GetTypeId() == Js::TypeIds_Array || this->GetTypeId() == Js::TypeIds_ES5Array, "Should only be used on basic arrays (or called as super from ES5Array.");
  10568. ScriptContext* ctx = this->GetScriptContext();
  10569. uint32 index = Js::JavascriptArray::InvalidIndex;
  10570. while(true)
  10571. {
  10572. index = this->GetNextIndex(index);
  10573. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10574. {
  10575. break;
  10576. }
  10577. Js::Var aval = nullptr;
  10578. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10579. {
  10580. extractor->MarkVisitVar(aval);
  10581. }
  10582. }
  10583. }
  10584. void JavascriptArray::ProcessCorePaths()
  10585. {
  10586. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic arrays.");
  10587. ScriptContext* ctx = this->GetScriptContext();
  10588. uint32 index = Js::JavascriptArray::InvalidIndex;
  10589. while(true)
  10590. {
  10591. index = this->GetNextIndex(index);
  10592. if(index == Js::JavascriptArray::InvalidIndex) // End of array
  10593. {
  10594. break;
  10595. }
  10596. Js::Var aval = nullptr;
  10597. if(this->DirectGetVarItemAt(index, &aval, ctx))
  10598. {
  10599. TTD::UtilSupport::TTAutoString pathExt;
  10600. ctx->TTDWellKnownInfo->BuildArrayIndexBuffer(index, pathExt);
  10601. ctx->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, aval, pathExt.GetStrValue());
  10602. }
  10603. }
  10604. }
  10605. TTD::NSSnapObjects::SnapObjectType JavascriptArray::GetSnapTag_TTD() const
  10606. {
  10607. return TTD::NSSnapObjects::SnapObjectType::SnapArrayObject;
  10608. }
  10609. void JavascriptArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10610. {
  10611. TTDAssert(this->GetTypeId() == Js::TypeIds_Array, "Should only be used on basic Js arrays.");
  10612. TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>* sai = TTD::NSSnapObjects::ExtractArrayValues<TTD::TTDVar>(this, alloc);
  10613. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<TTD::TTDVar>*, TTD::NSSnapObjects::SnapObjectType::SnapArrayObject>(objData, sai);
  10614. }
  10615. #endif
  10616. JavascriptNativeArray::JavascriptNativeArray(JavascriptNativeArray * instance, bool deepCopy) :
  10617. JavascriptArray(instance, false, deepCopy),
  10618. weakRefToFuncBody(instance->weakRefToFuncBody)
  10619. {
  10620. }
  10621. JavascriptNativeIntArray::JavascriptNativeIntArray(JavascriptNativeIntArray * instance, bool boxHead, bool deepCopy) :
  10622. JavascriptNativeArray(instance, deepCopy)
  10623. {
  10624. if (boxHead)
  10625. {
  10626. InitBoxedInlineSegments(instance, deepCopy);
  10627. }
  10628. else
  10629. {
  10630. // Base class ctor should have copied these
  10631. Assert(head == instance->head);
  10632. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10633. }
  10634. }
  10635. JavascriptNativeIntArray *
  10636. JavascriptNativeIntArray::BoxStackInstance(JavascriptNativeIntArray * instance, bool deepCopy)
  10637. {
  10638. return JavascriptArray::BoxStackInstance<JavascriptNativeIntArray>(instance, deepCopy);
  10639. }
  10640. #if ENABLE_TTD
  10641. TTD::NSSnapObjects::SnapObjectType JavascriptNativeIntArray::GetSnapTag_TTD() const
  10642. {
  10643. return TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject;
  10644. }
  10645. void JavascriptNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10646. {
  10647. TTD::NSSnapObjects::SnapArrayInfo<int32>* sai = TTD::NSSnapObjects::ExtractArrayValues<int32>(this, alloc);
  10648. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<int32>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeIntArrayObject>(objData, sai);
  10649. }
  10650. #if ENABLE_COPYONACCESS_ARRAY
  10651. TTD::NSSnapObjects::SnapObjectType JavascriptCopyOnAccessNativeIntArray::GetSnapTag_TTD() const
  10652. {
  10653. return TTD::NSSnapObjects::SnapObjectType::Invalid;
  10654. }
  10655. void JavascriptCopyOnAccessNativeIntArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10656. {
  10657. TTDAssert(false, "Not implemented yet!!!");
  10658. }
  10659. #endif
  10660. #endif
  10661. JavascriptNativeFloatArray::JavascriptNativeFloatArray(JavascriptNativeFloatArray * instance, bool boxHead, bool deepCopy) :
  10662. JavascriptNativeArray(instance, deepCopy)
  10663. {
  10664. if (boxHead)
  10665. {
  10666. InitBoxedInlineSegments(instance, deepCopy);
  10667. }
  10668. else
  10669. {
  10670. // Base class ctor should have copied these
  10671. Assert(head == instance->head);
  10672. Assert(segmentUnion.lastUsedSegment == instance->GetLastUsedSegment());
  10673. }
  10674. }
  10675. JavascriptNativeFloatArray *
  10676. JavascriptNativeFloatArray::BoxStackInstance(JavascriptNativeFloatArray * instance, bool deepCopy)
  10677. {
  10678. return JavascriptArray::BoxStackInstance<JavascriptNativeFloatArray>(instance, deepCopy);
  10679. }
  10680. #if ENABLE_TTD
  10681. TTD::NSSnapObjects::SnapObjectType JavascriptNativeFloatArray::GetSnapTag_TTD() const
  10682. {
  10683. return TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject;
  10684. }
  10685. void JavascriptNativeFloatArray::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  10686. {
  10687. TTDAssert(this->GetTypeId() == Js::TypeIds_NativeFloatArray, "Should only be used on native float arrays.");
  10688. TTD::NSSnapObjects::SnapArrayInfo<double>* sai = TTD::NSSnapObjects::ExtractArrayValues<double>(this, alloc);
  10689. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapArrayInfo<double>*, TTD::NSSnapObjects::SnapObjectType::SnapNativeFloatArrayObject>(objData, sai);
  10690. }
  10691. #endif
  10692. template<typename T>
  10693. RecyclableObject*
  10694. JavascriptArray::ArraySpeciesCreate(Var originalArray, T length, ScriptContext* scriptContext, bool *pIsIntArray, bool *pIsFloatArray, bool *pIsBuiltinArrayCtor)
  10695. {
  10696. if (originalArray == nullptr || !scriptContext->GetConfig()->IsES6SpeciesEnabled())
  10697. {
  10698. return nullptr;
  10699. }
  10700. JS_REENTRANCY_LOCK(jsReentLock, scriptContext->GetThreadContext());
  10701. SETOBJECT_FOR_MUTATION(jsReentLock, originalArray);
  10702. auto* library = scriptContext->GetLibrary();
  10703. if (JavascriptArray::IsNonES5Array(originalArray))
  10704. {
  10705. auto* dynamicObject = UnsafeVarTo<DynamicObject>(originalArray);
  10706. auto* typeHandler = dynamicObject->GetDynamicType()->GetTypeHandler();
  10707. if (typeHandler->IsPathTypeHandler()
  10708. && !PathTypeHandlerBase::FromTypeHandler(typeHandler)->HasUserDefinedCtor()
  10709. && dynamicObject->GetPrototype() == library->GetArrayPrototype()
  10710. && !library->GetArrayObjectHasUserDefinedSpecies())
  10711. {
  10712. return nullptr;
  10713. }
  10714. }
  10715. Var constructor = library->GetUndefined();
  10716. JS_REENTRANT(jsReentLock, BOOL isArray = JavascriptOperators::IsArray(originalArray));
  10717. if (isArray)
  10718. {
  10719. JS_REENTRANT(jsReentLock, BOOL getProp = JavascriptOperators::GetProperty(UnsafeVarTo<RecyclableObject>(originalArray), PropertyIds::constructor, &constructor, scriptContext));
  10720. if (!getProp)
  10721. {
  10722. return nullptr;
  10723. }
  10724. if (JavascriptOperators::IsConstructor(constructor))
  10725. {
  10726. ScriptContext* constructorScriptContext = UnsafeVarTo<RecyclableObject>(constructor)->GetScriptContext();
  10727. if (constructorScriptContext != scriptContext)
  10728. {
  10729. if (constructorScriptContext->GetLibrary()->GetArrayConstructor() == constructor)
  10730. {
  10731. constructor = library->GetUndefined();
  10732. }
  10733. }
  10734. }
  10735. if (JavascriptOperators::IsObject(constructor))
  10736. {
  10737. JS_REENTRANT(jsReentLock, getProp = JavascriptOperators::GetProperty((RecyclableObject*)constructor, PropertyIds::_symbolSpecies, &constructor, scriptContext));
  10738. if (!getProp)
  10739. {
  10740. if (pIsBuiltinArrayCtor != nullptr)
  10741. {
  10742. *pIsBuiltinArrayCtor = false;
  10743. }
  10744. return nullptr;
  10745. }
  10746. if (constructor == library->GetNull())
  10747. {
  10748. constructor = library->GetUndefined();
  10749. }
  10750. }
  10751. }
  10752. if (constructor == library->GetUndefined() || constructor == library->GetArrayConstructor())
  10753. {
  10754. if (length > UINT_MAX)
  10755. {
  10756. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArrayLengthConstructIncorrect);
  10757. }
  10758. if (nullptr == pIsIntArray)
  10759. {
  10760. return library->CreateArray(static_cast<uint32>(length));
  10761. }
  10762. else
  10763. {
  10764. // If the constructor function is the built-in Array constructor, we can be smart and create the right type of native array.
  10765. JavascriptArray* pArr = VarTo<JavascriptArray>(originalArray);
  10766. pArr->GetArrayTypeAndConvert(pIsIntArray, pIsFloatArray);
  10767. return CreateNewArrayHelper(static_cast<uint32>(length), *pIsIntArray, *pIsFloatArray, pArr, scriptContext);
  10768. }
  10769. }
  10770. if (!JavascriptOperators::IsConstructor(constructor))
  10771. {
  10772. JavascriptError::ThrowTypeError(scriptContext, JSERR_NotAConstructor, _u("constructor[Symbol.species]"));
  10773. }
  10774. if (pIsBuiltinArrayCtor != nullptr)
  10775. {
  10776. *pIsBuiltinArrayCtor = false;
  10777. }
  10778. Js::Var constructorArgs[] = { constructor, JavascriptNumber::ToVar(length, scriptContext) };
  10779. Js::CallInfo constructorCallInfo(Js::CallFlags_New, _countof(constructorArgs));
  10780. AssertOrFailFast(Js::VarIs<Js::RecyclableObject>(constructor));
  10781. ThreadContext* threadContext = scriptContext->GetThreadContext();
  10782. Var scObject = threadContext->ExecuteImplicitCall((RecyclableObject*)constructor, ImplicitCall_Accessor, [&]()->Js::Var
  10783. {
  10784. JS_REENTRANT_UNLOCK(jsReentLock, return JavascriptOperators::NewScObject(constructor, Js::Arguments(constructorCallInfo, constructorArgs), scriptContext));
  10785. });
  10786. return VarTo<RecyclableObject>(scObject);
  10787. }
  10788. /*static*/
  10789. PropertyId const JavascriptArray::specialPropertyIds[] =
  10790. {
  10791. PropertyIds::length
  10792. };
  10793. BOOL JavascriptArray::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  10794. {
  10795. if (propertyId == PropertyIds::length)
  10796. {
  10797. JavascriptError::ThrowCantDeleteIfStrictModeOrNonconfigurable(
  10798. flags, GetScriptContext(), BuiltInPropertyRecords::length.buffer);
  10799. return false;
  10800. }
  10801. return DynamicObject::DeleteProperty(propertyId, flags);
  10802. }
  10803. BOOL JavascriptArray::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  10804. {
  10805. if (BuiltInPropertyRecords::length.Equals(propertyNameString))
  10806. {
  10807. JavascriptError::ThrowCantDeleteIfStrictModeOrNonconfigurable(
  10808. flags, GetScriptContext(), BuiltInPropertyRecords::length.buffer);
  10809. return false;
  10810. }
  10811. return DynamicObject::DeleteProperty(propertyNameString, flags);
  10812. }
  10813. PropertyQueryFlags JavascriptArray::HasPropertyQuery(PropertyId propertyId, _Inout_opt_ PropertyValueInfo* info)
  10814. {
  10815. if (propertyId == PropertyIds::length)
  10816. {
  10817. return PropertyQueryFlags::Property_Found;
  10818. }
  10819. ScriptContext* scriptContext = GetScriptContext();
  10820. uint32 index;
  10821. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10822. {
  10823. return JavascriptConversion::BooleanToPropertyQueryFlags(this->HasItem(index));
  10824. }
  10825. return DynamicObject::HasPropertyQuery(propertyId, info);
  10826. }
  10827. BOOL JavascriptArray::IsEnumerable(PropertyId propertyId)
  10828. {
  10829. if (propertyId == PropertyIds::length)
  10830. {
  10831. return false;
  10832. }
  10833. return DynamicObject::IsEnumerable(propertyId);
  10834. }
  10835. BOOL JavascriptArray::IsConfigurable(PropertyId propertyId)
  10836. {
  10837. if (propertyId == PropertyIds::length)
  10838. {
  10839. return false;
  10840. }
  10841. return DynamicObject::IsConfigurable(propertyId);
  10842. }
  10843. //
  10844. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10845. // handling and only check instance objectArray for numeric propertyIds.
  10846. //
  10847. BOOL JavascriptArray::SetEnumerable(PropertyId propertyId, BOOL value)
  10848. {
  10849. if (propertyId == PropertyIds::length)
  10850. {
  10851. Assert(!value); // Can't change array length enumerable
  10852. return true;
  10853. }
  10854. ScriptContext* scriptContext = this->GetScriptContext();
  10855. uint32 index;
  10856. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10857. {
  10858. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10859. ->SetEnumerable(this, propertyId, value);
  10860. }
  10861. return __super::SetEnumerable(propertyId, value);
  10862. }
  10863. //
  10864. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10865. // handling and only check instance objectArray for numeric propertyIds.
  10866. //
  10867. BOOL JavascriptArray::SetWritable(PropertyId propertyId, BOOL value)
  10868. {
  10869. ScriptContext* scriptContext = this->GetScriptContext();
  10870. uint32 index;
  10871. bool setLengthNonWritable = (propertyId == PropertyIds::length && !value);
  10872. if (setLengthNonWritable || scriptContext->IsNumericPropertyId(propertyId, &index))
  10873. {
  10874. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10875. ->SetWritable(this, propertyId, value);
  10876. }
  10877. return __super::SetWritable(propertyId, value);
  10878. }
  10879. //
  10880. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10881. // handling and only check instance objectArray for numeric propertyIds.
  10882. //
  10883. BOOL JavascriptArray::SetConfigurable(PropertyId propertyId, BOOL value)
  10884. {
  10885. if (propertyId == PropertyIds::length)
  10886. {
  10887. Assert(!value); // Can't change array length configurable
  10888. return true;
  10889. }
  10890. ScriptContext* scriptContext = this->GetScriptContext();
  10891. uint32 index;
  10892. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10893. {
  10894. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10895. ->SetConfigurable(this, propertyId, value);
  10896. }
  10897. return __super::SetConfigurable(propertyId, value);
  10898. }
  10899. //
  10900. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10901. // handling and only check instance objectArray for numeric propertyIds.
  10902. //
  10903. BOOL JavascriptArray::SetAttributes(PropertyId propertyId, PropertyAttributes attributes)
  10904. {
  10905. ScriptContext* scriptContext = this->GetScriptContext();
  10906. // SetAttributes on "length" is not expected. DefineOwnProperty uses SetWritable. If this is
  10907. // changed, we need to handle it here.
  10908. Assert(propertyId != PropertyIds::length);
  10909. uint32 index;
  10910. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10911. {
  10912. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10913. ->SetItemAttributes(this, index, attributes);
  10914. }
  10915. return __super::SetAttributes(propertyId, attributes);
  10916. }
  10917. //
  10918. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10919. // handling and only check instance objectArray for numeric propertyIds.
  10920. //
  10921. BOOL JavascriptArray::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  10922. {
  10923. ScriptContext* scriptContext = this->GetScriptContext();
  10924. uint32 index;
  10925. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  10926. {
  10927. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10928. ->SetItemAccessors(this, index, getter, setter);
  10929. }
  10930. return __super::SetAccessors(propertyId, getter, setter, flags);
  10931. }
  10932. //
  10933. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10934. // handling and only check instance objectArray for numeric propertyIds.
  10935. //
  10936. BOOL JavascriptArray::SetItemWithAttributes(uint32 index, Var value, PropertyAttributes attributes)
  10937. {
  10938. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10939. ->SetItemWithAttributes(this, index, value, attributes);
  10940. }
  10941. //
  10942. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10943. // handling and only check instance objectArray for numeric propertyIds.
  10944. //
  10945. BOOL JavascriptArray::SetItemAttributes(uint32 index, PropertyAttributes attributes)
  10946. {
  10947. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10948. ->SetItemAttributes(this, index, attributes);
  10949. }
  10950. //
  10951. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10952. // handling and only check instance objectArray for numeric propertyIds.
  10953. //
  10954. BOOL JavascriptArray::SetItemAccessors(uint32 index, Var getter, Var setter)
  10955. {
  10956. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)
  10957. ->SetItemAccessors(this, index, getter, setter);
  10958. }
  10959. // Check if this objectArray isFrozen.
  10960. BOOL JavascriptArray::IsObjectArrayFrozen()
  10961. {
  10962. // If this is still a JavascriptArray, it's not frozen.
  10963. return false;
  10964. }
  10965. JavascriptEnumerator * JavascriptArray::GetIndexEnumerator(EnumeratorFlags flags, ScriptContext* requestContext)
  10966. {
  10967. #if ENABLE_COPYONACCESS_ARRAY
  10968. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10969. #endif
  10970. if (!!(flags & EnumeratorFlags::SnapShotSemantics))
  10971. {
  10972. return RecyclerNew(GetRecycler(), JavascriptArrayIndexSnapshotEnumerator, this, flags, requestContext);
  10973. }
  10974. return RecyclerNew(GetRecycler(), JavascriptArrayIndexEnumerator, this, flags, requestContext);
  10975. }
  10976. BOOL JavascriptArray::GetNonIndexEnumerator(JavascriptStaticEnumerator * enumerator, ScriptContext* requestContext)
  10977. {
  10978. #if ENABLE_COPYONACCESS_ARRAY
  10979. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  10980. #endif
  10981. return enumerator->Initialize(nullptr, nullptr, this, EnumeratorFlags::SnapShotSemantics, requestContext, nullptr);
  10982. }
  10983. BOOL JavascriptArray::IsItemEnumerable(uint32 index)
  10984. {
  10985. return true;
  10986. }
  10987. //
  10988. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10989. // handling and only check instance objectArray for numeric propertyIds.
  10990. //
  10991. BOOL JavascriptArray::PreventExtensions()
  10992. {
  10993. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->PreventExtensions(this);
  10994. }
  10995. //
  10996. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  10997. // handling and only check instance objectArray for numeric propertyIds.
  10998. //
  10999. BOOL JavascriptArray::Seal()
  11000. {
  11001. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Seal(this);
  11002. }
  11003. //
  11004. // Evolve typeHandlers explicitly so that simple typeHandlers can skip array
  11005. // handling and only check instance objectArray for numeric propertyIds.
  11006. //
  11007. BOOL JavascriptArray::Freeze()
  11008. {
  11009. return GetTypeHandler()->ConvertToTypeWithItemAttributes(this)->Freeze(this);
  11010. }
  11011. BOOL JavascriptArray::GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext)
  11012. {
  11013. if (index == 0)
  11014. {
  11015. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  11016. return true;
  11017. }
  11018. return false;
  11019. }
  11020. // Returns the number of special non-enumerable properties this type has.
  11021. uint JavascriptArray::GetSpecialPropertyCount() const
  11022. {
  11023. return _countof(specialPropertyIds);
  11024. }
  11025. // Returns the list of special non-enumerable properties for the type.
  11026. PropertyId const * JavascriptArray::GetSpecialPropertyIds() const
  11027. {
  11028. return specialPropertyIds;
  11029. }
  11030. PropertyQueryFlags JavascriptArray::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  11031. {
  11032. return JavascriptArray::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  11033. }
  11034. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  11035. {
  11036. #if ENABLE_COPYONACCESS_ARRAY
  11037. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11038. #endif
  11039. if (GetPropertyBuiltIns(propertyId, value))
  11040. {
  11041. return PropertyQueryFlags::Property_Found;
  11042. }
  11043. ScriptContext* scriptContext = GetScriptContext();
  11044. uint32 index;
  11045. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  11046. {
  11047. return JavascriptConversion::BooleanToPropertyQueryFlags(this->GetItem(this, index, value, scriptContext));
  11048. }
  11049. return DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  11050. }
  11051. PropertyQueryFlags JavascriptArray::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  11052. {
  11053. #if ENABLE_COPYONACCESS_ARRAY
  11054. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11055. #endif
  11056. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  11057. "Numeric property names should have been converted to uint or PropertyRecord*");
  11058. PropertyRecord const* propertyRecord;
  11059. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  11060. if (propertyRecord != nullptr && GetPropertyBuiltIns(propertyRecord->GetPropertyId(), value))
  11061. {
  11062. return PropertyQueryFlags::Property_Found;
  11063. }
  11064. return DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext);
  11065. }
  11066. BOOL JavascriptArray::GetPropertyBuiltIns(PropertyId propertyId, Var* value)
  11067. {
  11068. //
  11069. // length being accessed. Return array length
  11070. //
  11071. if (propertyId == PropertyIds::length)
  11072. {
  11073. *value = JavascriptNumber::ToVar(this->GetLength(), GetScriptContext());
  11074. return true;
  11075. }
  11076. return false;
  11077. }
  11078. PropertyQueryFlags JavascriptArray::HasItemQuery(uint32 index)
  11079. {
  11080. Var value;
  11081. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, &value));
  11082. }
  11083. PropertyQueryFlags JavascriptArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  11084. {
  11085. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  11086. }
  11087. PropertyQueryFlags JavascriptArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  11088. {
  11089. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<Var>(index, value));
  11090. }
  11091. BOOL JavascriptArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  11092. {
  11093. return this->DirectGetItemAt<Var>(index, value);
  11094. }
  11095. PropertyQueryFlags JavascriptNativeIntArray::HasItemQuery(uint32 index)
  11096. {
  11097. #if ENABLE_COPYONACCESS_ARRAY
  11098. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11099. #endif
  11100. int32 value;
  11101. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<int32>(index, &value));
  11102. }
  11103. PropertyQueryFlags JavascriptNativeFloatArray::HasItemQuery(uint32 index)
  11104. {
  11105. double dvalue;
  11106. return JavascriptConversion::BooleanToPropertyQueryFlags(this->DirectGetItemAt<double>(index, &dvalue));
  11107. }
  11108. PropertyQueryFlags JavascriptNativeIntArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  11109. {
  11110. #if ENABLE_COPYONACCESS_ARRAY
  11111. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11112. #endif
  11113. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeIntArray::DirectGetVarItemAt(index, value, requestContext));
  11114. }
  11115. BOOL JavascriptNativeIntArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  11116. {
  11117. int32 intvalue;
  11118. if (!this->DirectGetItemAt<int32>(index, &intvalue))
  11119. {
  11120. return FALSE;
  11121. }
  11122. *value = JavascriptNumber::ToVar(intvalue, requestContext);
  11123. return TRUE;
  11124. }
  11125. PropertyQueryFlags JavascriptNativeIntArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  11126. {
  11127. return JavascriptNativeIntArray::GetItemQuery(originalInstance, index, value, requestContext);
  11128. }
  11129. PropertyQueryFlags JavascriptNativeFloatArray::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  11130. {
  11131. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptNativeFloatArray::DirectGetVarItemAt(index, value, requestContext));
  11132. }
  11133. BOOL JavascriptNativeFloatArray::DirectGetVarItemAt(uint32 index, Var *value, ScriptContext *requestContext)
  11134. {
  11135. double dvalue;
  11136. int32 ivalue;
  11137. if (!this->DirectGetItemAt<double>(index, &dvalue))
  11138. {
  11139. return FALSE;
  11140. }
  11141. if (*(uint64*)&dvalue == 0ull)
  11142. {
  11143. *value = TaggedInt::ToVarUnchecked(0);
  11144. }
  11145. else if (JavascriptNumber::TryGetInt32Value(dvalue, &ivalue) && !TaggedInt::IsOverflow(ivalue))
  11146. {
  11147. *value = TaggedInt::ToVarUnchecked(ivalue);
  11148. }
  11149. else
  11150. {
  11151. *value = JavascriptNumber::ToVarWithCheck(dvalue, requestContext);
  11152. }
  11153. return TRUE;
  11154. }
  11155. PropertyQueryFlags JavascriptNativeFloatArray::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  11156. {
  11157. return JavascriptNativeFloatArray::GetItemQuery(originalInstance, index, value, requestContext);
  11158. }
  11159. BOOL JavascriptArray::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  11160. {
  11161. #if ENABLE_COPYONACCESS_ARRAY
  11162. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11163. #endif
  11164. uint32 indexValue;
  11165. if (propertyId == PropertyIds::length)
  11166. {
  11167. return this->SetLength(value);
  11168. }
  11169. else if (GetScriptContext()->IsNumericPropertyId(propertyId, &indexValue))
  11170. {
  11171. // Call this or subclass method
  11172. return SetItem(indexValue, value, flags);
  11173. }
  11174. else
  11175. {
  11176. return DynamicObject::SetProperty(propertyId, value, flags, info);
  11177. }
  11178. }
  11179. BOOL JavascriptArray::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  11180. {
  11181. AssertMsg(!PropertyRecord::IsPropertyNameNumeric(propertyNameString->GetString(), propertyNameString->GetLength()),
  11182. "Numeric property names should have been converted to uint or PropertyRecord*");
  11183. #if ENABLE_COPYONACCESS_ARRAY
  11184. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11185. #endif
  11186. PropertyRecord const* propertyRecord;
  11187. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  11188. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::length)
  11189. {
  11190. return this->SetLength(value);
  11191. }
  11192. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  11193. }
  11194. BOOL JavascriptArray::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  11195. {
  11196. #if ENABLE_COPYONACCESS_ARRAY
  11197. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11198. #endif
  11199. ScriptContext* scriptContext = GetScriptContext();
  11200. if (propertyId == PropertyIds::length)
  11201. {
  11202. Assert(attributes == PropertyWritable);
  11203. Assert(IsWritable(propertyId) && !IsConfigurable(propertyId) && !IsEnumerable(propertyId));
  11204. return this->SetLength(value);
  11205. }
  11206. uint32 index;
  11207. if (scriptContext->IsNumericPropertyId(propertyId, &index))
  11208. {
  11209. // Call this or subclass method
  11210. return SetItemWithAttributes(index, value, attributes);
  11211. }
  11212. return __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  11213. }
  11214. BOOL JavascriptArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  11215. {
  11216. this->DirectSetItemAt(index, value);
  11217. return true;
  11218. }
  11219. BOOL JavascriptNativeIntArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  11220. {
  11221. int32 iValue;
  11222. double dValue;
  11223. #if ENABLE_COPYONACCESS_ARRAY
  11224. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11225. #endif
  11226. TypeId typeId = this->TrySetNativeIntArrayItem(value, &iValue, &dValue);
  11227. if (typeId == TypeIds_NativeIntArray)
  11228. {
  11229. this->SetItem(index, iValue);
  11230. }
  11231. else if (typeId == TypeIds_NativeFloatArray)
  11232. {
  11233. reinterpret_cast<JavascriptNativeFloatArray*>(this)->DirectSetItemAt<double>(index, dValue);
  11234. }
  11235. else
  11236. {
  11237. this->DirectSetItemAt<Var>(index, value);
  11238. }
  11239. return TRUE;
  11240. }
  11241. TypeId JavascriptNativeIntArray::TrySetNativeIntArrayItem(Var value, int32 *iValue, double *dValue)
  11242. {
  11243. if (TaggedInt::Is(value))
  11244. {
  11245. int32 i = TaggedInt::ToInt32(value);
  11246. if (i != JavascriptNativeIntArray::MissingItem)
  11247. {
  11248. *iValue = i;
  11249. return TypeIds_NativeIntArray;
  11250. }
  11251. }
  11252. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  11253. {
  11254. bool isInt32;
  11255. int32 i;
  11256. double d = JavascriptNumber::GetValue(value);
  11257. if (JavascriptNumber::TryGetInt32OrUInt32Value(d, &i, &isInt32))
  11258. {
  11259. if (isInt32 && i != JavascriptNativeIntArray::MissingItem)
  11260. {
  11261. *iValue = i;
  11262. return TypeIds_NativeIntArray;
  11263. }
  11264. }
  11265. else
  11266. {
  11267. *dValue = d;
  11268. JavascriptNativeIntArray::ToNativeFloatArray(this);
  11269. return TypeIds_NativeFloatArray;
  11270. }
  11271. }
  11272. JavascriptNativeIntArray::ToVarArray(this);
  11273. return TypeIds_Array;
  11274. }
  11275. BOOL JavascriptNativeIntArray::SetItem(uint32 index, int32 iValue)
  11276. {
  11277. if (iValue == JavascriptNativeIntArray::MissingItem)
  11278. {
  11279. JavascriptArray *varArr = JavascriptNativeIntArray::ToVarArray(this);
  11280. varArr->DirectSetItemAt(index, JavascriptNumber::ToVar(iValue, GetScriptContext()));
  11281. return TRUE;
  11282. }
  11283. this->DirectSetItemAt(index, iValue);
  11284. return TRUE;
  11285. }
  11286. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  11287. {
  11288. double dValue;
  11289. TypeId typeId = this->TrySetNativeFloatArrayItem(value, &dValue);
  11290. if (typeId == TypeIds_NativeFloatArray)
  11291. {
  11292. this->SetItem(index, dValue);
  11293. }
  11294. else
  11295. {
  11296. this->DirectSetItemAt(index, value);
  11297. }
  11298. return TRUE;
  11299. }
  11300. TypeId JavascriptNativeFloatArray::TrySetNativeFloatArrayItem(Var value, double *dValue)
  11301. {
  11302. if (TaggedInt::Is(value))
  11303. {
  11304. *dValue = (double)TaggedInt::ToInt32(value);
  11305. return TypeIds_NativeFloatArray;
  11306. }
  11307. else if (JavascriptNumber::Is_NoTaggedIntCheck(value))
  11308. {
  11309. *dValue = JavascriptNumber::GetValue(value);
  11310. return TypeIds_NativeFloatArray;
  11311. }
  11312. JavascriptNativeFloatArray::ToVarArray(this);
  11313. return TypeIds_Array;
  11314. }
  11315. BOOL JavascriptNativeFloatArray::SetItem(uint32 index, double dValue)
  11316. {
  11317. if (*(uint64*)&dValue == *(uint64*)&JavascriptNativeFloatArray::MissingItem)
  11318. {
  11319. JavascriptArray *varArr = JavascriptNativeFloatArray::ToVarArray(this);
  11320. varArr->DirectSetItemAt(index, JavascriptNumber::ToVarNoCheck(dValue, GetScriptContext()));
  11321. return TRUE;
  11322. }
  11323. this->DirectSetItemAt<double>(index, dValue);
  11324. return TRUE;
  11325. }
  11326. BOOL JavascriptArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  11327. {
  11328. return this->DirectDeleteItemAt<Var>(index);
  11329. }
  11330. BOOL JavascriptNativeIntArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  11331. {
  11332. return this->DirectDeleteItemAt<int32>(index);
  11333. }
  11334. BOOL JavascriptNativeFloatArray::DeleteItem(uint32 index, PropertyOperationFlags flags)
  11335. {
  11336. return this->DirectDeleteItemAt<double>(index);
  11337. }
  11338. BOOL JavascriptArray::GetEnumerator(JavascriptStaticEnumerator * enumerator, EnumeratorFlags flags, ScriptContext* requestContext, EnumeratorCache * enumeratorCache)
  11339. {
  11340. #if ENABLE_COPYONACCESS_ARRAY
  11341. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(this);
  11342. #endif
  11343. return enumerator->Initialize(nullptr, this, this, flags, requestContext, enumeratorCache);
  11344. }
  11345. BOOL JavascriptArray::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  11346. {
  11347. stringBuilder->Append(_u('['));
  11348. if (this->length < 10)
  11349. {
  11350. auto funcPtr = [&]()
  11351. {
  11352. ENTER_PINNED_SCOPE(JavascriptString, valueStr);
  11353. valueStr = JavascriptArray::JoinHelper(this, GetLibrary()->GetCommaDisplayString(), requestContext);
  11354. stringBuilder->Append(valueStr->GetString(), valueStr->GetLength());
  11355. LEAVE_PINNED_SCOPE();
  11356. };
  11357. if (!requestContext->GetThreadContext()->IsScriptActive())
  11358. {
  11359. BEGIN_JS_RUNTIME_CALL(requestContext);
  11360. {
  11361. funcPtr();
  11362. }
  11363. END_JS_RUNTIME_CALL(requestContext);
  11364. }
  11365. else
  11366. {
  11367. funcPtr();
  11368. }
  11369. }
  11370. else
  11371. {
  11372. stringBuilder->AppendCppLiteral(_u("..."));
  11373. }
  11374. stringBuilder->Append(_u(']'));
  11375. return TRUE;
  11376. }
  11377. BOOL JavascriptArray::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  11378. {
  11379. stringBuilder->AppendCppLiteral(_u("Object, (Array)"));
  11380. return TRUE;
  11381. }
  11382. bool JavascriptNativeArray::Is(TypeId typeId)
  11383. {
  11384. return JavascriptNativeIntArray::Is(typeId) || JavascriptNativeFloatArray::Is(typeId);
  11385. }
  11386. bool JavascriptNativeIntArray::Is(TypeId typeId)
  11387. {
  11388. return typeId == TypeIds_NativeIntArray;
  11389. }
  11390. bool JavascriptNativeFloatArray::Is(TypeId typeId)
  11391. {
  11392. return typeId == TypeIds_NativeFloatArray;
  11393. }
  11394. template int Js::JavascriptArray::GetParamForIndexOf<unsigned int>(unsigned int, Js::Arguments const&, void*&, unsigned int&, Js::ScriptContext*);
  11395. template bool Js::JavascriptArray::ArrayElementEnumerator::MoveNext<void*>();
  11396. template void Js::JavascriptArray::SetArrayLiteralItem<void*>(unsigned int, void*);
  11397. template void* Js::JavascriptArray::TemplatedIndexOfHelper<false, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);
  11398. template void* Js::JavascriptArray::TemplatedIndexOfHelper<true, Js::TypedArrayBase, unsigned int>(Js::TypedArrayBase*, void*, unsigned int, unsigned int, Js::ScriptContext*);